1 //===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the primary stateless implementation of the 10 // Alias Analysis interface that implements identities (two different 11 // globals cannot alias, etc), but does no stateful analysis. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Analysis/BasicAliasAnalysis.h" 16 #include "llvm/ADT/APInt.h" 17 #include "llvm/ADT/ScopeExit.h" 18 #include "llvm/ADT/SmallPtrSet.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/Analysis/AliasAnalysis.h" 22 #include "llvm/Analysis/AssumptionCache.h" 23 #include "llvm/Analysis/CFG.h" 24 #include "llvm/Analysis/CaptureTracking.h" 25 #include "llvm/Analysis/InstructionSimplify.h" 26 #include "llvm/Analysis/MemoryBuiltins.h" 27 #include "llvm/Analysis/MemoryLocation.h" 28 #include "llvm/Analysis/PhiValues.h" 29 #include "llvm/Analysis/TargetLibraryInfo.h" 30 #include "llvm/Analysis/ValueTracking.h" 31 #include "llvm/IR/Argument.h" 32 #include "llvm/IR/Attributes.h" 33 #include "llvm/IR/Constant.h" 34 #include "llvm/IR/ConstantRange.h" 35 #include "llvm/IR/Constants.h" 36 #include "llvm/IR/DataLayout.h" 37 #include "llvm/IR/DerivedTypes.h" 38 #include "llvm/IR/Dominators.h" 39 #include "llvm/IR/Function.h" 40 #include "llvm/IR/GetElementPtrTypeIterator.h" 41 #include "llvm/IR/GlobalAlias.h" 42 #include "llvm/IR/GlobalVariable.h" 43 #include "llvm/IR/InstrTypes.h" 44 #include "llvm/IR/Instruction.h" 45 #include "llvm/IR/Instructions.h" 46 #include "llvm/IR/IntrinsicInst.h" 47 #include "llvm/IR/Intrinsics.h" 48 #include "llvm/IR/Metadata.h" 49 #include "llvm/IR/Operator.h" 50 #include "llvm/IR/Type.h" 51 #include "llvm/IR/User.h" 52 #include "llvm/IR/Value.h" 53 #include "llvm/InitializePasses.h" 54 #include "llvm/Pass.h" 55 #include "llvm/Support/Casting.h" 56 #include "llvm/Support/CommandLine.h" 57 #include "llvm/Support/Compiler.h" 58 #include "llvm/Support/KnownBits.h" 59 #include <cassert> 60 #include <cstdint> 61 #include <cstdlib> 62 #include <utility> 63 64 #define DEBUG_TYPE "basicaa" 65 66 using namespace llvm; 67 68 /// Enable analysis of recursive PHI nodes. 69 static cl::opt<bool> EnableRecPhiAnalysis("basic-aa-recphi", cl::Hidden, 70 cl::init(true)); 71 72 /// By default, even on 32-bit architectures we use 64-bit integers for 73 /// calculations. This will allow us to more-aggressively decompose indexing 74 /// expressions calculated using i64 values (e.g., long long in C) which is 75 /// common enough to worry about. 76 static cl::opt<bool> ForceAtLeast64Bits("basic-aa-force-at-least-64b", 77 cl::Hidden, cl::init(true)); 78 static cl::opt<bool> DoubleCalcBits("basic-aa-double-calc-bits", 79 cl::Hidden, cl::init(false)); 80 81 /// SearchLimitReached / SearchTimes shows how often the limit of 82 /// to decompose GEPs is reached. It will affect the precision 83 /// of basic alias analysis. 84 STATISTIC(SearchLimitReached, "Number of times the limit to " 85 "decompose GEPs is reached"); 86 STATISTIC(SearchTimes, "Number of times a GEP is decomposed"); 87 88 /// Cutoff after which to stop analysing a set of phi nodes potentially involved 89 /// in a cycle. Because we are analysing 'through' phi nodes, we need to be 90 /// careful with value equivalence. We use reachability to make sure a value 91 /// cannot be involved in a cycle. 92 const unsigned MaxNumPhiBBsValueReachabilityCheck = 20; 93 94 // The max limit of the search depth in DecomposeGEPExpression() and 95 // getUnderlyingObject(), both functions need to use the same search 96 // depth otherwise the algorithm in aliasGEP will assert. 97 static const unsigned MaxLookupSearchDepth = 6; 98 99 bool BasicAAResult::invalidate(Function &Fn, const PreservedAnalyses &PA, 100 FunctionAnalysisManager::Invalidator &Inv) { 101 // We don't care if this analysis itself is preserved, it has no state. But 102 // we need to check that the analyses it depends on have been. Note that we 103 // may be created without handles to some analyses and in that case don't 104 // depend on them. 105 if (Inv.invalidate<AssumptionAnalysis>(Fn, PA) || 106 (DT && Inv.invalidate<DominatorTreeAnalysis>(Fn, PA)) || 107 (PV && Inv.invalidate<PhiValuesAnalysis>(Fn, PA))) 108 return true; 109 110 // Otherwise this analysis result remains valid. 111 return false; 112 } 113 114 //===----------------------------------------------------------------------===// 115 // Useful predicates 116 //===----------------------------------------------------------------------===// 117 118 /// Returns true if the pointer is one which would have been considered an 119 /// escape by isNonEscapingLocalObject. 120 static bool isEscapeSource(const Value *V) { 121 if (isa<CallBase>(V)) 122 return true; 123 124 // The load case works because isNonEscapingLocalObject considers all 125 // stores to be escapes (it passes true for the StoreCaptures argument 126 // to PointerMayBeCaptured). 127 if (isa<LoadInst>(V)) 128 return true; 129 130 // The inttoptr case works because isNonEscapingLocalObject considers all 131 // means of converting or equating a pointer to an int (ptrtoint, ptr store 132 // which could be followed by an integer load, ptr<->int compare) as 133 // escaping, and objects located at well-known addresses via platform-specific 134 // means cannot be considered non-escaping local objects. 135 if (isa<IntToPtrInst>(V)) 136 return true; 137 138 return false; 139 } 140 141 /// Returns the size of the object specified by V or UnknownSize if unknown. 142 static uint64_t getObjectSize(const Value *V, const DataLayout &DL, 143 const TargetLibraryInfo &TLI, 144 bool NullIsValidLoc, 145 bool RoundToAlign = false) { 146 uint64_t Size; 147 ObjectSizeOpts Opts; 148 Opts.RoundToAlign = RoundToAlign; 149 Opts.NullIsUnknownSize = NullIsValidLoc; 150 if (getObjectSize(V, Size, DL, &TLI, Opts)) 151 return Size; 152 return MemoryLocation::UnknownSize; 153 } 154 155 /// Returns true if we can prove that the object specified by V is smaller than 156 /// Size. 157 static bool isObjectSmallerThan(const Value *V, uint64_t Size, 158 const DataLayout &DL, 159 const TargetLibraryInfo &TLI, 160 bool NullIsValidLoc) { 161 // Note that the meanings of the "object" are slightly different in the 162 // following contexts: 163 // c1: llvm::getObjectSize() 164 // c2: llvm.objectsize() intrinsic 165 // c3: isObjectSmallerThan() 166 // c1 and c2 share the same meaning; however, the meaning of "object" in c3 167 // refers to the "entire object". 168 // 169 // Consider this example: 170 // char *p = (char*)malloc(100) 171 // char *q = p+80; 172 // 173 // In the context of c1 and c2, the "object" pointed by q refers to the 174 // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20. 175 // 176 // However, in the context of c3, the "object" refers to the chunk of memory 177 // being allocated. So, the "object" has 100 bytes, and q points to the middle 178 // the "object". In case q is passed to isObjectSmallerThan() as the 1st 179 // parameter, before the llvm::getObjectSize() is called to get the size of 180 // entire object, we should: 181 // - either rewind the pointer q to the base-address of the object in 182 // question (in this case rewind to p), or 183 // - just give up. It is up to caller to make sure the pointer is pointing 184 // to the base address the object. 185 // 186 // We go for 2nd option for simplicity. 187 if (!isIdentifiedObject(V)) 188 return false; 189 190 // This function needs to use the aligned object size because we allow 191 // reads a bit past the end given sufficient alignment. 192 uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc, 193 /*RoundToAlign*/ true); 194 195 return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size; 196 } 197 198 /// Return the minimal extent from \p V to the end of the underlying object, 199 /// assuming the result is used in an aliasing query. E.g., we do use the query 200 /// location size and the fact that null pointers cannot alias here. 201 static uint64_t getMinimalExtentFrom(const Value &V, 202 const LocationSize &LocSize, 203 const DataLayout &DL, 204 bool NullIsValidLoc) { 205 // If we have dereferenceability information we know a lower bound for the 206 // extent as accesses for a lower offset would be valid. We need to exclude 207 // the "or null" part if null is a valid pointer. We can ignore frees, as an 208 // access after free would be undefined behavior. 209 bool CanBeNull, CanBeFreed; 210 uint64_t DerefBytes = 211 V.getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed); 212 DerefBytes = (CanBeNull && NullIsValidLoc) ? 0 : DerefBytes; 213 // If queried with a precise location size, we assume that location size to be 214 // accessed, thus valid. 215 if (LocSize.isPrecise()) 216 DerefBytes = std::max(DerefBytes, LocSize.getValue()); 217 return DerefBytes; 218 } 219 220 /// Returns true if we can prove that the object specified by V has size Size. 221 static bool isObjectSize(const Value *V, uint64_t Size, const DataLayout &DL, 222 const TargetLibraryInfo &TLI, bool NullIsValidLoc) { 223 uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc); 224 return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size; 225 } 226 227 //===----------------------------------------------------------------------===// 228 // CaptureInfo implementations 229 //===----------------------------------------------------------------------===// 230 231 CaptureInfo::~CaptureInfo() = default; 232 233 bool SimpleCaptureInfo::isNotCapturedBeforeOrAt(const Value *Object, 234 const Instruction *I) { 235 return isNonEscapingLocalObject(Object, &IsCapturedCache); 236 } 237 238 bool EarliestEscapeInfo::isNotCapturedBeforeOrAt(const Value *Object, 239 const Instruction *I) { 240 if (!isIdentifiedFunctionLocal(Object)) 241 return false; 242 243 auto Iter = EarliestEscapes.insert({Object, nullptr}); 244 if (Iter.second) { 245 Instruction *EarliestCapture = FindEarliestCapture( 246 Object, *const_cast<Function *>(I->getFunction()), 247 /*ReturnCaptures=*/false, /*StoreCaptures=*/true, DT); 248 if (EarliestCapture) { 249 auto Ins = Inst2Obj.insert({EarliestCapture, {}}); 250 Ins.first->second.push_back(Object); 251 } 252 Iter.first->second = EarliestCapture; 253 } 254 255 // No capturing instruction. 256 if (!Iter.first->second) 257 return true; 258 259 return I != Iter.first->second && 260 !isPotentiallyReachable(Iter.first->second, I, nullptr, &DT, &LI); 261 } 262 263 void EarliestEscapeInfo::removeInstruction(Instruction *I) { 264 auto Iter = Inst2Obj.find(I); 265 if (Iter != Inst2Obj.end()) { 266 for (const Value *Obj : Iter->second) 267 EarliestEscapes.erase(Obj); 268 Inst2Obj.erase(I); 269 } 270 } 271 272 //===----------------------------------------------------------------------===// 273 // GetElementPtr Instruction Decomposition and Analysis 274 //===----------------------------------------------------------------------===// 275 276 namespace { 277 /// Represents zext(sext(V)). 278 struct ExtendedValue { 279 const Value *V; 280 unsigned ZExtBits; 281 unsigned SExtBits; 282 283 explicit ExtendedValue(const Value *V, unsigned ZExtBits = 0, 284 unsigned SExtBits = 0) 285 : V(V), ZExtBits(ZExtBits), SExtBits(SExtBits) {} 286 287 unsigned getBitWidth() const { 288 return V->getType()->getPrimitiveSizeInBits() + ZExtBits + SExtBits; 289 } 290 291 ExtendedValue withValue(const Value *NewV) const { 292 return ExtendedValue(NewV, ZExtBits, SExtBits); 293 } 294 295 ExtendedValue withZExtOfValue(const Value *NewV) const { 296 unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() - 297 NewV->getType()->getPrimitiveSizeInBits(); 298 // zext(sext(zext(NewV))) == zext(zext(zext(NewV))) 299 return ExtendedValue(NewV, ZExtBits + SExtBits + ExtendBy, 0); 300 } 301 302 ExtendedValue withSExtOfValue(const Value *NewV) const { 303 unsigned ExtendBy = V->getType()->getPrimitiveSizeInBits() - 304 NewV->getType()->getPrimitiveSizeInBits(); 305 // zext(sext(sext(NewV))) 306 return ExtendedValue(NewV, ZExtBits, SExtBits + ExtendBy); 307 } 308 309 APInt evaluateWith(APInt N) const { 310 assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() && 311 "Incompatible bit width"); 312 if (SExtBits) N = N.sext(N.getBitWidth() + SExtBits); 313 if (ZExtBits) N = N.zext(N.getBitWidth() + ZExtBits); 314 return N; 315 } 316 317 KnownBits evaluateWith(KnownBits N) const { 318 assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() && 319 "Incompatible bit width"); 320 if (SExtBits) N = N.sext(N.getBitWidth() + SExtBits); 321 if (ZExtBits) N = N.zext(N.getBitWidth() + ZExtBits); 322 return N; 323 } 324 325 ConstantRange evaluateWith(ConstantRange N) const { 326 assert(N.getBitWidth() == V->getType()->getPrimitiveSizeInBits() && 327 "Incompatible bit width"); 328 if (SExtBits) N = N.signExtend(N.getBitWidth() + SExtBits); 329 if (ZExtBits) N = N.zeroExtend(N.getBitWidth() + ZExtBits); 330 return N; 331 } 332 333 bool canDistributeOver(bool NUW, bool NSW) const { 334 // zext(x op<nuw> y) == zext(x) op<nuw> zext(y) 335 // sext(x op<nsw> y) == sext(x) op<nsw> sext(y) 336 return (!ZExtBits || NUW) && (!SExtBits || NSW); 337 } 338 339 bool hasSameExtensionsAs(const ExtendedValue &Other) const { 340 return ZExtBits == Other.ZExtBits && SExtBits == Other.SExtBits; 341 } 342 }; 343 344 /// Represents zext(sext(V)) * Scale + Offset. 345 struct LinearExpression { 346 ExtendedValue Val; 347 APInt Scale; 348 APInt Offset; 349 350 /// True if all operations in this expression are NSW. 351 bool IsNSW; 352 353 LinearExpression(const ExtendedValue &Val, const APInt &Scale, 354 const APInt &Offset, bool IsNSW) 355 : Val(Val), Scale(Scale), Offset(Offset), IsNSW(IsNSW) {} 356 357 LinearExpression(const ExtendedValue &Val) : Val(Val), IsNSW(true) { 358 unsigned BitWidth = Val.getBitWidth(); 359 Scale = APInt(BitWidth, 1); 360 Offset = APInt(BitWidth, 0); 361 } 362 }; 363 } 364 365 /// Analyzes the specified value as a linear expression: "A*V + B", where A and 366 /// B are constant integers. 367 static LinearExpression GetLinearExpression( 368 const ExtendedValue &Val, const DataLayout &DL, unsigned Depth, 369 AssumptionCache *AC, DominatorTree *DT) { 370 // Limit our recursion depth. 371 if (Depth == 6) 372 return Val; 373 374 if (const ConstantInt *Const = dyn_cast<ConstantInt>(Val.V)) 375 return LinearExpression(Val, APInt(Val.getBitWidth(), 0), 376 Val.evaluateWith(Const->getValue()), true); 377 378 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(Val.V)) { 379 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) { 380 APInt RHS = Val.evaluateWith(RHSC->getValue()); 381 // The only non-OBO case we deal with is or, and only limited to the 382 // case where it is both nuw and nsw. 383 bool NUW = true, NSW = true; 384 if (isa<OverflowingBinaryOperator>(BOp)) { 385 NUW &= BOp->hasNoUnsignedWrap(); 386 NSW &= BOp->hasNoSignedWrap(); 387 } 388 if (!Val.canDistributeOver(NUW, NSW)) 389 return Val; 390 391 LinearExpression E(Val); 392 switch (BOp->getOpcode()) { 393 default: 394 // We don't understand this instruction, so we can't decompose it any 395 // further. 396 return Val; 397 case Instruction::Or: 398 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't 399 // analyze it. 400 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC, 401 BOp, DT)) 402 return Val; 403 404 LLVM_FALLTHROUGH; 405 case Instruction::Add: { 406 E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL, 407 Depth + 1, AC, DT); 408 E.Offset += RHS; 409 E.IsNSW &= NSW; 410 break; 411 } 412 case Instruction::Sub: { 413 E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL, 414 Depth + 1, AC, DT); 415 E.Offset -= RHS; 416 E.IsNSW &= NSW; 417 break; 418 } 419 case Instruction::Mul: { 420 E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL, 421 Depth + 1, AC, DT); 422 E.Offset *= RHS; 423 E.Scale *= RHS; 424 E.IsNSW &= NSW; 425 break; 426 } 427 case Instruction::Shl: 428 // We're trying to linearize an expression of the kind: 429 // shl i8 -128, 36 430 // where the shift count exceeds the bitwidth of the type. 431 // We can't decompose this further (the expression would return 432 // a poison value). 433 if (RHS.getLimitedValue() > Val.getBitWidth()) 434 return Val; 435 436 E = GetLinearExpression(Val.withValue(BOp->getOperand(0)), DL, 437 Depth + 1, AC, DT); 438 E.Offset <<= RHS.getLimitedValue(); 439 E.Scale <<= RHS.getLimitedValue(); 440 E.IsNSW &= NSW; 441 break; 442 } 443 return E; 444 } 445 } 446 447 if (isa<ZExtInst>(Val.V)) 448 return GetLinearExpression( 449 Val.withZExtOfValue(cast<CastInst>(Val.V)->getOperand(0)), 450 DL, Depth + 1, AC, DT); 451 452 if (isa<SExtInst>(Val.V)) 453 return GetLinearExpression( 454 Val.withSExtOfValue(cast<CastInst>(Val.V)->getOperand(0)), 455 DL, Depth + 1, AC, DT); 456 457 return Val; 458 } 459 460 /// To ensure a pointer offset fits in an integer of size PointerSize 461 /// (in bits) when that size is smaller than the maximum pointer size. This is 462 /// an issue, for example, in particular for 32b pointers with negative indices 463 /// that rely on two's complement wrap-arounds for precise alias information 464 /// where the maximum pointer size is 64b. 465 static APInt adjustToPointerSize(const APInt &Offset, unsigned PointerSize) { 466 assert(PointerSize <= Offset.getBitWidth() && "Invalid PointerSize!"); 467 unsigned ShiftBits = Offset.getBitWidth() - PointerSize; 468 return (Offset << ShiftBits).ashr(ShiftBits); 469 } 470 471 static unsigned getMaxPointerSize(const DataLayout &DL) { 472 unsigned MaxPointerSize = DL.getMaxPointerSizeInBits(); 473 if (MaxPointerSize < 64 && ForceAtLeast64Bits) MaxPointerSize = 64; 474 if (DoubleCalcBits) MaxPointerSize *= 2; 475 476 return MaxPointerSize; 477 } 478 479 namespace { 480 // A linear transformation of a Value; this class represents 481 // ZExt(SExt(V, SExtBits), ZExtBits) * Scale. 482 struct VariableGEPIndex { 483 ExtendedValue Val; 484 APInt Scale; 485 486 // Context instruction to use when querying information about this index. 487 const Instruction *CxtI; 488 489 /// True if all operations in this expression are NSW. 490 bool IsNSW; 491 492 void dump() const { 493 print(dbgs()); 494 dbgs() << "\n"; 495 } 496 void print(raw_ostream &OS) const { 497 OS << "(V=" << Val.V->getName() 498 << ", zextbits=" << Val.ZExtBits 499 << ", sextbits=" << Val.SExtBits 500 << ", scale=" << Scale << ")"; 501 } 502 }; 503 } 504 505 // Represents the internal structure of a GEP, decomposed into a base pointer, 506 // constant offsets, and variable scaled indices. 507 struct BasicAAResult::DecomposedGEP { 508 // Base pointer of the GEP 509 const Value *Base; 510 // Total constant offset from base. 511 APInt Offset; 512 // Scaled variable (non-constant) indices. 513 SmallVector<VariableGEPIndex, 4> VarIndices; 514 // Is GEP index scale compile-time constant. 515 bool HasCompileTimeConstantScale; 516 // Are all operations inbounds GEPs or non-indexing operations? 517 // (None iff expression doesn't involve any geps) 518 Optional<bool> InBounds; 519 520 void dump() const { 521 print(dbgs()); 522 dbgs() << "\n"; 523 } 524 void print(raw_ostream &OS) const { 525 OS << "(DecomposedGEP Base=" << Base->getName() 526 << ", Offset=" << Offset 527 << ", VarIndices=["; 528 for (size_t i = 0; i < VarIndices.size(); i++) { 529 if (i != 0) 530 OS << ", "; 531 VarIndices[i].print(OS); 532 } 533 OS << "], HasCompileTimeConstantScale=" << HasCompileTimeConstantScale 534 << ")"; 535 } 536 }; 537 538 539 /// If V is a symbolic pointer expression, decompose it into a base pointer 540 /// with a constant offset and a number of scaled symbolic offsets. 541 /// 542 /// The scaled symbolic offsets (represented by pairs of a Value* and a scale 543 /// in the VarIndices vector) are Value*'s that are known to be scaled by the 544 /// specified amount, but which may have other unrepresented high bits. As 545 /// such, the gep cannot necessarily be reconstructed from its decomposed form. 546 /// 547 /// This function is capable of analyzing everything that getUnderlyingObject 548 /// can look through. To be able to do that getUnderlyingObject and 549 /// DecomposeGEPExpression must use the same search depth 550 /// (MaxLookupSearchDepth). 551 BasicAAResult::DecomposedGEP 552 BasicAAResult::DecomposeGEPExpression(const Value *V, const DataLayout &DL, 553 AssumptionCache *AC, DominatorTree *DT) { 554 // Limit recursion depth to limit compile time in crazy cases. 555 unsigned MaxLookup = MaxLookupSearchDepth; 556 SearchTimes++; 557 const Instruction *CxtI = dyn_cast<Instruction>(V); 558 559 unsigned MaxPointerSize = getMaxPointerSize(DL); 560 DecomposedGEP Decomposed; 561 Decomposed.Offset = APInt(MaxPointerSize, 0); 562 Decomposed.HasCompileTimeConstantScale = true; 563 do { 564 // See if this is a bitcast or GEP. 565 const Operator *Op = dyn_cast<Operator>(V); 566 if (!Op) { 567 // The only non-operator case we can handle are GlobalAliases. 568 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 569 if (!GA->isInterposable()) { 570 V = GA->getAliasee(); 571 continue; 572 } 573 } 574 Decomposed.Base = V; 575 return Decomposed; 576 } 577 578 if (Op->getOpcode() == Instruction::BitCast || 579 Op->getOpcode() == Instruction::AddrSpaceCast) { 580 V = Op->getOperand(0); 581 continue; 582 } 583 584 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op); 585 if (!GEPOp) { 586 if (const auto *PHI = dyn_cast<PHINode>(V)) { 587 // Look through single-arg phi nodes created by LCSSA. 588 if (PHI->getNumIncomingValues() == 1) { 589 V = PHI->getIncomingValue(0); 590 continue; 591 } 592 } else if (const auto *Call = dyn_cast<CallBase>(V)) { 593 // CaptureTracking can know about special capturing properties of some 594 // intrinsics like launder.invariant.group, that can't be expressed with 595 // the attributes, but have properties like returning aliasing pointer. 596 // Because some analysis may assume that nocaptured pointer is not 597 // returned from some special intrinsic (because function would have to 598 // be marked with returns attribute), it is crucial to use this function 599 // because it should be in sync with CaptureTracking. Not using it may 600 // cause weird miscompilations where 2 aliasing pointers are assumed to 601 // noalias. 602 if (auto *RP = getArgumentAliasingToReturnedPointer(Call, false)) { 603 V = RP; 604 continue; 605 } 606 } 607 608 Decomposed.Base = V; 609 return Decomposed; 610 } 611 612 // Track whether we've seen at least one in bounds gep, and if so, whether 613 // all geps parsed were in bounds. 614 if (Decomposed.InBounds == None) 615 Decomposed.InBounds = GEPOp->isInBounds(); 616 else if (!GEPOp->isInBounds()) 617 Decomposed.InBounds = false; 618 619 assert(GEPOp->getSourceElementType()->isSized() && "GEP must be sized"); 620 621 // Don't attempt to analyze GEPs if index scale is not a compile-time 622 // constant. 623 if (isa<ScalableVectorType>(GEPOp->getSourceElementType())) { 624 Decomposed.Base = V; 625 Decomposed.HasCompileTimeConstantScale = false; 626 return Decomposed; 627 } 628 629 unsigned AS = GEPOp->getPointerAddressSpace(); 630 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices. 631 gep_type_iterator GTI = gep_type_begin(GEPOp); 632 unsigned PointerSize = DL.getPointerSizeInBits(AS); 633 // Assume all GEP operands are constants until proven otherwise. 634 bool GepHasConstantOffset = true; 635 for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end(); 636 I != E; ++I, ++GTI) { 637 const Value *Index = *I; 638 // Compute the (potentially symbolic) offset in bytes for this index. 639 if (StructType *STy = GTI.getStructTypeOrNull()) { 640 // For a struct, add the member offset. 641 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue(); 642 if (FieldNo == 0) 643 continue; 644 645 Decomposed.Offset += DL.getStructLayout(STy)->getElementOffset(FieldNo); 646 continue; 647 } 648 649 // For an array/pointer, add the element offset, explicitly scaled. 650 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) { 651 if (CIdx->isZero()) 652 continue; 653 Decomposed.Offset += 654 DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize() * 655 CIdx->getValue().sextOrTrunc(MaxPointerSize); 656 continue; 657 } 658 659 GepHasConstantOffset = false; 660 661 APInt Scale(MaxPointerSize, 662 DL.getTypeAllocSize(GTI.getIndexedType()).getFixedSize()); 663 // If the integer type is smaller than the pointer size, it is implicitly 664 // sign extended to pointer size. 665 unsigned Width = Index->getType()->getIntegerBitWidth(); 666 unsigned SExtBits = PointerSize > Width ? PointerSize - Width : 0; 667 LinearExpression LE = GetLinearExpression( 668 ExtendedValue(Index, 0, SExtBits), DL, 0, AC, DT); 669 670 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale. 671 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale. 672 673 // It can be the case that, even through C1*V+C2 does not overflow for 674 // relevant values of V, (C2*Scale) can overflow. In that case, we cannot 675 // decompose the expression in this way. 676 // 677 // FIXME: C1*Scale and the other operations in the decomposed 678 // (C1*Scale)*V+C2*Scale can also overflow. We should check for this 679 // possibility. 680 bool Overflow; 681 APInt ScaledOffset = LE.Offset.sextOrTrunc(MaxPointerSize) 682 .smul_ov(Scale, Overflow); 683 if (Overflow) { 684 LE = LinearExpression(ExtendedValue(Index, 0, SExtBits)); 685 } else { 686 Decomposed.Offset += ScaledOffset; 687 Scale *= LE.Scale.sextOrTrunc(MaxPointerSize); 688 } 689 690 // If we already had an occurrence of this index variable, merge this 691 // scale into it. For example, we want to handle: 692 // A[x][x] -> x*16 + x*4 -> x*20 693 // This also ensures that 'x' only appears in the index list once. 694 for (unsigned i = 0, e = Decomposed.VarIndices.size(); i != e; ++i) { 695 if (Decomposed.VarIndices[i].Val.V == LE.Val.V && 696 Decomposed.VarIndices[i].Val.hasSameExtensionsAs(LE.Val)) { 697 Scale += Decomposed.VarIndices[i].Scale; 698 Decomposed.VarIndices.erase(Decomposed.VarIndices.begin() + i); 699 break; 700 } 701 } 702 703 // Make sure that we have a scale that makes sense for this target's 704 // pointer size. 705 Scale = adjustToPointerSize(Scale, PointerSize); 706 707 if (!!Scale) { 708 VariableGEPIndex Entry = {LE.Val, Scale, CxtI, LE.IsNSW}; 709 Decomposed.VarIndices.push_back(Entry); 710 } 711 } 712 713 // Take care of wrap-arounds 714 if (GepHasConstantOffset) 715 Decomposed.Offset = adjustToPointerSize(Decomposed.Offset, PointerSize); 716 717 // Analyze the base pointer next. 718 V = GEPOp->getOperand(0); 719 } while (--MaxLookup); 720 721 // If the chain of expressions is too deep, just return early. 722 Decomposed.Base = V; 723 SearchLimitReached++; 724 return Decomposed; 725 } 726 727 /// Returns whether the given pointer value points to memory that is local to 728 /// the function, with global constants being considered local to all 729 /// functions. 730 bool BasicAAResult::pointsToConstantMemory(const MemoryLocation &Loc, 731 AAQueryInfo &AAQI, bool OrLocal) { 732 assert(Visited.empty() && "Visited must be cleared after use!"); 733 734 unsigned MaxLookup = 8; 735 SmallVector<const Value *, 16> Worklist; 736 Worklist.push_back(Loc.Ptr); 737 do { 738 const Value *V = getUnderlyingObject(Worklist.pop_back_val()); 739 if (!Visited.insert(V).second) { 740 Visited.clear(); 741 return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal); 742 } 743 744 // An alloca instruction defines local memory. 745 if (OrLocal && isa<AllocaInst>(V)) 746 continue; 747 748 // A global constant counts as local memory for our purposes. 749 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) { 750 // Note: this doesn't require GV to be "ODR" because it isn't legal for a 751 // global to be marked constant in some modules and non-constant in 752 // others. GV may even be a declaration, not a definition. 753 if (!GV->isConstant()) { 754 Visited.clear(); 755 return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal); 756 } 757 continue; 758 } 759 760 // If both select values point to local memory, then so does the select. 761 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) { 762 Worklist.push_back(SI->getTrueValue()); 763 Worklist.push_back(SI->getFalseValue()); 764 continue; 765 } 766 767 // If all values incoming to a phi node point to local memory, then so does 768 // the phi. 769 if (const PHINode *PN = dyn_cast<PHINode>(V)) { 770 // Don't bother inspecting phi nodes with many operands. 771 if (PN->getNumIncomingValues() > MaxLookup) { 772 Visited.clear(); 773 return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal); 774 } 775 append_range(Worklist, PN->incoming_values()); 776 continue; 777 } 778 779 // Otherwise be conservative. 780 Visited.clear(); 781 return AAResultBase::pointsToConstantMemory(Loc, AAQI, OrLocal); 782 } while (!Worklist.empty() && --MaxLookup); 783 784 Visited.clear(); 785 return Worklist.empty(); 786 } 787 788 static bool isIntrinsicCall(const CallBase *Call, Intrinsic::ID IID) { 789 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Call); 790 return II && II->getIntrinsicID() == IID; 791 } 792 793 /// Returns the behavior when calling the given call site. 794 FunctionModRefBehavior BasicAAResult::getModRefBehavior(const CallBase *Call) { 795 if (Call->doesNotAccessMemory()) 796 // Can't do better than this. 797 return FMRB_DoesNotAccessMemory; 798 799 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior; 800 801 // If the callsite knows it only reads memory, don't return worse 802 // than that. 803 if (Call->onlyReadsMemory()) 804 Min = FMRB_OnlyReadsMemory; 805 else if (Call->doesNotReadMemory()) 806 Min = FMRB_OnlyWritesMemory; 807 808 if (Call->onlyAccessesArgMemory()) 809 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees); 810 else if (Call->onlyAccessesInaccessibleMemory()) 811 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem); 812 else if (Call->onlyAccessesInaccessibleMemOrArgMem()) 813 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem); 814 815 // If the call has operand bundles then aliasing attributes from the function 816 // it calls do not directly apply to the call. This can be made more precise 817 // in the future. 818 if (!Call->hasOperandBundles()) 819 if (const Function *F = Call->getCalledFunction()) 820 Min = 821 FunctionModRefBehavior(Min & getBestAAResults().getModRefBehavior(F)); 822 823 return Min; 824 } 825 826 /// Returns the behavior when calling the given function. For use when the call 827 /// site is not known. 828 FunctionModRefBehavior BasicAAResult::getModRefBehavior(const Function *F) { 829 // If the function declares it doesn't access memory, we can't do better. 830 if (F->doesNotAccessMemory()) 831 return FMRB_DoesNotAccessMemory; 832 833 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior; 834 835 // If the function declares it only reads memory, go with that. 836 if (F->onlyReadsMemory()) 837 Min = FMRB_OnlyReadsMemory; 838 else if (F->doesNotReadMemory()) 839 Min = FMRB_OnlyWritesMemory; 840 841 if (F->onlyAccessesArgMemory()) 842 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees); 843 else if (F->onlyAccessesInaccessibleMemory()) 844 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem); 845 else if (F->onlyAccessesInaccessibleMemOrArgMem()) 846 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem); 847 848 return Min; 849 } 850 851 /// Returns true if this is a writeonly (i.e Mod only) parameter. 852 static bool isWriteOnlyParam(const CallBase *Call, unsigned ArgIdx, 853 const TargetLibraryInfo &TLI) { 854 if (Call->paramHasAttr(ArgIdx, Attribute::WriteOnly)) 855 return true; 856 857 // We can bound the aliasing properties of memset_pattern16 just as we can 858 // for memcpy/memset. This is particularly important because the 859 // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16 860 // whenever possible. 861 // FIXME Consider handling this in InferFunctionAttr.cpp together with other 862 // attributes. 863 LibFunc F; 864 if (Call->getCalledFunction() && 865 TLI.getLibFunc(*Call->getCalledFunction(), F) && 866 F == LibFunc_memset_pattern16 && TLI.has(F)) 867 if (ArgIdx == 0) 868 return true; 869 870 // TODO: memset_pattern4, memset_pattern8 871 // TODO: _chk variants 872 // TODO: strcmp, strcpy 873 874 return false; 875 } 876 877 ModRefInfo BasicAAResult::getArgModRefInfo(const CallBase *Call, 878 unsigned ArgIdx) { 879 // Checking for known builtin intrinsics and target library functions. 880 if (isWriteOnlyParam(Call, ArgIdx, TLI)) 881 return ModRefInfo::Mod; 882 883 if (Call->paramHasAttr(ArgIdx, Attribute::ReadOnly)) 884 return ModRefInfo::Ref; 885 886 if (Call->paramHasAttr(ArgIdx, Attribute::ReadNone)) 887 return ModRefInfo::NoModRef; 888 889 return AAResultBase::getArgModRefInfo(Call, ArgIdx); 890 } 891 892 #ifndef NDEBUG 893 static const Function *getParent(const Value *V) { 894 if (const Instruction *inst = dyn_cast<Instruction>(V)) { 895 if (!inst->getParent()) 896 return nullptr; 897 return inst->getParent()->getParent(); 898 } 899 900 if (const Argument *arg = dyn_cast<Argument>(V)) 901 return arg->getParent(); 902 903 return nullptr; 904 } 905 906 static bool notDifferentParent(const Value *O1, const Value *O2) { 907 908 const Function *F1 = getParent(O1); 909 const Function *F2 = getParent(O2); 910 911 return !F1 || !F2 || F1 == F2; 912 } 913 #endif 914 915 AliasResult BasicAAResult::alias(const MemoryLocation &LocA, 916 const MemoryLocation &LocB, 917 AAQueryInfo &AAQI) { 918 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) && 919 "BasicAliasAnalysis doesn't support interprocedural queries."); 920 return aliasCheck(LocA.Ptr, LocA.Size, LocB.Ptr, LocB.Size, AAQI); 921 } 922 923 /// Checks to see if the specified callsite can clobber the specified memory 924 /// object. 925 /// 926 /// Since we only look at local properties of this function, we really can't 927 /// say much about this query. We do, however, use simple "address taken" 928 /// analysis on local objects. 929 ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call, 930 const MemoryLocation &Loc, 931 AAQueryInfo &AAQI) { 932 assert(notDifferentParent(Call, Loc.Ptr) && 933 "AliasAnalysis query involving multiple functions!"); 934 935 const Value *Object = getUnderlyingObject(Loc.Ptr); 936 937 // Calls marked 'tail' cannot read or write allocas from the current frame 938 // because the current frame might be destroyed by the time they run. However, 939 // a tail call may use an alloca with byval. Calling with byval copies the 940 // contents of the alloca into argument registers or stack slots, so there is 941 // no lifetime issue. 942 if (isa<AllocaInst>(Object)) 943 if (const CallInst *CI = dyn_cast<CallInst>(Call)) 944 if (CI->isTailCall() && 945 !CI->getAttributes().hasAttrSomewhere(Attribute::ByVal)) 946 return ModRefInfo::NoModRef; 947 948 // Stack restore is able to modify unescaped dynamic allocas. Assume it may 949 // modify them even though the alloca is not escaped. 950 if (auto *AI = dyn_cast<AllocaInst>(Object)) 951 if (!AI->isStaticAlloca() && isIntrinsicCall(Call, Intrinsic::stackrestore)) 952 return ModRefInfo::Mod; 953 954 // If the pointer is to a locally allocated object that does not escape, 955 // then the call can not mod/ref the pointer unless the call takes the pointer 956 // as an argument, and itself doesn't capture it. 957 if (!isa<Constant>(Object) && Call != Object && 958 AAQI.CI->isNotCapturedBeforeOrAt(Object, Call)) { 959 960 // Optimistically assume that call doesn't touch Object and check this 961 // assumption in the following loop. 962 ModRefInfo Result = ModRefInfo::NoModRef; 963 bool IsMustAlias = true; 964 965 unsigned OperandNo = 0; 966 for (auto CI = Call->data_operands_begin(), CE = Call->data_operands_end(); 967 CI != CE; ++CI, ++OperandNo) { 968 // Only look at the no-capture or byval pointer arguments. If this 969 // pointer were passed to arguments that were neither of these, then it 970 // couldn't be no-capture. 971 if (!(*CI)->getType()->isPointerTy() || 972 (!Call->doesNotCapture(OperandNo) && OperandNo < Call->arg_size() && 973 !Call->isByValArgument(OperandNo))) 974 continue; 975 976 // Call doesn't access memory through this operand, so we don't care 977 // if it aliases with Object. 978 if (Call->doesNotAccessMemory(OperandNo)) 979 continue; 980 981 // If this is a no-capture pointer argument, see if we can tell that it 982 // is impossible to alias the pointer we're checking. 983 AliasResult AR = getBestAAResults().alias( 984 MemoryLocation::getBeforeOrAfter(*CI), 985 MemoryLocation::getBeforeOrAfter(Object), AAQI); 986 if (AR != AliasResult::MustAlias) 987 IsMustAlias = false; 988 // Operand doesn't alias 'Object', continue looking for other aliases 989 if (AR == AliasResult::NoAlias) 990 continue; 991 // Operand aliases 'Object', but call doesn't modify it. Strengthen 992 // initial assumption and keep looking in case if there are more aliases. 993 if (Call->onlyReadsMemory(OperandNo)) { 994 Result = setRef(Result); 995 continue; 996 } 997 // Operand aliases 'Object' but call only writes into it. 998 if (Call->doesNotReadMemory(OperandNo)) { 999 Result = setMod(Result); 1000 continue; 1001 } 1002 // This operand aliases 'Object' and call reads and writes into it. 1003 // Setting ModRef will not yield an early return below, MustAlias is not 1004 // used further. 1005 Result = ModRefInfo::ModRef; 1006 break; 1007 } 1008 1009 // No operand aliases, reset Must bit. Add below if at least one aliases 1010 // and all aliases found are MustAlias. 1011 if (isNoModRef(Result)) 1012 IsMustAlias = false; 1013 1014 // Early return if we improved mod ref information 1015 if (!isModAndRefSet(Result)) { 1016 if (isNoModRef(Result)) 1017 return ModRefInfo::NoModRef; 1018 return IsMustAlias ? setMust(Result) : clearMust(Result); 1019 } 1020 } 1021 1022 // If the call is malloc/calloc like, we can assume that it doesn't 1023 // modify any IR visible value. This is only valid because we assume these 1024 // routines do not read values visible in the IR. TODO: Consider special 1025 // casing realloc and strdup routines which access only their arguments as 1026 // well. Or alternatively, replace all of this with inaccessiblememonly once 1027 // that's implemented fully. 1028 if (isMallocOrCallocLikeFn(Call, &TLI)) { 1029 // Be conservative if the accessed pointer may alias the allocation - 1030 // fallback to the generic handling below. 1031 if (getBestAAResults().alias(MemoryLocation::getBeforeOrAfter(Call), Loc, 1032 AAQI) == AliasResult::NoAlias) 1033 return ModRefInfo::NoModRef; 1034 } 1035 1036 // The semantics of memcpy intrinsics either exactly overlap or do not 1037 // overlap, i.e., source and destination of any given memcpy are either 1038 // no-alias or must-alias. 1039 if (auto *Inst = dyn_cast<AnyMemCpyInst>(Call)) { 1040 AliasResult SrcAA = 1041 getBestAAResults().alias(MemoryLocation::getForSource(Inst), Loc, AAQI); 1042 AliasResult DestAA = 1043 getBestAAResults().alias(MemoryLocation::getForDest(Inst), Loc, AAQI); 1044 // It's also possible for Loc to alias both src and dest, or neither. 1045 ModRefInfo rv = ModRefInfo::NoModRef; 1046 if (SrcAA != AliasResult::NoAlias) 1047 rv = setRef(rv); 1048 if (DestAA != AliasResult::NoAlias) 1049 rv = setMod(rv); 1050 return rv; 1051 } 1052 1053 // Guard intrinsics are marked as arbitrarily writing so that proper control 1054 // dependencies are maintained but they never mods any particular memory 1055 // location. 1056 // 1057 // *Unlike* assumes, guard intrinsics are modeled as reading memory since the 1058 // heap state at the point the guard is issued needs to be consistent in case 1059 // the guard invokes the "deopt" continuation. 1060 if (isIntrinsicCall(Call, Intrinsic::experimental_guard)) 1061 return ModRefInfo::Ref; 1062 // The same applies to deoptimize which is essentially a guard(false). 1063 if (isIntrinsicCall(Call, Intrinsic::experimental_deoptimize)) 1064 return ModRefInfo::Ref; 1065 1066 // Like assumes, invariant.start intrinsics were also marked as arbitrarily 1067 // writing so that proper control dependencies are maintained but they never 1068 // mod any particular memory location visible to the IR. 1069 // *Unlike* assumes (which are now modeled as NoModRef), invariant.start 1070 // intrinsic is now modeled as reading memory. This prevents hoisting the 1071 // invariant.start intrinsic over stores. Consider: 1072 // *ptr = 40; 1073 // *ptr = 50; 1074 // invariant_start(ptr) 1075 // int val = *ptr; 1076 // print(val); 1077 // 1078 // This cannot be transformed to: 1079 // 1080 // *ptr = 40; 1081 // invariant_start(ptr) 1082 // *ptr = 50; 1083 // int val = *ptr; 1084 // print(val); 1085 // 1086 // The transformation will cause the second store to be ignored (based on 1087 // rules of invariant.start) and print 40, while the first program always 1088 // prints 50. 1089 if (isIntrinsicCall(Call, Intrinsic::invariant_start)) 1090 return ModRefInfo::Ref; 1091 1092 // The AAResultBase base class has some smarts, lets use them. 1093 return AAResultBase::getModRefInfo(Call, Loc, AAQI); 1094 } 1095 1096 ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call1, 1097 const CallBase *Call2, 1098 AAQueryInfo &AAQI) { 1099 // Guard intrinsics are marked as arbitrarily writing so that proper control 1100 // dependencies are maintained but they never mods any particular memory 1101 // location. 1102 // 1103 // *Unlike* assumes, guard intrinsics are modeled as reading memory since the 1104 // heap state at the point the guard is issued needs to be consistent in case 1105 // the guard invokes the "deopt" continuation. 1106 1107 // NB! This function is *not* commutative, so we special case two 1108 // possibilities for guard intrinsics. 1109 1110 if (isIntrinsicCall(Call1, Intrinsic::experimental_guard)) 1111 return isModSet(createModRefInfo(getModRefBehavior(Call2))) 1112 ? ModRefInfo::Ref 1113 : ModRefInfo::NoModRef; 1114 1115 if (isIntrinsicCall(Call2, Intrinsic::experimental_guard)) 1116 return isModSet(createModRefInfo(getModRefBehavior(Call1))) 1117 ? ModRefInfo::Mod 1118 : ModRefInfo::NoModRef; 1119 1120 // The AAResultBase base class has some smarts, lets use them. 1121 return AAResultBase::getModRefInfo(Call1, Call2, AAQI); 1122 } 1123 1124 /// Return true if we know V to the base address of the corresponding memory 1125 /// object. This implies that any address less than V must be out of bounds 1126 /// for the underlying object. Note that just being isIdentifiedObject() is 1127 /// not enough - For example, a negative offset from a noalias argument or call 1128 /// can be inbounds w.r.t the actual underlying object. 1129 static bool isBaseOfObject(const Value *V) { 1130 // TODO: We can handle other cases here 1131 // 1) For GC languages, arguments to functions are often required to be 1132 // base pointers. 1133 // 2) Result of allocation routines are often base pointers. Leverage TLI. 1134 return (isa<AllocaInst>(V) || isa<GlobalVariable>(V)); 1135 } 1136 1137 /// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against 1138 /// another pointer. 1139 /// 1140 /// We know that V1 is a GEP, but we don't know anything about V2. 1141 /// UnderlyingV1 is getUnderlyingObject(GEP1), UnderlyingV2 is the same for 1142 /// V2. 1143 AliasResult BasicAAResult::aliasGEP( 1144 const GEPOperator *GEP1, LocationSize V1Size, 1145 const Value *V2, LocationSize V2Size, 1146 const Value *UnderlyingV1, const Value *UnderlyingV2, AAQueryInfo &AAQI) { 1147 if (!V1Size.hasValue() && !V2Size.hasValue()) { 1148 // TODO: This limitation exists for compile-time reasons. Relax it if we 1149 // can avoid exponential pathological cases. 1150 if (!isa<GEPOperator>(V2)) 1151 return AliasResult::MayAlias; 1152 1153 // If both accesses have unknown size, we can only check whether the base 1154 // objects don't alias. 1155 AliasResult BaseAlias = getBestAAResults().alias( 1156 MemoryLocation::getBeforeOrAfter(UnderlyingV1), 1157 MemoryLocation::getBeforeOrAfter(UnderlyingV2), AAQI); 1158 return BaseAlias == AliasResult::NoAlias ? AliasResult::NoAlias 1159 : AliasResult::MayAlias; 1160 } 1161 1162 DecomposedGEP DecompGEP1 = DecomposeGEPExpression(GEP1, DL, &AC, DT); 1163 DecomposedGEP DecompGEP2 = DecomposeGEPExpression(V2, DL, &AC, DT); 1164 1165 // Don't attempt to analyze the decomposed GEP if index scale is not a 1166 // compile-time constant. 1167 if (!DecompGEP1.HasCompileTimeConstantScale || 1168 !DecompGEP2.HasCompileTimeConstantScale) 1169 return AliasResult::MayAlias; 1170 1171 assert(DecompGEP1.Base == UnderlyingV1 && DecompGEP2.Base == UnderlyingV2 && 1172 "DecomposeGEPExpression returned a result different from " 1173 "getUnderlyingObject"); 1174 1175 // Subtract the GEP2 pointer from the GEP1 pointer to find out their 1176 // symbolic difference. 1177 subtractDecomposedGEPs(DecompGEP1, DecompGEP2); 1178 1179 // If an inbounds GEP would have to start from an out of bounds address 1180 // for the two to alias, then we can assume noalias. 1181 if (*DecompGEP1.InBounds && DecompGEP1.VarIndices.empty() && 1182 V2Size.hasValue() && DecompGEP1.Offset.sge(V2Size.getValue()) && 1183 isBaseOfObject(DecompGEP2.Base)) 1184 return AliasResult::NoAlias; 1185 1186 if (isa<GEPOperator>(V2)) { 1187 // Symmetric case to above. 1188 if (*DecompGEP2.InBounds && DecompGEP1.VarIndices.empty() && 1189 V1Size.hasValue() && DecompGEP1.Offset.sle(-V1Size.getValue()) && 1190 isBaseOfObject(DecompGEP1.Base)) 1191 return AliasResult::NoAlias; 1192 } 1193 1194 // For GEPs with identical offsets, we can preserve the size and AAInfo 1195 // when performing the alias check on the underlying objects. 1196 if (DecompGEP1.Offset == 0 && DecompGEP1.VarIndices.empty()) 1197 return getBestAAResults().alias( 1198 MemoryLocation(UnderlyingV1, V1Size), 1199 MemoryLocation(UnderlyingV2, V2Size), AAQI); 1200 1201 // Do the base pointers alias? 1202 AliasResult BaseAlias = getBestAAResults().alias( 1203 MemoryLocation::getBeforeOrAfter(UnderlyingV1), 1204 MemoryLocation::getBeforeOrAfter(UnderlyingV2), AAQI); 1205 1206 // If we get a No or May, then return it immediately, no amount of analysis 1207 // will improve this situation. 1208 if (BaseAlias != AliasResult::MustAlias) { 1209 assert(BaseAlias == AliasResult::NoAlias || 1210 BaseAlias == AliasResult::MayAlias); 1211 return BaseAlias; 1212 } 1213 1214 // If there is a constant difference between the pointers, but the difference 1215 // is less than the size of the associated memory object, then we know 1216 // that the objects are partially overlapping. If the difference is 1217 // greater, we know they do not overlap. 1218 if (DecompGEP1.Offset != 0 && DecompGEP1.VarIndices.empty()) { 1219 APInt &Off = DecompGEP1.Offset; 1220 1221 // Initialize for Off >= 0 (V2 <= GEP1) case. 1222 const Value *LeftPtr = V2; 1223 const Value *RightPtr = GEP1; 1224 LocationSize VLeftSize = V2Size; 1225 LocationSize VRightSize = V1Size; 1226 const bool Swapped = Off.isNegative(); 1227 1228 if (Swapped) { 1229 // Swap if we have the situation where: 1230 // + + 1231 // | BaseOffset | 1232 // ---------------->| 1233 // |-->V1Size |-------> V2Size 1234 // GEP1 V2 1235 std::swap(LeftPtr, RightPtr); 1236 std::swap(VLeftSize, VRightSize); 1237 Off = -Off; 1238 } 1239 1240 if (VLeftSize.hasValue()) { 1241 const uint64_t LSize = VLeftSize.getValue(); 1242 if (Off.ult(LSize)) { 1243 // Conservatively drop processing if a phi was visited and/or offset is 1244 // too big. 1245 AliasResult AR = AliasResult::PartialAlias; 1246 if (VRightSize.hasValue() && Off.ule(INT32_MAX) && 1247 (Off + VRightSize.getValue()).ule(LSize)) { 1248 // Memory referenced by right pointer is nested. Save the offset in 1249 // cache. Note that originally offset estimated as GEP1-V2, but 1250 // AliasResult contains the shift that represents GEP1+Offset=V2. 1251 AR.setOffset(-Off.getSExtValue()); 1252 AR.swap(Swapped); 1253 } 1254 return AR; 1255 } 1256 return AliasResult::NoAlias; 1257 } 1258 } 1259 1260 if (!DecompGEP1.VarIndices.empty()) { 1261 APInt GCD; 1262 bool AllNonNegative = DecompGEP1.Offset.isNonNegative(); 1263 bool AllNonPositive = DecompGEP1.Offset.isNonPositive(); 1264 for (unsigned i = 0, e = DecompGEP1.VarIndices.size(); i != e; ++i) { 1265 const VariableGEPIndex &Index = DecompGEP1.VarIndices[i]; 1266 const APInt &Scale = Index.Scale; 1267 APInt ScaleForGCD = Scale; 1268 if (!Index.IsNSW) 1269 ScaleForGCD = APInt::getOneBitSet(Scale.getBitWidth(), 1270 Scale.countTrailingZeros()); 1271 1272 if (i == 0) 1273 GCD = ScaleForGCD.abs(); 1274 else 1275 GCD = APIntOps::GreatestCommonDivisor(GCD, ScaleForGCD.abs()); 1276 1277 if (AllNonNegative || AllNonPositive) { 1278 KnownBits Known = Index.Val.evaluateWith( 1279 computeKnownBits(Index.Val.V, DL, 0, &AC, Index.CxtI, DT)); 1280 // TODO: Account for implicit trunc. 1281 bool SignKnownZero = Known.isNonNegative(); 1282 bool SignKnownOne = Known.isNegative(); 1283 AllNonNegative &= (SignKnownZero && Scale.isNonNegative()) || 1284 (SignKnownOne && Scale.isNonPositive()); 1285 AllNonPositive &= (SignKnownZero && Scale.isNonPositive()) || 1286 (SignKnownOne && Scale.isNonNegative()); 1287 } 1288 } 1289 1290 // We now have accesses at two offsets from the same base: 1291 // 1. (...)*GCD + DecompGEP1.Offset with size V1Size 1292 // 2. 0 with size V2Size 1293 // Using arithmetic modulo GCD, the accesses are at 1294 // [ModOffset..ModOffset+V1Size) and [0..V2Size). If the first access fits 1295 // into the range [V2Size..GCD), then we know they cannot overlap. 1296 APInt ModOffset = DecompGEP1.Offset.srem(GCD); 1297 if (ModOffset.isNegative()) 1298 ModOffset += GCD; // We want mod, not rem. 1299 if (V1Size.hasValue() && V2Size.hasValue() && 1300 ModOffset.uge(V2Size.getValue()) && 1301 (GCD - ModOffset).uge(V1Size.getValue())) 1302 return AliasResult::NoAlias; 1303 1304 // If we know all the variables are non-negative, then the total offset is 1305 // also non-negative and >= DecompGEP1.Offset. We have the following layout: 1306 // [0, V2Size) ... [TotalOffset, TotalOffer+V1Size] 1307 // If DecompGEP1.Offset >= V2Size, the accesses don't alias. 1308 if (AllNonNegative && V2Size.hasValue() && 1309 DecompGEP1.Offset.uge(V2Size.getValue())) 1310 return AliasResult::NoAlias; 1311 // Similarly, if the variables are non-positive, then the total offset is 1312 // also non-positive and <= DecompGEP1.Offset. We have the following layout: 1313 // [TotalOffset, TotalOffset+V1Size) ... [0, V2Size) 1314 // If -DecompGEP1.Offset >= V1Size, the accesses don't alias. 1315 if (AllNonPositive && V1Size.hasValue() && 1316 (-DecompGEP1.Offset).uge(V1Size.getValue())) 1317 return AliasResult::NoAlias; 1318 1319 if (V1Size.hasValue() && V2Size.hasValue()) { 1320 // Try to determine the range of values for VarIndex. 1321 // VarIndexRange is such that: 1322 // (VarIndex <= -MinAbsVarIndex || MinAbsVarIndex <= VarIndex) && 1323 // VarIndexRange.contains(VarIndex) 1324 Optional<APInt> MinAbsVarIndex; 1325 Optional<ConstantRange> VarIndexRange; 1326 if (DecompGEP1.VarIndices.size() == 1) { 1327 // VarIndex = Scale*V. 1328 const VariableGEPIndex &Var = DecompGEP1.VarIndices[0]; 1329 if (isKnownNonZero(Var.Val.V, DL, 0, &AC, Var.CxtI, DT)) { 1330 // If V != 0 then abs(VarIndex) >= abs(Scale). 1331 MinAbsVarIndex = Var.Scale.abs(); 1332 } 1333 ConstantRange R = Var.Val.evaluateWith( 1334 computeConstantRange(Var.Val.V, true, &AC, Var.CxtI)); 1335 if (!R.isFullSet() && !R.isEmptySet()) 1336 VarIndexRange = R.sextOrTrunc(Var.Scale.getBitWidth()) 1337 .multiply(ConstantRange(Var.Scale)); 1338 } else if (DecompGEP1.VarIndices.size() == 2) { 1339 // VarIndex = Scale*V0 + (-Scale)*V1. 1340 // If V0 != V1 then abs(VarIndex) >= abs(Scale). 1341 // Check that VisitedPhiBBs is empty, to avoid reasoning about 1342 // inequality of values across loop iterations. 1343 const VariableGEPIndex &Var0 = DecompGEP1.VarIndices[0]; 1344 const VariableGEPIndex &Var1 = DecompGEP1.VarIndices[1]; 1345 if (Var0.Scale == -Var1.Scale && 1346 Var0.Val.hasSameExtensionsAs(Var1.Val) && VisitedPhiBBs.empty() && 1347 isKnownNonEqual(Var0.Val.V, Var1.Val.V, DL, &AC, /* CxtI */ nullptr, 1348 DT)) 1349 MinAbsVarIndex = Var0.Scale.abs(); 1350 } 1351 1352 if (MinAbsVarIndex) { 1353 // The constant offset will have added at least +/-MinAbsVarIndex to it. 1354 APInt OffsetLo = DecompGEP1.Offset - *MinAbsVarIndex; 1355 APInt OffsetHi = DecompGEP1.Offset + *MinAbsVarIndex; 1356 // We know that Offset <= OffsetLo || Offset >= OffsetHi 1357 if (OffsetLo.isNegative() && (-OffsetLo).uge(V1Size.getValue()) && 1358 OffsetHi.isNonNegative() && OffsetHi.uge(V2Size.getValue())) 1359 return AliasResult::NoAlias; 1360 } 1361 1362 if (VarIndexRange) { 1363 ConstantRange OffsetRange = 1364 VarIndexRange->add(ConstantRange(DecompGEP1.Offset)); 1365 1366 // We know that Offset >= MinOffset. 1367 // (MinOffset >= V2Size) => (Offset >= V2Size) => NoAlias. 1368 if (OffsetRange.getSignedMin().sge(V2Size.getValue())) 1369 return AliasResult::NoAlias; 1370 1371 // We know that Offset <= MaxOffset. 1372 // (MaxOffset <= -V1Size) => (Offset <= -V1Size) => NoAlias. 1373 if (OffsetRange.getSignedMax().sle(-V1Size.getValue())) 1374 return AliasResult::NoAlias; 1375 } 1376 } 1377 1378 if (constantOffsetHeuristic(DecompGEP1, V1Size, V2Size, &AC, DT)) 1379 return AliasResult::NoAlias; 1380 } 1381 1382 // Statically, we can see that the base objects are the same, but the 1383 // pointers have dynamic offsets which we can't resolve. And none of our 1384 // little tricks above worked. 1385 return AliasResult::MayAlias; 1386 } 1387 1388 static AliasResult MergeAliasResults(AliasResult A, AliasResult B) { 1389 // If the results agree, take it. 1390 if (A == B) 1391 return A; 1392 // A mix of PartialAlias and MustAlias is PartialAlias. 1393 if ((A == AliasResult::PartialAlias && B == AliasResult::MustAlias) || 1394 (B == AliasResult::PartialAlias && A == AliasResult::MustAlias)) 1395 return AliasResult::PartialAlias; 1396 // Otherwise, we don't know anything. 1397 return AliasResult::MayAlias; 1398 } 1399 1400 /// Provides a bunch of ad-hoc rules to disambiguate a Select instruction 1401 /// against another. 1402 AliasResult 1403 BasicAAResult::aliasSelect(const SelectInst *SI, LocationSize SISize, 1404 const Value *V2, LocationSize V2Size, 1405 AAQueryInfo &AAQI) { 1406 // If the values are Selects with the same condition, we can do a more precise 1407 // check: just check for aliases between the values on corresponding arms. 1408 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) 1409 if (SI->getCondition() == SI2->getCondition()) { 1410 AliasResult Alias = getBestAAResults().alias( 1411 MemoryLocation(SI->getTrueValue(), SISize), 1412 MemoryLocation(SI2->getTrueValue(), V2Size), AAQI); 1413 if (Alias == AliasResult::MayAlias) 1414 return AliasResult::MayAlias; 1415 AliasResult ThisAlias = getBestAAResults().alias( 1416 MemoryLocation(SI->getFalseValue(), SISize), 1417 MemoryLocation(SI2->getFalseValue(), V2Size), AAQI); 1418 return MergeAliasResults(ThisAlias, Alias); 1419 } 1420 1421 // If both arms of the Select node NoAlias or MustAlias V2, then returns 1422 // NoAlias / MustAlias. Otherwise, returns MayAlias. 1423 AliasResult Alias = getBestAAResults().alias( 1424 MemoryLocation(V2, V2Size), 1425 MemoryLocation(SI->getTrueValue(), SISize), AAQI); 1426 if (Alias == AliasResult::MayAlias) 1427 return AliasResult::MayAlias; 1428 1429 AliasResult ThisAlias = getBestAAResults().alias( 1430 MemoryLocation(V2, V2Size), 1431 MemoryLocation(SI->getFalseValue(), SISize), AAQI); 1432 return MergeAliasResults(ThisAlias, Alias); 1433 } 1434 1435 /// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against 1436 /// another. 1437 AliasResult BasicAAResult::aliasPHI(const PHINode *PN, LocationSize PNSize, 1438 const Value *V2, LocationSize V2Size, 1439 AAQueryInfo &AAQI) { 1440 if (!PN->getNumIncomingValues()) 1441 return AliasResult::NoAlias; 1442 // If the values are PHIs in the same block, we can do a more precise 1443 // as well as efficient check: just check for aliases between the values 1444 // on corresponding edges. 1445 if (const PHINode *PN2 = dyn_cast<PHINode>(V2)) 1446 if (PN2->getParent() == PN->getParent()) { 1447 Optional<AliasResult> Alias; 1448 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1449 AliasResult ThisAlias = getBestAAResults().alias( 1450 MemoryLocation(PN->getIncomingValue(i), PNSize), 1451 MemoryLocation( 1452 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)), V2Size), 1453 AAQI); 1454 if (Alias) 1455 *Alias = MergeAliasResults(*Alias, ThisAlias); 1456 else 1457 Alias = ThisAlias; 1458 if (*Alias == AliasResult::MayAlias) 1459 break; 1460 } 1461 return *Alias; 1462 } 1463 1464 SmallVector<Value *, 4> V1Srcs; 1465 // If a phi operand recurses back to the phi, we can still determine NoAlias 1466 // if we don't alias the underlying objects of the other phi operands, as we 1467 // know that the recursive phi needs to be based on them in some way. 1468 bool isRecursive = false; 1469 auto CheckForRecPhi = [&](Value *PV) { 1470 if (!EnableRecPhiAnalysis) 1471 return false; 1472 if (getUnderlyingObject(PV) == PN) { 1473 isRecursive = true; 1474 return true; 1475 } 1476 return false; 1477 }; 1478 1479 if (PV) { 1480 // If we have PhiValues then use it to get the underlying phi values. 1481 const PhiValues::ValueSet &PhiValueSet = PV->getValuesForPhi(PN); 1482 // If we have more phi values than the search depth then return MayAlias 1483 // conservatively to avoid compile time explosion. The worst possible case 1484 // is if both sides are PHI nodes. In which case, this is O(m x n) time 1485 // where 'm' and 'n' are the number of PHI sources. 1486 if (PhiValueSet.size() > MaxLookupSearchDepth) 1487 return AliasResult::MayAlias; 1488 // Add the values to V1Srcs 1489 for (Value *PV1 : PhiValueSet) { 1490 if (CheckForRecPhi(PV1)) 1491 continue; 1492 V1Srcs.push_back(PV1); 1493 } 1494 } else { 1495 // If we don't have PhiInfo then just look at the operands of the phi itself 1496 // FIXME: Remove this once we can guarantee that we have PhiInfo always 1497 SmallPtrSet<Value *, 4> UniqueSrc; 1498 Value *OnePhi = nullptr; 1499 for (Value *PV1 : PN->incoming_values()) { 1500 if (isa<PHINode>(PV1)) { 1501 if (OnePhi && OnePhi != PV1) { 1502 // To control potential compile time explosion, we choose to be 1503 // conserviate when we have more than one Phi input. It is important 1504 // that we handle the single phi case as that lets us handle LCSSA 1505 // phi nodes and (combined with the recursive phi handling) simple 1506 // pointer induction variable patterns. 1507 return AliasResult::MayAlias; 1508 } 1509 OnePhi = PV1; 1510 } 1511 1512 if (CheckForRecPhi(PV1)) 1513 continue; 1514 1515 if (UniqueSrc.insert(PV1).second) 1516 V1Srcs.push_back(PV1); 1517 } 1518 1519 if (OnePhi && UniqueSrc.size() > 1) 1520 // Out of an abundance of caution, allow only the trivial lcssa and 1521 // recursive phi cases. 1522 return AliasResult::MayAlias; 1523 } 1524 1525 // If V1Srcs is empty then that means that the phi has no underlying non-phi 1526 // value. This should only be possible in blocks unreachable from the entry 1527 // block, but return MayAlias just in case. 1528 if (V1Srcs.empty()) 1529 return AliasResult::MayAlias; 1530 1531 // If this PHI node is recursive, indicate that the pointer may be moved 1532 // across iterations. We can only prove NoAlias if different underlying 1533 // objects are involved. 1534 if (isRecursive) 1535 PNSize = LocationSize::beforeOrAfterPointer(); 1536 1537 // In the recursive alias queries below, we may compare values from two 1538 // different loop iterations. Keep track of visited phi blocks, which will 1539 // be used when determining value equivalence. 1540 bool BlockInserted = VisitedPhiBBs.insert(PN->getParent()).second; 1541 auto _ = make_scope_exit([&]() { 1542 if (BlockInserted) 1543 VisitedPhiBBs.erase(PN->getParent()); 1544 }); 1545 1546 // If we inserted a block into VisitedPhiBBs, alias analysis results that 1547 // have been cached earlier may no longer be valid. Perform recursive queries 1548 // with a new AAQueryInfo. 1549 AAQueryInfo NewAAQI = AAQI.withEmptyCache(); 1550 AAQueryInfo *UseAAQI = BlockInserted ? &NewAAQI : &AAQI; 1551 1552 AliasResult Alias = getBestAAResults().alias( 1553 MemoryLocation(V2, V2Size), 1554 MemoryLocation(V1Srcs[0], PNSize), *UseAAQI); 1555 1556 // Early exit if the check of the first PHI source against V2 is MayAlias. 1557 // Other results are not possible. 1558 if (Alias == AliasResult::MayAlias) 1559 return AliasResult::MayAlias; 1560 // With recursive phis we cannot guarantee that MustAlias/PartialAlias will 1561 // remain valid to all elements and needs to conservatively return MayAlias. 1562 if (isRecursive && Alias != AliasResult::NoAlias) 1563 return AliasResult::MayAlias; 1564 1565 // If all sources of the PHI node NoAlias or MustAlias V2, then returns 1566 // NoAlias / MustAlias. Otherwise, returns MayAlias. 1567 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) { 1568 Value *V = V1Srcs[i]; 1569 1570 AliasResult ThisAlias = getBestAAResults().alias( 1571 MemoryLocation(V2, V2Size), MemoryLocation(V, PNSize), *UseAAQI); 1572 Alias = MergeAliasResults(ThisAlias, Alias); 1573 if (Alias == AliasResult::MayAlias) 1574 break; 1575 } 1576 1577 return Alias; 1578 } 1579 1580 /// Provides a bunch of ad-hoc rules to disambiguate in common cases, such as 1581 /// array references. 1582 AliasResult BasicAAResult::aliasCheck(const Value *V1, LocationSize V1Size, 1583 const Value *V2, LocationSize V2Size, 1584 AAQueryInfo &AAQI) { 1585 // If either of the memory references is empty, it doesn't matter what the 1586 // pointer values are. 1587 if (V1Size.isZero() || V2Size.isZero()) 1588 return AliasResult::NoAlias; 1589 1590 // Strip off any casts if they exist. 1591 V1 = V1->stripPointerCastsForAliasAnalysis(); 1592 V2 = V2->stripPointerCastsForAliasAnalysis(); 1593 1594 // If V1 or V2 is undef, the result is NoAlias because we can always pick a 1595 // value for undef that aliases nothing in the program. 1596 if (isa<UndefValue>(V1) || isa<UndefValue>(V2)) 1597 return AliasResult::NoAlias; 1598 1599 // Are we checking for alias of the same value? 1600 // Because we look 'through' phi nodes, we could look at "Value" pointers from 1601 // different iterations. We must therefore make sure that this is not the 1602 // case. The function isValueEqualInPotentialCycles ensures that this cannot 1603 // happen by looking at the visited phi nodes and making sure they cannot 1604 // reach the value. 1605 if (isValueEqualInPotentialCycles(V1, V2)) 1606 return AliasResult::MustAlias; 1607 1608 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy()) 1609 return AliasResult::NoAlias; // Scalars cannot alias each other 1610 1611 // Figure out what objects these things are pointing to if we can. 1612 const Value *O1 = getUnderlyingObject(V1, MaxLookupSearchDepth); 1613 const Value *O2 = getUnderlyingObject(V2, MaxLookupSearchDepth); 1614 1615 // Null values in the default address space don't point to any object, so they 1616 // don't alias any other pointer. 1617 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1)) 1618 if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace())) 1619 return AliasResult::NoAlias; 1620 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2)) 1621 if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace())) 1622 return AliasResult::NoAlias; 1623 1624 if (O1 != O2) { 1625 // If V1/V2 point to two different objects, we know that we have no alias. 1626 if (isIdentifiedObject(O1) && isIdentifiedObject(O2)) 1627 return AliasResult::NoAlias; 1628 1629 // Constant pointers can't alias with non-const isIdentifiedObject objects. 1630 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) || 1631 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1))) 1632 return AliasResult::NoAlias; 1633 1634 // Function arguments can't alias with things that are known to be 1635 // unambigously identified at the function level. 1636 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) || 1637 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1))) 1638 return AliasResult::NoAlias; 1639 1640 // If one pointer is the result of a call/invoke or load and the other is a 1641 // non-escaping local object within the same function, then we know the 1642 // object couldn't escape to a point where the call could return it. 1643 // 1644 // Note that if the pointers are in different functions, there are a 1645 // variety of complications. A call with a nocapture argument may still 1646 // temporary store the nocapture argument's value in a temporary memory 1647 // location if that memory location doesn't escape. Or it may pass a 1648 // nocapture value to other functions as long as they don't capture it. 1649 if (isEscapeSource(O1) && 1650 AAQI.CI->isNotCapturedBeforeOrAt(O2, cast<Instruction>(O1))) 1651 return AliasResult::NoAlias; 1652 if (isEscapeSource(O2) && 1653 AAQI.CI->isNotCapturedBeforeOrAt(O1, cast<Instruction>(O2))) 1654 return AliasResult::NoAlias; 1655 } 1656 1657 // If the size of one access is larger than the entire object on the other 1658 // side, then we know such behavior is undefined and can assume no alias. 1659 bool NullIsValidLocation = NullPointerIsDefined(&F); 1660 if ((isObjectSmallerThan( 1661 O2, getMinimalExtentFrom(*V1, V1Size, DL, NullIsValidLocation), DL, 1662 TLI, NullIsValidLocation)) || 1663 (isObjectSmallerThan( 1664 O1, getMinimalExtentFrom(*V2, V2Size, DL, NullIsValidLocation), DL, 1665 TLI, NullIsValidLocation))) 1666 return AliasResult::NoAlias; 1667 1668 // If one the accesses may be before the accessed pointer, canonicalize this 1669 // by using unknown after-pointer sizes for both accesses. This is 1670 // equivalent, because regardless of which pointer is lower, one of them 1671 // will always came after the other, as long as the underlying objects aren't 1672 // disjoint. We do this so that the rest of BasicAA does not have to deal 1673 // with accesses before the base pointer, and to improve cache utilization by 1674 // merging equivalent states. 1675 if (V1Size.mayBeBeforePointer() || V2Size.mayBeBeforePointer()) { 1676 V1Size = LocationSize::afterPointer(); 1677 V2Size = LocationSize::afterPointer(); 1678 } 1679 1680 // FIXME: If this depth limit is hit, then we may cache sub-optimal results 1681 // for recursive queries. For this reason, this limit is chosen to be large 1682 // enough to be very rarely hit, while still being small enough to avoid 1683 // stack overflows. 1684 if (AAQI.Depth >= 512) 1685 return AliasResult::MayAlias; 1686 1687 // Check the cache before climbing up use-def chains. This also terminates 1688 // otherwise infinitely recursive queries. 1689 AAQueryInfo::LocPair Locs({V1, V1Size}, {V2, V2Size}); 1690 const bool Swapped = V1 > V2; 1691 if (Swapped) 1692 std::swap(Locs.first, Locs.second); 1693 const auto &Pair = AAQI.AliasCache.try_emplace( 1694 Locs, AAQueryInfo::CacheEntry{AliasResult::NoAlias, 0}); 1695 if (!Pair.second) { 1696 auto &Entry = Pair.first->second; 1697 if (!Entry.isDefinitive()) { 1698 // Remember that we used an assumption. 1699 ++Entry.NumAssumptionUses; 1700 ++AAQI.NumAssumptionUses; 1701 } 1702 // Cache contains sorted {V1,V2} pairs but we should return original order. 1703 auto Result = Entry.Result; 1704 Result.swap(Swapped); 1705 return Result; 1706 } 1707 1708 int OrigNumAssumptionUses = AAQI.NumAssumptionUses; 1709 unsigned OrigNumAssumptionBasedResults = AAQI.AssumptionBasedResults.size(); 1710 AliasResult Result = 1711 aliasCheckRecursive(V1, V1Size, V2, V2Size, AAQI, O1, O2); 1712 1713 auto It = AAQI.AliasCache.find(Locs); 1714 assert(It != AAQI.AliasCache.end() && "Must be in cache"); 1715 auto &Entry = It->second; 1716 1717 // Check whether a NoAlias assumption has been used, but disproven. 1718 bool AssumptionDisproven = 1719 Entry.NumAssumptionUses > 0 && Result != AliasResult::NoAlias; 1720 if (AssumptionDisproven) 1721 Result = AliasResult::MayAlias; 1722 1723 // This is a definitive result now, when considered as a root query. 1724 AAQI.NumAssumptionUses -= Entry.NumAssumptionUses; 1725 Entry.Result = Result; 1726 // Cache contains sorted {V1,V2} pairs. 1727 Entry.Result.swap(Swapped); 1728 Entry.NumAssumptionUses = -1; 1729 1730 // If the assumption has been disproven, remove any results that may have 1731 // been based on this assumption. Do this after the Entry updates above to 1732 // avoid iterator invalidation. 1733 if (AssumptionDisproven) 1734 while (AAQI.AssumptionBasedResults.size() > OrigNumAssumptionBasedResults) 1735 AAQI.AliasCache.erase(AAQI.AssumptionBasedResults.pop_back_val()); 1736 1737 // The result may still be based on assumptions higher up in the chain. 1738 // Remember it, so it can be purged from the cache later. 1739 if (OrigNumAssumptionUses != AAQI.NumAssumptionUses && 1740 Result != AliasResult::MayAlias) 1741 AAQI.AssumptionBasedResults.push_back(Locs); 1742 return Result; 1743 } 1744 1745 AliasResult BasicAAResult::aliasCheckRecursive( 1746 const Value *V1, LocationSize V1Size, 1747 const Value *V2, LocationSize V2Size, 1748 AAQueryInfo &AAQI, const Value *O1, const Value *O2) { 1749 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) { 1750 AliasResult Result = aliasGEP(GV1, V1Size, V2, V2Size, O1, O2, AAQI); 1751 if (Result != AliasResult::MayAlias) 1752 return Result; 1753 } else if (const GEPOperator *GV2 = dyn_cast<GEPOperator>(V2)) { 1754 AliasResult Result = aliasGEP(GV2, V2Size, V1, V1Size, O2, O1, AAQI); 1755 if (Result != AliasResult::MayAlias) 1756 return Result; 1757 } 1758 1759 if (const PHINode *PN = dyn_cast<PHINode>(V1)) { 1760 AliasResult Result = aliasPHI(PN, V1Size, V2, V2Size, AAQI); 1761 if (Result != AliasResult::MayAlias) 1762 return Result; 1763 } else if (const PHINode *PN = dyn_cast<PHINode>(V2)) { 1764 AliasResult Result = aliasPHI(PN, V2Size, V1, V1Size, AAQI); 1765 if (Result != AliasResult::MayAlias) 1766 return Result; 1767 } 1768 1769 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) { 1770 AliasResult Result = aliasSelect(S1, V1Size, V2, V2Size, AAQI); 1771 if (Result != AliasResult::MayAlias) 1772 return Result; 1773 } else if (const SelectInst *S2 = dyn_cast<SelectInst>(V2)) { 1774 AliasResult Result = aliasSelect(S2, V2Size, V1, V1Size, AAQI); 1775 if (Result != AliasResult::MayAlias) 1776 return Result; 1777 } 1778 1779 // If both pointers are pointing into the same object and one of them 1780 // accesses the entire object, then the accesses must overlap in some way. 1781 if (O1 == O2) { 1782 bool NullIsValidLocation = NullPointerIsDefined(&F); 1783 if (V1Size.isPrecise() && V2Size.isPrecise() && 1784 (isObjectSize(O1, V1Size.getValue(), DL, TLI, NullIsValidLocation) || 1785 isObjectSize(O2, V2Size.getValue(), DL, TLI, NullIsValidLocation))) 1786 return AliasResult::PartialAlias; 1787 } 1788 1789 return AliasResult::MayAlias; 1790 } 1791 1792 /// Check whether two Values can be considered equivalent. 1793 /// 1794 /// In addition to pointer equivalence of \p V1 and \p V2 this checks whether 1795 /// they can not be part of a cycle in the value graph by looking at all 1796 /// visited phi nodes an making sure that the phis cannot reach the value. We 1797 /// have to do this because we are looking through phi nodes (That is we say 1798 /// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB). 1799 bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V, 1800 const Value *V2) { 1801 if (V != V2) 1802 return false; 1803 1804 const Instruction *Inst = dyn_cast<Instruction>(V); 1805 if (!Inst) 1806 return true; 1807 1808 if (VisitedPhiBBs.empty()) 1809 return true; 1810 1811 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck) 1812 return false; 1813 1814 // Make sure that the visited phis cannot reach the Value. This ensures that 1815 // the Values cannot come from different iterations of a potential cycle the 1816 // phi nodes could be involved in. 1817 for (auto *P : VisitedPhiBBs) 1818 if (isPotentiallyReachable(&P->front(), Inst, nullptr, DT)) 1819 return false; 1820 1821 return true; 1822 } 1823 1824 /// Computes the symbolic difference between two de-composed GEPs. 1825 void BasicAAResult::subtractDecomposedGEPs(DecomposedGEP &DestGEP, 1826 const DecomposedGEP &SrcGEP) { 1827 DestGEP.Offset -= SrcGEP.Offset; 1828 for (const VariableGEPIndex &Src : SrcGEP.VarIndices) { 1829 // Find V in Dest. This is N^2, but pointer indices almost never have more 1830 // than a few variable indexes. 1831 bool Found = false; 1832 for (auto I : enumerate(DestGEP.VarIndices)) { 1833 VariableGEPIndex &Dest = I.value(); 1834 if (!isValueEqualInPotentialCycles(Dest.Val.V, Src.Val.V) || 1835 !Dest.Val.hasSameExtensionsAs(Src.Val)) 1836 continue; 1837 1838 // If we found it, subtract off Scale V's from the entry in Dest. If it 1839 // goes to zero, remove the entry. 1840 if (Dest.Scale != Src.Scale) { 1841 Dest.Scale -= Src.Scale; 1842 Dest.IsNSW = false; 1843 } else { 1844 DestGEP.VarIndices.erase(DestGEP.VarIndices.begin() + I.index()); 1845 } 1846 Found = true; 1847 break; 1848 } 1849 1850 // If we didn't consume this entry, add it to the end of the Dest list. 1851 if (!Found) { 1852 VariableGEPIndex Entry = {Src.Val, -Src.Scale, Src.CxtI, Src.IsNSW}; 1853 DestGEP.VarIndices.push_back(Entry); 1854 } 1855 } 1856 } 1857 1858 bool BasicAAResult::constantOffsetHeuristic( 1859 const DecomposedGEP &GEP, LocationSize MaybeV1Size, 1860 LocationSize MaybeV2Size, AssumptionCache *AC, DominatorTree *DT) { 1861 if (GEP.VarIndices.size() != 2 || !MaybeV1Size.hasValue() || 1862 !MaybeV2Size.hasValue()) 1863 return false; 1864 1865 const uint64_t V1Size = MaybeV1Size.getValue(); 1866 const uint64_t V2Size = MaybeV2Size.getValue(); 1867 1868 const VariableGEPIndex &Var0 = GEP.VarIndices[0], &Var1 = GEP.VarIndices[1]; 1869 1870 if (!Var0.Val.hasSameExtensionsAs(Var1.Val) || Var0.Scale != -Var1.Scale || 1871 Var0.Val.V->getType() != Var1.Val.V->getType()) 1872 return false; 1873 1874 // We'll strip off the Extensions of Var0 and Var1 and do another round 1875 // of GetLinearExpression decomposition. In the example above, if Var0 1876 // is zext(%x + 1) we should get V1 == %x and V1Offset == 1. 1877 1878 LinearExpression E0 = 1879 GetLinearExpression(ExtendedValue(Var0.Val.V), DL, 0, AC, DT); 1880 LinearExpression E1 = 1881 GetLinearExpression(ExtendedValue(Var1.Val.V), DL, 0, AC, DT); 1882 if (E0.Scale != E1.Scale || !E0.Val.hasSameExtensionsAs(E1.Val) || 1883 !isValueEqualInPotentialCycles(E0.Val.V, E1.Val.V)) 1884 return false; 1885 1886 // We have a hit - Var0 and Var1 only differ by a constant offset! 1887 1888 // If we've been sext'ed then zext'd the maximum difference between Var0 and 1889 // Var1 is possible to calculate, but we're just interested in the absolute 1890 // minimum difference between the two. The minimum distance may occur due to 1891 // wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so 1892 // the minimum distance between %i and %i + 5 is 3. 1893 APInt MinDiff = E0.Offset - E1.Offset, Wrapped = -MinDiff; 1894 MinDiff = APIntOps::umin(MinDiff, Wrapped); 1895 APInt MinDiffBytes = 1896 MinDiff.zextOrTrunc(Var0.Scale.getBitWidth()) * Var0.Scale.abs(); 1897 1898 // We can't definitely say whether GEP1 is before or after V2 due to wrapping 1899 // arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other 1900 // values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and 1901 // V2Size can fit in the MinDiffBytes gap. 1902 return MinDiffBytes.uge(V1Size + GEP.Offset.abs()) && 1903 MinDiffBytes.uge(V2Size + GEP.Offset.abs()); 1904 } 1905 1906 //===----------------------------------------------------------------------===// 1907 // BasicAliasAnalysis Pass 1908 //===----------------------------------------------------------------------===// 1909 1910 AnalysisKey BasicAA::Key; 1911 1912 BasicAAResult BasicAA::run(Function &F, FunctionAnalysisManager &AM) { 1913 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 1914 auto &AC = AM.getResult<AssumptionAnalysis>(F); 1915 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); 1916 auto *PV = AM.getCachedResult<PhiValuesAnalysis>(F); 1917 return BasicAAResult(F.getParent()->getDataLayout(), F, TLI, AC, DT, PV); 1918 } 1919 1920 BasicAAWrapperPass::BasicAAWrapperPass() : FunctionPass(ID) { 1921 initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry()); 1922 } 1923 1924 char BasicAAWrapperPass::ID = 0; 1925 1926 void BasicAAWrapperPass::anchor() {} 1927 1928 INITIALIZE_PASS_BEGIN(BasicAAWrapperPass, "basic-aa", 1929 "Basic Alias Analysis (stateless AA impl)", true, true) 1930 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1931 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1932 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1933 INITIALIZE_PASS_DEPENDENCY(PhiValuesWrapperPass) 1934 INITIALIZE_PASS_END(BasicAAWrapperPass, "basic-aa", 1935 "Basic Alias Analysis (stateless AA impl)", true, true) 1936 1937 FunctionPass *llvm::createBasicAAWrapperPass() { 1938 return new BasicAAWrapperPass(); 1939 } 1940 1941 bool BasicAAWrapperPass::runOnFunction(Function &F) { 1942 auto &ACT = getAnalysis<AssumptionCacheTracker>(); 1943 auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>(); 1944 auto &DTWP = getAnalysis<DominatorTreeWrapperPass>(); 1945 auto *PVWP = getAnalysisIfAvailable<PhiValuesWrapperPass>(); 1946 1947 Result.reset(new BasicAAResult(F.getParent()->getDataLayout(), F, 1948 TLIWP.getTLI(F), ACT.getAssumptionCache(F), 1949 &DTWP.getDomTree(), 1950 PVWP ? &PVWP->getResult() : nullptr)); 1951 1952 return false; 1953 } 1954 1955 void BasicAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 1956 AU.setPreservesAll(); 1957 AU.addRequiredTransitive<AssumptionCacheTracker>(); 1958 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 1959 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 1960 AU.addUsedIfAvailable<PhiValuesWrapperPass>(); 1961 } 1962 1963 BasicAAResult llvm::createLegacyPMBasicAAResult(Pass &P, Function &F) { 1964 return BasicAAResult( 1965 F.getParent()->getDataLayout(), F, 1966 P.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 1967 P.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F)); 1968 } 1969