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