blob: 5d0a627f842629ef0feb16f4875d91fbb1b9fb8c [file] [log] [blame]
Dan Gohman113902e2010-04-08 18:47:09 +00001//===-- Lint.cpp - Check for common errors in LLVM IR ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass statically checks for common and easily-identified constructs
11// which produce undefined or likely unintended behavior in LLVM IR.
12//
13// It is not a guarantee of correctness, in two ways. First, it isn't
14// comprehensive. There are checks which could be done statically which are
15// not yet implemented. Some of these are indicated by TODO comments, but
16// those aren't comprehensive either. Second, many conditions cannot be
17// checked statically. This pass does no dynamic instrumentation, so it
18// can't check for all possible problems.
Matt Arsenault38c18ef2014-03-06 17:33:55 +000019//
Dan Gohman113902e2010-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 Gohmand3b6e412010-07-06 15:21:57 +000022// but this pass will warn about it anyway. This is the main reason why most
23// of these checks live here instead of in the Verifier pass.
Dan Gohman08833552010-04-22 01:30:05 +000024//
Dan Gohman113902e2010-04-08 18:47:09 +000025// Optimization passes may make conditions that this pass checks for more or
26// less obvious. If an optimization pass appears to be introducing a warning,
27// it may be that the optimization pass is merely exposing an existing
28// condition in the code.
Matt Arsenault38c18ef2014-03-06 17:33:55 +000029//
Dan Gohman113902e2010-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 Arsenault38c18ef2014-03-06 17:33:55 +000034//
Dan Gohman113902e2010-04-08 18:47:09 +000035//===----------------------------------------------------------------------===//
36
Chandler Carruthd04a8d42012-12-03 16:50:05 +000037#include "llvm/Analysis/Lint.h"
Eugene Zelenko82d16ec2016-08-13 00:50:41 +000038#include "llvm/ADT/APInt.h"
39#include "llvm/ADT/ArrayRef.h"
40#include "llvm/ADT/SmallPtrSet.h"
41#include "llvm/ADT/Twine.h"
Dan Gohman113902e2010-04-08 18:47:09 +000042#include "llvm/Analysis/AliasAnalysis.h"
Daniel Jasper8de3a542016-12-19 08:22:17 +000043#include "llvm/Analysis/AssumptionCache.h"
Dan Gohmanff26d4e2010-05-28 16:21:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000045#include "llvm/Analysis/InstructionSimplify.h"
Dan Gohmanff26d4e2010-05-28 16:21:24 +000046#include "llvm/Analysis/Loads.h"
Eugene Zelenko82d16ec2016-08-13 00:50:41 +000047#include "llvm/Analysis/MemoryLocation.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000048#include "llvm/Analysis/Passes.h"
Chandler Carruthbda13492015-01-15 02:16:27 +000049#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman113902e2010-04-08 18:47:09 +000050#include "llvm/Analysis/ValueTracking.h"
Eugene Zelenko82d16ec2016-08-13 00:50:41 +000051#include "llvm/IR/Argument.h"
52#include "llvm/IR/BasicBlock.h"
Chandler Carruth4bbfbdf2014-03-04 11:01:28 +000053#include "llvm/IR/CallSite.h"
Eugene Zelenko82d16ec2016-08-13 00:50:41 +000054#include "llvm/IR/Constant.h"
55#include "llvm/IR/Constants.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000056#include "llvm/IR/DataLayout.h"
Eugene Zelenko82d16ec2016-08-13 00:50:41 +000057#include "llvm/IR/DerivedTypes.h"
Chandler Carruth56e13942014-01-13 09:26:24 +000058#include "llvm/IR/Dominators.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000059#include "llvm/IR/Function.h"
Eugene Zelenko82d16ec2016-08-13 00:50:41 +000060#include "llvm/IR/GlobalVariable.h"
Chandler Carruth67f6bf72014-03-06 03:23:41 +000061#include "llvm/IR/InstVisitor.h"
Eugene Zelenko82d16ec2016-08-13 00:50:41 +000062#include "llvm/IR/InstrTypes.h"
63#include "llvm/IR/Instruction.h"
64#include "llvm/IR/Instructions.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000065#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth417c5c12015-02-13 10:01:29 +000066#include "llvm/IR/LegacyPassManager.h"
Chandler Carruthe3e43d92017-06-06 11:49:48 +000067#include "llvm/IR/Module.h"
Eugene Zelenko82d16ec2016-08-13 00:50:41 +000068#include "llvm/IR/Type.h"
69#include "llvm/IR/Value.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000070#include "llvm/Pass.h"
Eugene Zelenko82d16ec2016-08-13 00:50:41 +000071#include "llvm/Support/Casting.h"
Dan Gohman113902e2010-04-08 18:47:09 +000072#include "llvm/Support/Debug.h"
Craig Topper58c7fe62017-04-26 16:39:58 +000073#include "llvm/Support/KnownBits.h"
Eugene Zelenko82d16ec2016-08-13 00:50:41 +000074#include "llvm/Support/MathExtras.h"
Dan Gohman113902e2010-04-08 18:47:09 +000075#include "llvm/Support/raw_ostream.h"
Eugene Zelenko82d16ec2016-08-13 00:50:41 +000076#include <cassert>
77#include <cstdint>
78#include <iterator>
79#include <string>
80
Dan Gohman113902e2010-04-08 18:47:09 +000081using namespace llvm;
82
83namespace {
Dan Gohman5b61b382010-04-30 19:05:00 +000084 namespace MemRef {
Benjamin Kramerc8a95a82015-03-08 16:07:39 +000085 static const unsigned Read = 1;
86 static const unsigned Write = 2;
87 static const unsigned Callee = 4;
88 static const unsigned Branchee = 8;
Eugene Zelenko82d16ec2016-08-13 00:50:41 +000089 } // end namespace MemRef
Dan Gohman5b61b382010-04-30 19:05:00 +000090
Dan Gohman113902e2010-04-08 18:47:09 +000091 class Lint : public FunctionPass, public InstVisitor<Lint> {
92 friend class InstVisitor<Lint>;
93
Dan Gohmanbe02b202010-04-09 01:39:53 +000094 void visitFunction(Function &F);
95
Dan Gohman113902e2010-04-08 18:47:09 +000096 void visitCallSite(CallSite CS);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +000097 void visitMemoryReference(Instruction &I, Value *Ptr,
Dan Gohman3da848b2010-10-19 22:54:46 +000098 uint64_t Size, unsigned Align,
Chris Lattnerdb125cf2011-07-18 04:54:35 +000099 Type *Ty, unsigned Flags);
Andrew Kaylor77418512015-02-10 19:52:43 +0000100 void visitEHBeginCatch(IntrinsicInst *II);
101 void visitEHEndCatch(IntrinsicInst *II);
Dan Gohman113902e2010-04-08 18:47:09 +0000102
Dan Gohman113902e2010-04-08 18:47:09 +0000103 void visitCallInst(CallInst &I);
104 void visitInvokeInst(InvokeInst &I);
105 void visitReturnInst(ReturnInst &I);
106 void visitLoadInst(LoadInst &I);
107 void visitStoreInst(StoreInst &I);
Dan Gohmanbe02b202010-04-09 01:39:53 +0000108 void visitXor(BinaryOperator &I);
109 void visitSub(BinaryOperator &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000110 void visitLShr(BinaryOperator &I);
111 void visitAShr(BinaryOperator &I);
112 void visitShl(BinaryOperator &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000113 void visitSDiv(BinaryOperator &I);
114 void visitUDiv(BinaryOperator &I);
115 void visitSRem(BinaryOperator &I);
116 void visitURem(BinaryOperator &I);
117 void visitAllocaInst(AllocaInst &I);
118 void visitVAArgInst(VAArgInst &I);
119 void visitIndirectBrInst(IndirectBrInst &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000120 void visitExtractElementInst(ExtractElementInst &I);
121 void visitInsertElementInst(InsertElementInst &I);
Dan Gohmanbe02b202010-04-09 01:39:53 +0000122 void visitUnreachableInst(UnreachableInst &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000123
Chandler Carruthda530042015-08-06 02:05:46 +0000124 Value *findValue(Value *V, bool OffsetOk) const;
125 Value *findValueImpl(Value *V, bool OffsetOk,
Craig Topper431bdfc2014-08-21 05:55:13 +0000126 SmallPtrSetImpl<Value *> &Visited) const;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000127
Dan Gohman113902e2010-04-08 18:47:09 +0000128 public:
129 Module *Mod;
Chandler Carruthda530042015-08-06 02:05:46 +0000130 const DataLayout *DL;
Dan Gohman113902e2010-04-08 18:47:09 +0000131 AliasAnalysis *AA;
Daniel Jasper8de3a542016-12-19 08:22:17 +0000132 AssumptionCache *AC;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000133 DominatorTree *DT;
Chad Rosier618c1db2011-12-01 03:08:23 +0000134 TargetLibraryInfo *TLI;
Dan Gohman113902e2010-04-08 18:47:09 +0000135
Alp Toker8dd8d5c2014-06-26 22:52:05 +0000136 std::string Messages;
137 raw_string_ostream MessagesStr;
Dan Gohman113902e2010-04-08 18:47:09 +0000138
139 static char ID; // Pass identification, replacement for typeid
Alp Toker8dd8d5c2014-06-26 22:52:05 +0000140 Lint() : FunctionPass(ID), MessagesStr(Messages) {
Owen Anderson081c34b2010-10-19 17:21:58 +0000141 initializeLintPass(*PassRegistry::getPassRegistry());
142 }
Dan Gohman113902e2010-04-08 18:47:09 +0000143
Craig Topperc37e6c02014-03-05 07:30:04 +0000144 bool runOnFunction(Function &F) override;
Dan Gohman113902e2010-04-08 18:47:09 +0000145
Craig Topperc37e6c02014-03-05 07:30:04 +0000146 void getAnalysisUsage(AnalysisUsage &AU) const override {
Dan Gohman113902e2010-04-08 18:47:09 +0000147 AU.setPreservesAll();
Chandler Carruth91468332015-09-09 17:55:00 +0000148 AU.addRequired<AAResultsWrapperPass>();
Daniel Jasper8de3a542016-12-19 08:22:17 +0000149 AU.addRequired<AssumptionCacheTracker>();
Chandler Carrutheeeec3c2015-01-15 10:41:28 +0000150 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth7f2eff72014-01-13 13:07:17 +0000151 AU.addRequired<DominatorTreeWrapperPass>();
Dan Gohman113902e2010-04-08 18:47:09 +0000152 }
Craig Topperc37e6c02014-03-05 07:30:04 +0000153 void print(raw_ostream &O, const Module *M) const override {}
Dan Gohman113902e2010-04-08 18:47:09 +0000154
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000155 void WriteValues(ArrayRef<const Value *> Vs) {
156 for (const Value *V : Vs) {
157 if (!V)
158 continue;
159 if (isa<Instruction>(V)) {
160 MessagesStr << *V << '\n';
161 } else {
162 V->printAsOperand(MessagesStr, true, Mod);
163 MessagesStr << '\n';
164 }
Dan Gohman113902e2010-04-08 18:47:09 +0000165 }
166 }
167
Adrian Prantl26b584c2018-05-01 15:54:18 +0000168 /// A check failed, so printout out the condition and the message.
Duncan P. N. Exon Smitha7189672015-03-16 17:49:03 +0000169 ///
170 /// This provides a nice place to put a breakpoint if you want to see why
171 /// something is not correct.
Duncan P. N. Exon Smithf141a552015-03-14 16:47:37 +0000172 void CheckFailed(const Twine &Message) { MessagesStr << Message << '\n'; }
173
Adrian Prantl26b584c2018-05-01 15:54:18 +0000174 /// A check failed (with values to print).
Duncan P. N. Exon Smitha7189672015-03-16 17:49:03 +0000175 ///
176 /// This calls the Message-only version so that the above is easier to set
177 /// a breakpoint on.
Duncan P. N. Exon Smithf141a552015-03-14 16:47:37 +0000178 template <typename T1, typename... Ts>
179 void CheckFailed(const Twine &Message, const T1 &V1, const Ts &...Vs) {
180 CheckFailed(Message);
181 WriteValues({V1, Vs...});
Dan Gohman113902e2010-04-08 18:47:09 +0000182 }
Dan Gohman113902e2010-04-08 18:47:09 +0000183 };
Eugene Zelenko82d16ec2016-08-13 00:50:41 +0000184} // end anonymous namespace
Dan Gohman113902e2010-04-08 18:47:09 +0000185
186char Lint::ID = 0;
Owen Anderson2ab36d32010-10-12 19:48:12 +0000187INITIALIZE_PASS_BEGIN(Lint, "lint", "Statically lint-checks LLVM IR",
188 false, true)
Daniel Jasper8de3a542016-12-19 08:22:17 +0000189INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carrutheeeec3c2015-01-15 10:41:28 +0000190INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Chandler Carruth7f2eff72014-01-13 13:07:17 +0000191INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chandler Carruth91468332015-09-09 17:55:00 +0000192INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Owen Anderson2ab36d32010-10-12 19:48:12 +0000193INITIALIZE_PASS_END(Lint, "lint", "Statically lint-checks LLVM IR",
194 false, true)
Dan Gohman113902e2010-04-08 18:47:09 +0000195
196// Assert - We know that cond should be true, if not print an error message.
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000197#define Assert(C, ...) \
Eugene Zelenko82d16ec2016-08-13 00:50:41 +0000198 do { if (!(C)) { CheckFailed(__VA_ARGS__); return; } } while (false)
Dan Gohman113902e2010-04-08 18:47:09 +0000199
200// Lint::run - This is the main Analysis entry point for a
201// function.
202//
203bool Lint::runOnFunction(Function &F) {
204 Mod = F.getParent();
Chandler Carruthda530042015-08-06 02:05:46 +0000205 DL = &F.getParent()->getDataLayout();
Chandler Carruth91468332015-09-09 17:55:00 +0000206 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Daniel Jasper8de3a542016-12-19 08:22:17 +0000207 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chandler Carruth7f2eff72014-01-13 13:07:17 +0000208 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carrutheeeec3c2015-01-15 10:41:28 +0000209 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Dan Gohman113902e2010-04-08 18:47:09 +0000210 visit(F);
211 dbgs() << MessagesStr.str();
Alp Toker8dd8d5c2014-06-26 22:52:05 +0000212 Messages.clear();
Dan Gohman113902e2010-04-08 18:47:09 +0000213 return false;
214}
215
Dan Gohmanbe02b202010-04-09 01:39:53 +0000216void Lint::visitFunction(Function &F) {
217 // This isn't undefined behavior, it's just a little unusual, and it's a
218 // fairly common mistake to neglect to name a function.
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000219 Assert(F.hasName() || F.hasLocalLinkage(),
220 "Unusual: Unnamed function with non-local linkage", &F);
Dan Gohman0ce24992010-07-06 15:23:00 +0000221
222 // TODO: Check for irreducible control flow.
Dan Gohman113902e2010-04-08 18:47:09 +0000223}
224
225void Lint::visitCallSite(CallSite CS) {
226 Instruction &I = *CS.getInstruction();
227 Value *Callee = CS.getCalledValue();
228
Chandler Carruth2cdca0c42015-06-17 07:21:38 +0000229 visitMemoryReference(I, Callee, MemoryLocation::UnknownSize, 0, nullptr,
230 MemRef::Callee);
Dan Gohman113902e2010-04-08 18:47:09 +0000231
Chandler Carruthda530042015-08-06 02:05:46 +0000232 if (Function *F = dyn_cast<Function>(findValue(Callee,
Mehdi Amini529919f2015-03-10 02:37:25 +0000233 /*OffsetOk=*/false))) {
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000234 Assert(CS.getCallingConv() == F->getCallingConv(),
235 "Undefined behavior: Caller and callee calling convention differ",
236 &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000237
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000238 FunctionType *FT = F->getFunctionType();
Matt Arsenault20f1fe52013-11-10 03:18:50 +0000239 unsigned NumActualArgs = CS.arg_size();
Dan Gohman113902e2010-04-08 18:47:09 +0000240
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000241 Assert(FT->isVarArg() ? FT->getNumParams() <= NumActualArgs
242 : FT->getNumParams() == NumActualArgs,
243 "Undefined behavior: Call argument count mismatches callee "
244 "argument count",
245 &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000246
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000247 Assert(FT->getReturnType() == I.getType(),
248 "Undefined behavior: Call return type mismatches "
249 "callee return type",
250 &I);
Dan Gohman545d0062010-07-12 18:02:04 +0000251
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000252 // Check argument types (in case the callee was casted) and attributes.
Dan Gohman0ce24992010-07-06 15:23:00 +0000253 // TODO: Verify that caller and callee attributes are compatible.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000254 Function::arg_iterator PI = F->arg_begin(), PE = F->arg_end();
255 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
256 for (; AI != AE; ++AI) {
257 Value *Actual = *AI;
258 if (PI != PE) {
Duncan P. N. Exon Smithd3a5adc2015-10-10 00:53:03 +0000259 Argument *Formal = &*PI++;
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000260 Assert(Formal->getType() == Actual->getType(),
261 "Undefined behavior: Call argument type mismatches "
262 "callee parameter type",
263 &I);
Dan Gohman10e77262010-06-01 20:51:40 +0000264
Dan Gohmanc1f1efd2010-12-13 22:53:18 +0000265 // Check that noalias arguments don't alias other arguments. This is
266 // not fully precise because we don't know the sizes of the dereferenced
267 // memory regions.
Mikael Holmene7f98a92017-12-27 08:48:33 +0000268 if (Formal->hasNoAliasAttr() && Actual->getType()->isPointerTy()) {
269 AttributeList PAL = CS.getAttributes();
270 unsigned ArgNo = 0;
271 for (CallSite::arg_iterator BI = CS.arg_begin(); BI != AE; ++BI) {
272 // Skip ByVal arguments since they will be memcpy'd to the callee's
273 // stack so we're not really passing the pointer anyway.
274 if (PAL.hasParamAttribute(ArgNo++, Attribute::ByVal))
275 continue;
Dan Gohman4a2a3ea2010-12-10 20:04:06 +0000276 if (AI != BI && (*BI)->getType()->isPointerTy()) {
Chandler Carruth1e3557d2015-06-22 02:16:51 +0000277 AliasResult Result = AA->alias(*AI, *BI);
278 Assert(Result != MustAlias && Result != PartialAlias,
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000279 "Unusual: noalias argument aliases another argument", &I);
Dan Gohman4a2a3ea2010-12-10 20:04:06 +0000280 }
Mikael Holmene7f98a92017-12-27 08:48:33 +0000281 }
282 }
Dan Gohman10e77262010-06-01 20:51:40 +0000283
284 // Check that an sret argument points to valid memory.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000285 if (Formal->hasStructRetAttr() && Actual->getType()->isPointerTy()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000286 Type *Ty =
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000287 cast<PointerType>(Formal->getType())->getElementType();
Chandler Carruthda530042015-08-06 02:05:46 +0000288 visitMemoryReference(I, Actual, DL->getTypeStoreSize(Ty),
289 DL->getABITypeAlignment(Ty), Ty,
Mehdi Amini529919f2015-03-10 02:37:25 +0000290 MemRef::Read | MemRef::Write);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000291 }
292 }
293 }
Dan Gohman113902e2010-04-08 18:47:09 +0000294 }
295
Mikael Holmenc14b5c32017-11-15 07:46:48 +0000296 if (CS.isCall()) {
297 const CallInst *CI = cast<CallInst>(CS.getInstruction());
298 if (CI->isTailCall()) {
299 const AttributeList &PAL = CI->getAttributes();
300 unsigned ArgNo = 0;
301 for (Value *Arg : CS.args()) {
302 // Skip ByVal arguments since they will be memcpy'd to the callee's
303 // stack anyway.
304 if (PAL.hasParamAttribute(ArgNo++, Attribute::ByVal))
305 continue;
306 Value *Obj = findValue(Arg, /*OffsetOk=*/true);
307 Assert(!isa<AllocaInst>(Obj),
308 "Undefined behavior: Call with \"tail\" keyword references "
309 "alloca",
310 &I);
311 }
Dan Gohman113b3e22010-05-26 21:46:36 +0000312 }
Mikael Holmenc14b5c32017-11-15 07:46:48 +0000313 }
Dan Gohman113b3e22010-05-26 21:46:36 +0000314
Dan Gohman113902e2010-04-08 18:47:09 +0000315
316 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I))
317 switch (II->getIntrinsicID()) {
318 default: break;
319
320 // TODO: Check more intrinsics
321
322 case Intrinsic::memcpy: {
323 MemCpyInst *MCI = cast<MemCpyInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000324 // TODO: If the size is known, use it.
Chandler Carruth2cdca0c42015-06-17 07:21:38 +0000325 visitMemoryReference(I, MCI->getDest(), MemoryLocation::UnknownSize,
Daniel Neilson8ff1aed2018-01-31 16:42:15 +0000326 MCI->getDestAlignment(), nullptr, MemRef::Write);
Chandler Carruth2cdca0c42015-06-17 07:21:38 +0000327 visitMemoryReference(I, MCI->getSource(), MemoryLocation::UnknownSize,
Daniel Neilson8ff1aed2018-01-31 16:42:15 +0000328 MCI->getSourceAlignment(), nullptr, MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000329
Dan Gohmanbe02b202010-04-09 01:39:53 +0000330 // Check that the memcpy arguments don't overlap. The AliasAnalysis API
331 // isn't expressive enough for what we really want to do. Known partial
332 // overlap is not distinguished from the case where nothing is known.
George Burgess IV1a44b0b2018-12-23 02:50:08 +0000333 auto Size = LocationSize::unknown();
Dan Gohman113902e2010-04-08 18:47:09 +0000334 if (const ConstantInt *Len =
Chandler Carruthda530042015-08-06 02:05:46 +0000335 dyn_cast<ConstantInt>(findValue(MCI->getLength(),
Mehdi Amini529919f2015-03-10 02:37:25 +0000336 /*OffsetOk=*/false)))
Dan Gohman113902e2010-04-08 18:47:09 +0000337 if (Len->getValue().isIntN(32))
George Burgess IV1a44b0b2018-12-23 02:50:08 +0000338 Size = LocationSize::precise(Len->getValue().getZExtValue());
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000339 Assert(AA->alias(MCI->getSource(), Size, MCI->getDest(), Size) !=
Chandler Carruth1e3557d2015-06-22 02:16:51 +0000340 MustAlias,
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000341 "Undefined behavior: memcpy source and destination overlap", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000342 break;
343 }
344 case Intrinsic::memmove: {
345 MemMoveInst *MMI = cast<MemMoveInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000346 // TODO: If the size is known, use it.
Chandler Carruth2cdca0c42015-06-17 07:21:38 +0000347 visitMemoryReference(I, MMI->getDest(), MemoryLocation::UnknownSize,
Daniel Neilson8ff1aed2018-01-31 16:42:15 +0000348 MMI->getDestAlignment(), nullptr, MemRef::Write);
Chandler Carruth2cdca0c42015-06-17 07:21:38 +0000349 visitMemoryReference(I, MMI->getSource(), MemoryLocation::UnknownSize,
Daniel Neilson8ff1aed2018-01-31 16:42:15 +0000350 MMI->getSourceAlignment(), nullptr, MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000351 break;
352 }
353 case Intrinsic::memset: {
354 MemSetInst *MSI = cast<MemSetInst>(&I);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000355 // TODO: If the size is known, use it.
Chandler Carruth2cdca0c42015-06-17 07:21:38 +0000356 visitMemoryReference(I, MSI->getDest(), MemoryLocation::UnknownSize,
Daniel Neilson8ff1aed2018-01-31 16:42:15 +0000357 MSI->getDestAlignment(), nullptr, MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000358 break;
359 }
360
361 case Intrinsic::vastart:
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000362 Assert(I.getParent()->getParent()->isVarArg(),
363 "Undefined behavior: va_start called in a non-varargs function",
364 &I);
Dan Gohmanbe02b202010-04-09 01:39:53 +0000365
Chandler Carruth2cdca0c42015-06-17 07:21:38 +0000366 visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
367 nullptr, MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000368 break;
369 case Intrinsic::vacopy:
Chandler Carruth2cdca0c42015-06-17 07:21:38 +0000370 visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
371 nullptr, MemRef::Write);
372 visitMemoryReference(I, CS.getArgument(1), MemoryLocation::UnknownSize, 0,
373 nullptr, MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000374 break;
375 case Intrinsic::vaend:
Chandler Carruth2cdca0c42015-06-17 07:21:38 +0000376 visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
377 nullptr, MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000378 break;
Dan Gohman882ddb42010-05-26 22:21:25 +0000379
380 case Intrinsic::stackrestore:
381 // Stackrestore doesn't read or write memory, but it sets the
382 // stack pointer, which the compiler may read from or write to
383 // at any time, so check it for both readability and writeability.
Chandler Carruth2cdca0c42015-06-17 07:21:38 +0000384 visitMemoryReference(I, CS.getArgument(0), MemoryLocation::UnknownSize, 0,
385 nullptr, MemRef::Read | MemRef::Write);
Dan Gohman882ddb42010-05-26 22:21:25 +0000386 break;
Dan Gohman113902e2010-04-08 18:47:09 +0000387 }
388}
389
390void Lint::visitCallInst(CallInst &I) {
391 return visitCallSite(&I);
392}
393
394void Lint::visitInvokeInst(InvokeInst &I) {
395 return visitCallSite(&I);
396}
397
398void Lint::visitReturnInst(ReturnInst &I) {
399 Function *F = I.getParent()->getParent();
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000400 Assert(!F->doesNotReturn(),
401 "Unusual: Return statement in function with noreturn attribute", &I);
Dan Gohman292fc872010-05-28 04:33:42 +0000402
403 if (Value *V = I.getReturnValue()) {
Chandler Carruthda530042015-08-06 02:05:46 +0000404 Value *Obj = findValue(V, /*OffsetOk=*/true);
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000405 Assert(!isa<AllocaInst>(Obj), "Unusual: Returning alloca value", &I);
Dan Gohman292fc872010-05-28 04:33:42 +0000406 }
Dan Gohman113902e2010-04-08 18:47:09 +0000407}
408
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000409// TODO: Check that the reference is in bounds.
Dan Gohman0ce24992010-07-06 15:23:00 +0000410// TODO: Check readnone/readonly function attributes.
Dan Gohman113902e2010-04-08 18:47:09 +0000411void Lint::visitMemoryReference(Instruction &I,
Dan Gohman3da848b2010-10-19 22:54:46 +0000412 Value *Ptr, uint64_t Size, unsigned Align,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000413 Type *Ty, unsigned Flags) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000414 // If no memory is being referenced, it doesn't matter if the pointer
415 // is valid.
416 if (Size == 0)
417 return;
418
Chandler Carruthda530042015-08-06 02:05:46 +0000419 Value *UnderlyingObject = findValue(Ptr, /*OffsetOk=*/true);
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000420 Assert(!isa<ConstantPointerNull>(UnderlyingObject),
421 "Undefined behavior: Null pointer dereference", &I);
422 Assert(!isa<UndefValue>(UnderlyingObject),
423 "Undefined behavior: Undef pointer dereference", &I);
424 Assert(!isa<ConstantInt>(UnderlyingObject) ||
Craig Topper6dbd34d2017-07-06 18:39:47 +0000425 !cast<ConstantInt>(UnderlyingObject)->isMinusOne(),
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000426 "Unusual: All-ones pointer dereference", &I);
427 Assert(!isa<ConstantInt>(UnderlyingObject) ||
428 !cast<ConstantInt>(UnderlyingObject)->isOne(),
429 "Unusual: Address one pointer dereference", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000430
Dan Gohman5b61b382010-04-30 19:05:00 +0000431 if (Flags & MemRef::Write) {
432 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(UnderlyingObject))
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000433 Assert(!GV->isConstant(), "Undefined behavior: Write to read-only memory",
434 &I);
435 Assert(!isa<Function>(UnderlyingObject) &&
436 !isa<BlockAddress>(UnderlyingObject),
437 "Undefined behavior: Write to text section", &I);
Dan Gohman5b61b382010-04-30 19:05:00 +0000438 }
439 if (Flags & MemRef::Read) {
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000440 Assert(!isa<Function>(UnderlyingObject), "Unusual: Load from function body",
441 &I);
442 Assert(!isa<BlockAddress>(UnderlyingObject),
443 "Undefined behavior: Load from block address", &I);
Dan Gohman5b61b382010-04-30 19:05:00 +0000444 }
445 if (Flags & MemRef::Callee) {
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000446 Assert(!isa<BlockAddress>(UnderlyingObject),
447 "Undefined behavior: Call to block address", &I);
Dan Gohman5b61b382010-04-30 19:05:00 +0000448 }
449 if (Flags & MemRef::Branchee) {
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000450 Assert(!isa<Constant>(UnderlyingObject) ||
451 isa<BlockAddress>(UnderlyingObject),
452 "Undefined behavior: Branch to non-blockaddress", &I);
Dan Gohman5b61b382010-04-30 19:05:00 +0000453 }
454
Duncan Sandsc7c42f72012-09-26 07:45:36 +0000455 // Check for buffer overflows and misalignment.
Dan Gohmana070d2a2013-01-31 02:00:45 +0000456 // Only handles memory references that read/write something simple like an
457 // alloca instruction or a global variable.
458 int64_t Offset = 0;
Chandler Carruthda530042015-08-06 02:05:46 +0000459 if (Value *Base = GetPointerBaseWithConstantOffset(Ptr, Offset, *DL)) {
Dan Gohmana070d2a2013-01-31 02:00:45 +0000460 // OK, so the access is to a constant offset from Ptr. Check that Ptr is
461 // something we can handle and if so extract the size of this base object
462 // along with its alignment.
Chandler Carruth2cdca0c42015-06-17 07:21:38 +0000463 uint64_t BaseSize = MemoryLocation::UnknownSize;
Dan Gohmana070d2a2013-01-31 02:00:45 +0000464 unsigned BaseAlign = 0;
Dan Gohman113902e2010-04-08 18:47:09 +0000465
Dan Gohmana070d2a2013-01-31 02:00:45 +0000466 if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
467 Type *ATy = AI->getAllocatedType();
Mehdi Amini529919f2015-03-10 02:37:25 +0000468 if (!AI->isArrayAllocation() && ATy->isSized())
Chandler Carruthda530042015-08-06 02:05:46 +0000469 BaseSize = DL->getTypeAllocSize(ATy);
Dan Gohmana070d2a2013-01-31 02:00:45 +0000470 BaseAlign = AI->getAlignment();
Mehdi Amini529919f2015-03-10 02:37:25 +0000471 if (BaseAlign == 0 && ATy->isSized())
Chandler Carruthda530042015-08-06 02:05:46 +0000472 BaseAlign = DL->getABITypeAlignment(ATy);
Dan Gohmana070d2a2013-01-31 02:00:45 +0000473 } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
474 // If the global may be defined differently in another compilation unit
475 // then don't warn about funky memory accesses.
476 if (GV->hasDefinitiveInitializer()) {
Manuel Jacob75e1cfb2016-01-16 20:30:46 +0000477 Type *GTy = GV->getValueType();
Mehdi Amini529919f2015-03-10 02:37:25 +0000478 if (GTy->isSized())
Chandler Carruthda530042015-08-06 02:05:46 +0000479 BaseSize = DL->getTypeAllocSize(GTy);
Dan Gohmana070d2a2013-01-31 02:00:45 +0000480 BaseAlign = GV->getAlignment();
Mehdi Amini529919f2015-03-10 02:37:25 +0000481 if (BaseAlign == 0 && GTy->isSized())
Chandler Carruthda530042015-08-06 02:05:46 +0000482 BaseAlign = DL->getABITypeAlignment(GTy);
Duncan Sands00edf4c2012-09-25 10:00:49 +0000483 }
Dan Gohman113902e2010-04-08 18:47:09 +0000484 }
Dan Gohmana070d2a2013-01-31 02:00:45 +0000485
486 // Accesses from before the start or after the end of the object are not
487 // defined.
Chandler Carruth2cdca0c42015-06-17 07:21:38 +0000488 Assert(Size == MemoryLocation::UnknownSize ||
489 BaseSize == MemoryLocation::UnknownSize ||
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000490 (Offset >= 0 && Offset + Size <= BaseSize),
491 "Undefined behavior: Buffer overflow", &I);
Dan Gohmana070d2a2013-01-31 02:00:45 +0000492
493 // Accesses that say that the memory is more aligned than it is are not
494 // defined.
Mehdi Amini529919f2015-03-10 02:37:25 +0000495 if (Align == 0 && Ty && Ty->isSized())
Chandler Carruthda530042015-08-06 02:05:46 +0000496 Align = DL->getABITypeAlignment(Ty);
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000497 Assert(!BaseAlign || Align <= MinAlign(BaseAlign, Offset),
498 "Undefined behavior: Memory reference address is misaligned", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000499 }
500}
501
502void Lint::visitLoadInst(LoadInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000503 visitMemoryReference(I, I.getPointerOperand(),
Chandler Carruthda530042015-08-06 02:05:46 +0000504 DL->getTypeStoreSize(I.getType()), I.getAlignment(),
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000505 I.getType(), MemRef::Read);
Dan Gohman113902e2010-04-08 18:47:09 +0000506}
507
508void Lint::visitStoreInst(StoreInst &I) {
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000509 visitMemoryReference(I, I.getPointerOperand(),
Chandler Carruthda530042015-08-06 02:05:46 +0000510 DL->getTypeStoreSize(I.getOperand(0)->getType()),
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000511 I.getAlignment(),
512 I.getOperand(0)->getType(), MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000513}
514
Dan Gohmanbe02b202010-04-09 01:39:53 +0000515void Lint::visitXor(BinaryOperator &I) {
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000516 Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
517 "Undefined result: xor(undef, undef)", &I);
Dan Gohmanbe02b202010-04-09 01:39:53 +0000518}
519
520void Lint::visitSub(BinaryOperator &I) {
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000521 Assert(!isa<UndefValue>(I.getOperand(0)) || !isa<UndefValue>(I.getOperand(1)),
522 "Undefined result: sub(undef, undef)", &I);
Dan Gohmanbe02b202010-04-09 01:39:53 +0000523}
524
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000525void Lint::visitLShr(BinaryOperator &I) {
Chandler Carruthda530042015-08-06 02:05:46 +0000526 if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(1),
527 /*OffsetOk=*/false)))
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000528 Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
529 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000530}
531
532void Lint::visitAShr(BinaryOperator &I) {
Chandler Carruthda530042015-08-06 02:05:46 +0000533 if (ConstantInt *CI =
534 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000535 Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
536 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000537}
538
539void Lint::visitShl(BinaryOperator &I) {
Chandler Carruthda530042015-08-06 02:05:46 +0000540 if (ConstantInt *CI =
541 dyn_cast<ConstantInt>(findValue(I.getOperand(1), /*OffsetOk=*/false)))
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000542 Assert(CI->getValue().ult(cast<IntegerType>(I.getType())->getBitWidth()),
543 "Undefined result: Shift count out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000544}
545
Daniel Jasper8de3a542016-12-19 08:22:17 +0000546static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT,
547 AssumptionCache *AC) {
Dan Gohmanbe02b202010-04-09 01:39:53 +0000548 // Assume undef could be zero.
Matt Arsenaulte3e5f772013-08-26 23:29:33 +0000549 if (isa<UndefValue>(V))
550 return true;
Dan Gohmanbe02b202010-04-09 01:39:53 +0000551
Matt Arsenaulte3e5f772013-08-26 23:29:33 +0000552 VectorType *VecTy = dyn_cast<VectorType>(V->getType());
553 if (!VecTy) {
Craig Toppere3a11162017-05-24 16:53:07 +0000554 KnownBits Known = computeKnownBits(V, DL, 0, AC, dyn_cast<Instruction>(V), DT);
Craig Topperace8b392017-05-05 17:36:09 +0000555 return Known.isZero();
Matt Arsenaulte3e5f772013-08-26 23:29:33 +0000556 }
557
558 // Per-component check doesn't work with zeroinitializer
559 Constant *C = dyn_cast<Constant>(V);
560 if (!C)
561 return false;
562
563 if (C->isZeroValue())
564 return true;
565
566 // For a vector, KnownZero will only be true if all values are zero, so check
567 // this per component
Matt Arsenaulte3e5f772013-08-26 23:29:33 +0000568 for (unsigned I = 0, N = VecTy->getNumElements(); I != N; ++I) {
569 Constant *Elem = C->getAggregateElement(I);
570 if (isa<UndefValue>(Elem))
571 return true;
572
Craig Toppere3a11162017-05-24 16:53:07 +0000573 KnownBits Known = computeKnownBits(Elem, DL);
Craig Topperace8b392017-05-05 17:36:09 +0000574 if (Known.isZero())
Matt Arsenaulte3e5f772013-08-26 23:29:33 +0000575 return true;
576 }
577
578 return false;
Dan Gohman113902e2010-04-08 18:47:09 +0000579}
580
581void Lint::visitSDiv(BinaryOperator &I) {
Daniel Jasper8de3a542016-12-19 08:22:17 +0000582 Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000583 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000584}
585
586void Lint::visitUDiv(BinaryOperator &I) {
Daniel Jasper8de3a542016-12-19 08:22:17 +0000587 Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000588 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000589}
590
591void Lint::visitSRem(BinaryOperator &I) {
Daniel Jasper8de3a542016-12-19 08:22:17 +0000592 Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000593 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000594}
595
596void Lint::visitURem(BinaryOperator &I) {
Daniel Jasper8de3a542016-12-19 08:22:17 +0000597 Assert(!isZero(I.getOperand(1), I.getModule()->getDataLayout(), DT, AC),
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000598 "Undefined behavior: Division by zero", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000599}
600
601void Lint::visitAllocaInst(AllocaInst &I) {
602 if (isa<ConstantInt>(I.getArraySize()))
603 // This isn't undefined behavior, it's just an obvious pessimization.
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000604 Assert(&I.getParent()->getParent()->getEntryBlock() == I.getParent(),
605 "Pessimization: Static alloca outside of entry block", &I);
Dan Gohman0ce24992010-07-06 15:23:00 +0000606
607 // TODO: Check for an unusual size (MSB set?)
Dan Gohman113902e2010-04-08 18:47:09 +0000608}
609
610void Lint::visitVAArgInst(VAArgInst &I) {
Chandler Carruth2cdca0c42015-06-17 07:21:38 +0000611 visitMemoryReference(I, I.getOperand(0), MemoryLocation::UnknownSize, 0,
Craig Topper570e52c2014-04-15 04:59:12 +0000612 nullptr, MemRef::Read | MemRef::Write);
Dan Gohman113902e2010-04-08 18:47:09 +0000613}
614
615void Lint::visitIndirectBrInst(IndirectBrInst &I) {
Chandler Carruth2cdca0c42015-06-17 07:21:38 +0000616 visitMemoryReference(I, I.getAddress(), MemoryLocation::UnknownSize, 0,
Craig Topper570e52c2014-04-15 04:59:12 +0000617 nullptr, MemRef::Branchee);
Dan Gohmana8afb2a2010-08-02 23:06:43 +0000618
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000619 Assert(I.getNumDestinations() != 0,
620 "Undefined behavior: indirectbr with no destinations", &I);
Dan Gohman113902e2010-04-08 18:47:09 +0000621}
622
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000623void Lint::visitExtractElementInst(ExtractElementInst &I) {
Chandler Carruthda530042015-08-06 02:05:46 +0000624 if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getIndexOperand(),
625 /*OffsetOk=*/false)))
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000626 Assert(CI->getValue().ult(I.getVectorOperandType()->getNumElements()),
627 "Undefined result: extractelement index out of range", &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000628}
629
630void Lint::visitInsertElementInst(InsertElementInst &I) {
Chandler Carruthda530042015-08-06 02:05:46 +0000631 if (ConstantInt *CI = dyn_cast<ConstantInt>(findValue(I.getOperand(2),
632 /*OffsetOk=*/false)))
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000633 Assert(CI->getValue().ult(I.getType()->getNumElements()),
634 "Undefined result: insertelement index out of range", &I);
Dan Gohmanbe02b202010-04-09 01:39:53 +0000635}
636
637void Lint::visitUnreachableInst(UnreachableInst &I) {
638 // This isn't undefined behavior, it's merely suspicious.
Duncan P. N. Exon Smithd3a5adc2015-10-10 00:53:03 +0000639 Assert(&I == &I.getParent()->front() ||
640 std::prev(I.getIterator())->mayHaveSideEffects(),
Benjamin Kramerfab98a42015-03-07 21:15:40 +0000641 "Unusual: unreachable immediately preceded by instruction without "
642 "side effects",
643 &I);
Dan Gohmandd98c4d2010-04-08 23:05:57 +0000644}
645
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000646/// findValue - Look through bitcasts and simple memory reference patterns
647/// to identify an equivalent, but more informative, value. If OffsetOk
648/// is true, look through getelementptrs with non-zero offsets too.
649///
650/// Most analysis passes don't require this logic, because instcombine
651/// will simplify most of these kinds of things away. But it's a goal of
652/// this Lint pass to be useful even on non-optimized IR.
Chandler Carruthda530042015-08-06 02:05:46 +0000653Value *Lint::findValue(Value *V, bool OffsetOk) const {
Dan Gohman17d95962010-05-28 16:45:33 +0000654 SmallPtrSet<Value *, 4> Visited;
Chandler Carruthda530042015-08-06 02:05:46 +0000655 return findValueImpl(V, OffsetOk, Visited);
Dan Gohman17d95962010-05-28 16:45:33 +0000656}
657
658/// findValueImpl - Implementation helper for findValue.
Chandler Carruthda530042015-08-06 02:05:46 +0000659Value *Lint::findValueImpl(Value *V, bool OffsetOk,
Craig Topper431bdfc2014-08-21 05:55:13 +0000660 SmallPtrSetImpl<Value *> &Visited) const {
Dan Gohman17d95962010-05-28 16:45:33 +0000661 // Detect self-referential values.
David Blaikie5401ba72014-11-19 07:49:26 +0000662 if (!Visited.insert(V).second)
Dan Gohman17d95962010-05-28 16:45:33 +0000663 return UndefValue::get(V->getType());
664
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000665 // TODO: Look through sext or zext cast, when the result is known to
666 // be interpreted as signed or unsigned, respectively.
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000667 // TODO: Look through eliminable cast pairs.
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000668 // TODO: Look through calls with unique return values.
669 // TODO: Look through vector insert/extract/shuffle.
Chandler Carruthda530042015-08-06 02:05:46 +0000670 V = OffsetOk ? GetUnderlyingObject(V, *DL) : V->stripPointerCasts();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000671 if (LoadInst *L = dyn_cast<LoadInst>(V)) {
Duncan P. N. Exon Smithd3a5adc2015-10-10 00:53:03 +0000672 BasicBlock::iterator BBI = L->getIterator();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000673 BasicBlock *BB = L->getParent();
Dan Gohman13ec30b2010-05-28 17:44:00 +0000674 SmallPtrSet<BasicBlock *, 4> VisitedBlocks;
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000675 for (;;) {
David Blaikie5401ba72014-11-19 07:49:26 +0000676 if (!VisitedBlocks.insert(BB).second)
677 break;
Larisse Voufo69328802015-09-18 19:14:35 +0000678 if (Value *U =
Eduard Burtescuf79a0312016-01-22 01:51:51 +0000679 FindAvailableLoadedValue(L, BB, BBI, DefMaxInstsToScan, AA))
Chandler Carruthda530042015-08-06 02:05:46 +0000680 return findValueImpl(U, OffsetOk, Visited);
Dan Gohman13ec30b2010-05-28 17:44:00 +0000681 if (BBI != BB->begin()) break;
682 BB = BB->getUniquePredecessor();
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000683 if (!BB) break;
684 BBI = BB->end();
685 }
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000686 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
Duncan Sandsff103412010-11-17 04:30:22 +0000687 if (Value *W = PN->hasConstantValue())
Duncan Sands23a19572010-11-17 10:23:23 +0000688 if (W != V)
Chandler Carruthda530042015-08-06 02:05:46 +0000689 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000690 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
Chandler Carruthda530042015-08-06 02:05:46 +0000691 if (CI->isNoopCast(*DL))
692 return findValueImpl(CI->getOperand(0), OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000693 } else if (ExtractValueInst *Ex = dyn_cast<ExtractValueInst>(V)) {
694 if (Value *W = FindInsertedValue(Ex->getAggregateOperand(),
Jay Foadfc6d3a42011-07-13 10:26:04 +0000695 Ex->getIndices()))
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000696 if (W != V)
Chandler Carruthda530042015-08-06 02:05:46 +0000697 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000698 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
699 // Same as above, but for ConstantExpr instead of Instruction.
700 if (Instruction::isCast(CE->getOpcode())) {
701 if (CastInst::isNoopCast(Instruction::CastOps(CE->getOpcode()),
Mehdi Amini529919f2015-03-10 02:37:25 +0000702 CE->getOperand(0)->getType(), CE->getType(),
Mikael Holmen42c9fd02017-10-03 06:03:49 +0000703 *DL))
Chandler Carruthda530042015-08-06 02:05:46 +0000704 return findValueImpl(CE->getOperand(0), OffsetOk, Visited);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000705 } else if (CE->getOpcode() == Instruction::ExtractValue) {
Jay Foadd30aa5a2011-04-13 15:22:40 +0000706 ArrayRef<unsigned> Indices = CE->getIndices();
Jay Foadfc6d3a42011-07-13 10:26:04 +0000707 if (Value *W = FindInsertedValue(CE->getOperand(0), Indices))
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000708 if (W != V)
Chandler Carruthda530042015-08-06 02:05:46 +0000709 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanaec2a0d2010-05-28 21:43:57 +0000710 }
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000711 }
712
713 // As a last resort, try SimplifyInstruction or constant folding.
714 if (Instruction *Inst = dyn_cast<Instruction>(V)) {
Daniel Berline2c51262017-04-28 19:55:38 +0000715 if (Value *W = SimplifyInstruction(Inst, {*DL, TLI, DT, AC}))
Chandler Carruthda530042015-08-06 02:05:46 +0000716 return findValueImpl(W, OffsetOk, Visited);
David Majnemere43ff142016-07-29 03:27:26 +0000717 } else if (auto *C = dyn_cast<Constant>(V)) {
718 if (Value *W = ConstantFoldConstant(C, *DL, TLI))
719 if (W && W != V)
Chandler Carruthda530042015-08-06 02:05:46 +0000720 return findValueImpl(W, OffsetOk, Visited);
Dan Gohmanff26d4e2010-05-28 16:21:24 +0000721 }
722
723 return V;
724}
725
Dan Gohman113902e2010-04-08 18:47:09 +0000726//===----------------------------------------------------------------------===//
727// Implement the public interfaces to this file...
728//===----------------------------------------------------------------------===//
729
730FunctionPass *llvm::createLintPass() {
731 return new Lint();
732}
733
734/// lintFunction - Check a function for errors, printing messages on stderr.
735///
736void llvm::lintFunction(const Function &f) {
737 Function &F = const_cast<Function&>(f);
738 assert(!F.isDeclaration() && "Cannot lint external functions");
739
Chandler Carruth417c5c12015-02-13 10:01:29 +0000740 legacy::FunctionPassManager FPM(F.getParent());
Dan Gohman113902e2010-04-08 18:47:09 +0000741 Lint *V = new Lint();
742 FPM.add(V);
743 FPM.run(F);
744}
745
746/// lintModule - Check a module for errors, printing messages on stderr.
Dan Gohman113902e2010-04-08 18:47:09 +0000747///
Dan Gohmana0f7ff32010-05-26 22:28:53 +0000748void llvm::lintModule(const Module &M) {
Chandler Carruth417c5c12015-02-13 10:01:29 +0000749 legacy::PassManager PM;
Dan Gohman113902e2010-04-08 18:47:09 +0000750 Lint *V = new Lint();
751 PM.add(V);
752 PM.run(const_cast<Module&>(M));
Dan Gohman113902e2010-04-08 18:47:09 +0000753}