Add a comment.
[oota-llvm.git] / lib / Analysis / Lint.cpp
1 //===-- Lint.cpp - Check for common errors in LLVM IR ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass statically checks for common and easily-identified constructs
11 // which produce undefined or likely unintended behavior in LLVM IR.
12 //
13 // It is not a guarantee of correctness, in two ways. First, it isn't
14 // comprehensive. There are checks which could be done statically which are
15 // not yet implemented. Some of these are indicated by TODO comments, but
16 // those aren't comprehensive either. Second, many conditions cannot be
17 // checked statically. This pass does no dynamic instrumentation, so it
18 // can't check for all possible problems.
19 // 
20 // Another limitation is that it assumes all code will be executed. A store
21 // through a null pointer in a basic block which is never reached is harmless,
22 // but this pass will warn about it anyway. This is the main reason why most
23 // of these checks live here instead of in the Verifier pass.
24 //
25 // 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"
39 #include "llvm/Analysis/InstructionSimplify.h"
40 #include "llvm/Analysis/ConstantFolding.h"
41 #include "llvm/Analysis/Dominators.h"
42 #include "llvm/Analysis/Lint.h"
43 #include "llvm/Analysis/Loads.h"
44 #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"
55 #include "llvm/ADT/STLExtras.h"
56 using namespace llvm;
57
58 namespace {
59   namespace MemRef {
60     static unsigned Read     = 1;
61     static unsigned Write    = 2;
62     static unsigned Callee   = 4;
63     static unsigned Branchee = 8;
64   }
65
66   class Lint : public FunctionPass, public InstVisitor<Lint> {
67     friend class InstVisitor<Lint>;
68
69     void visitFunction(Function &F);
70
71     void visitCallSite(CallSite CS);
72     void visitMemoryReference(Instruction &I, Value *Ptr,
73                               unsigned Size, unsigned Align,
74                               const Type *Ty, unsigned Flags);
75
76     void visitCallInst(CallInst &I);
77     void visitInvokeInst(InvokeInst &I);
78     void visitReturnInst(ReturnInst &I);
79     void visitLoadInst(LoadInst &I);
80     void visitStoreInst(StoreInst &I);
81     void visitXor(BinaryOperator &I);
82     void visitSub(BinaryOperator &I);
83     void visitLShr(BinaryOperator &I);
84     void visitAShr(BinaryOperator &I);
85     void visitShl(BinaryOperator &I);
86     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);
93     void visitExtractElementInst(ExtractElementInst &I);
94     void visitInsertElementInst(InsertElementInst &I);
95     void visitUnreachableInst(UnreachableInst &I);
96
97     Value *findValue(Value *V, bool OffsetOk) const;
98     Value *findValueImpl(Value *V, bool OffsetOk,
99                          SmallPtrSet<Value *, 4> &Visited) const;
100
101   public:
102     Module *Mod;
103     AliasAnalysis *AA;
104     DominatorTree *DT;
105     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>();
118       AU.addRequired<DominatorTree>();
119     }
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
169 char Lint::ID = 0;
170 static RegisterPass<Lint>
171 X("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 //
188 bool Lint::runOnFunction(Function &F) {
189   Mod = F.getParent();
190   AA = &getAnalysis<AliasAnalysis>();
191   DT = &getAnalysis<DominatorTree>();
192   TD = getAnalysisIfAvailable<TargetData>();
193   visit(F);
194   dbgs() << MessagesStr.str();
195   Messages.clear();
196   return false;
197 }
198
199 void 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);
204 }
205
206 void Lint::visitCallSite(CallSite CS) {
207   Instruction &I = *CS.getInstruction();
208   Value *Callee = CS.getCalledValue();
209
210   visitMemoryReference(I, Callee, ~0u, 0, 0, MemRef::Callee);
211
212   if (Function *F = dyn_cast<Function>(findValue(Callee, /*OffsetOk=*/false))) {
213     Assert1(CS.getCallingConv() == F->getCallingConv(),
214             "Undefined behavior: Caller and callee calling convention differ",
215             &I);
216
217     const FunctionType *FT = F->getFunctionType();
218     unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
219
220     Assert1(FT->isVarArg() ?
221               FT->getNumParams() <= NumActualArgs :
222               FT->getNumParams() == NumActualArgs,
223             "Undefined behavior: Call argument count mismatches callee "
224             "argument count", &I);
225
226     // Check argument types (in case the callee was casted) and attributes.
227     Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
228     CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
229     for (; AI != AE; ++AI) {
230       Value *Actual = *AI;
231       if (PI != PE) {
232         Argument *Formal = PI++;
233         Assert1(Formal->getType() == Actual->getType(),
234                 "Undefined behavior: Call argument type mismatches "
235                 "callee parameter type", &I);
236
237         // Check that noalias arguments don't alias other arguments. The
238         // AliasAnalysis API isn't expressive enough for what we really want
239         // to do. Known partial overlap is not distinguished from the case
240         // where nothing is known.
241         if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy())
242           for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI) {
243             Assert1(AI == BI ||
244                     AA->alias(*AI, ~0u, *BI, ~0u) != AliasAnalysis::MustAlias,
245                     "Unusual: noalias argument aliases another argument", &I);
246           }
247
248         // Check that an sret argument points to valid memory.
249         if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
250           const Type *Ty =
251             cast<PointerType>(Formal->getType())->getElementType();
252           visitMemoryReference(I, Actual, AA->getTypeStoreSize(Ty),
253                                TD ? TD->getABITypeAlignment(Ty) : 0,
254                                Ty, MemRef::Read | MemRef::Write);
255         }
256       }
257     }
258   }
259
260   if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
261     for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
262          AI != AE; ++AI) {
263       Value *Obj = findValue(*AI, /*OffsetOk=*/true);
264       Assert1(!isa<AllocaInst>(Obj),
265               "Undefined behavior: Call with \"tail\" keyword references "
266               "alloca", &I);
267     }
268
269
270   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
271     switch (II->getIntrinsicID()) {
272     default: break;
273
274     // TODO: Check more intrinsics
275
276     case Intrinsic::memcpy: {
277       MemCpyInst *MCI = cast<MemCpyInst>(&I);
278       // TODO: If the size is known, use it.
279       visitMemoryReference(I, MCI->getDest(), ~0u, MCI->getAlignment(), 0,
280                            MemRef::Write);
281       visitMemoryReference(I, MCI->getSource(), ~0u, MCI->getAlignment(), 0,
282                            MemRef::Read);
283
284       // Check that the memcpy arguments don't overlap. The AliasAnalysis API
285       // isn't expressive enough for what we really want to do. Known partial
286       // overlap is not distinguished from the case where nothing is known.
287       unsigned Size = 0;
288       if (const ConstantInt *Len =
289             dyn_cast<ConstantInt>(findValue(MCI->getLength(),
290                                             /*OffsetOk=*/false)))
291         if (Len->getValue().isIntN(32))
292           Size = Len->getValue().getZExtValue();
293       Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
294               AliasAnalysis::MustAlias,
295               "Undefined behavior: memcpy source and destination overlap", &I);
296       break;
297     }
298     case Intrinsic::memmove: {
299       MemMoveInst *MMI = cast<MemMoveInst>(&I);
300       // TODO: If the size is known, use it.
301       visitMemoryReference(I, MMI->getDest(), ~0u, MMI->getAlignment(), 0,
302                            MemRef::Write);
303       visitMemoryReference(I, MMI->getSource(), ~0u, MMI->getAlignment(), 0,
304                            MemRef::Read);
305       break;
306     }
307     case Intrinsic::memset: {
308       MemSetInst *MSI = cast<MemSetInst>(&I);
309       // TODO: If the size is known, use it.
310       visitMemoryReference(I, MSI->getDest(), ~0u, MSI->getAlignment(), 0,
311                            MemRef::Write);
312       break;
313     }
314
315     case Intrinsic::vastart:
316       Assert1(I.getParent()->getParent()->isVarArg(),
317               "Undefined behavior: va_start called in a non-varargs function",
318               &I);
319
320       visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0,
321                            MemRef::Read | MemRef::Write);
322       break;
323     case Intrinsic::vacopy:
324       visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0, MemRef::Write);
325       visitMemoryReference(I, CS.getArgument(1), ~0u, 0, 0, MemRef::Read);
326       break;
327     case Intrinsic::vaend:
328       visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0,
329                            MemRef::Read | MemRef::Write);
330       break;
331
332     case Intrinsic::stackrestore:
333       // Stackrestore doesn't read or write memory, but it sets the
334       // stack pointer, which the compiler may read from or write to
335       // at any time, so check it for both readability and writeability.
336       visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0,
337                            MemRef::Read | MemRef::Write);
338       break;
339     }
340 }
341
342 void Lint::visitCallInst(CallInst &I) {
343   return visitCallSite(&I);
344 }
345
346 void Lint::visitInvokeInst(InvokeInst &I) {
347   return visitCallSite(&I);
348 }
349
350 void Lint::visitReturnInst(ReturnInst &I) {
351   Function *F = I.getParent()->getParent();
352   Assert1(!F->doesNotReturn(),
353           "Unusual: Return statement in function with noreturn attribute",
354           &I);
355
356   if (Value *V = I.getReturnValue()) {
357     Value *Obj = findValue(V, /*OffsetOk=*/true);
358     Assert1(!isa<AllocaInst>(Obj),
359             "Unusual: Returning alloca value", &I);
360   }
361 }
362
363 // TODO: Check that the reference is in bounds.
364 void Lint::visitMemoryReference(Instruction &I,
365                                 Value *Ptr, unsigned Size, unsigned Align,
366                                 const Type *Ty, unsigned Flags) {
367   // If no memory is being referenced, it doesn't matter if the pointer
368   // is valid.
369   if (Size == 0)
370     return;
371
372   Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
373   Assert1(!isa<ConstantPointerNull>(UnderlyingObject),
374           "Undefined behavior: Null pointer dereference", &I);
375   Assert1(!isa<UndefValue>(UnderlyingObject),
376           "Undefined behavior: Undef pointer dereference", &I);
377   Assert1(!isa<ConstantInt>(UnderlyingObject) ||
378           !cast<ConstantInt>(UnderlyingObject)->isAllOnesValue(),
379           "Unusual: All-ones pointer dereference", &I);
380   Assert1(!isa<ConstantInt>(UnderlyingObject) ||
381           !cast<ConstantInt>(UnderlyingObject)->isOne(),
382           "Unusual: Address one pointer dereference", &I);
383
384   if (Flags & MemRef::Write) {
385     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
386       Assert1(!GV->isConstant(),
387               "Undefined behavior: Write to read-only memory", &I);
388     Assert1(!isa<Function>(UnderlyingObject) &&
389             !isa<BlockAddress>(UnderlyingObject),
390             "Undefined behavior: Write to text section", &I);
391   }
392   if (Flags & MemRef::Read) {
393     Assert1(!isa<Function>(UnderlyingObject),
394             "Unusual: Load from function body", &I);
395     Assert1(!isa<BlockAddress>(UnderlyingObject),
396             "Undefined behavior: Load from block address", &I);
397   }
398   if (Flags & MemRef::Callee) {
399     Assert1(!isa<BlockAddress>(UnderlyingObject),
400             "Undefined behavior: Call to block address", &I);
401   }
402   if (Flags & MemRef::Branchee) {
403     Assert1(!isa<Constant>(UnderlyingObject) ||
404             isa<BlockAddress>(UnderlyingObject),
405             "Undefined behavior: Branch to non-blockaddress", &I);
406   }
407
408   if (TD) {
409     if (Align == 0 && Ty) Align = TD->getABITypeAlignment(Ty);
410
411     if (Align != 0) {
412       unsigned BitWidth = TD->getTypeSizeInBits(Ptr->getType());
413       APInt Mask = APInt::getAllOnesValue(BitWidth),
414                    KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
415       ComputeMaskedBits(Ptr, Mask, KnownZero, KnownOne, TD);
416       Assert1(!(KnownOne & APInt::getLowBitsSet(BitWidth, Log2_32(Align))),
417               "Undefined behavior: Memory reference address is misaligned", &I);
418     }
419   }
420 }
421
422 void Lint::visitLoadInst(LoadInst &I) {
423   visitMemoryReference(I, I.getPointerOperand(),
424                        AA->getTypeStoreSize(I.getType()), I.getAlignment(),
425                        I.getType(), MemRef::Read);
426 }
427
428 void Lint::visitStoreInst(StoreInst &I) {
429   visitMemoryReference(I, I.getPointerOperand(),
430                        AA->getTypeStoreSize(I.getOperand(0)->getType()),
431                        I.getAlignment(),
432                        I.getOperand(0)->getType(), MemRef::Write);
433 }
434
435 void Lint::visitXor(BinaryOperator &I) {
436   Assert1(!isa<UndefValue>(I.getOperand(0)) ||
437           !isa<UndefValue>(I.getOperand(1)),
438           "Undefined result: xor(undef, undef)", &I);
439 }
440
441 void Lint::visitSub(BinaryOperator &I) {
442   Assert1(!isa<UndefValue>(I.getOperand(0)) ||
443           !isa<UndefValue>(I.getOperand(1)),
444           "Undefined result: sub(undef, undef)", &I);
445 }
446
447 void Lint::visitLShr(BinaryOperator &I) {
448   if (ConstantInt *CI =
449         dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
450     Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
451             "Undefined result: Shift count out of range", &I);
452 }
453
454 void Lint::visitAShr(BinaryOperator &I) {
455   if (ConstantInt *CI =
456         dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
457     Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
458             "Undefined result: Shift count out of range", &I);
459 }
460
461 void Lint::visitShl(BinaryOperator &I) {
462   if (ConstantInt *CI =
463         dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
464     Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
465             "Undefined result: Shift count out of range", &I);
466 }
467
468 static bool isZero(Value *V, TargetData *TD) {
469   // Assume undef could be zero.
470   if (isa<UndefValue>(V)) return true;
471
472   unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
473   APInt Mask = APInt::getAllOnesValue(BitWidth),
474                KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
475   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
476   return KnownZero.isAllOnesValue();
477 }
478
479 void Lint::visitSDiv(BinaryOperator &I) {
480   Assert1(!isZero(I.getOperand(1), TD),
481           "Undefined behavior: Division by zero", &I);
482 }
483
484 void Lint::visitUDiv(BinaryOperator &I) {
485   Assert1(!isZero(I.getOperand(1), TD),
486           "Undefined behavior: Division by zero", &I);
487 }
488
489 void Lint::visitSRem(BinaryOperator &I) {
490   Assert1(!isZero(I.getOperand(1), TD),
491           "Undefined behavior: Division by zero", &I);
492 }
493
494 void Lint::visitURem(BinaryOperator &I) {
495   Assert1(!isZero(I.getOperand(1), TD),
496           "Undefined behavior: Division by zero", &I);
497 }
498
499 void Lint::visitAllocaInst(AllocaInst &I) {
500   if (isa<ConstantInt>(I.getArraySize()))
501     // This isn't undefined behavior, it's just an obvious pessimization.
502     Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
503             "Pessimization: Static alloca outside of entry block", &I);
504 }
505
506 void Lint::visitVAArgInst(VAArgInst &I) {
507   visitMemoryReference(I, I.getOperand(0), ~0u, 0, 0,
508                        MemRef::Read | MemRef::Write);
509 }
510
511 void Lint::visitIndirectBrInst(IndirectBrInst &I) {
512   visitMemoryReference(I, I.getAddress(), ~0u, 0, 0, MemRef::Branchee);
513 }
514
515 void Lint::visitExtractElementInst(ExtractElementInst &I) {
516   if (ConstantInt *CI =
517         dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
518                                         /*OffsetOk=*/false)))
519     Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
520             "Undefined result: extractelement index out of range", &I);
521 }
522
523 void Lint::visitInsertElementInst(InsertElementInst &I) {
524   if (ConstantInt *CI =
525         dyn_cast<ConstantInt>(findValue(I.getOperand(2),
526                                         /*OffsetOk=*/false)))
527     Assert1(CI->getValue().ult(I.getType()->getNumElements()),
528             "Undefined result: insertelement index out of range", &I);
529 }
530
531 void Lint::visitUnreachableInst(UnreachableInst &I) {
532   // This isn't undefined behavior, it's merely suspicious.
533   Assert1(&I == I.getParent()->begin() ||
534           prior(BasicBlock::iterator(&I))->mayHaveSideEffects(),
535           "Unusual: unreachable immediately preceded by instruction without "
536           "side effects", &I);
537 }
538
539 /// findValue - Look through bitcasts and simple memory reference patterns
540 /// to identify an equivalent, but more informative, value.  If OffsetOk
541 /// is true, look through getelementptrs with non-zero offsets too.
542 ///
543 /// Most analysis passes don't require this logic, because instcombine
544 /// will simplify most of these kinds of things away. But it's a goal of
545 /// this Lint pass to be useful even on non-optimized IR.
546 Value *Lint::findValue(Value *V, bool OffsetOk) const {
547   SmallPtrSet<Value *, 4> Visited;
548   return findValueImpl(V, OffsetOk, Visited);
549 }
550
551 /// findValueImpl - Implementation helper for findValue.
552 Value *Lint::findValueImpl(Value *V, bool OffsetOk,
553                            SmallPtrSet<Value *, 4> &Visited) const {
554   // Detect self-referential values.
555   if (!Visited.insert(V))
556     return UndefValue::get(V->getType());
557
558   // TODO: Look through sext or zext cast, when the result is known to
559   // be interpreted as signed or unsigned, respectively.
560   // TODO: Look through eliminable cast pairs.
561   // TODO: Look through calls with unique return values.
562   // TODO: Look through vector insert/extract/shuffle.
563   V = OffsetOk ? V->getUnderlyingObject() : V->stripPointerCasts();
564   if (LoadInst *L = dyn_cast<LoadInst>(V)) {
565     BasicBlock::iterator BBI = L;
566     BasicBlock *BB = L->getParent();
567     SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
568     for (;;) {
569       if (!VisitedBlocks.insert(BB)) break;
570       if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(),
571                                               BB, BBI, 6, AA))
572         return findValueImpl(U, OffsetOk, Visited);
573       if (BBI != BB->begin()) break;
574       BB = BB->getUniquePredecessor();
575       if (!BB) break;
576       BBI = BB->end();
577     }
578   } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
579     if (Value *W = PN->hasConstantValue(DT))
580       return findValueImpl(W, OffsetOk, Visited);
581   } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
582     if (CI->isNoopCast(TD ? TD->getIntPtrType(V->getContext()) :
583                             Type::getInt64Ty(V->getContext())))
584       return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
585   } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
586     if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
587                                      Ex->idx_begin(),
588                                      Ex->idx_end()))
589       if (W != V)
590         return findValueImpl(W, OffsetOk, Visited);
591   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
592     // Same as above, but for ConstantExpr instead of Instruction.
593     if (Instruction::isCast(CE->getOpcode())) {
594       if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
595                                CE->getOperand(0)->getType(),
596                                CE->getType(),
597                                TD ? TD->getIntPtrType(V->getContext()) :
598                                     Type::getInt64Ty(V->getContext())))
599         return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
600     } else if (CE->getOpcode() == Instruction::ExtractValue) {
601       const SmallVector<unsigned, 4> &Indices = CE->getIndices();
602       if (Value *W = FindInsertedValue(CE->getOperand(0),
603                                        Indices.begin(),
604                                        Indices.end()))
605         if (W != V)
606           return findValueImpl(W, OffsetOk, Visited);
607     }
608   }
609
610   // As a last resort, try SimplifyInstruction or constant folding.
611   if (Instruction *Inst = dyn_cast<Instruction>(V)) {
612     if (Value *W = SimplifyInstruction(Inst, TD))
613       if (W != Inst)
614         return findValueImpl(W, OffsetOk, Visited);
615   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
616     if (Value *W = ConstantFoldConstantExpression(CE, TD))
617       if (W != V)
618         return findValueImpl(W, OffsetOk, Visited);
619   }
620
621   return V;
622 }
623
624 //===----------------------------------------------------------------------===//
625 //  Implement the public interfaces to this file...
626 //===----------------------------------------------------------------------===//
627
628 FunctionPass *llvm::createLintPass() {
629   return new Lint();
630 }
631
632 /// lintFunction - Check a function for errors, printing messages on stderr.
633 ///
634 void llvm::lintFunction(const Function &f) {
635   Function &F = const_cast<Function&>(f);
636   assert(!F.isDeclaration() && "Cannot lint external functions");
637
638   FunctionPassManager FPM(F.getParent());
639   Lint *V = new Lint();
640   FPM.add(V);
641   FPM.run(F);
642 }
643
644 /// lintModule - Check a module for errors, printing messages on stderr.
645 ///
646 void llvm::lintModule(const Module &M) {
647   PassManager PM;
648   Lint *V = new Lint();
649   PM.add(V);
650   PM.run(const_cast<Module&>(M));
651 }