blob: 4b9f284c9dc255160305b2fb8c29487074893131 [file] [log] [blame]
Dan Gohman113902e2010-04-08 18:47:09 +00001//===-- 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.
Dan Gohman08833552010-04-22 01:30:05 +000023//
Dan Gohman113902e2010-04-08 18:47:09 +000024// 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"
Dan Gohmanff26d4e2010-05-28 16:21:24 +000038#include "llvm/Analysis/InstructionSimplify.h"
39#include "llvm/Analysis/ConstantFolding.h"
40#include "llvm/Analysis/Dominators.h"
Dan Gohman113902e2010-04-08 18:47:09 +000041#include "llvm/Analysis/Lint.h"
Dan Gohmanff26d4e2010-05-28 16:21:24 +000042#include "llvm/Analysis/Loads.h"
Dan Gohman113902e2010-04-08 18:47:09 +000043#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"
Dan Gohmanbe02b202010-04-09 01:39:53 +000054#include "llvm/ADT/STLExtras.h"
Dan Gohman113902e2010-04-08 18:47:09 +000055using namespace llvm;
56
57namespace {
Dan Gohman5b61b382010-04-30 19:05:00 +000058 namespace MemRef {
59 static unsigned Read = 1;
60 static unsigned Write = 2;
61 static unsigned Callee = 4;
62 static unsigned Branchee = 8;
63 }
64
Dan Gohman113902e2010-04-08 18:47:09 +000065 class Lint : public FunctionPass, public InstVisitor<Lint> {
66 friend class InstVisitor<Lint>;
67
Dan Gohmanbe02b202010-04-09 01:39:53 +000068 void visitFunction(Function &F);
69
Dan Gohman113902e2010-04-08 18:47:09 +000070 void visitCallSite(CallSite CS);
71 void visitMemoryReference(Instruction &I, Value *Ptr, unsigned Align,
Dan Gohman5b61b382010-04-30 19:05:00 +000072 const Type *Ty, unsigned Flags);
Dan Gohman113902e2010-04-08 18:47:09 +000073
Dan Gohman113902e2010-04-08 18:47:09 +000074 void visitCallInst(CallInst &I);
75 void visitInvokeInst(InvokeInst &I);
76 void visitReturnInst(ReturnInst &I);
77 void visitLoadInst(LoadInst &I);
78 void visitStoreInst(StoreInst &I);
Dan Gohmanbe02b202010-04-09 01:39:53 +000079 void visitXor(BinaryOperator &I);
80 void visitSub(BinaryOperator &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +000081 void visitLShr(BinaryOperator &I);
82 void visitAShr(BinaryOperator &I);
83 void visitShl(BinaryOperator &I);
Dan Gohman113902e2010-04-08 18:47:09 +000084 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);
Dan Gohmandd98c4d2010-04-08 23:05:57 +000091 void visitExtractElementInst(ExtractElementInst &I);
92 void visitInsertElementInst(InsertElementInst &I);
Dan Gohmanbe02b202010-04-09 01:39:53 +000093 void visitUnreachableInst(UnreachableInst &I);
Dan Gohman113902e2010-04-08 18:47:09 +000094
Dan Gohmanff26d4e2010-05-28 16:21:24 +000095 Value *findValue(Value *V, bool OffsetOk) const;
96
Dan Gohman113902e2010-04-08 18:47:09 +000097 public:
98 Module *Mod;
99 AliasAnalysis *AA;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000100 DominatorTree *DT;
Dan Gohman113902e2010-04-08 18:47:09 +0000101 TargetData *TD;
102
103 std::string Messages;
104 raw_string_ostream MessagesStr;
105
106 static char ID; // Pass identification, replacement for typeid
107 Lint() : FunctionPass(&ID), MessagesStr(Messages) {}
108
109 virtual bool runOnFunction(Function &F);
110
111 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
112 AU.setPreservesAll();
113 AU.addRequired<AliasAnalysis>();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000114 AU.addRequired<DominatorTree>();
Dan Gohman113902e2010-04-08 18:47:09 +0000115 }
116 virtual void print(raw_ostream &O, const Module *M) const {}
117
118 void WriteValue(const Value *V) {
119 if (!V) return;
120 if (isa<Instruction>(V)) {
121 MessagesStr << *V << '\n';
122 } else {
123 WriteAsOperand(MessagesStr, V, true, Mod);
124 MessagesStr << '\n';
125 }
126 }
127
128 void WriteType(const Type *T) {
129 if (!T) return;
130 MessagesStr << ' ';
131 WriteTypeSymbolic(MessagesStr, T, Mod);
132 }
133
134 // CheckFailed - A check failed, so print out the condition and the message
135 // that failed. This provides a nice place to put a breakpoint if you want
136 // to see why something is not correct.
137 void CheckFailed(const Twine &Message,
138 const Value *V1 = 0, const Value *V2 = 0,
139 const Value *V3 = 0, const Value *V4 = 0) {
140 MessagesStr << Message.str() << "\n";
141 WriteValue(V1);
142 WriteValue(V2);
143 WriteValue(V3);
144 WriteValue(V4);
145 }
146
147 void CheckFailed(const Twine &Message, const Value *V1,
148 const Type *T2, const Value *V3 = 0) {
149 MessagesStr << Message.str() << "\n";
150 WriteValue(V1);
151 WriteType(T2);
152 WriteValue(V3);
153 }
154
155 void CheckFailed(const Twine &Message, const Type *T1,
156 const Type *T2 = 0, const Type *T3 = 0) {
157 MessagesStr << Message.str() << "\n";
158 WriteType(T1);
159 WriteType(T2);
160 WriteType(T3);
161 }
162 };
163}
164
165char Lint::ID = 0;
166static RegisterPass<Lint>
167X("lint", "Statically lint-checks LLVM IR", false, true);
168
169// Assert - We know that cond should be true, if not print an error message.
170#define Assert(C, M) \
171 do { if (!(C)) { CheckFailed(M); return; } } while (0)
172#define Assert1(C, M, V1) \
173 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
174#define Assert2(C, M, V1, V2) \
175 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
176#define Assert3(C, M, V1, V2, V3) \
177 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
178#define Assert4(C, M, V1, V2, V3, V4) \
179 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
180
181// Lint::run - This is the main Analysis entry point for a
182// function.
183//
184bool Lint::runOnFunction(Function &F) {
185 Mod = F.getParent();
186 AA = &getAnalysis<AliasAnalysis>();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000187 DT = &getAnalysis<DominatorTree>();
Dan Gohman113902e2010-04-08 18:47:09 +0000188 TD = getAnalysisIfAvailable<TargetData>();
189 visit(F);
190 dbgs() << MessagesStr.str();
Dan Gohmana0f7ff32010-05-26 22:28:53 +0000191 Messages.clear();
Dan Gohman113902e2010-04-08 18:47:09 +0000192 return false;
193}
194
Dan Gohmanbe02b202010-04-09 01:39:53 +0000195void Lint::visitFunction(Function &F) {
196 // This isn't undefined behavior, it's just a little unusual, and it's a
197 // fairly common mistake to neglect to name a function.
198 Assert1(F.hasName() || F.hasLocalLinkage(),
199 "Unusual: Unnamed function with non-local linkage", &F);
Dan Gohman113902e2010-04-08 18:47:09 +0000200}
201
202void Lint::visitCallSite(CallSite CS) {
203 Instruction &I = *CS.getInstruction();
204 Value *Callee = CS.getCalledValue();
205
Dan Gohman5b61b382010-04-30 19:05:00 +0000206 visitMemoryReference(I, Callee, 0, 0, MemRef::Callee);
Dan Gohman113902e2010-04-08 18:47:09 +0000207
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000208 if (Function *F = dyn_cast<Function>(findValue(Callee, /*OffsetOk=*/false))) {
Dan Gohman113902e2010-04-08 18:47:09 +0000209 Assert1(CS.getCallingConv() == F->getCallingConv(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000210 "Undefined behavior: Caller and callee calling convention differ",
211 &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000212
213 const FunctionType *FT = F->getFunctionType();
214 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
215
216 Assert1(FT->isVarArg() ?
217 FT->getNumParams() <= NumActualArgs :
218 FT->getNumParams() == NumActualArgs,
Dan Gohmanbe02b202010-04-09 01:39:53 +0000219 "Undefined behavior: Call argument count mismatches callee "
220 "argument count", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000221
222 // TODO: Check argument types (in case the callee was casted)
223
224 // TODO: Check ABI-significant attributes.
225
226 // TODO: Check noalias attribute.
227
228 // TODO: Check sret attribute.
229 }
230
Dan Gohman113b3e22010-05-26 21:46:36 +0000231 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
232 for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
233 AI != AE; ++AI) {
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000234 Value *Obj = findValue(*AI, /*OffsetOk=*/true);
Dan Gohman078f8592010-05-28 16:34:49 +0000235 Assert1(!isa<AllocaInst>(Obj),
Dan Gohman113b3e22010-05-26 21:46:36 +0000236 "Undefined behavior: Call with \"tail\" keyword references "
Dan Gohman078f8592010-05-28 16:34:49 +0000237 "alloca", &I);
Dan Gohman113b3e22010-05-26 21:46:36 +0000238 }
239
Dan Gohman113902e2010-04-08 18:47:09 +0000240
241 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
242 switch (II->getIntrinsicID()) {
243 default: break;
244
245 // TODO: Check more intrinsics
246
247 case Intrinsic::memcpy: {
248 MemCpyInst *MCI = cast<MemCpyInst>(&I);
Dan Gohman5b61b382010-04-30 19:05:00 +0000249 visitMemoryReference(I, MCI->getSource(), MCI->getAlignment(), 0,
250 MemRef::Write);
251 visitMemoryReference(I, MCI->getDest(), MCI->getAlignment(), 0,
252 MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000253
Dan Gohmanbe02b202010-04-09 01:39:53 +0000254 // Check that the memcpy arguments don't overlap. The AliasAnalysis API
255 // isn't expressive enough for what we really want to do. Known partial
256 // overlap is not distinguished from the case where nothing is known.
Dan Gohman113902e2010-04-08 18:47:09 +0000257 unsigned Size = 0;
258 if (const ConstantInt *Len =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000259 dyn_cast<ConstantInt>(findValue(MCI->getLength(),
260 /*OffsetOk=*/false)))
Dan Gohman113902e2010-04-08 18:47:09 +0000261 if (Len->getValue().isIntN(32))
262 Size = Len->getValue().getZExtValue();
263 Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
264 AliasAnalysis::MustAlias,
Dan Gohmanbe02b202010-04-09 01:39:53 +0000265 "Undefined behavior: memcpy source and destination overlap", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000266 break;
267 }
268 case Intrinsic::memmove: {
269 MemMoveInst *MMI = cast<MemMoveInst>(&I);
Dan Gohman5b61b382010-04-30 19:05:00 +0000270 visitMemoryReference(I, MMI->getSource(), MMI->getAlignment(), 0,
271 MemRef::Write);
272 visitMemoryReference(I, MMI->getDest(), MMI->getAlignment(), 0,
273 MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000274 break;
275 }
276 case Intrinsic::memset: {
277 MemSetInst *MSI = cast<MemSetInst>(&I);
Dan Gohman5b61b382010-04-30 19:05:00 +0000278 visitMemoryReference(I, MSI->getDest(), MSI->getAlignment(), 0,
279 MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000280 break;
281 }
282
283 case Intrinsic::vastart:
Dan Gohmanbe02b202010-04-09 01:39:53 +0000284 Assert1(I.getParent()->getParent()->isVarArg(),
285 "Undefined behavior: va_start called in a non-varargs function",
286 &I);
287
Dan Gohman5b61b382010-04-30 19:05:00 +0000288 visitMemoryReference(I, CS.getArgument(0), 0, 0,
289 MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000290 break;
291 case Intrinsic::vacopy:
Dan Gohman5b61b382010-04-30 19:05:00 +0000292 visitMemoryReference(I, CS.getArgument(0), 0, 0, MemRef::Write);
293 visitMemoryReference(I, CS.getArgument(1), 0, 0, MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000294 break;
295 case Intrinsic::vaend:
Dan Gohman5b61b382010-04-30 19:05:00 +0000296 visitMemoryReference(I, CS.getArgument(0), 0, 0,
297 MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000298 break;
Dan Gohman882ddb42010-05-26 22:21:25 +0000299
300 case Intrinsic::stackrestore:
301 // Stackrestore doesn't read or write memory, but it sets the
302 // stack pointer, which the compiler may read from or write to
303 // at any time, so check it for both readability and writeability.
304 visitMemoryReference(I, CS.getArgument(0), 0, 0,
305 MemRef::Read | MemRef::Write);
306 break;
Dan Gohman113902e2010-04-08 18:47:09 +0000307 }
308}
309
310void Lint::visitCallInst(CallInst &I) {
311 return visitCallSite(&I);
312}
313
314void Lint::visitInvokeInst(InvokeInst &I) {
315 return visitCallSite(&I);
316}
317
318void Lint::visitReturnInst(ReturnInst &I) {
319 Function *F = I.getParent()->getParent();
320 Assert1(!F->doesNotReturn(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000321 "Unusual: Return statement in function with noreturn attribute",
322 &I);
Dan Gohman292fc872010-05-28 04:33:42 +0000323
324 if (Value *V = I.getReturnValue()) {
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000325 Value *Obj = findValue(V, /*OffsetOk=*/true);
Dan Gohman078f8592010-05-28 16:34:49 +0000326 Assert1(!isa<AllocaInst>(Obj),
327 "Unusual: Returning alloca value", &I);
Dan Gohman292fc872010-05-28 04:33:42 +0000328 }
Dan Gohman113902e2010-04-08 18:47:09 +0000329}
330
331// TODO: Add a length argument and check that the reference is in bounds
Dan Gohman113902e2010-04-08 18:47:09 +0000332void Lint::visitMemoryReference(Instruction &I,
Dan Gohman5b61b382010-04-30 19:05:00 +0000333 Value *Ptr, unsigned Align, const Type *Ty,
334 unsigned Flags) {
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000335 Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
Dan Gohmanbe02b202010-04-09 01:39:53 +0000336 Assert1(!isa<ConstantPointerNull>(UnderlyingObject),
337 "Undefined behavior: Null pointer dereference", &I);
338 Assert1(!isa<UndefValue>(UnderlyingObject),
339 "Undefined behavior: Undef pointer dereference", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000340
Dan Gohman5b61b382010-04-30 19:05:00 +0000341 if (Flags & MemRef::Write) {
342 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
343 Assert1(!GV->isConstant(),
344 "Undefined behavior: Write to read-only memory", &I);
345 Assert1(!isa<Function>(UnderlyingObject) &&
346 !isa<BlockAddress>(UnderlyingObject),
347 "Undefined behavior: Write to text section", &I);
348 }
349 if (Flags & MemRef::Read) {
350 Assert1(!isa<Function>(UnderlyingObject),
351 "Unusual: Load from function body", &I);
352 Assert1(!isa<BlockAddress>(UnderlyingObject),
353 "Undefined behavior: Load from block address", &I);
354 }
355 if (Flags & MemRef::Callee) {
356 Assert1(!isa<BlockAddress>(UnderlyingObject),
357 "Undefined behavior: Call to block address", &I);
358 }
359 if (Flags & MemRef::Branchee) {
360 Assert1(!isa<Constant>(UnderlyingObject) ||
361 isa<BlockAddress>(UnderlyingObject),
362 "Undefined behavior: Branch to non-blockaddress", &I);
363 }
364
Dan Gohman113902e2010-04-08 18:47:09 +0000365 if (TD) {
366 if (Align == 0 && Ty) Align = TD->getABITypeAlignment(Ty);
367
368 if (Align != 0) {
369 unsigned BitWidth = TD->getTypeSizeInBits(Ptr->getType());
370 APInt Mask = APInt::getAllOnesValue(BitWidth),
371 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
372 ComputeMaskedBits(Ptr, Mask, KnownZero, KnownOne, TD);
373 Assert1(!(KnownOne & APInt::getLowBitsSet(BitWidth, Log2_32(Align))),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000374 "Undefined behavior: Memory reference address is misaligned", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000375 }
376 }
377}
378
379void Lint::visitLoadInst(LoadInst &I) {
Dan Gohman5b61b382010-04-30 19:05:00 +0000380 visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(), I.getType(),
381 MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000382}
383
384void Lint::visitStoreInst(StoreInst &I) {
385 visitMemoryReference(I, I.getPointerOperand(), I.getAlignment(),
Dan Gohman5b61b382010-04-30 19:05:00 +0000386 I.getOperand(0)->getType(), MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000387}
388
Dan Gohmanbe02b202010-04-09 01:39:53 +0000389void Lint::visitXor(BinaryOperator &I) {
390 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
391 !isa<UndefValue>(I.getOperand(1)),
392 "Undefined result: xor(undef, undef)", &I);
393}
394
395void Lint::visitSub(BinaryOperator &I) {
396 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
397 !isa<UndefValue>(I.getOperand(1)),
398 "Undefined result: sub(undef, undef)", &I);
399}
400
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000401void Lint::visitLShr(BinaryOperator &I) {
402 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000403 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000404 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000405 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000406}
407
408void Lint::visitAShr(BinaryOperator &I) {
409 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000410 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000411 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000412 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000413}
414
415void Lint::visitShl(BinaryOperator &I) {
416 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000417 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000418 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000419 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000420}
421
Dan Gohman113902e2010-04-08 18:47:09 +0000422static bool isZero(Value *V, TargetData *TD) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000423 // Assume undef could be zero.
424 if (isa<UndefValue>(V)) return true;
425
Dan Gohman113902e2010-04-08 18:47:09 +0000426 unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
427 APInt Mask = APInt::getAllOnesValue(BitWidth),
428 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
429 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
430 return KnownZero.isAllOnesValue();
431}
432
433void Lint::visitSDiv(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000434 Assert1(!isZero(I.getOperand(1), TD),
435 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000436}
437
438void Lint::visitUDiv(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000439 Assert1(!isZero(I.getOperand(1), TD),
440 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000441}
442
443void Lint::visitSRem(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000444 Assert1(!isZero(I.getOperand(1), TD),
445 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000446}
447
448void Lint::visitURem(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000449 Assert1(!isZero(I.getOperand(1), TD),
450 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000451}
452
453void Lint::visitAllocaInst(AllocaInst &I) {
454 if (isa<ConstantInt>(I.getArraySize()))
455 // This isn't undefined behavior, it's just an obvious pessimization.
456 Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000457 "Pessimization: Static alloca outside of entry block", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000458}
459
460void Lint::visitVAArgInst(VAArgInst &I) {
Dan Gohman5b61b382010-04-30 19:05:00 +0000461 visitMemoryReference(I, I.getOperand(0), 0, 0,
462 MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000463}
464
465void Lint::visitIndirectBrInst(IndirectBrInst &I) {
Dan Gohman5b61b382010-04-30 19:05:00 +0000466 visitMemoryReference(I, I.getAddress(), 0, 0, MemRef::Branchee);
Dan Gohman113902e2010-04-08 18:47:09 +0000467}
468
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000469void Lint::visitExtractElementInst(ExtractElementInst &I) {
470 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000471 dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
472 /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000473 Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000474 "Undefined result: extractelement index out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000475}
476
477void Lint::visitInsertElementInst(InsertElementInst &I) {
478 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000479 dyn_cast<ConstantInt>(findValue(I.getOperand(2),
480 /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000481 Assert1(CI->getValue().ult(I.getType()->getNumElements()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000482 "Undefined result: insertelement index out of range", &I);
483}
484
485void Lint::visitUnreachableInst(UnreachableInst &I) {
486 // This isn't undefined behavior, it's merely suspicious.
487 Assert1(&I == I.getParent()->begin() ||
488 prior(BasicBlock::iterator(&I))->mayHaveSideEffects(),
489 "Unusual: unreachable immediately preceded by instruction without "
490 "side effects", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000491}
492
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000493/// findValue - Look through bitcasts and simple memory reference patterns
494/// to identify an equivalent, but more informative, value. If OffsetOk
495/// is true, look through getelementptrs with non-zero offsets too.
496///
497/// Most analysis passes don't require this logic, because instcombine
498/// will simplify most of these kinds of things away. But it's a goal of
499/// this Lint pass to be useful even on non-optimized IR.
500Value *Lint::findValue(Value *V, bool OffsetOk) const {
501 // TODO: Look through sext or zext cast, when the result is known to
502 // be interpreted as signed or unsigned, respectively.
503 // TODO: Look through calls with unique return values.
504 // TODO: Look through vector insert/extract/shuffle.
505 V = OffsetOk ? V->getUnderlyingObject() : V->stripPointerCasts();
506 if (LoadInst *L = dyn_cast<LoadInst>(V)) {
507 BasicBlock::iterator BBI = L;
508 BasicBlock *BB = L->getParent();
509 for (;;) {
510 if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(),
511 BB, BBI, 6, AA))
512 return findValue(U, OffsetOk);
513 BB = L->getParent()->getUniquePredecessor();
514 if (!BB) break;
515 BBI = BB->end();
516 }
517 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
518 if (CI->isNoopCast(TD ? TD->getIntPtrType(V->getContext()) :
519 Type::getInt64Ty(V->getContext())))
520 return findValue(CI->getOperand(0), OffsetOk);
521 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
522 if (Value *W = PN->hasConstantValue(DT))
523 return findValue(W, OffsetOk);
524 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
525 if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
526 Ex->idx_begin(),
527 Ex->idx_end()))
528 if (W != V)
529 return findValue(W, OffsetOk);
530 }
531
532 // As a last resort, try SimplifyInstruction or constant folding.
533 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
534 if (Value *W = SimplifyInstruction(Inst, TD))
535 if (W != Inst)
536 return findValue(W, OffsetOk);
537 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
538 if (Value *W = ConstantFoldConstantExpression(CE, TD))
539 if (W != V)
540 return findValue(W, OffsetOk);
541 }
542
543 return V;
544}
545
Dan Gohman113902e2010-04-08 18:47:09 +0000546//===----------------------------------------------------------------------===//
547// Implement the public interfaces to this file...
548//===----------------------------------------------------------------------===//
549
550FunctionPass *llvm::createLintPass() {
551 return new Lint();
552}
553
554/// lintFunction - Check a function for errors, printing messages on stderr.
555///
556void llvm::lintFunction(const Function &f) {
557 Function &F = const_cast<Function&>(f);
558 assert(!F.isDeclaration() && "Cannot lint external functions");
559
560 FunctionPassManager FPM(F.getParent());
561 Lint *V = new Lint();
562 FPM.add(V);
563 FPM.run(F);
564}
565
566/// lintModule - Check a module for errors, printing messages on stderr.
Dan Gohman113902e2010-04-08 18:47:09 +0000567///
Dan Gohmana0f7ff32010-05-26 22:28:53 +0000568void llvm::lintModule(const Module &M) {
Dan Gohman113902e2010-04-08 18:47:09 +0000569 PassManager PM;
570 Lint *V = new Lint();
571 PM.add(V);
572 PM.run(const_cast<Module&>(M));
Dan Gohman113902e2010-04-08 18:47:09 +0000573}