Fix batch of converting RegisterPass<> to INTIALIZE_PASS().
[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 INITIALIZE_PASS(Lint, "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 //
187 bool Lint::runOnFunction(Function &F) {
188   Mod = F.getParent();
189   AA = &getAnalysis<AliasAnalysis>();
190   DT = &getAnalysis<DominatorTree>();
191   TD = getAnalysisIfAvailable<TargetData>();
192   visit(F);
193   dbgs() << MessagesStr.str();
194   Messages.clear();
195   return false;
196 }
197
198 void 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);
203
204   // TODO: Check for irreducible control flow.
205 }
206
207 void Lint::visitCallSite(CallSite CS) {
208   Instruction &I = *CS.getInstruction();
209   Value *Callee = CS.getCalledValue();
210
211   visitMemoryReference(I, Callee, ~0u, 0, 0, MemRef::Callee);
212
213   if (Function *F = dyn_cast<Function>(findValue(Callee, /*OffsetOk=*/false))) {
214     Assert1(CS.getCallingConv() == F->getCallingConv(),
215             "Undefined behavior: Caller and callee calling convention differ",
216             &I);
217
218     const FunctionType *FT = F->getFunctionType();
219     unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
220
221     Assert1(FT->isVarArg() ?
222               FT->getNumParams() <= NumActualArgs :
223               FT->getNumParams() == NumActualArgs,
224             "Undefined behavior: Call argument count mismatches callee "
225             "argument count", &I);
226
227     Assert1(FT->getReturnType() == I.getType(),
228             "Undefined behavior: Call return type mismatches "
229             "callee return type", &I);
230
231     // Check argument types (in case the callee was casted) and attributes.
232     // TODO: Verify that caller and callee attributes are compatible.
233     Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
234     CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
235     for (; AI != AE; ++AI) {
236       Value *Actual = *AI;
237       if (PI != PE) {
238         Argument *Formal = PI++;
239         Assert1(Formal->getType() == Actual->getType(),
240                 "Undefined behavior: Call argument type mismatches "
241                 "callee parameter type", &I);
242
243         // Check that noalias arguments don't alias other arguments. The
244         // AliasAnalysis API isn't expressive enough for what we really want
245         // to do. Known partial overlap is not distinguished from the case
246         // where nothing is known.
247         if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy())
248           for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI) {
249             Assert1(AI == BI ||
250                     AA->alias(*AI, ~0u, *BI, ~0u) != AliasAnalysis::MustAlias,
251                     "Unusual: noalias argument aliases another argument", &I);
252           }
253
254         // Check that an sret argument points to valid memory.
255         if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
256           const Type *Ty =
257             cast<PointerType>(Formal->getType())->getElementType();
258           visitMemoryReference(I, Actual, AA->getTypeStoreSize(Ty),
259                                TD ? TD->getABITypeAlignment(Ty) : 0,
260                                Ty, MemRef::Read | MemRef::Write);
261         }
262       }
263     }
264   }
265
266   if (CS.isCall() && cast<CallInst>(CS.getInstruction())->isTailCall())
267     for (CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
268          AI != AE; ++AI) {
269       Value *Obj = findValue(*AI, /*OffsetOk=*/true);
270       Assert1(!isa<AllocaInst>(Obj),
271               "Undefined behavior: Call with \"tail\" keyword references "
272               "alloca", &I);
273     }
274
275
276   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
277     switch (II->getIntrinsicID()) {
278     default: break;
279
280     // TODO: Check more intrinsics
281
282     case Intrinsic::memcpy: {
283       MemCpyInst *MCI = cast<MemCpyInst>(&I);
284       // TODO: If the size is known, use it.
285       visitMemoryReference(I, MCI->getDest(), ~0u, MCI->getAlignment(), 0,
286                            MemRef::Write);
287       visitMemoryReference(I, MCI->getSource(), ~0u, MCI->getAlignment(), 0,
288                            MemRef::Read);
289
290       // Check that the memcpy arguments don't overlap. The AliasAnalysis API
291       // isn't expressive enough for what we really want to do. Known partial
292       // overlap is not distinguished from the case where nothing is known.
293       unsigned Size = 0;
294       if (const ConstantInt *Len =
295             dyn_cast<ConstantInt>(findValue(MCI->getLength(),
296                                             /*OffsetOk=*/false)))
297         if (Len->getValue().isIntN(32))
298           Size = Len->getValue().getZExtValue();
299       Assert1(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
300               AliasAnalysis::MustAlias,
301               "Undefined behavior: memcpy source and destination overlap", &I);
302       break;
303     }
304     case Intrinsic::memmove: {
305       MemMoveInst *MMI = cast<MemMoveInst>(&I);
306       // TODO: If the size is known, use it.
307       visitMemoryReference(I, MMI->getDest(), ~0u, MMI->getAlignment(), 0,
308                            MemRef::Write);
309       visitMemoryReference(I, MMI->getSource(), ~0u, MMI->getAlignment(), 0,
310                            MemRef::Read);
311       break;
312     }
313     case Intrinsic::memset: {
314       MemSetInst *MSI = cast<MemSetInst>(&I);
315       // TODO: If the size is known, use it.
316       visitMemoryReference(I, MSI->getDest(), ~0u, MSI->getAlignment(), 0,
317                            MemRef::Write);
318       break;
319     }
320
321     case Intrinsic::vastart:
322       Assert1(I.getParent()->getParent()->isVarArg(),
323               "Undefined behavior: va_start called in a non-varargs function",
324               &I);
325
326       visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0,
327                            MemRef::Read | MemRef::Write);
328       break;
329     case Intrinsic::vacopy:
330       visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0, MemRef::Write);
331       visitMemoryReference(I, CS.getArgument(1), ~0u, 0, 0, MemRef::Read);
332       break;
333     case Intrinsic::vaend:
334       visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0,
335                            MemRef::Read | MemRef::Write);
336       break;
337
338     case Intrinsic::stackrestore:
339       // Stackrestore doesn't read or write memory, but it sets the
340       // stack pointer, which the compiler may read from or write to
341       // at any time, so check it for both readability and writeability.
342       visitMemoryReference(I, CS.getArgument(0), ~0u, 0, 0,
343                            MemRef::Read | MemRef::Write);
344       break;
345     }
346 }
347
348 void Lint::visitCallInst(CallInst &I) {
349   return visitCallSite(&I);
350 }
351
352 void Lint::visitInvokeInst(InvokeInst &I) {
353   return visitCallSite(&I);
354 }
355
356 void Lint::visitReturnInst(ReturnInst &I) {
357   Function *F = I.getParent()->getParent();
358   Assert1(!F->doesNotReturn(),
359           "Unusual: Return statement in function with noreturn attribute",
360           &I);
361
362   if (Value *V = I.getReturnValue()) {
363     Value *Obj = findValue(V, /*OffsetOk=*/true);
364     Assert1(!isa<AllocaInst>(Obj),
365             "Unusual: Returning alloca value", &I);
366   }
367 }
368
369 // TODO: Check that the reference is in bounds.
370 // TODO: Check readnone/readonly function attributes.
371 void Lint::visitMemoryReference(Instruction &I,
372                                 Value *Ptr, unsigned Size, unsigned Align,
373                                 const Type *Ty, unsigned Flags) {
374   // If no memory is being referenced, it doesn't matter if the pointer
375   // is valid.
376   if (Size == 0)
377     return;
378
379   Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
380   Assert1(!isa<ConstantPointerNull>(UnderlyingObject),
381           "Undefined behavior: Null pointer dereference", &I);
382   Assert1(!isa<UndefValue>(UnderlyingObject),
383           "Undefined behavior: Undef pointer dereference", &I);
384   Assert1(!isa<ConstantInt>(UnderlyingObject) ||
385           !cast<ConstantInt>(UnderlyingObject)->isAllOnesValue(),
386           "Unusual: All-ones pointer dereference", &I);
387   Assert1(!isa<ConstantInt>(UnderlyingObject) ||
388           !cast<ConstantInt>(UnderlyingObject)->isOne(),
389           "Unusual: Address one pointer dereference", &I);
390
391   if (Flags & MemRef::Write) {
392     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
393       Assert1(!GV->isConstant(),
394               "Undefined behavior: Write to read-only memory", &I);
395     Assert1(!isa<Function>(UnderlyingObject) &&
396             !isa<BlockAddress>(UnderlyingObject),
397             "Undefined behavior: Write to text section", &I);
398   }
399   if (Flags & MemRef::Read) {
400     Assert1(!isa<Function>(UnderlyingObject),
401             "Unusual: Load from function body", &I);
402     Assert1(!isa<BlockAddress>(UnderlyingObject),
403             "Undefined behavior: Load from block address", &I);
404   }
405   if (Flags & MemRef::Callee) {
406     Assert1(!isa<BlockAddress>(UnderlyingObject),
407             "Undefined behavior: Call to block address", &I);
408   }
409   if (Flags & MemRef::Branchee) {
410     Assert1(!isa<Constant>(UnderlyingObject) ||
411             isa<BlockAddress>(UnderlyingObject),
412             "Undefined behavior: Branch to non-blockaddress", &I);
413   }
414
415   if (TD) {
416     if (Align == 0 && Ty) Align = TD->getABITypeAlignment(Ty);
417
418     if (Align != 0) {
419       unsigned BitWidth = TD->getTypeSizeInBits(Ptr->getType());
420       APInt Mask = APInt::getAllOnesValue(BitWidth),
421                    KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
422       ComputeMaskedBits(Ptr, Mask, KnownZero, KnownOne, TD);
423       Assert1(!(KnownOne & APInt::getLowBitsSet(BitWidth, Log2_32(Align))),
424               "Undefined behavior: Memory reference address is misaligned", &I);
425     }
426   }
427 }
428
429 void Lint::visitLoadInst(LoadInst &I) {
430   visitMemoryReference(I, I.getPointerOperand(),
431                        AA->getTypeStoreSize(I.getType()), I.getAlignment(),
432                        I.getType(), MemRef::Read);
433 }
434
435 void Lint::visitStoreInst(StoreInst &I) {
436   visitMemoryReference(I, I.getPointerOperand(),
437                        AA->getTypeStoreSize(I.getOperand(0)->getType()),
438                        I.getAlignment(),
439                        I.getOperand(0)->getType(), MemRef::Write);
440 }
441
442 void Lint::visitXor(BinaryOperator &I) {
443   Assert1(!isa<UndefValue>(I.getOperand(0)) ||
444           !isa<UndefValue>(I.getOperand(1)),
445           "Undefined result: xor(undef, undef)", &I);
446 }
447
448 void Lint::visitSub(BinaryOperator &I) {
449   Assert1(!isa<UndefValue>(I.getOperand(0)) ||
450           !isa<UndefValue>(I.getOperand(1)),
451           "Undefined result: sub(undef, undef)", &I);
452 }
453
454 void Lint::visitLShr(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::visitAShr(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 void Lint::visitShl(BinaryOperator &I) {
469   if (ConstantInt *CI =
470         dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
471     Assert1(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
472             "Undefined result: Shift count out of range", &I);
473 }
474
475 static bool isZero(Value *V, TargetData *TD) {
476   // Assume undef could be zero.
477   if (isa<UndefValue>(V)) return true;
478
479   unsigned BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
480   APInt Mask = APInt::getAllOnesValue(BitWidth),
481                KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
482   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD);
483   return KnownZero.isAllOnesValue();
484 }
485
486 void Lint::visitSDiv(BinaryOperator &I) {
487   Assert1(!isZero(I.getOperand(1), TD),
488           "Undefined behavior: Division by zero", &I);
489 }
490
491 void Lint::visitUDiv(BinaryOperator &I) {
492   Assert1(!isZero(I.getOperand(1), TD),
493           "Undefined behavior: Division by zero", &I);
494 }
495
496 void Lint::visitSRem(BinaryOperator &I) {
497   Assert1(!isZero(I.getOperand(1), TD),
498           "Undefined behavior: Division by zero", &I);
499 }
500
501 void Lint::visitURem(BinaryOperator &I) {
502   Assert1(!isZero(I.getOperand(1), TD),
503           "Undefined behavior: Division by zero", &I);
504 }
505
506 void Lint::visitAllocaInst(AllocaInst &I) {
507   if (isa<ConstantInt>(I.getArraySize()))
508     // This isn't undefined behavior, it's just an obvious pessimization.
509     Assert1(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
510             "Pessimization: Static alloca outside of entry block", &I);
511
512   // TODO: Check for an unusual size (MSB set?)
513 }
514
515 void Lint::visitVAArgInst(VAArgInst &I) {
516   visitMemoryReference(I, I.getOperand(0), ~0u, 0, 0,
517                        MemRef::Read | MemRef::Write);
518 }
519
520 void Lint::visitIndirectBrInst(IndirectBrInst &I) {
521   visitMemoryReference(I, I.getAddress(), ~0u, 0, 0, MemRef::Branchee);
522 }
523
524 void Lint::visitExtractElementInst(ExtractElementInst &I) {
525   if (ConstantInt *CI =
526         dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
527                                         /*OffsetOk=*/false)))
528     Assert1(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
529             "Undefined result: extractelement index out of range", &I);
530 }
531
532 void Lint::visitInsertElementInst(InsertElementInst &I) {
533   if (ConstantInt *CI =
534         dyn_cast<ConstantInt>(findValue(I.getOperand(2),
535                                         /*OffsetOk=*/false)))
536     Assert1(CI->getValue().ult(I.getType()->getNumElements()),
537             "Undefined result: insertelement index out of range", &I);
538 }
539
540 void Lint::visitUnreachableInst(UnreachableInst &I) {
541   // This isn't undefined behavior, it's merely suspicious.
542   Assert1(&I == I.getParent()->begin() ||
543           prior(BasicBlock::iterator(&I))->mayHaveSideEffects(),
544           "Unusual: unreachable immediately preceded by instruction without "
545           "side effects", &I);
546 }
547
548 /// findValue - Look through bitcasts and simple memory reference patterns
549 /// to identify an equivalent, but more informative, value.  If OffsetOk
550 /// is true, look through getelementptrs with non-zero offsets too.
551 ///
552 /// Most analysis passes don't require this logic, because instcombine
553 /// will simplify most of these kinds of things away. But it's a goal of
554 /// this Lint pass to be useful even on non-optimized IR.
555 Value *Lint::findValue(Value *V, bool OffsetOk) const {
556   SmallPtrSet<Value *, 4> Visited;
557   return findValueImpl(V, OffsetOk, Visited);
558 }
559
560 /// findValueImpl - Implementation helper for findValue.
561 Value *Lint::findValueImpl(Value *V, bool OffsetOk,
562                            SmallPtrSet<Value *, 4> &Visited) const {
563   // Detect self-referential values.
564   if (!Visited.insert(V))
565     return UndefValue::get(V->getType());
566
567   // TODO: Look through sext or zext cast, when the result is known to
568   // be interpreted as signed or unsigned, respectively.
569   // TODO: Look through eliminable cast pairs.
570   // TODO: Look through calls with unique return values.
571   // TODO: Look through vector insert/extract/shuffle.
572   V = OffsetOk ? V->getUnderlyingObject() : V->stripPointerCasts();
573   if (LoadInst *L = dyn_cast<LoadInst>(V)) {
574     BasicBlock::iterator BBI = L;
575     BasicBlock *BB = L->getParent();
576     SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
577     for (;;) {
578       if (!VisitedBlocks.insert(BB)) break;
579       if (Value *U = FindAvailableLoadedValue(L->getPointerOperand(),
580                                               BB, BBI, 6, AA))
581         return findValueImpl(U, OffsetOk, Visited);
582       if (BBI != BB->begin()) break;
583       BB = BB->getUniquePredecessor();
584       if (!BB) break;
585       BBI = BB->end();
586     }
587   } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
588     if (Value *W = PN->hasConstantValue(DT))
589       return findValueImpl(W, OffsetOk, Visited);
590   } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
591     if (CI->isNoopCast(TD ? TD->getIntPtrType(V->getContext()) :
592                             Type::getInt64Ty(V->getContext())))
593       return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
594   } 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)
599         return findValueImpl(W, OffsetOk, Visited);
600   } 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     }
617   }
618
619   // As a last resort, try SimplifyInstruction or constant folding.
620   if (Instruction *Inst = dyn_cast<Instruction>(V)) {
621     if (Value *W = SimplifyInstruction(Inst, TD))
622       if (W != Inst)
623         return findValueImpl(W, OffsetOk, Visited);
624   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
625     if (Value *W = ConstantFoldConstantExpression(CE, TD))
626       if (W != V)
627         return findValueImpl(W, OffsetOk, Visited);
628   }
629
630   return V;
631 }
632
633 //===----------------------------------------------------------------------===//
634 //  Implement the public interfaces to this file...
635 //===----------------------------------------------------------------------===//
636
637 FunctionPass *llvm::createLintPass() {
638   return new Lint();
639 }
640
641 /// lintFunction - Check a function for errors, printing messages on stderr.
642 ///
643 void llvm::lintFunction(const Function &f) {
644   Function &F = const_cast<Function&>(f);
645   assert(!F.isDeclaration() && "Cannot lint external functions");
646
647   FunctionPassManager FPM(F.getParent());
648   Lint *V = new Lint();
649   FPM.add(V);
650   FPM.run(F);
651 }
652
653 /// lintModule - Check a module for errors, printing messages on stderr.
654 ///
655 void llvm::lintModule(const Module &M) {
656   PassManager PM;
657   Lint *V = new Lint();
658   PM.add(V);
659   PM.run(const_cast<Module&>(M));
660 }