1//===-- Lint.cpp - Check for common errors in LLVM IR ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass statically checks for common and easily-identified constructs
10// which produce undefined or likely unintended behavior in LLVM IR.
11//
12// It is not a guarantee of correctness, in two ways. First, it isn't
13// comprehensive. There are checks which could be done statically which are
14// not yet implemented. Some of these are indicated by TODO comments, but
15// those aren't comprehensive either. Second, many conditions cannot be
16// checked statically. This pass does no dynamic instrumentation, so it
17// can't check for all possible problems.
18//
19// Another limitation is that it assumes all code will be executed. A store
20// through a null pointer in a basic block which is never reached is harmless,
21// but this pass will warn about it anyway. This is the main reason why most
22// of these checks live here instead of in the Verifier pass.
23//
24// Optimization passes may make conditions that this pass checks for more or
25// less obvious. If an optimization pass appears to be introducing a warning,
26// it may be that the optimization pass is merely exposing an existing
27// condition in the code.
28//
29// This code may be run before instcombine. In many cases, instcombine checks
30// for the same kinds of things and turns instructions with undefined behavior
31// into unreachable (or equivalent). Because of this, this pass makes some
32// effort to look through bitcasts and so on.
33//
34//===----------------------------------------------------------------------===//
35
36#include "llvm/Analysis/Lint.h"
37#include "llvm/ADT/APInt.h"
38#include "llvm/ADT/ArrayRef.h"
39#include "llvm/ADT/SmallPtrSet.h"
40#include "llvm/ADT/Twine.h"
41#include "llvm/Analysis/AliasAnalysis.h"
42#include "llvm/Analysis/AssumptionCache.h"
43#include "llvm/Analysis/BasicAliasAnalysis.h"
44#include "llvm/Analysis/ConstantFolding.h"
45#include "llvm/Analysis/InstructionSimplify.h"
46#include "llvm/Analysis/Loads.h"
47#include "llvm/Analysis/MemoryLocation.h"
48#include "llvm/Analysis/ScopedNoAliasAA.h"
49#include "llvm/Analysis/TargetLibraryInfo.h"
50#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
51#include "llvm/Analysis/ValueTracking.h"
52#include "llvm/IR/Argument.h"
53#include "llvm/IR/BasicBlock.h"
54#include "llvm/IR/Constant.h"
55#include "llvm/IR/Constants.h"
56#include "llvm/IR/DataLayout.h"
57#include "llvm/IR/DerivedTypes.h"
58#include "llvm/IR/Dominators.h"
59#include "llvm/IR/Function.h"
60#include "llvm/IR/GlobalVariable.h"
61#include "llvm/IR/InstVisitor.h"
62#include "llvm/IR/InstrTypes.h"
63#include "llvm/IR/Instruction.h"
64#include "llvm/IR/Instructions.h"
65#include "llvm/IR/IntrinsicInst.h"
66#include "llvm/IR/Module.h"
67#include "llvm/IR/PassManager.h"
68#include "llvm/IR/Type.h"
69#include "llvm/IR/Value.h"
70#include "llvm/Support/AMDGPUAddrSpace.h"
71#include "llvm/Support/Casting.h"
72#include "llvm/Support/KnownBits.h"
73#include "llvm/Support/raw_ostream.h"
74#include <cassert>
75#include <cstdint>
76#include <iterator>
77#include <string>
78
79using namespace llvm;
80
81namespace {
82namespace MemRef {
83static const unsigned Read = 1;
84static const unsigned Write = 2;
85static const unsigned Callee = 4;
86static const unsigned Branchee = 8;
87} // end namespace MemRef
88
89class Lint : public InstVisitor<Lint> {
90 friend class InstVisitor<Lint>;
91
92 void visitFunction(Function &F);
93
94 void visitCallBase(CallBase &CB);
95 void visitMemoryReference(Instruction &I, const MemoryLocation &Loc,
96 MaybeAlign Alignment, Type *Ty, unsigned Flags);
97
98 void visitReturnInst(ReturnInst &I);
99 void visitLoadInst(LoadInst &I);
100 void visitStoreInst(StoreInst &I);
101 void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I);
102 void visitAtomicRMWInst(AtomicRMWInst &I);
103 void visitXor(BinaryOperator &I);
104 void visitSub(BinaryOperator &I);
105 void visitLShr(BinaryOperator &I);
106 void visitAShr(BinaryOperator &I);
107 void visitShl(BinaryOperator &I);
108 void visitSDiv(BinaryOperator &I);
109 void visitUDiv(BinaryOperator &I);
110 void visitSRem(BinaryOperator &I);
111 void visitURem(BinaryOperator &I);
112 void visitAllocaInst(AllocaInst &I);
113 void visitVAArgInst(VAArgInst &I);
114 void visitIndirectBrInst(IndirectBrInst &I);
115 void visitExtractElementInst(ExtractElementInst &I);
116 void visitInsertElementInst(InsertElementInst &I);
117 void visitUnreachableInst(UnreachableInst &I);
118
119 Value *findValue(Value *V, bool OffsetOk) const;
120 Value *findValueImpl(Value *V, bool OffsetOk,
121 SmallPtrSetImpl<Value *> &Visited) const;
122
123public:
124 Module *Mod;
125 const Triple &TT;
126 const DataLayout *DL;
127 AliasAnalysis *AA;
128 AssumptionCache *AC;
129 DominatorTree *DT;
130 TargetLibraryInfo *TLI;
131
132 std::string Messages;
133 raw_string_ostream MessagesStr;
134
135 Lint(Module *Mod, const DataLayout *DL, AliasAnalysis *AA,
136 AssumptionCache *AC, DominatorTree *DT, TargetLibraryInfo *TLI)
137 : Mod(Mod), TT(Mod->getTargetTriple()), DL(DL), AA(AA), AC(AC), DT(DT),
138 TLI(TLI), MessagesStr(Messages) {}
139
140 void WriteValues(ArrayRef<const Value *> Vs) {
141 for (const Value *V : Vs) {
142 if (!V)
143 continue;
144 if (isa<Instruction>(Val: V)) {
145 MessagesStr << *V << '\n';
146 } else {
147 V->printAsOperand(O&: MessagesStr, PrintType: true, M: Mod);
148 MessagesStr << '\n';
149 }
150 }
151 }
152
153 /// A check failed, so printout out the condition and the message.
154 ///
155 /// This provides a nice place to put a breakpoint if you want to see why
156 /// something is not correct.
157 void CheckFailed(const Twine &Message) { MessagesStr << Message << '\n'; }
158
159 /// A check failed (with values to print).
160 ///
161 /// This calls the Message-only version so that the above is easier to set
162 /// a breakpoint on.
163 template <typename T1, typename... Ts>
164 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &... Vs) {
165 CheckFailed(Message);
166 WriteValues(Vs: {V1, Vs...});
167 }
168};
169} // end anonymous namespace
170
171// Check - We know that cond should be true, if not print an error message.
172#define Check(C, ...) \
173 do { \
174 if (!(C)) { \
175 CheckFailed(__VA_ARGS__); \
176 return; \
177 } \
178 } while (false)
179
180void Lint::visitFunction(Function &F) {
181 // This isn't undefined behavior, it's just a little unusual, and it's a
182 // fairly common mistake to neglect to name a function.
183 Check(F.hasName() || F.hasLocalLinkage(),
184 "Unusual: Unnamed function with non-local linkage", &F);
185
186 // TODO: Check for irreducible control flow.
187}
188
189void Lint::visitCallBase(CallBase &I) {
190 Value *Callee = I.getCalledOperand();
191
192 visitMemoryReference(I, Loc: MemoryLocation::getAfter(Ptr: Callee), Alignment: std::nullopt,
193 Ty: nullptr, Flags: MemRef::Callee);
194
195 if (Function *F = dyn_cast<Function>(Val: findValue(V: Callee,
196 /*OffsetOk=*/false))) {
197 Check(I.getCallingConv() == F->getCallingConv(),
198 "Undefined behavior: Caller and callee calling convention differ",
199 &I);
200
201 FunctionType *FT = F->getFunctionType();
202 unsigned NumActualArgs = I.arg_size();
203
204 Check(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs
205 : FT->getNumParams() == NumActualArgs,
206 "Undefined behavior: Call argument count mismatches callee "
207 "argument count",
208 &I);
209
210 Check(FT->getReturnType() == I.getType(),
211 "Undefined behavior: Call return type mismatches "
212 "callee return type",
213 &I);
214
215 // Check argument types (in case the callee was casted) and attributes.
216 // TODO: Verify that caller and callee attributes are compatible.
217 Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
218 auto AI = I.arg_begin(), AE = I.arg_end();
219 for (; AI != AE; ++AI) {
220 Value *Actual = *AI;
221 if (PI != PE) {
222 Argument *Formal = &*PI++;
223 Check(Formal->getType() == Actual->getType(),
224 "Undefined behavior: Call argument type mismatches "
225 "callee parameter type",
226 &I);
227
228 // Check that noalias arguments don't alias other arguments. This is
229 // not fully precise because we don't know the sizes of the dereferenced
230 // memory regions.
231 if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy()) {
232 AttributeList PAL = I.getAttributes();
233 unsigned ArgNo = 0;
234 for (auto *BI = I.arg_begin(); BI != AE; ++BI, ++ArgNo) {
235 // Skip ByVal arguments since they will be memcpy'd to the callee's
236 // stack so we're not really passing the pointer anyway.
237 if (PAL.hasParamAttr(ArgNo, Kind: Attribute::ByVal))
238 continue;
239 // If both arguments are readonly, they have no dependence.
240 if (Formal->onlyReadsMemory() && I.onlyReadsMemory(OpNo: ArgNo))
241 continue;
242 // Skip readnone arguments since those are guaranteed not to be
243 // dereferenced anyway.
244 if (I.doesNotAccessMemory(OpNo: ArgNo))
245 continue;
246 if (AI != BI && (*BI)->getType()->isPointerTy() &&
247 !isa<ConstantPointerNull>(Val: *BI)) {
248 AliasResult Result = AA->alias(V1: *AI, V2: *BI);
249 Check(Result != AliasResult::MustAlias &&
250 Result != AliasResult::PartialAlias,
251 "Unusual: noalias argument aliases another argument", &I);
252 }
253 }
254 }
255
256 // Check that an sret argument points to valid memory.
257 if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
258 Type *Ty = Formal->getParamStructRetType();
259 MemoryLocation Loc(
260 Actual, LocationSize::precise(Value: DL->getTypeStoreSize(Ty)));
261 visitMemoryReference(I, Loc, Alignment: DL->getABITypeAlign(Ty), Ty,
262 Flags: MemRef::Read | MemRef::Write);
263 }
264
265 // Check that ABI attributes for the function and call-site match.
266 unsigned ArgNo = AI->getOperandNo();
267 AttributeList CallAttrs = I.getAttributes();
268 for (Attribute::AttrKind Attr :
269 drop_begin(RangeOrContainer: enum_seq(Begin: Attribute::None, End: Attribute::EndAttrKinds,
270 force_iteration_on_noniterable_enum))) {
271 if (!Attribute::isABIAttr(Kind: Attr))
272 continue;
273
274 Attribute CallAttr = CallAttrs.getParamAttr(ArgNo, Kind: Attr);
275 Attribute FnAttr = F->getParamAttribute(ArgNo, Kind: Attr);
276 Check(CallAttr.isValid() == FnAttr.isValid(),
277 Twine("Undefined behavior: ABI attribute ") +
278 Attribute::getNameFromAttrKind(Attr) +
279 " not present on both function and call-site",
280 &I);
281 if (CallAttr.isValid() && FnAttr.isValid()) {
282 Check(CallAttr == FnAttr,
283 Twine("Undefined behavior: ABI attribute ") +
284 Attribute::getNameFromAttrKind(Attr) +
285 " does not have same argument for function and call-site",
286 &I);
287 }
288 }
289 }
290 }
291 }
292
293 if (const auto *CI = dyn_cast<CallInst>(Val: &I)) {
294 if (CI->isTailCall()) {
295 const AttributeList &PAL = CI->getAttributes();
296 unsigned ArgNo = 0;
297 for (Value *Arg : I.args()) {
298 // Skip ByVal arguments since they will be memcpy'd to the callee's
299 // stack anyway.
300 if (PAL.hasParamAttr(ArgNo: ArgNo++, Kind: Attribute::ByVal))
301 continue;
302 Value *Obj = findValue(V: Arg, /*OffsetOk=*/true);
303 Check(!isa<AllocaInst>(Obj),
304 "Undefined behavior: Call with \"tail\" keyword references "
305 "alloca",
306 &I);
307 }
308 }
309 }
310
311 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: &I))
312 switch (II->getIntrinsicID()) {
313 default:
314 break;
315
316 // TODO: Check more intrinsics
317
318 case Intrinsic::memcpy:
319 case Intrinsic::memcpy_inline: {
320 MemCpyInst *MCI = cast<MemCpyInst>(Val: &I);
321 visitMemoryReference(I, Loc: MemoryLocation::getForDest(MI: MCI),
322 Alignment: MCI->getDestAlign(), Ty: nullptr, Flags: MemRef::Write);
323 visitMemoryReference(I, Loc: MemoryLocation::getForSource(MTI: MCI),
324 Alignment: MCI->getSourceAlign(), Ty: nullptr, Flags: MemRef::Read);
325
326 // Check that the memcpy arguments don't overlap. The AliasAnalysis API
327 // isn't expressive enough for what we really want to do. Known partial
328 // overlap is not distinguished from the case where nothing is known.
329 auto Size = LocationSize::afterPointer();
330 if (const ConstantInt *Len =
331 dyn_cast<ConstantInt>(Val: findValue(V: MCI->getLength(),
332 /*OffsetOk=*/false)))
333 if (Len->getValue().isIntN(N: 32))
334 Size = LocationSize::precise(Value: Len->getValue().getZExtValue());
335 Check(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
336 AliasResult::MustAlias,
337 "Undefined behavior: memcpy source and destination overlap", &I);
338 break;
339 }
340 case Intrinsic::memmove: {
341 MemMoveInst *MMI = cast<MemMoveInst>(Val: &I);
342 visitMemoryReference(I, Loc: MemoryLocation::getForDest(MI: MMI),
343 Alignment: MMI->getDestAlign(), Ty: nullptr, Flags: MemRef::Write);
344 visitMemoryReference(I, Loc: MemoryLocation::getForSource(MTI: MMI),
345 Alignment: MMI->getSourceAlign(), Ty: nullptr, Flags: MemRef::Read);
346 break;
347 }
348 case Intrinsic::memset:
349 case Intrinsic::memset_inline: {
350 MemSetInst *MSI = cast<MemSetInst>(Val: &I);
351 visitMemoryReference(I, Loc: MemoryLocation::getForDest(MI: MSI),
352 Alignment: MSI->getDestAlign(), Ty: nullptr, Flags: MemRef::Write);
353 break;
354 }
355 case Intrinsic::vastart:
356 // vastart in non-varargs function is rejected by the verifier
357 visitMemoryReference(I, Loc: MemoryLocation::getForArgument(Call: &I, ArgIdx: 0, TLI),
358 Alignment: std::nullopt, Ty: nullptr, Flags: MemRef::Read | MemRef::Write);
359 break;
360 case Intrinsic::vacopy:
361 visitMemoryReference(I, Loc: MemoryLocation::getForArgument(Call: &I, ArgIdx: 0, TLI),
362 Alignment: std::nullopt, Ty: nullptr, Flags: MemRef::Write);
363 visitMemoryReference(I, Loc: MemoryLocation::getForArgument(Call: &I, ArgIdx: 1, TLI),
364 Alignment: std::nullopt, Ty: nullptr, Flags: MemRef::Read);
365 break;
366 case Intrinsic::vaend:
367 visitMemoryReference(I, Loc: MemoryLocation::getForArgument(Call: &I, ArgIdx: 0, TLI),
368 Alignment: std::nullopt, Ty: nullptr, Flags: MemRef::Read | MemRef::Write);
369 break;
370
371 case Intrinsic::stackrestore:
372 // Stackrestore doesn't read or write memory, but it sets the
373 // stack pointer, which the compiler may read from or write to
374 // at any time, so check it for both readability and writeability.
375 visitMemoryReference(I, Loc: MemoryLocation::getForArgument(Call: &I, ArgIdx: 0, TLI),
376 Alignment: std::nullopt, Ty: nullptr, Flags: MemRef::Read | MemRef::Write);
377 break;
378 }
379}
380
381void Lint::visitReturnInst(ReturnInst &I) {
382 Function *F = I.getParent()->getParent();
383 Check(!F->doesNotReturn(),
384 "Unusual: Return statement in function with noreturn attribute", &I);
385
386 if (Value *V = I.getReturnValue()) {
387 Value *Obj = findValue(V, /*OffsetOk=*/true);
388 Check(!isa<AllocaInst>(Obj), "Unusual: Returning alloca value", &I);
389 }
390}
391
392// TODO: Check that the reference is in bounds.
393// TODO: Check readnone/readonly function attributes.
394void Lint::visitMemoryReference(Instruction &I, const MemoryLocation &Loc,
395 MaybeAlign Align, Type *Ty, unsigned Flags) {
396 // If no memory is being referenced, it doesn't matter if the pointer
397 // is valid.
398 if (Loc.Size.isZero())
399 return;
400
401 Value *Ptr = const_cast<Value *>(Loc.Ptr);
402 Value *UnderlyingObject = findValue(V: Ptr, /*OffsetOk=*/true);
403 Check(!isa<ConstantPointerNull>(UnderlyingObject),
404 "Undefined behavior: Null pointer dereference", &I);
405 Check(!isa<UndefValue>(UnderlyingObject),
406 "Undefined behavior: Undef pointer dereference", &I);
407 Check(!isa<ConstantInt>(UnderlyingObject) ||
408 !cast<ConstantInt>(UnderlyingObject)->isMinusOne(),
409 "Unusual: All-ones pointer dereference", &I);
410 Check(!isa<ConstantInt>(UnderlyingObject) ||
411 !cast<ConstantInt>(UnderlyingObject)->isOne(),
412 "Unusual: Address one pointer dereference", &I);
413
414 if (Flags & MemRef::Write) {
415 if (TT.isAMDGPU())
416 Check(!AMDGPU::isConstantAddressSpace(
417 UnderlyingObject->getType()->getPointerAddressSpace()),
418 "Undefined behavior: Write to memory in const addrspace", &I);
419
420 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val: UnderlyingObject))
421 Check(!GV->isConstant(), "Undefined behavior: Write to read-only memory",
422 &I);
423 Check(!isa<Function>(UnderlyingObject) &&
424 !isa<BlockAddress>(UnderlyingObject),
425 "Undefined behavior: Write to text section", &I);
426 }
427 if (Flags & MemRef::Read) {
428 Check(!isa<Function>(UnderlyingObject), "Unusual: Load from function body",
429 &I);
430 Check(!isa<BlockAddress>(UnderlyingObject),
431 "Undefined behavior: Load from block address", &I);
432 }
433 if (Flags & MemRef::Callee) {
434 Check(!isa<BlockAddress>(UnderlyingObject),
435 "Undefined behavior: Call to block address", &I);
436 }
437 if (Flags & MemRef::Branchee) {
438 Check(!isa<Constant>(UnderlyingObject) ||
439 isa<BlockAddress>(UnderlyingObject),
440 "Undefined behavior: Branch to non-blockaddress", &I);
441 }
442
443 // Check for buffer overflows and misalignment.
444 // Only handles memory references that read/write something simple like an
445 // alloca instruction or a global variable.
446 int64_t Offset = 0;
447 if (Value *Base = GetPointerBaseWithConstantOffset(Ptr, Offset, DL: *DL)) {
448 // OK, so the access is to a constant offset from Ptr. Check that Ptr is
449 // something we can handle and if so extract the size of this base object
450 // along with its alignment.
451 uint64_t BaseSize = MemoryLocation::UnknownSize;
452 MaybeAlign BaseAlign;
453
454 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val: Base)) {
455 std::optional<TypeSize> ATy = AI->getAllocationSize(DL: *DL);
456 if (ATy && !ATy->isScalable())
457 BaseSize = ATy->getFixedValue();
458 BaseAlign = AI->getAlign();
459 } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Val: Base)) {
460 // If the global may be defined differently in another compilation unit
461 // then don't warn about funky memory accesses.
462 if (GV->hasDefinitiveInitializer()) {
463 Type *GTy = GV->getValueType();
464 if (GTy->isSized())
465 BaseSize = DL->getTypeAllocSize(Ty: GTy);
466 BaseAlign = GV->getAlign();
467 if (!BaseAlign && GTy->isSized())
468 BaseAlign = DL->getABITypeAlign(Ty: GTy);
469 }
470 }
471
472 // Accesses from before the start or after the end of the object are not
473 // defined.
474 Check(!Loc.Size.hasValue() || Loc.Size.isScalable() ||
475 BaseSize == MemoryLocation::UnknownSize ||
476 (Offset >= 0 && Offset + Loc.Size.getValue() <= BaseSize),
477 "Undefined behavior: Buffer overflow", &I);
478
479 // Accesses that say that the memory is more aligned than it is are not
480 // defined.
481 if (!Align && Ty && Ty->isSized())
482 Align = DL->getABITypeAlign(Ty);
483 if (BaseAlign && Align)
484 Check(*Align <= commonAlignment(*BaseAlign, Offset),
485 "Undefined behavior: Memory reference address is misaligned", &I);
486 }
487}
488
489void Lint::visitLoadInst(LoadInst &I) {
490 visitMemoryReference(I, Loc: MemoryLocation::get(LI: &I), Align: I.getAlign(), Ty: I.getType(),
491 Flags: MemRef::Read);
492}
493
494void Lint::visitStoreInst(StoreInst &I) {
495 visitMemoryReference(I, Loc: MemoryLocation::get(SI: &I), Align: I.getAlign(),
496 Ty: I.getOperand(i_nocapture: 0)->getType(), Flags: MemRef::Write);
497}
498
499void Lint::visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
500 visitMemoryReference(I, Loc: MemoryLocation::get(CXI: &I), Align: I.getAlign(),
501 Ty: I.getOperand(i_nocapture: 0)->getType(), Flags: MemRef::Write);
502}
503
504void Lint::visitAtomicRMWInst(AtomicRMWInst &I) {
505 visitMemoryReference(I, Loc: MemoryLocation::get(RMWI: &I), Align: I.getAlign(),
506 Ty: I.getOperand(i_nocapture: 0)->getType(), Flags: MemRef::Write);
507}
508
509void Lint::visitXor(BinaryOperator &I) {
510 Check(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
511 "Undefined result: xor(undef, undef)", &I);
512}
513
514void Lint::visitSub(BinaryOperator &I) {
515 Check(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
516 "Undefined result: sub(undef, undef)", &I);
517}
518
519void Lint::visitLShr(BinaryOperator &I) {
520 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: findValue(V: I.getOperand(i_nocapture: 1),
521 /*OffsetOk=*/false)))
522 Check(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
523 "Undefined result: Shift count out of range", &I);
524}
525
526void Lint::visitAShr(BinaryOperator &I) {
527 if (ConstantInt *CI =
528 dyn_cast<ConstantInt>(Val: findValue(V: I.getOperand(i_nocapture: 1), /*OffsetOk=*/false)))
529 Check(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
530 "Undefined result: Shift count out of range", &I);
531}
532
533void Lint::visitShl(BinaryOperator &I) {
534 if (ConstantInt *CI =
535 dyn_cast<ConstantInt>(Val: findValue(V: I.getOperand(i_nocapture: 1), /*OffsetOk=*/false)))
536 Check(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
537 "Undefined result: Shift count out of range", &I);
538}
539
540static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT,
541 AssumptionCache *AC) {
542 // Assume undef could be zero.
543 if (isa<UndefValue>(Val: V))
544 return true;
545
546 VectorType *VecTy = dyn_cast<VectorType>(Val: V->getType());
547 if (!VecTy) {
548 KnownBits Known = computeKnownBits(V, DL, AC, CxtI: dyn_cast<Instruction>(Val: V), DT);
549 return Known.isZero();
550 }
551
552 // Per-component check doesn't work with zeroinitializer
553 Constant *C = dyn_cast<Constant>(Val: V);
554 if (!C)
555 return false;
556
557 if (C->isNullValue())
558 return true;
559
560 // For a vector, KnownZero will only be true if all values are zero, so check
561 // this per component
562 for (unsigned I = 0, N = cast<FixedVectorType>(Val: VecTy)->getNumElements();
563 I != N; ++I) {
564 Constant *Elem = C->getAggregateElement(Elt: I);
565 if (isa<UndefValue>(Val: Elem))
566 return true;
567
568 KnownBits Known = computeKnownBits(V: Elem, DL);
569 if (Known.isZero())
570 return true;
571 }
572
573 return false;
574}
575
576void Lint::visitSDiv(BinaryOperator &I) {
577 Check(!isZero(I.getOperand(1), I.getDataLayout(), DT, AC),
578 "Undefined behavior: Division by zero", &I);
579}
580
581void Lint::visitUDiv(BinaryOperator &I) {
582 Check(!isZero(I.getOperand(1), I.getDataLayout(), DT, AC),
583 "Undefined behavior: Division by zero", &I);
584}
585
586void Lint::visitSRem(BinaryOperator &I) {
587 Check(!isZero(I.getOperand(1), I.getDataLayout(), DT, AC),
588 "Undefined behavior: Division by zero", &I);
589}
590
591void Lint::visitURem(BinaryOperator &I) {
592 Check(!isZero(I.getOperand(1), I.getDataLayout(), DT, AC),
593 "Undefined behavior: Division by zero", &I);
594}
595
596void Lint::visitAllocaInst(AllocaInst &I) {
597 if (isa<ConstantInt>(Val: I.getArraySize()))
598 // This isn't undefined behavior, it's just an obvious pessimization.
599 Check(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
600 "Pessimization: Static alloca outside of entry block", &I);
601
602 // TODO: Check for an unusual size (MSB set?)
603}
604
605void Lint::visitVAArgInst(VAArgInst &I) {
606 visitMemoryReference(I, Loc: MemoryLocation::get(VI: &I), Align: std::nullopt, Ty: nullptr,
607 Flags: MemRef::Read | MemRef::Write);
608}
609
610void Lint::visitIndirectBrInst(IndirectBrInst &I) {
611 visitMemoryReference(I, Loc: MemoryLocation::getAfter(Ptr: I.getAddress()),
612 Align: std::nullopt, Ty: nullptr, Flags: MemRef::Branchee);
613
614 Check(I.getNumDestinations() != 0,
615 "Undefined behavior: indirectbr with no destinations", &I);
616}
617
618void Lint::visitExtractElementInst(ExtractElementInst &I) {
619 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: findValue(V: I.getIndexOperand(),
620 /*OffsetOk=*/false))) {
621 ElementCount EC = I.getVectorOperandType()->getElementCount();
622 Check(EC.isScalable() || CI->getValue().ult(EC.getFixedValue()),
623 "Undefined result: extractelement index out of range", &I);
624 }
625}
626
627void Lint::visitInsertElementInst(InsertElementInst &I) {
628 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: findValue(V: I.getOperand(i_nocapture: 2),
629 /*OffsetOk=*/false))) {
630 ElementCount EC = I.getType()->getElementCount();
631 Check(EC.isScalable() || CI->getValue().ult(EC.getFixedValue()),
632 "Undefined result: insertelement index out of range", &I);
633 }
634}
635
636void Lint::visitUnreachableInst(UnreachableInst &I) {
637 // This isn't undefined behavior, it's merely suspicious.
638 Check(&I == &I.getParent()->front() ||
639 std::prev(I.getIterator())->mayHaveSideEffects(),
640 "Unusual: unreachable immediately preceded by instruction without "
641 "side effects",
642 &I);
643}
644
645/// findValue - Look through bitcasts and simple memory reference patterns
646/// to identify an equivalent, but more informative, value. If OffsetOk
647/// is true, look through getelementptrs with non-zero offsets too.
648///
649/// Most analysis passes don't require this logic, because instcombine
650/// will simplify most of these kinds of things away. But it's a goal of
651/// this Lint pass to be useful even on non-optimized IR.
652Value *Lint::findValue(Value *V, bool OffsetOk) const {
653 SmallPtrSet<Value *, 4> Visited;
654 return findValueImpl(V, OffsetOk, Visited);
655}
656
657/// findValueImpl - Implementation helper for findValue.
658Value *Lint::findValueImpl(Value *V, bool OffsetOk,
659 SmallPtrSetImpl<Value *> &Visited) const {
660 // Detect self-referential values.
661 if (!Visited.insert(Ptr: V).second)
662 return PoisonValue::get(T: V->getType());
663
664 // TODO: Look through sext or zext cast, when the result is known to
665 // be interpreted as signed or unsigned, respectively.
666 // TODO: Look through eliminable cast pairs.
667 // TODO: Look through calls with unique return values.
668 // TODO: Look through vector insert/extract/shuffle.
669 V = OffsetOk ? getUnderlyingObject(V) : V->stripPointerCasts();
670 if (LoadInst *L = dyn_cast<LoadInst>(Val: V)) {
671 BasicBlock::iterator BBI = L->getIterator();
672 BasicBlock *BB = L->getParent();
673 SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
674 BatchAAResults BatchAA(*AA);
675 for (;;) {
676 if (!VisitedBlocks.insert(Ptr: BB).second)
677 break;
678 if (Value *U =
679 FindAvailableLoadedValue(Load: L, ScanBB: BB, ScanFrom&: BBI, MaxInstsToScan: DefMaxInstsToScan, AA: &BatchAA))
680 return findValueImpl(V: U, OffsetOk, Visited);
681 if (BBI != BB->begin())
682 break;
683 BB = BB->getUniquePredecessor();
684 if (!BB)
685 break;
686 BBI = BB->end();
687 }
688 } else if (PHINode *PN = dyn_cast<PHINode>(Val: V)) {
689 if (Value *W = PN->hasConstantValue())
690 return findValueImpl(V: W, OffsetOk, Visited);
691 } else if (CastInst *CI = dyn_cast<CastInst>(Val: V)) {
692 if (CI->isNoopCast(DL: *DL))
693 return findValueImpl(V: CI->getOperand(i_nocapture: 0), OffsetOk, Visited);
694 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(Val: V)) {
695 if (Value *W =
696 FindInsertedValue(V: Ex->getAggregateOperand(), idx_range: Ex->getIndices()))
697 if (W != V)
698 return findValueImpl(V: W, OffsetOk, Visited);
699 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: V)) {
700 // Same as above, but for ConstantExpr instead of Instruction.
701 if (Instruction::isCast(Opcode: CE->getOpcode())) {
702 if (CastInst::isNoopCast(Opcode: Instruction::CastOps(CE->getOpcode()),
703 SrcTy: CE->getOperand(i_nocapture: 0)->getType(), DstTy: CE->getType(),
704 DL: *DL))
705 return findValueImpl(V: CE->getOperand(i_nocapture: 0), OffsetOk, Visited);
706 }
707 }
708
709 // As a last resort, try SimplifyInstruction or constant folding.
710 if (Instruction *Inst = dyn_cast<Instruction>(Val: V)) {
711 if (Value *W = simplifyInstruction(I: Inst, Q: {*DL, TLI, DT, AC}))
712 return findValueImpl(V: W, OffsetOk, Visited);
713 } else if (auto *C = dyn_cast<Constant>(Val: V)) {
714 Value *W = ConstantFoldConstant(C, DL: *DL, TLI);
715 if (W != V)
716 return findValueImpl(V: W, OffsetOk, Visited);
717 }
718
719 return V;
720}
721
722PreservedAnalyses LintPass::run(Function &F, FunctionAnalysisManager &AM) {
723 auto *Mod = F.getParent();
724 auto *DL = &F.getDataLayout();
725 auto *AA = &AM.getResult<AAManager>(IR&: F);
726 auto *AC = &AM.getResult<AssumptionAnalysis>(IR&: F);
727 auto *DT = &AM.getResult<DominatorTreeAnalysis>(IR&: F);
728 auto *TLI = &AM.getResult<TargetLibraryAnalysis>(IR&: F);
729 Lint L(Mod, DL, AA, AC, DT, TLI);
730 L.visit(F);
731 dbgs() << L.MessagesStr.str();
732 if (AbortOnError && !L.MessagesStr.str().empty())
733 report_fatal_error(
734 reason: "linter found errors, aborting. (enabled by abort-on-error)", gen_crash_diag: false);
735 return PreservedAnalyses::all();
736}
737
738void LintPass::printPipeline(
739 raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
740 PassInfoMixin<LintPass>::printPipeline(OS, MapClassName2PassName);
741 if (AbortOnError)
742 OS << "<abort-on-error>";
743}
744
745//===----------------------------------------------------------------------===//
746// Implement the public interfaces to this file...
747//===----------------------------------------------------------------------===//
748
749/// lintFunction - Check a function for errors, printing messages on stderr.
750///
751void llvm::lintFunction(const Function &f, bool AbortOnError) {
752 Function &F = const_cast<Function &>(f);
753 assert(!F.isDeclaration() && "Cannot lint external functions");
754
755 FunctionAnalysisManager FAM;
756 FAM.registerPass(PassBuilder: [&] { return TargetLibraryAnalysis(); });
757 FAM.registerPass(PassBuilder: [&] { return DominatorTreeAnalysis(); });
758 FAM.registerPass(PassBuilder: [&] { return AssumptionAnalysis(); });
759 FAM.registerPass(PassBuilder: [&] {
760 AAManager AA;
761 AA.registerFunctionAnalysis<BasicAA>();
762 AA.registerFunctionAnalysis<ScopedNoAliasAA>();
763 AA.registerFunctionAnalysis<TypeBasedAA>();
764 return AA;
765 });
766 LintPass(AbortOnError).run(F, AM&: FAM);
767}
768
769/// lintModule - Check a module for errors, printing messages on stderr.
770///
771void llvm::lintModule(const Module &M, bool AbortOnError) {
772 for (const Function &F : M) {
773 if (!F.isDeclaration())
774 lintFunction(f: F, AbortOnError);
775 }
776}
777