1 //===-- Lint.cpp - Check for common errors in LLVM IR ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass statically checks for common and easily-identified constructs
11 // which produce undefined or likely unintended behavior in LLVM IR.
13 // It is not a guarantee of correctness, in two ways. First, it isn't
14 // comprehensive. There are checks which could be done statically which are
15 // not yet implemented. Some of these are indicated by TODO comments, but
16 // those aren't comprehensive either. Second, many conditions cannot be
17 // checked statically. This pass does no dynamic instrumentation, so it
18 // can't check for all possible problems.
20 // Another limitation is that it assumes all code will be executed. A store
21 // through a null pointer in a basic block which is never reached is harmless,
22 // but this pass will warn about it anyway.
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.
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.
34 //===----------------------------------------------------------------------===//
36 #include "llvm/Analysis/Passes.h"
37 #include "llvm/Analysis/AliasAnalysis.h"
38 #include "llvm/Analysis/InstructionSimplify.h"
39 #include "llvm/Analysis/ConstantFolding.h"
40 #include "llvm/Analysis/Dominators.h"
41 #include "llvm/Analysis/Lint.h"
42 #include "llvm/Analysis/Loads.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/Assembly/Writer.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Pass.h"
47 #include "llvm/PassManager.h"
48 #include "llvm/IntrinsicInst.h"
49 #include "llvm/Function.h"
50 #include "llvm/Support/CallSite.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/InstVisitor.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/ADT/STLExtras.h"
59 static unsigned Read = 1;
60 static unsigned Write = 2;
61 static unsigned Callee = 4;
62 static unsigned Branchee = 8;
65 class Lint : public FunctionPass, public InstVisitor<Lint> {
66 friend class InstVisitor<Lint>;
68 void visitFunction(Function &F);
70 void visitCallSite(CallSite CS);
71 void visitMemoryReference(Instruction &I, Value *Ptr, unsigned Align,
72 const Type *Ty, unsigned Flags);
74 void visitCallInst(CallInst &I);
75 void visitInvokeInst(InvokeInst &I);
76 void visitReturnInst(ReturnInst &I);
77 void visitLoadInst(LoadInst &I);
78 void visitStoreInst(StoreInst &I);
79 void visitXor(BinaryOperator &I);
80 void visitSub(BinaryOperator &I);
81 void visitLShr(BinaryOperator &I);
82 void visitAShr(BinaryOperator &I);
83 void visitShl(BinaryOperator &I);
84 void visitSDiv(BinaryOperator &I);
85 void visitUDiv(BinaryOperator &I);
86 void visitSRem(BinaryOperator &I);
87 void visitURem(BinaryOperator &I);
88 void visitAllocaInst(AllocaInst &I);
89 void visitVAArgInst(VAArgInst &I);
90 void visitIndirectBrInst(IndirectBrInst &I);
91 void visitExtractElementInst(ExtractElementInst &I);
92 void visitInsertElementInst(InsertElementInst &I);
93 void visitUnreachableInst(UnreachableInst &I);
95 Value *findValue(Value *V, bool OffsetOk) const;
96 Value *findValueImpl(Value *V, bool OffsetOk,
97 SmallPtrSet<Value *, 4> &Visited) const;
105 std::string Messages;
106 raw_string_ostream MessagesStr;
108 static char ID; // Pass identification, replacement for typeid
109 Lint() : FunctionPass(&ID), MessagesStr(Messages) {}
111 virtual bool runOnFunction(Function &F);
113 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
114 AU.setPreservesAll();
115 AU.addRequired<AliasAnalysis>();
116 AU.addRequired<DominatorTree>();
118 virtual void print(raw_ostream &O, const Module *M) const {}
120 void WriteValue(const Value *V) {
122 if (isa<Instruction>(V)) {
123 MessagesStr << *V << '\n';
125 WriteAsOperand(MessagesStr, V, true, Mod);
130 void WriteType(const Type *T) {
133 WriteTypeSymbolic(MessagesStr, T, Mod);
136 // CheckFailed - A check failed, so print out the condition and the message
137 // that failed. This provides a nice place to put a breakpoint if you want
138 // to see why something is not correct.
139 void CheckFailed(const Twine &Message,
140 const Value *V1 = 0, const Value *V2 = 0,
141 const Value *V3 = 0, const Value *V4 = 0) {
142 MessagesStr << Message.str() << "\n";
149 void CheckFailed(const Twine &Message, const Value *V1,
150 const Type *T2, const Value *V3 = 0) {
151 MessagesStr << Message.str() << "\n";
157 void CheckFailed(const Twine &Message, const Type *T1,
158 const Type *T2 = 0, const Type *T3 = 0) {
159 MessagesStr << Message.str() << "\n";
168 static RegisterPass<Lint>
169 X("lint", "Statically lint-checks LLVM IR", false, true);
171 // Assert - We know that cond should be true, if not print an error message.
172 #define Assert(C, M) \
173 do { if (!(C)) { CheckFailed(M); return; } } while (0)
174 #define Assert1(C, M, V1) \
175 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
176 #define Assert2(C, M, V1, V2) \
177 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
178 #define Assert3(C, M, V1, V2, V3) \
179 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
180 #define Assert4(C, M, V1, V2, V3, V4) \
181 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
183 // Lint::run - This is the main Analysis entry point for a
186 bool Lint::runOnFunction(Function &F) {
188 AA = &getAnalysis<AliasAnalysis>();
189 DT = &getAnalysis<DominatorTree>();
190 TD = getAnalysisIfAvailable<TargetData>();
192 dbgs() << MessagesStr.str();
197 void Lint::visitFunction(Function &F) {
198 // This isn't undefined behavior, it's just a little unusual, and it's a
199 // fairly common mistake to neglect to name a function.
200 Assert1(F.hasName() || F.hasLocalLinkage(),
201 "Unusual: Unnamed function with non-local linkage", &F);
204 void Lint::visitCallSite(CallSite CS) {
205 Instruction &I = *CS.getInstruction();
206 Value *Callee = CS.getCalledValue();
208 visitMemoryReference(I, Callee, 0, 0, MemRef::Callee);
210 if (Function *F = dyn_cast<Function>(findValue(Callee, /*OffsetOk=*/false))) {
211 Assert1(CS.getCallingConv() == F->getCallingConv(),
212 "Undefined behavior: Caller and callee calling convention differ",
215 const FunctionType *FT = F->getFunctionType();
216 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
218 Assert1(FT->isVarArg() ?
219 FT->getNumParams() <= NumActualArgs :
220 FT->getNumParams() == NumActualArgs,
221 "Undefined behavior: Call argument count mismatches callee "
222 "argument count", &I);
224 // TODO: Check argument types (in case the callee was casted)
226 // TODO: Check ABI-significant attributes.
228 // TODO: Check noalias attribute.
230 // TODO: Check sret attribute.
233 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
234 for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
236 Value *Obj = findValue(*AI, /*OffsetOk=*/true);
237 Assert1(!isa<AllocaInst>(Obj),
238 "Undefined behavior: Call with \"tail\" keyword references "
243 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
244 switch (II->getIntrinsicID()) {
247 // TODO: Check more intrinsics
249 case Intrinsic::memcpy: {
250 MemCpyInst *MCI = cast<MemCpyInst>(&I);
251 visitMemoryReference(I, MCI->getSource(), MCI->getAlignment(), 0,
253 visitMemoryReference(I, MCI->getDest(), MCI->getAlignment(), 0,
256 // Check that the memcpy arguments don't overlap. The AliasAnalysis API
257 // isn't expressive enough for what we really want to do. Known partial
258 // overlap is not distinguished from the case where nothing is known.
260 if (const ConstantInt *Len =
261 dyn_cast<ConstantInt>(findValue(MCI->getLength(),
262 /*OffsetOk=*/false)))
263 if (Len->getValue().isIntN(32))
264 Size = Len->getValue().getZExtValue();
265 Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
266 AliasAnalysis::MustAlias,
267 "Undefined behavior: memcpy source and destination overlap", &I);
270 case Intrinsic::memmove: {
271 MemMoveInst *MMI = cast<MemMoveInst>(&I);
272 visitMemoryReference(I, MMI->getSource(), MMI->getAlignment(), 0,
274 visitMemoryReference(I, MMI->getDest(), MMI->getAlignment(), 0,
278 case Intrinsic::memset: {
279 MemSetInst *MSI = cast<MemSetInst>(&I);
280 visitMemoryReference(I, MSI->getDest(), MSI->getAlignment(), 0,
285 case Intrinsic::vastart:
286 Assert1(I.getParent()->getParent()->isVarArg(),
287 "Undefined behavior: va_start called in a non-varargs function",
290 visitMemoryReference(I, CS.getArgument(0), 0, 0,
291 MemRef::Read | MemRef::Write);
293 case Intrinsic::vacopy:
294 visitMemoryReference(I, CS.getArgument(0), 0, 0, MemRef::Write);
295 visitMemoryReference(I, CS.getArgument(1), 0, 0, MemRef::Read);
297 case Intrinsic::vaend:
298 visitMemoryReference(I, CS.getArgument(0), 0, 0,
299 MemRef::Read | MemRef::Write);
302 case Intrinsic::stackrestore:
303 // Stackrestore doesn't read or write memory, but it sets the
304 // stack pointer, which the compiler may read from or write to
305 // at any time, so check it for both readability and writeability.
306 visitMemoryReference(I, CS.getArgument(0), 0, 0,
307 MemRef::Read | MemRef::Write);
312 void Lint::visitCallInst(CallInst &I) {
313 return visitCallSite(&I);
316 void Lint::visitInvokeInst(InvokeInst &I) {
317 return visitCallSite(&I);
320 void Lint::visitReturnInst(ReturnInst &I) {
321 Function *F = I.getParent()->getParent();
322 Assert1(!F->doesNotReturn(),
323 "Unusual: Return statement in function with noreturn attribute",
326 if (Value *V = I.getReturnValue()) {
327 Value *Obj = findValue(V, /*OffsetOk=*/true);
328 Assert1(!isa<AllocaInst>(Obj),
329 "Unusual: Returning alloca value", &I);
333 // TODO: Add a length argument and check that the reference is in bounds
334 void Lint::visitMemoryReference(Instruction &I,
335 Value *Ptr, unsigned Align, const Type *Ty,
337 Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
338 Assert1(!isa<ConstantPointerNull>(UnderlyingObject),
339 "Undefined behavior: Null pointer dereference", &I);
340 Assert1(!isa<UndefValue>(UnderlyingObject),
341 "Undefined behavior: Undef pointer dereference", &I);
343 if (Flags & MemRef::Write) {
344 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
345 Assert1(!GV->isConstant(),
346 "Undefined behavior: Write to read-only memory", &I);
347 Assert1(!isa<Function>(UnderlyingObject) &&
348 !isa<BlockAddress>(UnderlyingObject),
349 "Undefined behavior: Write to text section", &I);
351 if (Flags & MemRef::Read) {
352 Assert1(!isa<Function>(UnderlyingObject),
353 "Unusual: Load from function body", &I);
354 Assert1(!isa<BlockAddress>(UnderlyingObject),
355 "Undefined behavior: Load from block address", &I);
357 if (Flags & MemRef::Callee) {
358 Assert1(!isa<BlockAddress>(UnderlyingObject),
359 "Undefined behavior: Call to block address", &I);
361 if (Flags & MemRef::Branchee) {
362 Assert1(!isa<Constant>(UnderlyingObject) ||
363 isa<BlockAddress>(UnderlyingObject),
364 "Undefined behavior: Branch to non-blockaddress", &I);
368 if (Align == 0 && Ty) Align = TD->getABITypeAlignment(Ty);
371 unsigned BitWidth = TD->getTypeSizeInBits(Ptr->getType());
372 APInt Mask = APInt::getAllOnesValue(BitWidth),
373 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
374 ComputeMaskedBits(Ptr, Mask, KnownZero, KnownOne, TD);
375 Assert1(!(KnownOne & APInt::getLowBitsSet(BitWidth, Log2_32(Align))),
376 "Undefined behavior: Memory reference address is misaligned", &I);
381 void Lint::visitLoadInst(LoadInst &I) {
382 visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(), I.getType(),
386 void Lint::visitStoreInst(StoreInst &I) {
387 visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(),
388 I.getOperand(0)->getType(), MemRef::Write);
391 void Lint::visitXor(BinaryOperator &I) {
392 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
393 !isa<UndefValue>(I.getOperand(1)),
394 "Undefined result: xor(undef, undef)", &I);
397 void Lint::visitSub(BinaryOperator &I) {
398 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
399 !isa<UndefValue>(I.getOperand(1)),
400 "Undefined result: sub(undef, undef)", &I);
403 void Lint::visitLShr(BinaryOperator &I) {
404 if (ConstantInt *CI =
405 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
406 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
407 "Undefined result: Shift count out of range", &I);
410 void Lint::visitAShr(BinaryOperator &I) {
411 if (ConstantInt *CI =
412 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
413 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
414 "Undefined result: Shift count out of range", &I);
417 void Lint::visitShl(BinaryOperator &I) {
418 if (ConstantInt *CI =
419 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
420 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
421 "Undefined result: Shift count out of range", &I);
424 static bool isZero(Value *V, TargetData *TD) {
425 // Assume undef could be zero.
426 if (isa<UndefValue>(V)) return true;
428 unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
429 APInt Mask = APInt::getAllOnesValue(BitWidth),
430 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
431 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
432 return KnownZero.isAllOnesValue();
435 void Lint::visitSDiv(BinaryOperator &I) {
436 Assert1(!isZero(I.getOperand(1), TD),
437 "Undefined behavior: Division by zero", &I);
440 void Lint::visitUDiv(BinaryOperator &I) {
441 Assert1(!isZero(I.getOperand(1), TD),
442 "Undefined behavior: Division by zero", &I);
445 void Lint::visitSRem(BinaryOperator &I) {
446 Assert1(!isZero(I.getOperand(1), TD),
447 "Undefined behavior: Division by zero", &I);
450 void Lint::visitURem(BinaryOperator &I) {
451 Assert1(!isZero(I.getOperand(1), TD),
452 "Undefined behavior: Division by zero", &I);
455 void Lint::visitAllocaInst(AllocaInst &I) {
456 if (isa<ConstantInt>(I.getArraySize()))
457 // This isn't undefined behavior, it's just an obvious pessimization.
458 Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
459 "Pessimization: Static alloca outside of entry block", &I);
462 void Lint::visitVAArgInst(VAArgInst &I) {
463 visitMemoryReference(I, I.getOperand(0), 0, 0,
464 MemRef::Read | MemRef::Write);
467 void Lint::visitIndirectBrInst(IndirectBrInst &I) {
468 visitMemoryReference(I, I.getAddress(), 0, 0, MemRef::Branchee);
471 void Lint::visitExtractElementInst(ExtractElementInst &I) {
472 if (ConstantInt *CI =
473 dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
474 /*OffsetOk=*/false)))
475 Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
476 "Undefined result: extractelement index out of range", &I);
479 void Lint::visitInsertElementInst(InsertElementInst &I) {
480 if (ConstantInt *CI =
481 dyn_cast<ConstantInt>(findValue(I.getOperand(2),
482 /*OffsetOk=*/false)))
483 Assert1(CI->getValue().ult(I.getType()->getNumElements()),
484 "Undefined result: insertelement index out of range", &I);
487 void Lint::visitUnreachableInst(UnreachableInst &I) {
488 // This isn't undefined behavior, it's merely suspicious.
489 Assert1(&I == I.getParent()->begin() ||
490 prior(BasicBlock::iterator(&I))->mayHaveSideEffects(),
491 "Unusual: unreachable immediately preceded by instruction without "
495 /// findValue - Look through bitcasts and simple memory reference patterns
496 /// to identify an equivalent, but more informative, value. If OffsetOk
497 /// is true, look through getelementptrs with non-zero offsets too.
499 /// Most analysis passes don't require this logic, because instcombine
500 /// will simplify most of these kinds of things away. But it's a goal of
501 /// this Lint pass to be useful even on non-optimized IR.
502 Value *Lint::findValue(Value *V, bool OffsetOk) const {
503 SmallPtrSet<Value *, 4> Visited;
504 return findValueImpl(V, OffsetOk, Visited);
507 /// findValueImpl - Implementation helper for findValue.
508 Value *Lint::findValueImpl(Value *V, bool OffsetOk,
509 SmallPtrSet<Value *, 4> &Visited) const {
510 // Detect self-referential values.
511 if (!Visited.insert(V))
512 return UndefValue::get(V->getType());
514 // TODO: Look through sext or zext cast, when the result is known to
515 // be interpreted as signed or unsigned, respectively.
516 // TODO: Look through calls with unique return values.
517 // TODO: Look through vector insert/extract/shuffle.
518 V = OffsetOk ? V->getUnderlyingObject() : V->stripPointerCasts();
519 if (LoadInst *L = dyn_cast<LoadInst>(V)) {
520 BasicBlock::iterator BBI = L;
521 BasicBlock *BB = L->getParent();
523 if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(),
525 return findValueImpl(U, OffsetOk, Visited);
526 BB = L->getParent()->getUniquePredecessor();
530 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
531 if (CI->isNoopCast(TD ? TD->getIntPtrType(V->getContext()) :
532 Type::getInt64Ty(V->getContext())))
533 return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
534 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
535 if (Value *W = PN->hasConstantValue(DT))
536 return findValueImpl(W, OffsetOk, Visited);
537 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
538 if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
542 return findValueImpl(W, OffsetOk, Visited);
545 // As a last resort, try SimplifyInstruction or constant folding.
546 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
547 if (Value *W = SimplifyInstruction(Inst, TD))
549 return findValueImpl(W, OffsetOk, Visited);
550 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
551 if (Value *W = ConstantFoldConstantExpression(CE, TD))
553 return findValueImpl(W, OffsetOk, Visited);
559 //===----------------------------------------------------------------------===//
560 // Implement the public interfaces to this file...
561 //===----------------------------------------------------------------------===//
563 FunctionPass *llvm::createLintPass() {
567 /// lintFunction - Check a function for errors, printing messages on stderr.
569 void llvm::lintFunction(const Function &f) {
570 Function &F = const_cast<Function&>(f);
571 assert(!F.isDeclaration() && "Cannot lint external functions");
573 FunctionPassManager FPM(F.getParent());
574 Lint *V = new Lint();
579 /// lintModule - Check a module for errors, printing messages on stderr.
581 void llvm::lintModule(const Module &M) {
583 Lint *V = new Lint();
585 PM.run(const_cast<Module&>(M));