blob: a544ac0c504f88ba0c808accd5b754a4078788b6 [file] [log] [blame]
Dan Gohman826bdf82010-05-28 16:19:17 +00001//===- Loads.cpp - Local load analysis ------------------------------------===//
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 file defines simple local analyses for load instructions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Analysis/Loads.h"
15#include "llvm/Analysis/AliasAnalysis.h"
Nuno Lopes69dcc7d2012-12-31 17:42:11 +000016#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/DataLayout.h"
18#include "llvm/IR/GlobalAlias.h"
19#include "llvm/IR/GlobalVariable.h"
20#include "llvm/IR/IntrinsicInst.h"
21#include "llvm/IR/LLVMContext.h"
Mehdi Amini9a9738f2015-03-03 22:01:13 +000022#include "llvm/IR/Module.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/Operator.h"
Dan Gohman826bdf82010-05-28 16:19:17 +000024using namespace llvm;
25
Chandler Carruthb56052f2014-10-18 23:31:55 +000026/// \brief Test if A and B will obviously have the same value.
27///
28/// This includes recognizing that %t0 and %t1 will have the same
Dan Gohman826bdf82010-05-28 16:19:17 +000029/// value in code like this:
Chandler Carruthb56052f2014-10-18 23:31:55 +000030/// \code
Dan Gohman826bdf82010-05-28 16:19:17 +000031/// %t0 = getelementptr \@a, 0, 3
32/// store i32 0, i32* %t0
33/// %t1 = getelementptr \@a, 0, 3
34/// %t2 = load i32* %t1
Chandler Carruthb56052f2014-10-18 23:31:55 +000035/// \endcode
Dan Gohman826bdf82010-05-28 16:19:17 +000036///
37static bool AreEquivalentAddressValues(const Value *A, const Value *B) {
38 // Test if the values are trivially equivalent.
Chandler Carruthbe49df32014-10-18 23:41:25 +000039 if (A == B)
40 return true;
Hans Wennborg060b9942011-06-03 17:15:37 +000041
Dan Gohman826bdf82010-05-28 16:19:17 +000042 // Test if the values come from identical arithmetic instructions.
43 // Use isIdenticalToWhenDefined instead of isIdenticalTo because
44 // this function is only used when one address use dominates the
45 // other, which means that they'll always either have the same
46 // value or one of them will have an undefined value.
Chandler Carruthbe49df32014-10-18 23:41:25 +000047 if (isa<BinaryOperator>(A) || isa<CastInst>(A) || isa<PHINode>(A) ||
48 isa<GetElementPtrInst>(A))
Dan Gohman826bdf82010-05-28 16:19:17 +000049 if (const Instruction *BI = dyn_cast<Instruction>(B))
50 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
51 return true;
Hans Wennborg060b9942011-06-03 17:15:37 +000052
Dan Gohman826bdf82010-05-28 16:19:17 +000053 // Otherwise they may not be equivalent.
54 return false;
55}
56
Chandler Carruth1f27f032014-10-18 23:46:17 +000057/// \brief Check if executing a load of this pointer value cannot trap.
58///
59/// If it is not obviously safe to load from the specified pointer, we do
60/// a quick local scan of the basic block containing \c ScanFrom, to determine
61/// if the address is already accessed.
62///
63/// This uses the pointee type to determine how many bytes need to be safe to
64/// load from the pointer.
Dan Gohman826bdf82010-05-28 16:19:17 +000065bool llvm::isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom,
Mehdi Aminia28d91d2015-03-10 02:37:25 +000066 unsigned Align) {
67 const DataLayout &DL = ScanFrom->getModule()->getDataLayout();
Artur Pilipenko0e21d542015-06-25 12:18:43 +000068
69 // Zero alignment means that the load has the ABI alignment for the target
70 if (Align == 0)
71 Align = DL.getABITypeAlignment(V->getType()->getPointerElementType());
72 assert(isPowerOf2_32(Align));
73
Nuno Lopes69dcc7d2012-12-31 17:42:11 +000074 int64_t ByteOffset = 0;
Dan Gohman826bdf82010-05-28 16:19:17 +000075 Value *Base = V;
Chandler Carruth38e98d52014-10-18 23:47:22 +000076 Base = GetPointerBaseWithConstantOffset(V, ByteOffset, DL);
Nuno Lopes69dcc7d2012-12-31 17:42:11 +000077
78 if (ByteOffset < 0) // out of bounds
79 return false;
Dan Gohman826bdf82010-05-28 16:19:17 +000080
Craig Topper9f008862014-04-15 04:59:12 +000081 Type *BaseType = nullptr;
Dan Gohman826bdf82010-05-28 16:19:17 +000082 unsigned BaseAlign = 0;
83 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Base)) {
84 // An alloca is safe to load from as load as it is suitably aligned.
85 BaseType = AI->getAllocatedType();
86 BaseAlign = AI->getAlignment();
Nuno Lopes69dcc7d2012-12-31 17:42:11 +000087 } else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) {
Chandler Carruth8a993732014-10-19 00:42:16 +000088 // Global variables are not necessarily safe to load from if they are
89 // overridden. Their size may change or they may be weak and require a test
90 // to determine if they were in fact provided.
Nuno Lopes69dcc7d2012-12-31 17:42:11 +000091 if (!GV->mayBeOverridden()) {
Dan Gohman826bdf82010-05-28 16:19:17 +000092 BaseType = GV->getType()->getElementType();
93 BaseAlign = GV->getAlignment();
94 }
95 }
96
Chandler Carrutheeec35a2014-10-20 00:24:14 +000097 PointerType *AddrTy = cast<PointerType>(V->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +000098 uint64_t LoadSize = DL.getTypeStoreSize(AddrTy->getElementType());
Chandler Carrutheeec35a2014-10-20 00:24:14 +000099
Chandler Carruth8a993732014-10-19 00:42:16 +0000100 // If we found a base allocated type from either an alloca or global variable,
101 // try to see if we are definitively within the allocated region. We need to
102 // know the size of the base type and the loaded type to do anything in this
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000103 // case.
104 if (BaseType && BaseType->isSized()) {
Chandler Carruth8a993732014-10-19 00:42:16 +0000105 if (BaseAlign == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000106 BaseAlign = DL.getPrefTypeAlignment(BaseType);
Dan Gohman826bdf82010-05-28 16:19:17 +0000107
108 if (Align <= BaseAlign) {
Dan Gohman826bdf82010-05-28 16:19:17 +0000109 // Check if the load is within the bounds of the underlying object.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000110 if (ByteOffset + LoadSize <= DL.getTypeAllocSize(BaseType) &&
Artur Pilipenko0e21d542015-06-25 12:18:43 +0000111 ((ByteOffset % Align) == 0))
Dan Gohman826bdf82010-05-28 16:19:17 +0000112 return true;
113 }
114 }
115
116 // Otherwise, be a little bit aggressive by scanning the local block where we
117 // want to check to see if the pointer is already being loaded or stored
118 // from/to. If so, the previous load or store would have already trapped,
119 // so there is no harm doing an extra load (also, CSE will later eliminate
120 // the load entirely).
121 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
122
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000123 // We can at least always strip pointer casts even though we can't use the
124 // base here.
125 V = V->stripPointerCasts();
126
Dan Gohman826bdf82010-05-28 16:19:17 +0000127 while (BBI != E) {
128 --BBI;
129
130 // If we see a free or a call which may write to memory (i.e. which might do
131 // a free) the pointer could be marked invalid.
132 if (isa<CallInst>(BBI) && BBI->mayWriteToMemory() &&
133 !isa<DbgInfoIntrinsic>(BBI))
134 return false;
135
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000136 Value *AccessedPtr;
Artur Pilipenko0e21d542015-06-25 12:18:43 +0000137 unsigned AccessedAlign;
138 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000139 AccessedPtr = LI->getPointerOperand();
Artur Pilipenko0e21d542015-06-25 12:18:43 +0000140 AccessedAlign = LI->getAlignment();
141 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000142 AccessedPtr = SI->getPointerOperand();
Artur Pilipenko0e21d542015-06-25 12:18:43 +0000143 AccessedAlign = SI->getAlignment();
144 } else
145 continue;
146
147 Type *AccessedTy = AccessedPtr->getType()->getPointerElementType();
148 if (AccessedAlign == 0)
149 AccessedAlign = DL.getABITypeAlignment(AccessedTy);
150 if (AccessedAlign < Align)
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000151 continue;
152
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000153 // Handle trivial cases.
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000154 if (AccessedPtr == V)
155 return true;
156
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000157 if (AreEquivalentAddressValues(AccessedPtr->stripPointerCasts(), V) &&
Artur Pilipenko0e21d542015-06-25 12:18:43 +0000158 LoadSize <= DL.getTypeStoreSize(AccessedTy))
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000159 return true;
Dan Gohman826bdf82010-05-28 16:19:17 +0000160 }
161 return false;
162}
163
Larisse Voufo532bf712015-09-18 19:14:35 +0000164/// DefMaxInstsToScan - the default number of maximum instructions
165/// to scan in the block, used by FindAvailableLoadedValue().
166/// FindAvailableLoadedValue() was introduced in r60148, to improve jump
167/// threading in part by eliminating partially redundant loads.
168/// At that point, the value of MaxInstsToScan was already set to '6'
169/// without documented explanation.
170cl::opt<unsigned>
171llvm::DefMaxInstsToScan("available-load-scan-limit", cl::init(6), cl::Hidden,
172 cl::desc("Use this to specify the default maximum number of instructions "
173 "to scan backward from a given instruction, when searching for "
174 "available loaded value"));
175
Chandler Carruthb56052f2014-10-18 23:31:55 +0000176/// \brief Scan the ScanBB block backwards to see if we have the value at the
Dan Gohman826bdf82010-05-28 16:19:17 +0000177/// memory address *Ptr locally available within a small number of instructions.
Dan Gohman826bdf82010-05-28 16:19:17 +0000178///
Chandler Carruthb56052f2014-10-18 23:31:55 +0000179/// The scan starts from \c ScanFrom. \c MaxInstsToScan specifies the maximum
180/// instructions to scan in the block. If it is set to \c 0, it will scan the whole
181/// block.
Dan Gohman826bdf82010-05-28 16:19:17 +0000182///
Chandler Carruthb56052f2014-10-18 23:31:55 +0000183/// If the value is available, this function returns it. If not, it returns the
184/// iterator for the last validated instruction that the value would be live
185/// through. If we scanned the entire block and didn't find something that
186/// invalidates \c *Ptr or provides it, \c ScanFrom is left at the last
187/// instruction processed and this returns null.
Chris Lattner87fa77b2012-03-13 18:07:41 +0000188///
Chandler Carruthb56052f2014-10-18 23:31:55 +0000189/// You can also optionally specify an alias analysis implementation, which
190/// makes this more precise.
191///
192/// If \c AATags is non-null and a load or store is found, the AA tags from the
193/// load or store are recorded there. If there are no AA tags or if no access is
194/// found, it is left unmodified.
Dan Gohman826bdf82010-05-28 16:19:17 +0000195Value *llvm::FindAvailableLoadedValue(Value *Ptr, BasicBlock *ScanBB,
196 BasicBlock::iterator &ScanFrom,
197 unsigned MaxInstsToScan,
Chandler Carruthd67244d2014-10-18 23:19:03 +0000198 AliasAnalysis *AA, AAMDNodes *AATags) {
199 if (MaxInstsToScan == 0)
200 MaxInstsToScan = ~0U;
Dan Gohman826bdf82010-05-28 16:19:17 +0000201
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000202 Type *AccessTy = cast<PointerType>(Ptr->getType())->getElementType();
203
Mehdi Amini46a43552015-03-04 18:43:29 +0000204 const DataLayout &DL = ScanBB->getModule()->getDataLayout();
Chandler Carruth1a3c2c42014-11-25 08:20:27 +0000205
206 // Try to get the store size for the type.
Mehdi Amini46a43552015-03-04 18:43:29 +0000207 uint64_t AccessSize = DL.getTypeStoreSize(AccessTy);
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000208
209 Value *StrippedPtr = Ptr->stripPointerCasts();
Chandler Carruthd67244d2014-10-18 23:19:03 +0000210
Dan Gohman826bdf82010-05-28 16:19:17 +0000211 while (ScanFrom != ScanBB->begin()) {
212 // We must ignore debug info directives when counting (otherwise they
213 // would affect codegen).
214 Instruction *Inst = --ScanFrom;
215 if (isa<DbgInfoIntrinsic>(Inst))
216 continue;
217
218 // Restore ScanFrom to expected value in case next test succeeds
219 ScanFrom++;
Chandler Carruthd67244d2014-10-18 23:19:03 +0000220
Dan Gohman826bdf82010-05-28 16:19:17 +0000221 // Don't scan huge blocks.
Chandler Carruthd67244d2014-10-18 23:19:03 +0000222 if (MaxInstsToScan-- == 0)
223 return nullptr;
224
Dan Gohman826bdf82010-05-28 16:19:17 +0000225 --ScanFrom;
226 // If this is a load of Ptr, the loaded value is available.
Eli Friedman4419cd22011-08-15 21:56:39 +0000227 // (This is true even if the load is volatile or atomic, although
228 // those cases are unlikely.)
Dan Gohman826bdf82010-05-28 16:19:17 +0000229 if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000230 if (AreEquivalentAddressValues(
231 LI->getPointerOperand()->stripPointerCasts(), StrippedPtr) &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000232 CastInst::isBitOrNoopPointerCastable(LI->getType(), AccessTy, DL)) {
Chandler Carruthd67244d2014-10-18 23:19:03 +0000233 if (AATags)
234 LI->getAAMetadata(*AATags);
Dan Gohman826bdf82010-05-28 16:19:17 +0000235 return LI;
Chris Lattner87fa77b2012-03-13 18:07:41 +0000236 }
Chandler Carruthd67244d2014-10-18 23:19:03 +0000237
Dan Gohman826bdf82010-05-28 16:19:17 +0000238 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000239 Value *StorePtr = SI->getPointerOperand()->stripPointerCasts();
Dan Gohman826bdf82010-05-28 16:19:17 +0000240 // If this is a store through Ptr, the value is available!
Eli Friedman4419cd22011-08-15 21:56:39 +0000241 // (This is true even if the store is volatile or atomic, although
242 // those cases are unlikely.)
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000243 if (AreEquivalentAddressValues(StorePtr, StrippedPtr) &&
Chandler Carruth1a3c2c42014-11-25 08:20:27 +0000244 CastInst::isBitOrNoopPointerCastable(SI->getValueOperand()->getType(),
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000245 AccessTy, DL)) {
Chandler Carruthd67244d2014-10-18 23:19:03 +0000246 if (AATags)
247 SI->getAAMetadata(*AATags);
Dan Gohman826bdf82010-05-28 16:19:17 +0000248 return SI->getOperand(0);
Chris Lattner87fa77b2012-03-13 18:07:41 +0000249 }
Chandler Carruthd67244d2014-10-18 23:19:03 +0000250
Chandler Carrutha32038b2014-10-20 10:03:01 +0000251 // If both StrippedPtr and StorePtr reach all the way to an alloca or
252 // global and they are different, ignore the store. This is a trivial form
253 // of alias analysis that is important for reg2mem'd code.
Chandler Carrutheeec35a2014-10-20 00:24:14 +0000254 if ((isa<AllocaInst>(StrippedPtr) || isa<GlobalVariable>(StrippedPtr)) &&
Chandler Carrutha32038b2014-10-20 10:03:01 +0000255 (isa<AllocaInst>(StorePtr) || isa<GlobalVariable>(StorePtr)) &&
256 StrippedPtr != StorePtr)
Dan Gohman826bdf82010-05-28 16:19:17 +0000257 continue;
Chandler Carruthd67244d2014-10-18 23:19:03 +0000258
Dan Gohman826bdf82010-05-28 16:19:17 +0000259 // If we have alias analysis and it says the store won't modify the loaded
260 // value, ignore the store.
Chandler Carruth194f59c2015-07-22 23:15:57 +0000261 if (AA && (AA->getModRefInfo(SI, StrippedPtr, AccessSize) & MRI_Mod) == 0)
Dan Gohman826bdf82010-05-28 16:19:17 +0000262 continue;
Chandler Carruthd67244d2014-10-18 23:19:03 +0000263
Dan Gohman826bdf82010-05-28 16:19:17 +0000264 // Otherwise the store that may or may not alias the pointer, bail out.
265 ++ScanFrom;
Craig Topper9f008862014-04-15 04:59:12 +0000266 return nullptr;
Dan Gohman826bdf82010-05-28 16:19:17 +0000267 }
Chandler Carruthd67244d2014-10-18 23:19:03 +0000268
Dan Gohman826bdf82010-05-28 16:19:17 +0000269 // If this is some other instruction that may clobber Ptr, bail out.
270 if (Inst->mayWriteToMemory()) {
271 // If alias analysis claims that it really won't modify the load,
272 // ignore it.
273 if (AA &&
Chandler Carruth194f59c2015-07-22 23:15:57 +0000274 (AA->getModRefInfo(Inst, StrippedPtr, AccessSize) & MRI_Mod) == 0)
Dan Gohman826bdf82010-05-28 16:19:17 +0000275 continue;
Chandler Carruthd67244d2014-10-18 23:19:03 +0000276
Dan Gohman826bdf82010-05-28 16:19:17 +0000277 // May modify the pointer, bail out.
278 ++ScanFrom;
Craig Topper9f008862014-04-15 04:59:12 +0000279 return nullptr;
Dan Gohman826bdf82010-05-28 16:19:17 +0000280 }
281 }
Chandler Carruthd67244d2014-10-18 23:19:03 +0000282
Dan Gohman826bdf82010-05-28 16:19:17 +0000283 // Got to the start of the block, we didn't find it, but are done for this
284 // block.
Craig Topper9f008862014-04-15 04:59:12 +0000285 return nullptr;
Dan Gohman826bdf82010-05-28 16:19:17 +0000286}