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