BasicAliasAnalysis.cpp revision ceb4d1aecb9deffe59b3dcdc9a783ffde8477be9
1//===- BasicAliasAnalysis.cpp - Local 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 default implementation of the Alias Analysis interface
11// that simply implements a few identities (two different globals cannot alias,
12// etc), but otherwise does no analysis.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Analysis/AliasAnalysis.h"
17#include "llvm/Analysis/Passes.h"
18#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
21#include "llvm/GlobalVariable.h"
22#include "llvm/Instructions.h"
23#include "llvm/IntrinsicInst.h"
24#include "llvm/Pass.h"
25#include "llvm/Target/TargetData.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/STLExtras.h"
28#include "llvm/Support/Compiler.h"
29#include "llvm/Support/GetElementPtrTypeIterator.h"
30#include "llvm/Support/ManagedStatic.h"
31#include <algorithm>
32using namespace llvm;
33
34//===----------------------------------------------------------------------===//
35// Useful predicates
36//===----------------------------------------------------------------------===//
37
38// Determine if a value escapes from the function it is contained in (being
39// returned by the function does not count as escaping here).  If a value local
40// to the function does not escape, there is no way another function can mod/ref
41// it.  We do this by looking at its uses and determining if they can escape
42// (recursively).
43static bool AddressMightEscape(const Value *V) {
44  for (Value::use_const_iterator UI = V->use_begin(), E = V->use_end();
45       UI != E; ++UI) {
46    const Instruction *I = cast<Instruction>(*UI);
47    switch (I->getOpcode()) {
48    case Instruction::Load:
49      break; //next use.
50    case Instruction::Store:
51      if (I->getOperand(0) == V)
52        return true; // Escapes if the pointer is stored.
53      break; // next use.
54    case Instruction::GetElementPtr:
55      if (AddressMightEscape(I))
56        return true;
57      break; // next use.
58    case Instruction::BitCast:
59      if (AddressMightEscape(I))
60        return true;
61      break; // next use
62    case Instruction::Ret:
63      // If returned, the address will escape to calling functions, but no
64      // callees could modify it.
65      break; // next use
66    case Instruction::Call:
67      // If the argument to the call has the nocapture attribute, then the call
68      // may store or load to the pointer, but it cannot escape.
69      if (cast<CallInst>(I)->paramHasAttr(UI.getOperandNo(),
70                                          Attribute::NoCapture))
71        continue;
72      return true;
73    case Instruction::Invoke:
74      // If the argument to the call has the nocapture attribute, then the call
75      // may store or load to the pointer, but it cannot escape.
76      if (cast<InvokeInst>(I)->paramHasAttr(UI.getOperandNo()-2,
77                                            Attribute::NoCapture))
78        continue;
79      return true;
80    default:
81      return true;
82    }
83  }
84  return false;
85}
86
87static const User *isGEP(const Value *V) {
88  if (isa<GetElementPtrInst>(V) ||
89      (isa<ConstantExpr>(V) &&
90       cast<ConstantExpr>(V)->getOpcode() == Instruction::GetElementPtr))
91    return cast<User>(V);
92  return 0;
93}
94
95static const Value *GetGEPOperands(const Value *V,
96                                   SmallVector<Value*, 16> &GEPOps) {
97  assert(GEPOps.empty() && "Expect empty list to populate!");
98  GEPOps.insert(GEPOps.end(), cast<User>(V)->op_begin()+1,
99                cast<User>(V)->op_end());
100
101  // Accumulate all of the chained indexes into the operand array
102  V = cast<User>(V)->getOperand(0);
103
104  while (const User *G = isGEP(V)) {
105    if (!isa<Constant>(GEPOps[0]) || isa<GlobalValue>(GEPOps[0]) ||
106        !cast<Constant>(GEPOps[0])->isNullValue())
107      break;  // Don't handle folding arbitrary pointer offsets yet...
108    GEPOps.erase(GEPOps.begin());   // Drop the zero index
109    GEPOps.insert(GEPOps.begin(), G->op_begin()+1, G->op_end());
110    V = G->getOperand(0);
111  }
112  return V;
113}
114
115/// isNoAliasCall - Return true if this pointer is returned by a noalias
116/// function.
117static bool isNoAliasCall(const Value *V) {
118  if (isa<CallInst>(V) || isa<InvokeInst>(V))
119    return CallSite(const_cast<Instruction*>(cast<Instruction>(V)))
120      .paramHasAttr(0, Attribute::NoAlias);
121  return false;
122}
123
124/// isIdentifiedObject - Return true if this pointer refers to a distinct and
125/// identifiable object.  This returns true for:
126///    Global Variables and Functions
127///    Allocas and Mallocs
128///    ByVal and NoAlias Arguments
129///    NoAlias returns
130///
131static bool isIdentifiedObject(const Value *V) {
132  if (isa<GlobalValue>(V) || isa<AllocationInst>(V) || isNoAliasCall(V))
133    return true;
134  if (const Argument *A = dyn_cast<Argument>(V))
135    return A->hasNoAliasAttr() || A->hasByValAttr();
136  return false;
137}
138
139/// isKnownNonNull - Return true if we know that the specified value is never
140/// null.
141static bool isKnownNonNull(const Value *V) {
142  // Alloca never returns null, malloc might.
143  if (isa<AllocaInst>(V)) return true;
144
145  // A byval argument is never null.
146  if (const Argument *A = dyn_cast<Argument>(V))
147    return A->hasByValAttr();
148
149  // Global values are not null unless extern weak.
150  if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
151    return !GV->hasExternalWeakLinkage();
152  return false;
153}
154
155/// isNonEscapingLocalObject - Return true if the pointer is to a function-local
156/// object that never escapes from the function.
157static bool isNonEscapingLocalObject(const Value *V) {
158  // If this is a local allocation, check to see if it escapes.
159  if (isa<AllocationInst>(V) || isNoAliasCall(V))
160    return !AddressMightEscape(V);
161
162  // If this is an argument that corresponds to a byval or noalias argument,
163  // then it has not escaped before entering the function.  Check if it escapes
164  // inside the function.
165  if (const Argument *A = dyn_cast<Argument>(V))
166    if (A->hasByValAttr() || A->hasNoAliasAttr()) {
167      // Don't bother analyzing arguments already known not to escape.
168      if (A->hasNoCaptureAttr())
169        return true;
170      return !AddressMightEscape(V);
171    }
172  return false;
173}
174
175
176/// isObjectSmallerThan - Return true if we can prove that the object specified
177/// by V is smaller than Size.
178static bool isObjectSmallerThan(const Value *V, unsigned Size,
179                                const TargetData &TD) {
180  const Type *AccessTy;
181  if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
182    AccessTy = GV->getType()->getElementType();
183  } else if (const AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
184    if (!AI->isArrayAllocation())
185      AccessTy = AI->getType()->getElementType();
186    else
187      return false;
188  } else if (const Argument *A = dyn_cast<Argument>(V)) {
189    if (A->hasByValAttr())
190      AccessTy = cast<PointerType>(A->getType())->getElementType();
191    else
192      return false;
193  } else {
194    return false;
195  }
196
197  if (AccessTy->isSized())
198    return TD.getTypePaddedSize(AccessTy) < Size;
199  return false;
200}
201
202//===----------------------------------------------------------------------===//
203// NoAA Pass
204//===----------------------------------------------------------------------===//
205
206namespace {
207  /// NoAA - This class implements the -no-aa pass, which always returns "I
208  /// don't know" for alias queries.  NoAA is unlike other alias analysis
209  /// implementations, in that it does not chain to a previous analysis.  As
210  /// such it doesn't follow many of the rules that other alias analyses must.
211  ///
212  struct VISIBILITY_HIDDEN NoAA : public ImmutablePass, public AliasAnalysis {
213    static char ID; // Class identification, replacement for typeinfo
214    NoAA() : ImmutablePass(&ID) {}
215    explicit NoAA(void *PID) : ImmutablePass(PID) { }
216
217    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
218      AU.addRequired<TargetData>();
219    }
220
221    virtual void initializePass() {
222      TD = &getAnalysis<TargetData>();
223    }
224
225    virtual AliasResult alias(const Value *V1, unsigned V1Size,
226                              const Value *V2, unsigned V2Size) {
227      return MayAlias;
228    }
229
230    virtual ModRefBehavior getModRefBehavior(Function *F, CallSite CS,
231                                         std::vector<PointerAccessInfo> *Info) {
232      return UnknownModRefBehavior;
233    }
234
235    virtual void getArgumentAccesses(Function *F, CallSite CS,
236                                     std::vector<PointerAccessInfo> &Info) {
237      assert(0 && "This method may not be called on this function!");
238    }
239
240    virtual void getMustAliases(Value *P, std::vector<Value*> &RetVals) { }
241    virtual bool pointsToConstantMemory(const Value *P) { return false; }
242    virtual ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size) {
243      return ModRef;
244    }
245    virtual ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
246      return ModRef;
247    }
248    virtual bool hasNoModRefInfoForCalls() const { return true; }
249
250    virtual void deleteValue(Value *V) {}
251    virtual void copyValue(Value *From, Value *To) {}
252  };
253}  // End of anonymous namespace
254
255// Register this pass...
256char NoAA::ID = 0;
257static RegisterPass<NoAA>
258U("no-aa", "No Alias Analysis (always returns 'may' alias)", true, true);
259
260// Declare that we implement the AliasAnalysis interface
261static RegisterAnalysisGroup<AliasAnalysis> V(U);
262
263ImmutablePass *llvm::createNoAAPass() { return new NoAA(); }
264
265//===----------------------------------------------------------------------===//
266// BasicAA Pass
267//===----------------------------------------------------------------------===//
268
269namespace {
270  /// BasicAliasAnalysis - This is the default alias analysis implementation.
271  /// Because it doesn't chain to a previous alias analysis (like -no-aa), it
272  /// derives from the NoAA class.
273  struct VISIBILITY_HIDDEN BasicAliasAnalysis : public NoAA {
274    static char ID; // Class identification, replacement for typeinfo
275    BasicAliasAnalysis() : NoAA(&ID) {}
276    AliasResult alias(const Value *V1, unsigned V1Size,
277                      const Value *V2, unsigned V2Size);
278
279    ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
280    ModRefResult getModRefInfo(CallSite CS1, CallSite CS2);
281
282    /// hasNoModRefInfoForCalls - We can provide mod/ref information against
283    /// non-escaping allocations.
284    virtual bool hasNoModRefInfoForCalls() const { return false; }
285
286    /// pointsToConstantMemory - Chase pointers until we find a (constant
287    /// global) or not.
288    bool pointsToConstantMemory(const Value *P);
289
290  private:
291    // CheckGEPInstructions - Check two GEP instructions with known
292    // must-aliasing base pointers.  This checks to see if the index expressions
293    // preclude the pointers from aliasing...
294    AliasResult
295    CheckGEPInstructions(const Type* BasePtr1Ty,
296                         Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1Size,
297                         const Type *BasePtr2Ty,
298                         Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2Size);
299  };
300}  // End of anonymous namespace
301
302// Register this pass...
303char BasicAliasAnalysis::ID = 0;
304static RegisterPass<BasicAliasAnalysis>
305X("basicaa", "Basic Alias Analysis (default AA impl)", false, true);
306
307// Declare that we implement the AliasAnalysis interface
308static RegisterAnalysisGroup<AliasAnalysis, true> Y(X);
309
310ImmutablePass *llvm::createBasicAliasAnalysisPass() {
311  return new BasicAliasAnalysis();
312}
313
314
315/// pointsToConstantMemory - Chase pointers until we find a (constant
316/// global) or not.
317bool BasicAliasAnalysis::pointsToConstantMemory(const Value *P) {
318  if (const GlobalVariable *GV =
319        dyn_cast<GlobalVariable>(P->getUnderlyingObject()))
320    return GV->isConstant();
321  return false;
322}
323
324// getModRefInfo - Check to see if the specified callsite can clobber the
325// specified memory object.  Since we only look at local properties of this
326// function, we really can't say much about this query.  We do, however, use
327// simple "address taken" analysis on local objects.
328//
329AliasAnalysis::ModRefResult
330BasicAliasAnalysis::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
331  if (!isa<Constant>(P)) {
332    const Value *Object = P->getUnderlyingObject();
333
334    // If this is a tail call and P points to a stack location, we know that
335    // the tail call cannot access or modify the local stack.
336    // We cannot exclude byval arguments here; these belong to the caller of
337    // the current function not to the current function, and a tail callee
338    // may reference them.
339    if (isa<AllocaInst>(Object))
340      if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
341        if (CI->isTailCall())
342          return NoModRef;
343
344    // If the pointer is to a locally allocated object that does not escape,
345    // then the call can not mod/ref the pointer unless the call takes the
346    // argument without capturing it.
347    if (isNonEscapingLocalObject(Object)) {
348      bool passedAsArg = false;
349      // TODO: Eventually only check 'nocapture' arguments.
350      for (CallSite::arg_iterator CI = CS.arg_begin(), CE = CS.arg_end();
351           CI != CE; ++CI)
352        if (isa<PointerType>((*CI)->getType()) &&
353            alias(cast<Value>(CI), ~0U, P, ~0U) != NoAlias)
354          passedAsArg = true;
355
356      if (!passedAsArg)
357        return NoModRef;
358    }
359  }
360
361  // The AliasAnalysis base class has some smarts, lets use them.
362  return AliasAnalysis::getModRefInfo(CS, P, Size);
363}
364
365
366AliasAnalysis::ModRefResult
367BasicAliasAnalysis::getModRefInfo(CallSite CS1, CallSite CS2) {
368  // If CS1 or CS2 are readnone, they don't interact.
369  ModRefBehavior CS1B = AliasAnalysis::getModRefBehavior(CS1);
370  if (CS1B == DoesNotAccessMemory) return NoModRef;
371
372  ModRefBehavior CS2B = AliasAnalysis::getModRefBehavior(CS2);
373  if (CS2B == DoesNotAccessMemory) return NoModRef;
374
375  // If they both only read from memory, just return ref.
376  if (CS1B == OnlyReadsMemory && CS2B == OnlyReadsMemory)
377    return Ref;
378
379  // Otherwise, fall back to NoAA (mod+ref).
380  return NoAA::getModRefInfo(CS1, CS2);
381}
382
383
384// alias - Provide a bunch of ad-hoc rules to disambiguate in common cases, such
385// as array references.
386//
387AliasAnalysis::AliasResult
388BasicAliasAnalysis::alias(const Value *V1, unsigned V1Size,
389                          const Value *V2, unsigned V2Size) {
390  // Strip off any constant expression casts if they exist
391  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V1))
392    if (CE->isCast() && isa<PointerType>(CE->getOperand(0)->getType()))
393      V1 = CE->getOperand(0);
394  if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V2))
395    if (CE->isCast() && isa<PointerType>(CE->getOperand(0)->getType()))
396      V2 = CE->getOperand(0);
397
398  // Are we checking for alias of the same value?
399  if (V1 == V2) return MustAlias;
400
401  if (!isa<PointerType>(V1->getType()) || !isa<PointerType>(V2->getType()))
402    return NoAlias;  // Scalars cannot alias each other
403
404  // Strip off cast instructions.   Since V1 and V2 are pointers, they must be
405  // pointer<->pointer bitcasts.
406  if (const BitCastInst *I = dyn_cast<BitCastInst>(V1))
407    return alias(I->getOperand(0), V1Size, V2, V2Size);
408  if (const BitCastInst *I = dyn_cast<BitCastInst>(V2))
409    return alias(V1, V1Size, I->getOperand(0), V2Size);
410
411  // Figure out what objects these things are pointing to if we can.
412  const Value *O1 = V1->getUnderlyingObject();
413  const Value *O2 = V2->getUnderlyingObject();
414
415  if (O1 != O2) {
416    // If V1/V2 point to two different objects we know that we have no alias.
417    if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
418      return NoAlias;
419
420    // Arguments can't alias with local allocations or noalias calls.
421    if ((isa<Argument>(O1) && (isa<AllocationInst>(O2) || isNoAliasCall(O2))) ||
422        (isa<Argument>(O2) && (isa<AllocationInst>(O1) || isNoAliasCall(O1))))
423      return NoAlias;
424
425    // Most objects can't alias null.
426    if ((isa<ConstantPointerNull>(V2) && isKnownNonNull(O1)) ||
427        (isa<ConstantPointerNull>(V1) && isKnownNonNull(O2)))
428      return NoAlias;
429  }
430
431  // If the size of one access is larger than the entire object on the other
432  // side, then we know such behavior is undefined and can assume no alias.
433  const TargetData &TD = getTargetData();
434  if ((V1Size != ~0U && isObjectSmallerThan(O2, V1Size, TD)) ||
435      (V2Size != ~0U && isObjectSmallerThan(O1, V2Size, TD)))
436    return NoAlias;
437
438  // If one pointer is the result of a call/invoke and the other is a
439  // non-escaping local object, then we know the object couldn't escape to a
440  // point where the call could return it.
441  if ((isa<CallInst>(O1) || isa<InvokeInst>(O1)) &&
442      isNonEscapingLocalObject(O2))
443    return NoAlias;
444  if ((isa<CallInst>(O2) || isa<InvokeInst>(O2)) &&
445      isNonEscapingLocalObject(O1))
446    return NoAlias;
447
448  // If we have two gep instructions with must-alias'ing base pointers, figure
449  // out if the indexes to the GEP tell us anything about the derived pointer.
450  // Note that we also handle chains of getelementptr instructions as well as
451  // constant expression getelementptrs here.
452  //
453  if (isGEP(V1) && isGEP(V2)) {
454    const User *GEP1 = cast<User>(V1);
455    const User *GEP2 = cast<User>(V2);
456
457    // If V1 and V2 are identical GEPs, just recurse down on both of them.
458    // This allows us to analyze things like:
459    //   P = gep A, 0, i, 1
460    //   Q = gep B, 0, i, 1
461    // by just analyzing A and B.  This is even safe for variable indices.
462    if (GEP1->getType() == GEP2->getType() &&
463        GEP1->getNumOperands() == GEP2->getNumOperands() &&
464        GEP1->getOperand(0)->getType() == GEP2->getOperand(0)->getType() &&
465        // All operands are the same, ignoring the base.
466        std::equal(GEP1->op_begin()+1, GEP1->op_end(), GEP2->op_begin()+1))
467      return alias(GEP1->getOperand(0), V1Size, GEP2->getOperand(0), V2Size);
468
469
470    // Drill down into the first non-gep value, to test for must-aliasing of
471    // the base pointers.
472    while (isGEP(GEP1->getOperand(0)) &&
473           GEP1->getOperand(1) ==
474           Constant::getNullValue(GEP1->getOperand(1)->getType()))
475      GEP1 = cast<User>(GEP1->getOperand(0));
476    const Value *BasePtr1 = GEP1->getOperand(0);
477
478    while (isGEP(GEP2->getOperand(0)) &&
479           GEP2->getOperand(1) ==
480           Constant::getNullValue(GEP2->getOperand(1)->getType()))
481      GEP2 = cast<User>(GEP2->getOperand(0));
482    const Value *BasePtr2 = GEP2->getOperand(0);
483
484    // Do the base pointers alias?
485    AliasResult BaseAlias = alias(BasePtr1, ~0U, BasePtr2, ~0U);
486    if (BaseAlias == NoAlias) return NoAlias;
487    if (BaseAlias == MustAlias) {
488      // If the base pointers alias each other exactly, check to see if we can
489      // figure out anything about the resultant pointers, to try to prove
490      // non-aliasing.
491
492      // Collect all of the chained GEP operands together into one simple place
493      SmallVector<Value*, 16> GEP1Ops, GEP2Ops;
494      BasePtr1 = GetGEPOperands(V1, GEP1Ops);
495      BasePtr2 = GetGEPOperands(V2, GEP2Ops);
496
497      // If GetGEPOperands were able to fold to the same must-aliased pointer,
498      // do the comparison.
499      if (BasePtr1 == BasePtr2) {
500        AliasResult GAlias =
501          CheckGEPInstructions(BasePtr1->getType(),
502                               &GEP1Ops[0], GEP1Ops.size(), V1Size,
503                               BasePtr2->getType(),
504                               &GEP2Ops[0], GEP2Ops.size(), V2Size);
505        if (GAlias != MayAlias)
506          return GAlias;
507      }
508    }
509  }
510
511  // Check to see if these two pointers are related by a getelementptr
512  // instruction.  If one pointer is a GEP with a non-zero index of the other
513  // pointer, we know they cannot alias.
514  //
515  if (isGEP(V2)) {
516    std::swap(V1, V2);
517    std::swap(V1Size, V2Size);
518  }
519
520  if (V1Size != ~0U && V2Size != ~0U)
521    if (isGEP(V1)) {
522      SmallVector<Value*, 16> GEPOperands;
523      const Value *BasePtr = GetGEPOperands(V1, GEPOperands);
524
525      AliasResult R = alias(BasePtr, V1Size, V2, V2Size);
526      if (R == MustAlias) {
527        // If there is at least one non-zero constant index, we know they cannot
528        // alias.
529        bool ConstantFound = false;
530        bool AllZerosFound = true;
531        for (unsigned i = 0, e = GEPOperands.size(); i != e; ++i)
532          if (const Constant *C = dyn_cast<Constant>(GEPOperands[i])) {
533            if (!C->isNullValue()) {
534              ConstantFound = true;
535              AllZerosFound = false;
536              break;
537            }
538          } else {
539            AllZerosFound = false;
540          }
541
542        // If we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2 must aliases
543        // the ptr, the end result is a must alias also.
544        if (AllZerosFound)
545          return MustAlias;
546
547        if (ConstantFound) {
548          if (V2Size <= 1 && V1Size <= 1)  // Just pointer check?
549            return NoAlias;
550
551          // Otherwise we have to check to see that the distance is more than
552          // the size of the argument... build an index vector that is equal to
553          // the arguments provided, except substitute 0's for any variable
554          // indexes we find...
555          if (cast<PointerType>(
556                BasePtr->getType())->getElementType()->isSized()) {
557            for (unsigned i = 0; i != GEPOperands.size(); ++i)
558              if (!isa<ConstantInt>(GEPOperands[i]))
559                GEPOperands[i] =
560                  Constant::getNullValue(GEPOperands[i]->getType());
561            int64_t Offset =
562              getTargetData().getIndexedOffset(BasePtr->getType(),
563                                               &GEPOperands[0],
564                                               GEPOperands.size());
565
566            if (Offset >= (int64_t)V2Size || Offset <= -(int64_t)V1Size)
567              return NoAlias;
568          }
569        }
570      }
571    }
572
573  return MayAlias;
574}
575
576// This function is used to determine if the indices of two GEP instructions are
577// equal. V1 and V2 are the indices.
578static bool IndexOperandsEqual(Value *V1, Value *V2) {
579  if (V1->getType() == V2->getType())
580    return V1 == V2;
581  if (Constant *C1 = dyn_cast<Constant>(V1))
582    if (Constant *C2 = dyn_cast<Constant>(V2)) {
583      // Sign extend the constants to long types, if necessary
584      if (C1->getType() != Type::Int64Ty)
585        C1 = ConstantExpr::getSExt(C1, Type::Int64Ty);
586      if (C2->getType() != Type::Int64Ty)
587        C2 = ConstantExpr::getSExt(C2, Type::Int64Ty);
588      return C1 == C2;
589    }
590  return false;
591}
592
593/// CheckGEPInstructions - Check two GEP instructions with known must-aliasing
594/// base pointers.  This checks to see if the index expressions preclude the
595/// pointers from aliasing...
596AliasAnalysis::AliasResult
597BasicAliasAnalysis::CheckGEPInstructions(
598  const Type* BasePtr1Ty, Value **GEP1Ops, unsigned NumGEP1Ops, unsigned G1S,
599  const Type *BasePtr2Ty, Value **GEP2Ops, unsigned NumGEP2Ops, unsigned G2S) {
600  // We currently can't handle the case when the base pointers have different
601  // primitive types.  Since this is uncommon anyway, we are happy being
602  // extremely conservative.
603  if (BasePtr1Ty != BasePtr2Ty)
604    return MayAlias;
605
606  const PointerType *GEPPointerTy = cast<PointerType>(BasePtr1Ty);
607
608  // Find the (possibly empty) initial sequence of equal values... which are not
609  // necessarily constants.
610  unsigned NumGEP1Operands = NumGEP1Ops, NumGEP2Operands = NumGEP2Ops;
611  unsigned MinOperands = std::min(NumGEP1Operands, NumGEP2Operands);
612  unsigned MaxOperands = std::max(NumGEP1Operands, NumGEP2Operands);
613  unsigned UnequalOper = 0;
614  while (UnequalOper != MinOperands &&
615         IndexOperandsEqual(GEP1Ops[UnequalOper], GEP2Ops[UnequalOper])) {
616    // Advance through the type as we go...
617    ++UnequalOper;
618    if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
619      BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[UnequalOper-1]);
620    else {
621      // If all operands equal each other, then the derived pointers must
622      // alias each other...
623      BasePtr1Ty = 0;
624      assert(UnequalOper == NumGEP1Operands && UnequalOper == NumGEP2Operands &&
625             "Ran out of type nesting, but not out of operands?");
626      return MustAlias;
627    }
628  }
629
630  // If we have seen all constant operands, and run out of indexes on one of the
631  // getelementptrs, check to see if the tail of the leftover one is all zeros.
632  // If so, return mustalias.
633  if (UnequalOper == MinOperands) {
634    if (NumGEP1Ops < NumGEP2Ops) {
635      std::swap(GEP1Ops, GEP2Ops);
636      std::swap(NumGEP1Ops, NumGEP2Ops);
637    }
638
639    bool AllAreZeros = true;
640    for (unsigned i = UnequalOper; i != MaxOperands; ++i)
641      if (!isa<Constant>(GEP1Ops[i]) ||
642          !cast<Constant>(GEP1Ops[i])->isNullValue()) {
643        AllAreZeros = false;
644        break;
645      }
646    if (AllAreZeros) return MustAlias;
647  }
648
649
650  // So now we know that the indexes derived from the base pointers,
651  // which are known to alias, are different.  We can still determine a
652  // no-alias result if there are differing constant pairs in the index
653  // chain.  For example:
654  //        A[i][0] != A[j][1] iff (&A[0][1]-&A[0][0] >= std::max(G1S, G2S))
655  //
656  // We have to be careful here about array accesses.  In particular, consider:
657  //        A[1][0] vs A[0][i]
658  // In this case, we don't *know* that the array will be accessed in bounds:
659  // the index could even be negative.  Because of this, we have to
660  // conservatively *give up* and return may alias.  We disregard differing
661  // array subscripts that are followed by a variable index without going
662  // through a struct.
663  //
664  unsigned SizeMax = std::max(G1S, G2S);
665  if (SizeMax == ~0U) return MayAlias; // Avoid frivolous work.
666
667  // Scan for the first operand that is constant and unequal in the
668  // two getelementptrs...
669  unsigned FirstConstantOper = UnequalOper;
670  for (; FirstConstantOper != MinOperands; ++FirstConstantOper) {
671    const Value *G1Oper = GEP1Ops[FirstConstantOper];
672    const Value *G2Oper = GEP2Ops[FirstConstantOper];
673
674    if (G1Oper != G2Oper)   // Found non-equal constant indexes...
675      if (Constant *G1OC = dyn_cast<ConstantInt>(const_cast<Value*>(G1Oper)))
676        if (Constant *G2OC = dyn_cast<ConstantInt>(const_cast<Value*>(G2Oper))){
677          if (G1OC->getType() != G2OC->getType()) {
678            // Sign extend both operands to long.
679            if (G1OC->getType() != Type::Int64Ty)
680              G1OC = ConstantExpr::getSExt(G1OC, Type::Int64Ty);
681            if (G2OC->getType() != Type::Int64Ty)
682              G2OC = ConstantExpr::getSExt(G2OC, Type::Int64Ty);
683            GEP1Ops[FirstConstantOper] = G1OC;
684            GEP2Ops[FirstConstantOper] = G2OC;
685          }
686
687          if (G1OC != G2OC) {
688            // Handle the "be careful" case above: if this is an array/vector
689            // subscript, scan for a subsequent variable array index.
690            if (isa<SequentialType>(BasePtr1Ty))  {
691              const Type *NextTy =
692                cast<SequentialType>(BasePtr1Ty)->getElementType();
693              bool isBadCase = false;
694
695              for (unsigned Idx = FirstConstantOper+1;
696                   Idx != MinOperands && isa<SequentialType>(NextTy); ++Idx) {
697                const Value *V1 = GEP1Ops[Idx], *V2 = GEP2Ops[Idx];
698                if (!isa<Constant>(V1) || !isa<Constant>(V2)) {
699                  isBadCase = true;
700                  break;
701                }
702                NextTy = cast<SequentialType>(NextTy)->getElementType();
703              }
704
705              if (isBadCase) G1OC = 0;
706            }
707
708            // Make sure they are comparable (ie, not constant expressions), and
709            // make sure the GEP with the smaller leading constant is GEP1.
710            if (G1OC) {
711              Constant *Compare = ConstantExpr::getICmp(ICmpInst::ICMP_SGT,
712                                                        G1OC, G2OC);
713              if (ConstantInt *CV = dyn_cast<ConstantInt>(Compare)) {
714                if (CV->getZExtValue()) {  // If they are comparable and G2 > G1
715                  std::swap(GEP1Ops, GEP2Ops);  // Make GEP1 < GEP2
716                  std::swap(NumGEP1Ops, NumGEP2Ops);
717                }
718                break;
719              }
720            }
721          }
722        }
723    BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->getTypeAtIndex(G1Oper);
724  }
725
726  // No shared constant operands, and we ran out of common operands.  At this
727  // point, the GEP instructions have run through all of their operands, and we
728  // haven't found evidence that there are any deltas between the GEP's.
729  // However, one GEP may have more operands than the other.  If this is the
730  // case, there may still be hope.  Check this now.
731  if (FirstConstantOper == MinOperands) {
732    // Make GEP1Ops be the longer one if there is a longer one.
733    if (NumGEP1Ops < NumGEP2Ops) {
734      std::swap(GEP1Ops, GEP2Ops);
735      std::swap(NumGEP1Ops, NumGEP2Ops);
736    }
737
738    // Is there anything to check?
739    if (NumGEP1Ops > MinOperands) {
740      for (unsigned i = FirstConstantOper; i != MaxOperands; ++i)
741        if (isa<ConstantInt>(GEP1Ops[i]) &&
742            !cast<ConstantInt>(GEP1Ops[i])->isZero()) {
743          // Yup, there's a constant in the tail.  Set all variables to
744          // constants in the GEP instruction to make it suitable for
745          // TargetData::getIndexedOffset.
746          for (i = 0; i != MaxOperands; ++i)
747            if (!isa<ConstantInt>(GEP1Ops[i]))
748              GEP1Ops[i] = Constant::getNullValue(GEP1Ops[i]->getType());
749          // Okay, now get the offset.  This is the relative offset for the full
750          // instruction.
751          const TargetData &TD = getTargetData();
752          int64_t Offset1 = TD.getIndexedOffset(GEPPointerTy, GEP1Ops,
753                                                NumGEP1Ops);
754
755          // Now check without any constants at the end.
756          int64_t Offset2 = TD.getIndexedOffset(GEPPointerTy, GEP1Ops,
757                                                MinOperands);
758
759          // Make sure we compare the absolute difference.
760          if (Offset1 > Offset2)
761            std::swap(Offset1, Offset2);
762
763          // If the tail provided a bit enough offset, return noalias!
764          if ((uint64_t)(Offset2-Offset1) >= SizeMax)
765            return NoAlias;
766          // Otherwise break - we don't look for another constant in the tail.
767          break;
768        }
769    }
770
771    // Couldn't find anything useful.
772    return MayAlias;
773  }
774
775  // If there are non-equal constants arguments, then we can figure
776  // out a minimum known delta between the two index expressions... at
777  // this point we know that the first constant index of GEP1 is less
778  // than the first constant index of GEP2.
779
780  // Advance BasePtr[12]Ty over this first differing constant operand.
781  BasePtr2Ty = cast<CompositeType>(BasePtr1Ty)->
782      getTypeAtIndex(GEP2Ops[FirstConstantOper]);
783  BasePtr1Ty = cast<CompositeType>(BasePtr1Ty)->
784      getTypeAtIndex(GEP1Ops[FirstConstantOper]);
785
786  // We are going to be using TargetData::getIndexedOffset to determine the
787  // offset that each of the GEP's is reaching.  To do this, we have to convert
788  // all variable references to constant references.  To do this, we convert the
789  // initial sequence of array subscripts into constant zeros to start with.
790  const Type *ZeroIdxTy = GEPPointerTy;
791  for (unsigned i = 0; i != FirstConstantOper; ++i) {
792    if (!isa<StructType>(ZeroIdxTy))
793      GEP1Ops[i] = GEP2Ops[i] = Constant::getNullValue(Type::Int32Ty);
794
795    if (const CompositeType *CT = dyn_cast<CompositeType>(ZeroIdxTy))
796      ZeroIdxTy = CT->getTypeAtIndex(GEP1Ops[i]);
797  }
798
799  // We know that GEP1Ops[FirstConstantOper] & GEP2Ops[FirstConstantOper] are ok
800
801  // Loop over the rest of the operands...
802  for (unsigned i = FirstConstantOper+1; i != MaxOperands; ++i) {
803    const Value *Op1 = i < NumGEP1Ops ? GEP1Ops[i] : 0;
804    const Value *Op2 = i < NumGEP2Ops ? GEP2Ops[i] : 0;
805    // If they are equal, use a zero index...
806    if (Op1 == Op2 && BasePtr1Ty == BasePtr2Ty) {
807      if (!isa<ConstantInt>(Op1))
808        GEP1Ops[i] = GEP2Ops[i] = Constant::getNullValue(Op1->getType());
809      // Otherwise, just keep the constants we have.
810    } else {
811      if (Op1) {
812        if (const ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
813          // If this is an array index, make sure the array element is in range.
814          if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty)) {
815            if (Op1C->getZExtValue() >= AT->getNumElements())
816              return MayAlias;  // Be conservative with out-of-range accesses
817          } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty)) {
818            if (Op1C->getZExtValue() >= VT->getNumElements())
819              return MayAlias;  // Be conservative with out-of-range accesses
820          }
821
822        } else {
823          // GEP1 is known to produce a value less than GEP2.  To be
824          // conservatively correct, we must assume the largest possible
825          // constant is used in this position.  This cannot be the initial
826          // index to the GEP instructions (because we know we have at least one
827          // element before this one with the different constant arguments), so
828          // we know that the current index must be into either a struct or
829          // array.  Because we know it's not constant, this cannot be a
830          // structure index.  Because of this, we can calculate the maximum
831          // value possible.
832          //
833          if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr1Ty))
834            GEP1Ops[i] = ConstantInt::get(Type::Int64Ty,AT->getNumElements()-1);
835          else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr1Ty))
836            GEP1Ops[i] = ConstantInt::get(Type::Int64Ty,VT->getNumElements()-1);
837        }
838      }
839
840      if (Op2) {
841        if (const ConstantInt *Op2C = dyn_cast<ConstantInt>(Op2)) {
842          // If this is an array index, make sure the array element is in range.
843          if (const ArrayType *AT = dyn_cast<ArrayType>(BasePtr2Ty)) {
844            if (Op2C->getZExtValue() >= AT->getNumElements())
845              return MayAlias;  // Be conservative with out-of-range accesses
846          } else if (const VectorType *VT = dyn_cast<VectorType>(BasePtr2Ty)) {
847            if (Op2C->getZExtValue() >= VT->getNumElements())
848              return MayAlias;  // Be conservative with out-of-range accesses
849          }
850        } else {  // Conservatively assume the minimum value for this index
851          GEP2Ops[i] = Constant::getNullValue(Op2->getType());
852        }
853      }
854    }
855
856    if (BasePtr1Ty && Op1) {
857      if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr1Ty))
858        BasePtr1Ty = CT->getTypeAtIndex(GEP1Ops[i]);
859      else
860        BasePtr1Ty = 0;
861    }
862
863    if (BasePtr2Ty && Op2) {
864      if (const CompositeType *CT = dyn_cast<CompositeType>(BasePtr2Ty))
865        BasePtr2Ty = CT->getTypeAtIndex(GEP2Ops[i]);
866      else
867        BasePtr2Ty = 0;
868    }
869  }
870
871  if (GEPPointerTy->getElementType()->isSized()) {
872    int64_t Offset1 =
873      getTargetData().getIndexedOffset(GEPPointerTy, GEP1Ops, NumGEP1Ops);
874    int64_t Offset2 =
875      getTargetData().getIndexedOffset(GEPPointerTy, GEP2Ops, NumGEP2Ops);
876    assert(Offset1 != Offset2 &&
877           "There is at least one different constant here!");
878
879    // Make sure we compare the absolute difference.
880    if (Offset1 > Offset2)
881      std::swap(Offset1, Offset2);
882
883    if ((uint64_t)(Offset2-Offset1) >= SizeMax) {
884      //cerr << "Determined that these two GEP's don't alias ["
885      //     << SizeMax << " bytes]: \n" << *GEP1 << *GEP2;
886      return NoAlias;
887    }
888  }
889  return MayAlias;
890}
891
892// Make sure that anything that uses AliasAnalysis pulls in this file...
893DEFINING_FILE_FOR(BasicAliasAnalysis)
894