blob: 60654e6170172126e6052dc64d9439c1efa555a3 [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,
Dan Gohmand3b6e412010-07-06 15:21:57 +000022// but this pass will warn about it anyway. This is the main reason why most
23// of these checks live here instead of in the Verifier pass.
Dan Gohman08833552010-04-22 01:30:05 +000024//
Dan Gohman113902e2010-04-08 18:47:09 +000025// Optimization passes may make conditions that this pass checks for more or
26// less obvious. If an optimization pass appears to be introducing a warning,
27// it may be that the optimization pass is merely exposing an existing
28// condition in the code.
29//
30// This code may be run before instcombine. In many cases, instcombine checks
31// for the same kinds of things and turns instructions with undefined behavior
32// into unreachable (or equivalent). Because of this, this pass makes some
33// effort to look through bitcasts and so on.
34//
35//===----------------------------------------------------------------------===//
36
37#include "llvm/Analysis/Passes.h"
38#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohmanff26d4e2010-05-28 16:21:24 +000039#include "llvm/Analysis/InstructionSimplify.h"
40#include "llvm/Analysis/ConstantFolding.h"
41#include "llvm/Analysis/Dominators.h"
Dan Gohman113902e2010-04-08 18:47:09 +000042#include "llvm/Analysis/Lint.h"
Dan Gohmanff26d4e2010-05-28 16:21:24 +000043#include "llvm/Analysis/Loads.h"
Dan Gohman113902e2010-04-08 18:47:09 +000044#include "llvm/Analysis/ValueTracking.h"
45#include "llvm/Assembly/Writer.h"
46#include "llvm/Target/TargetData.h"
47#include "llvm/Pass.h"
48#include "llvm/PassManager.h"
49#include "llvm/IntrinsicInst.h"
50#include "llvm/Function.h"
51#include "llvm/Support/CallSite.h"
52#include "llvm/Support/Debug.h"
53#include "llvm/Support/InstVisitor.h"
54#include "llvm/Support/raw_ostream.h"
Dan Gohmanbe02b202010-04-09 01:39:53 +000055#include "llvm/ADT/STLExtras.h"
Dan Gohman113902e2010-04-08 18:47:09 +000056using namespace llvm;
57
58namespace {
Dan Gohman5b61b382010-04-30 19:05:00 +000059 namespace MemRef {
60 static unsigned Read = 1;
61 static unsigned Write = 2;
62 static unsigned Callee = 4;
63 static unsigned Branchee = 8;
64 }
65
Dan Gohman113902e2010-04-08 18:47:09 +000066 class Lint : public FunctionPass, public InstVisitor<Lint> {
67 friend class InstVisitor<Lint>;
68
Dan Gohmanbe02b202010-04-09 01:39:53 +000069 void visitFunction(Function &F);
70
Dan Gohman113902e2010-04-08 18:47:09 +000071 void visitCallSite(CallSite CS);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +000072 void visitMemoryReference(Instruction &I, Value *Ptr,
73 unsigned Size, unsigned Align,
Dan Gohman5b61b382010-04-30 19:05:00 +000074 const Type *Ty, unsigned Flags);
Dan Gohman113902e2010-04-08 18:47:09 +000075
Dan Gohman113902e2010-04-08 18:47:09 +000076 void visitCallInst(CallInst &I);
77 void visitInvokeInst(InvokeInst &I);
78 void visitReturnInst(ReturnInst &I);
79 void visitLoadInst(LoadInst &I);
80 void visitStoreInst(StoreInst &I);
Dan Gohmanbe02b202010-04-09 01:39:53 +000081 void visitXor(BinaryOperator &I);
82 void visitSub(BinaryOperator &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +000083 void visitLShr(BinaryOperator &I);
84 void visitAShr(BinaryOperator &I);
85 void visitShl(BinaryOperator &I);
Dan Gohman113902e2010-04-08 18:47:09 +000086 void visitSDiv(BinaryOperator &I);
87 void visitUDiv(BinaryOperator &I);
88 void visitSRem(BinaryOperator &I);
89 void visitURem(BinaryOperator &I);
90 void visitAllocaInst(AllocaInst &I);
91 void visitVAArgInst(VAArgInst &I);
92 void visitIndirectBrInst(IndirectBrInst &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +000093 void visitExtractElementInst(ExtractElementInst &I);
94 void visitInsertElementInst(InsertElementInst &I);
Dan Gohmanbe02b202010-04-09 01:39:53 +000095 void visitUnreachableInst(UnreachableInst &I);
Dan Gohman113902e2010-04-08 18:47:09 +000096
Dan Gohmanff26d4e2010-05-28 16:21:24 +000097 Value *findValue(Value *V, bool OffsetOk) const;
Dan Gohman17d95962010-05-28 16:45:33 +000098 Value *findValueImpl(Value *V, bool OffsetOk,
99 SmallPtrSet<Value *, 4> &Visited) const;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000100
Dan Gohman113902e2010-04-08 18:47:09 +0000101 public:
102 Module *Mod;
103 AliasAnalysis *AA;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000104 DominatorTree *DT;
Dan Gohman113902e2010-04-08 18:47:09 +0000105 TargetData *TD;
106
107 std::string Messages;
108 raw_string_ostream MessagesStr;
109
110 static char ID; // Pass identification, replacement for typeid
111 Lint() : FunctionPass(&ID), MessagesStr(Messages) {}
112
113 virtual bool runOnFunction(Function &F);
114
115 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
116 AU.setPreservesAll();
117 AU.addRequired<AliasAnalysis>();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000118 AU.addRequired<DominatorTree>();
Dan Gohman113902e2010-04-08 18:47:09 +0000119 }
120 virtual void print(raw_ostream &O, const Module *M) const {}
121
122 void WriteValue(const Value *V) {
123 if (!V) return;
124 if (isa<Instruction>(V)) {
125 MessagesStr << *V << '\n';
126 } else {
127 WriteAsOperand(MessagesStr, V, true, Mod);
128 MessagesStr << '\n';
129 }
130 }
131
132 void WriteType(const Type *T) {
133 if (!T) return;
134 MessagesStr << ' ';
135 WriteTypeSymbolic(MessagesStr, T, Mod);
136 }
137
138 // CheckFailed - A check failed, so print out the condition and the message
139 // that failed. This provides a nice place to put a breakpoint if you want
140 // to see why something is not correct.
141 void CheckFailed(const Twine &Message,
142 const Value *V1 = 0, const Value *V2 = 0,
143 const Value *V3 = 0, const Value *V4 = 0) {
144 MessagesStr << Message.str() << "\n";
145 WriteValue(V1);
146 WriteValue(V2);
147 WriteValue(V3);
148 WriteValue(V4);
149 }
150
151 void CheckFailed(const Twine &Message, const Value *V1,
152 const Type *T2, const Value *V3 = 0) {
153 MessagesStr << Message.str() << "\n";
154 WriteValue(V1);
155 WriteType(T2);
156 WriteValue(V3);
157 }
158
159 void CheckFailed(const Twine &Message, const Type *T1,
160 const Type *T2 = 0, const Type *T3 = 0) {
161 MessagesStr << Message.str() << "\n";
162 WriteType(T1);
163 WriteType(T2);
164 WriteType(T3);
165 }
166 };
167}
168
169char Lint::ID = 0;
170static RegisterPass<Lint>
171X("lint", "Statically lint-checks LLVM IR", false, true);
172
173// Assert - We know that cond should be true, if not print an error message.
174#define Assert(C, M) \
175 do { if (!(C)) { CheckFailed(M); return; } } while (0)
176#define Assert1(C, M, V1) \
177 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
178#define Assert2(C, M, V1, V2) \
179 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
180#define Assert3(C, M, V1, V2, V3) \
181 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
182#define Assert4(C, M, V1, V2, V3, V4) \
183 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
184
185// Lint::run - This is the main Analysis entry point for a
186// function.
187//
188bool Lint::runOnFunction(Function &F) {
189 Mod = F.getParent();
190 AA = &getAnalysis<AliasAnalysis>();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000191 DT = &getAnalysis<DominatorTree>();
Dan Gohman113902e2010-04-08 18:47:09 +0000192 TD = getAnalysisIfAvailable<TargetData>();
193 visit(F);
194 dbgs() << MessagesStr.str();
Dan Gohmana0f7ff32010-05-26 22:28:53 +0000195 Messages.clear();
Dan Gohman113902e2010-04-08 18:47:09 +0000196 return false;
197}
198
Dan Gohmanbe02b202010-04-09 01:39:53 +0000199void Lint::visitFunction(Function &F) {
200 // This isn't undefined behavior, it's just a little unusual, and it's a
201 // fairly common mistake to neglect to name a function.
202 Assert1(F.hasName() || F.hasLocalLinkage(),
203 "Unusual: Unnamed function with non-local linkage", &F);
Dan Gohman0ce24992010-07-06 15:23:00 +0000204
205 // TODO: Check for irreducible control flow.
Dan Gohman113902e2010-04-08 18:47:09 +0000206}
207
208void Lint::visitCallSite(CallSite CS) {
209 Instruction &I = *CS.getInstruction();
210 Value *Callee = CS.getCalledValue();
211
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000212 visitMemoryReference(I, Callee, ~0u, 0, 0, MemRef::Callee);
Dan Gohman113902e2010-04-08 18:47:09 +0000213
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000214 if (Function *F = dyn_cast<Function>(findValue(Callee, /*OffsetOk=*/false))) {
Dan Gohman113902e2010-04-08 18:47:09 +0000215 Assert1(CS.getCallingConv() == F->getCallingConv(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000216 "Undefined behavior: Caller and callee calling convention differ",
217 &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000218
219 const FunctionType *FT = F->getFunctionType();
220 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
221
222 Assert1(FT->isVarArg() ?
223 FT->getNumParams() <= NumActualArgs :
224 FT->getNumParams() == NumActualArgs,
Dan Gohmanbe02b202010-04-09 01:39:53 +0000225 "Undefined behavior: Call argument count mismatches callee "
226 "argument count", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000227
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000228 // Check argument types (in case the callee was casted) and attributes.
Dan Gohman0ce24992010-07-06 15:23:00 +0000229 // TODO: Verify that caller and callee attributes are compatible.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000230 Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
231 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
232 for (; AI != AE; ++AI) {
233 Value *Actual = *AI;
234 if (PI != PE) {
235 Argument *Formal = PI++;
236 Assert1(Formal->getType() == Actual->getType(),
237 "Undefined behavior: Call argument type mismatches "
238 "callee parameter type", &I);
Dan Gohman10e77262010-06-01 20:51:40 +0000239
240 // Check that noalias arguments don't alias other arguments. The
241 // AliasAnalysis API isn't expressive enough for what we really want
242 // to do. Known partial overlap is not distinguished from the case
243 // where nothing is known.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000244 if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy())
Dan Gohman10e77262010-06-01 20:51:40 +0000245 for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI) {
246 Assert1(AI == BI ||
247 AA->alias(*AI, ~0u, *BI, ~0u) != AliasAnalysis::MustAlias,
248 "Unusual: noalias argument aliases another argument", &I);
249 }
250
251 // Check that an sret argument points to valid memory.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000252 if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
253 const Type *Ty =
254 cast<PointerType>(Formal->getType())->getElementType();
255 visitMemoryReference(I, Actual, AA->getTypeStoreSize(Ty),
256 TD ? TD->getABITypeAlignment(Ty) : 0,
257 Ty, MemRef::Read | MemRef::Write);
258 }
259 }
260 }
Dan Gohman113902e2010-04-08 18:47:09 +0000261 }
262
Dan Gohman113b3e22010-05-26 21:46:36 +0000263 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
264 for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
265 AI != AE; ++AI) {
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000266 Value *Obj = findValue(*AI, /*OffsetOk=*/true);
Dan Gohman078f8592010-05-28 16:34:49 +0000267 Assert1(!isa<AllocaInst>(Obj),
Dan Gohman113b3e22010-05-26 21:46:36 +0000268 "Undefined behavior: Call with \"tail\" keyword references "
Dan Gohman078f8592010-05-28 16:34:49 +0000269 "alloca", &I);
Dan Gohman113b3e22010-05-26 21:46:36 +0000270 }
271
Dan Gohman113902e2010-04-08 18:47:09 +0000272
273 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
274 switch (II->getIntrinsicID()) {
275 default: break;
276
277 // TODO: Check more intrinsics
278
279 case Intrinsic::memcpy: {
280 MemCpyInst *MCI = cast<MemCpyInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000281 // TODO: If the size is known, use it.
282 visitMemoryReference(I, MCI->getDest(), ~0u, MCI->getAlignment(), 0,
Dan Gohman13ec30b2010-05-28 17:44:00 +0000283 MemRef::Write);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000284 visitMemoryReference(I, MCI->getSource(), ~0u, MCI->getAlignment(), 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000285 MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000286
Dan Gohmanbe02b202010-04-09 01:39:53 +0000287 // Check that the memcpy arguments don't overlap. The AliasAnalysis API
288 // isn't expressive enough for what we really want to do. Known partial
289 // overlap is not distinguished from the case where nothing is known.
Dan Gohman113902e2010-04-08 18:47:09 +0000290 unsigned Size = 0;
291 if (const ConstantInt *Len =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000292 dyn_cast<ConstantInt>(findValue(MCI->getLength(),
293 /*OffsetOk=*/false)))
Dan Gohman113902e2010-04-08 18:47:09 +0000294 if (Len->getValue().isIntN(32))
295 Size = Len->getValue().getZExtValue();
296 Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
297 AliasAnalysis::MustAlias,
Dan Gohmanbe02b202010-04-09 01:39:53 +0000298 "Undefined behavior: memcpy source and destination overlap", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000299 break;
300 }
301 case Intrinsic::memmove: {
302 MemMoveInst *MMI = cast<MemMoveInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000303 // TODO: If the size is known, use it.
304 visitMemoryReference(I, MMI->getDest(), ~0u, MMI->getAlignment(), 0,
Dan Gohman13ec30b2010-05-28 17:44:00 +0000305 MemRef::Write);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000306 visitMemoryReference(I, MMI->getSource(), ~0u, MMI->getAlignment(), 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000307 MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000308 break;
309 }
310 case Intrinsic::memset: {
311 MemSetInst *MSI = cast<MemSetInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000312 // TODO: If the size is known, use it.
313 visitMemoryReference(I, MSI->getDest(), ~0u, MSI->getAlignment(), 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000314 MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000315 break;
316 }
317
318 case Intrinsic::vastart:
Dan Gohmanbe02b202010-04-09 01:39:53 +0000319 Assert1(I.getParent()->getParent()->isVarArg(),
320 "Undefined behavior: va_start called in a non-varargs function",
321 &I);
322
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000323 visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000324 MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000325 break;
326 case Intrinsic::vacopy:
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000327 visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0, MemRef::Write);
328 visitMemoryReference(I, CS.getArgument(1), ~0u, 0, 0, MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000329 break;
330 case Intrinsic::vaend:
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000331 visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000332 MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000333 break;
Dan Gohman882ddb42010-05-26 22:21:25 +0000334
335 case Intrinsic::stackrestore:
336 // Stackrestore doesn't read or write memory, but it sets the
337 // stack pointer, which the compiler may read from or write to
338 // at any time, so check it for both readability and writeability.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000339 visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0,
Dan Gohman882ddb42010-05-26 22:21:25 +0000340 MemRef::Read | MemRef::Write);
341 break;
Dan Gohman113902e2010-04-08 18:47:09 +0000342 }
343}
344
345void Lint::visitCallInst(CallInst &I) {
346 return visitCallSite(&I);
347}
348
349void Lint::visitInvokeInst(InvokeInst &I) {
350 return visitCallSite(&I);
351}
352
353void Lint::visitReturnInst(ReturnInst &I) {
354 Function *F = I.getParent()->getParent();
355 Assert1(!F->doesNotReturn(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000356 "Unusual: Return statement in function with noreturn attribute",
357 &I);
Dan Gohman292fc872010-05-28 04:33:42 +0000358
359 if (Value *V = I.getReturnValue()) {
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000360 Value *Obj = findValue(V, /*OffsetOk=*/true);
Dan Gohman078f8592010-05-28 16:34:49 +0000361 Assert1(!isa<AllocaInst>(Obj),
362 "Unusual: Returning alloca value", &I);
Dan Gohman292fc872010-05-28 04:33:42 +0000363 }
Dan Gohman113902e2010-04-08 18:47:09 +0000364}
365
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000366// TODO: Check that the reference is in bounds.
Dan Gohman0ce24992010-07-06 15:23:00 +0000367// TODO: Check readnone/readonly function attributes.
Dan Gohman113902e2010-04-08 18:47:09 +0000368void Lint::visitMemoryReference(Instruction &I,
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000369 Value *Ptr, unsigned Size, unsigned Align,
370 const Type *Ty, unsigned Flags) {
371 // If no memory is being referenced, it doesn't matter if the pointer
372 // is valid.
373 if (Size == 0)
374 return;
375
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000376 Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
Dan Gohmanbe02b202010-04-09 01:39:53 +0000377 Assert1(!isa<ConstantPointerNull>(UnderlyingObject),
378 "Undefined behavior: Null pointer dereference", &I);
379 Assert1(!isa<UndefValue>(UnderlyingObject),
380 "Undefined behavior: Undef pointer dereference", &I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000381 Assert1(!isa<ConstantInt>(UnderlyingObject) ||
382 !cast<ConstantInt>(UnderlyingObject)->isAllOnesValue(),
383 "Unusual: All-ones pointer dereference", &I);
384 Assert1(!isa<ConstantInt>(UnderlyingObject) ||
385 !cast<ConstantInt>(UnderlyingObject)->isOne(),
386 "Unusual: Address one pointer dereference", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000387
Dan Gohman5b61b382010-04-30 19:05:00 +0000388 if (Flags & MemRef::Write) {
389 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
390 Assert1(!GV->isConstant(),
391 "Undefined behavior: Write to read-only memory", &I);
392 Assert1(!isa<Function>(UnderlyingObject) &&
393 !isa<BlockAddress>(UnderlyingObject),
394 "Undefined behavior: Write to text section", &I);
395 }
396 if (Flags & MemRef::Read) {
397 Assert1(!isa<Function>(UnderlyingObject),
398 "Unusual: Load from function body", &I);
399 Assert1(!isa<BlockAddress>(UnderlyingObject),
400 "Undefined behavior: Load from block address", &I);
401 }
402 if (Flags & MemRef::Callee) {
403 Assert1(!isa<BlockAddress>(UnderlyingObject),
404 "Undefined behavior: Call to block address", &I);
405 }
406 if (Flags & MemRef::Branchee) {
407 Assert1(!isa<Constant>(UnderlyingObject) ||
408 isa<BlockAddress>(UnderlyingObject),
409 "Undefined behavior: Branch to non-blockaddress", &I);
410 }
411
Dan Gohman113902e2010-04-08 18:47:09 +0000412 if (TD) {
413 if (Align == 0 && Ty) Align = TD->getABITypeAlignment(Ty);
414
415 if (Align != 0) {
416 unsigned BitWidth = TD->getTypeSizeInBits(Ptr->getType());
417 APInt Mask = APInt::getAllOnesValue(BitWidth),
418 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
419 ComputeMaskedBits(Ptr, Mask, KnownZero, KnownOne, TD);
420 Assert1(!(KnownOne & APInt::getLowBitsSet(BitWidth, Log2_32(Align))),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000421 "Undefined behavior: Memory reference address is misaligned", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000422 }
423 }
424}
425
426void Lint::visitLoadInst(LoadInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000427 visitMemoryReference(I, I.getPointerOperand(),
428 AA->getTypeStoreSize(I.getType()), I.getAlignment(),
429 I.getType(), MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000430}
431
432void Lint::visitStoreInst(StoreInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000433 visitMemoryReference(I, I.getPointerOperand(),
434 AA->getTypeStoreSize(I.getOperand(0)->getType()),
435 I.getAlignment(),
436 I.getOperand(0)->getType(), MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000437}
438
Dan Gohmanbe02b202010-04-09 01:39:53 +0000439void Lint::visitXor(BinaryOperator &I) {
440 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
441 !isa<UndefValue>(I.getOperand(1)),
442 "Undefined result: xor(undef, undef)", &I);
443}
444
445void Lint::visitSub(BinaryOperator &I) {
446 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
447 !isa<UndefValue>(I.getOperand(1)),
448 "Undefined result: sub(undef, undef)", &I);
449}
450
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000451void Lint::visitLShr(BinaryOperator &I) {
452 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000453 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000454 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000455 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000456}
457
458void Lint::visitAShr(BinaryOperator &I) {
459 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000460 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000461 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000462 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000463}
464
465void Lint::visitShl(BinaryOperator &I) {
466 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000467 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000468 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000469 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000470}
471
Dan Gohman113902e2010-04-08 18:47:09 +0000472static bool isZero(Value *V, TargetData *TD) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000473 // Assume undef could be zero.
474 if (isa<UndefValue>(V)) return true;
475
Dan Gohman113902e2010-04-08 18:47:09 +0000476 unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
477 APInt Mask = APInt::getAllOnesValue(BitWidth),
478 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
479 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
480 return KnownZero.isAllOnesValue();
481}
482
483void Lint::visitSDiv(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000484 Assert1(!isZero(I.getOperand(1), TD),
485 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000486}
487
488void Lint::visitUDiv(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000489 Assert1(!isZero(I.getOperand(1), TD),
490 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000491}
492
493void Lint::visitSRem(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000494 Assert1(!isZero(I.getOperand(1), TD),
495 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000496}
497
498void Lint::visitURem(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000499 Assert1(!isZero(I.getOperand(1), TD),
500 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000501}
502
503void Lint::visitAllocaInst(AllocaInst &I) {
504 if (isa<ConstantInt>(I.getArraySize()))
505 // This isn't undefined behavior, it's just an obvious pessimization.
506 Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000507 "Pessimization: Static alloca outside of entry block", &I);
Dan Gohman0ce24992010-07-06 15:23:00 +0000508
509 // TODO: Check for an unusual size (MSB set?)
Dan Gohman113902e2010-04-08 18:47:09 +0000510}
511
512void Lint::visitVAArgInst(VAArgInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000513 visitMemoryReference(I, I.getOperand(0), ~0u, 0, 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000514 MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000515}
516
517void Lint::visitIndirectBrInst(IndirectBrInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000518 visitMemoryReference(I, I.getAddress(), ~0u, 0, 0, MemRef::Branchee);
Dan Gohman113902e2010-04-08 18:47:09 +0000519}
520
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000521void Lint::visitExtractElementInst(ExtractElementInst &I) {
522 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000523 dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
524 /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000525 Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000526 "Undefined result: extractelement index out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000527}
528
529void Lint::visitInsertElementInst(InsertElementInst &I) {
530 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000531 dyn_cast<ConstantInt>(findValue(I.getOperand(2),
532 /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000533 Assert1(CI->getValue().ult(I.getType()->getNumElements()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000534 "Undefined result: insertelement index out of range", &I);
535}
536
537void Lint::visitUnreachableInst(UnreachableInst &I) {
538 // This isn't undefined behavior, it's merely suspicious.
539 Assert1(&I == I.getParent()->begin() ||
540 prior(BasicBlock::iterator(&I))->mayHaveSideEffects(),
541 "Unusual: unreachable immediately preceded by instruction without "
542 "side effects", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000543}
544
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000545/// findValue - Look through bitcasts and simple memory reference patterns
546/// to identify an equivalent, but more informative, value. If OffsetOk
547/// is true, look through getelementptrs with non-zero offsets too.
548///
549/// Most analysis passes don't require this logic, because instcombine
550/// will simplify most of these kinds of things away. But it's a goal of
551/// this Lint pass to be useful even on non-optimized IR.
552Value *Lint::findValue(Value *V, bool OffsetOk) const {
Dan Gohman17d95962010-05-28 16:45:33 +0000553 SmallPtrSet<Value *, 4> Visited;
554 return findValueImpl(V, OffsetOk, Visited);
555}
556
557/// findValueImpl - Implementation helper for findValue.
558Value *Lint::findValueImpl(Value *V, bool OffsetOk,
559 SmallPtrSet<Value *, 4> &Visited) const {
560 // Detect self-referential values.
561 if (!Visited.insert(V))
562 return UndefValue::get(V->getType());
563
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000564 // TODO: Look through sext or zext cast, when the result is known to
565 // be interpreted as signed or unsigned, respectively.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000566 // TODO: Look through eliminable cast pairs.
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000567 // TODO: Look through calls with unique return values.
568 // TODO: Look through vector insert/extract/shuffle.
569 V = OffsetOk ? V->getUnderlyingObject() : V->stripPointerCasts();
570 if (LoadInst *L = dyn_cast<LoadInst>(V)) {
571 BasicBlock::iterator BBI = L;
572 BasicBlock *BB = L->getParent();
Dan Gohman13ec30b2010-05-28 17:44:00 +0000573 SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000574 for (;;) {
Dan Gohman13ec30b2010-05-28 17:44:00 +0000575 if (!VisitedBlocks.insert(BB)) break;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000576 if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(),
577 BB, BBI, 6, AA))
Dan Gohman17d95962010-05-28 16:45:33 +0000578 return findValueImpl(U, OffsetOk, Visited);
Dan Gohman13ec30b2010-05-28 17:44:00 +0000579 if (BBI != BB->begin()) break;
580 BB = BB->getUniquePredecessor();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000581 if (!BB) break;
582 BBI = BB->end();
583 }
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000584 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
585 if (Value *W = PN->hasConstantValue(DT))
586 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000587 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
588 if (CI->isNoopCast(TD ? TD->getIntPtrType(V->getContext()) :
589 Type::getInt64Ty(V->getContext())))
Dan Gohman17d95962010-05-28 16:45:33 +0000590 return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000591 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
592 if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
593 Ex->idx_begin(),
594 Ex->idx_end()))
595 if (W != V)
Dan Gohman17d95962010-05-28 16:45:33 +0000596 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000597 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
598 // Same as above, but for ConstantExpr instead of Instruction.
599 if (Instruction::isCast(CE->getOpcode())) {
600 if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
601 CE->getOperand(0)->getType(),
602 CE->getType(),
603 TD ? TD->getIntPtrType(V->getContext()) :
604 Type::getInt64Ty(V->getContext())))
605 return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
606 } else if (CE->getOpcode() == Instruction::ExtractValue) {
607 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
608 if (Value *W = FindInsertedValue(CE->getOperand(0),
609 Indices.begin(),
610 Indices.end()))
611 if (W != V)
612 return findValueImpl(W, OffsetOk, Visited);
613 }
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000614 }
615
616 // As a last resort, try SimplifyInstruction or constant folding.
617 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
618 if (Value *W = SimplifyInstruction(Inst, TD))
619 if (W != Inst)
Dan Gohman17d95962010-05-28 16:45:33 +0000620 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000621 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
622 if (Value *W = ConstantFoldConstantExpression(CE, TD))
623 if (W != V)
Dan Gohman17d95962010-05-28 16:45:33 +0000624 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000625 }
626
627 return V;
628}
629
Dan Gohman113902e2010-04-08 18:47:09 +0000630//===----------------------------------------------------------------------===//
631// Implement the public interfaces to this file...
632//===----------------------------------------------------------------------===//
633
634FunctionPass *llvm::createLintPass() {
635 return new Lint();
636}
637
638/// lintFunction - Check a function for errors, printing messages on stderr.
639///
640void llvm::lintFunction(const Function &f) {
641 Function &F = const_cast<Function&>(f);
642 assert(!F.isDeclaration() && "Cannot lint external functions");
643
644 FunctionPassManager FPM(F.getParent());
645 Lint *V = new Lint();
646 FPM.add(V);
647 FPM.run(F);
648}
649
650/// lintModule - Check a module for errors, printing messages on stderr.
Dan Gohman113902e2010-04-08 18:47:09 +0000651///
Dan Gohmana0f7ff32010-05-26 22:28:53 +0000652void llvm::lintModule(const Module &M) {
Dan Gohman113902e2010-04-08 18:47:09 +0000653 PassManager PM;
654 Lint *V = new Lint();
655 PM.add(V);
656 PM.run(const_cast<Module&>(M));
Dan Gohman113902e2010-04-08 18:47:09 +0000657}