Fix Visual C++ error C2248:
[oota-llvm.git] / lib / Analysis / BasicAliasAnalysis.cpp
1 //===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===//
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 the primary stateless implementation of the
11 // Alias Analysis interface that implements identities (two different
12 // globals cannot alias, etc), but does no stateful analysis.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Analysis/BasicAliasAnalysis.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/CFG.h"
21 #include "llvm/Analysis/CaptureTracking.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/LoopInfo.h"
24 #include "llvm/Analysis/MemoryBuiltins.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/GlobalAlias.h"
31 #include "llvm/IR/GlobalVariable.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/IntrinsicInst.h"
34 #include "llvm/IR/LLVMContext.h"
35 #include "llvm/IR/Operator.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include <algorithm>
39 using namespace llvm;
40
41 /// Enable analysis of recursive PHI nodes.
42 static cl::opt<bool> EnableRecPhiAnalysis("basicaa-recphi", cl::Hidden,
43                                           cl::init(false));
44
45 /// SearchLimitReached / SearchTimes shows how often the limit of
46 /// to decompose GEPs is reached. It will affect the precision
47 /// of basic alias analysis.
48 #define DEBUG_TYPE "basicaa"
49 STATISTIC(SearchLimitReached, "Number of times the limit to "
50                               "decompose GEPs is reached");
51 STATISTIC(SearchTimes, "Number of times a GEP is decomposed");
52
53 /// Cutoff after which to stop analysing a set of phi nodes potentially involved
54 /// in a cycle. Because we are analysing 'through' phi nodes we need to be
55 /// careful with value equivalence. We use reachability to make sure a value
56 /// cannot be involved in a cycle.
57 const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
58
59 // The max limit of the search depth in DecomposeGEPExpression() and
60 // GetUnderlyingObject(), both functions need to use the same search
61 // depth otherwise the algorithm in aliasGEP will assert.
62 static const unsigned MaxLookupSearchDepth = 6;
63
64 //===----------------------------------------------------------------------===//
65 // Useful predicates
66 //===----------------------------------------------------------------------===//
67
68 /// isNonEscapingLocalObject - Return true if the pointer is to a function-local
69 /// object that never escapes from the function.
70 static bool isNonEscapingLocalObject(const Value *V) {
71   // If this is a local allocation, check to see if it escapes.
72   if (isa<AllocaInst>(V) || isNoAliasCall(V))
73     // Set StoreCaptures to True so that we can assume in our callers that the
74     // pointer is not the result of a load instruction. Currently
75     // PointerMayBeCaptured doesn't have any special analysis for the
76     // StoreCaptures=false case; if it did, our callers could be refined to be
77     // more precise.
78     return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
79
80   // If this is an argument that corresponds to a byval or noalias argument,
81   // then it has not escaped before entering the function.  Check if it escapes
82   // inside the function.
83   if (const Argument *A = dyn_cast<Argument>(V))
84     if (A->hasByValAttr() || A->hasNoAliasAttr())
85       // Note even if the argument is marked nocapture we still need to check
86       // for copies made inside the function. The nocapture attribute only
87       // specifies that there are no copies made that outlive the function.
88       return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
89
90   return false;
91 }
92
93 /// isEscapeSource - Return true if the pointer is one which would have
94 /// been considered an escape by isNonEscapingLocalObject.
95 static bool isEscapeSource(const Value *V) {
96   if (isa<CallInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V))
97     return true;
98
99   // The load case works because isNonEscapingLocalObject considers all
100   // stores to be escapes (it passes true for the StoreCaptures argument
101   // to PointerMayBeCaptured).
102   if (isa<LoadInst>(V))
103     return true;
104
105   return false;
106 }
107
108 /// getObjectSize - Return the size of the object specified by V, or
109 /// UnknownSize if unknown.
110 static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
111                               const TargetLibraryInfo &TLI,
112                               bool RoundToAlign = false) {
113   uint64_t Size;
114   if (getObjectSize(V, Size, DL, &TLI, RoundToAlign))
115     return Size;
116   return MemoryLocation::UnknownSize;
117 }
118
119 /// isObjectSmallerThan - Return true if we can prove that the object specified
120 /// by V is smaller than Size.
121 static bool isObjectSmallerThan(const Value *V, uint64_t Size,
122                                 const DataLayout &DL,
123                                 const TargetLibraryInfo &TLI) {
124   // Note that the meanings of the "object" are slightly different in the
125   // following contexts:
126   //    c1: llvm::getObjectSize()
127   //    c2: llvm.objectsize() intrinsic
128   //    c3: isObjectSmallerThan()
129   // c1 and c2 share the same meaning; however, the meaning of "object" in c3
130   // refers to the "entire object".
131   //
132   //  Consider this example:
133   //     char *p = (char*)malloc(100)
134   //     char *q = p+80;
135   //
136   //  In the context of c1 and c2, the "object" pointed by q refers to the
137   // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
138   //
139   //  However, in the context of c3, the "object" refers to the chunk of memory
140   // being allocated. So, the "object" has 100 bytes, and q points to the middle
141   // the "object". In case q is passed to isObjectSmallerThan() as the 1st
142   // parameter, before the llvm::getObjectSize() is called to get the size of
143   // entire object, we should:
144   //    - either rewind the pointer q to the base-address of the object in
145   //      question (in this case rewind to p), or
146   //    - just give up. It is up to caller to make sure the pointer is pointing
147   //      to the base address the object.
148   //
149   // We go for 2nd option for simplicity.
150   if (!isIdentifiedObject(V))
151     return false;
152
153   // This function needs to use the aligned object size because we allow
154   // reads a bit past the end given sufficient alignment.
155   uint64_t ObjectSize = getObjectSize(V, DL, TLI, /*RoundToAlign*/ true);
156
157   return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size;
158 }
159
160 /// isObjectSize - Return true if we can prove that the object specified
161 /// by V has size Size.
162 static bool isObjectSize(const Value *V, uint64_t Size, const DataLayout &DL,
163                          const TargetLibraryInfo &TLI) {
164   uint64_t ObjectSize = getObjectSize(V, DL, TLI);
165   return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size;
166 }
167
168 //===----------------------------------------------------------------------===//
169 // GetElementPtr Instruction Decomposition and Analysis
170 //===----------------------------------------------------------------------===//
171
172 /// GetLinearExpression - Analyze the specified value as a linear expression:
173 /// "A*V + B", where A and B are constant integers.  Return the scale and offset
174 /// values as APInts and return V as a Value*, and return whether we looked
175 /// through any sign or zero extends.  The incoming Value is known to have
176 /// IntegerType and it may already be sign or zero extended.
177 ///
178 /// Note that this looks through extends, so the high bits may not be
179 /// represented in the result.
180 /*static*/ Value *BasicAliasAnalysis::GetLinearExpression(
181     Value *V, APInt &Scale, APInt &Offset, ExtensionKind &Extension,
182     const DataLayout &DL, unsigned Depth, AssumptionCache *AC,
183     DominatorTree *DT) {
184   assert(V->getType()->isIntegerTy() && "Not an integer value");
185
186   // Limit our recursion depth.
187   if (Depth == 6) {
188     Scale = 1;
189     Offset = 0;
190     return V;
191   }
192
193   if (ConstantInt *Const = dyn_cast<ConstantInt>(V)) {
194     // if it's a constant, just convert it to an offset
195     // and remove the variable.
196     Offset += Const->getValue();
197     assert(Scale == 0 && "Constant values don't have a scale");
198     return V;
199   }
200
201   if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
202     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
203       switch (BOp->getOpcode()) {
204       default:
205         break;
206       case Instruction::Or:
207         // X|C == X+C if all the bits in C are unset in X.  Otherwise we can't
208         // analyze it.
209         if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC,
210                                BOp, DT))
211           break;
212       // FALL THROUGH.
213       case Instruction::Add:
214         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
215                                 DL, Depth + 1, AC, DT);
216         Offset += RHSC->getValue();
217         return V;
218       case Instruction::Mul:
219         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
220                                 DL, Depth + 1, AC, DT);
221         Offset *= RHSC->getValue();
222         Scale *= RHSC->getValue();
223         return V;
224       case Instruction::Shl:
225         V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, Extension,
226                                 DL, Depth + 1, AC, DT);
227         Offset <<= RHSC->getValue().getLimitedValue();
228         Scale <<= RHSC->getValue().getLimitedValue();
229         return V;
230       }
231     }
232   }
233
234   // Since GEP indices are sign extended anyway, we don't care about the high
235   // bits of a sign or zero extended value - just scales and offsets.  The
236   // extensions have to be consistent though.
237   if ((isa<SExtInst>(V) && Extension != EK_ZeroExt) ||
238       (isa<ZExtInst>(V) && Extension != EK_SignExt)) {
239     Value *CastOp = cast<CastInst>(V)->getOperand(0);
240     unsigned OldWidth = Scale.getBitWidth();
241     unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
242     Scale = Scale.trunc(SmallWidth);
243     Offset = Offset.trunc(SmallWidth);
244     Extension = isa<SExtInst>(V) ? EK_SignExt : EK_ZeroExt;
245
246     Value *Result = GetLinearExpression(CastOp, Scale, Offset, Extension, DL,
247                                         Depth + 1, AC, DT);
248     Scale = Scale.zext(OldWidth);
249
250     // We have to sign-extend even if Extension == EK_ZeroExt as we can't
251     // decompose a sign extension (i.e. zext(x - 1) != zext(x) - zext(-1)).
252     Offset = Offset.sext(OldWidth);
253
254     return Result;
255   }
256
257   Scale = 1;
258   Offset = 0;
259   return V;
260 }
261
262 /// DecomposeGEPExpression - If V is a symbolic pointer expression, decompose it
263 /// into a base pointer with a constant offset and a number of scaled symbolic
264 /// offsets.
265 ///
266 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale in
267 /// the VarIndices vector) are Value*'s that are known to be scaled by the
268 /// specified amount, but which may have other unrepresented high bits. As such,
269 /// the gep cannot necessarily be reconstructed from its decomposed form.
270 ///
271 /// When DataLayout is around, this function is capable of analyzing everything
272 /// that GetUnderlyingObject can look through. To be able to do that
273 /// GetUnderlyingObject and DecomposeGEPExpression must use the same search
274 /// depth (MaxLookupSearchDepth).
275 /// When DataLayout not is around, it just looks through pointer casts.
276 ///
277 /*static*/ const Value *BasicAliasAnalysis::DecomposeGEPExpression(
278     const Value *V, int64_t &BaseOffs,
279     SmallVectorImpl<VariableGEPIndex> &VarIndices, bool &MaxLookupReached,
280     const DataLayout &DL, AssumptionCache *AC, DominatorTree *DT) {
281   // Limit recursion depth to limit compile time in crazy cases.
282   unsigned MaxLookup = MaxLookupSearchDepth;
283   MaxLookupReached = false;
284   SearchTimes++;
285
286   BaseOffs = 0;
287   do {
288     // See if this is a bitcast or GEP.
289     const Operator *Op = dyn_cast<Operator>(V);
290     if (!Op) {
291       // The only non-operator case we can handle are GlobalAliases.
292       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
293         if (!GA->mayBeOverridden()) {
294           V = GA->getAliasee();
295           continue;
296         }
297       }
298       return V;
299     }
300
301     if (Op->getOpcode() == Instruction::BitCast ||
302         Op->getOpcode() == Instruction::AddrSpaceCast) {
303       V = Op->getOperand(0);
304       continue;
305     }
306
307     const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
308     if (!GEPOp) {
309       // If it's not a GEP, hand it off to SimplifyInstruction to see if it
310       // can come up with something. This matches what GetUnderlyingObject does.
311       if (const Instruction *I = dyn_cast<Instruction>(V))
312         // TODO: Get a DominatorTree and AssumptionCache and use them here
313         // (these are both now available in this function, but this should be
314         // updated when GetUnderlyingObject is updated). TLI should be
315         // provided also.
316         if (const Value *Simplified =
317                 SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
318           V = Simplified;
319           continue;
320         }
321
322       return V;
323     }
324
325     // Don't attempt to analyze GEPs over unsized objects.
326     if (!GEPOp->getOperand(0)->getType()->getPointerElementType()->isSized())
327       return V;
328
329     unsigned AS = GEPOp->getPointerAddressSpace();
330     // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
331     gep_type_iterator GTI = gep_type_begin(GEPOp);
332     for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end();
333          I != E; ++I) {
334       Value *Index = *I;
335       // Compute the (potentially symbolic) offset in bytes for this index.
336       if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
337         // For a struct, add the member offset.
338         unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
339         if (FieldNo == 0)
340           continue;
341
342         BaseOffs += DL.getStructLayout(STy)->getElementOffset(FieldNo);
343         continue;
344       }
345
346       // For an array/pointer, add the element offset, explicitly scaled.
347       if (ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
348         if (CIdx->isZero())
349           continue;
350         BaseOffs += DL.getTypeAllocSize(*GTI) * CIdx->getSExtValue();
351         continue;
352       }
353
354       uint64_t Scale = DL.getTypeAllocSize(*GTI);
355       ExtensionKind Extension = EK_NotExtended;
356
357       // If the integer type is smaller than the pointer size, it is implicitly
358       // sign extended to pointer size.
359       unsigned Width = Index->getType()->getIntegerBitWidth();
360       if (DL.getPointerSizeInBits(AS) > Width)
361         Extension = EK_SignExt;
362
363       // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
364       APInt IndexScale(Width, 0), IndexOffset(Width, 0);
365       Index = GetLinearExpression(Index, IndexScale, IndexOffset, Extension, DL,
366                                   0, AC, DT);
367
368       // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
369       // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
370       BaseOffs += IndexOffset.getSExtValue() * Scale;
371       Scale *= IndexScale.getSExtValue();
372
373       // If we already had an occurrence of this index variable, merge this
374       // scale into it.  For example, we want to handle:
375       //   A[x][x] -> x*16 + x*4 -> x*20
376       // This also ensures that 'x' only appears in the index list once.
377       for (unsigned i = 0, e = VarIndices.size(); i != e; ++i) {
378         if (VarIndices[i].V == Index && VarIndices[i].Extension == Extension) {
379           Scale += VarIndices[i].Scale;
380           VarIndices.erase(VarIndices.begin() + i);
381           break;
382         }
383       }
384
385       // Make sure that we have a scale that makes sense for this target's
386       // pointer size.
387       if (unsigned ShiftBits = 64 - DL.getPointerSizeInBits(AS)) {
388         Scale <<= ShiftBits;
389         Scale = (int64_t)Scale >> ShiftBits;
390       }
391
392       if (Scale) {
393         VariableGEPIndex Entry = {Index, Extension,
394                                   static_cast<int64_t>(Scale)};
395         VarIndices.push_back(Entry);
396       }
397     }
398
399     // Analyze the base pointer next.
400     V = GEPOp->getOperand(0);
401   } while (--MaxLookup);
402
403   // If the chain of expressions is too deep, just return early.
404   MaxLookupReached = true;
405   SearchLimitReached++;
406   return V;
407 }
408
409 //===----------------------------------------------------------------------===//
410 // BasicAliasAnalysis Pass
411 //===----------------------------------------------------------------------===//
412
413 // Register the pass...
414 char BasicAliasAnalysis::ID = 0;
415 INITIALIZE_AG_PASS_BEGIN(BasicAliasAnalysis, AliasAnalysis, "basicaa",
416                          "Basic Alias Analysis (stateless AA impl)", false,
417                          true, false)
418 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
419 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
420 INITIALIZE_AG_PASS_END(BasicAliasAnalysis, AliasAnalysis, "basicaa",
421                        "Basic Alias Analysis (stateless AA impl)", false, true,
422                        false)
423
424 ImmutablePass *llvm::createBasicAliasAnalysisPass() {
425   return new BasicAliasAnalysis();
426 }
427
428 /// pointsToConstantMemory - Returns whether the given pointer value
429 /// points to memory that is local to the function, with global constants being
430 /// considered local to all functions.
431 bool BasicAliasAnalysis::pointsToConstantMemory(const MemoryLocation &Loc,
432                                                 bool OrLocal) {
433   assert(Visited.empty() && "Visited must be cleared after use!");
434
435   unsigned MaxLookup = 8;
436   SmallVector<const Value *, 16> Worklist;
437   Worklist.push_back(Loc.Ptr);
438   do {
439     const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), *DL);
440     if (!Visited.insert(V).second) {
441       Visited.clear();
442       return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
443     }
444
445     // An alloca instruction defines local memory.
446     if (OrLocal && isa<AllocaInst>(V))
447       continue;
448
449     // A global constant counts as local memory for our purposes.
450     if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
451       // Note: this doesn't require GV to be "ODR" because it isn't legal for a
452       // global to be marked constant in some modules and non-constant in
453       // others.  GV may even be a declaration, not a definition.
454       if (!GV->isConstant()) {
455         Visited.clear();
456         return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
457       }
458       continue;
459     }
460
461     // If both select values point to local memory, then so does the select.
462     if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
463       Worklist.push_back(SI->getTrueValue());
464       Worklist.push_back(SI->getFalseValue());
465       continue;
466     }
467
468     // If all values incoming to a phi node point to local memory, then so does
469     // the phi.
470     if (const PHINode *PN = dyn_cast<PHINode>(V)) {
471       // Don't bother inspecting phi nodes with many operands.
472       if (PN->getNumIncomingValues() > MaxLookup) {
473         Visited.clear();
474         return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
475       }
476       for (Value *IncValue : PN->incoming_values())
477         Worklist.push_back(IncValue);
478       continue;
479     }
480
481     // Otherwise be conservative.
482     Visited.clear();
483     return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
484
485   } while (!Worklist.empty() && --MaxLookup);
486
487   Visited.clear();
488   return Worklist.empty();
489 }
490
491 // FIXME: This code is duplicated with MemoryLocation and should be hoisted to
492 // some common utility location.
493 static bool isMemsetPattern16(const Function *MS,
494                               const TargetLibraryInfo &TLI) {
495   if (TLI.has(LibFunc::memset_pattern16) &&
496       MS->getName() == "memset_pattern16") {
497     FunctionType *MemsetType = MS->getFunctionType();
498     if (!MemsetType->isVarArg() && MemsetType->getNumParams() == 3 &&
499         isa<PointerType>(MemsetType->getParamType(0)) &&
500         isa<PointerType>(MemsetType->getParamType(1)) &&
501         isa<IntegerType>(MemsetType->getParamType(2)))
502       return true;
503   }
504
505   return false;
506 }
507
508 /// getModRefBehavior - Return the behavior when calling the given call site.
509 FunctionModRefBehavior
510 BasicAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
511   if (CS.doesNotAccessMemory())
512     // Can't do better than this.
513     return FMRB_DoesNotAccessMemory;
514
515   FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
516
517   // If the callsite knows it only reads memory, don't return worse
518   // than that.
519   if (CS.onlyReadsMemory())
520     Min = FMRB_OnlyReadsMemory;
521
522   if (CS.onlyAccessesArgMemory())
523     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
524
525   // The AliasAnalysis base class has some smarts, lets use them.
526   return FunctionModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
527 }
528
529 /// getModRefBehavior - Return the behavior when calling the given function.
530 /// For use when the call site is not known.
531 FunctionModRefBehavior
532 BasicAliasAnalysis::getModRefBehavior(const Function *F) {
533   // If the function declares it doesn't access memory, we can't do better.
534   if (F->doesNotAccessMemory())
535     return FMRB_DoesNotAccessMemory;
536
537   // For intrinsics, we can check the table.
538   if (Intrinsic::ID iid = F->getIntrinsicID()) {
539 #define GET_INTRINSIC_MODREF_BEHAVIOR
540 #include "llvm/IR/Intrinsics.gen"
541 #undef GET_INTRINSIC_MODREF_BEHAVIOR
542   }
543
544   FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
545
546   // If the function declares it only reads memory, go with that.
547   if (F->onlyReadsMemory())
548     Min = FMRB_OnlyReadsMemory;
549
550   if (F->onlyAccessesArgMemory())
551     Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
552
553   const TargetLibraryInfo &TLI =
554       getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
555   if (isMemsetPattern16(F, TLI))
556     Min = FMRB_OnlyAccessesArgumentPointees;
557
558   // Otherwise be conservative.
559   return FunctionModRefBehavior(AliasAnalysis::getModRefBehavior(F) & Min);
560 }
561
562 ModRefInfo BasicAliasAnalysis::getArgModRefInfo(ImmutableCallSite CS,
563                                                 unsigned ArgIdx) {
564   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction()))
565     switch (II->getIntrinsicID()) {
566     default:
567       break;
568     case Intrinsic::memset:
569     case Intrinsic::memcpy:
570     case Intrinsic::memmove:
571       assert((ArgIdx == 0 || ArgIdx == 1) &&
572              "Invalid argument index for memory intrinsic");
573       return ArgIdx ? MRI_Ref : MRI_Mod;
574     }
575
576   // We can bound the aliasing properties of memset_pattern16 just as we can
577   // for memcpy/memset.  This is particularly important because the
578   // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
579   // whenever possible.
580   if (CS.getCalledFunction() &&
581       isMemsetPattern16(CS.getCalledFunction(), *TLI)) {
582     assert((ArgIdx == 0 || ArgIdx == 1) &&
583            "Invalid argument index for memset_pattern16");
584     return ArgIdx ? MRI_Ref : MRI_Mod;
585   }
586   // FIXME: Handle memset_pattern4 and memset_pattern8 also.
587
588   return AliasAnalysis::getArgModRefInfo(CS, ArgIdx);
589 }
590
591 static bool isAssumeIntrinsic(ImmutableCallSite CS) {
592   const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
593   if (II && II->getIntrinsicID() == Intrinsic::assume)
594     return true;
595
596   return false;
597 }
598
599 bool BasicAliasAnalysis::doInitialization(Module &M) {
600   InitializeAliasAnalysis(this, &M.getDataLayout());
601   return true;
602 }
603
604 /// getModRefInfo - Check to see if the specified callsite can clobber the
605 /// specified memory object.  Since we only look at local properties of this
606 /// function, we really can't say much about this query.  We do, however, use
607 /// simple "address taken" analysis on local objects.
608 ModRefInfo BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
609                                              const MemoryLocation &Loc) {
610   assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&
611          "AliasAnalysis query involving multiple functions!");
612
613   const Value *Object = GetUnderlyingObject(Loc.Ptr, *DL);
614
615   // If this is a tail call and Loc.Ptr points to a stack location, we know that
616   // the tail call cannot access or modify the local stack.
617   // We cannot exclude byval arguments here; these belong to the caller of
618   // the current function not to the current function, and a tail callee
619   // may reference them.
620   if (isa<AllocaInst>(Object))
621     if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
622       if (CI->isTailCall())
623         return MRI_NoModRef;
624
625   // If the pointer is to a locally allocated object that does not escape,
626   // then the call can not mod/ref the pointer unless the call takes the pointer
627   // as an argument, and itself doesn't capture it.
628   if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
629       isNonEscapingLocalObject(Object)) {
630     bool PassedAsArg = false;
631     unsigned ArgNo = 0;
632     for (ImmutableCallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
633          CI != CE; ++CI, ++ArgNo) {
634       // Only look at the no-capture or byval pointer arguments.  If this
635       // pointer were passed to arguments that were neither of these, then it
636       // couldn't be no-capture.
637       if (!(*CI)->getType()->isPointerTy() ||
638           (!CS.doesNotCapture(ArgNo) && !CS.isByValArgument(ArgNo)))
639         continue;
640
641       // If this is a no-capture pointer argument, see if we can tell that it
642       // is impossible to alias the pointer we're checking.  If not, we have to
643       // assume that the call could touch the pointer, even though it doesn't
644       // escape.
645       if (!isNoAlias(MemoryLocation(*CI), MemoryLocation(Object))) {
646         PassedAsArg = true;
647         break;
648       }
649     }
650
651     if (!PassedAsArg)
652       return MRI_NoModRef;
653   }
654
655   // While the assume intrinsic is marked as arbitrarily writing so that
656   // proper control dependencies will be maintained, it never aliases any
657   // particular memory location.
658   if (isAssumeIntrinsic(CS))
659     return MRI_NoModRef;
660
661   // The AliasAnalysis base class has some smarts, lets use them.
662   return AliasAnalysis::getModRefInfo(CS, Loc);
663 }
664
665 ModRefInfo BasicAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
666                                              ImmutableCallSite CS2) {
667   // While the assume intrinsic is marked as arbitrarily writing so that
668   // proper control dependencies will be maintained, it never aliases any
669   // particular memory location.
670   if (isAssumeIntrinsic(CS1) || isAssumeIntrinsic(CS2))
671     return MRI_NoModRef;
672
673   // The AliasAnalysis base class has some smarts, lets use them.
674   return AliasAnalysis::getModRefInfo(CS1, CS2);
675 }
676
677 /// \brief Provide ad-hoc rules to disambiguate accesses through two GEP
678 /// operators, both having the exact same pointer operand.
679 static AliasResult aliasSameBasePointerGEPs(const GEPOperator *GEP1,
680                                             uint64_t V1Size,
681                                             const GEPOperator *GEP2,
682                                             uint64_t V2Size,
683                                             const DataLayout &DL) {
684
685   assert(GEP1->getPointerOperand() == GEP2->getPointerOperand() &&
686          "Expected GEPs with the same pointer operand");
687
688   // Try to determine whether GEP1 and GEP2 index through arrays, into structs,
689   // such that the struct field accesses provably cannot alias.
690   // We also need at least two indices (the pointer, and the struct field).
691   if (GEP1->getNumIndices() != GEP2->getNumIndices() ||
692       GEP1->getNumIndices() < 2)
693     return MayAlias;
694
695   // If we don't know the size of the accesses through both GEPs, we can't
696   // determine whether the struct fields accessed can't alias.
697   if (V1Size == MemoryLocation::UnknownSize ||
698       V2Size == MemoryLocation::UnknownSize)
699     return MayAlias;
700
701   ConstantInt *C1 =
702       dyn_cast<ConstantInt>(GEP1->getOperand(GEP1->getNumOperands() - 1));
703   ConstantInt *C2 =
704       dyn_cast<ConstantInt>(GEP2->getOperand(GEP2->getNumOperands() - 1));
705
706   // If the last (struct) indices aren't constants, we can't say anything.
707   // If they're identical, the other indices might be also be dynamically
708   // equal, so the GEPs can alias.
709   if (!C1 || !C2 || C1 == C2)
710     return MayAlias;
711
712   // Find the last-indexed type of the GEP, i.e., the type you'd get if
713   // you stripped the last index.
714   // On the way, look at each indexed type.  If there's something other
715   // than an array, different indices can lead to different final types.
716   SmallVector<Value *, 8> IntermediateIndices;
717
718   // Insert the first index; we don't need to check the type indexed
719   // through it as it only drops the pointer indirection.
720   assert(GEP1->getNumIndices() > 1 && "Not enough GEP indices to examine");
721   IntermediateIndices.push_back(GEP1->getOperand(1));
722
723   // Insert all the remaining indices but the last one.
724   // Also, check that they all index through arrays.
725   for (unsigned i = 1, e = GEP1->getNumIndices() - 1; i != e; ++i) {
726     if (!isa<ArrayType>(GetElementPtrInst::getIndexedType(
727             GEP1->getSourceElementType(), IntermediateIndices)))
728       return MayAlias;
729     IntermediateIndices.push_back(GEP1->getOperand(i + 1));
730   }
731
732   StructType *LastIndexedStruct =
733       dyn_cast<StructType>(GetElementPtrInst::getIndexedType(
734           GEP1->getSourceElementType(), IntermediateIndices));
735
736   if (!LastIndexedStruct)
737     return MayAlias;
738
739   // We know that:
740   // - both GEPs begin indexing from the exact same pointer;
741   // - the last indices in both GEPs are constants, indexing into a struct;
742   // - said indices are different, hence, the pointed-to fields are different;
743   // - both GEPs only index through arrays prior to that.
744   //
745   // This lets us determine that the struct that GEP1 indexes into and the
746   // struct that GEP2 indexes into must either precisely overlap or be
747   // completely disjoint.  Because they cannot partially overlap, indexing into
748   // different non-overlapping fields of the struct will never alias.
749
750   // Therefore, the only remaining thing needed to show that both GEPs can't
751   // alias is that the fields are not overlapping.
752   const StructLayout *SL = DL.getStructLayout(LastIndexedStruct);
753   const uint64_t StructSize = SL->getSizeInBytes();
754   const uint64_t V1Off = SL->getElementOffset(C1->getZExtValue());
755   const uint64_t V2Off = SL->getElementOffset(C2->getZExtValue());
756
757   auto EltsDontOverlap = [StructSize](uint64_t V1Off, uint64_t V1Size,
758                                       uint64_t V2Off, uint64_t V2Size) {
759     return V1Off < V2Off && V1Off + V1Size <= V2Off &&
760            ((V2Off + V2Size <= StructSize) ||
761             (V2Off + V2Size - StructSize <= V1Off));
762   };
763
764   if (EltsDontOverlap(V1Off, V1Size, V2Off, V2Size) ||
765       EltsDontOverlap(V2Off, V2Size, V1Off, V1Size))
766     return NoAlias;
767
768   return MayAlias;
769 }
770
771 /// aliasGEP - Provide a bunch of ad-hoc rules to disambiguate a GEP instruction
772 /// against another pointer.  We know that V1 is a GEP, but we don't know
773 /// anything about V2.  UnderlyingV1 is GetUnderlyingObject(GEP1, DL),
774 /// UnderlyingV2 is the same for V2.
775 ///
776 AliasResult BasicAliasAnalysis::aliasGEP(
777     const GEPOperator *GEP1, uint64_t V1Size, const AAMDNodes &V1AAInfo,
778     const Value *V2, uint64_t V2Size, const AAMDNodes &V2AAInfo,
779     const Value *UnderlyingV1, const Value *UnderlyingV2) {
780   int64_t GEP1BaseOffset;
781   bool GEP1MaxLookupReached;
782   SmallVector<VariableGEPIndex, 4> GEP1VariableIndices;
783
784   // We have to get two AssumptionCaches here because GEP1 and V2 may be from
785   // different functions.
786   // FIXME: This really doesn't make any sense. We get a dominator tree below
787   // that can only refer to a single function. But this function (aliasGEP) is
788   // a method on an immutable pass that can be called when there *isn't*
789   // a single function. The old pass management layer makes this "work", but
790   // this isn't really a clean solution.
791   AssumptionCacheTracker &ACT = getAnalysis<AssumptionCacheTracker>();
792   AssumptionCache *AC1 = nullptr, *AC2 = nullptr;
793   if (auto *GEP1I = dyn_cast<Instruction>(GEP1))
794     AC1 = &ACT.getAssumptionCache(
795         const_cast<Function &>(*GEP1I->getParent()->getParent()));
796   if (auto *I2 = dyn_cast<Instruction>(V2))
797     AC2 = &ACT.getAssumptionCache(
798         const_cast<Function &>(*I2->getParent()->getParent()));
799
800   DominatorTreeWrapperPass *DTWP =
801       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
802   DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
803
804   // If we have two gep instructions with must-alias or not-alias'ing base
805   // pointers, figure out if the indexes to the GEP tell us anything about the
806   // derived pointer.
807   if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
808     // Do the base pointers alias?
809     AliasResult BaseAlias =
810         aliasCheck(UnderlyingV1, MemoryLocation::UnknownSize, AAMDNodes(),
811                    UnderlyingV2, MemoryLocation::UnknownSize, AAMDNodes());
812
813     // Check for geps of non-aliasing underlying pointers where the offsets are
814     // identical.
815     if ((BaseAlias == MayAlias) && V1Size == V2Size) {
816       // Do the base pointers alias assuming type and size.
817       AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size, V1AAInfo,
818                                                 UnderlyingV2, V2Size, V2AAInfo);
819       if (PreciseBaseAlias == NoAlias) {
820         // See if the computed offset from the common pointer tells us about the
821         // relation of the resulting pointer.
822         int64_t GEP2BaseOffset;
823         bool GEP2MaxLookupReached;
824         SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
825         const Value *GEP2BasePtr =
826             DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
827                                    GEP2MaxLookupReached, *DL, AC2, DT);
828         const Value *GEP1BasePtr =
829             DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
830                                    GEP1MaxLookupReached, *DL, AC1, DT);
831         // DecomposeGEPExpression and GetUnderlyingObject should return the
832         // same result except when DecomposeGEPExpression has no DataLayout.
833         if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
834           assert(!DL &&
835                  "DecomposeGEPExpression and GetUnderlyingObject disagree!");
836           return MayAlias;
837         }
838         // If the max search depth is reached the result is undefined
839         if (GEP2MaxLookupReached || GEP1MaxLookupReached)
840           return MayAlias;
841
842         // Same offsets.
843         if (GEP1BaseOffset == GEP2BaseOffset &&
844             GEP1VariableIndices == GEP2VariableIndices)
845           return NoAlias;
846         GEP1VariableIndices.clear();
847       }
848     }
849
850     // If we get a No or May, then return it immediately, no amount of analysis
851     // will improve this situation.
852     if (BaseAlias != MustAlias)
853       return BaseAlias;
854
855     // Otherwise, we have a MustAlias.  Since the base pointers alias each other
856     // exactly, see if the computed offset from the common pointer tells us
857     // about the relation of the resulting pointer.
858     const Value *GEP1BasePtr =
859         DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
860                                GEP1MaxLookupReached, *DL, AC1, DT);
861
862     int64_t GEP2BaseOffset;
863     bool GEP2MaxLookupReached;
864     SmallVector<VariableGEPIndex, 4> GEP2VariableIndices;
865     const Value *GEP2BasePtr =
866         DecomposeGEPExpression(GEP2, GEP2BaseOffset, GEP2VariableIndices,
867                                GEP2MaxLookupReached, *DL, AC2, DT);
868
869     // DecomposeGEPExpression and GetUnderlyingObject should return the
870     // same result except when DecomposeGEPExpression has no DataLayout.
871     if (GEP1BasePtr != UnderlyingV1 || GEP2BasePtr != UnderlyingV2) {
872       assert(!DL && "DecomposeGEPExpression and GetUnderlyingObject disagree!");
873       return MayAlias;
874     }
875
876     // If we know the two GEPs are based off of the exact same pointer (and not
877     // just the same underlying object), see if that tells us anything about
878     // the resulting pointers.
879     if (DL && GEP1->getPointerOperand() == GEP2->getPointerOperand()) {
880       AliasResult R = aliasSameBasePointerGEPs(GEP1, V1Size, GEP2, V2Size, *DL);
881       // If we couldn't find anything interesting, don't abandon just yet.
882       if (R != MayAlias)
883         return R;
884     }
885
886     // If the max search depth is reached the result is undefined
887     if (GEP2MaxLookupReached || GEP1MaxLookupReached)
888       return MayAlias;
889
890     // Subtract the GEP2 pointer from the GEP1 pointer to find out their
891     // symbolic difference.
892     GEP1BaseOffset -= GEP2BaseOffset;
893     GetIndexDifference(GEP1VariableIndices, GEP2VariableIndices);
894
895   } else {
896     // Check to see if these two pointers are related by the getelementptr
897     // instruction.  If one pointer is a GEP with a non-zero index of the other
898     // pointer, we know they cannot alias.
899
900     // If both accesses are unknown size, we can't do anything useful here.
901     if (V1Size == MemoryLocation::UnknownSize &&
902         V2Size == MemoryLocation::UnknownSize)
903       return MayAlias;
904
905     AliasResult R = aliasCheck(UnderlyingV1, MemoryLocation::UnknownSize,
906                                AAMDNodes(), V2, V2Size, V2AAInfo);
907     if (R != MustAlias)
908       // If V2 may alias GEP base pointer, conservatively returns MayAlias.
909       // If V2 is known not to alias GEP base pointer, then the two values
910       // cannot alias per GEP semantics: "A pointer value formed from a
911       // getelementptr instruction is associated with the addresses associated
912       // with the first operand of the getelementptr".
913       return R;
914
915     const Value *GEP1BasePtr =
916         DecomposeGEPExpression(GEP1, GEP1BaseOffset, GEP1VariableIndices,
917                                GEP1MaxLookupReached, *DL, AC1, DT);
918
919     // DecomposeGEPExpression and GetUnderlyingObject should return the
920     // same result except when DecomposeGEPExpression has no DataLayout.
921     if (GEP1BasePtr != UnderlyingV1) {
922       assert(!DL && "DecomposeGEPExpression and GetUnderlyingObject disagree!");
923       return MayAlias;
924     }
925     // If the max search depth is reached the result is undefined
926     if (GEP1MaxLookupReached)
927       return MayAlias;
928   }
929
930   // In the two GEP Case, if there is no difference in the offsets of the
931   // computed pointers, the resultant pointers are a must alias.  This
932   // hapens when we have two lexically identical GEP's (for example).
933   //
934   // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
935   // must aliases the GEP, the end result is a must alias also.
936   if (GEP1BaseOffset == 0 && GEP1VariableIndices.empty())
937     return MustAlias;
938
939   // If there is a constant difference between the pointers, but the difference
940   // is less than the size of the associated memory object, then we know
941   // that the objects are partially overlapping.  If the difference is
942   // greater, we know they do not overlap.
943   if (GEP1BaseOffset != 0 && GEP1VariableIndices.empty()) {
944     if (GEP1BaseOffset >= 0) {
945       if (V2Size != MemoryLocation::UnknownSize) {
946         if ((uint64_t)GEP1BaseOffset < V2Size)
947           return PartialAlias;
948         return NoAlias;
949       }
950     } else {
951       // We have the situation where:
952       // +                +
953       // | BaseOffset     |
954       // ---------------->|
955       // |-->V1Size       |-------> V2Size
956       // GEP1             V2
957       // We need to know that V2Size is not unknown, otherwise we might have
958       // stripped a gep with negative index ('gep <ptr>, -1, ...).
959       if (V1Size != MemoryLocation::UnknownSize &&
960           V2Size != MemoryLocation::UnknownSize) {
961         if (-(uint64_t)GEP1BaseOffset < V1Size)
962           return PartialAlias;
963         return NoAlias;
964       }
965     }
966   }
967
968   if (!GEP1VariableIndices.empty()) {
969     uint64_t Modulo = 0;
970     bool AllPositive = true;
971     for (unsigned i = 0, e = GEP1VariableIndices.size(); i != e; ++i) {
972
973       // Try to distinguish something like &A[i][1] against &A[42][0].
974       // Grab the least significant bit set in any of the scales. We
975       // don't need std::abs here (even if the scale's negative) as we'll
976       // be ^'ing Modulo with itself later.
977       Modulo |= (uint64_t)GEP1VariableIndices[i].Scale;
978
979       if (AllPositive) {
980         // If the Value could change between cycles, then any reasoning about
981         // the Value this cycle may not hold in the next cycle. We'll just
982         // give up if we can't determine conditions that hold for every cycle:
983         const Value *V = GEP1VariableIndices[i].V;
984
985         bool SignKnownZero, SignKnownOne;
986         ComputeSignBit(const_cast<Value *>(V), SignKnownZero, SignKnownOne, *DL,
987                        0, AC1, nullptr, DT);
988
989         // Zero-extension widens the variable, and so forces the sign
990         // bit to zero.
991         bool IsZExt = GEP1VariableIndices[i].Extension == EK_ZeroExt;
992         SignKnownZero |= IsZExt;
993         SignKnownOne &= !IsZExt;
994
995         // If the variable begins with a zero then we know it's
996         // positive, regardless of whether the value is signed or
997         // unsigned.
998         int64_t Scale = GEP1VariableIndices[i].Scale;
999         AllPositive =
1000             (SignKnownZero && Scale >= 0) || (SignKnownOne && Scale < 0);
1001       }
1002     }
1003
1004     Modulo = Modulo ^ (Modulo & (Modulo - 1));
1005
1006     // We can compute the difference between the two addresses
1007     // mod Modulo. Check whether that difference guarantees that the
1008     // two locations do not alias.
1009     uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
1010     if (V1Size != MemoryLocation::UnknownSize &&
1011         V2Size != MemoryLocation::UnknownSize && ModOffset >= V2Size &&
1012         V1Size <= Modulo - ModOffset)
1013       return NoAlias;
1014
1015     // If we know all the variables are positive, then GEP1 >= GEP1BasePtr.
1016     // If GEP1BasePtr > V2 (GEP1BaseOffset > 0) then we know the pointers
1017     // don't alias if V2Size can fit in the gap between V2 and GEP1BasePtr.
1018     if (AllPositive && GEP1BaseOffset > 0 && V2Size <= (uint64_t)GEP1BaseOffset)
1019       return NoAlias;
1020   }
1021
1022   // Statically, we can see that the base objects are the same, but the
1023   // pointers have dynamic offsets which we can't resolve. And none of our
1024   // little tricks above worked.
1025   //
1026   // TODO: Returning PartialAlias instead of MayAlias is a mild hack; the
1027   // practical effect of this is protecting TBAA in the case of dynamic
1028   // indices into arrays of unions or malloc'd memory.
1029   return PartialAlias;
1030 }
1031
1032 static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {
1033   // If the results agree, take it.
1034   if (A == B)
1035     return A;
1036   // A mix of PartialAlias and MustAlias is PartialAlias.
1037   if ((A == PartialAlias && B == MustAlias) ||
1038       (B == PartialAlias && A == MustAlias))
1039     return PartialAlias;
1040   // Otherwise, we don't know anything.
1041   return MayAlias;
1042 }
1043
1044 /// aliasSelect - Provide a bunch of ad-hoc rules to disambiguate a Select
1045 /// instruction against another.
1046 AliasResult BasicAliasAnalysis::aliasSelect(const SelectInst *SI,
1047                                             uint64_t SISize,
1048                                             const AAMDNodes &SIAAInfo,
1049                                             const Value *V2, uint64_t V2Size,
1050                                             const AAMDNodes &V2AAInfo) {
1051   // If the values are Selects with the same condition, we can do a more precise
1052   // check: just check for aliases between the values on corresponding arms.
1053   if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1054     if (SI->getCondition() == SI2->getCondition()) {
1055       AliasResult Alias = aliasCheck(SI->getTrueValue(), SISize, SIAAInfo,
1056                                      SI2->getTrueValue(), V2Size, V2AAInfo);
1057       if (Alias == MayAlias)
1058         return MayAlias;
1059       AliasResult ThisAlias =
1060           aliasCheck(SI->getFalseValue(), SISize, SIAAInfo,
1061                      SI2->getFalseValue(), V2Size, V2AAInfo);
1062       return MergeAliasResults(ThisAlias, Alias);
1063     }
1064
1065   // If both arms of the Select node NoAlias or MustAlias V2, then returns
1066   // NoAlias / MustAlias. Otherwise, returns MayAlias.
1067   AliasResult Alias =
1068       aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(), SISize, SIAAInfo);
1069   if (Alias == MayAlias)
1070     return MayAlias;
1071
1072   AliasResult ThisAlias =
1073       aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(), SISize, SIAAInfo);
1074   return MergeAliasResults(ThisAlias, Alias);
1075 }
1076
1077 // aliasPHI - Provide a bunch of ad-hoc rules to disambiguate a PHI instruction
1078 // against another.
1079 AliasResult BasicAliasAnalysis::aliasPHI(const PHINode *PN, uint64_t PNSize,
1080                                          const AAMDNodes &PNAAInfo,
1081                                          const Value *V2, uint64_t V2Size,
1082                                          const AAMDNodes &V2AAInfo) {
1083   // Track phi nodes we have visited. We use this information when we determine
1084   // value equivalence.
1085   VisitedPhiBBs.insert(PN->getParent());
1086
1087   // If the values are PHIs in the same block, we can do a more precise
1088   // as well as efficient check: just check for aliases between the values
1089   // on corresponding edges.
1090   if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1091     if (PN2->getParent() == PN->getParent()) {
1092       LocPair Locs(MemoryLocation(PN, PNSize, PNAAInfo),
1093                    MemoryLocation(V2, V2Size, V2AAInfo));
1094       if (PN > V2)
1095         std::swap(Locs.first, Locs.second);
1096       // Analyse the PHIs' inputs under the assumption that the PHIs are
1097       // NoAlias.
1098       // If the PHIs are May/MustAlias there must be (recursively) an input
1099       // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
1100       // there must be an operation on the PHIs within the PHIs' value cycle
1101       // that causes a MayAlias.
1102       // Pretend the phis do not alias.
1103       AliasResult Alias = NoAlias;
1104       assert(AliasCache.count(Locs) &&
1105              "There must exist an entry for the phi node");
1106       AliasResult OrigAliasResult = AliasCache[Locs];
1107       AliasCache[Locs] = NoAlias;
1108
1109       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1110         AliasResult ThisAlias =
1111             aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo,
1112                        PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
1113                        V2Size, V2AAInfo);
1114         Alias = MergeAliasResults(ThisAlias, Alias);
1115         if (Alias == MayAlias)
1116           break;
1117       }
1118
1119       // Reset if speculation failed.
1120       if (Alias != NoAlias)
1121         AliasCache[Locs] = OrigAliasResult;
1122
1123       return Alias;
1124     }
1125
1126   SmallPtrSet<Value *, 4> UniqueSrc;
1127   SmallVector<Value *, 4> V1Srcs;
1128   bool isRecursive = false;
1129   for (Value *PV1 : PN->incoming_values()) {
1130     if (isa<PHINode>(PV1))
1131       // If any of the source itself is a PHI, return MayAlias conservatively
1132       // to avoid compile time explosion. The worst possible case is if both
1133       // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
1134       // and 'n' are the number of PHI sources.
1135       return MayAlias;
1136
1137     if (EnableRecPhiAnalysis)
1138       if (GEPOperator *PV1GEP = dyn_cast<GEPOperator>(PV1)) {
1139         // Check whether the incoming value is a GEP that advances the pointer
1140         // result of this PHI node (e.g. in a loop). If this is the case, we
1141         // would recurse and always get a MayAlias. Handle this case specially
1142         // below.
1143         if (PV1GEP->getPointerOperand() == PN && PV1GEP->getNumIndices() == 1 &&
1144             isa<ConstantInt>(PV1GEP->idx_begin())) {
1145           isRecursive = true;
1146           continue;
1147         }
1148       }
1149
1150     if (UniqueSrc.insert(PV1).second)
1151       V1Srcs.push_back(PV1);
1152   }
1153
1154   // If this PHI node is recursive, set the size of the accessed memory to
1155   // unknown to represent all the possible values the GEP could advance the
1156   // pointer to.
1157   if (isRecursive)
1158     PNSize = MemoryLocation::UnknownSize;
1159
1160   AliasResult Alias =
1161       aliasCheck(V2, V2Size, V2AAInfo, V1Srcs[0], PNSize, PNAAInfo);
1162
1163   // Early exit if the check of the first PHI source against V2 is MayAlias.
1164   // Other results are not possible.
1165   if (Alias == MayAlias)
1166     return MayAlias;
1167
1168   // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1169   // NoAlias / MustAlias. Otherwise, returns MayAlias.
1170   for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1171     Value *V = V1Srcs[i];
1172
1173     AliasResult ThisAlias =
1174         aliasCheck(V2, V2Size, V2AAInfo, V, PNSize, PNAAInfo);
1175     Alias = MergeAliasResults(ThisAlias, Alias);
1176     if (Alias == MayAlias)
1177       break;
1178   }
1179
1180   return Alias;
1181 }
1182
1183 // aliasCheck - Provide a bunch of ad-hoc rules to disambiguate in common cases,
1184 // such as array references.
1185 //
1186 AliasResult BasicAliasAnalysis::aliasCheck(const Value *V1, uint64_t V1Size,
1187                                            AAMDNodes V1AAInfo, const Value *V2,
1188                                            uint64_t V2Size,
1189                                            AAMDNodes V2AAInfo) {
1190   // If either of the memory references is empty, it doesn't matter what the
1191   // pointer values are.
1192   if (V1Size == 0 || V2Size == 0)
1193     return NoAlias;
1194
1195   // Strip off any casts if they exist.
1196   V1 = V1->stripPointerCasts();
1197   V2 = V2->stripPointerCasts();
1198
1199   // If V1 or V2 is undef, the result is NoAlias because we can always pick a
1200   // value for undef that aliases nothing in the program.
1201   if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
1202     return NoAlias;
1203
1204   // Are we checking for alias of the same value?
1205   // Because we look 'through' phi nodes we could look at "Value" pointers from
1206   // different iterations. We must therefore make sure that this is not the
1207   // case. The function isValueEqualInPotentialCycles ensures that this cannot
1208   // happen by looking at the visited phi nodes and making sure they cannot
1209   // reach the value.
1210   if (isValueEqualInPotentialCycles(V1, V2))
1211     return MustAlias;
1212
1213   if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
1214     return NoAlias; // Scalars cannot alias each other
1215
1216   // Figure out what objects these things are pointing to if we can.
1217   const Value *O1 = GetUnderlyingObject(V1, *DL, MaxLookupSearchDepth);
1218   const Value *O2 = GetUnderlyingObject(V2, *DL, MaxLookupSearchDepth);
1219
1220   // Null values in the default address space don't point to any object, so they
1221   // don't alias any other pointer.
1222   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1223     if (CPN->getType()->getAddressSpace() == 0)
1224       return NoAlias;
1225   if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1226     if (CPN->getType()->getAddressSpace() == 0)
1227       return NoAlias;
1228
1229   if (O1 != O2) {
1230     // If V1/V2 point to two different objects we know that we have no alias.
1231     if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
1232       return NoAlias;
1233
1234     // Constant pointers can't alias with non-const isIdentifiedObject objects.
1235     if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1236         (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
1237       return NoAlias;
1238
1239     // Function arguments can't alias with things that are known to be
1240     // unambigously identified at the function level.
1241     if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1242         (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
1243       return NoAlias;
1244
1245     // Most objects can't alias null.
1246     if ((isa<ConstantPointerNull>(O2) && isKnownNonNull(O1)) ||
1247         (isa<ConstantPointerNull>(O1) && isKnownNonNull(O2)))
1248       return NoAlias;
1249
1250     // If one pointer is the result of a call/invoke or load and the other is a
1251     // non-escaping local object within the same function, then we know the
1252     // object couldn't escape to a point where the call could return it.
1253     //
1254     // Note that if the pointers are in different functions, there are a
1255     // variety of complications. A call with a nocapture argument may still
1256     // temporary store the nocapture argument's value in a temporary memory
1257     // location if that memory location doesn't escape. Or it may pass a
1258     // nocapture value to other functions as long as they don't capture it.
1259     if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1260       return NoAlias;
1261     if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1262       return NoAlias;
1263   }
1264
1265   // If the size of one access is larger than the entire object on the other
1266   // side, then we know such behavior is undefined and can assume no alias.
1267   if (DL)
1268     if ((V1Size != MemoryLocation::UnknownSize &&
1269          isObjectSmallerThan(O2, V1Size, *DL, *TLI)) ||
1270         (V2Size != MemoryLocation::UnknownSize &&
1271          isObjectSmallerThan(O1, V2Size, *DL, *TLI)))
1272       return NoAlias;
1273
1274   // Check the cache before climbing up use-def chains. This also terminates
1275   // otherwise infinitely recursive queries.
1276   LocPair Locs(MemoryLocation(V1, V1Size, V1AAInfo),
1277                MemoryLocation(V2, V2Size, V2AAInfo));
1278   if (V1 > V2)
1279     std::swap(Locs.first, Locs.second);
1280   std::pair<AliasCacheTy::iterator, bool> Pair =
1281       AliasCache.insert(std::make_pair(Locs, MayAlias));
1282   if (!Pair.second)
1283     return Pair.first->second;
1284
1285   // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1286   // GEP can't simplify, we don't even look at the PHI cases.
1287   if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
1288     std::swap(V1, V2);
1289     std::swap(V1Size, V2Size);
1290     std::swap(O1, O2);
1291     std::swap(V1AAInfo, V2AAInfo);
1292   }
1293   if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1294     AliasResult Result =
1295         aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2);
1296     if (Result != MayAlias)
1297       return AliasCache[Locs] = Result;
1298   }
1299
1300   if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1301     std::swap(V1, V2);
1302     std::swap(V1Size, V2Size);
1303     std::swap(V1AAInfo, V2AAInfo);
1304   }
1305   if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1306     AliasResult Result = aliasPHI(PN, V1Size, V1AAInfo, V2, V2Size, V2AAInfo);
1307     if (Result != MayAlias)
1308       return AliasCache[Locs] = Result;
1309   }
1310
1311   if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1312     std::swap(V1, V2);
1313     std::swap(V1Size, V2Size);
1314     std::swap(V1AAInfo, V2AAInfo);
1315   }
1316   if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1317     AliasResult Result =
1318         aliasSelect(S1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo);
1319     if (Result != MayAlias)
1320       return AliasCache[Locs] = Result;
1321   }
1322
1323   // If both pointers are pointing into the same object and one of them
1324   // accesses is accessing the entire object, then the accesses must
1325   // overlap in some way.
1326   if (DL && O1 == O2)
1327     if ((V1Size != MemoryLocation::UnknownSize &&
1328          isObjectSize(O1, V1Size, *DL, *TLI)) ||
1329         (V2Size != MemoryLocation::UnknownSize &&
1330          isObjectSize(O2, V2Size, *DL, *TLI)))
1331       return AliasCache[Locs] = PartialAlias;
1332
1333   AliasResult Result =
1334       AliasAnalysis::alias(MemoryLocation(V1, V1Size, V1AAInfo),
1335                            MemoryLocation(V2, V2Size, V2AAInfo));
1336   return AliasCache[Locs] = Result;
1337 }
1338
1339 bool BasicAliasAnalysis::isValueEqualInPotentialCycles(const Value *V,
1340                                                        const Value *V2) {
1341   if (V != V2)
1342     return false;
1343
1344   const Instruction *Inst = dyn_cast<Instruction>(V);
1345   if (!Inst)
1346     return true;
1347
1348   if (VisitedPhiBBs.empty())
1349     return true;
1350
1351   if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1352     return false;
1353
1354   // Use dominance or loop info if available.
1355   DominatorTreeWrapperPass *DTWP =
1356       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
1357   DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
1358   auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
1359   LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
1360
1361   // Make sure that the visited phis cannot reach the Value. This ensures that
1362   // the Values cannot come from different iterations of a potential cycle the
1363   // phi nodes could be involved in.
1364   for (auto *P : VisitedPhiBBs)
1365     if (isPotentiallyReachable(P->begin(), Inst, DT, LI))
1366       return false;
1367
1368   return true;
1369 }
1370
1371 /// GetIndexDifference - Dest and Src are the variable indices from two
1372 /// decomposed GetElementPtr instructions GEP1 and GEP2 which have common base
1373 /// pointers.  Subtract the GEP2 indices from GEP1 to find the symbolic
1374 /// difference between the two pointers.
1375 void BasicAliasAnalysis::GetIndexDifference(
1376     SmallVectorImpl<VariableGEPIndex> &Dest,
1377     const SmallVectorImpl<VariableGEPIndex> &Src) {
1378   if (Src.empty())
1379     return;
1380
1381   for (unsigned i = 0, e = Src.size(); i != e; ++i) {
1382     const Value *V = Src[i].V;
1383     ExtensionKind Extension = Src[i].Extension;
1384     int64_t Scale = Src[i].Scale;
1385
1386     // Find V in Dest.  This is N^2, but pointer indices almost never have more
1387     // than a few variable indexes.
1388     for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
1389       if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
1390           Dest[j].Extension != Extension)
1391         continue;
1392
1393       // If we found it, subtract off Scale V's from the entry in Dest.  If it
1394       // goes to zero, remove the entry.
1395       if (Dest[j].Scale != Scale)
1396         Dest[j].Scale -= Scale;
1397       else
1398         Dest.erase(Dest.begin() + j);
1399       Scale = 0;
1400       break;
1401     }
1402
1403     // If we didn't consume this entry, add it to the end of the Dest list.
1404     if (Scale) {
1405       VariableGEPIndex Entry = {V, Extension, -Scale};
1406       Dest.push_back(Entry);
1407     }
1408   }
1409 }