Add a -lint pass which checks for common sources of undefined or likely
[oota-llvm.git] / lib / Analysis / Lint.cpp
1 //===-- Lint.cpp - Check for common errors in LLVM IR ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass statically checks for common and easily-identified constructs
11 // which produce undefined or likely unintended behavior in LLVM IR.
12 //
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.
19 // 
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.
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/Passes.h"
37 #include "llvm/Analysis/AliasAnalysis.h"
38 #include "llvm/Analysis/Lint.h"
39 #include "llvm/Analysis/ValueTracking.h"
40 #include "llvm/Assembly/Writer.h"
41 #include "llvm/Target/TargetData.h"
42 #include "llvm/Pass.h"
43 #include "llvm/PassManager.h"
44 #include "llvm/IntrinsicInst.h"
45 #include "llvm/Function.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/raw_ostream.h"
50 using namespace llvm;
51
52 namespace {
53   class Lint : public FunctionPass, public InstVisitor<Lint> {
54     friend class InstVisitor<Lint>;
55
56     void visitCallSite(CallSite CS);
57     void visitMemoryReference(Instruction &I, Value *Ptr, unsigned Align,
58                               const Type *Ty);
59
60     void visitInstruction(Instruction &I);
61     void visitCallInst(CallInst &I);
62     void visitInvokeInst(InvokeInst &I);
63     void visitReturnInst(ReturnInst &I);
64     void visitLoadInst(LoadInst &I);
65     void visitStoreInst(StoreInst &I);
66     void visitSDiv(BinaryOperator &I);
67     void visitUDiv(BinaryOperator &I);
68     void visitSRem(BinaryOperator &I);
69     void visitURem(BinaryOperator &I);
70     void visitAllocaInst(AllocaInst &I);
71     void visitVAArgInst(VAArgInst &I);
72     void visitIndirectBrInst(IndirectBrInst &I);
73
74   public:
75     Module *Mod;
76     AliasAnalysis *AA;
77     TargetData *TD;
78
79     std::string Messages;
80     raw_string_ostream MessagesStr;
81
82     static char ID; // Pass identification, replacement for typeid
83     Lint() : FunctionPass(&ID), MessagesStr(Messages) {}
84
85     virtual bool runOnFunction(Function &F);
86
87     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
88       AU.setPreservesAll();
89       AU.addRequired<AliasAnalysis>();
90     }
91     virtual void print(raw_ostream &O, const Module *M) const {}
92
93     void WriteValue(const Value *V) {
94       if (!V) return;
95       if (isa<Instruction>(V)) {
96         MessagesStr << *V << '\n';
97       } else {
98         WriteAsOperand(MessagesStr, V, true, Mod);
99         MessagesStr << '\n';
100       }
101     }
102
103     void WriteType(const Type *T) {
104       if (!T) return;
105       MessagesStr << ' ';
106       WriteTypeSymbolic(MessagesStr, T, Mod);
107     }
108
109     // CheckFailed - A check failed, so print out the condition and the message
110     // that failed.  This provides a nice place to put a breakpoint if you want
111     // to see why something is not correct.
112     void CheckFailed(const Twine &Message,
113                      const Value *V1 = 0, const Value *V2 = 0,
114                      const Value *V3 = 0, const Value *V4 = 0) {
115       MessagesStr << Message.str() << "\n";
116       WriteValue(V1);
117       WriteValue(V2);
118       WriteValue(V3);
119       WriteValue(V4);
120     }
121
122     void CheckFailed(const Twine &Message, const Value *V1,
123                      const Type *T2, const Value *V3 = 0) {
124       MessagesStr << Message.str() << "\n";
125       WriteValue(V1);
126       WriteType(T2);
127       WriteValue(V3);
128     }
129
130     void CheckFailed(const Twine &Message, const Type *T1,
131                      const Type *T2 = 0, const Type *T3 = 0) {
132       MessagesStr << Message.str() << "\n";
133       WriteType(T1);
134       WriteType(T2);
135       WriteType(T3);
136     }
137   };
138 }
139
140 char Lint::ID = 0;
141 static RegisterPass<Lint>
142 X("lint", "Statically lint-checks LLVM IR", false, true);
143
144 // Assert - We know that cond should be true, if not print an error message.
145 #define Assert(C, M) \
146     do { if (!(C)) { CheckFailed(M); return; } } while (0)
147 #define Assert1(C, M, V1) \
148     do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
149 #define Assert2(C, M, V1, V2) \
150     do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
151 #define Assert3(C, M, V1, V2, V3) \
152     do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
153 #define Assert4(C, M, V1, V2, V3, V4) \
154     do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
155
156 // Lint::run - This is the main Analysis entry point for a
157 // function.
158 //
159 bool Lint::runOnFunction(Function &F) {
160   Mod = F.getParent();
161   AA = &getAnalysis<AliasAnalysis>();
162   TD = getAnalysisIfAvailable<TargetData>();
163   visit(F);
164   dbgs() << MessagesStr.str();
165   return false;
166 }
167
168 void Lint::visitInstruction(Instruction &I) {
169 }
170
171 void Lint::visitCallSite(CallSite CS) {
172   Instruction &I = *CS.getInstruction();
173   Value *Callee = CS.getCalledValue();
174
175   // TODO: Check function alignment?
176   visitMemoryReference(I, Callee, 0, 0);
177
178   if (Function *F = dyn_cast<Function>(Callee->stripPointerCasts())) {
179     Assert1(CS.getCallingConv() == F->getCallingConv(),
180             "Caller and callee calling convention differ", &I);
181
182     const FunctionType *FT = F->getFunctionType();
183     unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
184
185     Assert1(FT->isVarArg() ?
186               FT->getNumParams() <= NumActualArgs :
187               FT->getNumParams() == NumActualArgs,
188             "Call argument count mismatches callee argument count", &I);
189       
190     // TODO: Check argument types (in case the callee was casted)
191
192     // TODO: Check ABI-significant attributes.
193
194     // TODO: Check noalias attribute.
195
196     // TODO: Check sret attribute.
197   }
198
199   // TODO: Check the "tail" keyword constraints.
200
201   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
202     switch (II->getIntrinsicID()) {
203     default: break;
204
205     // TODO: Check more intrinsics
206
207     case Intrinsic::memcpy: {
208       MemCpyInst *MCI = cast<MemCpyInst>(&I);
209       visitMemoryReference(I, MCI->getSource(), MCI->getAlignment(), 0);
210       visitMemoryReference(I, MCI->getDest(), MCI->getAlignment(), 0);
211
212       unsigned Size = 0;
213       if (const ConstantInt *Len =
214             dyn_cast<ConstantInt>(MCI->getLength()->stripPointerCasts()))
215         if (Len->getValue().isIntN(32))
216           Size = Len->getValue().getZExtValue();
217       Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
218               AliasAnalysis::MustAlias,
219               "memcpy source and destination overlap", &I);
220       break;
221     }
222     case Intrinsic::memmove: {
223       MemMoveInst *MMI = cast<MemMoveInst>(&I);
224       visitMemoryReference(I, MMI->getSource(), MMI->getAlignment(), 0);
225       visitMemoryReference(I, MMI->getDest(), MMI->getAlignment(), 0);
226       break;
227     }
228     case Intrinsic::memset: {
229       MemSetInst *MSI = cast<MemSetInst>(&I);
230       visitMemoryReference(I, MSI->getDest(), MSI->getAlignment(), 0);
231       break;
232     }
233
234     case Intrinsic::vastart:
235       visitMemoryReference(I, CS.getArgument(0), 0, 0);
236       break;
237     case Intrinsic::vacopy:
238       visitMemoryReference(I, CS.getArgument(0), 0, 0);
239       visitMemoryReference(I, CS.getArgument(1), 0, 0);
240       break;
241     case Intrinsic::vaend:
242       visitMemoryReference(I, CS.getArgument(0), 0, 0);
243       break;
244
245     case Intrinsic::stackrestore:
246       visitMemoryReference(I, CS.getArgument(0), 0, 0);
247       break;
248     }
249 }
250
251 void Lint::visitCallInst(CallInst &I) {
252   return visitCallSite(&I);
253 }
254
255 void Lint::visitInvokeInst(InvokeInst &I) {
256   return visitCallSite(&I);
257 }
258
259 void Lint::visitReturnInst(ReturnInst &I) {
260   Function *F = I.getParent()->getParent();
261   Assert1(!F->doesNotReturn(),
262           "Return statement in function with noreturn attribute", &I);
263 }
264
265 // TODO: Add a length argument and check that the reference is in bounds
266 // TODO: Add read/write/execute flags and check for writing to read-only
267 //       memory or jumping to suspicious writeable memory
268 void Lint::visitMemoryReference(Instruction &I,
269                                 Value *Ptr, unsigned Align, const Type *Ty) {
270   Assert1(!isa<ConstantPointerNull>(Ptr->getUnderlyingObject()),
271           "Null pointer dereference", &I);
272   Assert1(!isa<UndefValue>(Ptr->getUnderlyingObject()),
273           "Undef pointer dereference", &I);
274
275   if (TD) {
276     if (Align == 0 && Ty) Align = TD->getABITypeAlignment(Ty);
277
278     if (Align != 0) {
279       unsigned BitWidth = TD->getTypeSizeInBits(Ptr->getType());
280       APInt Mask = APInt::getAllOnesValue(BitWidth),
281                    KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
282       ComputeMaskedBits(Ptr, Mask, KnownZero, KnownOne, TD);
283       Assert1(!(KnownOne & APInt::getLowBitsSet(BitWidth, Log2_32(Align))),
284               "Memory reference address is misaligned", &I);
285     }
286   }
287 }
288
289 void Lint::visitLoadInst(LoadInst &I) {
290   visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(), I.getType());
291 }
292
293 void Lint::visitStoreInst(StoreInst &I) {
294   visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(),
295                   I.getOperand(0)->getType());
296 }
297
298 static bool isZero(Value *V, TargetData *TD) {
299   unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
300   APInt Mask = APInt::getAllOnesValue(BitWidth),
301                KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
302   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
303   return KnownZero.isAllOnesValue();
304 }
305
306 void Lint::visitSDiv(BinaryOperator &I) {
307   Assert1(!isZero(I.getOperand(1), TD), "Division by zero", &I);
308 }
309
310 void Lint::visitUDiv(BinaryOperator &I) {
311   Assert1(!isZero(I.getOperand(1), TD), "Division by zero", &I);
312 }
313
314 void Lint::visitSRem(BinaryOperator &I) {
315   Assert1(!isZero(I.getOperand(1), TD), "Division by zero", &I);
316 }
317
318 void Lint::visitURem(BinaryOperator &I) {
319   Assert1(!isZero(I.getOperand(1), TD), "Division by zero", &I);
320 }
321
322 void Lint::visitAllocaInst(AllocaInst &I) {
323   if (isa<ConstantInt>(I.getArraySize()))
324     // This isn't undefined behavior, it's just an obvious pessimization.
325     Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
326             "Static alloca outside of entry block", &I);
327 }
328
329 void Lint::visitVAArgInst(VAArgInst &I) {
330   visitMemoryReference(I, I.getOperand(0), 0, 0);
331 }
332
333 void Lint::visitIndirectBrInst(IndirectBrInst &I) {
334   visitMemoryReference(I, I.getAddress(), 0, 0);
335 }
336
337 //===----------------------------------------------------------------------===//
338 //  Implement the public interfaces to this file...
339 //===----------------------------------------------------------------------===//
340
341 FunctionPass *llvm::createLintPass() {
342   return new Lint();
343 }
344
345 /// lintFunction - Check a function for errors, printing messages on stderr.
346 ///
347 void llvm::lintFunction(const Function &f) {
348   Function &F = const_cast<Function&>(f);
349   assert(!F.isDeclaration() && "Cannot lint external functions");
350
351   FunctionPassManager FPM(F.getParent());
352   Lint *V = new Lint();
353   FPM.add(V);
354   FPM.run(F);
355 }
356
357 /// lintModule - Check a module for errors, printing messages on stderr.
358 /// Return true if the module is corrupt.
359 ///
360 void llvm::lintModule(const Module &M, std::string *ErrorInfo) {
361   PassManager PM;
362   Lint *V = new Lint();
363   PM.add(V);
364   PM.run(const_cast<Module&>(M));
365
366   if (ErrorInfo)
367     *ErrorInfo = V->MessagesStr.str();
368 }