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. 208 bool CanBeNull, CanBeFreed; 209 uint64_t DerefBytes = 210 V.getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed); 211 DerefBytes = (CanBeNull && NullIsValidLoc) ? 0 : DerefBytes; 212 DerefBytes = CanBeFreed ? 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) && 973 OperandNo < Call->getNumArgOperands() && 974 !Call->isByValArgument(OperandNo))) 975 continue; 976 977 // Call doesn't access memory through this operand, so we don't care 978 // if it aliases with Object. 979 if (Call->doesNotAccessMemory(OperandNo)) 980 continue; 981 982 // If this is a no-capture pointer argument, see if we can tell that it 983 // is impossible to alias the pointer we're checking. 984 AliasResult AR = getBestAAResults().alias( 985 MemoryLocation::getBeforeOrAfter(*CI), 986 MemoryLocation::getBeforeOrAfter(Object), AAQI); 987 if (AR != AliasResult::MustAlias) 988 IsMustAlias = false; 989 // Operand doesn't alias 'Object', continue looking for other aliases 990 if (AR == AliasResult::NoAlias) 991 continue; 992 // Operand aliases 'Object', but call doesn't modify it. Strengthen 993 // initial assumption and keep looking in case if there are more aliases. 994 if (Call->onlyReadsMemory(OperandNo)) { 995 Result = setRef(Result); 996 continue; 997 } 998 // Operand aliases 'Object' but call only writes into it. 999 if (Call->doesNotReadMemory(OperandNo)) { 1000 Result = setMod(Result); 1001 continue; 1002 } 1003 // This operand aliases 'Object' and call reads and writes into it. 1004 // Setting ModRef will not yield an early return below, MustAlias is not 1005 // used further. 1006 Result = ModRefInfo::ModRef; 1007 break; 1008 } 1009 1010 // No operand aliases, reset Must bit. Add below if at least one aliases 1011 // and all aliases found are MustAlias. 1012 if (isNoModRef(Result)) 1013 IsMustAlias = false; 1014 1015 // Early return if we improved mod ref information 1016 if (!isModAndRefSet(Result)) { 1017 if (isNoModRef(Result)) 1018 return ModRefInfo::NoModRef; 1019 return IsMustAlias ? setMust(Result) : clearMust(Result); 1020 } 1021 } 1022 1023 // If the call is malloc/calloc like, we can assume that it doesn't 1024 // modify any IR visible value. This is only valid because we assume these 1025 // routines do not read values visible in the IR. TODO: Consider special 1026 // casing realloc and strdup routines which access only their arguments as 1027 // well. Or alternatively, replace all of this with inaccessiblememonly once 1028 // that's implemented fully. 1029 if (isMallocOrCallocLikeFn(Call, &TLI)) { 1030 // Be conservative if the accessed pointer may alias the allocation - 1031 // fallback to the generic handling below. 1032 if (getBestAAResults().alias(MemoryLocation::getBeforeOrAfter(Call), Loc, 1033 AAQI) == AliasResult::NoAlias) 1034 return ModRefInfo::NoModRef; 1035 } 1036 1037 // The semantics of memcpy intrinsics either exactly overlap or do not 1038 // overlap, i.e., source and destination of any given memcpy are either 1039 // no-alias or must-alias. 1040 if (auto *Inst = dyn_cast<AnyMemCpyInst>(Call)) { 1041 AliasResult SrcAA = 1042 getBestAAResults().alias(MemoryLocation::getForSource(Inst), Loc, AAQI); 1043 AliasResult DestAA = 1044 getBestAAResults().alias(MemoryLocation::getForDest(Inst), Loc, AAQI); 1045 // It's also possible for Loc to alias both src and dest, or neither. 1046 ModRefInfo rv = ModRefInfo::NoModRef; 1047 if (SrcAA != AliasResult::NoAlias) 1048 rv = setRef(rv); 1049 if (DestAA != AliasResult::NoAlias) 1050 rv = setMod(rv); 1051 return rv; 1052 } 1053 1054 // Guard intrinsics are marked as arbitrarily writing so that proper control 1055 // dependencies are maintained but they never mods any particular memory 1056 // location. 1057 // 1058 // *Unlike* assumes, guard intrinsics are modeled as reading memory since the 1059 // heap state at the point the guard is issued needs to be consistent in case 1060 // the guard invokes the "deopt" continuation. 1061 if (isIntrinsicCall(Call, Intrinsic::experimental_guard)) 1062 return ModRefInfo::Ref; 1063 // The same applies to deoptimize which is essentially a guard(false). 1064 if (isIntrinsicCall(Call, Intrinsic::experimental_deoptimize)) 1065 return ModRefInfo::Ref; 1066 1067 // Like assumes, invariant.start intrinsics were also marked as arbitrarily 1068 // writing so that proper control dependencies are maintained but they never 1069 // mod any particular memory location visible to the IR. 1070 // *Unlike* assumes (which are now modeled as NoModRef), invariant.start 1071 // intrinsic is now modeled as reading memory. This prevents hoisting the 1072 // invariant.start intrinsic over stores. Consider: 1073 // *ptr = 40; 1074 // *ptr = 50; 1075 // invariant_start(ptr) 1076 // int val = *ptr; 1077 // print(val); 1078 // 1079 // This cannot be transformed to: 1080 // 1081 // *ptr = 40; 1082 // invariant_start(ptr) 1083 // *ptr = 50; 1084 // int val = *ptr; 1085 // print(val); 1086 // 1087 // The transformation will cause the second store to be ignored (based on 1088 // rules of invariant.start) and print 40, while the first program always 1089 // prints 50. 1090 if (isIntrinsicCall(Call, Intrinsic::invariant_start)) 1091 return ModRefInfo::Ref; 1092 1093 // The AAResultBase base class has some smarts, lets use them. 1094 return AAResultBase::getModRefInfo(Call, Loc, AAQI); 1095 } 1096 1097 ModRefInfo BasicAAResult::getModRefInfo(const CallBase *Call1, 1098 const CallBase *Call2, 1099 AAQueryInfo &AAQI) { 1100 // Guard intrinsics are marked as arbitrarily writing so that proper control 1101 // dependencies are maintained but they never mods any particular memory 1102 // location. 1103 // 1104 // *Unlike* assumes, guard intrinsics are modeled as reading memory since the 1105 // heap state at the point the guard is issued needs to be consistent in case 1106 // the guard invokes the "deopt" continuation. 1107 1108 // NB! This function is *not* commutative, so we special case two 1109 // possibilities for guard intrinsics. 1110 1111 if (isIntrinsicCall(Call1, Intrinsic::experimental_guard)) 1112 return isModSet(createModRefInfo(getModRefBehavior(Call2))) 1113 ? ModRefInfo::Ref 1114 : ModRefInfo::NoModRef; 1115 1116 if (isIntrinsicCall(Call2, Intrinsic::experimental_guard)) 1117 return isModSet(createModRefInfo(getModRefBehavior(Call1))) 1118 ? ModRefInfo::Mod 1119 : ModRefInfo::NoModRef; 1120 1121 // The AAResultBase base class has some smarts, lets use them. 1122 return AAResultBase::getModRefInfo(Call1, Call2, AAQI); 1123 } 1124 1125 /// Return true if we know V to the base address of the corresponding memory 1126 /// object. This implies that any address less than V must be out of bounds 1127 /// for the underlying object. Note that just being isIdentifiedObject() is 1128 /// not enough - For example, a negative offset from a noalias argument or call 1129 /// can be inbounds w.r.t the actual underlying object. 1130 static bool isBaseOfObject(const Value *V) { 1131 // TODO: We can handle other cases here 1132 // 1) For GC languages, arguments to functions are often required to be 1133 // base pointers. 1134 // 2) Result of allocation routines are often base pointers. Leverage TLI. 1135 return (isa<AllocaInst>(V) || isa<GlobalVariable>(V)); 1136 } 1137 1138 /// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against 1139 /// another pointer. 1140 /// 1141 /// We know that V1 is a GEP, but we don't know anything about V2. 1142 /// UnderlyingV1 is getUnderlyingObject(GEP1), UnderlyingV2 is the same for 1143 /// V2. 1144 AliasResult BasicAAResult::aliasGEP( 1145 const GEPOperator *GEP1, LocationSize V1Size, 1146 const Value *V2, LocationSize V2Size, 1147 const Value *UnderlyingV1, const Value *UnderlyingV2, AAQueryInfo &AAQI) { 1148 if (!V1Size.hasValue() && !V2Size.hasValue()) { 1149 // TODO: This limitation exists for compile-time reasons. Relax it if we 1150 // can avoid exponential pathological cases. 1151 if (!isa<GEPOperator>(V2)) 1152 return AliasResult::MayAlias; 1153 1154 // If both accesses have unknown size, we can only check whether the base 1155 // objects don't alias. 1156 AliasResult BaseAlias = getBestAAResults().alias( 1157 MemoryLocation::getBeforeOrAfter(UnderlyingV1), 1158 MemoryLocation::getBeforeOrAfter(UnderlyingV2), AAQI); 1159 return BaseAlias == AliasResult::NoAlias ? AliasResult::NoAlias 1160 : AliasResult::MayAlias; 1161 } 1162 1163 DecomposedGEP DecompGEP1 = DecomposeGEPExpression(GEP1, DL, &AC, DT); 1164 DecomposedGEP DecompGEP2 = DecomposeGEPExpression(V2, DL, &AC, DT); 1165 1166 // Don't attempt to analyze the decomposed GEP if index scale is not a 1167 // compile-time constant. 1168 if (!DecompGEP1.HasCompileTimeConstantScale || 1169 !DecompGEP2.HasCompileTimeConstantScale) 1170 return AliasResult::MayAlias; 1171 1172 assert(DecompGEP1.Base == UnderlyingV1 && DecompGEP2.Base == UnderlyingV2 && 1173 "DecomposeGEPExpression returned a result different from " 1174 "getUnderlyingObject"); 1175 1176 // Subtract the GEP2 pointer from the GEP1 pointer to find out their 1177 // symbolic difference. 1178 subtractDecomposedGEPs(DecompGEP1, DecompGEP2); 1179 1180 // If an inbounds GEP would have to start from an out of bounds address 1181 // for the two to alias, then we can assume noalias. 1182 if (*DecompGEP1.InBounds && DecompGEP1.VarIndices.empty() && 1183 V2Size.hasValue() && DecompGEP1.Offset.sge(V2Size.getValue()) && 1184 isBaseOfObject(DecompGEP2.Base)) 1185 return AliasResult::NoAlias; 1186 1187 if (isa<GEPOperator>(V2)) { 1188 // Symmetric case to above. 1189 if (*DecompGEP2.InBounds && DecompGEP1.VarIndices.empty() && 1190 V1Size.hasValue() && DecompGEP1.Offset.sle(-V1Size.getValue()) && 1191 isBaseOfObject(DecompGEP1.Base)) 1192 return AliasResult::NoAlias; 1193 } 1194 1195 // For GEPs with identical offsets, we can preserve the size and AAInfo 1196 // when performing the alias check on the underlying objects. 1197 if (DecompGEP1.Offset == 0 && DecompGEP1.VarIndices.empty()) 1198 return getBestAAResults().alias( 1199 MemoryLocation(UnderlyingV1, V1Size), 1200 MemoryLocation(UnderlyingV2, V2Size), AAQI); 1201 1202 // Do the base pointers alias? 1203 AliasResult BaseAlias = getBestAAResults().alias( 1204 MemoryLocation::getBeforeOrAfter(UnderlyingV1), 1205 MemoryLocation::getBeforeOrAfter(UnderlyingV2), AAQI); 1206 1207 // If we get a No or May, then return it immediately, no amount of analysis 1208 // will improve this situation. 1209 if (BaseAlias != AliasResult::MustAlias) { 1210 assert(BaseAlias == AliasResult::NoAlias || 1211 BaseAlias == AliasResult::MayAlias); 1212 return BaseAlias; 1213 } 1214 1215 // If there is a constant difference between the pointers, but the difference 1216 // is less than the size of the associated memory object, then we know 1217 // that the objects are partially overlapping. If the difference is 1218 // greater, we know they do not overlap. 1219 if (DecompGEP1.Offset != 0 && DecompGEP1.VarIndices.empty()) { 1220 APInt &Off = DecompGEP1.Offset; 1221 1222 // Initialize for Off >= 0 (V2 <= GEP1) case. 1223 const Value *LeftPtr = V2; 1224 const Value *RightPtr = GEP1; 1225 LocationSize VLeftSize = V2Size; 1226 LocationSize VRightSize = V1Size; 1227 const bool Swapped = Off.isNegative(); 1228 1229 if (Swapped) { 1230 // Swap if we have the situation where: 1231 // + + 1232 // | BaseOffset | 1233 // ---------------->| 1234 // |-->V1Size |-------> V2Size 1235 // GEP1 V2 1236 std::swap(LeftPtr, RightPtr); 1237 std::swap(VLeftSize, VRightSize); 1238 Off = -Off; 1239 } 1240 1241 if (VLeftSize.hasValue()) { 1242 const uint64_t LSize = VLeftSize.getValue(); 1243 if (Off.ult(LSize)) { 1244 // Conservatively drop processing if a phi was visited and/or offset is 1245 // too big. 1246 AliasResult AR = AliasResult::PartialAlias; 1247 if (VRightSize.hasValue() && Off.ule(INT32_MAX) && 1248 (Off + VRightSize.getValue()).ule(LSize)) { 1249 // Memory referenced by right pointer is nested. Save the offset in 1250 // cache. Note that originally offset estimated as GEP1-V2, but 1251 // AliasResult contains the shift that represents GEP1+Offset=V2. 1252 AR.setOffset(-Off.getSExtValue()); 1253 AR.swap(Swapped); 1254 } 1255 return AR; 1256 } 1257 return AliasResult::NoAlias; 1258 } 1259 } 1260 1261 if (!DecompGEP1.VarIndices.empty()) { 1262 APInt GCD; 1263 bool AllNonNegative = DecompGEP1.Offset.isNonNegative(); 1264 bool AllNonPositive = DecompGEP1.Offset.isNonPositive(); 1265 for (unsigned i = 0, e = DecompGEP1.VarIndices.size(); i != e; ++i) { 1266 const VariableGEPIndex &Index = DecompGEP1.VarIndices[i]; 1267 const APInt &Scale = Index.Scale; 1268 APInt ScaleForGCD = Scale; 1269 if (!Index.IsNSW) 1270 ScaleForGCD = APInt::getOneBitSet(Scale.getBitWidth(), 1271 Scale.countTrailingZeros()); 1272 1273 if (i == 0) 1274 GCD = ScaleForGCD.abs(); 1275 else 1276 GCD = APIntOps::GreatestCommonDivisor(GCD, ScaleForGCD.abs()); 1277 1278 if (AllNonNegative || AllNonPositive) { 1279 KnownBits Known = Index.Val.evaluateWith( 1280 computeKnownBits(Index.Val.V, DL, 0, &AC, Index.CxtI, DT)); 1281 // TODO: Account for implicit trunc. 1282 bool SignKnownZero = Known.isNonNegative(); 1283 bool SignKnownOne = Known.isNegative(); 1284 AllNonNegative &= (SignKnownZero && Scale.isNonNegative()) || 1285 (SignKnownOne && Scale.isNonPositive()); 1286 AllNonPositive &= (SignKnownZero && Scale.isNonPositive()) || 1287 (SignKnownOne && Scale.isNonNegative()); 1288 } 1289 } 1290 1291 // We now have accesses at two offsets from the same base: 1292 // 1. (...)*GCD + DecompGEP1.Offset with size V1Size 1293 // 2. 0 with size V2Size 1294 // Using arithmetic modulo GCD, the accesses are at 1295 // [ModOffset..ModOffset+V1Size) and [0..V2Size). If the first access fits 1296 // into the range [V2Size..GCD), then we know they cannot overlap. 1297 APInt ModOffset = DecompGEP1.Offset.srem(GCD); 1298 if (ModOffset.isNegative()) 1299 ModOffset += GCD; // We want mod, not rem. 1300 if (V1Size.hasValue() && V2Size.hasValue() && 1301 ModOffset.uge(V2Size.getValue()) && 1302 (GCD - ModOffset).uge(V1Size.getValue())) 1303 return AliasResult::NoAlias; 1304 1305 // If we know all the variables are non-negative, then the total offset is 1306 // also non-negative and >= DecompGEP1.Offset. We have the following layout: 1307 // [0, V2Size) ... [TotalOffset, TotalOffer+V1Size] 1308 // If DecompGEP1.Offset >= V2Size, the accesses don't alias. 1309 if (AllNonNegative && V2Size.hasValue() && 1310 DecompGEP1.Offset.uge(V2Size.getValue())) 1311 return AliasResult::NoAlias; 1312 // Similarly, if the variables are non-positive, then the total offset is 1313 // also non-positive and <= DecompGEP1.Offset. We have the following layout: 1314 // [TotalOffset, TotalOffset+V1Size) ... [0, V2Size) 1315 // If -DecompGEP1.Offset >= V1Size, the accesses don't alias. 1316 if (AllNonPositive && V1Size.hasValue() && 1317 (-DecompGEP1.Offset).uge(V1Size.getValue())) 1318 return AliasResult::NoAlias; 1319 1320 if (V1Size.hasValue() && V2Size.hasValue()) { 1321 // Try to determine the range of values for VarIndex. 1322 // VarIndexRange is such that: 1323 // (VarIndex <= -MinAbsVarIndex || MinAbsVarIndex <= VarIndex) && 1324 // VarIndexRange.contains(VarIndex) 1325 Optional<APInt> MinAbsVarIndex; 1326 Optional<ConstantRange> VarIndexRange; 1327 if (DecompGEP1.VarIndices.size() == 1) { 1328 // VarIndex = Scale*V. 1329 const VariableGEPIndex &Var = DecompGEP1.VarIndices[0]; 1330 if (isKnownNonZero(Var.Val.V, DL, 0, &AC, Var.CxtI, DT)) { 1331 // If V != 0 then abs(VarIndex) >= abs(Scale). 1332 MinAbsVarIndex = Var.Scale.abs(); 1333 } 1334 ConstantRange R = Var.Val.evaluateWith( 1335 computeConstantRange(Var.Val.V, true, &AC, Var.CxtI)); 1336 if (!R.isFullSet() && !R.isEmptySet()) 1337 VarIndexRange = R.sextOrTrunc(Var.Scale.getBitWidth()) 1338 .multiply(ConstantRange(Var.Scale)); 1339 } else if (DecompGEP1.VarIndices.size() == 2) { 1340 // VarIndex = Scale*V0 + (-Scale)*V1. 1341 // If V0 != V1 then abs(VarIndex) >= abs(Scale). 1342 // Check that VisitedPhiBBs is empty, to avoid reasoning about 1343 // inequality of values across loop iterations. 1344 const VariableGEPIndex &Var0 = DecompGEP1.VarIndices[0]; 1345 const VariableGEPIndex &Var1 = DecompGEP1.VarIndices[1]; 1346 if (Var0.Scale == -Var1.Scale && 1347 Var0.Val.hasSameExtensionsAs(Var1.Val) && VisitedPhiBBs.empty() && 1348 isKnownNonEqual(Var0.Val.V, Var1.Val.V, DL, &AC, /* CxtI */ nullptr, 1349 DT)) 1350 MinAbsVarIndex = Var0.Scale.abs(); 1351 } 1352 1353 if (MinAbsVarIndex) { 1354 // The constant offset will have added at least +/-MinAbsVarIndex to it. 1355 APInt OffsetLo = DecompGEP1.Offset - *MinAbsVarIndex; 1356 APInt OffsetHi = DecompGEP1.Offset + *MinAbsVarIndex; 1357 // We know that Offset <= OffsetLo || Offset >= OffsetHi 1358 if (OffsetLo.isNegative() && (-OffsetLo).uge(V1Size.getValue()) && 1359 OffsetHi.isNonNegative() && OffsetHi.uge(V2Size.getValue())) 1360 return AliasResult::NoAlias; 1361 } 1362 1363 if (VarIndexRange) { 1364 ConstantRange OffsetRange = 1365 VarIndexRange->add(ConstantRange(DecompGEP1.Offset)); 1366 1367 // We know that Offset >= MinOffset. 1368 // (MinOffset >= V2Size) => (Offset >= V2Size) => NoAlias. 1369 if (OffsetRange.getSignedMin().sge(V2Size.getValue())) 1370 return AliasResult::NoAlias; 1371 1372 // We know that Offset <= MaxOffset. 1373 // (MaxOffset <= -V1Size) => (Offset <= -V1Size) => NoAlias. 1374 if (OffsetRange.getSignedMax().sle(-V1Size.getValue())) 1375 return AliasResult::NoAlias; 1376 } 1377 } 1378 1379 if (constantOffsetHeuristic(DecompGEP1, V1Size, V2Size, &AC, DT)) 1380 return AliasResult::NoAlias; 1381 } 1382 1383 // Statically, we can see that the base objects are the same, but the 1384 // pointers have dynamic offsets which we can't resolve. And none of our 1385 // little tricks above worked. 1386 return AliasResult::MayAlias; 1387 } 1388 1389 static AliasResult MergeAliasResults(AliasResult A, AliasResult B) { 1390 // If the results agree, take it. 1391 if (A == B) 1392 return A; 1393 // A mix of PartialAlias and MustAlias is PartialAlias. 1394 if ((A == AliasResult::PartialAlias && B == AliasResult::MustAlias) || 1395 (B == AliasResult::PartialAlias && A == AliasResult::MustAlias)) 1396 return AliasResult::PartialAlias; 1397 // Otherwise, we don't know anything. 1398 return AliasResult::MayAlias; 1399 } 1400 1401 /// Provides a bunch of ad-hoc rules to disambiguate a Select instruction 1402 /// against another. 1403 AliasResult 1404 BasicAAResult::aliasSelect(const SelectInst *SI, LocationSize SISize, 1405 const Value *V2, LocationSize V2Size, 1406 AAQueryInfo &AAQI) { 1407 // If the values are Selects with the same condition, we can do a more precise 1408 // check: just check for aliases between the values on corresponding arms. 1409 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) 1410 if (SI->getCondition() == SI2->getCondition()) { 1411 AliasResult Alias = getBestAAResults().alias( 1412 MemoryLocation(SI->getTrueValue(), SISize), 1413 MemoryLocation(SI2->getTrueValue(), V2Size), AAQI); 1414 if (Alias == AliasResult::MayAlias) 1415 return AliasResult::MayAlias; 1416 AliasResult ThisAlias = getBestAAResults().alias( 1417 MemoryLocation(SI->getFalseValue(), SISize), 1418 MemoryLocation(SI2->getFalseValue(), V2Size), AAQI); 1419 return MergeAliasResults(ThisAlias, Alias); 1420 } 1421 1422 // If both arms of the Select node NoAlias or MustAlias V2, then returns 1423 // NoAlias / MustAlias. Otherwise, returns MayAlias. 1424 AliasResult Alias = getBestAAResults().alias( 1425 MemoryLocation(V2, V2Size), 1426 MemoryLocation(SI->getTrueValue(), SISize), AAQI); 1427 if (Alias == AliasResult::MayAlias) 1428 return AliasResult::MayAlias; 1429 1430 AliasResult ThisAlias = getBestAAResults().alias( 1431 MemoryLocation(V2, V2Size), 1432 MemoryLocation(SI->getFalseValue(), SISize), AAQI); 1433 return MergeAliasResults(ThisAlias, Alias); 1434 } 1435 1436 /// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against 1437 /// another. 1438 AliasResult BasicAAResult::aliasPHI(const PHINode *PN, LocationSize PNSize, 1439 const Value *V2, LocationSize V2Size, 1440 AAQueryInfo &AAQI) { 1441 if (!PN->getNumIncomingValues()) 1442 return AliasResult::NoAlias; 1443 // If the values are PHIs in the same block, we can do a more precise 1444 // as well as efficient check: just check for aliases between the values 1445 // on corresponding edges. 1446 if (const PHINode *PN2 = dyn_cast<PHINode>(V2)) 1447 if (PN2->getParent() == PN->getParent()) { 1448 Optional<AliasResult> Alias; 1449 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1450 AliasResult ThisAlias = getBestAAResults().alias( 1451 MemoryLocation(PN->getIncomingValue(i), PNSize), 1452 MemoryLocation( 1453 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)), V2Size), 1454 AAQI); 1455 if (Alias) 1456 *Alias = MergeAliasResults(*Alias, ThisAlias); 1457 else 1458 Alias = ThisAlias; 1459 if (*Alias == AliasResult::MayAlias) 1460 break; 1461 } 1462 return *Alias; 1463 } 1464 1465 SmallVector<Value *, 4> V1Srcs; 1466 // If a phi operand recurses back to the phi, we can still determine NoAlias 1467 // if we don't alias the underlying objects of the other phi operands, as we 1468 // know that the recursive phi needs to be based on them in some way. 1469 bool isRecursive = false; 1470 auto CheckForRecPhi = [&](Value *PV) { 1471 if (!EnableRecPhiAnalysis) 1472 return false; 1473 if (getUnderlyingObject(PV) == PN) { 1474 isRecursive = true; 1475 return true; 1476 } 1477 return false; 1478 }; 1479 1480 if (PV) { 1481 // If we have PhiValues then use it to get the underlying phi values. 1482 const PhiValues::ValueSet &PhiValueSet = PV->getValuesForPhi(PN); 1483 // If we have more phi values than the search depth then return MayAlias 1484 // conservatively to avoid compile time explosion. The worst possible case 1485 // is if both sides are PHI nodes. In which case, this is O(m x n) time 1486 // where 'm' and 'n' are the number of PHI sources. 1487 if (PhiValueSet.size() > MaxLookupSearchDepth) 1488 return AliasResult::MayAlias; 1489 // Add the values to V1Srcs 1490 for (Value *PV1 : PhiValueSet) { 1491 if (CheckForRecPhi(PV1)) 1492 continue; 1493 V1Srcs.push_back(PV1); 1494 } 1495 } else { 1496 // If we don't have PhiInfo then just look at the operands of the phi itself 1497 // FIXME: Remove this once we can guarantee that we have PhiInfo always 1498 SmallPtrSet<Value *, 4> UniqueSrc; 1499 Value *OnePhi = nullptr; 1500 for (Value *PV1 : PN->incoming_values()) { 1501 if (isa<PHINode>(PV1)) { 1502 if (OnePhi && OnePhi != PV1) { 1503 // To control potential compile time explosion, we choose to be 1504 // conserviate when we have more than one Phi input. It is important 1505 // that we handle the single phi case as that lets us handle LCSSA 1506 // phi nodes and (combined with the recursive phi handling) simple 1507 // pointer induction variable patterns. 1508 return AliasResult::MayAlias; 1509 } 1510 OnePhi = PV1; 1511 } 1512 1513 if (CheckForRecPhi(PV1)) 1514 continue; 1515 1516 if (UniqueSrc.insert(PV1).second) 1517 V1Srcs.push_back(PV1); 1518 } 1519 1520 if (OnePhi && UniqueSrc.size() > 1) 1521 // Out of an abundance of caution, allow only the trivial lcssa and 1522 // recursive phi cases. 1523 return AliasResult::MayAlias; 1524 } 1525 1526 // If V1Srcs is empty then that means that the phi has no underlying non-phi 1527 // value. This should only be possible in blocks unreachable from the entry 1528 // block, but return MayAlias just in case. 1529 if (V1Srcs.empty()) 1530 return AliasResult::MayAlias; 1531 1532 // If this PHI node is recursive, indicate that the pointer may be moved 1533 // across iterations. We can only prove NoAlias if different underlying 1534 // objects are involved. 1535 if (isRecursive) 1536 PNSize = LocationSize::beforeOrAfterPointer(); 1537 1538 // In the recursive alias queries below, we may compare values from two 1539 // different loop iterations. Keep track of visited phi blocks, which will 1540 // be used when determining value equivalence. 1541 bool BlockInserted = VisitedPhiBBs.insert(PN->getParent()).second; 1542 auto _ = make_scope_exit([&]() { 1543 if (BlockInserted) 1544 VisitedPhiBBs.erase(PN->getParent()); 1545 }); 1546 1547 // If we inserted a block into VisitedPhiBBs, alias analysis results that 1548 // have been cached earlier may no longer be valid. Perform recursive queries 1549 // with a new AAQueryInfo. 1550 AAQueryInfo NewAAQI = AAQI.withEmptyCache(); 1551 AAQueryInfo *UseAAQI = BlockInserted ? &NewAAQI : &AAQI; 1552 1553 AliasResult Alias = getBestAAResults().alias( 1554 MemoryLocation(V2, V2Size), 1555 MemoryLocation(V1Srcs[0], PNSize), *UseAAQI); 1556 1557 // Early exit if the check of the first PHI source against V2 is MayAlias. 1558 // Other results are not possible. 1559 if (Alias == AliasResult::MayAlias) 1560 return AliasResult::MayAlias; 1561 // With recursive phis we cannot guarantee that MustAlias/PartialAlias will 1562 // remain valid to all elements and needs to conservatively return MayAlias. 1563 if (isRecursive && Alias != AliasResult::NoAlias) 1564 return AliasResult::MayAlias; 1565 1566 // If all sources of the PHI node NoAlias or MustAlias V2, then returns 1567 // NoAlias / MustAlias. Otherwise, returns MayAlias. 1568 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) { 1569 Value *V = V1Srcs[i]; 1570 1571 AliasResult ThisAlias = getBestAAResults().alias( 1572 MemoryLocation(V2, V2Size), MemoryLocation(V, PNSize), *UseAAQI); 1573 Alias = MergeAliasResults(ThisAlias, Alias); 1574 if (Alias == AliasResult::MayAlias) 1575 break; 1576 } 1577 1578 return Alias; 1579 } 1580 1581 /// Provides a bunch of ad-hoc rules to disambiguate in common cases, such as 1582 /// array references. 1583 AliasResult BasicAAResult::aliasCheck(const Value *V1, LocationSize V1Size, 1584 const Value *V2, LocationSize V2Size, 1585 AAQueryInfo &AAQI) { 1586 // If either of the memory references is empty, it doesn't matter what the 1587 // pointer values are. 1588 if (V1Size.isZero() || V2Size.isZero()) 1589 return AliasResult::NoAlias; 1590 1591 // Strip off any casts if they exist. 1592 V1 = V1->stripPointerCastsForAliasAnalysis(); 1593 V2 = V2->stripPointerCastsForAliasAnalysis(); 1594 1595 // If V1 or V2 is undef, the result is NoAlias because we can always pick a 1596 // value for undef that aliases nothing in the program. 1597 if (isa<UndefValue>(V1) || isa<UndefValue>(V2)) 1598 return AliasResult::NoAlias; 1599 1600 // Are we checking for alias of the same value? 1601 // Because we look 'through' phi nodes, we could look at "Value" pointers from 1602 // different iterations. We must therefore make sure that this is not the 1603 // case. The function isValueEqualInPotentialCycles ensures that this cannot 1604 // happen by looking at the visited phi nodes and making sure they cannot 1605 // reach the value. 1606 if (isValueEqualInPotentialCycles(V1, V2)) 1607 return AliasResult::MustAlias; 1608 1609 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy()) 1610 return AliasResult::NoAlias; // Scalars cannot alias each other 1611 1612 // Figure out what objects these things are pointing to if we can. 1613 const Value *O1 = getUnderlyingObject(V1, MaxLookupSearchDepth); 1614 const Value *O2 = getUnderlyingObject(V2, MaxLookupSearchDepth); 1615 1616 // Null values in the default address space don't point to any object, so they 1617 // don't alias any other pointer. 1618 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1)) 1619 if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace())) 1620 return AliasResult::NoAlias; 1621 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2)) 1622 if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace())) 1623 return AliasResult::NoAlias; 1624 1625 if (O1 != O2) { 1626 // If V1/V2 point to two different objects, we know that we have no alias. 1627 if (isIdentifiedObject(O1) && isIdentifiedObject(O2)) 1628 return AliasResult::NoAlias; 1629 1630 // Constant pointers can't alias with non-const isIdentifiedObject objects. 1631 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) || 1632 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1))) 1633 return AliasResult::NoAlias; 1634 1635 // Function arguments can't alias with things that are known to be 1636 // unambigously identified at the function level. 1637 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) || 1638 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1))) 1639 return AliasResult::NoAlias; 1640 1641 // If one pointer is the result of a call/invoke or load and the other is a 1642 // non-escaping local object within the same function, then we know the 1643 // object couldn't escape to a point where the call could return it. 1644 // 1645 // Note that if the pointers are in different functions, there are a 1646 // variety of complications. A call with a nocapture argument may still 1647 // temporary store the nocapture argument's value in a temporary memory 1648 // location if that memory location doesn't escape. Or it may pass a 1649 // nocapture value to other functions as long as they don't capture it. 1650 if (isEscapeSource(O1) && 1651 AAQI.CI->isNotCapturedBeforeOrAt(O2, cast<Instruction>(O1))) 1652 return AliasResult::NoAlias; 1653 if (isEscapeSource(O2) && 1654 AAQI.CI->isNotCapturedBeforeOrAt(O1, cast<Instruction>(O2))) 1655 return AliasResult::NoAlias; 1656 } 1657 1658 // If the size of one access is larger than the entire object on the other 1659 // side, then we know such behavior is undefined and can assume no alias. 1660 bool NullIsValidLocation = NullPointerIsDefined(&F); 1661 if ((isObjectSmallerThan( 1662 O2, getMinimalExtentFrom(*V1, V1Size, DL, NullIsValidLocation), DL, 1663 TLI, NullIsValidLocation)) || 1664 (isObjectSmallerThan( 1665 O1, getMinimalExtentFrom(*V2, V2Size, DL, NullIsValidLocation), DL, 1666 TLI, NullIsValidLocation))) 1667 return AliasResult::NoAlias; 1668 1669 // If one the accesses may be before the accessed pointer, canonicalize this 1670 // by using unknown after-pointer sizes for both accesses. This is 1671 // equivalent, because regardless of which pointer is lower, one of them 1672 // will always came after the other, as long as the underlying objects aren't 1673 // disjoint. We do this so that the rest of BasicAA does not have to deal 1674 // with accesses before the base pointer, and to improve cache utilization by 1675 // merging equivalent states. 1676 if (V1Size.mayBeBeforePointer() || V2Size.mayBeBeforePointer()) { 1677 V1Size = LocationSize::afterPointer(); 1678 V2Size = LocationSize::afterPointer(); 1679 } 1680 1681 // FIXME: If this depth limit is hit, then we may cache sub-optimal results 1682 // for recursive queries. For this reason, this limit is chosen to be large 1683 // enough to be very rarely hit, while still being small enough to avoid 1684 // stack overflows. 1685 if (AAQI.Depth >= 512) 1686 return AliasResult::MayAlias; 1687 1688 // Check the cache before climbing up use-def chains. This also terminates 1689 // otherwise infinitely recursive queries. 1690 AAQueryInfo::LocPair Locs({V1, V1Size}, {V2, V2Size}); 1691 const bool Swapped = V1 > V2; 1692 if (Swapped) 1693 std::swap(Locs.first, Locs.second); 1694 const auto &Pair = AAQI.AliasCache.try_emplace( 1695 Locs, AAQueryInfo::CacheEntry{AliasResult::NoAlias, 0}); 1696 if (!Pair.second) { 1697 auto &Entry = Pair.first->second; 1698 if (!Entry.isDefinitive()) { 1699 // Remember that we used an assumption. 1700 ++Entry.NumAssumptionUses; 1701 ++AAQI.NumAssumptionUses; 1702 } 1703 // Cache contains sorted {V1,V2} pairs but we should return original order. 1704 auto Result = Entry.Result; 1705 Result.swap(Swapped); 1706 return Result; 1707 } 1708 1709 int OrigNumAssumptionUses = AAQI.NumAssumptionUses; 1710 unsigned OrigNumAssumptionBasedResults = AAQI.AssumptionBasedResults.size(); 1711 AliasResult Result = 1712 aliasCheckRecursive(V1, V1Size, V2, V2Size, AAQI, O1, O2); 1713 1714 auto It = AAQI.AliasCache.find(Locs); 1715 assert(It != AAQI.AliasCache.end() && "Must be in cache"); 1716 auto &Entry = It->second; 1717 1718 // Check whether a NoAlias assumption has been used, but disproven. 1719 bool AssumptionDisproven = 1720 Entry.NumAssumptionUses > 0 && Result != AliasResult::NoAlias; 1721 if (AssumptionDisproven) 1722 Result = AliasResult::MayAlias; 1723 1724 // This is a definitive result now, when considered as a root query. 1725 AAQI.NumAssumptionUses -= Entry.NumAssumptionUses; 1726 Entry.Result = Result; 1727 // Cache contains sorted {V1,V2} pairs. 1728 Entry.Result.swap(Swapped); 1729 Entry.NumAssumptionUses = -1; 1730 1731 // If the assumption has been disproven, remove any results that may have 1732 // been based on this assumption. Do this after the Entry updates above to 1733 // avoid iterator invalidation. 1734 if (AssumptionDisproven) 1735 while (AAQI.AssumptionBasedResults.size() > OrigNumAssumptionBasedResults) 1736 AAQI.AliasCache.erase(AAQI.AssumptionBasedResults.pop_back_val()); 1737 1738 // The result may still be based on assumptions higher up in the chain. 1739 // Remember it, so it can be purged from the cache later. 1740 if (OrigNumAssumptionUses != AAQI.NumAssumptionUses && 1741 Result != AliasResult::MayAlias) 1742 AAQI.AssumptionBasedResults.push_back(Locs); 1743 return Result; 1744 } 1745 1746 AliasResult BasicAAResult::aliasCheckRecursive( 1747 const Value *V1, LocationSize V1Size, 1748 const Value *V2, LocationSize V2Size, 1749 AAQueryInfo &AAQI, const Value *O1, const Value *O2) { 1750 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) { 1751 AliasResult Result = aliasGEP(GV1, V1Size, V2, V2Size, O1, O2, AAQI); 1752 if (Result != AliasResult::MayAlias) 1753 return Result; 1754 } else if (const GEPOperator *GV2 = dyn_cast<GEPOperator>(V2)) { 1755 AliasResult Result = aliasGEP(GV2, V2Size, V1, V1Size, O2, O1, AAQI); 1756 if (Result != AliasResult::MayAlias) 1757 return Result; 1758 } 1759 1760 if (const PHINode *PN = dyn_cast<PHINode>(V1)) { 1761 AliasResult Result = aliasPHI(PN, V1Size, V2, V2Size, AAQI); 1762 if (Result != AliasResult::MayAlias) 1763 return Result; 1764 } else if (const PHINode *PN = dyn_cast<PHINode>(V2)) { 1765 AliasResult Result = aliasPHI(PN, V2Size, V1, V1Size, AAQI); 1766 if (Result != AliasResult::MayAlias) 1767 return Result; 1768 } 1769 1770 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) { 1771 AliasResult Result = aliasSelect(S1, V1Size, V2, V2Size, AAQI); 1772 if (Result != AliasResult::MayAlias) 1773 return Result; 1774 } else if (const SelectInst *S2 = dyn_cast<SelectInst>(V2)) { 1775 AliasResult Result = aliasSelect(S2, V2Size, V1, V1Size, AAQI); 1776 if (Result != AliasResult::MayAlias) 1777 return Result; 1778 } 1779 1780 // If both pointers are pointing into the same object and one of them 1781 // accesses the entire object, then the accesses must overlap in some way. 1782 if (O1 == O2) { 1783 bool NullIsValidLocation = NullPointerIsDefined(&F); 1784 if (V1Size.isPrecise() && V2Size.isPrecise() && 1785 (isObjectSize(O1, V1Size.getValue(), DL, TLI, NullIsValidLocation) || 1786 isObjectSize(O2, V2Size.getValue(), DL, TLI, NullIsValidLocation))) 1787 return AliasResult::PartialAlias; 1788 } 1789 1790 return AliasResult::MayAlias; 1791 } 1792 1793 /// Check whether two Values can be considered equivalent. 1794 /// 1795 /// In addition to pointer equivalence of \p V1 and \p V2 this checks whether 1796 /// they can not be part of a cycle in the value graph by looking at all 1797 /// visited phi nodes an making sure that the phis cannot reach the value. We 1798 /// have to do this because we are looking through phi nodes (That is we say 1799 /// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB). 1800 bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V, 1801 const Value *V2) { 1802 if (V != V2) 1803 return false; 1804 1805 const Instruction *Inst = dyn_cast<Instruction>(V); 1806 if (!Inst) 1807 return true; 1808 1809 if (VisitedPhiBBs.empty()) 1810 return true; 1811 1812 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck) 1813 return false; 1814 1815 // Make sure that the visited phis cannot reach the Value. This ensures that 1816 // the Values cannot come from different iterations of a potential cycle the 1817 // phi nodes could be involved in. 1818 for (auto *P : VisitedPhiBBs) 1819 if (isPotentiallyReachable(&P->front(), Inst, nullptr, DT)) 1820 return false; 1821 1822 return true; 1823 } 1824 1825 /// Computes the symbolic difference between two de-composed GEPs. 1826 void BasicAAResult::subtractDecomposedGEPs(DecomposedGEP &DestGEP, 1827 const DecomposedGEP &SrcGEP) { 1828 DestGEP.Offset -= SrcGEP.Offset; 1829 for (const VariableGEPIndex &Src : SrcGEP.VarIndices) { 1830 // Find V in Dest. This is N^2, but pointer indices almost never have more 1831 // than a few variable indexes. 1832 bool Found = false; 1833 for (auto I : enumerate(DestGEP.VarIndices)) { 1834 VariableGEPIndex &Dest = I.value(); 1835 if (!isValueEqualInPotentialCycles(Dest.Val.V, Src.Val.V) || 1836 !Dest.Val.hasSameExtensionsAs(Src.Val)) 1837 continue; 1838 1839 // If we found it, subtract off Scale V's from the entry in Dest. If it 1840 // goes to zero, remove the entry. 1841 if (Dest.Scale != Src.Scale) { 1842 Dest.Scale -= Src.Scale; 1843 Dest.IsNSW = false; 1844 } else { 1845 DestGEP.VarIndices.erase(DestGEP.VarIndices.begin() + I.index()); 1846 } 1847 Found = true; 1848 break; 1849 } 1850 1851 // If we didn't consume this entry, add it to the end of the Dest list. 1852 if (!Found) { 1853 VariableGEPIndex Entry = {Src.Val, -Src.Scale, Src.CxtI, Src.IsNSW}; 1854 DestGEP.VarIndices.push_back(Entry); 1855 } 1856 } 1857 } 1858 1859 bool BasicAAResult::constantOffsetHeuristic( 1860 const DecomposedGEP &GEP, LocationSize MaybeV1Size, 1861 LocationSize MaybeV2Size, AssumptionCache *AC, DominatorTree *DT) { 1862 if (GEP.VarIndices.size() != 2 || !MaybeV1Size.hasValue() || 1863 !MaybeV2Size.hasValue()) 1864 return false; 1865 1866 const uint64_t V1Size = MaybeV1Size.getValue(); 1867 const uint64_t V2Size = MaybeV2Size.getValue(); 1868 1869 const VariableGEPIndex &Var0 = GEP.VarIndices[0], &Var1 = GEP.VarIndices[1]; 1870 1871 if (!Var0.Val.hasSameExtensionsAs(Var1.Val) || Var0.Scale != -Var1.Scale || 1872 Var0.Val.V->getType() != Var1.Val.V->getType()) 1873 return false; 1874 1875 // We'll strip off the Extensions of Var0 and Var1 and do another round 1876 // of GetLinearExpression decomposition. In the example above, if Var0 1877 // is zext(%x + 1) we should get V1 == %x and V1Offset == 1. 1878 1879 LinearExpression E0 = 1880 GetLinearExpression(ExtendedValue(Var0.Val.V), DL, 0, AC, DT); 1881 LinearExpression E1 = 1882 GetLinearExpression(ExtendedValue(Var1.Val.V), DL, 0, AC, DT); 1883 if (E0.Scale != E1.Scale || !E0.Val.hasSameExtensionsAs(E1.Val) || 1884 !isValueEqualInPotentialCycles(E0.Val.V, E1.Val.V)) 1885 return false; 1886 1887 // We have a hit - Var0 and Var1 only differ by a constant offset! 1888 1889 // If we've been sext'ed then zext'd the maximum difference between Var0 and 1890 // Var1 is possible to calculate, but we're just interested in the absolute 1891 // minimum difference between the two. The minimum distance may occur due to 1892 // wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so 1893 // the minimum distance between %i and %i + 5 is 3. 1894 APInt MinDiff = E0.Offset - E1.Offset, Wrapped = -MinDiff; 1895 MinDiff = APIntOps::umin(MinDiff, Wrapped); 1896 APInt MinDiffBytes = 1897 MinDiff.zextOrTrunc(Var0.Scale.getBitWidth()) * Var0.Scale.abs(); 1898 1899 // We can't definitely say whether GEP1 is before or after V2 due to wrapping 1900 // arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other 1901 // values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and 1902 // V2Size can fit in the MinDiffBytes gap. 1903 return MinDiffBytes.uge(V1Size + GEP.Offset.abs()) && 1904 MinDiffBytes.uge(V2Size + GEP.Offset.abs()); 1905 } 1906 1907 //===----------------------------------------------------------------------===// 1908 // BasicAliasAnalysis Pass 1909 //===----------------------------------------------------------------------===// 1910 1911 AnalysisKey BasicAA::Key; 1912 1913 BasicAAResult BasicAA::run(Function &F, FunctionAnalysisManager &AM) { 1914 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F); 1915 auto &AC = AM.getResult<AssumptionAnalysis>(F); 1916 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); 1917 auto *PV = AM.getCachedResult<PhiValuesAnalysis>(F); 1918 return BasicAAResult(F.getParent()->getDataLayout(), F, TLI, AC, DT, PV); 1919 } 1920 1921 BasicAAWrapperPass::BasicAAWrapperPass() : FunctionPass(ID) { 1922 initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry()); 1923 } 1924 1925 char BasicAAWrapperPass::ID = 0; 1926 1927 void BasicAAWrapperPass::anchor() {} 1928 1929 INITIALIZE_PASS_BEGIN(BasicAAWrapperPass, "basic-aa", 1930 "Basic Alias Analysis (stateless AA impl)", true, true) 1931 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1932 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 1933 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1934 INITIALIZE_PASS_DEPENDENCY(PhiValuesWrapperPass) 1935 INITIALIZE_PASS_END(BasicAAWrapperPass, "basic-aa", 1936 "Basic Alias Analysis (stateless AA impl)", true, true) 1937 1938 FunctionPass *llvm::createBasicAAWrapperPass() { 1939 return new BasicAAWrapperPass(); 1940 } 1941 1942 bool BasicAAWrapperPass::runOnFunction(Function &F) { 1943 auto &ACT = getAnalysis<AssumptionCacheTracker>(); 1944 auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>(); 1945 auto &DTWP = getAnalysis<DominatorTreeWrapperPass>(); 1946 auto *PVWP = getAnalysisIfAvailable<PhiValuesWrapperPass>(); 1947 1948 Result.reset(new BasicAAResult(F.getParent()->getDataLayout(), F, 1949 TLIWP.getTLI(F), ACT.getAssumptionCache(F), 1950 &DTWP.getDomTree(), 1951 PVWP ? &PVWP->getResult() : nullptr)); 1952 1953 return false; 1954 } 1955 1956 void BasicAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { 1957 AU.setPreservesAll(); 1958 AU.addRequiredTransitive<AssumptionCacheTracker>(); 1959 AU.addRequiredTransitive<DominatorTreeWrapperPass>(); 1960 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>(); 1961 AU.addUsedIfAvailable<PhiValuesWrapperPass>(); 1962 } 1963 1964 BasicAAResult llvm::createLegacyPMBasicAAResult(Pass &P, Function &F) { 1965 return BasicAAResult( 1966 F.getParent()->getDataLayout(), F, 1967 P.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F), 1968 P.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F)); 1969 } 1970