blob: 2dfb09c95ad69dfce11dca0c61af99e59346717b [file] [log] [blame]
Dan Gohman98bc4372010-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.
Matt Arsenaulta236ea52014-03-06 17:33:55 +000019//
Dan Gohman98bc4372010-04-08 18:47:09 +000020// 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 Gohmanf855b392010-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 Gohmanc951e6e2010-04-22 01:30:05 +000024//
Dan Gohman98bc4372010-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.
Matt Arsenaulta236ea52014-03-06 17:33:55 +000029//
Dan Gohman98bc4372010-04-08 18:47:09 +000030// 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.
Matt Arsenaulta236ea52014-03-06 17:33:55 +000034//
Dan Gohman98bc4372010-04-08 18:47:09 +000035//===----------------------------------------------------------------------===//
36
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Analysis/Lint.h"
38#include "llvm/ADT/STLExtras.h"
Chandler Carruth71f308a2015-02-13 09:09:03 +000039#include "llvm/ADT/SmallSet.h"
Dan Gohman98bc4372010-04-08 18:47:09 +000040#include "llvm/Analysis/AliasAnalysis.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000041#include "llvm/Analysis/AssumptionCache.h"
Dan Gohman54d7aaa2010-05-28 16:21:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000043#include "llvm/Analysis/InstructionSimplify.h"
Dan Gohman54d7aaa2010-05-28 16:21:24 +000044#include "llvm/Analysis/Loads.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000045#include "llvm/Analysis/Passes.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000046#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman98bc4372010-04-08 18:47:09 +000047#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000048#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000049#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000050#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/Function.h"
Chandler Carruth50fee932015-08-06 02:05:46 +000052#include "llvm/IR/Module.h"
Chandler Carruth7da14f12014-03-06 03:23:41 +000053#include "llvm/IR/InstVisitor.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000054#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth30d69c22015-02-13 10:01:29 +000055#include "llvm/IR/LegacyPassManager.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000056#include "llvm/Pass.h"
Dan Gohman98bc4372010-04-08 18:47:09 +000057#include "llvm/Support/Debug.h"
Dan Gohman98bc4372010-04-08 18:47:09 +000058#include "llvm/Support/raw_ostream.h"
59using namespace llvm;
60
61namespace {
Dan Gohman299e7b92010-04-30 19:05:00 +000062 namespace MemRef {
Benjamin Kramer57a3d082015-03-08 16:07:39 +000063 static const unsigned Read = 1;
64 static const unsigned Write = 2;
65 static const unsigned Callee = 4;
66 static const unsigned Branchee = 8;
Dan Gohman299e7b92010-04-30 19:05:00 +000067 }
68
Dan Gohman98bc4372010-04-08 18:47:09 +000069 class Lint : public FunctionPass, public InstVisitor<Lint> {
70 friend class InstVisitor<Lint>;
71
Dan Gohman9ba08a42010-04-09 01:39:53 +000072 void visitFunction(Function &F);
73
Dan Gohman98bc4372010-04-08 18:47:09 +000074 void visitCallSite(CallSite CS);
Dan Gohman0fa67e42010-05-28 21:43:57 +000075 void visitMemoryReference(Instruction &I, Value *Ptr,
Dan Gohmanf372cf82010-10-19 22:54:46 +000076 uint64_t Size, unsigned Align,
Chris Lattner229907c2011-07-18 04:54:35 +000077 Type *Ty, unsigned Flags);
Andrew Kaylor78b53db2015-02-10 19:52:43 +000078 void visitEHBeginCatch(IntrinsicInst *II);
79 void visitEHEndCatch(IntrinsicInst *II);
Dan Gohman98bc4372010-04-08 18:47:09 +000080
Dan Gohman98bc4372010-04-08 18:47:09 +000081 void visitCallInst(CallInst &I);
82 void visitInvokeInst(InvokeInst &I);
83 void visitReturnInst(ReturnInst &I);
84 void visitLoadInst(LoadInst &I);
85 void visitStoreInst(StoreInst &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +000086 void visitXor(BinaryOperator &I);
87 void visitSub(BinaryOperator &I);
Dan Gohman7808d492010-04-08 23:05:57 +000088 void visitLShr(BinaryOperator &I);
89 void visitAShr(BinaryOperator &I);
90 void visitShl(BinaryOperator &I);
Dan Gohman98bc4372010-04-08 18:47:09 +000091 void visitSDiv(BinaryOperator &I);
92 void visitUDiv(BinaryOperator &I);
93 void visitSRem(BinaryOperator &I);
94 void visitURem(BinaryOperator &I);
95 void visitAllocaInst(AllocaInst &I);
96 void visitVAArgInst(VAArgInst &I);
97 void visitIndirectBrInst(IndirectBrInst &I);
Dan Gohman7808d492010-04-08 23:05:57 +000098 void visitExtractElementInst(ExtractElementInst &I);
99 void visitInsertElementInst(InsertElementInst &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000100 void visitUnreachableInst(UnreachableInst &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000101
Chandler Carruth50fee932015-08-06 02:05:46 +0000102 Value *findValue(Value *V, bool OffsetOk) const;
103 Value *findValueImpl(Value *V, bool OffsetOk,
Craig Topper71b7b682014-08-21 05:55:13 +0000104 SmallPtrSetImpl<Value *> &Visited) const;
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000105
Dan Gohman98bc4372010-04-08 18:47:09 +0000106 public:
107 Module *Mod;
Chandler Carruth50fee932015-08-06 02:05:46 +0000108 const DataLayout *DL;
Dan Gohman98bc4372010-04-08 18:47:09 +0000109 AliasAnalysis *AA;
Chandler Carruth66b31302015-01-04 12:03:27 +0000110 AssumptionCache *AC;
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000111 DominatorTree *DT;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000112 TargetLibraryInfo *TLI;
Dan Gohman98bc4372010-04-08 18:47:09 +0000113
Alp Tokere69170a2014-06-26 22:52:05 +0000114 std::string Messages;
115 raw_string_ostream MessagesStr;
Dan Gohman98bc4372010-04-08 18:47:09 +0000116
117 static char ID; // Pass identification, replacement for typeid
Alp Tokere69170a2014-06-26 22:52:05 +0000118 Lint() : FunctionPass(ID), MessagesStr(Messages) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000119 initializeLintPass(*PassRegistry::getPassRegistry());
120 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000121
Craig Toppere9ba7592014-03-05 07:30:04 +0000122 bool runOnFunction(Function &F) override;
Dan Gohman98bc4372010-04-08 18:47:09 +0000123
Craig Toppere9ba7592014-03-05 07:30:04 +0000124 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman98bc4372010-04-08 18:47:09 +0000125 AU.setPreservesAll();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000126 AU.addRequired<AAResultsWrapperPass>();
Chandler Carruth66b31302015-01-04 12:03:27 +0000127 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000128 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth73523022014-01-13 13:07:17 +0000129 AU.addRequired<DominatorTreeWrapperPass>();
Dan Gohman98bc4372010-04-08 18:47:09 +0000130 }
Craig Toppere9ba7592014-03-05 07:30:04 +0000131 void print(raw_ostream &O, const Module *M) const override {}
Dan Gohman98bc4372010-04-08 18:47:09 +0000132
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000133 void WriteValues(ArrayRef<const Value *> Vs) {
134 for (const Value *V : Vs) {
135 if (!V)
136 continue;
137 if (isa<Instruction>(V)) {
138 MessagesStr << *V << '\n';
139 } else {
140 V->printAsOperand(MessagesStr, true, Mod);
141 MessagesStr << '\n';
142 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000143 }
144 }
145
Duncan P. N. Exon Smithf2929c92015-03-16 17:49:03 +0000146 /// \brief A check failed, so printout out the condition and the message.
147 ///
148 /// This provides a nice place to put a breakpoint if you want to see why
149 /// something is not correct.
Duncan P. N. Exon Smithec9d3f72015-03-14 16:47:37 +0000150 void CheckFailed(const Twine &Message) { MessagesStr << Message << '\n'; }
151
Duncan P. N. Exon Smithf2929c92015-03-16 17:49:03 +0000152 /// \brief A check failed (with values to print).
153 ///
154 /// This calls the Message-only version so that the above is easier to set
155 /// a breakpoint on.
Duncan P. N. Exon Smithec9d3f72015-03-14 16:47:37 +0000156 template <typename T1, typename... Ts>
157 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &...Vs) {
158 CheckFailed(Message);
159 WriteValues({V1, Vs...});
Dan Gohman98bc4372010-04-08 18:47:09 +0000160 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000161 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000162}
Dan Gohman98bc4372010-04-08 18:47:09 +0000163
164char Lint::ID = 0;
Owen Anderson8ac477f2010-10-12 19:48:12 +0000165INITIALIZE_PASS_BEGIN(Lint, "lint", "Statically lint-checks LLVM IR",
166 false, true)
Chandler Carruth66b31302015-01-04 12:03:27 +0000167INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000168INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth73523022014-01-13 13:07:17 +0000169INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000170INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000171INITIALIZE_PASS_END(Lint, "lint", "Statically lint-checks LLVM IR",
172 false, true)
Dan Gohman98bc4372010-04-08 18:47:09 +0000173
174// Assert - We know that cond should be true, if not print an error message.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000175#define Assert(C, ...) \
176 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (0)
Dan Gohman98bc4372010-04-08 18:47:09 +0000177
178// Lint::run - This is the main Analysis entry point for a
179// function.
180//
181bool Lint::runOnFunction(Function &F) {
182 Mod = F.getParent();
Chandler Carruth50fee932015-08-06 02:05:46 +0000183 DL = &F.getParent()->getDataLayout();
Chandler Carruth7b560d42015-09-09 17:55:00 +0000184 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Chandler Carruth66b31302015-01-04 12:03:27 +0000185 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth73523022014-01-13 13:07:17 +0000186 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000187 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Dan Gohman98bc4372010-04-08 18:47:09 +0000188 visit(F);
189 dbgs() << MessagesStr.str();
Alp Tokere69170a2014-06-26 22:52:05 +0000190 Messages.clear();
Dan Gohman98bc4372010-04-08 18:47:09 +0000191 return false;
192}
193
Dan Gohman9ba08a42010-04-09 01:39:53 +0000194void Lint::visitFunction(Function &F) {
195 // This isn't undefined behavior, it's just a little unusual, and it's a
196 // fairly common mistake to neglect to name a function.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000197 Assert(F.hasName() || F.hasLocalLinkage(),
198 "Unusual: Unnamed function with non-local linkage", &F);
Dan Gohman1e33b182010-07-06 15:23:00 +0000199
200 // TODO: Check for irreducible control flow.
Dan Gohman98bc4372010-04-08 18:47:09 +0000201}
202
203void Lint::visitCallSite(CallSite CS) {
204 Instruction &I = *CS.getInstruction();
205 Value *Callee = CS.getCalledValue();
206
Chandler Carruthecbd1682015-06-17 07:21:38 +0000207 visitMemoryReference(I, Callee, MemoryLocation::UnknownSize, 0, nullptr,
208 MemRef::Callee);
Dan Gohman98bc4372010-04-08 18:47:09 +0000209
Chandler Carruth50fee932015-08-06 02:05:46 +0000210 if (Function *F = dyn_cast<Function>(findValue(Callee,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000211 /*OffsetOk=*/false))) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000212 Assert(CS.getCallingConv() == F->getCallingConv(),
213 "Undefined behavior: Caller and callee calling convention differ",
214 &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000215
Chris Lattner229907c2011-07-18 04:54:35 +0000216 FunctionType *FT = F->getFunctionType();
Matt Arsenaultb12f2f32013-11-10 03:18:50 +0000217 unsigned NumActualArgs = CS.arg_size();
Dan Gohman98bc4372010-04-08 18:47:09 +0000218
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000219 Assert(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs
220 : FT->getNumParams() == NumActualArgs,
221 "Undefined behavior: Call argument count mismatches callee "
222 "argument count",
223 &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000224
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000225 Assert(FT->getReturnType() == I.getType(),
226 "Undefined behavior: Call return type mismatches "
227 "callee return type",
228 &I);
Dan Gohmanc128e702010-07-12 18:02:04 +0000229
Dan Gohman0fa67e42010-05-28 21:43:57 +0000230 // Check argument types (in case the callee was casted) and attributes.
Dan Gohman1e33b182010-07-06 15:23:00 +0000231 // TODO: Verify that caller and callee attributes are compatible.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000232 Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
233 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
234 for (; AI != AE; ++AI) {
235 Value *Actual = *AI;
236 if (PI != PE) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000237 Argument *Formal = &*PI++;
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000238 Assert(Formal->getType() == Actual->getType(),
239 "Undefined behavior: Call argument type mismatches "
240 "callee parameter type",
241 &I);
Dan Gohman49a372c2010-06-01 20:51:40 +0000242
Dan Gohman3cb55a12010-12-13 22:53:18 +0000243 // Check that noalias arguments don't alias other arguments. This is
244 // not fully precise because we don't know the sizes of the dereferenced
245 // memory regions.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000246 if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy())
Dan Gohman7dacf8f2010-11-11 19:23:51 +0000247 for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI)
Dan Gohman201acdb2010-12-10 20:04:06 +0000248 if (AI != BI && (*BI)->getType()->isPointerTy()) {
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000249 AliasResult Result = AA->alias(*AI, *BI);
250 Assert(Result != MustAlias && Result != PartialAlias,
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000251 "Unusual: noalias argument aliases another argument", &I);
Dan Gohman201acdb2010-12-10 20:04:06 +0000252 }
Dan Gohman49a372c2010-06-01 20:51:40 +0000253
254 // Check that an sret argument points to valid memory.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000255 if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000256 Type *Ty =
Dan Gohman0fa67e42010-05-28 21:43:57 +0000257 cast<PointerType>(Formal->getType())->getElementType();
Chandler Carruth50fee932015-08-06 02:05:46 +0000258 visitMemoryReference(I, Actual, DL->getTypeStoreSize(Ty),
259 DL->getABITypeAlignment(Ty), Ty,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000260 MemRef::Read | MemRef::Write);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000261 }
262 }
263 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000264 }
265
Dan Gohman1249adf2010-05-26 21:46:36 +0000266 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) {
Chandler Carruth50fee932015-08-06 02:05:46 +0000269 Value *Obj = findValue(*AI, /*OffsetOk=*/true);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000270 Assert(!isa<AllocaInst>(Obj),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000271 "Undefined behavior: Call with \"tail\" keyword references "
272 "alloca",
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000273 &I);
Dan Gohman1249adf2010-05-26 21:46:36 +0000274 }
275
Dan Gohman98bc4372010-04-08 18:47:09 +0000276
277 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
278 switch (II->getIntrinsicID()) {
279 default: break;
280
281 // TODO: Check more intrinsics
282
283 case Intrinsic::memcpy: {
284 MemCpyInst *MCI = cast<MemCpyInst>(&I);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000285 // TODO: If the size is known, use it.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000286 visitMemoryReference(I, MCI->getDest(), MemoryLocation::UnknownSize,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000287 MCI->getAlignment(), nullptr, MemRef::Write);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000288 visitMemoryReference(I, MCI->getSource(), MemoryLocation::UnknownSize,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000289 MCI->getAlignment(), nullptr, MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000290
Dan Gohman9ba08a42010-04-09 01:39:53 +0000291 // Check that the memcpy arguments don't overlap. The AliasAnalysis API
292 // isn't expressive enough for what we really want to do. Known partial
293 // overlap is not distinguished from the case where nothing is known.
Dan Gohmanf372cf82010-10-19 22:54:46 +0000294 uint64_t Size = 0;
Dan Gohman98bc4372010-04-08 18:47:09 +0000295 if (const ConstantInt *Len =
Chandler Carruth50fee932015-08-06 02:05:46 +0000296 dyn_cast<ConstantInt>(findValue(MCI->getLength(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000297 /*OffsetOk=*/false)))
Dan Gohman98bc4372010-04-08 18:47:09 +0000298 if (Len->getValue().isIntN(32))
299 Size = Len->getValue().getZExtValue();
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000300 Assert(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000301 MustAlias,
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000302 "Undefined behavior: memcpy source and destination overlap", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000303 break;
304 }
305 case Intrinsic::memmove: {
306 MemMoveInst *MMI = cast<MemMoveInst>(&I);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000307 // TODO: If the size is known, use it.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000308 visitMemoryReference(I, MMI->getDest(), MemoryLocation::UnknownSize,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000309 MMI->getAlignment(), nullptr, MemRef::Write);
Chandler Carruthecbd1682015-06-17 07:21:38 +0000310 visitMemoryReference(I, MMI->getSource(), MemoryLocation::UnknownSize,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000311 MMI->getAlignment(), nullptr, MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000312 break;
313 }
314 case Intrinsic::memset: {
315 MemSetInst *MSI = cast<MemSetInst>(&I);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000316 // TODO: If the size is known, use it.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000317 visitMemoryReference(I, MSI->getDest(), MemoryLocation::UnknownSize,
Pete Cooper67cf9a72015-11-19 05:56:52 +0000318 MSI->getAlignment(), nullptr, MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000319 break;
320 }
321
322 case Intrinsic::vastart:
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000323 Assert(I.getParent()->getParent()->isVarArg(),
324 "Undefined behavior: va_start called in a non-varargs function",
325 &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000326
Chandler Carruthecbd1682015-06-17 07:21:38 +0000327 visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
328 nullptr, MemRef::Read | MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000329 break;
330 case Intrinsic::vacopy:
Chandler Carruthecbd1682015-06-17 07:21:38 +0000331 visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
332 nullptr, MemRef::Write);
333 visitMemoryReference(I, CS.getArgument(1), MemoryLocation::UnknownSize, 0,
334 nullptr, MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000335 break;
336 case Intrinsic::vaend:
Chandler Carruthecbd1682015-06-17 07:21:38 +0000337 visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
338 nullptr, MemRef::Read | MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000339 break;
Dan Gohmana20a5cd2010-05-26 22:21:25 +0000340
341 case Intrinsic::stackrestore:
342 // Stackrestore doesn't read or write memory, but it sets the
343 // stack pointer, which the compiler may read from or write to
344 // at any time, so check it for both readability and writeability.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000345 visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
346 nullptr, MemRef::Read | MemRef::Write);
Dan Gohmana20a5cd2010-05-26 22:21:25 +0000347 break;
Dan Gohman98bc4372010-04-08 18:47:09 +0000348 }
349}
350
351void Lint::visitCallInst(CallInst &I) {
352 return visitCallSite(&I);
353}
354
355void Lint::visitInvokeInst(InvokeInst &I) {
356 return visitCallSite(&I);
357}
358
359void Lint::visitReturnInst(ReturnInst &I) {
360 Function *F = I.getParent()->getParent();
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000361 Assert(!F->doesNotReturn(),
362 "Unusual: Return statement in function with noreturn attribute", &I);
Dan Gohmanddba4b72010-05-28 04:33:42 +0000363
364 if (Value *V = I.getReturnValue()) {
Chandler Carruth50fee932015-08-06 02:05:46 +0000365 Value *Obj = findValue(V, /*OffsetOk=*/true);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000366 Assert(!isa<AllocaInst>(Obj), "Unusual: Returning alloca value", &I);
Dan Gohmanddba4b72010-05-28 04:33:42 +0000367 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000368}
369
Dan Gohman0fa67e42010-05-28 21:43:57 +0000370// TODO: Check that the reference is in bounds.
Dan Gohman1e33b182010-07-06 15:23:00 +0000371// TODO: Check readnone/readonly function attributes.
Dan Gohman98bc4372010-04-08 18:47:09 +0000372void Lint::visitMemoryReference(Instruction &I,
Dan Gohmanf372cf82010-10-19 22:54:46 +0000373 Value *Ptr, uint64_t Size, unsigned Align,
Chris Lattner229907c2011-07-18 04:54:35 +0000374 Type *Ty, unsigned Flags) {
Dan Gohman0fa67e42010-05-28 21:43:57 +0000375 // If no memory is being referenced, it doesn't matter if the pointer
376 // is valid.
377 if (Size == 0)
378 return;
379
Chandler Carruth50fee932015-08-06 02:05:46 +0000380 Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000381 Assert(!isa<ConstantPointerNull>(UnderlyingObject),
382 "Undefined behavior: Null pointer dereference", &I);
383 Assert(!isa<UndefValue>(UnderlyingObject),
384 "Undefined behavior: Undef pointer dereference", &I);
385 Assert(!isa<ConstantInt>(UnderlyingObject) ||
386 !cast<ConstantInt>(UnderlyingObject)->isAllOnesValue(),
387 "Unusual: All-ones pointer dereference", &I);
388 Assert(!isa<ConstantInt>(UnderlyingObject) ||
389 !cast<ConstantInt>(UnderlyingObject)->isOne(),
390 "Unusual: Address one pointer dereference", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000391
Dan Gohman299e7b92010-04-30 19:05:00 +0000392 if (Flags & MemRef::Write) {
393 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000394 Assert(!GV->isConstant(), "Undefined behavior: Write to read-only memory",
395 &I);
396 Assert(!isa<Function>(UnderlyingObject) &&
397 !isa<BlockAddress>(UnderlyingObject),
398 "Undefined behavior: Write to text section", &I);
Dan Gohman299e7b92010-04-30 19:05:00 +0000399 }
400 if (Flags & MemRef::Read) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000401 Assert(!isa<Function>(UnderlyingObject), "Unusual: Load from function body",
402 &I);
403 Assert(!isa<BlockAddress>(UnderlyingObject),
404 "Undefined behavior: Load from block address", &I);
Dan Gohman299e7b92010-04-30 19:05:00 +0000405 }
406 if (Flags & MemRef::Callee) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000407 Assert(!isa<BlockAddress>(UnderlyingObject),
408 "Undefined behavior: Call to block address", &I);
Dan Gohman299e7b92010-04-30 19:05:00 +0000409 }
410 if (Flags & MemRef::Branchee) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000411 Assert(!isa<Constant>(UnderlyingObject) ||
412 isa<BlockAddress>(UnderlyingObject),
413 "Undefined behavior: Branch to non-blockaddress", &I);
Dan Gohman299e7b92010-04-30 19:05:00 +0000414 }
415
Duncan Sandsa221eea2012-09-26 07:45:36 +0000416 // Check for buffer overflows and misalignment.
Dan Gohman20a2ae92013-01-31 02:00:45 +0000417 // Only handles memory references that read/write something simple like an
418 // alloca instruction or a global variable.
419 int64_t Offset = 0;
Chandler Carruth50fee932015-08-06 02:05:46 +0000420 if (Value *Base = GetPointerBaseWithConstantOffset(Ptr, Offset, *DL)) {
Dan Gohman20a2ae92013-01-31 02:00:45 +0000421 // OK, so the access is to a constant offset from Ptr. Check that Ptr is
422 // something we can handle and if so extract the size of this base object
423 // along with its alignment.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000424 uint64_t BaseSize = MemoryLocation::UnknownSize;
Dan Gohman20a2ae92013-01-31 02:00:45 +0000425 unsigned BaseAlign = 0;
Dan Gohman98bc4372010-04-08 18:47:09 +0000426
Dan Gohman20a2ae92013-01-31 02:00:45 +0000427 if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
428 Type *ATy = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000429 if (!AI->isArrayAllocation() && ATy->isSized())
Chandler Carruth50fee932015-08-06 02:05:46 +0000430 BaseSize = DL->getTypeAllocSize(ATy);
Dan Gohman20a2ae92013-01-31 02:00:45 +0000431 BaseAlign = AI->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000432 if (BaseAlign == 0 && ATy->isSized())
Chandler Carruth50fee932015-08-06 02:05:46 +0000433 BaseAlign = DL->getABITypeAlignment(ATy);
Dan Gohman20a2ae92013-01-31 02:00:45 +0000434 } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
435 // If the global may be defined differently in another compilation unit
436 // then don't warn about funky memory accesses.
437 if (GV->hasDefinitiveInitializer()) {
438 Type *GTy = GV->getType()->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000439 if (GTy->isSized())
Chandler Carruth50fee932015-08-06 02:05:46 +0000440 BaseSize = DL->getTypeAllocSize(GTy);
Dan Gohman20a2ae92013-01-31 02:00:45 +0000441 BaseAlign = GV->getAlignment();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000442 if (BaseAlign == 0 && GTy->isSized())
Chandler Carruth50fee932015-08-06 02:05:46 +0000443 BaseAlign = DL->getABITypeAlignment(GTy);
Duncan Sands3f4d0b12012-09-25 10:00:49 +0000444 }
Dan Gohman98bc4372010-04-08 18:47:09 +0000445 }
Dan Gohman20a2ae92013-01-31 02:00:45 +0000446
447 // Accesses from before the start or after the end of the object are not
448 // defined.
Chandler Carruthecbd1682015-06-17 07:21:38 +0000449 Assert(Size == MemoryLocation::UnknownSize ||
450 BaseSize == MemoryLocation::UnknownSize ||
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000451 (Offset >= 0 && Offset + Size <= BaseSize),
452 "Undefined behavior: Buffer overflow", &I);
Dan Gohman20a2ae92013-01-31 02:00:45 +0000453
454 // Accesses that say that the memory is more aligned than it is are not
455 // defined.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000456 if (Align == 0 && Ty && Ty->isSized())
Chandler Carruth50fee932015-08-06 02:05:46 +0000457 Align = DL->getABITypeAlignment(Ty);
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000458 Assert(!BaseAlign || Align <= MinAlign(BaseAlign, Offset),
459 "Undefined behavior: Memory reference address is misaligned", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000460 }
461}
462
463void Lint::visitLoadInst(LoadInst &I) {
Dan Gohman0fa67e42010-05-28 21:43:57 +0000464 visitMemoryReference(I, I.getPointerOperand(),
Chandler Carruth50fee932015-08-06 02:05:46 +0000465 DL->getTypeStoreSize(I.getType()), I.getAlignment(),
Dan Gohman0fa67e42010-05-28 21:43:57 +0000466 I.getType(), MemRef::Read);
Dan Gohman98bc4372010-04-08 18:47:09 +0000467}
468
469void Lint::visitStoreInst(StoreInst &I) {
Dan Gohman0fa67e42010-05-28 21:43:57 +0000470 visitMemoryReference(I, I.getPointerOperand(),
Chandler Carruth50fee932015-08-06 02:05:46 +0000471 DL->getTypeStoreSize(I.getOperand(0)->getType()),
Dan Gohman0fa67e42010-05-28 21:43:57 +0000472 I.getAlignment(),
473 I.getOperand(0)->getType(), MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000474}
475
Dan Gohman9ba08a42010-04-09 01:39:53 +0000476void Lint::visitXor(BinaryOperator &I) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000477 Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
478 "Undefined result: xor(undef, undef)", &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000479}
480
481void Lint::visitSub(BinaryOperator &I) {
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000482 Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
483 "Undefined result: sub(undef, undef)", &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000484}
485
Dan Gohman7808d492010-04-08 23:05:57 +0000486void Lint::visitLShr(BinaryOperator &I) {
Chandler Carruth50fee932015-08-06 02:05:46 +0000487 if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(1),
488 /*OffsetOk=*/false)))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000489 Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
490 "Undefined result: Shift count out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000491}
492
493void Lint::visitAShr(BinaryOperator &I) {
Chandler Carruth50fee932015-08-06 02:05:46 +0000494 if (ConstantInt *CI =
495 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000496 Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
497 "Undefined result: Shift count out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000498}
499
500void Lint::visitShl(BinaryOperator &I) {
Chandler Carruth50fee932015-08-06 02:05:46 +0000501 if (ConstantInt *CI =
502 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000503 Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
504 "Undefined result: Shift count out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000505}
506
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000507static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +0000508 AssumptionCache *AC) {
Dan Gohman9ba08a42010-04-09 01:39:53 +0000509 // Assume undef could be zero.
Matt Arsenault5faa6692013-08-26 23:29:33 +0000510 if (isa<UndefValue>(V))
511 return true;
Dan Gohman9ba08a42010-04-09 01:39:53 +0000512
Matt Arsenault5faa6692013-08-26 23:29:33 +0000513 VectorType *VecTy = dyn_cast<VectorType>(V->getType());
514 if (!VecTy) {
515 unsigned BitWidth = V->getType()->getIntegerBitWidth();
516 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +0000517 computeKnownBits(V, KnownZero, KnownOne, DL, 0, AC,
518 dyn_cast<Instruction>(V), DT);
Matt Arsenault5faa6692013-08-26 23:29:33 +0000519 return KnownZero.isAllOnesValue();
520 }
521
522 // Per-component check doesn't work with zeroinitializer
523 Constant *C = dyn_cast<Constant>(V);
524 if (!C)
525 return false;
526
527 if (C->isZeroValue())
528 return true;
529
530 // For a vector, KnownZero will only be true if all values are zero, so check
531 // this per component
532 unsigned BitWidth = VecTy->getElementType()->getIntegerBitWidth();
533 for (unsigned I = 0, N = VecTy->getNumElements(); I != N; ++I) {
534 Constant *Elem = C->getAggregateElement(I);
535 if (isa<UndefValue>(Elem))
536 return true;
537
538 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Jay Foada0653a32014-05-14 21:14:37 +0000539 computeKnownBits(Elem, KnownZero, KnownOne, DL);
Matt Arsenault5faa6692013-08-26 23:29:33 +0000540 if (KnownZero.isAllOnesValue())
541 return true;
542 }
543
544 return false;
Dan Gohman98bc4372010-04-08 18:47:09 +0000545}
546
547void Lint::visitSDiv(BinaryOperator &I) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000548 Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000549 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000550}
551
552void Lint::visitUDiv(BinaryOperator &I) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000553 Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000554 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000555}
556
557void Lint::visitSRem(BinaryOperator &I) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000558 Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000559 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000560}
561
562void Lint::visitURem(BinaryOperator &I) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000563 Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000564 "Undefined behavior: Division by zero", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000565}
566
567void Lint::visitAllocaInst(AllocaInst &I) {
568 if (isa<ConstantInt>(I.getArraySize()))
569 // This isn't undefined behavior, it's just an obvious pessimization.
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000570 Assert(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
571 "Pessimization: Static alloca outside of entry block", &I);
Dan Gohman1e33b182010-07-06 15:23:00 +0000572
573 // TODO: Check for an unusual size (MSB set?)
Dan Gohman98bc4372010-04-08 18:47:09 +0000574}
575
576void Lint::visitVAArgInst(VAArgInst &I) {
Chandler Carruthecbd1682015-06-17 07:21:38 +0000577 visitMemoryReference(I, I.getOperand(0), MemoryLocation::UnknownSize, 0,
Craig Topper9f008862014-04-15 04:59:12 +0000578 nullptr, MemRef::Read | MemRef::Write);
Dan Gohman98bc4372010-04-08 18:47:09 +0000579}
580
581void Lint::visitIndirectBrInst(IndirectBrInst &I) {
Chandler Carruthecbd1682015-06-17 07:21:38 +0000582 visitMemoryReference(I, I.getAddress(), MemoryLocation::UnknownSize, 0,
Craig Topper9f008862014-04-15 04:59:12 +0000583 nullptr, MemRef::Branchee);
Dan Gohmand8968da2010-08-02 23:06:43 +0000584
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000585 Assert(I.getNumDestinations() != 0,
586 "Undefined behavior: indirectbr with no destinations", &I);
Dan Gohman98bc4372010-04-08 18:47:09 +0000587}
588
Dan Gohman7808d492010-04-08 23:05:57 +0000589void Lint::visitExtractElementInst(ExtractElementInst &I) {
Chandler Carruth50fee932015-08-06 02:05:46 +0000590 if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
591 /*OffsetOk=*/false)))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000592 Assert(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
593 "Undefined result: extractelement index out of range", &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000594}
595
596void Lint::visitInsertElementInst(InsertElementInst &I) {
Chandler Carruth50fee932015-08-06 02:05:46 +0000597 if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(2),
598 /*OffsetOk=*/false)))
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000599 Assert(CI->getValue().ult(I.getType()->getNumElements()),
600 "Undefined result: insertelement index out of range", &I);
Dan Gohman9ba08a42010-04-09 01:39:53 +0000601}
602
603void Lint::visitUnreachableInst(UnreachableInst &I) {
604 // This isn't undefined behavior, it's merely suspicious.
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000605 Assert(&I == &I.getParent()->front() ||
606 std::prev(I.getIterator())->mayHaveSideEffects(),
Benjamin Kramerf027ad72015-03-07 21:15:40 +0000607 "Unusual: unreachable immediately preceded by instruction without "
608 "side effects",
609 &I);
Dan Gohman7808d492010-04-08 23:05:57 +0000610}
611
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000612/// findValue - Look through bitcasts and simple memory reference patterns
613/// to identify an equivalent, but more informative, value. If OffsetOk
614/// is true, look through getelementptrs with non-zero offsets too.
615///
616/// Most analysis passes don't require this logic, because instcombine
617/// will simplify most of these kinds of things away. But it's a goal of
618/// this Lint pass to be useful even on non-optimized IR.
Chandler Carruth50fee932015-08-06 02:05:46 +0000619Value *Lint::findValue(Value *V, bool OffsetOk) const {
Dan Gohman862f0342010-05-28 16:45:33 +0000620 SmallPtrSet<Value *, 4> Visited;
Chandler Carruth50fee932015-08-06 02:05:46 +0000621 return findValueImpl(V, OffsetOk, Visited);
Dan Gohman862f0342010-05-28 16:45:33 +0000622}
623
624/// findValueImpl - Implementation helper for findValue.
Chandler Carruth50fee932015-08-06 02:05:46 +0000625Value *Lint::findValueImpl(Value *V, bool OffsetOk,
Craig Topper71b7b682014-08-21 05:55:13 +0000626 SmallPtrSetImpl<Value *> &Visited) const {
Dan Gohman862f0342010-05-28 16:45:33 +0000627 // Detect self-referential values.
David Blaikie70573dc2014-11-19 07:49:26 +0000628 if (!Visited.insert(V).second)
Dan Gohman862f0342010-05-28 16:45:33 +0000629 return UndefValue::get(V->getType());
630
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000631 // TODO: Look through sext or zext cast, when the result is known to
632 // be interpreted as signed or unsigned, respectively.
Dan Gohman0fa67e42010-05-28 21:43:57 +0000633 // TODO: Look through eliminable cast pairs.
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000634 // TODO: Look through calls with unique return values.
635 // TODO: Look through vector insert/extract/shuffle.
Chandler Carruth50fee932015-08-06 02:05:46 +0000636 V = OffsetOk ? GetUnderlyingObject(V, *DL) : V->stripPointerCasts();
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000637 if (LoadInst *L = dyn_cast<LoadInst>(V)) {
Duncan P. N. Exon Smith5a82c912015-10-10 00:53:03 +0000638 BasicBlock::iterator BBI = L->getIterator();
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000639 BasicBlock *BB = L->getParent();
Dan Gohmanc575ec62010-05-28 17:44:00 +0000640 SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000641 for (;;) {
David Blaikie70573dc2014-11-19 07:49:26 +0000642 if (!VisitedBlocks.insert(BB).second)
643 break;
Larisse Voufo532bf712015-09-18 19:14:35 +0000644 if (Value *U =
645 FindAvailableLoadedValue(L->getPointerOperand(),
646 BB, BBI, DefMaxInstsToScan, AA))
Chandler Carruth50fee932015-08-06 02:05:46 +0000647 return findValueImpl(U, OffsetOk, Visited);
Dan Gohmanc575ec62010-05-28 17:44:00 +0000648 if (BBI != BB->begin()) break;
649 BB = BB->getUniquePredecessor();
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000650 if (!BB) break;
651 BBI = BB->end();
652 }
Dan Gohman0fa67e42010-05-28 21:43:57 +0000653 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000654 if (Value *W = PN->hasConstantValue())
Duncan Sandsec7a6ec2010-11-17 10:23:23 +0000655 if (W != V)
Chandler Carruth50fee932015-08-06 02:05:46 +0000656 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000657 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
Chandler Carruth50fee932015-08-06 02:05:46 +0000658 if (CI->isNoopCast(*DL))
659 return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000660 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
661 if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
Jay Foad57aa6362011-07-13 10:26:04 +0000662 Ex->getIndices()))
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000663 if (W != V)
Chandler Carruth50fee932015-08-06 02:05:46 +0000664 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000665 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
666 // Same as above, but for ConstantExpr instead of Instruction.
667 if (Instruction::isCast(CE->getOpcode())) {
668 if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000669 CE->getOperand(0)->getType(), CE->getType(),
Chandler Carruth50fee932015-08-06 02:05:46 +0000670 DL->getIntPtrType(V->getType())))
671 return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000672 } else if (CE->getOpcode() == Instruction::ExtractValue) {
Jay Foad0091fe82011-04-13 15:22:40 +0000673 ArrayRef<unsigned> Indices = CE->getIndices();
Jay Foad57aa6362011-07-13 10:26:04 +0000674 if (Value *W = FindInsertedValue(CE->getOperand(0), Indices))
Dan Gohman0fa67e42010-05-28 21:43:57 +0000675 if (W != V)
Chandler Carruth50fee932015-08-06 02:05:46 +0000676 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman0fa67e42010-05-28 21:43:57 +0000677 }
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000678 }
679
680 // As a last resort, try SimplifyInstruction or constant folding.
681 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Chandler Carruth50fee932015-08-06 02:05:46 +0000682 if (Value *W = SimplifyInstruction(Inst, *DL, TLI, DT, AC))
683 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000684 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Chandler Carruth50fee932015-08-06 02:05:46 +0000685 if (Value *W = ConstantFoldConstantExpression(CE, *DL, TLI))
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000686 if (W != V)
Chandler Carruth50fee932015-08-06 02:05:46 +0000687 return findValueImpl(W, OffsetOk, Visited);
Dan Gohman54d7aaa2010-05-28 16:21:24 +0000688 }
689
690 return V;
691}
692
Dan Gohman98bc4372010-04-08 18:47:09 +0000693//===----------------------------------------------------------------------===//
694// Implement the public interfaces to this file...
695//===----------------------------------------------------------------------===//
696
697FunctionPass *llvm::createLintPass() {
698 return new Lint();
699}
700
701/// lintFunction - Check a function for errors, printing messages on stderr.
702///
703void llvm::lintFunction(const Function &f) {
704 Function &F = const_cast<Function&>(f);
705 assert(!F.isDeclaration() && "Cannot lint external functions");
706
Chandler Carruth30d69c22015-02-13 10:01:29 +0000707 legacy::FunctionPassManager FPM(F.getParent());
Dan Gohman98bc4372010-04-08 18:47:09 +0000708 Lint *V = new Lint();
709 FPM.add(V);
710 FPM.run(F);
711}
712
713/// lintModule - Check a module for errors, printing messages on stderr.
Dan Gohman98bc4372010-04-08 18:47:09 +0000714///
Dan Gohman084bcb12010-05-26 22:28:53 +0000715void llvm::lintModule(const Module &M) {
Chandler Carruth30d69c22015-02-13 10:01:29 +0000716 legacy::PassManager PM;
Dan Gohman98bc4372010-04-08 18:47:09 +0000717 Lint *V = new Lint();
718 PM.add(V);
719 PM.run(const_cast<Module&>(M));
Dan Gohman98bc4372010-04-08 18:47:09 +0000720}