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