blob: 6c137333d6daed1a1df7aaff7940c1b08193b785 [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);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +000071 void visitMemoryReference(Instruction &I, Value *Ptr,
72 unsigned Size, unsigned Align,
Dan Gohman5b61b382010-04-30 19:05:00 +000073 const Type *Ty, unsigned Flags);
Dan Gohman113902e2010-04-08 18:47:09 +000074
Dan Gohman113902e2010-04-08 18:47:09 +000075 void visitCallInst(CallInst &I);
76 void visitInvokeInst(InvokeInst &I);
77 void visitReturnInst(ReturnInst &I);
78 void visitLoadInst(LoadInst &I);
79 void visitStoreInst(StoreInst &I);
Dan Gohmanbe02b202010-04-09 01:39:53 +000080 void visitXor(BinaryOperator &I);
81 void visitSub(BinaryOperator &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +000082 void visitLShr(BinaryOperator &I);
83 void visitAShr(BinaryOperator &I);
84 void visitShl(BinaryOperator &I);
Dan Gohman113902e2010-04-08 18:47:09 +000085 void visitSDiv(BinaryOperator &I);
86 void visitUDiv(BinaryOperator &I);
87 void visitSRem(BinaryOperator &I);
88 void visitURem(BinaryOperator &I);
89 void visitAllocaInst(AllocaInst &I);
90 void visitVAArgInst(VAArgInst &I);
91 void visitIndirectBrInst(IndirectBrInst &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +000092 void visitExtractElementInst(ExtractElementInst &I);
93 void visitInsertElementInst(InsertElementInst &I);
Dan Gohmanbe02b202010-04-09 01:39:53 +000094 void visitUnreachableInst(UnreachableInst &I);
Dan Gohman113902e2010-04-08 18:47:09 +000095
Dan Gohmanff26d4e2010-05-28 16:21:24 +000096 Value *findValue(Value *V, bool OffsetOk) const;
Dan Gohman17d95962010-05-28 16:45:33 +000097 Value *findValueImpl(Value *V, bool OffsetOk,
98 SmallPtrSet<Value *, 4> &Visited) const;
Dan Gohmanff26d4e2010-05-28 16:21:24 +000099
Dan Gohman113902e2010-04-08 18:47:09 +0000100 public:
101 Module *Mod;
102 AliasAnalysis *AA;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000103 DominatorTree *DT;
Dan Gohman113902e2010-04-08 18:47:09 +0000104 TargetData *TD;
105
106 std::string Messages;
107 raw_string_ostream MessagesStr;
108
109 static char ID; // Pass identification, replacement for typeid
110 Lint() : FunctionPass(&ID), MessagesStr(Messages) {}
111
112 virtual bool runOnFunction(Function &F);
113
114 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
115 AU.setPreservesAll();
116 AU.addRequired<AliasAnalysis>();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000117 AU.addRequired<DominatorTree>();
Dan Gohman113902e2010-04-08 18:47:09 +0000118 }
119 virtual void print(raw_ostream &O, const Module *M) const {}
120
121 void WriteValue(const Value *V) {
122 if (!V) return;
123 if (isa<Instruction>(V)) {
124 MessagesStr << *V << '\n';
125 } else {
126 WriteAsOperand(MessagesStr, V, true, Mod);
127 MessagesStr << '\n';
128 }
129 }
130
131 void WriteType(const Type *T) {
132 if (!T) return;
133 MessagesStr << ' ';
134 WriteTypeSymbolic(MessagesStr, T, Mod);
135 }
136
137 // CheckFailed - A check failed, so print out the condition and the message
138 // that failed. This provides a nice place to put a breakpoint if you want
139 // to see why something is not correct.
140 void CheckFailed(const Twine &Message,
141 const Value *V1 = 0, const Value *V2 = 0,
142 const Value *V3 = 0, const Value *V4 = 0) {
143 MessagesStr << Message.str() << "\n";
144 WriteValue(V1);
145 WriteValue(V2);
146 WriteValue(V3);
147 WriteValue(V4);
148 }
149
150 void CheckFailed(const Twine &Message, const Value *V1,
151 const Type *T2, const Value *V3 = 0) {
152 MessagesStr << Message.str() << "\n";
153 WriteValue(V1);
154 WriteType(T2);
155 WriteValue(V3);
156 }
157
158 void CheckFailed(const Twine &Message, const Type *T1,
159 const Type *T2 = 0, const Type *T3 = 0) {
160 MessagesStr << Message.str() << "\n";
161 WriteType(T1);
162 WriteType(T2);
163 WriteType(T3);
164 }
165 };
166}
167
168char Lint::ID = 0;
169static RegisterPass<Lint>
170X("lint", "Statically lint-checks LLVM IR", false, true);
171
172// Assert - We know that cond should be true, if not print an error message.
173#define Assert(C, M) \
174 do { if (!(C)) { CheckFailed(M); return; } } while (0)
175#define Assert1(C, M, V1) \
176 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
177#define Assert2(C, M, V1, V2) \
178 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
179#define Assert3(C, M, V1, V2, V3) \
180 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
181#define Assert4(C, M, V1, V2, V3, V4) \
182 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
183
184// Lint::run - This is the main Analysis entry point for a
185// function.
186//
187bool Lint::runOnFunction(Function &F) {
188 Mod = F.getParent();
189 AA = &getAnalysis<AliasAnalysis>();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000190 DT = &getAnalysis<DominatorTree>();
Dan Gohman113902e2010-04-08 18:47:09 +0000191 TD = getAnalysisIfAvailable<TargetData>();
192 visit(F);
193 dbgs() << MessagesStr.str();
Dan Gohmana0f7ff32010-05-26 22:28:53 +0000194 Messages.clear();
Dan Gohman113902e2010-04-08 18:47:09 +0000195 return false;
196}
197
Dan Gohmanbe02b202010-04-09 01:39:53 +0000198void Lint::visitFunction(Function &F) {
199 // This isn't undefined behavior, it's just a little unusual, and it's a
200 // fairly common mistake to neglect to name a function.
201 Assert1(F.hasName() || F.hasLocalLinkage(),
202 "Unusual: Unnamed function with non-local linkage", &F);
Dan Gohman113902e2010-04-08 18:47:09 +0000203}
204
205void Lint::visitCallSite(CallSite CS) {
206 Instruction &I = *CS.getInstruction();
207 Value *Callee = CS.getCalledValue();
208
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000209 visitMemoryReference(I, Callee, ~0u, 0, 0, MemRef::Callee);
Dan Gohman113902e2010-04-08 18:47:09 +0000210
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000211 if (Function *F = dyn_cast<Function>(findValue(Callee, /*OffsetOk=*/false))) {
Dan Gohman113902e2010-04-08 18:47:09 +0000212 Assert1(CS.getCallingConv() == F->getCallingConv(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000213 "Undefined behavior: Caller and callee calling convention differ",
214 &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000215
216 const FunctionType *FT = F->getFunctionType();
217 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
218
219 Assert1(FT->isVarArg() ?
220 FT->getNumParams() <= NumActualArgs :
221 FT->getNumParams() == NumActualArgs,
Dan Gohmanbe02b202010-04-09 01:39:53 +0000222 "Undefined behavior: Call argument count mismatches callee "
223 "argument count", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000224
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000225 // Check argument types (in case the callee was casted) and attributes.
226 Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
227 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
228 for (; AI != AE; ++AI) {
229 Value *Actual = *AI;
230 if (PI != PE) {
231 Argument *Formal = PI++;
232 Assert1(Formal->getType() == Actual->getType(),
233 "Undefined behavior: Call argument type mismatches "
234 "callee parameter type", &I);
Dan Gohman10e77262010-06-01 20:51:40 +0000235
236 // Check that noalias arguments don't alias other arguments. The
237 // AliasAnalysis API isn't expressive enough for what we really want
238 // to do. Known partial overlap is not distinguished from the case
239 // where nothing is known.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000240 if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy())
Dan Gohman10e77262010-06-01 20:51:40 +0000241 for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI) {
242 Assert1(AI == BI ||
243 AA->alias(*AI, ~0u, *BI, ~0u) != AliasAnalysis::MustAlias,
244 "Unusual: noalias argument aliases another argument", &I);
245 }
246
247 // Check that an sret argument points to valid memory.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000248 if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
249 const Type *Ty =
250 cast<PointerType>(Formal->getType())->getElementType();
251 visitMemoryReference(I, Actual, AA->getTypeStoreSize(Ty),
252 TD ? TD->getABITypeAlignment(Ty) : 0,
253 Ty, MemRef::Read | MemRef::Write);
254 }
255 }
256 }
Dan Gohman113902e2010-04-08 18:47:09 +0000257 }
258
Dan Gohman113b3e22010-05-26 21:46:36 +0000259 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
260 for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
261 AI != AE; ++AI) {
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000262 Value *Obj = findValue(*AI, /*OffsetOk=*/true);
Dan Gohman078f8592010-05-28 16:34:49 +0000263 Assert1(!isa<AllocaInst>(Obj),
Dan Gohman113b3e22010-05-26 21:46:36 +0000264 "Undefined behavior: Call with \"tail\" keyword references "
Dan Gohman078f8592010-05-28 16:34:49 +0000265 "alloca", &I);
Dan Gohman113b3e22010-05-26 21:46:36 +0000266 }
267
Dan Gohman113902e2010-04-08 18:47:09 +0000268
269 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
270 switch (II->getIntrinsicID()) {
271 default: break;
272
273 // TODO: Check more intrinsics
274
275 case Intrinsic::memcpy: {
276 MemCpyInst *MCI = cast<MemCpyInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000277 // TODO: If the size is known, use it.
278 visitMemoryReference(I, MCI->getDest(), ~0u, MCI->getAlignment(), 0,
Dan Gohman13ec30b2010-05-28 17:44:00 +0000279 MemRef::Write);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000280 visitMemoryReference(I, MCI->getSource(), ~0u, MCI->getAlignment(), 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000281 MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000282
Dan Gohmanbe02b202010-04-09 01:39:53 +0000283 // Check that the memcpy arguments don't overlap. The AliasAnalysis API
284 // isn't expressive enough for what we really want to do. Known partial
285 // overlap is not distinguished from the case where nothing is known.
Dan Gohman113902e2010-04-08 18:47:09 +0000286 unsigned Size = 0;
287 if (const ConstantInt *Len =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000288 dyn_cast<ConstantInt>(findValue(MCI->getLength(),
289 /*OffsetOk=*/false)))
Dan Gohman113902e2010-04-08 18:47:09 +0000290 if (Len->getValue().isIntN(32))
291 Size = Len->getValue().getZExtValue();
292 Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
293 AliasAnalysis::MustAlias,
Dan Gohmanbe02b202010-04-09 01:39:53 +0000294 "Undefined behavior: memcpy source and destination overlap", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000295 break;
296 }
297 case Intrinsic::memmove: {
298 MemMoveInst *MMI = cast<MemMoveInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000299 // TODO: If the size is known, use it.
300 visitMemoryReference(I, MMI->getDest(), ~0u, MMI->getAlignment(), 0,
Dan Gohman13ec30b2010-05-28 17:44:00 +0000301 MemRef::Write);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000302 visitMemoryReference(I, MMI->getSource(), ~0u, MMI->getAlignment(), 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000303 MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000304 break;
305 }
306 case Intrinsic::memset: {
307 MemSetInst *MSI = cast<MemSetInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000308 // TODO: If the size is known, use it.
309 visitMemoryReference(I, MSI->getDest(), ~0u, MSI->getAlignment(), 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000310 MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000311 break;
312 }
313
314 case Intrinsic::vastart:
Dan Gohmanbe02b202010-04-09 01:39:53 +0000315 Assert1(I.getParent()->getParent()->isVarArg(),
316 "Undefined behavior: va_start called in a non-varargs function",
317 &I);
318
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000319 visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000320 MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000321 break;
322 case Intrinsic::vacopy:
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000323 visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0, MemRef::Write);
324 visitMemoryReference(I, CS.getArgument(1), ~0u, 0, 0, MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000325 break;
326 case Intrinsic::vaend:
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000327 visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000328 MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000329 break;
Dan Gohman882ddb42010-05-26 22:21:25 +0000330
331 case Intrinsic::stackrestore:
332 // Stackrestore doesn't read or write memory, but it sets the
333 // stack pointer, which the compiler may read from or write to
334 // at any time, so check it for both readability and writeability.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000335 visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0,
Dan Gohman882ddb42010-05-26 22:21:25 +0000336 MemRef::Read | MemRef::Write);
337 break;
Dan Gohman113902e2010-04-08 18:47:09 +0000338 }
339}
340
341void Lint::visitCallInst(CallInst &I) {
342 return visitCallSite(&I);
343}
344
345void Lint::visitInvokeInst(InvokeInst &I) {
346 return visitCallSite(&I);
347}
348
349void Lint::visitReturnInst(ReturnInst &I) {
350 Function *F = I.getParent()->getParent();
351 Assert1(!F->doesNotReturn(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000352 "Unusual: Return statement in function with noreturn attribute",
353 &I);
Dan Gohman292fc872010-05-28 04:33:42 +0000354
355 if (Value *V = I.getReturnValue()) {
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000356 Value *Obj = findValue(V, /*OffsetOk=*/true);
Dan Gohman078f8592010-05-28 16:34:49 +0000357 Assert1(!isa<AllocaInst>(Obj),
358 "Unusual: Returning alloca value", &I);
Dan Gohman292fc872010-05-28 04:33:42 +0000359 }
Dan Gohman113902e2010-04-08 18:47:09 +0000360}
361
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000362// TODO: Check that the reference is in bounds.
Dan Gohman113902e2010-04-08 18:47:09 +0000363void Lint::visitMemoryReference(Instruction &I,
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000364 Value *Ptr, unsigned Size, unsigned Align,
365 const Type *Ty, unsigned Flags) {
366 // If no memory is being referenced, it doesn't matter if the pointer
367 // is valid.
368 if (Size == 0)
369 return;
370
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000371 Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
Dan Gohmanbe02b202010-04-09 01:39:53 +0000372 Assert1(!isa<ConstantPointerNull>(UnderlyingObject),
373 "Undefined behavior: Null pointer dereference", &I);
374 Assert1(!isa<UndefValue>(UnderlyingObject),
375 "Undefined behavior: Undef pointer dereference", &I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000376 Assert1(!isa<ConstantInt>(UnderlyingObject) ||
377 !cast<ConstantInt>(UnderlyingObject)->isAllOnesValue(),
378 "Unusual: All-ones pointer dereference", &I);
379 Assert1(!isa<ConstantInt>(UnderlyingObject) ||
380 !cast<ConstantInt>(UnderlyingObject)->isOne(),
381 "Unusual: Address one pointer dereference", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000382
Dan Gohman5b61b382010-04-30 19:05:00 +0000383 if (Flags & MemRef::Write) {
384 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
385 Assert1(!GV->isConstant(),
386 "Undefined behavior: Write to read-only memory", &I);
387 Assert1(!isa<Function>(UnderlyingObject) &&
388 !isa<BlockAddress>(UnderlyingObject),
389 "Undefined behavior: Write to text section", &I);
390 }
391 if (Flags & MemRef::Read) {
392 Assert1(!isa<Function>(UnderlyingObject),
393 "Unusual: Load from function body", &I);
394 Assert1(!isa<BlockAddress>(UnderlyingObject),
395 "Undefined behavior: Load from block address", &I);
396 }
397 if (Flags & MemRef::Callee) {
398 Assert1(!isa<BlockAddress>(UnderlyingObject),
399 "Undefined behavior: Call to block address", &I);
400 }
401 if (Flags & MemRef::Branchee) {
402 Assert1(!isa<Constant>(UnderlyingObject) ||
403 isa<BlockAddress>(UnderlyingObject),
404 "Undefined behavior: Branch to non-blockaddress", &I);
405 }
406
Dan Gohman113902e2010-04-08 18:47:09 +0000407 if (TD) {
408 if (Align == 0 && Ty) Align = TD->getABITypeAlignment(Ty);
409
410 if (Align != 0) {
411 unsigned BitWidth = TD->getTypeSizeInBits(Ptr->getType());
412 APInt Mask = APInt::getAllOnesValue(BitWidth),
413 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
414 ComputeMaskedBits(Ptr, Mask, KnownZero, KnownOne, TD);
415 Assert1(!(KnownOne & APInt::getLowBitsSet(BitWidth, Log2_32(Align))),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000416 "Undefined behavior: Memory reference address is misaligned", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000417 }
418 }
419}
420
421void Lint::visitLoadInst(LoadInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000422 visitMemoryReference(I, I.getPointerOperand(),
423 AA->getTypeStoreSize(I.getType()), I.getAlignment(),
424 I.getType(), MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000425}
426
427void Lint::visitStoreInst(StoreInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000428 visitMemoryReference(I, I.getPointerOperand(),
429 AA->getTypeStoreSize(I.getOperand(0)->getType()),
430 I.getAlignment(),
431 I.getOperand(0)->getType(), MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000432}
433
Dan Gohmanbe02b202010-04-09 01:39:53 +0000434void Lint::visitXor(BinaryOperator &I) {
435 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
436 !isa<UndefValue>(I.getOperand(1)),
437 "Undefined result: xor(undef, undef)", &I);
438}
439
440void Lint::visitSub(BinaryOperator &I) {
441 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
442 !isa<UndefValue>(I.getOperand(1)),
443 "Undefined result: sub(undef, undef)", &I);
444}
445
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000446void Lint::visitLShr(BinaryOperator &I) {
447 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000448 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000449 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000450 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000451}
452
453void Lint::visitAShr(BinaryOperator &I) {
454 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000455 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000456 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000457 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000458}
459
460void Lint::visitShl(BinaryOperator &I) {
461 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000462 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000463 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000464 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000465}
466
Dan Gohman113902e2010-04-08 18:47:09 +0000467static bool isZero(Value *V, TargetData *TD) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000468 // Assume undef could be zero.
469 if (isa<UndefValue>(V)) return true;
470
Dan Gohman113902e2010-04-08 18:47:09 +0000471 unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
472 APInt Mask = APInt::getAllOnesValue(BitWidth),
473 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
474 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
475 return KnownZero.isAllOnesValue();
476}
477
478void Lint::visitSDiv(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000479 Assert1(!isZero(I.getOperand(1), TD),
480 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000481}
482
483void Lint::visitUDiv(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::visitSRem(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::visitURem(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::visitAllocaInst(AllocaInst &I) {
499 if (isa<ConstantInt>(I.getArraySize()))
500 // This isn't undefined behavior, it's just an obvious pessimization.
501 Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000502 "Pessimization: Static alloca outside of entry block", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000503}
504
505void Lint::visitVAArgInst(VAArgInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000506 visitMemoryReference(I, I.getOperand(0), ~0u, 0, 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000507 MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000508}
509
510void Lint::visitIndirectBrInst(IndirectBrInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000511 visitMemoryReference(I, I.getAddress(), ~0u, 0, 0, MemRef::Branchee);
Dan Gohman113902e2010-04-08 18:47:09 +0000512}
513
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000514void Lint::visitExtractElementInst(ExtractElementInst &I) {
515 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000516 dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
517 /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000518 Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000519 "Undefined result: extractelement index out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000520}
521
522void Lint::visitInsertElementInst(InsertElementInst &I) {
523 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000524 dyn_cast<ConstantInt>(findValue(I.getOperand(2),
525 /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000526 Assert1(CI->getValue().ult(I.getType()->getNumElements()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000527 "Undefined result: insertelement index out of range", &I);
528}
529
530void Lint::visitUnreachableInst(UnreachableInst &I) {
531 // This isn't undefined behavior, it's merely suspicious.
532 Assert1(&I == I.getParent()->begin() ||
533 prior(BasicBlock::iterator(&I))->mayHaveSideEffects(),
534 "Unusual: unreachable immediately preceded by instruction without "
535 "side effects", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000536}
537
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000538/// findValue - Look through bitcasts and simple memory reference patterns
539/// to identify an equivalent, but more informative, value. If OffsetOk
540/// is true, look through getelementptrs with non-zero offsets too.
541///
542/// Most analysis passes don't require this logic, because instcombine
543/// will simplify most of these kinds of things away. But it's a goal of
544/// this Lint pass to be useful even on non-optimized IR.
545Value *Lint::findValue(Value *V, bool OffsetOk) const {
Dan Gohman17d95962010-05-28 16:45:33 +0000546 SmallPtrSet<Value *, 4> Visited;
547 return findValueImpl(V, OffsetOk, Visited);
548}
549
550/// findValueImpl - Implementation helper for findValue.
551Value *Lint::findValueImpl(Value *V, bool OffsetOk,
552 SmallPtrSet<Value *, 4> &Visited) const {
553 // Detect self-referential values.
554 if (!Visited.insert(V))
555 return UndefValue::get(V->getType());
556
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000557 // TODO: Look through sext or zext cast, when the result is known to
558 // be interpreted as signed or unsigned, respectively.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000559 // TODO: Look through eliminable cast pairs.
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000560 // TODO: Look through calls with unique return values.
561 // TODO: Look through vector insert/extract/shuffle.
562 V = OffsetOk ? V->getUnderlyingObject() : V->stripPointerCasts();
563 if (LoadInst *L = dyn_cast<LoadInst>(V)) {
564 BasicBlock::iterator BBI = L;
565 BasicBlock *BB = L->getParent();
Dan Gohman13ec30b2010-05-28 17:44:00 +0000566 SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000567 for (;;) {
Dan Gohman13ec30b2010-05-28 17:44:00 +0000568 if (!VisitedBlocks.insert(BB)) break;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000569 if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(),
570 BB, BBI, 6, AA))
Dan Gohman17d95962010-05-28 16:45:33 +0000571 return findValueImpl(U, OffsetOk, Visited);
Dan Gohman13ec30b2010-05-28 17:44:00 +0000572 if (BBI != BB->begin()) break;
573 BB = BB->getUniquePredecessor();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000574 if (!BB) break;
575 BBI = BB->end();
576 }
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000577 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
578 if (Value *W = PN->hasConstantValue(DT))
579 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000580 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
581 if (CI->isNoopCast(TD ? TD->getIntPtrType(V->getContext()) :
582 Type::getInt64Ty(V->getContext())))
Dan Gohman17d95962010-05-28 16:45:33 +0000583 return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000584 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
585 if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
586 Ex->idx_begin(),
587 Ex->idx_end()))
588 if (W != V)
Dan Gohman17d95962010-05-28 16:45:33 +0000589 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000590 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
591 // Same as above, but for ConstantExpr instead of Instruction.
592 if (Instruction::isCast(CE->getOpcode())) {
593 if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
594 CE->getOperand(0)->getType(),
595 CE->getType(),
596 TD ? TD->getIntPtrType(V->getContext()) :
597 Type::getInt64Ty(V->getContext())))
598 return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
599 } else if (CE->getOpcode() == Instruction::ExtractValue) {
600 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
601 if (Value *W = FindInsertedValue(CE->getOperand(0),
602 Indices.begin(),
603 Indices.end()))
604 if (W != V)
605 return findValueImpl(W, OffsetOk, Visited);
606 }
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000607 }
608
609 // As a last resort, try SimplifyInstruction or constant folding.
610 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
611 if (Value *W = SimplifyInstruction(Inst, TD))
612 if (W != Inst)
Dan Gohman17d95962010-05-28 16:45:33 +0000613 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000614 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
615 if (Value *W = ConstantFoldConstantExpression(CE, TD))
616 if (W != V)
Dan Gohman17d95962010-05-28 16:45:33 +0000617 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000618 }
619
620 return V;
621}
622
Dan Gohman113902e2010-04-08 18:47:09 +0000623//===----------------------------------------------------------------------===//
624// Implement the public interfaces to this file...
625//===----------------------------------------------------------------------===//
626
627FunctionPass *llvm::createLintPass() {
628 return new Lint();
629}
630
631/// lintFunction - Check a function for errors, printing messages on stderr.
632///
633void llvm::lintFunction(const Function &f) {
634 Function &F = const_cast<Function&>(f);
635 assert(!F.isDeclaration() && "Cannot lint external functions");
636
637 FunctionPassManager FPM(F.getParent());
638 Lint *V = new Lint();
639 FPM.add(V);
640 FPM.run(F);
641}
642
643/// lintModule - Check a module for errors, printing messages on stderr.
Dan Gohman113902e2010-04-08 18:47:09 +0000644///
Dan Gohmana0f7ff32010-05-26 22:28:53 +0000645void llvm::lintModule(const Module &M) {
Dan Gohman113902e2010-04-08 18:47:09 +0000646 PassManager PM;
647 Lint *V = new Lint();
648 PM.add(V);
649 PM.run(const_cast<Module&>(M));
Dan Gohman113902e2010-04-08 18:47:09 +0000650}