blob: 270aa457f1709efe4fbb6bba8e9f15eb6d12152e [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,
Dan Gohman3da848b2010-10-19 22:54:46 +000073 uint64_t 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
Owen Anderson081c34b2010-10-19 17:21:58 +0000111 Lint() : FunctionPass(ID), MessagesStr(Messages) {
112 initializeLintPass(*PassRegistry::getPassRegistry());
113 }
Dan Gohman113902e2010-04-08 18:47:09 +0000114
115 virtual bool runOnFunction(Function &F);
116
117 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
118 AU.setPreservesAll();
119 AU.addRequired<AliasAnalysis>();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000120 AU.addRequired<DominatorTree>();
Dan Gohman113902e2010-04-08 18:47:09 +0000121 }
122 virtual void print(raw_ostream &O, const Module *M) const {}
123
124 void WriteValue(const Value *V) {
125 if (!V) return;
126 if (isa<Instruction>(V)) {
127 MessagesStr << *V << '\n';
128 } else {
129 WriteAsOperand(MessagesStr, V, true, Mod);
130 MessagesStr << '\n';
131 }
132 }
133
Dan Gohman113902e2010-04-08 18:47:09 +0000134 // 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 }
Dan Gohman113902e2010-04-08 18:47:09 +0000146 };
147}
148
149char Lint::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000150INITIALIZE_PASS_BEGIN(Lint, "lint", "Statically lint-checks LLVM IR",
151 false, true)
152INITIALIZE_PASS_DEPENDENCY(DominatorTree)
153INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
154INITIALIZE_PASS_END(Lint, "lint", "Statically lint-checks LLVM IR",
155 false, true)
Dan Gohman113902e2010-04-08 18:47:09 +0000156
157// Assert - We know that cond should be true, if not print an error message.
158#define Assert(C, M) \
159 do { if (!(C)) { CheckFailed(M); return; } } while (0)
160#define Assert1(C, M, V1) \
161 do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
162#define Assert2(C, M, V1, V2) \
163 do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
164#define Assert3(C, M, V1, V2, V3) \
165 do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
166#define Assert4(C, M, V1, V2, V3, V4) \
167 do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
168
169// Lint::run - This is the main Analysis entry point for a
170// function.
171//
172bool Lint::runOnFunction(Function &F) {
173 Mod = F.getParent();
174 AA = &getAnalysis<AliasAnalysis>();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000175 DT = &getAnalysis<DominatorTree>();
Dan Gohman113902e2010-04-08 18:47:09 +0000176 TD = getAnalysisIfAvailable<TargetData>();
177 visit(F);
178 dbgs() << MessagesStr.str();
Dan Gohmana0f7ff32010-05-26 22:28:53 +0000179 Messages.clear();
Dan Gohman113902e2010-04-08 18:47:09 +0000180 return false;
181}
182
Dan Gohmanbe02b202010-04-09 01:39:53 +0000183void Lint::visitFunction(Function &F) {
184 // This isn't undefined behavior, it's just a little unusual, and it's a
185 // fairly common mistake to neglect to name a function.
186 Assert1(F.hasName() || F.hasLocalLinkage(),
187 "Unusual: Unnamed function with non-local linkage", &F);
Dan Gohman0ce24992010-07-06 15:23:00 +0000188
189 // TODO: Check for irreducible control flow.
Dan Gohman113902e2010-04-08 18:47:09 +0000190}
191
192void Lint::visitCallSite(CallSite CS) {
193 Instruction &I = *CS.getInstruction();
194 Value *Callee = CS.getCalledValue();
195
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000196 visitMemoryReference(I, Callee, AliasAnalysis::UnknownSize,
197 0, 0, MemRef::Callee);
Dan Gohman113902e2010-04-08 18:47:09 +0000198
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000199 if (Function *F = dyn_cast<Function>(findValue(Callee, /*OffsetOk=*/false))) {
Dan Gohman113902e2010-04-08 18:47:09 +0000200 Assert1(CS.getCallingConv() == F->getCallingConv(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000201 "Undefined behavior: Caller and callee calling convention differ",
202 &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000203
204 const FunctionType *FT = F->getFunctionType();
205 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
206
207 Assert1(FT->isVarArg() ?
208 FT->getNumParams() <= NumActualArgs :
209 FT->getNumParams() == NumActualArgs,
Dan Gohmanbe02b202010-04-09 01:39:53 +0000210 "Undefined behavior: Call argument count mismatches callee "
211 "argument count", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000212
Dan Gohman545d0062010-07-12 18:02:04 +0000213 Assert1(FT->getReturnType() == I.getType(),
214 "Undefined behavior: Call return type mismatches "
215 "callee return type", &I);
216
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000217 // Check argument types (in case the callee was casted) and attributes.
Dan Gohman0ce24992010-07-06 15:23:00 +0000218 // TODO: Verify that caller and callee attributes are compatible.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000219 Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
220 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
221 for (; AI != AE; ++AI) {
222 Value *Actual = *AI;
223 if (PI != PE) {
224 Argument *Formal = PI++;
225 Assert1(Formal->getType() == Actual->getType(),
226 "Undefined behavior: Call argument type mismatches "
227 "callee parameter type", &I);
Dan Gohman10e77262010-06-01 20:51:40 +0000228
229 // Check that noalias arguments don't alias other arguments. The
230 // AliasAnalysis API isn't expressive enough for what we really want
231 // to do. Known partial overlap is not distinguished from the case
232 // where nothing is known.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000233 if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy())
Dan Gohmanf3b8c762010-11-11 19:23:51 +0000234 for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI)
Dan Gohman4a2a3ea2010-12-10 20:04:06 +0000235 if (AI != BI && (*BI)->getType()->isPointerTy()) {
236 AliasAnalysis::AliasResult Result = AA->alias(*AI, *BI);
237 Assert1(Result != AliasAnalysis::MustAlias &&
238 Result != AliasAnalysis::PartialAlias,
239 "Unusual: noalias argument aliases another argument", &I);
240 }
Dan Gohman10e77262010-06-01 20:51:40 +0000241
242 // Check that an sret argument points to valid memory.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000243 if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
244 const Type *Ty =
245 cast<PointerType>(Formal->getType())->getElementType();
246 visitMemoryReference(I, Actual, AA->getTypeStoreSize(Ty),
247 TD ? TD->getABITypeAlignment(Ty) : 0,
248 Ty, MemRef::Read | MemRef::Write);
249 }
250 }
251 }
Dan Gohman113902e2010-04-08 18:47:09 +0000252 }
253
Dan Gohman113b3e22010-05-26 21:46:36 +0000254 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
255 for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
256 AI != AE; ++AI) {
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000257 Value *Obj = findValue(*AI, /*OffsetOk=*/true);
Dan Gohman078f8592010-05-28 16:34:49 +0000258 Assert1(!isa<AllocaInst>(Obj),
Dan Gohman113b3e22010-05-26 21:46:36 +0000259 "Undefined behavior: Call with \"tail\" keyword references "
Dan Gohman078f8592010-05-28 16:34:49 +0000260 "alloca", &I);
Dan Gohman113b3e22010-05-26 21:46:36 +0000261 }
262
Dan Gohman113902e2010-04-08 18:47:09 +0000263
264 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
265 switch (II->getIntrinsicID()) {
266 default: break;
267
268 // TODO: Check more intrinsics
269
270 case Intrinsic::memcpy: {
271 MemCpyInst *MCI = cast<MemCpyInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000272 // TODO: If the size is known, use it.
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000273 visitMemoryReference(I, MCI->getDest(), AliasAnalysis::UnknownSize,
274 MCI->getAlignment(), 0,
Dan Gohman13ec30b2010-05-28 17:44:00 +0000275 MemRef::Write);
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000276 visitMemoryReference(I, MCI->getSource(), AliasAnalysis::UnknownSize,
277 MCI->getAlignment(), 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000278 MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000279
Dan Gohmanbe02b202010-04-09 01:39:53 +0000280 // Check that the memcpy arguments don't overlap. The AliasAnalysis API
281 // isn't expressive enough for what we really want to do. Known partial
282 // overlap is not distinguished from the case where nothing is known.
Dan Gohman3da848b2010-10-19 22:54:46 +0000283 uint64_t Size = 0;
Dan Gohman113902e2010-04-08 18:47:09 +0000284 if (const ConstantInt *Len =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000285 dyn_cast<ConstantInt>(findValue(MCI->getLength(),
286 /*OffsetOk=*/false)))
Dan Gohman113902e2010-04-08 18:47:09 +0000287 if (Len->getValue().isIntN(32))
288 Size = Len->getValue().getZExtValue();
289 Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
290 AliasAnalysis::MustAlias,
Dan Gohmanbe02b202010-04-09 01:39:53 +0000291 "Undefined behavior: memcpy source and destination overlap", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000292 break;
293 }
294 case Intrinsic::memmove: {
295 MemMoveInst *MMI = cast<MemMoveInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000296 // TODO: If the size is known, use it.
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000297 visitMemoryReference(I, MMI->getDest(), AliasAnalysis::UnknownSize,
298 MMI->getAlignment(), 0,
Dan Gohman13ec30b2010-05-28 17:44:00 +0000299 MemRef::Write);
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000300 visitMemoryReference(I, MMI->getSource(), AliasAnalysis::UnknownSize,
301 MMI->getAlignment(), 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000302 MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000303 break;
304 }
305 case Intrinsic::memset: {
306 MemSetInst *MSI = cast<MemSetInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000307 // TODO: If the size is known, use it.
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000308 visitMemoryReference(I, MSI->getDest(), AliasAnalysis::UnknownSize,
309 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 Gohmanf3a925d2010-10-19 17:06:23 +0000319 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
320 0, 0, MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000321 break;
322 case Intrinsic::vacopy:
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000323 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
324 0, 0, MemRef::Write);
325 visitMemoryReference(I, CS.getArgument(1), AliasAnalysis::UnknownSize,
326 0, 0, MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000327 break;
328 case Intrinsic::vaend:
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000329 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
330 0, 0, MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000331 break;
Dan Gohman882ddb42010-05-26 22:21:25 +0000332
333 case Intrinsic::stackrestore:
334 // Stackrestore doesn't read or write memory, but it sets the
335 // stack pointer, which the compiler may read from or write to
336 // at any time, so check it for both readability and writeability.
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000337 visitMemoryReference(I, CS.getArgument(0), AliasAnalysis::UnknownSize,
338 0, 0, MemRef::Read | MemRef::Write);
Dan Gohman882ddb42010-05-26 22:21:25 +0000339 break;
Dan Gohman113902e2010-04-08 18:47:09 +0000340 }
341}
342
343void Lint::visitCallInst(CallInst &I) {
344 return visitCallSite(&I);
345}
346
347void Lint::visitInvokeInst(InvokeInst &I) {
348 return visitCallSite(&I);
349}
350
351void Lint::visitReturnInst(ReturnInst &I) {
352 Function *F = I.getParent()->getParent();
353 Assert1(!F->doesNotReturn(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000354 "Unusual: Return statement in function with noreturn attribute",
355 &I);
Dan Gohman292fc872010-05-28 04:33:42 +0000356
357 if (Value *V = I.getReturnValue()) {
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000358 Value *Obj = findValue(V, /*OffsetOk=*/true);
Dan Gohman078f8592010-05-28 16:34:49 +0000359 Assert1(!isa<AllocaInst>(Obj),
360 "Unusual: Returning alloca value", &I);
Dan Gohman292fc872010-05-28 04:33:42 +0000361 }
Dan Gohman113902e2010-04-08 18:47:09 +0000362}
363
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000364// TODO: Check that the reference is in bounds.
Dan Gohman0ce24992010-07-06 15:23:00 +0000365// TODO: Check readnone/readonly function attributes.
Dan Gohman113902e2010-04-08 18:47:09 +0000366void Lint::visitMemoryReference(Instruction &I,
Dan Gohman3da848b2010-10-19 22:54:46 +0000367 Value *Ptr, uint64_t Size, unsigned Align,
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000368 const Type *Ty, unsigned Flags) {
369 // If no memory is being referenced, it doesn't matter if the pointer
370 // is valid.
371 if (Size == 0)
372 return;
373
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000374 Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
Dan Gohmanbe02b202010-04-09 01:39:53 +0000375 Assert1(!isa<ConstantPointerNull>(UnderlyingObject),
376 "Undefined behavior: Null pointer dereference", &I);
377 Assert1(!isa<UndefValue>(UnderlyingObject),
378 "Undefined behavior: Undef pointer dereference", &I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000379 Assert1(!isa<ConstantInt>(UnderlyingObject) ||
380 !cast<ConstantInt>(UnderlyingObject)->isAllOnesValue(),
381 "Unusual: All-ones pointer dereference", &I);
382 Assert1(!isa<ConstantInt>(UnderlyingObject) ||
383 !cast<ConstantInt>(UnderlyingObject)->isOne(),
384 "Unusual: Address one pointer dereference", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000385
Dan Gohman5b61b382010-04-30 19:05:00 +0000386 if (Flags & MemRef::Write) {
387 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
388 Assert1(!GV->isConstant(),
389 "Undefined behavior: Write to read-only memory", &I);
390 Assert1(!isa<Function>(UnderlyingObject) &&
391 !isa<BlockAddress>(UnderlyingObject),
392 "Undefined behavior: Write to text section", &I);
393 }
394 if (Flags & MemRef::Read) {
395 Assert1(!isa<Function>(UnderlyingObject),
396 "Unusual: Load from function body", &I);
397 Assert1(!isa<BlockAddress>(UnderlyingObject),
398 "Undefined behavior: Load from block address", &I);
399 }
400 if (Flags & MemRef::Callee) {
401 Assert1(!isa<BlockAddress>(UnderlyingObject),
402 "Undefined behavior: Call to block address", &I);
403 }
404 if (Flags & MemRef::Branchee) {
405 Assert1(!isa<Constant>(UnderlyingObject) ||
406 isa<BlockAddress>(UnderlyingObject),
407 "Undefined behavior: Branch to non-blockaddress", &I);
408 }
409
Dan Gohman113902e2010-04-08 18:47:09 +0000410 if (TD) {
411 if (Align == 0 && Ty) Align = TD->getABITypeAlignment(Ty);
412
413 if (Align != 0) {
414 unsigned BitWidth = TD->getTypeSizeInBits(Ptr->getType());
415 APInt Mask = APInt::getAllOnesValue(BitWidth),
416 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
417 ComputeMaskedBits(Ptr, Mask, KnownZero, KnownOne, TD);
418 Assert1(!(KnownOne & APInt::getLowBitsSet(BitWidth, Log2_32(Align))),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000419 "Undefined behavior: Memory reference address is misaligned", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000420 }
421 }
422}
423
424void Lint::visitLoadInst(LoadInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000425 visitMemoryReference(I, I.getPointerOperand(),
426 AA->getTypeStoreSize(I.getType()), I.getAlignment(),
427 I.getType(), MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000428}
429
430void Lint::visitStoreInst(StoreInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000431 visitMemoryReference(I, I.getPointerOperand(),
432 AA->getTypeStoreSize(I.getOperand(0)->getType()),
433 I.getAlignment(),
434 I.getOperand(0)->getType(), MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000435}
436
Dan Gohmanbe02b202010-04-09 01:39:53 +0000437void Lint::visitXor(BinaryOperator &I) {
438 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
439 !isa<UndefValue>(I.getOperand(1)),
440 "Undefined result: xor(undef, undef)", &I);
441}
442
443void Lint::visitSub(BinaryOperator &I) {
444 Assert1(!isa<UndefValue>(I.getOperand(0)) ||
445 !isa<UndefValue>(I.getOperand(1)),
446 "Undefined result: sub(undef, undef)", &I);
447}
448
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000449void Lint::visitLShr(BinaryOperator &I) {
450 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000451 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000452 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000453 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000454}
455
456void Lint::visitAShr(BinaryOperator &I) {
457 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000458 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000459 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000460 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000461}
462
463void Lint::visitShl(BinaryOperator &I) {
464 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000465 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000466 Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000467 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000468}
469
Dan Gohman113902e2010-04-08 18:47:09 +0000470static bool isZero(Value *V, TargetData *TD) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000471 // Assume undef could be zero.
472 if (isa<UndefValue>(V)) return true;
473
Dan Gohman113902e2010-04-08 18:47:09 +0000474 unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
475 APInt Mask = APInt::getAllOnesValue(BitWidth),
476 KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
477 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
478 return KnownZero.isAllOnesValue();
479}
480
481void Lint::visitSDiv(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000482 Assert1(!isZero(I.getOperand(1), TD),
483 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000484}
485
486void Lint::visitUDiv(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000487 Assert1(!isZero(I.getOperand(1), TD),
488 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000489}
490
491void Lint::visitSRem(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000492 Assert1(!isZero(I.getOperand(1), TD),
493 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000494}
495
496void Lint::visitURem(BinaryOperator &I) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000497 Assert1(!isZero(I.getOperand(1), TD),
498 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000499}
500
501void Lint::visitAllocaInst(AllocaInst &I) {
502 if (isa<ConstantInt>(I.getArraySize()))
503 // This isn't undefined behavior, it's just an obvious pessimization.
504 Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000505 "Pessimization: Static alloca outside of entry block", &I);
Dan Gohman0ce24992010-07-06 15:23:00 +0000506
507 // TODO: Check for an unusual size (MSB set?)
Dan Gohman113902e2010-04-08 18:47:09 +0000508}
509
510void Lint::visitVAArgInst(VAArgInst &I) {
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000511 visitMemoryReference(I, I.getOperand(0), AliasAnalysis::UnknownSize, 0, 0,
Dan Gohman5b61b382010-04-30 19:05:00 +0000512 MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000513}
514
515void Lint::visitIndirectBrInst(IndirectBrInst &I) {
Dan Gohmanf3a925d2010-10-19 17:06:23 +0000516 visitMemoryReference(I, I.getAddress(), AliasAnalysis::UnknownSize, 0, 0,
517 MemRef::Branchee);
Dan Gohmana8afb2a2010-08-02 23:06:43 +0000518
519 Assert1(I.getNumDestinations() != 0,
520 "Undefined behavior: indirectbr with no destinations", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000521}
522
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000523void Lint::visitExtractElementInst(ExtractElementInst &I) {
524 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000525 dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
526 /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000527 Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000528 "Undefined result: extractelement index out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000529}
530
531void Lint::visitInsertElementInst(InsertElementInst &I) {
532 if (ConstantInt *CI =
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000533 dyn_cast<ConstantInt>(findValue(I.getOperand(2),
534 /*OffsetOk=*/false)))
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000535 Assert1(CI->getValue().ult(I.getType()->getNumElements()),
Dan Gohmanbe02b202010-04-09 01:39:53 +0000536 "Undefined result: insertelement index out of range", &I);
537}
538
539void Lint::visitUnreachableInst(UnreachableInst &I) {
540 // This isn't undefined behavior, it's merely suspicious.
541 Assert1(&I == I.getParent()->begin() ||
542 prior(BasicBlock::iterator(&I))->mayHaveSideEffects(),
543 "Unusual: unreachable immediately preceded by instruction without "
544 "side effects", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000545}
546
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000547/// findValue - Look through bitcasts and simple memory reference patterns
548/// to identify an equivalent, but more informative, value. If OffsetOk
549/// is true, look through getelementptrs with non-zero offsets too.
550///
551/// Most analysis passes don't require this logic, because instcombine
552/// will simplify most of these kinds of things away. But it's a goal of
553/// this Lint pass to be useful even on non-optimized IR.
554Value *Lint::findValue(Value *V, bool OffsetOk) const {
Dan Gohman17d95962010-05-28 16:45:33 +0000555 SmallPtrSet<Value *, 4> Visited;
556 return findValueImpl(V, OffsetOk, Visited);
557}
558
559/// findValueImpl - Implementation helper for findValue.
560Value *Lint::findValueImpl(Value *V, bool OffsetOk,
561 SmallPtrSet<Value *, 4> &Visited) const {
562 // Detect self-referential values.
563 if (!Visited.insert(V))
564 return UndefValue::get(V->getType());
565
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000566 // TODO: Look through sext or zext cast, when the result is known to
567 // be interpreted as signed or unsigned, respectively.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000568 // TODO: Look through eliminable cast pairs.
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000569 // TODO: Look through calls with unique return values.
570 // TODO: Look through vector insert/extract/shuffle.
571 V = OffsetOk ? V->getUnderlyingObject() : V->stripPointerCasts();
572 if (LoadInst *L = dyn_cast<LoadInst>(V)) {
573 BasicBlock::iterator BBI = L;
574 BasicBlock *BB = L->getParent();
Dan Gohman13ec30b2010-05-28 17:44:00 +0000575 SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000576 for (;;) {
Dan Gohman13ec30b2010-05-28 17:44:00 +0000577 if (!VisitedBlocks.insert(BB)) break;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000578 if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(),
579 BB, BBI, 6, AA))
Dan Gohman17d95962010-05-28 16:45:33 +0000580 return findValueImpl(U, OffsetOk, Visited);
Dan Gohman13ec30b2010-05-28 17:44:00 +0000581 if (BBI != BB->begin()) break;
582 BB = BB->getUniquePredecessor();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000583 if (!BB) break;
584 BBI = BB->end();
585 }
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000586 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Duncan Sandsff103412010-11-17 04:30:22 +0000587 if (Value *W = PN->hasConstantValue())
Duncan Sands23a19572010-11-17 10:23:23 +0000588 if (W != V)
589 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000590 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
591 if (CI->isNoopCast(TD ? TD->getIntPtrType(V->getContext()) :
592 Type::getInt64Ty(V->getContext())))
Dan Gohman17d95962010-05-28 16:45:33 +0000593 return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000594 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
595 if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
596 Ex->idx_begin(),
597 Ex->idx_end()))
598 if (W != V)
Dan Gohman17d95962010-05-28 16:45:33 +0000599 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000600 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
601 // Same as above, but for ConstantExpr instead of Instruction.
602 if (Instruction::isCast(CE->getOpcode())) {
603 if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
604 CE->getOperand(0)->getType(),
605 CE->getType(),
606 TD ? TD->getIntPtrType(V->getContext()) :
607 Type::getInt64Ty(V->getContext())))
608 return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
609 } else if (CE->getOpcode() == Instruction::ExtractValue) {
610 const SmallVector<unsigned, 4> &Indices = CE->getIndices();
611 if (Value *W = FindInsertedValue(CE->getOperand(0),
612 Indices.begin(),
613 Indices.end()))
614 if (W != V)
615 return findValueImpl(W, OffsetOk, Visited);
616 }
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000617 }
618
619 // As a last resort, try SimplifyInstruction or constant folding.
620 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Duncan Sandsff103412010-11-17 04:30:22 +0000621 if (Value *W = SimplifyInstruction(Inst, TD, DT))
Duncan Sandsd261dc62010-11-17 08:35:29 +0000622 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000623 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
624 if (Value *W = ConstantFoldConstantExpression(CE, TD))
625 if (W != V)
Dan Gohman17d95962010-05-28 16:45:33 +0000626 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000627 }
628
629 return V;
630}
631
Dan Gohman113902e2010-04-08 18:47:09 +0000632//===----------------------------------------------------------------------===//
633// Implement the public interfaces to this file...
634//===----------------------------------------------------------------------===//
635
636FunctionPass *llvm::createLintPass() {
637 return new Lint();
638}
639
640/// lintFunction - Check a function for errors, printing messages on stderr.
641///
642void llvm::lintFunction(const Function &f) {
643 Function &F = const_cast<Function&>(f);
644 assert(!F.isDeclaration() && "Cannot lint external functions");
645
646 FunctionPassManager FPM(F.getParent());
647 Lint *V = new Lint();
648 FPM.add(V);
649 FPM.run(F);
650}
651
652/// lintModule - Check a module for errors, printing messages on stderr.
Dan Gohman113902e2010-04-08 18:47:09 +0000653///
Dan Gohmana0f7ff32010-05-26 22:28:53 +0000654void llvm::lintModule(const Module &M) {
Dan Gohman113902e2010-04-08 18:47:09 +0000655 PassManager PM;
656 Lint *V = new Lint();
657 PM.add(V);
658 PM.run(const_cast<Module&>(M));
Dan Gohman113902e2010-04-08 18:47:09 +0000659}