1 //===- AttributorAttributes.cpp - Attributes for Attributor deduction -----===// 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 // See the Attributor.h file comment and the class descriptions in that file for 10 // more information. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/IPO/Attributor.h" 15 16 #include "llvm/ADT/SCCIterator.h" 17 #include "llvm/ADT/SmallPtrSet.h" 18 #include "llvm/ADT/Statistic.h" 19 #include "llvm/Analysis/AliasAnalysis.h" 20 #include "llvm/Analysis/AssumeBundleQueries.h" 21 #include "llvm/Analysis/AssumptionCache.h" 22 #include "llvm/Analysis/CaptureTracking.h" 23 #include "llvm/Analysis/LazyValueInfo.h" 24 #include "llvm/Analysis/MemoryBuiltins.h" 25 #include "llvm/Analysis/ScalarEvolution.h" 26 #include "llvm/Analysis/TargetTransformInfo.h" 27 #include "llvm/Analysis/ValueTracking.h" 28 #include "llvm/IR/IRBuilder.h" 29 #include "llvm/IR/Instruction.h" 30 #include "llvm/IR/IntrinsicInst.h" 31 #include "llvm/IR/NoFolder.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/FileSystem.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/Transforms/IPO/ArgumentPromotion.h" 36 #include "llvm/Transforms/Utils/Local.h" 37 #include <cassert> 38 39 using namespace llvm; 40 41 #define DEBUG_TYPE "attributor" 42 43 static cl::opt<bool> ManifestInternal( 44 "attributor-manifest-internal", cl::Hidden, 45 cl::desc("Manifest Attributor internal string attributes."), 46 cl::init(false)); 47 48 static cl::opt<int> MaxHeapToStackSize("max-heap-to-stack-size", cl::init(128), 49 cl::Hidden); 50 51 template <> 52 unsigned llvm::PotentialConstantIntValuesState::MaxPotentialValues = 0; 53 54 static cl::opt<unsigned, true> MaxPotentialValues( 55 "attributor-max-potential-values", cl::Hidden, 56 cl::desc("Maximum number of potential values to be " 57 "tracked for each position."), 58 cl::location(llvm::PotentialConstantIntValuesState::MaxPotentialValues), 59 cl::init(7)); 60 61 STATISTIC(NumAAs, "Number of abstract attributes created"); 62 63 // Some helper macros to deal with statistics tracking. 64 // 65 // Usage: 66 // For simple IR attribute tracking overload trackStatistics in the abstract 67 // attribute and choose the right STATS_DECLTRACK_********* macro, 68 // e.g.,: 69 // void trackStatistics() const override { 70 // STATS_DECLTRACK_ARG_ATTR(returned) 71 // } 72 // If there is a single "increment" side one can use the macro 73 // STATS_DECLTRACK with a custom message. If there are multiple increment 74 // sides, STATS_DECL and STATS_TRACK can also be used separately. 75 // 76 #define BUILD_STAT_MSG_IR_ATTR(TYPE, NAME) \ 77 ("Number of " #TYPE " marked '" #NAME "'") 78 #define BUILD_STAT_NAME(NAME, TYPE) NumIR##TYPE##_##NAME 79 #define STATS_DECL_(NAME, MSG) STATISTIC(NAME, MSG); 80 #define STATS_DECL(NAME, TYPE, MSG) \ 81 STATS_DECL_(BUILD_STAT_NAME(NAME, TYPE), MSG); 82 #define STATS_TRACK(NAME, TYPE) ++(BUILD_STAT_NAME(NAME, TYPE)); 83 #define STATS_DECLTRACK(NAME, TYPE, MSG) \ 84 { \ 85 STATS_DECL(NAME, TYPE, MSG) \ 86 STATS_TRACK(NAME, TYPE) \ 87 } 88 #define STATS_DECLTRACK_ARG_ATTR(NAME) \ 89 STATS_DECLTRACK(NAME, Arguments, BUILD_STAT_MSG_IR_ATTR(arguments, NAME)) 90 #define STATS_DECLTRACK_CSARG_ATTR(NAME) \ 91 STATS_DECLTRACK(NAME, CSArguments, \ 92 BUILD_STAT_MSG_IR_ATTR(call site arguments, NAME)) 93 #define STATS_DECLTRACK_FN_ATTR(NAME) \ 94 STATS_DECLTRACK(NAME, Function, BUILD_STAT_MSG_IR_ATTR(functions, NAME)) 95 #define STATS_DECLTRACK_CS_ATTR(NAME) \ 96 STATS_DECLTRACK(NAME, CS, BUILD_STAT_MSG_IR_ATTR(call site, NAME)) 97 #define STATS_DECLTRACK_FNRET_ATTR(NAME) \ 98 STATS_DECLTRACK(NAME, FunctionReturn, \ 99 BUILD_STAT_MSG_IR_ATTR(function returns, NAME)) 100 #define STATS_DECLTRACK_CSRET_ATTR(NAME) \ 101 STATS_DECLTRACK(NAME, CSReturn, \ 102 BUILD_STAT_MSG_IR_ATTR(call site returns, NAME)) 103 #define STATS_DECLTRACK_FLOATING_ATTR(NAME) \ 104 STATS_DECLTRACK(NAME, Floating, \ 105 ("Number of floating values known to be '" #NAME "'")) 106 107 // Specialization of the operator<< for abstract attributes subclasses. This 108 // disambiguates situations where multiple operators are applicable. 109 namespace llvm { 110 #define PIPE_OPERATOR(CLASS) \ 111 raw_ostream &operator<<(raw_ostream &OS, const CLASS &AA) { \ 112 return OS << static_cast<const AbstractAttribute &>(AA); \ 113 } 114 115 PIPE_OPERATOR(AAIsDead) 116 PIPE_OPERATOR(AANoUnwind) 117 PIPE_OPERATOR(AANoSync) 118 PIPE_OPERATOR(AANoRecurse) 119 PIPE_OPERATOR(AAWillReturn) 120 PIPE_OPERATOR(AANoReturn) 121 PIPE_OPERATOR(AAReturnedValues) 122 PIPE_OPERATOR(AANonNull) 123 PIPE_OPERATOR(AANoAlias) 124 PIPE_OPERATOR(AADereferenceable) 125 PIPE_OPERATOR(AAAlign) 126 PIPE_OPERATOR(AANoCapture) 127 PIPE_OPERATOR(AAValueSimplify) 128 PIPE_OPERATOR(AANoFree) 129 PIPE_OPERATOR(AAHeapToStack) 130 PIPE_OPERATOR(AAReachability) 131 PIPE_OPERATOR(AAMemoryBehavior) 132 PIPE_OPERATOR(AAMemoryLocation) 133 PIPE_OPERATOR(AAValueConstantRange) 134 PIPE_OPERATOR(AAPrivatizablePtr) 135 PIPE_OPERATOR(AAUndefinedBehavior) 136 PIPE_OPERATOR(AAPotentialValues) 137 PIPE_OPERATOR(AANoUndef) 138 PIPE_OPERATOR(AACallEdges) 139 140 #undef PIPE_OPERATOR 141 } // namespace llvm 142 143 namespace { 144 145 /// Get pointer operand of memory accessing instruction. If \p I is 146 /// not a memory accessing instruction, return nullptr. If \p AllowVolatile, 147 /// is set to false and the instruction is volatile, return nullptr. 148 static const Value *getPointerOperand(const Instruction *I, 149 bool AllowVolatile) { 150 if (!AllowVolatile && I->isVolatile()) 151 return nullptr; 152 153 if (auto *LI = dyn_cast<LoadInst>(I)) { 154 return LI->getPointerOperand(); 155 } 156 157 if (auto *SI = dyn_cast<StoreInst>(I)) { 158 return SI->getPointerOperand(); 159 } 160 161 if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(I)) { 162 return CXI->getPointerOperand(); 163 } 164 165 if (auto *RMWI = dyn_cast<AtomicRMWInst>(I)) { 166 return RMWI->getPointerOperand(); 167 } 168 169 return nullptr; 170 } 171 172 /// Helper function to create a pointer of type \p ResTy, based on \p Ptr, and 173 /// advanced by \p Offset bytes. To aid later analysis the method tries to build 174 /// getelement pointer instructions that traverse the natural type of \p Ptr if 175 /// possible. If that fails, the remaining offset is adjusted byte-wise, hence 176 /// through a cast to i8*. 177 /// 178 /// TODO: This could probably live somewhere more prominantly if it doesn't 179 /// already exist. 180 static Value *constructPointer(Type *ResTy, Type *PtrElemTy, Value *Ptr, 181 int64_t Offset, IRBuilder<NoFolder> &IRB, 182 const DataLayout &DL) { 183 assert(Offset >= 0 && "Negative offset not supported yet!"); 184 LLVM_DEBUG(dbgs() << "Construct pointer: " << *Ptr << " + " << Offset 185 << "-bytes as " << *ResTy << "\n"); 186 187 if (Offset) { 188 SmallVector<Value *, 4> Indices; 189 std::string GEPName = Ptr->getName().str() + ".0"; 190 191 // Add 0 index to look through the pointer. 192 assert((uint64_t)Offset < DL.getTypeAllocSize(PtrElemTy) && 193 "Offset out of bounds"); 194 Indices.push_back(Constant::getNullValue(IRB.getInt32Ty())); 195 196 Type *Ty = PtrElemTy; 197 do { 198 auto *STy = dyn_cast<StructType>(Ty); 199 if (!STy) 200 // Non-aggregate type, we cast and make byte-wise progress now. 201 break; 202 203 const StructLayout *SL = DL.getStructLayout(STy); 204 if (int64_t(SL->getSizeInBytes()) < Offset) 205 break; 206 207 uint64_t Idx = SL->getElementContainingOffset(Offset); 208 assert(Idx < STy->getNumElements() && "Offset calculation error!"); 209 uint64_t Rem = Offset - SL->getElementOffset(Idx); 210 Ty = STy->getElementType(Idx); 211 212 LLVM_DEBUG(errs() << "Ty: " << *Ty << " Offset: " << Offset 213 << " Idx: " << Idx << " Rem: " << Rem << "\n"); 214 215 GEPName += "." + std::to_string(Idx); 216 Indices.push_back(ConstantInt::get(IRB.getInt32Ty(), Idx)); 217 Offset = Rem; 218 } while (Offset); 219 220 // Create a GEP for the indices collected above. 221 Ptr = IRB.CreateGEP(PtrElemTy, Ptr, Indices, GEPName); 222 223 // If an offset is left we use byte-wise adjustment. 224 if (Offset) { 225 Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy()); 226 Ptr = IRB.CreateGEP(IRB.getInt8Ty(), Ptr, IRB.getInt32(Offset), 227 GEPName + ".b" + Twine(Offset)); 228 } 229 } 230 231 // Ensure the result has the requested type. 232 Ptr = IRB.CreateBitOrPointerCast(Ptr, ResTy, Ptr->getName() + ".cast"); 233 234 LLVM_DEBUG(dbgs() << "Constructed pointer: " << *Ptr << "\n"); 235 return Ptr; 236 } 237 238 /// Recursively visit all values that might become \p IRP at some point. This 239 /// will be done by looking through cast instructions, selects, phis, and calls 240 /// with the "returned" attribute. Once we cannot look through the value any 241 /// further, the callback \p VisitValueCB is invoked and passed the current 242 /// value, the \p State, and a flag to indicate if we stripped anything. 243 /// Stripped means that we unpacked the value associated with \p IRP at least 244 /// once. Note that the value used for the callback may still be the value 245 /// associated with \p IRP (due to PHIs). To limit how much effort is invested, 246 /// we will never visit more values than specified by \p MaxValues. 247 template <typename AAType, typename StateTy> 248 static bool genericValueTraversal( 249 Attributor &A, IRPosition IRP, const AAType &QueryingAA, StateTy &State, 250 function_ref<bool(Value &, const Instruction *, StateTy &, bool)> 251 VisitValueCB, 252 const Instruction *CtxI, bool UseValueSimplify = true, int MaxValues = 16, 253 function_ref<Value *(Value *)> StripCB = nullptr) { 254 255 const AAIsDead *LivenessAA = nullptr; 256 if (IRP.getAnchorScope()) 257 LivenessAA = &A.getAAFor<AAIsDead>( 258 QueryingAA, 259 IRPosition::function(*IRP.getAnchorScope(), IRP.getCallBaseContext()), 260 DepClassTy::NONE); 261 bool AnyDead = false; 262 263 using Item = std::pair<Value *, const Instruction *>; 264 SmallSet<Item, 16> Visited; 265 SmallVector<Item, 16> Worklist; 266 Worklist.push_back({&IRP.getAssociatedValue(), CtxI}); 267 268 int Iteration = 0; 269 do { 270 Item I = Worklist.pop_back_val(); 271 Value *V = I.first; 272 CtxI = I.second; 273 if (StripCB) 274 V = StripCB(V); 275 276 // Check if we should process the current value. To prevent endless 277 // recursion keep a record of the values we followed! 278 if (!Visited.insert(I).second) 279 continue; 280 281 // Make sure we limit the compile time for complex expressions. 282 if (Iteration++ >= MaxValues) 283 return false; 284 285 // Explicitly look through calls with a "returned" attribute if we do 286 // not have a pointer as stripPointerCasts only works on them. 287 Value *NewV = nullptr; 288 if (V->getType()->isPointerTy()) { 289 NewV = V->stripPointerCasts(); 290 } else { 291 auto *CB = dyn_cast<CallBase>(V); 292 if (CB && CB->getCalledFunction()) { 293 for (Argument &Arg : CB->getCalledFunction()->args()) 294 if (Arg.hasReturnedAttr()) { 295 NewV = CB->getArgOperand(Arg.getArgNo()); 296 break; 297 } 298 } 299 } 300 if (NewV && NewV != V) { 301 Worklist.push_back({NewV, CtxI}); 302 continue; 303 } 304 305 // Look through select instructions, visit both potential values. 306 if (auto *SI = dyn_cast<SelectInst>(V)) { 307 Worklist.push_back({SI->getTrueValue(), CtxI}); 308 Worklist.push_back({SI->getFalseValue(), CtxI}); 309 continue; 310 } 311 312 // Look through phi nodes, visit all live operands. 313 if (auto *PHI = dyn_cast<PHINode>(V)) { 314 assert(LivenessAA && 315 "Expected liveness in the presence of instructions!"); 316 for (unsigned u = 0, e = PHI->getNumIncomingValues(); u < e; u++) { 317 BasicBlock *IncomingBB = PHI->getIncomingBlock(u); 318 if (A.isAssumedDead(*IncomingBB->getTerminator(), &QueryingAA, 319 LivenessAA, 320 /* CheckBBLivenessOnly */ true)) { 321 AnyDead = true; 322 continue; 323 } 324 Worklist.push_back( 325 {PHI->getIncomingValue(u), IncomingBB->getTerminator()}); 326 } 327 continue; 328 } 329 330 if (UseValueSimplify && !isa<Constant>(V)) { 331 bool UsedAssumedInformation = false; 332 Optional<Constant *> C = 333 A.getAssumedConstant(*V, QueryingAA, UsedAssumedInformation); 334 if (!C.hasValue()) 335 continue; 336 if (Value *NewV = C.getValue()) { 337 Worklist.push_back({NewV, CtxI}); 338 continue; 339 } 340 } 341 342 // Once a leaf is reached we inform the user through the callback. 343 if (!VisitValueCB(*V, CtxI, State, Iteration > 1)) 344 return false; 345 } while (!Worklist.empty()); 346 347 // If we actually used liveness information so we have to record a dependence. 348 if (AnyDead) 349 A.recordDependence(*LivenessAA, QueryingAA, DepClassTy::OPTIONAL); 350 351 // All values have been visited. 352 return true; 353 } 354 355 const Value *stripAndAccumulateMinimalOffsets( 356 Attributor &A, const AbstractAttribute &QueryingAA, const Value *Val, 357 const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, 358 bool UseAssumed = false) { 359 360 auto AttributorAnalysis = [&](Value &V, APInt &ROffset) -> bool { 361 const IRPosition &Pos = IRPosition::value(V); 362 // Only track dependence if we are going to use the assumed info. 363 const AAValueConstantRange &ValueConstantRangeAA = 364 A.getAAFor<AAValueConstantRange>(QueryingAA, Pos, 365 UseAssumed ? DepClassTy::OPTIONAL 366 : DepClassTy::NONE); 367 ConstantRange Range = UseAssumed ? ValueConstantRangeAA.getAssumed() 368 : ValueConstantRangeAA.getKnown(); 369 // We can only use the lower part of the range because the upper part can 370 // be higher than what the value can really be. 371 ROffset = Range.getSignedMin(); 372 return true; 373 }; 374 375 return Val->stripAndAccumulateConstantOffsets(DL, Offset, AllowNonInbounds, 376 AttributorAnalysis); 377 } 378 379 static const Value *getMinimalBaseOfAccsesPointerOperand( 380 Attributor &A, const AbstractAttribute &QueryingAA, const Instruction *I, 381 int64_t &BytesOffset, const DataLayout &DL, bool AllowNonInbounds = false) { 382 const Value *Ptr = getPointerOperand(I, /* AllowVolatile */ false); 383 if (!Ptr) 384 return nullptr; 385 APInt OffsetAPInt(DL.getIndexTypeSizeInBits(Ptr->getType()), 0); 386 const Value *Base = stripAndAccumulateMinimalOffsets( 387 A, QueryingAA, Ptr, DL, OffsetAPInt, AllowNonInbounds); 388 389 BytesOffset = OffsetAPInt.getSExtValue(); 390 return Base; 391 } 392 393 static const Value * 394 getBasePointerOfAccessPointerOperand(const Instruction *I, int64_t &BytesOffset, 395 const DataLayout &DL, 396 bool AllowNonInbounds = false) { 397 const Value *Ptr = getPointerOperand(I, /* AllowVolatile */ false); 398 if (!Ptr) 399 return nullptr; 400 401 return GetPointerBaseWithConstantOffset(Ptr, BytesOffset, DL, 402 AllowNonInbounds); 403 } 404 405 /// Helper function to clamp a state \p S of type \p StateType with the 406 /// information in \p R and indicate/return if \p S did change (as-in update is 407 /// required to be run again). 408 template <typename StateType> 409 ChangeStatus clampStateAndIndicateChange(StateType &S, const StateType &R) { 410 auto Assumed = S.getAssumed(); 411 S ^= R; 412 return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED 413 : ChangeStatus::CHANGED; 414 } 415 416 /// Clamp the information known for all returned values of a function 417 /// (identified by \p QueryingAA) into \p S. 418 template <typename AAType, typename StateType = typename AAType::StateType> 419 static void clampReturnedValueStates( 420 Attributor &A, const AAType &QueryingAA, StateType &S, 421 const IRPosition::CallBaseContext *CBContext = nullptr) { 422 LLVM_DEBUG(dbgs() << "[Attributor] Clamp return value states for " 423 << QueryingAA << " into " << S << "\n"); 424 425 assert((QueryingAA.getIRPosition().getPositionKind() == 426 IRPosition::IRP_RETURNED || 427 QueryingAA.getIRPosition().getPositionKind() == 428 IRPosition::IRP_CALL_SITE_RETURNED) && 429 "Can only clamp returned value states for a function returned or call " 430 "site returned position!"); 431 432 // Use an optional state as there might not be any return values and we want 433 // to join (IntegerState::operator&) the state of all there are. 434 Optional<StateType> T; 435 436 // Callback for each possibly returned value. 437 auto CheckReturnValue = [&](Value &RV) -> bool { 438 const IRPosition &RVPos = IRPosition::value(RV, CBContext); 439 const AAType &AA = 440 A.getAAFor<AAType>(QueryingAA, RVPos, DepClassTy::REQUIRED); 441 LLVM_DEBUG(dbgs() << "[Attributor] RV: " << RV << " AA: " << AA.getAsStr() 442 << " @ " << RVPos << "\n"); 443 const StateType &AAS = AA.getState(); 444 if (T.hasValue()) 445 *T &= AAS; 446 else 447 T = AAS; 448 LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " RV State: " << T 449 << "\n"); 450 return T->isValidState(); 451 }; 452 453 if (!A.checkForAllReturnedValues(CheckReturnValue, QueryingAA)) 454 S.indicatePessimisticFixpoint(); 455 else if (T.hasValue()) 456 S ^= *T; 457 } 458 459 /// Helper class for generic deduction: return value -> returned position. 460 template <typename AAType, typename BaseType, 461 typename StateType = typename BaseType::StateType, 462 bool PropagateCallBaseContext = false> 463 struct AAReturnedFromReturnedValues : public BaseType { 464 AAReturnedFromReturnedValues(const IRPosition &IRP, Attributor &A) 465 : BaseType(IRP, A) {} 466 467 /// See AbstractAttribute::updateImpl(...). 468 ChangeStatus updateImpl(Attributor &A) override { 469 StateType S(StateType::getBestState(this->getState())); 470 clampReturnedValueStates<AAType, StateType>( 471 A, *this, S, 472 PropagateCallBaseContext ? this->getCallBaseContext() : nullptr); 473 // TODO: If we know we visited all returned values, thus no are assumed 474 // dead, we can take the known information from the state T. 475 return clampStateAndIndicateChange<StateType>(this->getState(), S); 476 } 477 }; 478 479 /// Clamp the information known at all call sites for a given argument 480 /// (identified by \p QueryingAA) into \p S. 481 template <typename AAType, typename StateType = typename AAType::StateType> 482 static void clampCallSiteArgumentStates(Attributor &A, const AAType &QueryingAA, 483 StateType &S) { 484 LLVM_DEBUG(dbgs() << "[Attributor] Clamp call site argument states for " 485 << QueryingAA << " into " << S << "\n"); 486 487 assert(QueryingAA.getIRPosition().getPositionKind() == 488 IRPosition::IRP_ARGUMENT && 489 "Can only clamp call site argument states for an argument position!"); 490 491 // Use an optional state as there might not be any return values and we want 492 // to join (IntegerState::operator&) the state of all there are. 493 Optional<StateType> T; 494 495 // The argument number which is also the call site argument number. 496 unsigned ArgNo = QueryingAA.getIRPosition().getCallSiteArgNo(); 497 498 auto CallSiteCheck = [&](AbstractCallSite ACS) { 499 const IRPosition &ACSArgPos = IRPosition::callsite_argument(ACS, ArgNo); 500 // Check if a coresponding argument was found or if it is on not associated 501 // (which can happen for callback calls). 502 if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID) 503 return false; 504 505 const AAType &AA = 506 A.getAAFor<AAType>(QueryingAA, ACSArgPos, DepClassTy::REQUIRED); 507 LLVM_DEBUG(dbgs() << "[Attributor] ACS: " << *ACS.getInstruction() 508 << " AA: " << AA.getAsStr() << " @" << ACSArgPos << "\n"); 509 const StateType &AAS = AA.getState(); 510 if (T.hasValue()) 511 *T &= AAS; 512 else 513 T = AAS; 514 LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " CSA State: " << T 515 << "\n"); 516 return T->isValidState(); 517 }; 518 519 bool AllCallSitesKnown; 520 if (!A.checkForAllCallSites(CallSiteCheck, QueryingAA, true, 521 AllCallSitesKnown)) 522 S.indicatePessimisticFixpoint(); 523 else if (T.hasValue()) 524 S ^= *T; 525 } 526 527 /// This function is the bridge between argument position and the call base 528 /// context. 529 template <typename AAType, typename BaseType, 530 typename StateType = typename AAType::StateType> 531 bool getArgumentStateFromCallBaseContext(Attributor &A, 532 BaseType &QueryingAttribute, 533 IRPosition &Pos, StateType &State) { 534 assert((Pos.getPositionKind() == IRPosition::IRP_ARGUMENT) && 535 "Expected an 'argument' position !"); 536 const CallBase *CBContext = Pos.getCallBaseContext(); 537 if (!CBContext) 538 return false; 539 540 int ArgNo = Pos.getCallSiteArgNo(); 541 assert(ArgNo >= 0 && "Invalid Arg No!"); 542 543 const auto &AA = A.getAAFor<AAType>( 544 QueryingAttribute, IRPosition::callsite_argument(*CBContext, ArgNo), 545 DepClassTy::REQUIRED); 546 const StateType &CBArgumentState = 547 static_cast<const StateType &>(AA.getState()); 548 549 LLVM_DEBUG(dbgs() << "[Attributor] Briding Call site context to argument" 550 << "Position:" << Pos << "CB Arg state:" << CBArgumentState 551 << "\n"); 552 553 // NOTE: If we want to do call site grouping it should happen here. 554 State ^= CBArgumentState; 555 return true; 556 } 557 558 /// Helper class for generic deduction: call site argument -> argument position. 559 template <typename AAType, typename BaseType, 560 typename StateType = typename AAType::StateType, 561 bool BridgeCallBaseContext = false> 562 struct AAArgumentFromCallSiteArguments : public BaseType { 563 AAArgumentFromCallSiteArguments(const IRPosition &IRP, Attributor &A) 564 : BaseType(IRP, A) {} 565 566 /// See AbstractAttribute::updateImpl(...). 567 ChangeStatus updateImpl(Attributor &A) override { 568 StateType S = StateType::getBestState(this->getState()); 569 570 if (BridgeCallBaseContext) { 571 bool Success = 572 getArgumentStateFromCallBaseContext<AAType, BaseType, StateType>( 573 A, *this, this->getIRPosition(), S); 574 if (Success) 575 return clampStateAndIndicateChange<StateType>(this->getState(), S); 576 } 577 clampCallSiteArgumentStates<AAType, StateType>(A, *this, S); 578 579 // TODO: If we know we visited all incoming values, thus no are assumed 580 // dead, we can take the known information from the state T. 581 return clampStateAndIndicateChange<StateType>(this->getState(), S); 582 } 583 }; 584 585 /// Helper class for generic replication: function returned -> cs returned. 586 template <typename AAType, typename BaseType, 587 typename StateType = typename BaseType::StateType, 588 bool IntroduceCallBaseContext = false> 589 struct AACallSiteReturnedFromReturned : public BaseType { 590 AACallSiteReturnedFromReturned(const IRPosition &IRP, Attributor &A) 591 : BaseType(IRP, A) {} 592 593 /// See AbstractAttribute::updateImpl(...). 594 ChangeStatus updateImpl(Attributor &A) override { 595 assert(this->getIRPosition().getPositionKind() == 596 IRPosition::IRP_CALL_SITE_RETURNED && 597 "Can only wrap function returned positions for call site returned " 598 "positions!"); 599 auto &S = this->getState(); 600 601 const Function *AssociatedFunction = 602 this->getIRPosition().getAssociatedFunction(); 603 if (!AssociatedFunction) 604 return S.indicatePessimisticFixpoint(); 605 606 CallBase &CBContext = static_cast<CallBase &>(this->getAnchorValue()); 607 if (IntroduceCallBaseContext) 608 LLVM_DEBUG(dbgs() << "[Attributor] Introducing call base context:" 609 << CBContext << "\n"); 610 611 IRPosition FnPos = IRPosition::returned( 612 *AssociatedFunction, IntroduceCallBaseContext ? &CBContext : nullptr); 613 const AAType &AA = A.getAAFor<AAType>(*this, FnPos, DepClassTy::REQUIRED); 614 return clampStateAndIndicateChange(S, AA.getState()); 615 } 616 }; 617 618 /// Helper function to accumulate uses. 619 template <class AAType, typename StateType = typename AAType::StateType> 620 static void followUsesInContext(AAType &AA, Attributor &A, 621 MustBeExecutedContextExplorer &Explorer, 622 const Instruction *CtxI, 623 SetVector<const Use *> &Uses, 624 StateType &State) { 625 auto EIt = Explorer.begin(CtxI), EEnd = Explorer.end(CtxI); 626 for (unsigned u = 0; u < Uses.size(); ++u) { 627 const Use *U = Uses[u]; 628 if (const Instruction *UserI = dyn_cast<Instruction>(U->getUser())) { 629 bool Found = Explorer.findInContextOf(UserI, EIt, EEnd); 630 if (Found && AA.followUseInMBEC(A, U, UserI, State)) 631 for (const Use &Us : UserI->uses()) 632 Uses.insert(&Us); 633 } 634 } 635 } 636 637 /// Use the must-be-executed-context around \p I to add information into \p S. 638 /// The AAType class is required to have `followUseInMBEC` method with the 639 /// following signature and behaviour: 640 /// 641 /// bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I) 642 /// U - Underlying use. 643 /// I - The user of the \p U. 644 /// Returns true if the value should be tracked transitively. 645 /// 646 template <class AAType, typename StateType = typename AAType::StateType> 647 static void followUsesInMBEC(AAType &AA, Attributor &A, StateType &S, 648 Instruction &CtxI) { 649 650 // Container for (transitive) uses of the associated value. 651 SetVector<const Use *> Uses; 652 for (const Use &U : AA.getIRPosition().getAssociatedValue().uses()) 653 Uses.insert(&U); 654 655 MustBeExecutedContextExplorer &Explorer = 656 A.getInfoCache().getMustBeExecutedContextExplorer(); 657 658 followUsesInContext<AAType>(AA, A, Explorer, &CtxI, Uses, S); 659 660 if (S.isAtFixpoint()) 661 return; 662 663 SmallVector<const BranchInst *, 4> BrInsts; 664 auto Pred = [&](const Instruction *I) { 665 if (const BranchInst *Br = dyn_cast<BranchInst>(I)) 666 if (Br->isConditional()) 667 BrInsts.push_back(Br); 668 return true; 669 }; 670 671 // Here, accumulate conditional branch instructions in the context. We 672 // explore the child paths and collect the known states. The disjunction of 673 // those states can be merged to its own state. Let ParentState_i be a state 674 // to indicate the known information for an i-th branch instruction in the 675 // context. ChildStates are created for its successors respectively. 676 // 677 // ParentS_1 = ChildS_{1, 1} /\ ChildS_{1, 2} /\ ... /\ ChildS_{1, n_1} 678 // ParentS_2 = ChildS_{2, 1} /\ ChildS_{2, 2} /\ ... /\ ChildS_{2, n_2} 679 // ... 680 // ParentS_m = ChildS_{m, 1} /\ ChildS_{m, 2} /\ ... /\ ChildS_{m, n_m} 681 // 682 // Known State |= ParentS_1 \/ ParentS_2 \/... \/ ParentS_m 683 // 684 // FIXME: Currently, recursive branches are not handled. For example, we 685 // can't deduce that ptr must be dereferenced in below function. 686 // 687 // void f(int a, int c, int *ptr) { 688 // if(a) 689 // if (b) { 690 // *ptr = 0; 691 // } else { 692 // *ptr = 1; 693 // } 694 // else { 695 // if (b) { 696 // *ptr = 0; 697 // } else { 698 // *ptr = 1; 699 // } 700 // } 701 // } 702 703 Explorer.checkForAllContext(&CtxI, Pred); 704 for (const BranchInst *Br : BrInsts) { 705 StateType ParentState; 706 707 // The known state of the parent state is a conjunction of children's 708 // known states so it is initialized with a best state. 709 ParentState.indicateOptimisticFixpoint(); 710 711 for (const BasicBlock *BB : Br->successors()) { 712 StateType ChildState; 713 714 size_t BeforeSize = Uses.size(); 715 followUsesInContext(AA, A, Explorer, &BB->front(), Uses, ChildState); 716 717 // Erase uses which only appear in the child. 718 for (auto It = Uses.begin() + BeforeSize; It != Uses.end();) 719 It = Uses.erase(It); 720 721 ParentState &= ChildState; 722 } 723 724 // Use only known state. 725 S += ParentState; 726 } 727 } 728 729 /// -----------------------NoUnwind Function Attribute-------------------------- 730 731 struct AANoUnwindImpl : AANoUnwind { 732 AANoUnwindImpl(const IRPosition &IRP, Attributor &A) : AANoUnwind(IRP, A) {} 733 734 const std::string getAsStr() const override { 735 return getAssumed() ? "nounwind" : "may-unwind"; 736 } 737 738 /// See AbstractAttribute::updateImpl(...). 739 ChangeStatus updateImpl(Attributor &A) override { 740 auto Opcodes = { 741 (unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr, 742 (unsigned)Instruction::Call, (unsigned)Instruction::CleanupRet, 743 (unsigned)Instruction::CatchSwitch, (unsigned)Instruction::Resume}; 744 745 auto CheckForNoUnwind = [&](Instruction &I) { 746 if (!I.mayThrow()) 747 return true; 748 749 if (const auto *CB = dyn_cast<CallBase>(&I)) { 750 const auto &NoUnwindAA = A.getAAFor<AANoUnwind>( 751 *this, IRPosition::callsite_function(*CB), DepClassTy::REQUIRED); 752 return NoUnwindAA.isAssumedNoUnwind(); 753 } 754 return false; 755 }; 756 757 if (!A.checkForAllInstructions(CheckForNoUnwind, *this, Opcodes)) 758 return indicatePessimisticFixpoint(); 759 760 return ChangeStatus::UNCHANGED; 761 } 762 }; 763 764 struct AANoUnwindFunction final : public AANoUnwindImpl { 765 AANoUnwindFunction(const IRPosition &IRP, Attributor &A) 766 : AANoUnwindImpl(IRP, A) {} 767 768 /// See AbstractAttribute::trackStatistics() 769 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nounwind) } 770 }; 771 772 /// NoUnwind attribute deduction for a call sites. 773 struct AANoUnwindCallSite final : AANoUnwindImpl { 774 AANoUnwindCallSite(const IRPosition &IRP, Attributor &A) 775 : AANoUnwindImpl(IRP, A) {} 776 777 /// See AbstractAttribute::initialize(...). 778 void initialize(Attributor &A) override { 779 AANoUnwindImpl::initialize(A); 780 Function *F = getAssociatedFunction(); 781 if (!F || F->isDeclaration()) 782 indicatePessimisticFixpoint(); 783 } 784 785 /// See AbstractAttribute::updateImpl(...). 786 ChangeStatus updateImpl(Attributor &A) override { 787 // TODO: Once we have call site specific value information we can provide 788 // call site specific liveness information and then it makes 789 // sense to specialize attributes for call sites arguments instead of 790 // redirecting requests to the callee argument. 791 Function *F = getAssociatedFunction(); 792 const IRPosition &FnPos = IRPosition::function(*F); 793 auto &FnAA = A.getAAFor<AANoUnwind>(*this, FnPos, DepClassTy::REQUIRED); 794 return clampStateAndIndicateChange(getState(), FnAA.getState()); 795 } 796 797 /// See AbstractAttribute::trackStatistics() 798 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nounwind); } 799 }; 800 801 /// --------------------- Function Return Values ------------------------------- 802 803 /// "Attribute" that collects all potential returned values and the return 804 /// instructions that they arise from. 805 /// 806 /// If there is a unique returned value R, the manifest method will: 807 /// - mark R with the "returned" attribute, if R is an argument. 808 class AAReturnedValuesImpl : public AAReturnedValues, public AbstractState { 809 810 /// Mapping of values potentially returned by the associated function to the 811 /// return instructions that might return them. 812 MapVector<Value *, SmallSetVector<ReturnInst *, 4>> ReturnedValues; 813 814 /// Mapping to remember the number of returned values for a call site such 815 /// that we can avoid updates if nothing changed. 816 DenseMap<const CallBase *, unsigned> NumReturnedValuesPerKnownAA; 817 818 /// Set of unresolved calls returned by the associated function. 819 SmallSetVector<CallBase *, 4> UnresolvedCalls; 820 821 /// State flags 822 /// 823 ///{ 824 bool IsFixed = false; 825 bool IsValidState = true; 826 ///} 827 828 public: 829 AAReturnedValuesImpl(const IRPosition &IRP, Attributor &A) 830 : AAReturnedValues(IRP, A) {} 831 832 /// See AbstractAttribute::initialize(...). 833 void initialize(Attributor &A) override { 834 // Reset the state. 835 IsFixed = false; 836 IsValidState = true; 837 ReturnedValues.clear(); 838 839 Function *F = getAssociatedFunction(); 840 if (!F || F->isDeclaration()) { 841 indicatePessimisticFixpoint(); 842 return; 843 } 844 assert(!F->getReturnType()->isVoidTy() && 845 "Did not expect a void return type!"); 846 847 // The map from instruction opcodes to those instructions in the function. 848 auto &OpcodeInstMap = A.getInfoCache().getOpcodeInstMapForFunction(*F); 849 850 // Look through all arguments, if one is marked as returned we are done. 851 for (Argument &Arg : F->args()) { 852 if (Arg.hasReturnedAttr()) { 853 auto &ReturnInstSet = ReturnedValues[&Arg]; 854 if (auto *Insts = OpcodeInstMap.lookup(Instruction::Ret)) 855 for (Instruction *RI : *Insts) 856 ReturnInstSet.insert(cast<ReturnInst>(RI)); 857 858 indicateOptimisticFixpoint(); 859 return; 860 } 861 } 862 863 if (!A.isFunctionIPOAmendable(*F)) 864 indicatePessimisticFixpoint(); 865 } 866 867 /// See AbstractAttribute::manifest(...). 868 ChangeStatus manifest(Attributor &A) override; 869 870 /// See AbstractAttribute::getState(...). 871 AbstractState &getState() override { return *this; } 872 873 /// See AbstractAttribute::getState(...). 874 const AbstractState &getState() const override { return *this; } 875 876 /// See AbstractAttribute::updateImpl(Attributor &A). 877 ChangeStatus updateImpl(Attributor &A) override; 878 879 llvm::iterator_range<iterator> returned_values() override { 880 return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end()); 881 } 882 883 llvm::iterator_range<const_iterator> returned_values() const override { 884 return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end()); 885 } 886 887 const SmallSetVector<CallBase *, 4> &getUnresolvedCalls() const override { 888 return UnresolvedCalls; 889 } 890 891 /// Return the number of potential return values, -1 if unknown. 892 size_t getNumReturnValues() const override { 893 return isValidState() ? ReturnedValues.size() : -1; 894 } 895 896 /// Return an assumed unique return value if a single candidate is found. If 897 /// there cannot be one, return a nullptr. If it is not clear yet, return the 898 /// Optional::NoneType. 899 Optional<Value *> getAssumedUniqueReturnValue(Attributor &A) const; 900 901 /// See AbstractState::checkForAllReturnedValues(...). 902 bool checkForAllReturnedValuesAndReturnInsts( 903 function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred) 904 const override; 905 906 /// Pretty print the attribute similar to the IR representation. 907 const std::string getAsStr() const override; 908 909 /// See AbstractState::isAtFixpoint(). 910 bool isAtFixpoint() const override { return IsFixed; } 911 912 /// See AbstractState::isValidState(). 913 bool isValidState() const override { return IsValidState; } 914 915 /// See AbstractState::indicateOptimisticFixpoint(...). 916 ChangeStatus indicateOptimisticFixpoint() override { 917 IsFixed = true; 918 return ChangeStatus::UNCHANGED; 919 } 920 921 ChangeStatus indicatePessimisticFixpoint() override { 922 IsFixed = true; 923 IsValidState = false; 924 return ChangeStatus::CHANGED; 925 } 926 }; 927 928 ChangeStatus AAReturnedValuesImpl::manifest(Attributor &A) { 929 ChangeStatus Changed = ChangeStatus::UNCHANGED; 930 931 // Bookkeeping. 932 assert(isValidState()); 933 STATS_DECLTRACK(KnownReturnValues, FunctionReturn, 934 "Number of function with known return values"); 935 936 // Check if we have an assumed unique return value that we could manifest. 937 Optional<Value *> UniqueRV = getAssumedUniqueReturnValue(A); 938 939 if (!UniqueRV.hasValue() || !UniqueRV.getValue()) 940 return Changed; 941 942 // Bookkeeping. 943 STATS_DECLTRACK(UniqueReturnValue, FunctionReturn, 944 "Number of function with unique return"); 945 946 // Callback to replace the uses of CB with the constant C. 947 auto ReplaceCallSiteUsersWith = [&A](CallBase &CB, Constant &C) { 948 if (CB.use_empty()) 949 return ChangeStatus::UNCHANGED; 950 if (A.changeValueAfterManifest(CB, C)) 951 return ChangeStatus::CHANGED; 952 return ChangeStatus::UNCHANGED; 953 }; 954 955 // If the assumed unique return value is an argument, annotate it. 956 if (auto *UniqueRVArg = dyn_cast<Argument>(UniqueRV.getValue())) { 957 if (UniqueRVArg->getType()->canLosslesslyBitCastTo( 958 getAssociatedFunction()->getReturnType())) { 959 getIRPosition() = IRPosition::argument(*UniqueRVArg); 960 Changed = IRAttribute::manifest(A); 961 } 962 } else if (auto *RVC = dyn_cast<Constant>(UniqueRV.getValue())) { 963 // We can replace the returned value with the unique returned constant. 964 Value &AnchorValue = getAnchorValue(); 965 if (Function *F = dyn_cast<Function>(&AnchorValue)) { 966 for (const Use &U : F->uses()) 967 if (CallBase *CB = dyn_cast<CallBase>(U.getUser())) 968 if (CB->isCallee(&U)) { 969 Constant *RVCCast = 970 CB->getType() == RVC->getType() 971 ? RVC 972 : ConstantExpr::getPointerCast(RVC, CB->getType()); 973 Changed = ReplaceCallSiteUsersWith(*CB, *RVCCast) | Changed; 974 } 975 } else { 976 assert(isa<CallBase>(AnchorValue) && 977 "Expcected a function or call base anchor!"); 978 Constant *RVCCast = 979 AnchorValue.getType() == RVC->getType() 980 ? RVC 981 : ConstantExpr::getPointerCast(RVC, AnchorValue.getType()); 982 Changed = ReplaceCallSiteUsersWith(cast<CallBase>(AnchorValue), *RVCCast); 983 } 984 if (Changed == ChangeStatus::CHANGED) 985 STATS_DECLTRACK(UniqueConstantReturnValue, FunctionReturn, 986 "Number of function returns replaced by constant return"); 987 } 988 989 return Changed; 990 } 991 992 const std::string AAReturnedValuesImpl::getAsStr() const { 993 return (isAtFixpoint() ? "returns(#" : "may-return(#") + 994 (isValidState() ? std::to_string(getNumReturnValues()) : "?") + 995 ")[#UC: " + std::to_string(UnresolvedCalls.size()) + "]"; 996 } 997 998 Optional<Value *> 999 AAReturnedValuesImpl::getAssumedUniqueReturnValue(Attributor &A) const { 1000 // If checkForAllReturnedValues provides a unique value, ignoring potential 1001 // undef values that can also be present, it is assumed to be the actual 1002 // return value and forwarded to the caller of this method. If there are 1003 // multiple, a nullptr is returned indicating there cannot be a unique 1004 // returned value. 1005 Optional<Value *> UniqueRV; 1006 1007 auto Pred = [&](Value &RV) -> bool { 1008 // If we found a second returned value and neither the current nor the saved 1009 // one is an undef, there is no unique returned value. Undefs are special 1010 // since we can pretend they have any value. 1011 if (UniqueRV.hasValue() && UniqueRV != &RV && 1012 !(isa<UndefValue>(RV) || isa<UndefValue>(UniqueRV.getValue()))) { 1013 UniqueRV = nullptr; 1014 return false; 1015 } 1016 1017 // Do not overwrite a value with an undef. 1018 if (!UniqueRV.hasValue() || !isa<UndefValue>(RV)) 1019 UniqueRV = &RV; 1020 1021 return true; 1022 }; 1023 1024 if (!A.checkForAllReturnedValues(Pred, *this)) 1025 UniqueRV = nullptr; 1026 1027 return UniqueRV; 1028 } 1029 1030 bool AAReturnedValuesImpl::checkForAllReturnedValuesAndReturnInsts( 1031 function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred) 1032 const { 1033 if (!isValidState()) 1034 return false; 1035 1036 // Check all returned values but ignore call sites as long as we have not 1037 // encountered an overdefined one during an update. 1038 for (auto &It : ReturnedValues) { 1039 Value *RV = It.first; 1040 1041 CallBase *CB = dyn_cast<CallBase>(RV); 1042 if (CB && !UnresolvedCalls.count(CB)) 1043 continue; 1044 1045 if (!Pred(*RV, It.second)) 1046 return false; 1047 } 1048 1049 return true; 1050 } 1051 1052 ChangeStatus AAReturnedValuesImpl::updateImpl(Attributor &A) { 1053 size_t NumUnresolvedCalls = UnresolvedCalls.size(); 1054 bool Changed = false; 1055 1056 // State used in the value traversals starting in returned values. 1057 struct RVState { 1058 // The map in which we collect return values -> return instrs. 1059 decltype(ReturnedValues) &RetValsMap; 1060 // The flag to indicate a change. 1061 bool &Changed; 1062 // The return instrs we come from. 1063 SmallSetVector<ReturnInst *, 4> RetInsts; 1064 }; 1065 1066 // Callback for a leaf value returned by the associated function. 1067 auto VisitValueCB = [](Value &Val, const Instruction *, RVState &RVS, 1068 bool) -> bool { 1069 auto Size = RVS.RetValsMap[&Val].size(); 1070 RVS.RetValsMap[&Val].insert(RVS.RetInsts.begin(), RVS.RetInsts.end()); 1071 bool Inserted = RVS.RetValsMap[&Val].size() != Size; 1072 RVS.Changed |= Inserted; 1073 LLVM_DEBUG({ 1074 if (Inserted) 1075 dbgs() << "[AAReturnedValues] 1 Add new returned value " << Val 1076 << " => " << RVS.RetInsts.size() << "\n"; 1077 }); 1078 return true; 1079 }; 1080 1081 // Helper method to invoke the generic value traversal. 1082 auto VisitReturnedValue = [&](Value &RV, RVState &RVS, 1083 const Instruction *CtxI) { 1084 IRPosition RetValPos = IRPosition::value(RV, getCallBaseContext()); 1085 return genericValueTraversal<AAReturnedValues, RVState>( 1086 A, RetValPos, *this, RVS, VisitValueCB, CtxI, 1087 /* UseValueSimplify */ false); 1088 }; 1089 1090 // Callback for all "return intructions" live in the associated function. 1091 auto CheckReturnInst = [this, &VisitReturnedValue, &Changed](Instruction &I) { 1092 ReturnInst &Ret = cast<ReturnInst>(I); 1093 RVState RVS({ReturnedValues, Changed, {}}); 1094 RVS.RetInsts.insert(&Ret); 1095 return VisitReturnedValue(*Ret.getReturnValue(), RVS, &I); 1096 }; 1097 1098 // Start by discovering returned values from all live returned instructions in 1099 // the associated function. 1100 if (!A.checkForAllInstructions(CheckReturnInst, *this, {Instruction::Ret})) 1101 return indicatePessimisticFixpoint(); 1102 1103 // Once returned values "directly" present in the code are handled we try to 1104 // resolve returned calls. To avoid modifications to the ReturnedValues map 1105 // while we iterate over it we kept record of potential new entries in a copy 1106 // map, NewRVsMap. 1107 decltype(ReturnedValues) NewRVsMap; 1108 1109 auto HandleReturnValue = [&](Value *RV, 1110 SmallSetVector<ReturnInst *, 4> &RIs) { 1111 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Returned value: " << *RV << " by #" 1112 << RIs.size() << " RIs\n"); 1113 CallBase *CB = dyn_cast<CallBase>(RV); 1114 if (!CB || UnresolvedCalls.count(CB)) 1115 return; 1116 1117 if (!CB->getCalledFunction()) { 1118 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Unresolved call: " << *CB 1119 << "\n"); 1120 UnresolvedCalls.insert(CB); 1121 return; 1122 } 1123 1124 // TODO: use the function scope once we have call site AAReturnedValues. 1125 const auto &RetValAA = A.getAAFor<AAReturnedValues>( 1126 *this, IRPosition::function(*CB->getCalledFunction()), 1127 DepClassTy::REQUIRED); 1128 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Found another AAReturnedValues: " 1129 << RetValAA << "\n"); 1130 1131 // Skip dead ends, thus if we do not know anything about the returned 1132 // call we mark it as unresolved and it will stay that way. 1133 if (!RetValAA.getState().isValidState()) { 1134 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Unresolved call: " << *CB 1135 << "\n"); 1136 UnresolvedCalls.insert(CB); 1137 return; 1138 } 1139 1140 // Do not try to learn partial information. If the callee has unresolved 1141 // return values we will treat the call as unresolved/opaque. 1142 auto &RetValAAUnresolvedCalls = RetValAA.getUnresolvedCalls(); 1143 if (!RetValAAUnresolvedCalls.empty()) { 1144 UnresolvedCalls.insert(CB); 1145 return; 1146 } 1147 1148 // Now check if we can track transitively returned values. If possible, thus 1149 // if all return value can be represented in the current scope, do so. 1150 bool Unresolved = false; 1151 for (auto &RetValAAIt : RetValAA.returned_values()) { 1152 Value *RetVal = RetValAAIt.first; 1153 if (isa<Argument>(RetVal) || isa<CallBase>(RetVal) || 1154 isa<Constant>(RetVal)) 1155 continue; 1156 // Anything that did not fit in the above categories cannot be resolved, 1157 // mark the call as unresolved. 1158 LLVM_DEBUG(dbgs() << "[AAReturnedValues] transitively returned value " 1159 "cannot be translated: " 1160 << *RetVal << "\n"); 1161 UnresolvedCalls.insert(CB); 1162 Unresolved = true; 1163 break; 1164 } 1165 1166 if (Unresolved) 1167 return; 1168 1169 // Now track transitively returned values. 1170 unsigned &NumRetAA = NumReturnedValuesPerKnownAA[CB]; 1171 if (NumRetAA == RetValAA.getNumReturnValues()) { 1172 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Skip call as it has not " 1173 "changed since it was seen last\n"); 1174 return; 1175 } 1176 NumRetAA = RetValAA.getNumReturnValues(); 1177 1178 for (auto &RetValAAIt : RetValAA.returned_values()) { 1179 Value *RetVal = RetValAAIt.first; 1180 if (Argument *Arg = dyn_cast<Argument>(RetVal)) { 1181 // Arguments are mapped to call site operands and we begin the traversal 1182 // again. 1183 bool Unused = false; 1184 RVState RVS({NewRVsMap, Unused, RetValAAIt.second}); 1185 VisitReturnedValue(*CB->getArgOperand(Arg->getArgNo()), RVS, CB); 1186 continue; 1187 } 1188 if (isa<CallBase>(RetVal)) { 1189 // Call sites are resolved by the callee attribute over time, no need to 1190 // do anything for us. 1191 continue; 1192 } 1193 if (isa<Constant>(RetVal)) { 1194 // Constants are valid everywhere, we can simply take them. 1195 NewRVsMap[RetVal].insert(RIs.begin(), RIs.end()); 1196 continue; 1197 } 1198 } 1199 }; 1200 1201 for (auto &It : ReturnedValues) 1202 HandleReturnValue(It.first, It.second); 1203 1204 // Because processing the new information can again lead to new return values 1205 // we have to be careful and iterate until this iteration is complete. The 1206 // idea is that we are in a stable state at the end of an update. All return 1207 // values have been handled and properly categorized. We might not update 1208 // again if we have not requested a non-fix attribute so we cannot "wait" for 1209 // the next update to analyze a new return value. 1210 while (!NewRVsMap.empty()) { 1211 auto It = std::move(NewRVsMap.back()); 1212 NewRVsMap.pop_back(); 1213 1214 assert(!It.second.empty() && "Entry does not add anything."); 1215 auto &ReturnInsts = ReturnedValues[It.first]; 1216 for (ReturnInst *RI : It.second) 1217 if (ReturnInsts.insert(RI)) { 1218 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Add new returned value " 1219 << *It.first << " => " << *RI << "\n"); 1220 HandleReturnValue(It.first, ReturnInsts); 1221 Changed = true; 1222 } 1223 } 1224 1225 Changed |= (NumUnresolvedCalls != UnresolvedCalls.size()); 1226 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 1227 } 1228 1229 struct AAReturnedValuesFunction final : public AAReturnedValuesImpl { 1230 AAReturnedValuesFunction(const IRPosition &IRP, Attributor &A) 1231 : AAReturnedValuesImpl(IRP, A) {} 1232 1233 /// See AbstractAttribute::trackStatistics() 1234 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(returned) } 1235 }; 1236 1237 /// Returned values information for a call sites. 1238 struct AAReturnedValuesCallSite final : AAReturnedValuesImpl { 1239 AAReturnedValuesCallSite(const IRPosition &IRP, Attributor &A) 1240 : AAReturnedValuesImpl(IRP, A) {} 1241 1242 /// See AbstractAttribute::initialize(...). 1243 void initialize(Attributor &A) override { 1244 // TODO: Once we have call site specific value information we can provide 1245 // call site specific liveness information and then it makes 1246 // sense to specialize attributes for call sites instead of 1247 // redirecting requests to the callee. 1248 llvm_unreachable("Abstract attributes for returned values are not " 1249 "supported for call sites yet!"); 1250 } 1251 1252 /// See AbstractAttribute::updateImpl(...). 1253 ChangeStatus updateImpl(Attributor &A) override { 1254 return indicatePessimisticFixpoint(); 1255 } 1256 1257 /// See AbstractAttribute::trackStatistics() 1258 void trackStatistics() const override {} 1259 }; 1260 1261 /// ------------------------ NoSync Function Attribute ------------------------- 1262 1263 struct AANoSyncImpl : AANoSync { 1264 AANoSyncImpl(const IRPosition &IRP, Attributor &A) : AANoSync(IRP, A) {} 1265 1266 const std::string getAsStr() const override { 1267 return getAssumed() ? "nosync" : "may-sync"; 1268 } 1269 1270 /// See AbstractAttribute::updateImpl(...). 1271 ChangeStatus updateImpl(Attributor &A) override; 1272 1273 /// Helper function used to determine whether an instruction is non-relaxed 1274 /// atomic. In other words, if an atomic instruction does not have unordered 1275 /// or monotonic ordering 1276 static bool isNonRelaxedAtomic(Instruction *I); 1277 1278 /// Helper function specific for intrinsics which are potentially volatile 1279 static bool isNoSyncIntrinsic(Instruction *I); 1280 }; 1281 1282 bool AANoSyncImpl::isNonRelaxedAtomic(Instruction *I) { 1283 if (!I->isAtomic()) 1284 return false; 1285 1286 if (auto *FI = dyn_cast<FenceInst>(I)) 1287 // All legal orderings for fence are stronger than monotonic. 1288 return FI->getSyncScopeID() != SyncScope::SingleThread; 1289 else if (auto *AI = dyn_cast<AtomicCmpXchgInst>(I)) { 1290 // Unordered is not a legal ordering for cmpxchg. 1291 return (AI->getSuccessOrdering() != AtomicOrdering::Monotonic || 1292 AI->getFailureOrdering() != AtomicOrdering::Monotonic); 1293 } 1294 1295 AtomicOrdering Ordering; 1296 switch (I->getOpcode()) { 1297 case Instruction::AtomicRMW: 1298 Ordering = cast<AtomicRMWInst>(I)->getOrdering(); 1299 break; 1300 case Instruction::Store: 1301 Ordering = cast<StoreInst>(I)->getOrdering(); 1302 break; 1303 case Instruction::Load: 1304 Ordering = cast<LoadInst>(I)->getOrdering(); 1305 break; 1306 default: 1307 llvm_unreachable( 1308 "New atomic operations need to be known in the attributor."); 1309 } 1310 1311 return (Ordering != AtomicOrdering::Unordered && 1312 Ordering != AtomicOrdering::Monotonic); 1313 } 1314 1315 /// Return true if this intrinsic is nosync. This is only used for intrinsics 1316 /// which would be nosync except that they have a volatile flag. All other 1317 /// intrinsics are simply annotated with the nosync attribute in Intrinsics.td. 1318 bool AANoSyncImpl::isNoSyncIntrinsic(Instruction *I) { 1319 if (auto *MI = dyn_cast<MemIntrinsic>(I)) 1320 return !MI->isVolatile(); 1321 return false; 1322 } 1323 1324 ChangeStatus AANoSyncImpl::updateImpl(Attributor &A) { 1325 1326 auto CheckRWInstForNoSync = [&](Instruction &I) { 1327 /// We are looking for volatile instructions or Non-Relaxed atomics. 1328 1329 if (const auto *CB = dyn_cast<CallBase>(&I)) { 1330 if (CB->hasFnAttr(Attribute::NoSync)) 1331 return true; 1332 1333 if (isNoSyncIntrinsic(&I)) 1334 return true; 1335 1336 const auto &NoSyncAA = A.getAAFor<AANoSync>( 1337 *this, IRPosition::callsite_function(*CB), DepClassTy::REQUIRED); 1338 return NoSyncAA.isAssumedNoSync(); 1339 } 1340 1341 if (!I.isVolatile() && !isNonRelaxedAtomic(&I)) 1342 return true; 1343 1344 return false; 1345 }; 1346 1347 auto CheckForNoSync = [&](Instruction &I) { 1348 // At this point we handled all read/write effects and they are all 1349 // nosync, so they can be skipped. 1350 if (I.mayReadOrWriteMemory()) 1351 return true; 1352 1353 // non-convergent and readnone imply nosync. 1354 return !cast<CallBase>(I).isConvergent(); 1355 }; 1356 1357 if (!A.checkForAllReadWriteInstructions(CheckRWInstForNoSync, *this) || 1358 !A.checkForAllCallLikeInstructions(CheckForNoSync, *this)) 1359 return indicatePessimisticFixpoint(); 1360 1361 return ChangeStatus::UNCHANGED; 1362 } 1363 1364 struct AANoSyncFunction final : public AANoSyncImpl { 1365 AANoSyncFunction(const IRPosition &IRP, Attributor &A) 1366 : AANoSyncImpl(IRP, A) {} 1367 1368 /// See AbstractAttribute::trackStatistics() 1369 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nosync) } 1370 }; 1371 1372 /// NoSync attribute deduction for a call sites. 1373 struct AANoSyncCallSite final : AANoSyncImpl { 1374 AANoSyncCallSite(const IRPosition &IRP, Attributor &A) 1375 : AANoSyncImpl(IRP, A) {} 1376 1377 /// See AbstractAttribute::initialize(...). 1378 void initialize(Attributor &A) override { 1379 AANoSyncImpl::initialize(A); 1380 Function *F = getAssociatedFunction(); 1381 if (!F || F->isDeclaration()) 1382 indicatePessimisticFixpoint(); 1383 } 1384 1385 /// See AbstractAttribute::updateImpl(...). 1386 ChangeStatus updateImpl(Attributor &A) override { 1387 // TODO: Once we have call site specific value information we can provide 1388 // call site specific liveness information and then it makes 1389 // sense to specialize attributes for call sites arguments instead of 1390 // redirecting requests to the callee argument. 1391 Function *F = getAssociatedFunction(); 1392 const IRPosition &FnPos = IRPosition::function(*F); 1393 auto &FnAA = A.getAAFor<AANoSync>(*this, FnPos, DepClassTy::REQUIRED); 1394 return clampStateAndIndicateChange(getState(), FnAA.getState()); 1395 } 1396 1397 /// See AbstractAttribute::trackStatistics() 1398 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nosync); } 1399 }; 1400 1401 /// ------------------------ No-Free Attributes ---------------------------- 1402 1403 struct AANoFreeImpl : public AANoFree { 1404 AANoFreeImpl(const IRPosition &IRP, Attributor &A) : AANoFree(IRP, A) {} 1405 1406 /// See AbstractAttribute::updateImpl(...). 1407 ChangeStatus updateImpl(Attributor &A) override { 1408 auto CheckForNoFree = [&](Instruction &I) { 1409 const auto &CB = cast<CallBase>(I); 1410 if (CB.hasFnAttr(Attribute::NoFree)) 1411 return true; 1412 1413 const auto &NoFreeAA = A.getAAFor<AANoFree>( 1414 *this, IRPosition::callsite_function(CB), DepClassTy::REQUIRED); 1415 return NoFreeAA.isAssumedNoFree(); 1416 }; 1417 1418 if (!A.checkForAllCallLikeInstructions(CheckForNoFree, *this)) 1419 return indicatePessimisticFixpoint(); 1420 return ChangeStatus::UNCHANGED; 1421 } 1422 1423 /// See AbstractAttribute::getAsStr(). 1424 const std::string getAsStr() const override { 1425 return getAssumed() ? "nofree" : "may-free"; 1426 } 1427 }; 1428 1429 struct AANoFreeFunction final : public AANoFreeImpl { 1430 AANoFreeFunction(const IRPosition &IRP, Attributor &A) 1431 : AANoFreeImpl(IRP, A) {} 1432 1433 /// See AbstractAttribute::trackStatistics() 1434 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nofree) } 1435 }; 1436 1437 /// NoFree attribute deduction for a call sites. 1438 struct AANoFreeCallSite final : AANoFreeImpl { 1439 AANoFreeCallSite(const IRPosition &IRP, Attributor &A) 1440 : AANoFreeImpl(IRP, A) {} 1441 1442 /// See AbstractAttribute::initialize(...). 1443 void initialize(Attributor &A) override { 1444 AANoFreeImpl::initialize(A); 1445 Function *F = getAssociatedFunction(); 1446 if (!F || F->isDeclaration()) 1447 indicatePessimisticFixpoint(); 1448 } 1449 1450 /// See AbstractAttribute::updateImpl(...). 1451 ChangeStatus updateImpl(Attributor &A) override { 1452 // TODO: Once we have call site specific value information we can provide 1453 // call site specific liveness information and then it makes 1454 // sense to specialize attributes for call sites arguments instead of 1455 // redirecting requests to the callee argument. 1456 Function *F = getAssociatedFunction(); 1457 const IRPosition &FnPos = IRPosition::function(*F); 1458 auto &FnAA = A.getAAFor<AANoFree>(*this, FnPos, DepClassTy::REQUIRED); 1459 return clampStateAndIndicateChange(getState(), FnAA.getState()); 1460 } 1461 1462 /// See AbstractAttribute::trackStatistics() 1463 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(nofree); } 1464 }; 1465 1466 /// NoFree attribute for floating values. 1467 struct AANoFreeFloating : AANoFreeImpl { 1468 AANoFreeFloating(const IRPosition &IRP, Attributor &A) 1469 : AANoFreeImpl(IRP, A) {} 1470 1471 /// See AbstractAttribute::trackStatistics() 1472 void trackStatistics() const override{STATS_DECLTRACK_FLOATING_ATTR(nofree)} 1473 1474 /// See Abstract Attribute::updateImpl(...). 1475 ChangeStatus updateImpl(Attributor &A) override { 1476 const IRPosition &IRP = getIRPosition(); 1477 1478 const auto &NoFreeAA = A.getAAFor<AANoFree>( 1479 *this, IRPosition::function_scope(IRP), DepClassTy::OPTIONAL); 1480 if (NoFreeAA.isAssumedNoFree()) 1481 return ChangeStatus::UNCHANGED; 1482 1483 Value &AssociatedValue = getIRPosition().getAssociatedValue(); 1484 auto Pred = [&](const Use &U, bool &Follow) -> bool { 1485 Instruction *UserI = cast<Instruction>(U.getUser()); 1486 if (auto *CB = dyn_cast<CallBase>(UserI)) { 1487 if (CB->isBundleOperand(&U)) 1488 return false; 1489 if (!CB->isArgOperand(&U)) 1490 return true; 1491 unsigned ArgNo = CB->getArgOperandNo(&U); 1492 1493 const auto &NoFreeArg = A.getAAFor<AANoFree>( 1494 *this, IRPosition::callsite_argument(*CB, ArgNo), 1495 DepClassTy::REQUIRED); 1496 return NoFreeArg.isAssumedNoFree(); 1497 } 1498 1499 if (isa<GetElementPtrInst>(UserI) || isa<BitCastInst>(UserI) || 1500 isa<PHINode>(UserI) || isa<SelectInst>(UserI)) { 1501 Follow = true; 1502 return true; 1503 } 1504 if (isa<StoreInst>(UserI) || isa<LoadInst>(UserI) || 1505 isa<ReturnInst>(UserI)) 1506 return true; 1507 1508 // Unknown user. 1509 return false; 1510 }; 1511 if (!A.checkForAllUses(Pred, *this, AssociatedValue)) 1512 return indicatePessimisticFixpoint(); 1513 1514 return ChangeStatus::UNCHANGED; 1515 } 1516 }; 1517 1518 /// NoFree attribute for a call site argument. 1519 struct AANoFreeArgument final : AANoFreeFloating { 1520 AANoFreeArgument(const IRPosition &IRP, Attributor &A) 1521 : AANoFreeFloating(IRP, A) {} 1522 1523 /// See AbstractAttribute::trackStatistics() 1524 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nofree) } 1525 }; 1526 1527 /// NoFree attribute for call site arguments. 1528 struct AANoFreeCallSiteArgument final : AANoFreeFloating { 1529 AANoFreeCallSiteArgument(const IRPosition &IRP, Attributor &A) 1530 : AANoFreeFloating(IRP, A) {} 1531 1532 /// See AbstractAttribute::updateImpl(...). 1533 ChangeStatus updateImpl(Attributor &A) override { 1534 // TODO: Once we have call site specific value information we can provide 1535 // call site specific liveness information and then it makes 1536 // sense to specialize attributes for call sites arguments instead of 1537 // redirecting requests to the callee argument. 1538 Argument *Arg = getAssociatedArgument(); 1539 if (!Arg) 1540 return indicatePessimisticFixpoint(); 1541 const IRPosition &ArgPos = IRPosition::argument(*Arg); 1542 auto &ArgAA = A.getAAFor<AANoFree>(*this, ArgPos, DepClassTy::REQUIRED); 1543 return clampStateAndIndicateChange(getState(), ArgAA.getState()); 1544 } 1545 1546 /// See AbstractAttribute::trackStatistics() 1547 void trackStatistics() const override{STATS_DECLTRACK_CSARG_ATTR(nofree)}; 1548 }; 1549 1550 /// NoFree attribute for function return value. 1551 struct AANoFreeReturned final : AANoFreeFloating { 1552 AANoFreeReturned(const IRPosition &IRP, Attributor &A) 1553 : AANoFreeFloating(IRP, A) { 1554 llvm_unreachable("NoFree is not applicable to function returns!"); 1555 } 1556 1557 /// See AbstractAttribute::initialize(...). 1558 void initialize(Attributor &A) override { 1559 llvm_unreachable("NoFree is not applicable to function returns!"); 1560 } 1561 1562 /// See AbstractAttribute::updateImpl(...). 1563 ChangeStatus updateImpl(Attributor &A) override { 1564 llvm_unreachable("NoFree is not applicable to function returns!"); 1565 } 1566 1567 /// See AbstractAttribute::trackStatistics() 1568 void trackStatistics() const override {} 1569 }; 1570 1571 /// NoFree attribute deduction for a call site return value. 1572 struct AANoFreeCallSiteReturned final : AANoFreeFloating { 1573 AANoFreeCallSiteReturned(const IRPosition &IRP, Attributor &A) 1574 : AANoFreeFloating(IRP, A) {} 1575 1576 ChangeStatus manifest(Attributor &A) override { 1577 return ChangeStatus::UNCHANGED; 1578 } 1579 /// See AbstractAttribute::trackStatistics() 1580 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nofree) } 1581 }; 1582 1583 /// ------------------------ NonNull Argument Attribute ------------------------ 1584 static int64_t getKnownNonNullAndDerefBytesForUse( 1585 Attributor &A, const AbstractAttribute &QueryingAA, Value &AssociatedValue, 1586 const Use *U, const Instruction *I, bool &IsNonNull, bool &TrackUse) { 1587 TrackUse = false; 1588 1589 const Value *UseV = U->get(); 1590 if (!UseV->getType()->isPointerTy()) 1591 return 0; 1592 1593 // We need to follow common pointer manipulation uses to the accesses they 1594 // feed into. We can try to be smart to avoid looking through things we do not 1595 // like for now, e.g., non-inbounds GEPs. 1596 if (isa<CastInst>(I)) { 1597 TrackUse = true; 1598 return 0; 1599 } 1600 1601 if (isa<GetElementPtrInst>(I)) { 1602 TrackUse = true; 1603 return 0; 1604 } 1605 1606 Type *PtrTy = UseV->getType(); 1607 const Function *F = I->getFunction(); 1608 bool NullPointerIsDefined = 1609 F ? llvm::NullPointerIsDefined(F, PtrTy->getPointerAddressSpace()) : true; 1610 const DataLayout &DL = A.getInfoCache().getDL(); 1611 if (const auto *CB = dyn_cast<CallBase>(I)) { 1612 if (CB->isBundleOperand(U)) { 1613 if (RetainedKnowledge RK = getKnowledgeFromUse( 1614 U, {Attribute::NonNull, Attribute::Dereferenceable})) { 1615 IsNonNull |= 1616 (RK.AttrKind == Attribute::NonNull || !NullPointerIsDefined); 1617 return RK.ArgValue; 1618 } 1619 return 0; 1620 } 1621 1622 if (CB->isCallee(U)) { 1623 IsNonNull |= !NullPointerIsDefined; 1624 return 0; 1625 } 1626 1627 unsigned ArgNo = CB->getArgOperandNo(U); 1628 IRPosition IRP = IRPosition::callsite_argument(*CB, ArgNo); 1629 // As long as we only use known information there is no need to track 1630 // dependences here. 1631 auto &DerefAA = 1632 A.getAAFor<AADereferenceable>(QueryingAA, IRP, DepClassTy::NONE); 1633 IsNonNull |= DerefAA.isKnownNonNull(); 1634 return DerefAA.getKnownDereferenceableBytes(); 1635 } 1636 1637 int64_t Offset; 1638 const Value *Base = 1639 getMinimalBaseOfAccsesPointerOperand(A, QueryingAA, I, Offset, DL); 1640 if (Base) { 1641 if (Base == &AssociatedValue && 1642 getPointerOperand(I, /* AllowVolatile */ false) == UseV) { 1643 int64_t DerefBytes = 1644 (int64_t)DL.getTypeStoreSize(PtrTy->getPointerElementType()) + Offset; 1645 1646 IsNonNull |= !NullPointerIsDefined; 1647 return std::max(int64_t(0), DerefBytes); 1648 } 1649 } 1650 1651 /// Corner case when an offset is 0. 1652 Base = getBasePointerOfAccessPointerOperand(I, Offset, DL, 1653 /*AllowNonInbounds*/ true); 1654 if (Base) { 1655 if (Offset == 0 && Base == &AssociatedValue && 1656 getPointerOperand(I, /* AllowVolatile */ false) == UseV) { 1657 int64_t DerefBytes = 1658 (int64_t)DL.getTypeStoreSize(PtrTy->getPointerElementType()); 1659 IsNonNull |= !NullPointerIsDefined; 1660 return std::max(int64_t(0), DerefBytes); 1661 } 1662 } 1663 1664 return 0; 1665 } 1666 1667 struct AANonNullImpl : AANonNull { 1668 AANonNullImpl(const IRPosition &IRP, Attributor &A) 1669 : AANonNull(IRP, A), 1670 NullIsDefined(NullPointerIsDefined( 1671 getAnchorScope(), 1672 getAssociatedValue().getType()->getPointerAddressSpace())) {} 1673 1674 /// See AbstractAttribute::initialize(...). 1675 void initialize(Attributor &A) override { 1676 Value &V = getAssociatedValue(); 1677 if (!NullIsDefined && 1678 hasAttr({Attribute::NonNull, Attribute::Dereferenceable}, 1679 /* IgnoreSubsumingPositions */ false, &A)) { 1680 indicateOptimisticFixpoint(); 1681 return; 1682 } 1683 1684 if (isa<ConstantPointerNull>(V)) { 1685 indicatePessimisticFixpoint(); 1686 return; 1687 } 1688 1689 AANonNull::initialize(A); 1690 1691 bool CanBeNull, CanBeFreed; 1692 if (V.getPointerDereferenceableBytes(A.getDataLayout(), CanBeNull, 1693 CanBeFreed)) { 1694 if (!CanBeNull) { 1695 indicateOptimisticFixpoint(); 1696 return; 1697 } 1698 } 1699 1700 if (isa<GlobalValue>(&getAssociatedValue())) { 1701 indicatePessimisticFixpoint(); 1702 return; 1703 } 1704 1705 if (Instruction *CtxI = getCtxI()) 1706 followUsesInMBEC(*this, A, getState(), *CtxI); 1707 } 1708 1709 /// See followUsesInMBEC 1710 bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I, 1711 AANonNull::StateType &State) { 1712 bool IsNonNull = false; 1713 bool TrackUse = false; 1714 getKnownNonNullAndDerefBytesForUse(A, *this, getAssociatedValue(), U, I, 1715 IsNonNull, TrackUse); 1716 State.setKnown(IsNonNull); 1717 return TrackUse; 1718 } 1719 1720 /// See AbstractAttribute::getAsStr(). 1721 const std::string getAsStr() const override { 1722 return getAssumed() ? "nonnull" : "may-null"; 1723 } 1724 1725 /// Flag to determine if the underlying value can be null and still allow 1726 /// valid accesses. 1727 const bool NullIsDefined; 1728 }; 1729 1730 /// NonNull attribute for a floating value. 1731 struct AANonNullFloating : public AANonNullImpl { 1732 AANonNullFloating(const IRPosition &IRP, Attributor &A) 1733 : AANonNullImpl(IRP, A) {} 1734 1735 /// See AbstractAttribute::updateImpl(...). 1736 ChangeStatus updateImpl(Attributor &A) override { 1737 const DataLayout &DL = A.getDataLayout(); 1738 1739 DominatorTree *DT = nullptr; 1740 AssumptionCache *AC = nullptr; 1741 InformationCache &InfoCache = A.getInfoCache(); 1742 if (const Function *Fn = getAnchorScope()) { 1743 DT = InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*Fn); 1744 AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*Fn); 1745 } 1746 1747 auto VisitValueCB = [&](Value &V, const Instruction *CtxI, 1748 AANonNull::StateType &T, bool Stripped) -> bool { 1749 const auto &AA = A.getAAFor<AANonNull>(*this, IRPosition::value(V), 1750 DepClassTy::REQUIRED); 1751 if (!Stripped && this == &AA) { 1752 if (!isKnownNonZero(&V, DL, 0, AC, CtxI, DT)) 1753 T.indicatePessimisticFixpoint(); 1754 } else { 1755 // Use abstract attribute information. 1756 const AANonNull::StateType &NS = AA.getState(); 1757 T ^= NS; 1758 } 1759 return T.isValidState(); 1760 }; 1761 1762 StateType T; 1763 if (!genericValueTraversal<AANonNull, StateType>( 1764 A, getIRPosition(), *this, T, VisitValueCB, getCtxI())) 1765 return indicatePessimisticFixpoint(); 1766 1767 return clampStateAndIndicateChange(getState(), T); 1768 } 1769 1770 /// See AbstractAttribute::trackStatistics() 1771 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) } 1772 }; 1773 1774 /// NonNull attribute for function return value. 1775 struct AANonNullReturned final 1776 : AAReturnedFromReturnedValues<AANonNull, AANonNull> { 1777 AANonNullReturned(const IRPosition &IRP, Attributor &A) 1778 : AAReturnedFromReturnedValues<AANonNull, AANonNull>(IRP, A) {} 1779 1780 /// See AbstractAttribute::getAsStr(). 1781 const std::string getAsStr() const override { 1782 return getAssumed() ? "nonnull" : "may-null"; 1783 } 1784 1785 /// See AbstractAttribute::trackStatistics() 1786 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) } 1787 }; 1788 1789 /// NonNull attribute for function argument. 1790 struct AANonNullArgument final 1791 : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl> { 1792 AANonNullArgument(const IRPosition &IRP, Attributor &A) 1793 : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl>(IRP, A) {} 1794 1795 /// See AbstractAttribute::trackStatistics() 1796 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nonnull) } 1797 }; 1798 1799 struct AANonNullCallSiteArgument final : AANonNullFloating { 1800 AANonNullCallSiteArgument(const IRPosition &IRP, Attributor &A) 1801 : AANonNullFloating(IRP, A) {} 1802 1803 /// See AbstractAttribute::trackStatistics() 1804 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(nonnull) } 1805 }; 1806 1807 /// NonNull attribute for a call site return position. 1808 struct AANonNullCallSiteReturned final 1809 : AACallSiteReturnedFromReturned<AANonNull, AANonNullImpl> { 1810 AANonNullCallSiteReturned(const IRPosition &IRP, Attributor &A) 1811 : AACallSiteReturnedFromReturned<AANonNull, AANonNullImpl>(IRP, A) {} 1812 1813 /// See AbstractAttribute::trackStatistics() 1814 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nonnull) } 1815 }; 1816 1817 /// ------------------------ No-Recurse Attributes ---------------------------- 1818 1819 struct AANoRecurseImpl : public AANoRecurse { 1820 AANoRecurseImpl(const IRPosition &IRP, Attributor &A) : AANoRecurse(IRP, A) {} 1821 1822 /// See AbstractAttribute::getAsStr() 1823 const std::string getAsStr() const override { 1824 return getAssumed() ? "norecurse" : "may-recurse"; 1825 } 1826 }; 1827 1828 struct AANoRecurseFunction final : AANoRecurseImpl { 1829 AANoRecurseFunction(const IRPosition &IRP, Attributor &A) 1830 : AANoRecurseImpl(IRP, A) {} 1831 1832 /// See AbstractAttribute::initialize(...). 1833 void initialize(Attributor &A) override { 1834 AANoRecurseImpl::initialize(A); 1835 if (const Function *F = getAnchorScope()) 1836 if (A.getInfoCache().getSccSize(*F) != 1) 1837 indicatePessimisticFixpoint(); 1838 } 1839 1840 /// See AbstractAttribute::updateImpl(...). 1841 ChangeStatus updateImpl(Attributor &A) override { 1842 1843 // If all live call sites are known to be no-recurse, we are as well. 1844 auto CallSitePred = [&](AbstractCallSite ACS) { 1845 const auto &NoRecurseAA = A.getAAFor<AANoRecurse>( 1846 *this, IRPosition::function(*ACS.getInstruction()->getFunction()), 1847 DepClassTy::NONE); 1848 return NoRecurseAA.isKnownNoRecurse(); 1849 }; 1850 bool AllCallSitesKnown; 1851 if (A.checkForAllCallSites(CallSitePred, *this, true, AllCallSitesKnown)) { 1852 // If we know all call sites and all are known no-recurse, we are done. 1853 // If all known call sites, which might not be all that exist, are known 1854 // to be no-recurse, we are not done but we can continue to assume 1855 // no-recurse. If one of the call sites we have not visited will become 1856 // live, another update is triggered. 1857 if (AllCallSitesKnown) 1858 indicateOptimisticFixpoint(); 1859 return ChangeStatus::UNCHANGED; 1860 } 1861 1862 // If the above check does not hold anymore we look at the calls. 1863 auto CheckForNoRecurse = [&](Instruction &I) { 1864 const auto &CB = cast<CallBase>(I); 1865 if (CB.hasFnAttr(Attribute::NoRecurse)) 1866 return true; 1867 1868 const auto &NoRecurseAA = A.getAAFor<AANoRecurse>( 1869 *this, IRPosition::callsite_function(CB), DepClassTy::REQUIRED); 1870 if (!NoRecurseAA.isAssumedNoRecurse()) 1871 return false; 1872 1873 // Recursion to the same function 1874 if (CB.getCalledFunction() == getAnchorScope()) 1875 return false; 1876 1877 return true; 1878 }; 1879 1880 if (!A.checkForAllCallLikeInstructions(CheckForNoRecurse, *this)) 1881 return indicatePessimisticFixpoint(); 1882 return ChangeStatus::UNCHANGED; 1883 } 1884 1885 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(norecurse) } 1886 }; 1887 1888 /// NoRecurse attribute deduction for a call sites. 1889 struct AANoRecurseCallSite final : AANoRecurseImpl { 1890 AANoRecurseCallSite(const IRPosition &IRP, Attributor &A) 1891 : AANoRecurseImpl(IRP, A) {} 1892 1893 /// See AbstractAttribute::initialize(...). 1894 void initialize(Attributor &A) override { 1895 AANoRecurseImpl::initialize(A); 1896 Function *F = getAssociatedFunction(); 1897 if (!F || F->isDeclaration()) 1898 indicatePessimisticFixpoint(); 1899 } 1900 1901 /// See AbstractAttribute::updateImpl(...). 1902 ChangeStatus updateImpl(Attributor &A) override { 1903 // TODO: Once we have call site specific value information we can provide 1904 // call site specific liveness information and then it makes 1905 // sense to specialize attributes for call sites arguments instead of 1906 // redirecting requests to the callee argument. 1907 Function *F = getAssociatedFunction(); 1908 const IRPosition &FnPos = IRPosition::function(*F); 1909 auto &FnAA = A.getAAFor<AANoRecurse>(*this, FnPos, DepClassTy::REQUIRED); 1910 return clampStateAndIndicateChange(getState(), FnAA.getState()); 1911 } 1912 1913 /// See AbstractAttribute::trackStatistics() 1914 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(norecurse); } 1915 }; 1916 1917 /// -------------------- Undefined-Behavior Attributes ------------------------ 1918 1919 struct AAUndefinedBehaviorImpl : public AAUndefinedBehavior { 1920 AAUndefinedBehaviorImpl(const IRPosition &IRP, Attributor &A) 1921 : AAUndefinedBehavior(IRP, A) {} 1922 1923 /// See AbstractAttribute::updateImpl(...). 1924 // through a pointer (i.e. also branches etc.) 1925 ChangeStatus updateImpl(Attributor &A) override { 1926 const size_t UBPrevSize = KnownUBInsts.size(); 1927 const size_t NoUBPrevSize = AssumedNoUBInsts.size(); 1928 1929 auto InspectMemAccessInstForUB = [&](Instruction &I) { 1930 // Skip instructions that are already saved. 1931 if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I)) 1932 return true; 1933 1934 // If we reach here, we know we have an instruction 1935 // that accesses memory through a pointer operand, 1936 // for which getPointerOperand() should give it to us. 1937 const Value *PtrOp = getPointerOperand(&I, /* AllowVolatile */ true); 1938 assert(PtrOp && 1939 "Expected pointer operand of memory accessing instruction"); 1940 1941 // Either we stopped and the appropriate action was taken, 1942 // or we got back a simplified value to continue. 1943 Optional<Value *> SimplifiedPtrOp = stopOnUndefOrAssumed(A, PtrOp, &I); 1944 if (!SimplifiedPtrOp.hasValue()) 1945 return true; 1946 const Value *PtrOpVal = SimplifiedPtrOp.getValue(); 1947 1948 // A memory access through a pointer is considered UB 1949 // only if the pointer has constant null value. 1950 // TODO: Expand it to not only check constant values. 1951 if (!isa<ConstantPointerNull>(PtrOpVal)) { 1952 AssumedNoUBInsts.insert(&I); 1953 return true; 1954 } 1955 const Type *PtrTy = PtrOpVal->getType(); 1956 1957 // Because we only consider instructions inside functions, 1958 // assume that a parent function exists. 1959 const Function *F = I.getFunction(); 1960 1961 // A memory access using constant null pointer is only considered UB 1962 // if null pointer is _not_ defined for the target platform. 1963 if (llvm::NullPointerIsDefined(F, PtrTy->getPointerAddressSpace())) 1964 AssumedNoUBInsts.insert(&I); 1965 else 1966 KnownUBInsts.insert(&I); 1967 return true; 1968 }; 1969 1970 auto InspectBrInstForUB = [&](Instruction &I) { 1971 // A conditional branch instruction is considered UB if it has `undef` 1972 // condition. 1973 1974 // Skip instructions that are already saved. 1975 if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I)) 1976 return true; 1977 1978 // We know we have a branch instruction. 1979 auto BrInst = cast<BranchInst>(&I); 1980 1981 // Unconditional branches are never considered UB. 1982 if (BrInst->isUnconditional()) 1983 return true; 1984 1985 // Either we stopped and the appropriate action was taken, 1986 // or we got back a simplified value to continue. 1987 Optional<Value *> SimplifiedCond = 1988 stopOnUndefOrAssumed(A, BrInst->getCondition(), BrInst); 1989 if (!SimplifiedCond.hasValue()) 1990 return true; 1991 AssumedNoUBInsts.insert(&I); 1992 return true; 1993 }; 1994 1995 auto InspectCallSiteForUB = [&](Instruction &I) { 1996 // Check whether a callsite always cause UB or not 1997 1998 // Skip instructions that are already saved. 1999 if (AssumedNoUBInsts.count(&I) || KnownUBInsts.count(&I)) 2000 return true; 2001 2002 // Check nonnull and noundef argument attribute violation for each 2003 // callsite. 2004 CallBase &CB = cast<CallBase>(I); 2005 Function *Callee = CB.getCalledFunction(); 2006 if (!Callee) 2007 return true; 2008 for (unsigned idx = 0; idx < CB.getNumArgOperands(); idx++) { 2009 // If current argument is known to be simplified to null pointer and the 2010 // corresponding argument position is known to have nonnull attribute, 2011 // the argument is poison. Furthermore, if the argument is poison and 2012 // the position is known to have noundef attriubte, this callsite is 2013 // considered UB. 2014 if (idx >= Callee->arg_size()) 2015 break; 2016 Value *ArgVal = CB.getArgOperand(idx); 2017 if (!ArgVal) 2018 continue; 2019 // Here, we handle three cases. 2020 // (1) Not having a value means it is dead. (we can replace the value 2021 // with undef) 2022 // (2) Simplified to undef. The argument violate noundef attriubte. 2023 // (3) Simplified to null pointer where known to be nonnull. 2024 // The argument is a poison value and violate noundef attribute. 2025 IRPosition CalleeArgumentIRP = IRPosition::callsite_argument(CB, idx); 2026 auto &NoUndefAA = 2027 A.getAAFor<AANoUndef>(*this, CalleeArgumentIRP, DepClassTy::NONE); 2028 if (!NoUndefAA.isKnownNoUndef()) 2029 continue; 2030 auto &ValueSimplifyAA = A.getAAFor<AAValueSimplify>( 2031 *this, IRPosition::value(*ArgVal), DepClassTy::NONE); 2032 if (!ValueSimplifyAA.isKnown()) 2033 continue; 2034 Optional<Value *> SimplifiedVal = 2035 ValueSimplifyAA.getAssumedSimplifiedValue(A); 2036 if (!SimplifiedVal.hasValue() || 2037 isa<UndefValue>(*SimplifiedVal.getValue())) { 2038 KnownUBInsts.insert(&I); 2039 continue; 2040 } 2041 if (!ArgVal->getType()->isPointerTy() || 2042 !isa<ConstantPointerNull>(*SimplifiedVal.getValue())) 2043 continue; 2044 auto &NonNullAA = 2045 A.getAAFor<AANonNull>(*this, CalleeArgumentIRP, DepClassTy::NONE); 2046 if (NonNullAA.isKnownNonNull()) 2047 KnownUBInsts.insert(&I); 2048 } 2049 return true; 2050 }; 2051 2052 auto InspectReturnInstForUB = 2053 [&](Value &V, const SmallSetVector<ReturnInst *, 4> RetInsts) { 2054 // Check if a return instruction always cause UB or not 2055 // Note: It is guaranteed that the returned position of the anchor 2056 // scope has noundef attribute when this is called. 2057 // We also ensure the return position is not "assumed dead" 2058 // because the returned value was then potentially simplified to 2059 // `undef` in AAReturnedValues without removing the `noundef` 2060 // attribute yet. 2061 2062 // When the returned position has noundef attriubte, UB occur in the 2063 // following cases. 2064 // (1) Returned value is known to be undef. 2065 // (2) The value is known to be a null pointer and the returned 2066 // position has nonnull attribute (because the returned value is 2067 // poison). 2068 bool FoundUB = false; 2069 if (isa<UndefValue>(V)) { 2070 FoundUB = true; 2071 } else { 2072 if (isa<ConstantPointerNull>(V)) { 2073 auto &NonNullAA = A.getAAFor<AANonNull>( 2074 *this, IRPosition::returned(*getAnchorScope()), 2075 DepClassTy::NONE); 2076 if (NonNullAA.isKnownNonNull()) 2077 FoundUB = true; 2078 } 2079 } 2080 2081 if (FoundUB) 2082 for (ReturnInst *RI : RetInsts) 2083 KnownUBInsts.insert(RI); 2084 return true; 2085 }; 2086 2087 A.checkForAllInstructions(InspectMemAccessInstForUB, *this, 2088 {Instruction::Load, Instruction::Store, 2089 Instruction::AtomicCmpXchg, 2090 Instruction::AtomicRMW}, 2091 /* CheckBBLivenessOnly */ true); 2092 A.checkForAllInstructions(InspectBrInstForUB, *this, {Instruction::Br}, 2093 /* CheckBBLivenessOnly */ true); 2094 A.checkForAllCallLikeInstructions(InspectCallSiteForUB, *this); 2095 2096 // If the returned position of the anchor scope has noundef attriubte, check 2097 // all returned instructions. 2098 if (!getAnchorScope()->getReturnType()->isVoidTy()) { 2099 const IRPosition &ReturnIRP = IRPosition::returned(*getAnchorScope()); 2100 if (!A.isAssumedDead(ReturnIRP, this, nullptr)) { 2101 auto &RetPosNoUndefAA = 2102 A.getAAFor<AANoUndef>(*this, ReturnIRP, DepClassTy::NONE); 2103 if (RetPosNoUndefAA.isKnownNoUndef()) 2104 A.checkForAllReturnedValuesAndReturnInsts(InspectReturnInstForUB, 2105 *this); 2106 } 2107 } 2108 2109 if (NoUBPrevSize != AssumedNoUBInsts.size() || 2110 UBPrevSize != KnownUBInsts.size()) 2111 return ChangeStatus::CHANGED; 2112 return ChangeStatus::UNCHANGED; 2113 } 2114 2115 bool isKnownToCauseUB(Instruction *I) const override { 2116 return KnownUBInsts.count(I); 2117 } 2118 2119 bool isAssumedToCauseUB(Instruction *I) const override { 2120 // In simple words, if an instruction is not in the assumed to _not_ 2121 // cause UB, then it is assumed UB (that includes those 2122 // in the KnownUBInsts set). The rest is boilerplate 2123 // is to ensure that it is one of the instructions we test 2124 // for UB. 2125 2126 switch (I->getOpcode()) { 2127 case Instruction::Load: 2128 case Instruction::Store: 2129 case Instruction::AtomicCmpXchg: 2130 case Instruction::AtomicRMW: 2131 return !AssumedNoUBInsts.count(I); 2132 case Instruction::Br: { 2133 auto BrInst = cast<BranchInst>(I); 2134 if (BrInst->isUnconditional()) 2135 return false; 2136 return !AssumedNoUBInsts.count(I); 2137 } break; 2138 default: 2139 return false; 2140 } 2141 return false; 2142 } 2143 2144 ChangeStatus manifest(Attributor &A) override { 2145 if (KnownUBInsts.empty()) 2146 return ChangeStatus::UNCHANGED; 2147 for (Instruction *I : KnownUBInsts) 2148 A.changeToUnreachableAfterManifest(I); 2149 return ChangeStatus::CHANGED; 2150 } 2151 2152 /// See AbstractAttribute::getAsStr() 2153 const std::string getAsStr() const override { 2154 return getAssumed() ? "undefined-behavior" : "no-ub"; 2155 } 2156 2157 /// Note: The correctness of this analysis depends on the fact that the 2158 /// following 2 sets will stop changing after some point. 2159 /// "Change" here means that their size changes. 2160 /// The size of each set is monotonically increasing 2161 /// (we only add items to them) and it is upper bounded by the number of 2162 /// instructions in the processed function (we can never save more 2163 /// elements in either set than this number). Hence, at some point, 2164 /// they will stop increasing. 2165 /// Consequently, at some point, both sets will have stopped 2166 /// changing, effectively making the analysis reach a fixpoint. 2167 2168 /// Note: These 2 sets are disjoint and an instruction can be considered 2169 /// one of 3 things: 2170 /// 1) Known to cause UB (AAUndefinedBehavior could prove it) and put it in 2171 /// the KnownUBInsts set. 2172 /// 2) Assumed to cause UB (in every updateImpl, AAUndefinedBehavior 2173 /// has a reason to assume it). 2174 /// 3) Assumed to not cause UB. very other instruction - AAUndefinedBehavior 2175 /// could not find a reason to assume or prove that it can cause UB, 2176 /// hence it assumes it doesn't. We have a set for these instructions 2177 /// so that we don't reprocess them in every update. 2178 /// Note however that instructions in this set may cause UB. 2179 2180 protected: 2181 /// A set of all live instructions _known_ to cause UB. 2182 SmallPtrSet<Instruction *, 8> KnownUBInsts; 2183 2184 private: 2185 /// A set of all the (live) instructions that are assumed to _not_ cause UB. 2186 SmallPtrSet<Instruction *, 8> AssumedNoUBInsts; 2187 2188 // Should be called on updates in which if we're processing an instruction 2189 // \p I that depends on a value \p V, one of the following has to happen: 2190 // - If the value is assumed, then stop. 2191 // - If the value is known but undef, then consider it UB. 2192 // - Otherwise, do specific processing with the simplified value. 2193 // We return None in the first 2 cases to signify that an appropriate 2194 // action was taken and the caller should stop. 2195 // Otherwise, we return the simplified value that the caller should 2196 // use for specific processing. 2197 Optional<Value *> stopOnUndefOrAssumed(Attributor &A, const Value *V, 2198 Instruction *I) { 2199 const auto &ValueSimplifyAA = A.getAAFor<AAValueSimplify>( 2200 *this, IRPosition::value(*V), DepClassTy::REQUIRED); 2201 Optional<Value *> SimplifiedV = 2202 ValueSimplifyAA.getAssumedSimplifiedValue(A); 2203 if (!ValueSimplifyAA.isKnown()) { 2204 // Don't depend on assumed values. 2205 return llvm::None; 2206 } 2207 if (!SimplifiedV.hasValue()) { 2208 // If it is known (which we tested above) but it doesn't have a value, 2209 // then we can assume `undef` and hence the instruction is UB. 2210 KnownUBInsts.insert(I); 2211 return llvm::None; 2212 } 2213 Value *Val = SimplifiedV.getValue(); 2214 if (isa<UndefValue>(Val)) { 2215 KnownUBInsts.insert(I); 2216 return llvm::None; 2217 } 2218 return Val; 2219 } 2220 }; 2221 2222 struct AAUndefinedBehaviorFunction final : AAUndefinedBehaviorImpl { 2223 AAUndefinedBehaviorFunction(const IRPosition &IRP, Attributor &A) 2224 : AAUndefinedBehaviorImpl(IRP, A) {} 2225 2226 /// See AbstractAttribute::trackStatistics() 2227 void trackStatistics() const override { 2228 STATS_DECL(UndefinedBehaviorInstruction, Instruction, 2229 "Number of instructions known to have UB"); 2230 BUILD_STAT_NAME(UndefinedBehaviorInstruction, Instruction) += 2231 KnownUBInsts.size(); 2232 } 2233 }; 2234 2235 /// ------------------------ Will-Return Attributes ---------------------------- 2236 2237 // Helper function that checks whether a function has any cycle which we don't 2238 // know if it is bounded or not. 2239 // Loops with maximum trip count are considered bounded, any other cycle not. 2240 static bool mayContainUnboundedCycle(Function &F, Attributor &A) { 2241 ScalarEvolution *SE = 2242 A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>(F); 2243 LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>(F); 2244 // If either SCEV or LoopInfo is not available for the function then we assume 2245 // any cycle to be unbounded cycle. 2246 // We use scc_iterator which uses Tarjan algorithm to find all the maximal 2247 // SCCs.To detect if there's a cycle, we only need to find the maximal ones. 2248 if (!SE || !LI) { 2249 for (scc_iterator<Function *> SCCI = scc_begin(&F); !SCCI.isAtEnd(); ++SCCI) 2250 if (SCCI.hasCycle()) 2251 return true; 2252 return false; 2253 } 2254 2255 // If there's irreducible control, the function may contain non-loop cycles. 2256 if (mayContainIrreducibleControl(F, LI)) 2257 return true; 2258 2259 // Any loop that does not have a max trip count is considered unbounded cycle. 2260 for (auto *L : LI->getLoopsInPreorder()) { 2261 if (!SE->getSmallConstantMaxTripCount(L)) 2262 return true; 2263 } 2264 return false; 2265 } 2266 2267 struct AAWillReturnImpl : public AAWillReturn { 2268 AAWillReturnImpl(const IRPosition &IRP, Attributor &A) 2269 : AAWillReturn(IRP, A) {} 2270 2271 /// See AbstractAttribute::initialize(...). 2272 void initialize(Attributor &A) override { 2273 AAWillReturn::initialize(A); 2274 2275 if (isImpliedByMustprogressAndReadonly(A, /* KnownOnly */ true)) { 2276 indicateOptimisticFixpoint(); 2277 return; 2278 } 2279 } 2280 2281 /// Check for `mustprogress` and `readonly` as they imply `willreturn`. 2282 bool isImpliedByMustprogressAndReadonly(Attributor &A, bool KnownOnly) { 2283 // Check for `mustprogress` in the scope and the associated function which 2284 // might be different if this is a call site. 2285 if ((!getAnchorScope() || !getAnchorScope()->mustProgress()) && 2286 (!getAssociatedFunction() || !getAssociatedFunction()->mustProgress())) 2287 return false; 2288 2289 const auto &MemAA = 2290 A.getAAFor<AAMemoryBehavior>(*this, getIRPosition(), DepClassTy::NONE); 2291 if (!MemAA.isAssumedReadOnly()) 2292 return false; 2293 if (KnownOnly && !MemAA.isKnownReadOnly()) 2294 return false; 2295 if (!MemAA.isKnownReadOnly()) 2296 A.recordDependence(MemAA, *this, DepClassTy::OPTIONAL); 2297 2298 return true; 2299 } 2300 2301 /// See AbstractAttribute::updateImpl(...). 2302 ChangeStatus updateImpl(Attributor &A) override { 2303 if (isImpliedByMustprogressAndReadonly(A, /* KnownOnly */ false)) 2304 return ChangeStatus::UNCHANGED; 2305 2306 auto CheckForWillReturn = [&](Instruction &I) { 2307 IRPosition IPos = IRPosition::callsite_function(cast<CallBase>(I)); 2308 const auto &WillReturnAA = 2309 A.getAAFor<AAWillReturn>(*this, IPos, DepClassTy::REQUIRED); 2310 if (WillReturnAA.isKnownWillReturn()) 2311 return true; 2312 if (!WillReturnAA.isAssumedWillReturn()) 2313 return false; 2314 const auto &NoRecurseAA = 2315 A.getAAFor<AANoRecurse>(*this, IPos, DepClassTy::REQUIRED); 2316 return NoRecurseAA.isAssumedNoRecurse(); 2317 }; 2318 2319 if (!A.checkForAllCallLikeInstructions(CheckForWillReturn, *this)) 2320 return indicatePessimisticFixpoint(); 2321 2322 return ChangeStatus::UNCHANGED; 2323 } 2324 2325 /// See AbstractAttribute::getAsStr() 2326 const std::string getAsStr() const override { 2327 return getAssumed() ? "willreturn" : "may-noreturn"; 2328 } 2329 }; 2330 2331 struct AAWillReturnFunction final : AAWillReturnImpl { 2332 AAWillReturnFunction(const IRPosition &IRP, Attributor &A) 2333 : AAWillReturnImpl(IRP, A) {} 2334 2335 /// See AbstractAttribute::initialize(...). 2336 void initialize(Attributor &A) override { 2337 AAWillReturnImpl::initialize(A); 2338 2339 Function *F = getAnchorScope(); 2340 if (!F || F->isDeclaration() || mayContainUnboundedCycle(*F, A)) 2341 indicatePessimisticFixpoint(); 2342 } 2343 2344 /// See AbstractAttribute::trackStatistics() 2345 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(willreturn) } 2346 }; 2347 2348 /// WillReturn attribute deduction for a call sites. 2349 struct AAWillReturnCallSite final : AAWillReturnImpl { 2350 AAWillReturnCallSite(const IRPosition &IRP, Attributor &A) 2351 : AAWillReturnImpl(IRP, A) {} 2352 2353 /// See AbstractAttribute::initialize(...). 2354 void initialize(Attributor &A) override { 2355 AAWillReturnImpl::initialize(A); 2356 Function *F = getAssociatedFunction(); 2357 if (!F || !A.isFunctionIPOAmendable(*F)) 2358 indicatePessimisticFixpoint(); 2359 } 2360 2361 /// See AbstractAttribute::updateImpl(...). 2362 ChangeStatus updateImpl(Attributor &A) override { 2363 if (isImpliedByMustprogressAndReadonly(A, /* KnownOnly */ false)) 2364 return ChangeStatus::UNCHANGED; 2365 2366 // TODO: Once we have call site specific value information we can provide 2367 // call site specific liveness information and then it makes 2368 // sense to specialize attributes for call sites arguments instead of 2369 // redirecting requests to the callee argument. 2370 Function *F = getAssociatedFunction(); 2371 const IRPosition &FnPos = IRPosition::function(*F); 2372 auto &FnAA = A.getAAFor<AAWillReturn>(*this, FnPos, DepClassTy::REQUIRED); 2373 return clampStateAndIndicateChange(getState(), FnAA.getState()); 2374 } 2375 2376 /// See AbstractAttribute::trackStatistics() 2377 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(willreturn); } 2378 }; 2379 2380 /// -------------------AAReachability Attribute-------------------------- 2381 2382 struct AAReachabilityImpl : AAReachability { 2383 AAReachabilityImpl(const IRPosition &IRP, Attributor &A) 2384 : AAReachability(IRP, A) {} 2385 2386 const std::string getAsStr() const override { 2387 // TODO: Return the number of reachable queries. 2388 return "reachable"; 2389 } 2390 2391 /// See AbstractAttribute::initialize(...). 2392 void initialize(Attributor &A) override { indicatePessimisticFixpoint(); } 2393 2394 /// See AbstractAttribute::updateImpl(...). 2395 ChangeStatus updateImpl(Attributor &A) override { 2396 return indicatePessimisticFixpoint(); 2397 } 2398 }; 2399 2400 struct AAReachabilityFunction final : public AAReachabilityImpl { 2401 AAReachabilityFunction(const IRPosition &IRP, Attributor &A) 2402 : AAReachabilityImpl(IRP, A) {} 2403 2404 /// See AbstractAttribute::trackStatistics() 2405 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(reachable); } 2406 }; 2407 2408 /// ------------------------ NoAlias Argument Attribute ------------------------ 2409 2410 struct AANoAliasImpl : AANoAlias { 2411 AANoAliasImpl(const IRPosition &IRP, Attributor &A) : AANoAlias(IRP, A) { 2412 assert(getAssociatedType()->isPointerTy() && 2413 "Noalias is a pointer attribute"); 2414 } 2415 2416 const std::string getAsStr() const override { 2417 return getAssumed() ? "noalias" : "may-alias"; 2418 } 2419 }; 2420 2421 /// NoAlias attribute for a floating value. 2422 struct AANoAliasFloating final : AANoAliasImpl { 2423 AANoAliasFloating(const IRPosition &IRP, Attributor &A) 2424 : AANoAliasImpl(IRP, A) {} 2425 2426 /// See AbstractAttribute::initialize(...). 2427 void initialize(Attributor &A) override { 2428 AANoAliasImpl::initialize(A); 2429 Value *Val = &getAssociatedValue(); 2430 do { 2431 CastInst *CI = dyn_cast<CastInst>(Val); 2432 if (!CI) 2433 break; 2434 Value *Base = CI->getOperand(0); 2435 if (!Base->hasOneUse()) 2436 break; 2437 Val = Base; 2438 } while (true); 2439 2440 if (!Val->getType()->isPointerTy()) { 2441 indicatePessimisticFixpoint(); 2442 return; 2443 } 2444 2445 if (isa<AllocaInst>(Val)) 2446 indicateOptimisticFixpoint(); 2447 else if (isa<ConstantPointerNull>(Val) && 2448 !NullPointerIsDefined(getAnchorScope(), 2449 Val->getType()->getPointerAddressSpace())) 2450 indicateOptimisticFixpoint(); 2451 else if (Val != &getAssociatedValue()) { 2452 const auto &ValNoAliasAA = A.getAAFor<AANoAlias>( 2453 *this, IRPosition::value(*Val), DepClassTy::OPTIONAL); 2454 if (ValNoAliasAA.isKnownNoAlias()) 2455 indicateOptimisticFixpoint(); 2456 } 2457 } 2458 2459 /// See AbstractAttribute::updateImpl(...). 2460 ChangeStatus updateImpl(Attributor &A) override { 2461 // TODO: Implement this. 2462 return indicatePessimisticFixpoint(); 2463 } 2464 2465 /// See AbstractAttribute::trackStatistics() 2466 void trackStatistics() const override { 2467 STATS_DECLTRACK_FLOATING_ATTR(noalias) 2468 } 2469 }; 2470 2471 /// NoAlias attribute for an argument. 2472 struct AANoAliasArgument final 2473 : AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl> { 2474 using Base = AAArgumentFromCallSiteArguments<AANoAlias, AANoAliasImpl>; 2475 AANoAliasArgument(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {} 2476 2477 /// See AbstractAttribute::initialize(...). 2478 void initialize(Attributor &A) override { 2479 Base::initialize(A); 2480 // See callsite argument attribute and callee argument attribute. 2481 if (hasAttr({Attribute::ByVal})) 2482 indicateOptimisticFixpoint(); 2483 } 2484 2485 /// See AbstractAttribute::update(...). 2486 ChangeStatus updateImpl(Attributor &A) override { 2487 // We have to make sure no-alias on the argument does not break 2488 // synchronization when this is a callback argument, see also [1] below. 2489 // If synchronization cannot be affected, we delegate to the base updateImpl 2490 // function, otherwise we give up for now. 2491 2492 // If the function is no-sync, no-alias cannot break synchronization. 2493 const auto &NoSyncAA = 2494 A.getAAFor<AANoSync>(*this, IRPosition::function_scope(getIRPosition()), 2495 DepClassTy::OPTIONAL); 2496 if (NoSyncAA.isAssumedNoSync()) 2497 return Base::updateImpl(A); 2498 2499 // If the argument is read-only, no-alias cannot break synchronization. 2500 const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>( 2501 *this, getIRPosition(), DepClassTy::OPTIONAL); 2502 if (MemBehaviorAA.isAssumedReadOnly()) 2503 return Base::updateImpl(A); 2504 2505 // If the argument is never passed through callbacks, no-alias cannot break 2506 // synchronization. 2507 bool AllCallSitesKnown; 2508 if (A.checkForAllCallSites( 2509 [](AbstractCallSite ACS) { return !ACS.isCallbackCall(); }, *this, 2510 true, AllCallSitesKnown)) 2511 return Base::updateImpl(A); 2512 2513 // TODO: add no-alias but make sure it doesn't break synchronization by 2514 // introducing fake uses. See: 2515 // [1] Compiler Optimizations for OpenMP, J. Doerfert and H. Finkel, 2516 // International Workshop on OpenMP 2018, 2517 // http://compilers.cs.uni-saarland.de/people/doerfert/par_opt18.pdf 2518 2519 return indicatePessimisticFixpoint(); 2520 } 2521 2522 /// See AbstractAttribute::trackStatistics() 2523 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noalias) } 2524 }; 2525 2526 struct AANoAliasCallSiteArgument final : AANoAliasImpl { 2527 AANoAliasCallSiteArgument(const IRPosition &IRP, Attributor &A) 2528 : AANoAliasImpl(IRP, A) {} 2529 2530 /// See AbstractAttribute::initialize(...). 2531 void initialize(Attributor &A) override { 2532 // See callsite argument attribute and callee argument attribute. 2533 const auto &CB = cast<CallBase>(getAnchorValue()); 2534 if (CB.paramHasAttr(getCallSiteArgNo(), Attribute::NoAlias)) 2535 indicateOptimisticFixpoint(); 2536 Value &Val = getAssociatedValue(); 2537 if (isa<ConstantPointerNull>(Val) && 2538 !NullPointerIsDefined(getAnchorScope(), 2539 Val.getType()->getPointerAddressSpace())) 2540 indicateOptimisticFixpoint(); 2541 } 2542 2543 /// Determine if the underlying value may alias with the call site argument 2544 /// \p OtherArgNo of \p ICS (= the underlying call site). 2545 bool mayAliasWithArgument(Attributor &A, AAResults *&AAR, 2546 const AAMemoryBehavior &MemBehaviorAA, 2547 const CallBase &CB, unsigned OtherArgNo) { 2548 // We do not need to worry about aliasing with the underlying IRP. 2549 if (this->getCalleeArgNo() == (int)OtherArgNo) 2550 return false; 2551 2552 // If it is not a pointer or pointer vector we do not alias. 2553 const Value *ArgOp = CB.getArgOperand(OtherArgNo); 2554 if (!ArgOp->getType()->isPtrOrPtrVectorTy()) 2555 return false; 2556 2557 auto &CBArgMemBehaviorAA = A.getAAFor<AAMemoryBehavior>( 2558 *this, IRPosition::callsite_argument(CB, OtherArgNo), DepClassTy::NONE); 2559 2560 // If the argument is readnone, there is no read-write aliasing. 2561 if (CBArgMemBehaviorAA.isAssumedReadNone()) { 2562 A.recordDependence(CBArgMemBehaviorAA, *this, DepClassTy::OPTIONAL); 2563 return false; 2564 } 2565 2566 // If the argument is readonly and the underlying value is readonly, there 2567 // is no read-write aliasing. 2568 bool IsReadOnly = MemBehaviorAA.isAssumedReadOnly(); 2569 if (CBArgMemBehaviorAA.isAssumedReadOnly() && IsReadOnly) { 2570 A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL); 2571 A.recordDependence(CBArgMemBehaviorAA, *this, DepClassTy::OPTIONAL); 2572 return false; 2573 } 2574 2575 // We have to utilize actual alias analysis queries so we need the object. 2576 if (!AAR) 2577 AAR = A.getInfoCache().getAAResultsForFunction(*getAnchorScope()); 2578 2579 // Try to rule it out at the call site. 2580 bool IsAliasing = !AAR || !AAR->isNoAlias(&getAssociatedValue(), ArgOp); 2581 LLVM_DEBUG(dbgs() << "[NoAliasCSArg] Check alias between " 2582 "callsite arguments: " 2583 << getAssociatedValue() << " " << *ArgOp << " => " 2584 << (IsAliasing ? "" : "no-") << "alias \n"); 2585 2586 return IsAliasing; 2587 } 2588 2589 bool 2590 isKnownNoAliasDueToNoAliasPreservation(Attributor &A, AAResults *&AAR, 2591 const AAMemoryBehavior &MemBehaviorAA, 2592 const AANoAlias &NoAliasAA) { 2593 // We can deduce "noalias" if the following conditions hold. 2594 // (i) Associated value is assumed to be noalias in the definition. 2595 // (ii) Associated value is assumed to be no-capture in all the uses 2596 // possibly executed before this callsite. 2597 // (iii) There is no other pointer argument which could alias with the 2598 // value. 2599 2600 bool AssociatedValueIsNoAliasAtDef = NoAliasAA.isAssumedNoAlias(); 2601 if (!AssociatedValueIsNoAliasAtDef) { 2602 LLVM_DEBUG(dbgs() << "[AANoAlias] " << getAssociatedValue() 2603 << " is not no-alias at the definition\n"); 2604 return false; 2605 } 2606 2607 A.recordDependence(NoAliasAA, *this, DepClassTy::OPTIONAL); 2608 2609 const IRPosition &VIRP = IRPosition::value(getAssociatedValue()); 2610 const Function *ScopeFn = VIRP.getAnchorScope(); 2611 auto &NoCaptureAA = A.getAAFor<AANoCapture>(*this, VIRP, DepClassTy::NONE); 2612 // Check whether the value is captured in the scope using AANoCapture. 2613 // Look at CFG and check only uses possibly executed before this 2614 // callsite. 2615 auto UsePred = [&](const Use &U, bool &Follow) -> bool { 2616 Instruction *UserI = cast<Instruction>(U.getUser()); 2617 2618 // If UserI is the curr instruction and there is a single potential use of 2619 // the value in UserI we allow the use. 2620 // TODO: We should inspect the operands and allow those that cannot alias 2621 // with the value. 2622 if (UserI == getCtxI() && UserI->getNumOperands() == 1) 2623 return true; 2624 2625 if (ScopeFn) { 2626 const auto &ReachabilityAA = A.getAAFor<AAReachability>( 2627 *this, IRPosition::function(*ScopeFn), DepClassTy::OPTIONAL); 2628 2629 if (!ReachabilityAA.isAssumedReachable(A, *UserI, *getCtxI())) 2630 return true; 2631 2632 if (auto *CB = dyn_cast<CallBase>(UserI)) { 2633 if (CB->isArgOperand(&U)) { 2634 2635 unsigned ArgNo = CB->getArgOperandNo(&U); 2636 2637 const auto &NoCaptureAA = A.getAAFor<AANoCapture>( 2638 *this, IRPosition::callsite_argument(*CB, ArgNo), 2639 DepClassTy::OPTIONAL); 2640 2641 if (NoCaptureAA.isAssumedNoCapture()) 2642 return true; 2643 } 2644 } 2645 } 2646 2647 // For cases which can potentially have more users 2648 if (isa<GetElementPtrInst>(U) || isa<BitCastInst>(U) || isa<PHINode>(U) || 2649 isa<SelectInst>(U)) { 2650 Follow = true; 2651 return true; 2652 } 2653 2654 LLVM_DEBUG(dbgs() << "[AANoAliasCSArg] Unknown user: " << *U << "\n"); 2655 return false; 2656 }; 2657 2658 if (!NoCaptureAA.isAssumedNoCaptureMaybeReturned()) { 2659 if (!A.checkForAllUses(UsePred, *this, getAssociatedValue())) { 2660 LLVM_DEBUG( 2661 dbgs() << "[AANoAliasCSArg] " << getAssociatedValue() 2662 << " cannot be noalias as it is potentially captured\n"); 2663 return false; 2664 } 2665 } 2666 A.recordDependence(NoCaptureAA, *this, DepClassTy::OPTIONAL); 2667 2668 // Check there is no other pointer argument which could alias with the 2669 // value passed at this call site. 2670 // TODO: AbstractCallSite 2671 const auto &CB = cast<CallBase>(getAnchorValue()); 2672 for (unsigned OtherArgNo = 0; OtherArgNo < CB.getNumArgOperands(); 2673 OtherArgNo++) 2674 if (mayAliasWithArgument(A, AAR, MemBehaviorAA, CB, OtherArgNo)) 2675 return false; 2676 2677 return true; 2678 } 2679 2680 /// See AbstractAttribute::updateImpl(...). 2681 ChangeStatus updateImpl(Attributor &A) override { 2682 // If the argument is readnone we are done as there are no accesses via the 2683 // argument. 2684 auto &MemBehaviorAA = 2685 A.getAAFor<AAMemoryBehavior>(*this, getIRPosition(), DepClassTy::NONE); 2686 if (MemBehaviorAA.isAssumedReadNone()) { 2687 A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL); 2688 return ChangeStatus::UNCHANGED; 2689 } 2690 2691 const IRPosition &VIRP = IRPosition::value(getAssociatedValue()); 2692 const auto &NoAliasAA = 2693 A.getAAFor<AANoAlias>(*this, VIRP, DepClassTy::NONE); 2694 2695 AAResults *AAR = nullptr; 2696 if (isKnownNoAliasDueToNoAliasPreservation(A, AAR, MemBehaviorAA, 2697 NoAliasAA)) { 2698 LLVM_DEBUG( 2699 dbgs() << "[AANoAlias] No-Alias deduced via no-alias preservation\n"); 2700 return ChangeStatus::UNCHANGED; 2701 } 2702 2703 return indicatePessimisticFixpoint(); 2704 } 2705 2706 /// See AbstractAttribute::trackStatistics() 2707 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noalias) } 2708 }; 2709 2710 /// NoAlias attribute for function return value. 2711 struct AANoAliasReturned final : AANoAliasImpl { 2712 AANoAliasReturned(const IRPosition &IRP, Attributor &A) 2713 : AANoAliasImpl(IRP, A) {} 2714 2715 /// See AbstractAttribute::initialize(...). 2716 void initialize(Attributor &A) override { 2717 AANoAliasImpl::initialize(A); 2718 Function *F = getAssociatedFunction(); 2719 if (!F || F->isDeclaration()) 2720 indicatePessimisticFixpoint(); 2721 } 2722 2723 /// See AbstractAttribute::updateImpl(...). 2724 virtual ChangeStatus updateImpl(Attributor &A) override { 2725 2726 auto CheckReturnValue = [&](Value &RV) -> bool { 2727 if (Constant *C = dyn_cast<Constant>(&RV)) 2728 if (C->isNullValue() || isa<UndefValue>(C)) 2729 return true; 2730 2731 /// For now, we can only deduce noalias if we have call sites. 2732 /// FIXME: add more support. 2733 if (!isa<CallBase>(&RV)) 2734 return false; 2735 2736 const IRPosition &RVPos = IRPosition::value(RV); 2737 const auto &NoAliasAA = 2738 A.getAAFor<AANoAlias>(*this, RVPos, DepClassTy::REQUIRED); 2739 if (!NoAliasAA.isAssumedNoAlias()) 2740 return false; 2741 2742 const auto &NoCaptureAA = 2743 A.getAAFor<AANoCapture>(*this, RVPos, DepClassTy::REQUIRED); 2744 return NoCaptureAA.isAssumedNoCaptureMaybeReturned(); 2745 }; 2746 2747 if (!A.checkForAllReturnedValues(CheckReturnValue, *this)) 2748 return indicatePessimisticFixpoint(); 2749 2750 return ChangeStatus::UNCHANGED; 2751 } 2752 2753 /// See AbstractAttribute::trackStatistics() 2754 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noalias) } 2755 }; 2756 2757 /// NoAlias attribute deduction for a call site return value. 2758 struct AANoAliasCallSiteReturned final : AANoAliasImpl { 2759 AANoAliasCallSiteReturned(const IRPosition &IRP, Attributor &A) 2760 : AANoAliasImpl(IRP, A) {} 2761 2762 /// See AbstractAttribute::initialize(...). 2763 void initialize(Attributor &A) override { 2764 AANoAliasImpl::initialize(A); 2765 Function *F = getAssociatedFunction(); 2766 if (!F || F->isDeclaration()) 2767 indicatePessimisticFixpoint(); 2768 } 2769 2770 /// See AbstractAttribute::updateImpl(...). 2771 ChangeStatus updateImpl(Attributor &A) override { 2772 // TODO: Once we have call site specific value information we can provide 2773 // call site specific liveness information and then it makes 2774 // sense to specialize attributes for call sites arguments instead of 2775 // redirecting requests to the callee argument. 2776 Function *F = getAssociatedFunction(); 2777 const IRPosition &FnPos = IRPosition::returned(*F); 2778 auto &FnAA = A.getAAFor<AANoAlias>(*this, FnPos, DepClassTy::REQUIRED); 2779 return clampStateAndIndicateChange(getState(), FnAA.getState()); 2780 } 2781 2782 /// See AbstractAttribute::trackStatistics() 2783 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noalias); } 2784 }; 2785 2786 /// -------------------AAIsDead Function Attribute----------------------- 2787 2788 struct AAIsDeadValueImpl : public AAIsDead { 2789 AAIsDeadValueImpl(const IRPosition &IRP, Attributor &A) : AAIsDead(IRP, A) {} 2790 2791 /// See AAIsDead::isAssumedDead(). 2792 bool isAssumedDead() const override { return getAssumed(); } 2793 2794 /// See AAIsDead::isKnownDead(). 2795 bool isKnownDead() const override { return getKnown(); } 2796 2797 /// See AAIsDead::isAssumedDead(BasicBlock *). 2798 bool isAssumedDead(const BasicBlock *BB) const override { return false; } 2799 2800 /// See AAIsDead::isKnownDead(BasicBlock *). 2801 bool isKnownDead(const BasicBlock *BB) const override { return false; } 2802 2803 /// See AAIsDead::isAssumedDead(Instruction *I). 2804 bool isAssumedDead(const Instruction *I) const override { 2805 return I == getCtxI() && isAssumedDead(); 2806 } 2807 2808 /// See AAIsDead::isKnownDead(Instruction *I). 2809 bool isKnownDead(const Instruction *I) const override { 2810 return isAssumedDead(I) && getKnown(); 2811 } 2812 2813 /// See AbstractAttribute::getAsStr(). 2814 const std::string getAsStr() const override { 2815 return isAssumedDead() ? "assumed-dead" : "assumed-live"; 2816 } 2817 2818 /// Check if all uses are assumed dead. 2819 bool areAllUsesAssumedDead(Attributor &A, Value &V) { 2820 auto UsePred = [&](const Use &U, bool &Follow) { return false; }; 2821 // Explicitly set the dependence class to required because we want a long 2822 // chain of N dependent instructions to be considered live as soon as one is 2823 // without going through N update cycles. This is not required for 2824 // correctness. 2825 return A.checkForAllUses(UsePred, *this, V, DepClassTy::REQUIRED); 2826 } 2827 2828 /// Determine if \p I is assumed to be side-effect free. 2829 bool isAssumedSideEffectFree(Attributor &A, Instruction *I) { 2830 if (!I || wouldInstructionBeTriviallyDead(I)) 2831 return true; 2832 2833 auto *CB = dyn_cast<CallBase>(I); 2834 if (!CB || isa<IntrinsicInst>(CB)) 2835 return false; 2836 2837 const IRPosition &CallIRP = IRPosition::callsite_function(*CB); 2838 const auto &NoUnwindAA = 2839 A.getAndUpdateAAFor<AANoUnwind>(*this, CallIRP, DepClassTy::NONE); 2840 if (!NoUnwindAA.isAssumedNoUnwind()) 2841 return false; 2842 if (!NoUnwindAA.isKnownNoUnwind()) 2843 A.recordDependence(NoUnwindAA, *this, DepClassTy::OPTIONAL); 2844 2845 const auto &MemBehaviorAA = 2846 A.getAndUpdateAAFor<AAMemoryBehavior>(*this, CallIRP, DepClassTy::NONE); 2847 if (MemBehaviorAA.isAssumedReadOnly()) { 2848 if (!MemBehaviorAA.isKnownReadOnly()) 2849 A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL); 2850 return true; 2851 } 2852 return false; 2853 } 2854 }; 2855 2856 struct AAIsDeadFloating : public AAIsDeadValueImpl { 2857 AAIsDeadFloating(const IRPosition &IRP, Attributor &A) 2858 : AAIsDeadValueImpl(IRP, A) {} 2859 2860 /// See AbstractAttribute::initialize(...). 2861 void initialize(Attributor &A) override { 2862 if (isa<UndefValue>(getAssociatedValue())) { 2863 indicatePessimisticFixpoint(); 2864 return; 2865 } 2866 2867 Instruction *I = dyn_cast<Instruction>(&getAssociatedValue()); 2868 if (!isAssumedSideEffectFree(A, I)) 2869 indicatePessimisticFixpoint(); 2870 } 2871 2872 /// See AbstractAttribute::updateImpl(...). 2873 ChangeStatus updateImpl(Attributor &A) override { 2874 Instruction *I = dyn_cast<Instruction>(&getAssociatedValue()); 2875 if (!isAssumedSideEffectFree(A, I)) 2876 return indicatePessimisticFixpoint(); 2877 2878 if (!areAllUsesAssumedDead(A, getAssociatedValue())) 2879 return indicatePessimisticFixpoint(); 2880 return ChangeStatus::UNCHANGED; 2881 } 2882 2883 /// See AbstractAttribute::manifest(...). 2884 ChangeStatus manifest(Attributor &A) override { 2885 Value &V = getAssociatedValue(); 2886 if (auto *I = dyn_cast<Instruction>(&V)) { 2887 // If we get here we basically know the users are all dead. We check if 2888 // isAssumedSideEffectFree returns true here again because it might not be 2889 // the case and only the users are dead but the instruction (=call) is 2890 // still needed. 2891 if (isAssumedSideEffectFree(A, I) && !isa<InvokeInst>(I)) { 2892 A.deleteAfterManifest(*I); 2893 return ChangeStatus::CHANGED; 2894 } 2895 } 2896 if (V.use_empty()) 2897 return ChangeStatus::UNCHANGED; 2898 2899 bool UsedAssumedInformation = false; 2900 Optional<Constant *> C = 2901 A.getAssumedConstant(V, *this, UsedAssumedInformation); 2902 if (C.hasValue() && C.getValue()) 2903 return ChangeStatus::UNCHANGED; 2904 2905 // Replace the value with undef as it is dead but keep droppable uses around 2906 // as they provide information we don't want to give up on just yet. 2907 UndefValue &UV = *UndefValue::get(V.getType()); 2908 bool AnyChange = 2909 A.changeValueAfterManifest(V, UV, /* ChangeDropppable */ false); 2910 return AnyChange ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 2911 } 2912 2913 /// See AbstractAttribute::trackStatistics() 2914 void trackStatistics() const override { 2915 STATS_DECLTRACK_FLOATING_ATTR(IsDead) 2916 } 2917 }; 2918 2919 struct AAIsDeadArgument : public AAIsDeadFloating { 2920 AAIsDeadArgument(const IRPosition &IRP, Attributor &A) 2921 : AAIsDeadFloating(IRP, A) {} 2922 2923 /// See AbstractAttribute::initialize(...). 2924 void initialize(Attributor &A) override { 2925 if (!A.isFunctionIPOAmendable(*getAnchorScope())) 2926 indicatePessimisticFixpoint(); 2927 } 2928 2929 /// See AbstractAttribute::manifest(...). 2930 ChangeStatus manifest(Attributor &A) override { 2931 ChangeStatus Changed = AAIsDeadFloating::manifest(A); 2932 Argument &Arg = *getAssociatedArgument(); 2933 if (A.isValidFunctionSignatureRewrite(Arg, /* ReplacementTypes */ {})) 2934 if (A.registerFunctionSignatureRewrite( 2935 Arg, /* ReplacementTypes */ {}, 2936 Attributor::ArgumentReplacementInfo::CalleeRepairCBTy{}, 2937 Attributor::ArgumentReplacementInfo::ACSRepairCBTy{})) { 2938 Arg.dropDroppableUses(); 2939 return ChangeStatus::CHANGED; 2940 } 2941 return Changed; 2942 } 2943 2944 /// See AbstractAttribute::trackStatistics() 2945 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(IsDead) } 2946 }; 2947 2948 struct AAIsDeadCallSiteArgument : public AAIsDeadValueImpl { 2949 AAIsDeadCallSiteArgument(const IRPosition &IRP, Attributor &A) 2950 : AAIsDeadValueImpl(IRP, A) {} 2951 2952 /// See AbstractAttribute::initialize(...). 2953 void initialize(Attributor &A) override { 2954 if (isa<UndefValue>(getAssociatedValue())) 2955 indicatePessimisticFixpoint(); 2956 } 2957 2958 /// See AbstractAttribute::updateImpl(...). 2959 ChangeStatus updateImpl(Attributor &A) override { 2960 // TODO: Once we have call site specific value information we can provide 2961 // call site specific liveness information and then it makes 2962 // sense to specialize attributes for call sites arguments instead of 2963 // redirecting requests to the callee argument. 2964 Argument *Arg = getAssociatedArgument(); 2965 if (!Arg) 2966 return indicatePessimisticFixpoint(); 2967 const IRPosition &ArgPos = IRPosition::argument(*Arg); 2968 auto &ArgAA = A.getAAFor<AAIsDead>(*this, ArgPos, DepClassTy::REQUIRED); 2969 return clampStateAndIndicateChange(getState(), ArgAA.getState()); 2970 } 2971 2972 /// See AbstractAttribute::manifest(...). 2973 ChangeStatus manifest(Attributor &A) override { 2974 CallBase &CB = cast<CallBase>(getAnchorValue()); 2975 Use &U = CB.getArgOperandUse(getCallSiteArgNo()); 2976 assert(!isa<UndefValue>(U.get()) && 2977 "Expected undef values to be filtered out!"); 2978 UndefValue &UV = *UndefValue::get(U->getType()); 2979 if (A.changeUseAfterManifest(U, UV)) 2980 return ChangeStatus::CHANGED; 2981 return ChangeStatus::UNCHANGED; 2982 } 2983 2984 /// See AbstractAttribute::trackStatistics() 2985 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(IsDead) } 2986 }; 2987 2988 struct AAIsDeadCallSiteReturned : public AAIsDeadFloating { 2989 AAIsDeadCallSiteReturned(const IRPosition &IRP, Attributor &A) 2990 : AAIsDeadFloating(IRP, A), IsAssumedSideEffectFree(true) {} 2991 2992 /// See AAIsDead::isAssumedDead(). 2993 bool isAssumedDead() const override { 2994 return AAIsDeadFloating::isAssumedDead() && IsAssumedSideEffectFree; 2995 } 2996 2997 /// See AbstractAttribute::initialize(...). 2998 void initialize(Attributor &A) override { 2999 if (isa<UndefValue>(getAssociatedValue())) { 3000 indicatePessimisticFixpoint(); 3001 return; 3002 } 3003 3004 // We track this separately as a secondary state. 3005 IsAssumedSideEffectFree = isAssumedSideEffectFree(A, getCtxI()); 3006 } 3007 3008 /// See AbstractAttribute::updateImpl(...). 3009 ChangeStatus updateImpl(Attributor &A) override { 3010 ChangeStatus Changed = ChangeStatus::UNCHANGED; 3011 if (IsAssumedSideEffectFree && !isAssumedSideEffectFree(A, getCtxI())) { 3012 IsAssumedSideEffectFree = false; 3013 Changed = ChangeStatus::CHANGED; 3014 } 3015 3016 if (!areAllUsesAssumedDead(A, getAssociatedValue())) 3017 return indicatePessimisticFixpoint(); 3018 return Changed; 3019 } 3020 3021 /// See AbstractAttribute::trackStatistics() 3022 void trackStatistics() const override { 3023 if (IsAssumedSideEffectFree) 3024 STATS_DECLTRACK_CSRET_ATTR(IsDead) 3025 else 3026 STATS_DECLTRACK_CSRET_ATTR(UnusedResult) 3027 } 3028 3029 /// See AbstractAttribute::getAsStr(). 3030 const std::string getAsStr() const override { 3031 return isAssumedDead() 3032 ? "assumed-dead" 3033 : (getAssumed() ? "assumed-dead-users" : "assumed-live"); 3034 } 3035 3036 private: 3037 bool IsAssumedSideEffectFree; 3038 }; 3039 3040 struct AAIsDeadReturned : public AAIsDeadValueImpl { 3041 AAIsDeadReturned(const IRPosition &IRP, Attributor &A) 3042 : AAIsDeadValueImpl(IRP, A) {} 3043 3044 /// See AbstractAttribute::updateImpl(...). 3045 ChangeStatus updateImpl(Attributor &A) override { 3046 3047 A.checkForAllInstructions([](Instruction &) { return true; }, *this, 3048 {Instruction::Ret}); 3049 3050 auto PredForCallSite = [&](AbstractCallSite ACS) { 3051 if (ACS.isCallbackCall() || !ACS.getInstruction()) 3052 return false; 3053 return areAllUsesAssumedDead(A, *ACS.getInstruction()); 3054 }; 3055 3056 bool AllCallSitesKnown; 3057 if (!A.checkForAllCallSites(PredForCallSite, *this, true, 3058 AllCallSitesKnown)) 3059 return indicatePessimisticFixpoint(); 3060 3061 return ChangeStatus::UNCHANGED; 3062 } 3063 3064 /// See AbstractAttribute::manifest(...). 3065 ChangeStatus manifest(Attributor &A) override { 3066 // TODO: Rewrite the signature to return void? 3067 bool AnyChange = false; 3068 UndefValue &UV = *UndefValue::get(getAssociatedFunction()->getReturnType()); 3069 auto RetInstPred = [&](Instruction &I) { 3070 ReturnInst &RI = cast<ReturnInst>(I); 3071 if (!isa<UndefValue>(RI.getReturnValue())) 3072 AnyChange |= A.changeUseAfterManifest(RI.getOperandUse(0), UV); 3073 return true; 3074 }; 3075 A.checkForAllInstructions(RetInstPred, *this, {Instruction::Ret}); 3076 return AnyChange ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 3077 } 3078 3079 /// See AbstractAttribute::trackStatistics() 3080 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(IsDead) } 3081 }; 3082 3083 struct AAIsDeadFunction : public AAIsDead { 3084 AAIsDeadFunction(const IRPosition &IRP, Attributor &A) : AAIsDead(IRP, A) {} 3085 3086 /// See AbstractAttribute::initialize(...). 3087 void initialize(Attributor &A) override { 3088 const Function *F = getAnchorScope(); 3089 if (F && !F->isDeclaration()) { 3090 // We only want to compute liveness once. If the function is not part of 3091 // the SCC, skip it. 3092 if (A.isRunOn(*const_cast<Function *>(F))) { 3093 ToBeExploredFrom.insert(&F->getEntryBlock().front()); 3094 assumeLive(A, F->getEntryBlock()); 3095 } else { 3096 indicatePessimisticFixpoint(); 3097 } 3098 } 3099 } 3100 3101 /// See AbstractAttribute::getAsStr(). 3102 const std::string getAsStr() const override { 3103 return "Live[#BB " + std::to_string(AssumedLiveBlocks.size()) + "/" + 3104 std::to_string(getAnchorScope()->size()) + "][#TBEP " + 3105 std::to_string(ToBeExploredFrom.size()) + "][#KDE " + 3106 std::to_string(KnownDeadEnds.size()) + "]"; 3107 } 3108 3109 /// See AbstractAttribute::manifest(...). 3110 ChangeStatus manifest(Attributor &A) override { 3111 assert(getState().isValidState() && 3112 "Attempted to manifest an invalid state!"); 3113 3114 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 3115 Function &F = *getAnchorScope(); 3116 3117 if (AssumedLiveBlocks.empty()) { 3118 A.deleteAfterManifest(F); 3119 return ChangeStatus::CHANGED; 3120 } 3121 3122 // Flag to determine if we can change an invoke to a call assuming the 3123 // callee is nounwind. This is not possible if the personality of the 3124 // function allows to catch asynchronous exceptions. 3125 bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F); 3126 3127 KnownDeadEnds.set_union(ToBeExploredFrom); 3128 for (const Instruction *DeadEndI : KnownDeadEnds) { 3129 auto *CB = dyn_cast<CallBase>(DeadEndI); 3130 if (!CB) 3131 continue; 3132 const auto &NoReturnAA = A.getAndUpdateAAFor<AANoReturn>( 3133 *this, IRPosition::callsite_function(*CB), DepClassTy::OPTIONAL); 3134 bool MayReturn = !NoReturnAA.isAssumedNoReturn(); 3135 if (MayReturn && (!Invoke2CallAllowed || !isa<InvokeInst>(CB))) 3136 continue; 3137 3138 if (auto *II = dyn_cast<InvokeInst>(DeadEndI)) 3139 A.registerInvokeWithDeadSuccessor(const_cast<InvokeInst &>(*II)); 3140 else 3141 A.changeToUnreachableAfterManifest( 3142 const_cast<Instruction *>(DeadEndI->getNextNode())); 3143 HasChanged = ChangeStatus::CHANGED; 3144 } 3145 3146 STATS_DECL(AAIsDead, BasicBlock, "Number of dead basic blocks deleted."); 3147 for (BasicBlock &BB : F) 3148 if (!AssumedLiveBlocks.count(&BB)) { 3149 A.deleteAfterManifest(BB); 3150 ++BUILD_STAT_NAME(AAIsDead, BasicBlock); 3151 } 3152 3153 return HasChanged; 3154 } 3155 3156 /// See AbstractAttribute::updateImpl(...). 3157 ChangeStatus updateImpl(Attributor &A) override; 3158 3159 bool isEdgeDead(const BasicBlock *From, const BasicBlock *To) const override { 3160 return !AssumedLiveEdges.count(std::make_pair(From, To)); 3161 } 3162 3163 /// See AbstractAttribute::trackStatistics() 3164 void trackStatistics() const override {} 3165 3166 /// Returns true if the function is assumed dead. 3167 bool isAssumedDead() const override { return false; } 3168 3169 /// See AAIsDead::isKnownDead(). 3170 bool isKnownDead() const override { return false; } 3171 3172 /// See AAIsDead::isAssumedDead(BasicBlock *). 3173 bool isAssumedDead(const BasicBlock *BB) const override { 3174 assert(BB->getParent() == getAnchorScope() && 3175 "BB must be in the same anchor scope function."); 3176 3177 if (!getAssumed()) 3178 return false; 3179 return !AssumedLiveBlocks.count(BB); 3180 } 3181 3182 /// See AAIsDead::isKnownDead(BasicBlock *). 3183 bool isKnownDead(const BasicBlock *BB) const override { 3184 return getKnown() && isAssumedDead(BB); 3185 } 3186 3187 /// See AAIsDead::isAssumed(Instruction *I). 3188 bool isAssumedDead(const Instruction *I) const override { 3189 assert(I->getParent()->getParent() == getAnchorScope() && 3190 "Instruction must be in the same anchor scope function."); 3191 3192 if (!getAssumed()) 3193 return false; 3194 3195 // If it is not in AssumedLiveBlocks then it for sure dead. 3196 // Otherwise, it can still be after noreturn call in a live block. 3197 if (!AssumedLiveBlocks.count(I->getParent())) 3198 return true; 3199 3200 // If it is not after a liveness barrier it is live. 3201 const Instruction *PrevI = I->getPrevNode(); 3202 while (PrevI) { 3203 if (KnownDeadEnds.count(PrevI) || ToBeExploredFrom.count(PrevI)) 3204 return true; 3205 PrevI = PrevI->getPrevNode(); 3206 } 3207 return false; 3208 } 3209 3210 /// See AAIsDead::isKnownDead(Instruction *I). 3211 bool isKnownDead(const Instruction *I) const override { 3212 return getKnown() && isAssumedDead(I); 3213 } 3214 3215 /// Assume \p BB is (partially) live now and indicate to the Attributor \p A 3216 /// that internal function called from \p BB should now be looked at. 3217 bool assumeLive(Attributor &A, const BasicBlock &BB) { 3218 if (!AssumedLiveBlocks.insert(&BB).second) 3219 return false; 3220 3221 // We assume that all of BB is (probably) live now and if there are calls to 3222 // internal functions we will assume that those are now live as well. This 3223 // is a performance optimization for blocks with calls to a lot of internal 3224 // functions. It can however cause dead functions to be treated as live. 3225 for (const Instruction &I : BB) 3226 if (const auto *CB = dyn_cast<CallBase>(&I)) 3227 if (const Function *F = CB->getCalledFunction()) 3228 if (F->hasLocalLinkage()) 3229 A.markLiveInternalFunction(*F); 3230 return true; 3231 } 3232 3233 /// Collection of instructions that need to be explored again, e.g., we 3234 /// did assume they do not transfer control to (one of their) successors. 3235 SmallSetVector<const Instruction *, 8> ToBeExploredFrom; 3236 3237 /// Collection of instructions that are known to not transfer control. 3238 SmallSetVector<const Instruction *, 8> KnownDeadEnds; 3239 3240 /// Collection of all assumed live edges 3241 DenseSet<std::pair<const BasicBlock *, const BasicBlock *>> AssumedLiveEdges; 3242 3243 /// Collection of all assumed live BasicBlocks. 3244 DenseSet<const BasicBlock *> AssumedLiveBlocks; 3245 }; 3246 3247 static bool 3248 identifyAliveSuccessors(Attributor &A, const CallBase &CB, 3249 AbstractAttribute &AA, 3250 SmallVectorImpl<const Instruction *> &AliveSuccessors) { 3251 const IRPosition &IPos = IRPosition::callsite_function(CB); 3252 3253 const auto &NoReturnAA = 3254 A.getAndUpdateAAFor<AANoReturn>(AA, IPos, DepClassTy::OPTIONAL); 3255 if (NoReturnAA.isAssumedNoReturn()) 3256 return !NoReturnAA.isKnownNoReturn(); 3257 if (CB.isTerminator()) 3258 AliveSuccessors.push_back(&CB.getSuccessor(0)->front()); 3259 else 3260 AliveSuccessors.push_back(CB.getNextNode()); 3261 return false; 3262 } 3263 3264 static bool 3265 identifyAliveSuccessors(Attributor &A, const InvokeInst &II, 3266 AbstractAttribute &AA, 3267 SmallVectorImpl<const Instruction *> &AliveSuccessors) { 3268 bool UsedAssumedInformation = 3269 identifyAliveSuccessors(A, cast<CallBase>(II), AA, AliveSuccessors); 3270 3271 // First, determine if we can change an invoke to a call assuming the 3272 // callee is nounwind. This is not possible if the personality of the 3273 // function allows to catch asynchronous exceptions. 3274 if (AAIsDeadFunction::mayCatchAsynchronousExceptions(*II.getFunction())) { 3275 AliveSuccessors.push_back(&II.getUnwindDest()->front()); 3276 } else { 3277 const IRPosition &IPos = IRPosition::callsite_function(II); 3278 const auto &AANoUnw = 3279 A.getAndUpdateAAFor<AANoUnwind>(AA, IPos, DepClassTy::OPTIONAL); 3280 if (AANoUnw.isAssumedNoUnwind()) { 3281 UsedAssumedInformation |= !AANoUnw.isKnownNoUnwind(); 3282 } else { 3283 AliveSuccessors.push_back(&II.getUnwindDest()->front()); 3284 } 3285 } 3286 return UsedAssumedInformation; 3287 } 3288 3289 static bool 3290 identifyAliveSuccessors(Attributor &A, const BranchInst &BI, 3291 AbstractAttribute &AA, 3292 SmallVectorImpl<const Instruction *> &AliveSuccessors) { 3293 bool UsedAssumedInformation = false; 3294 if (BI.getNumSuccessors() == 1) { 3295 AliveSuccessors.push_back(&BI.getSuccessor(0)->front()); 3296 } else { 3297 Optional<Constant *> C = 3298 A.getAssumedConstant(*BI.getCondition(), AA, UsedAssumedInformation); 3299 if (!C.hasValue() || isa_and_nonnull<UndefValue>(C.getValue())) { 3300 // No value yet, assume both edges are dead. 3301 } else if (isa_and_nonnull<ConstantInt>(*C)) { 3302 const BasicBlock *SuccBB = 3303 BI.getSuccessor(1 - cast<ConstantInt>(*C)->getValue().getZExtValue()); 3304 AliveSuccessors.push_back(&SuccBB->front()); 3305 } else { 3306 AliveSuccessors.push_back(&BI.getSuccessor(0)->front()); 3307 AliveSuccessors.push_back(&BI.getSuccessor(1)->front()); 3308 UsedAssumedInformation = false; 3309 } 3310 } 3311 return UsedAssumedInformation; 3312 } 3313 3314 static bool 3315 identifyAliveSuccessors(Attributor &A, const SwitchInst &SI, 3316 AbstractAttribute &AA, 3317 SmallVectorImpl<const Instruction *> &AliveSuccessors) { 3318 bool UsedAssumedInformation = false; 3319 Optional<Constant *> C = 3320 A.getAssumedConstant(*SI.getCondition(), AA, UsedAssumedInformation); 3321 if (!C.hasValue() || isa_and_nonnull<UndefValue>(C.getValue())) { 3322 // No value yet, assume all edges are dead. 3323 } else if (isa_and_nonnull<ConstantInt>(C.getValue())) { 3324 for (auto &CaseIt : SI.cases()) { 3325 if (CaseIt.getCaseValue() == C.getValue()) { 3326 AliveSuccessors.push_back(&CaseIt.getCaseSuccessor()->front()); 3327 return UsedAssumedInformation; 3328 } 3329 } 3330 AliveSuccessors.push_back(&SI.getDefaultDest()->front()); 3331 return UsedAssumedInformation; 3332 } else { 3333 for (const BasicBlock *SuccBB : successors(SI.getParent())) 3334 AliveSuccessors.push_back(&SuccBB->front()); 3335 } 3336 return UsedAssumedInformation; 3337 } 3338 3339 ChangeStatus AAIsDeadFunction::updateImpl(Attributor &A) { 3340 ChangeStatus Change = ChangeStatus::UNCHANGED; 3341 3342 LLVM_DEBUG(dbgs() << "[AAIsDead] Live [" << AssumedLiveBlocks.size() << "/" 3343 << getAnchorScope()->size() << "] BBs and " 3344 << ToBeExploredFrom.size() << " exploration points and " 3345 << KnownDeadEnds.size() << " known dead ends\n"); 3346 3347 // Copy and clear the list of instructions we need to explore from. It is 3348 // refilled with instructions the next update has to look at. 3349 SmallVector<const Instruction *, 8> Worklist(ToBeExploredFrom.begin(), 3350 ToBeExploredFrom.end()); 3351 decltype(ToBeExploredFrom) NewToBeExploredFrom; 3352 3353 SmallVector<const Instruction *, 8> AliveSuccessors; 3354 while (!Worklist.empty()) { 3355 const Instruction *I = Worklist.pop_back_val(); 3356 LLVM_DEBUG(dbgs() << "[AAIsDead] Exploration inst: " << *I << "\n"); 3357 3358 // Fast forward for uninteresting instructions. We could look for UB here 3359 // though. 3360 while (!I->isTerminator() && !isa<CallBase>(I)) { 3361 Change = ChangeStatus::CHANGED; 3362 I = I->getNextNode(); 3363 } 3364 3365 AliveSuccessors.clear(); 3366 3367 bool UsedAssumedInformation = false; 3368 switch (I->getOpcode()) { 3369 // TODO: look for (assumed) UB to backwards propagate "deadness". 3370 default: 3371 assert(I->isTerminator() && 3372 "Expected non-terminators to be handled already!"); 3373 for (const BasicBlock *SuccBB : successors(I->getParent())) 3374 AliveSuccessors.push_back(&SuccBB->front()); 3375 break; 3376 case Instruction::Call: 3377 UsedAssumedInformation = identifyAliveSuccessors(A, cast<CallInst>(*I), 3378 *this, AliveSuccessors); 3379 break; 3380 case Instruction::Invoke: 3381 UsedAssumedInformation = identifyAliveSuccessors(A, cast<InvokeInst>(*I), 3382 *this, AliveSuccessors); 3383 break; 3384 case Instruction::Br: 3385 UsedAssumedInformation = identifyAliveSuccessors(A, cast<BranchInst>(*I), 3386 *this, AliveSuccessors); 3387 break; 3388 case Instruction::Switch: 3389 UsedAssumedInformation = identifyAliveSuccessors(A, cast<SwitchInst>(*I), 3390 *this, AliveSuccessors); 3391 break; 3392 } 3393 3394 if (UsedAssumedInformation) { 3395 NewToBeExploredFrom.insert(I); 3396 } else { 3397 Change = ChangeStatus::CHANGED; 3398 if (AliveSuccessors.empty() || 3399 (I->isTerminator() && AliveSuccessors.size() < I->getNumSuccessors())) 3400 KnownDeadEnds.insert(I); 3401 } 3402 3403 LLVM_DEBUG(dbgs() << "[AAIsDead] #AliveSuccessors: " 3404 << AliveSuccessors.size() << " UsedAssumedInformation: " 3405 << UsedAssumedInformation << "\n"); 3406 3407 for (const Instruction *AliveSuccessor : AliveSuccessors) { 3408 if (!I->isTerminator()) { 3409 assert(AliveSuccessors.size() == 1 && 3410 "Non-terminator expected to have a single successor!"); 3411 Worklist.push_back(AliveSuccessor); 3412 } else { 3413 // record the assumed live edge 3414 AssumedLiveEdges.insert( 3415 std::make_pair(I->getParent(), AliveSuccessor->getParent())); 3416 if (assumeLive(A, *AliveSuccessor->getParent())) 3417 Worklist.push_back(AliveSuccessor); 3418 } 3419 } 3420 } 3421 3422 ToBeExploredFrom = std::move(NewToBeExploredFrom); 3423 3424 // If we know everything is live there is no need to query for liveness. 3425 // Instead, indicating a pessimistic fixpoint will cause the state to be 3426 // "invalid" and all queries to be answered conservatively without lookups. 3427 // To be in this state we have to (1) finished the exploration and (3) not 3428 // discovered any non-trivial dead end and (2) not ruled unreachable code 3429 // dead. 3430 if (ToBeExploredFrom.empty() && 3431 getAnchorScope()->size() == AssumedLiveBlocks.size() && 3432 llvm::all_of(KnownDeadEnds, [](const Instruction *DeadEndI) { 3433 return DeadEndI->isTerminator() && DeadEndI->getNumSuccessors() == 0; 3434 })) 3435 return indicatePessimisticFixpoint(); 3436 return Change; 3437 } 3438 3439 /// Liveness information for a call sites. 3440 struct AAIsDeadCallSite final : AAIsDeadFunction { 3441 AAIsDeadCallSite(const IRPosition &IRP, Attributor &A) 3442 : AAIsDeadFunction(IRP, A) {} 3443 3444 /// See AbstractAttribute::initialize(...). 3445 void initialize(Attributor &A) override { 3446 // TODO: Once we have call site specific value information we can provide 3447 // call site specific liveness information and then it makes 3448 // sense to specialize attributes for call sites instead of 3449 // redirecting requests to the callee. 3450 llvm_unreachable("Abstract attributes for liveness are not " 3451 "supported for call sites yet!"); 3452 } 3453 3454 /// See AbstractAttribute::updateImpl(...). 3455 ChangeStatus updateImpl(Attributor &A) override { 3456 return indicatePessimisticFixpoint(); 3457 } 3458 3459 /// See AbstractAttribute::trackStatistics() 3460 void trackStatistics() const override {} 3461 }; 3462 3463 /// -------------------- Dereferenceable Argument Attribute -------------------- 3464 3465 template <> 3466 ChangeStatus clampStateAndIndicateChange<DerefState>(DerefState &S, 3467 const DerefState &R) { 3468 ChangeStatus CS0 = 3469 clampStateAndIndicateChange(S.DerefBytesState, R.DerefBytesState); 3470 ChangeStatus CS1 = clampStateAndIndicateChange(S.GlobalState, R.GlobalState); 3471 return CS0 | CS1; 3472 } 3473 3474 struct AADereferenceableImpl : AADereferenceable { 3475 AADereferenceableImpl(const IRPosition &IRP, Attributor &A) 3476 : AADereferenceable(IRP, A) {} 3477 using StateType = DerefState; 3478 3479 /// See AbstractAttribute::initialize(...). 3480 void initialize(Attributor &A) override { 3481 SmallVector<Attribute, 4> Attrs; 3482 getAttrs({Attribute::Dereferenceable, Attribute::DereferenceableOrNull}, 3483 Attrs, /* IgnoreSubsumingPositions */ false, &A); 3484 for (const Attribute &Attr : Attrs) 3485 takeKnownDerefBytesMaximum(Attr.getValueAsInt()); 3486 3487 const IRPosition &IRP = this->getIRPosition(); 3488 NonNullAA = &A.getAAFor<AANonNull>(*this, IRP, DepClassTy::NONE); 3489 3490 bool CanBeNull, CanBeFreed; 3491 takeKnownDerefBytesMaximum( 3492 IRP.getAssociatedValue().getPointerDereferenceableBytes( 3493 A.getDataLayout(), CanBeNull, CanBeFreed)); 3494 3495 bool IsFnInterface = IRP.isFnInterfaceKind(); 3496 Function *FnScope = IRP.getAnchorScope(); 3497 if (IsFnInterface && (!FnScope || !A.isFunctionIPOAmendable(*FnScope))) { 3498 indicatePessimisticFixpoint(); 3499 return; 3500 } 3501 3502 if (Instruction *CtxI = getCtxI()) 3503 followUsesInMBEC(*this, A, getState(), *CtxI); 3504 } 3505 3506 /// See AbstractAttribute::getState() 3507 /// { 3508 StateType &getState() override { return *this; } 3509 const StateType &getState() const override { return *this; } 3510 /// } 3511 3512 /// Helper function for collecting accessed bytes in must-be-executed-context 3513 void addAccessedBytesForUse(Attributor &A, const Use *U, const Instruction *I, 3514 DerefState &State) { 3515 const Value *UseV = U->get(); 3516 if (!UseV->getType()->isPointerTy()) 3517 return; 3518 3519 Type *PtrTy = UseV->getType(); 3520 const DataLayout &DL = A.getDataLayout(); 3521 int64_t Offset; 3522 if (const Value *Base = getBasePointerOfAccessPointerOperand( 3523 I, Offset, DL, /*AllowNonInbounds*/ true)) { 3524 if (Base == &getAssociatedValue() && 3525 getPointerOperand(I, /* AllowVolatile */ false) == UseV) { 3526 uint64_t Size = DL.getTypeStoreSize(PtrTy->getPointerElementType()); 3527 State.addAccessedBytes(Offset, Size); 3528 } 3529 } 3530 } 3531 3532 /// See followUsesInMBEC 3533 bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I, 3534 AADereferenceable::StateType &State) { 3535 bool IsNonNull = false; 3536 bool TrackUse = false; 3537 int64_t DerefBytes = getKnownNonNullAndDerefBytesForUse( 3538 A, *this, getAssociatedValue(), U, I, IsNonNull, TrackUse); 3539 LLVM_DEBUG(dbgs() << "[AADereferenceable] Deref bytes: " << DerefBytes 3540 << " for instruction " << *I << "\n"); 3541 3542 addAccessedBytesForUse(A, U, I, State); 3543 State.takeKnownDerefBytesMaximum(DerefBytes); 3544 return TrackUse; 3545 } 3546 3547 /// See AbstractAttribute::manifest(...). 3548 ChangeStatus manifest(Attributor &A) override { 3549 ChangeStatus Change = AADereferenceable::manifest(A); 3550 if (isAssumedNonNull() && hasAttr(Attribute::DereferenceableOrNull)) { 3551 removeAttrs({Attribute::DereferenceableOrNull}); 3552 return ChangeStatus::CHANGED; 3553 } 3554 return Change; 3555 } 3556 3557 void getDeducedAttributes(LLVMContext &Ctx, 3558 SmallVectorImpl<Attribute> &Attrs) const override { 3559 // TODO: Add *_globally support 3560 if (isAssumedNonNull()) 3561 Attrs.emplace_back(Attribute::getWithDereferenceableBytes( 3562 Ctx, getAssumedDereferenceableBytes())); 3563 else 3564 Attrs.emplace_back(Attribute::getWithDereferenceableOrNullBytes( 3565 Ctx, getAssumedDereferenceableBytes())); 3566 } 3567 3568 /// See AbstractAttribute::getAsStr(). 3569 const std::string getAsStr() const override { 3570 if (!getAssumedDereferenceableBytes()) 3571 return "unknown-dereferenceable"; 3572 return std::string("dereferenceable") + 3573 (isAssumedNonNull() ? "" : "_or_null") + 3574 (isAssumedGlobal() ? "_globally" : "") + "<" + 3575 std::to_string(getKnownDereferenceableBytes()) + "-" + 3576 std::to_string(getAssumedDereferenceableBytes()) + ">"; 3577 } 3578 }; 3579 3580 /// Dereferenceable attribute for a floating value. 3581 struct AADereferenceableFloating : AADereferenceableImpl { 3582 AADereferenceableFloating(const IRPosition &IRP, Attributor &A) 3583 : AADereferenceableImpl(IRP, A) {} 3584 3585 /// See AbstractAttribute::updateImpl(...). 3586 ChangeStatus updateImpl(Attributor &A) override { 3587 const DataLayout &DL = A.getDataLayout(); 3588 3589 auto VisitValueCB = [&](const Value &V, const Instruction *, DerefState &T, 3590 bool Stripped) -> bool { 3591 unsigned IdxWidth = 3592 DL.getIndexSizeInBits(V.getType()->getPointerAddressSpace()); 3593 APInt Offset(IdxWidth, 0); 3594 const Value *Base = 3595 stripAndAccumulateMinimalOffsets(A, *this, &V, DL, Offset, false); 3596 3597 const auto &AA = A.getAAFor<AADereferenceable>( 3598 *this, IRPosition::value(*Base), DepClassTy::REQUIRED); 3599 int64_t DerefBytes = 0; 3600 if (!Stripped && this == &AA) { 3601 // Use IR information if we did not strip anything. 3602 // TODO: track globally. 3603 bool CanBeNull, CanBeFreed; 3604 DerefBytes = 3605 Base->getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed); 3606 T.GlobalState.indicatePessimisticFixpoint(); 3607 } else { 3608 const DerefState &DS = AA.getState(); 3609 DerefBytes = DS.DerefBytesState.getAssumed(); 3610 T.GlobalState &= DS.GlobalState; 3611 } 3612 3613 // For now we do not try to "increase" dereferenceability due to negative 3614 // indices as we first have to come up with code to deal with loops and 3615 // for overflows of the dereferenceable bytes. 3616 int64_t OffsetSExt = Offset.getSExtValue(); 3617 if (OffsetSExt < 0) 3618 OffsetSExt = 0; 3619 3620 T.takeAssumedDerefBytesMinimum( 3621 std::max(int64_t(0), DerefBytes - OffsetSExt)); 3622 3623 if (this == &AA) { 3624 if (!Stripped) { 3625 // If nothing was stripped IR information is all we got. 3626 T.takeKnownDerefBytesMaximum( 3627 std::max(int64_t(0), DerefBytes - OffsetSExt)); 3628 T.indicatePessimisticFixpoint(); 3629 } else if (OffsetSExt > 0) { 3630 // If something was stripped but there is circular reasoning we look 3631 // for the offset. If it is positive we basically decrease the 3632 // dereferenceable bytes in a circluar loop now, which will simply 3633 // drive them down to the known value in a very slow way which we 3634 // can accelerate. 3635 T.indicatePessimisticFixpoint(); 3636 } 3637 } 3638 3639 return T.isValidState(); 3640 }; 3641 3642 DerefState T; 3643 if (!genericValueTraversal<AADereferenceable, DerefState>( 3644 A, getIRPosition(), *this, T, VisitValueCB, getCtxI())) 3645 return indicatePessimisticFixpoint(); 3646 3647 return clampStateAndIndicateChange(getState(), T); 3648 } 3649 3650 /// See AbstractAttribute::trackStatistics() 3651 void trackStatistics() const override { 3652 STATS_DECLTRACK_FLOATING_ATTR(dereferenceable) 3653 } 3654 }; 3655 3656 /// Dereferenceable attribute for a return value. 3657 struct AADereferenceableReturned final 3658 : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl> { 3659 AADereferenceableReturned(const IRPosition &IRP, Attributor &A) 3660 : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl>( 3661 IRP, A) {} 3662 3663 /// See AbstractAttribute::trackStatistics() 3664 void trackStatistics() const override { 3665 STATS_DECLTRACK_FNRET_ATTR(dereferenceable) 3666 } 3667 }; 3668 3669 /// Dereferenceable attribute for an argument 3670 struct AADereferenceableArgument final 3671 : AAArgumentFromCallSiteArguments<AADereferenceable, 3672 AADereferenceableImpl> { 3673 using Base = 3674 AAArgumentFromCallSiteArguments<AADereferenceable, AADereferenceableImpl>; 3675 AADereferenceableArgument(const IRPosition &IRP, Attributor &A) 3676 : Base(IRP, A) {} 3677 3678 /// See AbstractAttribute::trackStatistics() 3679 void trackStatistics() const override { 3680 STATS_DECLTRACK_ARG_ATTR(dereferenceable) 3681 } 3682 }; 3683 3684 /// Dereferenceable attribute for a call site argument. 3685 struct AADereferenceableCallSiteArgument final : AADereferenceableFloating { 3686 AADereferenceableCallSiteArgument(const IRPosition &IRP, Attributor &A) 3687 : AADereferenceableFloating(IRP, A) {} 3688 3689 /// See AbstractAttribute::trackStatistics() 3690 void trackStatistics() const override { 3691 STATS_DECLTRACK_CSARG_ATTR(dereferenceable) 3692 } 3693 }; 3694 3695 /// Dereferenceable attribute deduction for a call site return value. 3696 struct AADereferenceableCallSiteReturned final 3697 : AACallSiteReturnedFromReturned<AADereferenceable, AADereferenceableImpl> { 3698 using Base = 3699 AACallSiteReturnedFromReturned<AADereferenceable, AADereferenceableImpl>; 3700 AADereferenceableCallSiteReturned(const IRPosition &IRP, Attributor &A) 3701 : Base(IRP, A) {} 3702 3703 /// See AbstractAttribute::trackStatistics() 3704 void trackStatistics() const override { 3705 STATS_DECLTRACK_CS_ATTR(dereferenceable); 3706 } 3707 }; 3708 3709 // ------------------------ Align Argument Attribute ------------------------ 3710 3711 static unsigned getKnownAlignForUse(Attributor &A, AAAlign &QueryingAA, 3712 Value &AssociatedValue, const Use *U, 3713 const Instruction *I, bool &TrackUse) { 3714 // We need to follow common pointer manipulation uses to the accesses they 3715 // feed into. 3716 if (isa<CastInst>(I)) { 3717 // Follow all but ptr2int casts. 3718 TrackUse = !isa<PtrToIntInst>(I); 3719 return 0; 3720 } 3721 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) { 3722 if (GEP->hasAllConstantIndices()) 3723 TrackUse = true; 3724 return 0; 3725 } 3726 3727 MaybeAlign MA; 3728 if (const auto *CB = dyn_cast<CallBase>(I)) { 3729 if (CB->isBundleOperand(U) || CB->isCallee(U)) 3730 return 0; 3731 3732 unsigned ArgNo = CB->getArgOperandNo(U); 3733 IRPosition IRP = IRPosition::callsite_argument(*CB, ArgNo); 3734 // As long as we only use known information there is no need to track 3735 // dependences here. 3736 auto &AlignAA = A.getAAFor<AAAlign>(QueryingAA, IRP, DepClassTy::NONE); 3737 MA = MaybeAlign(AlignAA.getKnownAlign()); 3738 } 3739 3740 const DataLayout &DL = A.getDataLayout(); 3741 const Value *UseV = U->get(); 3742 if (auto *SI = dyn_cast<StoreInst>(I)) { 3743 if (SI->getPointerOperand() == UseV) 3744 MA = SI->getAlign(); 3745 } else if (auto *LI = dyn_cast<LoadInst>(I)) { 3746 if (LI->getPointerOperand() == UseV) 3747 MA = LI->getAlign(); 3748 } 3749 3750 if (!MA || *MA <= QueryingAA.getKnownAlign()) 3751 return 0; 3752 3753 unsigned Alignment = MA->value(); 3754 int64_t Offset; 3755 3756 if (const Value *Base = GetPointerBaseWithConstantOffset(UseV, Offset, DL)) { 3757 if (Base == &AssociatedValue) { 3758 // BasePointerAddr + Offset = Alignment * Q for some integer Q. 3759 // So we can say that the maximum power of two which is a divisor of 3760 // gcd(Offset, Alignment) is an alignment. 3761 3762 uint32_t gcd = 3763 greatestCommonDivisor(uint32_t(abs((int32_t)Offset)), Alignment); 3764 Alignment = llvm::PowerOf2Floor(gcd); 3765 } 3766 } 3767 3768 return Alignment; 3769 } 3770 3771 struct AAAlignImpl : AAAlign { 3772 AAAlignImpl(const IRPosition &IRP, Attributor &A) : AAAlign(IRP, A) {} 3773 3774 /// See AbstractAttribute::initialize(...). 3775 void initialize(Attributor &A) override { 3776 SmallVector<Attribute, 4> Attrs; 3777 getAttrs({Attribute::Alignment}, Attrs); 3778 for (const Attribute &Attr : Attrs) 3779 takeKnownMaximum(Attr.getValueAsInt()); 3780 3781 Value &V = getAssociatedValue(); 3782 // TODO: This is a HACK to avoid getPointerAlignment to introduce a ptr2int 3783 // use of the function pointer. This was caused by D73131. We want to 3784 // avoid this for function pointers especially because we iterate 3785 // their uses and int2ptr is not handled. It is not a correctness 3786 // problem though! 3787 if (!V.getType()->getPointerElementType()->isFunctionTy()) 3788 takeKnownMaximum(V.getPointerAlignment(A.getDataLayout()).value()); 3789 3790 if (getIRPosition().isFnInterfaceKind() && 3791 (!getAnchorScope() || 3792 !A.isFunctionIPOAmendable(*getAssociatedFunction()))) { 3793 indicatePessimisticFixpoint(); 3794 return; 3795 } 3796 3797 if (Instruction *CtxI = getCtxI()) 3798 followUsesInMBEC(*this, A, getState(), *CtxI); 3799 } 3800 3801 /// See AbstractAttribute::manifest(...). 3802 ChangeStatus manifest(Attributor &A) override { 3803 ChangeStatus LoadStoreChanged = ChangeStatus::UNCHANGED; 3804 3805 // Check for users that allow alignment annotations. 3806 Value &AssociatedValue = getAssociatedValue(); 3807 for (const Use &U : AssociatedValue.uses()) { 3808 if (auto *SI = dyn_cast<StoreInst>(U.getUser())) { 3809 if (SI->getPointerOperand() == &AssociatedValue) 3810 if (SI->getAlignment() < getAssumedAlign()) { 3811 STATS_DECLTRACK(AAAlign, Store, 3812 "Number of times alignment added to a store"); 3813 SI->setAlignment(Align(getAssumedAlign())); 3814 LoadStoreChanged = ChangeStatus::CHANGED; 3815 } 3816 } else if (auto *LI = dyn_cast<LoadInst>(U.getUser())) { 3817 if (LI->getPointerOperand() == &AssociatedValue) 3818 if (LI->getAlignment() < getAssumedAlign()) { 3819 LI->setAlignment(Align(getAssumedAlign())); 3820 STATS_DECLTRACK(AAAlign, Load, 3821 "Number of times alignment added to a load"); 3822 LoadStoreChanged = ChangeStatus::CHANGED; 3823 } 3824 } 3825 } 3826 3827 ChangeStatus Changed = AAAlign::manifest(A); 3828 3829 Align InheritAlign = 3830 getAssociatedValue().getPointerAlignment(A.getDataLayout()); 3831 if (InheritAlign >= getAssumedAlign()) 3832 return LoadStoreChanged; 3833 return Changed | LoadStoreChanged; 3834 } 3835 3836 // TODO: Provide a helper to determine the implied ABI alignment and check in 3837 // the existing manifest method and a new one for AAAlignImpl that value 3838 // to avoid making the alignment explicit if it did not improve. 3839 3840 /// See AbstractAttribute::getDeducedAttributes 3841 virtual void 3842 getDeducedAttributes(LLVMContext &Ctx, 3843 SmallVectorImpl<Attribute> &Attrs) const override { 3844 if (getAssumedAlign() > 1) 3845 Attrs.emplace_back( 3846 Attribute::getWithAlignment(Ctx, Align(getAssumedAlign()))); 3847 } 3848 3849 /// See followUsesInMBEC 3850 bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I, 3851 AAAlign::StateType &State) { 3852 bool TrackUse = false; 3853 3854 unsigned int KnownAlign = 3855 getKnownAlignForUse(A, *this, getAssociatedValue(), U, I, TrackUse); 3856 State.takeKnownMaximum(KnownAlign); 3857 3858 return TrackUse; 3859 } 3860 3861 /// See AbstractAttribute::getAsStr(). 3862 const std::string getAsStr() const override { 3863 return getAssumedAlign() ? ("align<" + std::to_string(getKnownAlign()) + 3864 "-" + std::to_string(getAssumedAlign()) + ">") 3865 : "unknown-align"; 3866 } 3867 }; 3868 3869 /// Align attribute for a floating value. 3870 struct AAAlignFloating : AAAlignImpl { 3871 AAAlignFloating(const IRPosition &IRP, Attributor &A) : AAAlignImpl(IRP, A) {} 3872 3873 /// See AbstractAttribute::updateImpl(...). 3874 ChangeStatus updateImpl(Attributor &A) override { 3875 const DataLayout &DL = A.getDataLayout(); 3876 3877 auto VisitValueCB = [&](Value &V, const Instruction *, 3878 AAAlign::StateType &T, bool Stripped) -> bool { 3879 const auto &AA = A.getAAFor<AAAlign>(*this, IRPosition::value(V), 3880 DepClassTy::REQUIRED); 3881 if (!Stripped && this == &AA) { 3882 int64_t Offset; 3883 unsigned Alignment = 1; 3884 if (const Value *Base = 3885 GetPointerBaseWithConstantOffset(&V, Offset, DL)) { 3886 Align PA = Base->getPointerAlignment(DL); 3887 // BasePointerAddr + Offset = Alignment * Q for some integer Q. 3888 // So we can say that the maximum power of two which is a divisor of 3889 // gcd(Offset, Alignment) is an alignment. 3890 3891 uint32_t gcd = greatestCommonDivisor(uint32_t(abs((int32_t)Offset)), 3892 uint32_t(PA.value())); 3893 Alignment = llvm::PowerOf2Floor(gcd); 3894 } else { 3895 Alignment = V.getPointerAlignment(DL).value(); 3896 } 3897 // Use only IR information if we did not strip anything. 3898 T.takeKnownMaximum(Alignment); 3899 T.indicatePessimisticFixpoint(); 3900 } else { 3901 // Use abstract attribute information. 3902 const AAAlign::StateType &DS = AA.getState(); 3903 T ^= DS; 3904 } 3905 return T.isValidState(); 3906 }; 3907 3908 StateType T; 3909 if (!genericValueTraversal<AAAlign, StateType>(A, getIRPosition(), *this, T, 3910 VisitValueCB, getCtxI())) 3911 return indicatePessimisticFixpoint(); 3912 3913 // TODO: If we know we visited all incoming values, thus no are assumed 3914 // dead, we can take the known information from the state T. 3915 return clampStateAndIndicateChange(getState(), T); 3916 } 3917 3918 /// See AbstractAttribute::trackStatistics() 3919 void trackStatistics() const override { STATS_DECLTRACK_FLOATING_ATTR(align) } 3920 }; 3921 3922 /// Align attribute for function return value. 3923 struct AAAlignReturned final 3924 : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl> { 3925 using Base = AAReturnedFromReturnedValues<AAAlign, AAAlignImpl>; 3926 AAAlignReturned(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {} 3927 3928 /// See AbstractAttribute::initialize(...). 3929 void initialize(Attributor &A) override { 3930 Base::initialize(A); 3931 Function *F = getAssociatedFunction(); 3932 if (!F || F->isDeclaration()) 3933 indicatePessimisticFixpoint(); 3934 } 3935 3936 /// See AbstractAttribute::trackStatistics() 3937 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(aligned) } 3938 }; 3939 3940 /// Align attribute for function argument. 3941 struct AAAlignArgument final 3942 : AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl> { 3943 using Base = AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl>; 3944 AAAlignArgument(const IRPosition &IRP, Attributor &A) : Base(IRP, A) {} 3945 3946 /// See AbstractAttribute::manifest(...). 3947 ChangeStatus manifest(Attributor &A) override { 3948 // If the associated argument is involved in a must-tail call we give up 3949 // because we would need to keep the argument alignments of caller and 3950 // callee in-sync. Just does not seem worth the trouble right now. 3951 if (A.getInfoCache().isInvolvedInMustTailCall(*getAssociatedArgument())) 3952 return ChangeStatus::UNCHANGED; 3953 return Base::manifest(A); 3954 } 3955 3956 /// See AbstractAttribute::trackStatistics() 3957 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(aligned) } 3958 }; 3959 3960 struct AAAlignCallSiteArgument final : AAAlignFloating { 3961 AAAlignCallSiteArgument(const IRPosition &IRP, Attributor &A) 3962 : AAAlignFloating(IRP, A) {} 3963 3964 /// See AbstractAttribute::manifest(...). 3965 ChangeStatus manifest(Attributor &A) override { 3966 // If the associated argument is involved in a must-tail call we give up 3967 // because we would need to keep the argument alignments of caller and 3968 // callee in-sync. Just does not seem worth the trouble right now. 3969 if (Argument *Arg = getAssociatedArgument()) 3970 if (A.getInfoCache().isInvolvedInMustTailCall(*Arg)) 3971 return ChangeStatus::UNCHANGED; 3972 ChangeStatus Changed = AAAlignImpl::manifest(A); 3973 Align InheritAlign = 3974 getAssociatedValue().getPointerAlignment(A.getDataLayout()); 3975 if (InheritAlign >= getAssumedAlign()) 3976 Changed = ChangeStatus::UNCHANGED; 3977 return Changed; 3978 } 3979 3980 /// See AbstractAttribute::updateImpl(Attributor &A). 3981 ChangeStatus updateImpl(Attributor &A) override { 3982 ChangeStatus Changed = AAAlignFloating::updateImpl(A); 3983 if (Argument *Arg = getAssociatedArgument()) { 3984 // We only take known information from the argument 3985 // so we do not need to track a dependence. 3986 const auto &ArgAlignAA = A.getAAFor<AAAlign>( 3987 *this, IRPosition::argument(*Arg), DepClassTy::NONE); 3988 takeKnownMaximum(ArgAlignAA.getKnownAlign()); 3989 } 3990 return Changed; 3991 } 3992 3993 /// See AbstractAttribute::trackStatistics() 3994 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(aligned) } 3995 }; 3996 3997 /// Align attribute deduction for a call site return value. 3998 struct AAAlignCallSiteReturned final 3999 : AACallSiteReturnedFromReturned<AAAlign, AAAlignImpl> { 4000 using Base = AACallSiteReturnedFromReturned<AAAlign, AAAlignImpl>; 4001 AAAlignCallSiteReturned(const IRPosition &IRP, Attributor &A) 4002 : Base(IRP, A) {} 4003 4004 /// See AbstractAttribute::initialize(...). 4005 void initialize(Attributor &A) override { 4006 Base::initialize(A); 4007 Function *F = getAssociatedFunction(); 4008 if (!F || F->isDeclaration()) 4009 indicatePessimisticFixpoint(); 4010 } 4011 4012 /// See AbstractAttribute::trackStatistics() 4013 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(align); } 4014 }; 4015 4016 /// ------------------ Function No-Return Attribute ---------------------------- 4017 struct AANoReturnImpl : public AANoReturn { 4018 AANoReturnImpl(const IRPosition &IRP, Attributor &A) : AANoReturn(IRP, A) {} 4019 4020 /// See AbstractAttribute::initialize(...). 4021 void initialize(Attributor &A) override { 4022 AANoReturn::initialize(A); 4023 Function *F = getAssociatedFunction(); 4024 if (!F || F->isDeclaration()) 4025 indicatePessimisticFixpoint(); 4026 } 4027 4028 /// See AbstractAttribute::getAsStr(). 4029 const std::string getAsStr() const override { 4030 return getAssumed() ? "noreturn" : "may-return"; 4031 } 4032 4033 /// See AbstractAttribute::updateImpl(Attributor &A). 4034 virtual ChangeStatus updateImpl(Attributor &A) override { 4035 auto CheckForNoReturn = [](Instruction &) { return false; }; 4036 if (!A.checkForAllInstructions(CheckForNoReturn, *this, 4037 {(unsigned)Instruction::Ret})) 4038 return indicatePessimisticFixpoint(); 4039 return ChangeStatus::UNCHANGED; 4040 } 4041 }; 4042 4043 struct AANoReturnFunction final : AANoReturnImpl { 4044 AANoReturnFunction(const IRPosition &IRP, Attributor &A) 4045 : AANoReturnImpl(IRP, A) {} 4046 4047 /// See AbstractAttribute::trackStatistics() 4048 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(noreturn) } 4049 }; 4050 4051 /// NoReturn attribute deduction for a call sites. 4052 struct AANoReturnCallSite final : AANoReturnImpl { 4053 AANoReturnCallSite(const IRPosition &IRP, Attributor &A) 4054 : AANoReturnImpl(IRP, A) {} 4055 4056 /// See AbstractAttribute::initialize(...). 4057 void initialize(Attributor &A) override { 4058 AANoReturnImpl::initialize(A); 4059 if (Function *F = getAssociatedFunction()) { 4060 const IRPosition &FnPos = IRPosition::function(*F); 4061 auto &FnAA = A.getAAFor<AANoReturn>(*this, FnPos, DepClassTy::REQUIRED); 4062 if (!FnAA.isAssumedNoReturn()) 4063 indicatePessimisticFixpoint(); 4064 } 4065 } 4066 4067 /// See AbstractAttribute::updateImpl(...). 4068 ChangeStatus updateImpl(Attributor &A) override { 4069 // TODO: Once we have call site specific value information we can provide 4070 // call site specific liveness information and then it makes 4071 // sense to specialize attributes for call sites arguments instead of 4072 // redirecting requests to the callee argument. 4073 Function *F = getAssociatedFunction(); 4074 const IRPosition &FnPos = IRPosition::function(*F); 4075 auto &FnAA = A.getAAFor<AANoReturn>(*this, FnPos, DepClassTy::REQUIRED); 4076 return clampStateAndIndicateChange(getState(), FnAA.getState()); 4077 } 4078 4079 /// See AbstractAttribute::trackStatistics() 4080 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(noreturn); } 4081 }; 4082 4083 /// ----------------------- Variable Capturing --------------------------------- 4084 4085 /// A class to hold the state of for no-capture attributes. 4086 struct AANoCaptureImpl : public AANoCapture { 4087 AANoCaptureImpl(const IRPosition &IRP, Attributor &A) : AANoCapture(IRP, A) {} 4088 4089 /// See AbstractAttribute::initialize(...). 4090 void initialize(Attributor &A) override { 4091 if (hasAttr(getAttrKind(), /* IgnoreSubsumingPositions */ true)) { 4092 indicateOptimisticFixpoint(); 4093 return; 4094 } 4095 Function *AnchorScope = getAnchorScope(); 4096 if (isFnInterfaceKind() && 4097 (!AnchorScope || !A.isFunctionIPOAmendable(*AnchorScope))) { 4098 indicatePessimisticFixpoint(); 4099 return; 4100 } 4101 4102 // You cannot "capture" null in the default address space. 4103 if (isa<ConstantPointerNull>(getAssociatedValue()) && 4104 getAssociatedValue().getType()->getPointerAddressSpace() == 0) { 4105 indicateOptimisticFixpoint(); 4106 return; 4107 } 4108 4109 const Function *F = 4110 isArgumentPosition() ? getAssociatedFunction() : AnchorScope; 4111 4112 // Check what state the associated function can actually capture. 4113 if (F) 4114 determineFunctionCaptureCapabilities(getIRPosition(), *F, *this); 4115 else 4116 indicatePessimisticFixpoint(); 4117 } 4118 4119 /// See AbstractAttribute::updateImpl(...). 4120 ChangeStatus updateImpl(Attributor &A) override; 4121 4122 /// see AbstractAttribute::isAssumedNoCaptureMaybeReturned(...). 4123 virtual void 4124 getDeducedAttributes(LLVMContext &Ctx, 4125 SmallVectorImpl<Attribute> &Attrs) const override { 4126 if (!isAssumedNoCaptureMaybeReturned()) 4127 return; 4128 4129 if (isArgumentPosition()) { 4130 if (isAssumedNoCapture()) 4131 Attrs.emplace_back(Attribute::get(Ctx, Attribute::NoCapture)); 4132 else if (ManifestInternal) 4133 Attrs.emplace_back(Attribute::get(Ctx, "no-capture-maybe-returned")); 4134 } 4135 } 4136 4137 /// Set the NOT_CAPTURED_IN_MEM and NOT_CAPTURED_IN_RET bits in \p Known 4138 /// depending on the ability of the function associated with \p IRP to capture 4139 /// state in memory and through "returning/throwing", respectively. 4140 static void determineFunctionCaptureCapabilities(const IRPosition &IRP, 4141 const Function &F, 4142 BitIntegerState &State) { 4143 // TODO: Once we have memory behavior attributes we should use them here. 4144 4145 // If we know we cannot communicate or write to memory, we do not care about 4146 // ptr2int anymore. 4147 if (F.onlyReadsMemory() && F.doesNotThrow() && 4148 F.getReturnType()->isVoidTy()) { 4149 State.addKnownBits(NO_CAPTURE); 4150 return; 4151 } 4152 4153 // A function cannot capture state in memory if it only reads memory, it can 4154 // however return/throw state and the state might be influenced by the 4155 // pointer value, e.g., loading from a returned pointer might reveal a bit. 4156 if (F.onlyReadsMemory()) 4157 State.addKnownBits(NOT_CAPTURED_IN_MEM); 4158 4159 // A function cannot communicate state back if it does not through 4160 // exceptions and doesn not return values. 4161 if (F.doesNotThrow() && F.getReturnType()->isVoidTy()) 4162 State.addKnownBits(NOT_CAPTURED_IN_RET); 4163 4164 // Check existing "returned" attributes. 4165 int ArgNo = IRP.getCalleeArgNo(); 4166 if (F.doesNotThrow() && ArgNo >= 0) { 4167 for (unsigned u = 0, e = F.arg_size(); u < e; ++u) 4168 if (F.hasParamAttribute(u, Attribute::Returned)) { 4169 if (u == unsigned(ArgNo)) 4170 State.removeAssumedBits(NOT_CAPTURED_IN_RET); 4171 else if (F.onlyReadsMemory()) 4172 State.addKnownBits(NO_CAPTURE); 4173 else 4174 State.addKnownBits(NOT_CAPTURED_IN_RET); 4175 break; 4176 } 4177 } 4178 } 4179 4180 /// See AbstractState::getAsStr(). 4181 const std::string getAsStr() const override { 4182 if (isKnownNoCapture()) 4183 return "known not-captured"; 4184 if (isAssumedNoCapture()) 4185 return "assumed not-captured"; 4186 if (isKnownNoCaptureMaybeReturned()) 4187 return "known not-captured-maybe-returned"; 4188 if (isAssumedNoCaptureMaybeReturned()) 4189 return "assumed not-captured-maybe-returned"; 4190 return "assumed-captured"; 4191 } 4192 }; 4193 4194 /// Attributor-aware capture tracker. 4195 struct AACaptureUseTracker final : public CaptureTracker { 4196 4197 /// Create a capture tracker that can lookup in-flight abstract attributes 4198 /// through the Attributor \p A. 4199 /// 4200 /// If a use leads to a potential capture, \p CapturedInMemory is set and the 4201 /// search is stopped. If a use leads to a return instruction, 4202 /// \p CommunicatedBack is set to true and \p CapturedInMemory is not changed. 4203 /// If a use leads to a ptr2int which may capture the value, 4204 /// \p CapturedInInteger is set. If a use is found that is currently assumed 4205 /// "no-capture-maybe-returned", the user is added to the \p PotentialCopies 4206 /// set. All values in \p PotentialCopies are later tracked as well. For every 4207 /// explored use we decrement \p RemainingUsesToExplore. Once it reaches 0, 4208 /// the search is stopped with \p CapturedInMemory and \p CapturedInInteger 4209 /// conservatively set to true. 4210 AACaptureUseTracker(Attributor &A, AANoCapture &NoCaptureAA, 4211 const AAIsDead &IsDeadAA, AANoCapture::StateType &State, 4212 SmallVectorImpl<const Value *> &PotentialCopies, 4213 unsigned &RemainingUsesToExplore) 4214 : A(A), NoCaptureAA(NoCaptureAA), IsDeadAA(IsDeadAA), State(State), 4215 PotentialCopies(PotentialCopies), 4216 RemainingUsesToExplore(RemainingUsesToExplore) {} 4217 4218 /// Determine if \p V maybe captured. *Also updates the state!* 4219 bool valueMayBeCaptured(const Value *V) { 4220 if (V->getType()->isPointerTy()) { 4221 PointerMayBeCaptured(V, this); 4222 } else { 4223 State.indicatePessimisticFixpoint(); 4224 } 4225 return State.isAssumed(AANoCapture::NO_CAPTURE_MAYBE_RETURNED); 4226 } 4227 4228 /// See CaptureTracker::tooManyUses(). 4229 void tooManyUses() override { 4230 State.removeAssumedBits(AANoCapture::NO_CAPTURE); 4231 } 4232 4233 bool isDereferenceableOrNull(Value *O, const DataLayout &DL) override { 4234 if (CaptureTracker::isDereferenceableOrNull(O, DL)) 4235 return true; 4236 const auto &DerefAA = A.getAAFor<AADereferenceable>( 4237 NoCaptureAA, IRPosition::value(*O), DepClassTy::OPTIONAL); 4238 return DerefAA.getAssumedDereferenceableBytes(); 4239 } 4240 4241 /// See CaptureTracker::captured(...). 4242 bool captured(const Use *U) override { 4243 Instruction *UInst = cast<Instruction>(U->getUser()); 4244 LLVM_DEBUG(dbgs() << "Check use: " << *U->get() << " in " << *UInst 4245 << "\n"); 4246 4247 // Because we may reuse the tracker multiple times we keep track of the 4248 // number of explored uses ourselves as well. 4249 if (RemainingUsesToExplore-- == 0) { 4250 LLVM_DEBUG(dbgs() << " - too many uses to explore!\n"); 4251 return isCapturedIn(/* Memory */ true, /* Integer */ true, 4252 /* Return */ true); 4253 } 4254 4255 // Deal with ptr2int by following uses. 4256 if (isa<PtrToIntInst>(UInst)) { 4257 LLVM_DEBUG(dbgs() << " - ptr2int assume the worst!\n"); 4258 return valueMayBeCaptured(UInst); 4259 } 4260 4261 // Explicitly catch return instructions. 4262 if (isa<ReturnInst>(UInst)) 4263 return isCapturedIn(/* Memory */ false, /* Integer */ false, 4264 /* Return */ true); 4265 4266 // For now we only use special logic for call sites. However, the tracker 4267 // itself knows about a lot of other non-capturing cases already. 4268 auto *CB = dyn_cast<CallBase>(UInst); 4269 if (!CB || !CB->isArgOperand(U)) 4270 return isCapturedIn(/* Memory */ true, /* Integer */ true, 4271 /* Return */ true); 4272 4273 unsigned ArgNo = CB->getArgOperandNo(U); 4274 const IRPosition &CSArgPos = IRPosition::callsite_argument(*CB, ArgNo); 4275 // If we have a abstract no-capture attribute for the argument we can use 4276 // it to justify a non-capture attribute here. This allows recursion! 4277 auto &ArgNoCaptureAA = 4278 A.getAAFor<AANoCapture>(NoCaptureAA, CSArgPos, DepClassTy::REQUIRED); 4279 if (ArgNoCaptureAA.isAssumedNoCapture()) 4280 return isCapturedIn(/* Memory */ false, /* Integer */ false, 4281 /* Return */ false); 4282 if (ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) { 4283 addPotentialCopy(*CB); 4284 return isCapturedIn(/* Memory */ false, /* Integer */ false, 4285 /* Return */ false); 4286 } 4287 4288 // Lastly, we could not find a reason no-capture can be assumed so we don't. 4289 return isCapturedIn(/* Memory */ true, /* Integer */ true, 4290 /* Return */ true); 4291 } 4292 4293 /// Register \p CS as potential copy of the value we are checking. 4294 void addPotentialCopy(CallBase &CB) { PotentialCopies.push_back(&CB); } 4295 4296 /// See CaptureTracker::shouldExplore(...). 4297 bool shouldExplore(const Use *U) override { 4298 // Check liveness and ignore droppable users. 4299 return !U->getUser()->isDroppable() && 4300 !A.isAssumedDead(*U, &NoCaptureAA, &IsDeadAA); 4301 } 4302 4303 /// Update the state according to \p CapturedInMem, \p CapturedInInt, and 4304 /// \p CapturedInRet, then return the appropriate value for use in the 4305 /// CaptureTracker::captured() interface. 4306 bool isCapturedIn(bool CapturedInMem, bool CapturedInInt, 4307 bool CapturedInRet) { 4308 LLVM_DEBUG(dbgs() << " - captures [Mem " << CapturedInMem << "|Int " 4309 << CapturedInInt << "|Ret " << CapturedInRet << "]\n"); 4310 if (CapturedInMem) 4311 State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_MEM); 4312 if (CapturedInInt) 4313 State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_INT); 4314 if (CapturedInRet) 4315 State.removeAssumedBits(AANoCapture::NOT_CAPTURED_IN_RET); 4316 return !State.isAssumed(AANoCapture::NO_CAPTURE_MAYBE_RETURNED); 4317 } 4318 4319 private: 4320 /// The attributor providing in-flight abstract attributes. 4321 Attributor &A; 4322 4323 /// The abstract attribute currently updated. 4324 AANoCapture &NoCaptureAA; 4325 4326 /// The abstract liveness state. 4327 const AAIsDead &IsDeadAA; 4328 4329 /// The state currently updated. 4330 AANoCapture::StateType &State; 4331 4332 /// Set of potential copies of the tracked value. 4333 SmallVectorImpl<const Value *> &PotentialCopies; 4334 4335 /// Global counter to limit the number of explored uses. 4336 unsigned &RemainingUsesToExplore; 4337 }; 4338 4339 ChangeStatus AANoCaptureImpl::updateImpl(Attributor &A) { 4340 const IRPosition &IRP = getIRPosition(); 4341 const Value *V = isArgumentPosition() ? IRP.getAssociatedArgument() 4342 : &IRP.getAssociatedValue(); 4343 if (!V) 4344 return indicatePessimisticFixpoint(); 4345 4346 const Function *F = 4347 isArgumentPosition() ? IRP.getAssociatedFunction() : IRP.getAnchorScope(); 4348 assert(F && "Expected a function!"); 4349 const IRPosition &FnPos = IRPosition::function(*F); 4350 const auto &IsDeadAA = A.getAAFor<AAIsDead>(*this, FnPos, DepClassTy::NONE); 4351 4352 AANoCapture::StateType T; 4353 4354 // Readonly means we cannot capture through memory. 4355 const auto &FnMemAA = 4356 A.getAAFor<AAMemoryBehavior>(*this, FnPos, DepClassTy::NONE); 4357 if (FnMemAA.isAssumedReadOnly()) { 4358 T.addKnownBits(NOT_CAPTURED_IN_MEM); 4359 if (FnMemAA.isKnownReadOnly()) 4360 addKnownBits(NOT_CAPTURED_IN_MEM); 4361 else 4362 A.recordDependence(FnMemAA, *this, DepClassTy::OPTIONAL); 4363 } 4364 4365 // Make sure all returned values are different than the underlying value. 4366 // TODO: we could do this in a more sophisticated way inside 4367 // AAReturnedValues, e.g., track all values that escape through returns 4368 // directly somehow. 4369 auto CheckReturnedArgs = [&](const AAReturnedValues &RVAA) { 4370 bool SeenConstant = false; 4371 for (auto &It : RVAA.returned_values()) { 4372 if (isa<Constant>(It.first)) { 4373 if (SeenConstant) 4374 return false; 4375 SeenConstant = true; 4376 } else if (!isa<Argument>(It.first) || 4377 It.first == getAssociatedArgument()) 4378 return false; 4379 } 4380 return true; 4381 }; 4382 4383 const auto &NoUnwindAA = 4384 A.getAAFor<AANoUnwind>(*this, FnPos, DepClassTy::OPTIONAL); 4385 if (NoUnwindAA.isAssumedNoUnwind()) { 4386 bool IsVoidTy = F->getReturnType()->isVoidTy(); 4387 const AAReturnedValues *RVAA = 4388 IsVoidTy ? nullptr 4389 : &A.getAAFor<AAReturnedValues>(*this, FnPos, 4390 4391 DepClassTy::OPTIONAL); 4392 if (IsVoidTy || CheckReturnedArgs(*RVAA)) { 4393 T.addKnownBits(NOT_CAPTURED_IN_RET); 4394 if (T.isKnown(NOT_CAPTURED_IN_MEM)) 4395 return ChangeStatus::UNCHANGED; 4396 if (NoUnwindAA.isKnownNoUnwind() && 4397 (IsVoidTy || RVAA->getState().isAtFixpoint())) { 4398 addKnownBits(NOT_CAPTURED_IN_RET); 4399 if (isKnown(NOT_CAPTURED_IN_MEM)) 4400 return indicateOptimisticFixpoint(); 4401 } 4402 } 4403 } 4404 4405 // Use the CaptureTracker interface and logic with the specialized tracker, 4406 // defined in AACaptureUseTracker, that can look at in-flight abstract 4407 // attributes and directly updates the assumed state. 4408 SmallVector<const Value *, 4> PotentialCopies; 4409 unsigned RemainingUsesToExplore = 4410 getDefaultMaxUsesToExploreForCaptureTracking(); 4411 AACaptureUseTracker Tracker(A, *this, IsDeadAA, T, PotentialCopies, 4412 RemainingUsesToExplore); 4413 4414 // Check all potential copies of the associated value until we can assume 4415 // none will be captured or we have to assume at least one might be. 4416 unsigned Idx = 0; 4417 PotentialCopies.push_back(V); 4418 while (T.isAssumed(NO_CAPTURE_MAYBE_RETURNED) && Idx < PotentialCopies.size()) 4419 Tracker.valueMayBeCaptured(PotentialCopies[Idx++]); 4420 4421 AANoCapture::StateType &S = getState(); 4422 auto Assumed = S.getAssumed(); 4423 S.intersectAssumedBits(T.getAssumed()); 4424 if (!isAssumedNoCaptureMaybeReturned()) 4425 return indicatePessimisticFixpoint(); 4426 return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED 4427 : ChangeStatus::CHANGED; 4428 } 4429 4430 /// NoCapture attribute for function arguments. 4431 struct AANoCaptureArgument final : AANoCaptureImpl { 4432 AANoCaptureArgument(const IRPosition &IRP, Attributor &A) 4433 : AANoCaptureImpl(IRP, A) {} 4434 4435 /// See AbstractAttribute::trackStatistics() 4436 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nocapture) } 4437 }; 4438 4439 /// NoCapture attribute for call site arguments. 4440 struct AANoCaptureCallSiteArgument final : AANoCaptureImpl { 4441 AANoCaptureCallSiteArgument(const IRPosition &IRP, Attributor &A) 4442 : AANoCaptureImpl(IRP, A) {} 4443 4444 /// See AbstractAttribute::initialize(...). 4445 void initialize(Attributor &A) override { 4446 if (Argument *Arg = getAssociatedArgument()) 4447 if (Arg->hasByValAttr()) 4448 indicateOptimisticFixpoint(); 4449 AANoCaptureImpl::initialize(A); 4450 } 4451 4452 /// See AbstractAttribute::updateImpl(...). 4453 ChangeStatus updateImpl(Attributor &A) override { 4454 // TODO: Once we have call site specific value information we can provide 4455 // call site specific liveness information and then it makes 4456 // sense to specialize attributes for call sites arguments instead of 4457 // redirecting requests to the callee argument. 4458 Argument *Arg = getAssociatedArgument(); 4459 if (!Arg) 4460 return indicatePessimisticFixpoint(); 4461 const IRPosition &ArgPos = IRPosition::argument(*Arg); 4462 auto &ArgAA = A.getAAFor<AANoCapture>(*this, ArgPos, DepClassTy::REQUIRED); 4463 return clampStateAndIndicateChange(getState(), ArgAA.getState()); 4464 } 4465 4466 /// See AbstractAttribute::trackStatistics() 4467 void trackStatistics() const override{STATS_DECLTRACK_CSARG_ATTR(nocapture)}; 4468 }; 4469 4470 /// NoCapture attribute for floating values. 4471 struct AANoCaptureFloating final : AANoCaptureImpl { 4472 AANoCaptureFloating(const IRPosition &IRP, Attributor &A) 4473 : AANoCaptureImpl(IRP, A) {} 4474 4475 /// See AbstractAttribute::trackStatistics() 4476 void trackStatistics() const override { 4477 STATS_DECLTRACK_FLOATING_ATTR(nocapture) 4478 } 4479 }; 4480 4481 /// NoCapture attribute for function return value. 4482 struct AANoCaptureReturned final : AANoCaptureImpl { 4483 AANoCaptureReturned(const IRPosition &IRP, Attributor &A) 4484 : AANoCaptureImpl(IRP, A) { 4485 llvm_unreachable("NoCapture is not applicable to function returns!"); 4486 } 4487 4488 /// See AbstractAttribute::initialize(...). 4489 void initialize(Attributor &A) override { 4490 llvm_unreachable("NoCapture is not applicable to function returns!"); 4491 } 4492 4493 /// See AbstractAttribute::updateImpl(...). 4494 ChangeStatus updateImpl(Attributor &A) override { 4495 llvm_unreachable("NoCapture is not applicable to function returns!"); 4496 } 4497 4498 /// See AbstractAttribute::trackStatistics() 4499 void trackStatistics() const override {} 4500 }; 4501 4502 /// NoCapture attribute deduction for a call site return value. 4503 struct AANoCaptureCallSiteReturned final : AANoCaptureImpl { 4504 AANoCaptureCallSiteReturned(const IRPosition &IRP, Attributor &A) 4505 : AANoCaptureImpl(IRP, A) {} 4506 4507 /// See AbstractAttribute::initialize(...). 4508 void initialize(Attributor &A) override { 4509 const Function *F = getAnchorScope(); 4510 // Check what state the associated function can actually capture. 4511 determineFunctionCaptureCapabilities(getIRPosition(), *F, *this); 4512 } 4513 4514 /// See AbstractAttribute::trackStatistics() 4515 void trackStatistics() const override { 4516 STATS_DECLTRACK_CSRET_ATTR(nocapture) 4517 } 4518 }; 4519 4520 /// ------------------ Value Simplify Attribute ---------------------------- 4521 struct AAValueSimplifyImpl : AAValueSimplify { 4522 AAValueSimplifyImpl(const IRPosition &IRP, Attributor &A) 4523 : AAValueSimplify(IRP, A) {} 4524 4525 /// See AbstractAttribute::initialize(...). 4526 void initialize(Attributor &A) override { 4527 if (getAssociatedValue().getType()->isVoidTy()) 4528 indicatePessimisticFixpoint(); 4529 } 4530 4531 /// See AbstractAttribute::getAsStr(). 4532 const std::string getAsStr() const override { 4533 LLVM_DEBUG({ 4534 errs() << "SAV: " << SimplifiedAssociatedValue << " "; 4535 if (SimplifiedAssociatedValue) 4536 errs() << "SAV: " << **SimplifiedAssociatedValue << " "; 4537 }); 4538 return getAssumed() ? (getKnown() ? "simplified" : "maybe-simple") 4539 : "not-simple"; 4540 } 4541 4542 /// See AbstractAttribute::trackStatistics() 4543 void trackStatistics() const override {} 4544 4545 /// See AAValueSimplify::getAssumedSimplifiedValue() 4546 Optional<Value *> getAssumedSimplifiedValue(Attributor &A) const override { 4547 if (!getAssumed()) 4548 return const_cast<Value *>(&getAssociatedValue()); 4549 return SimplifiedAssociatedValue; 4550 } 4551 4552 /// Helper function for querying AAValueSimplify and updating candicate. 4553 /// \param QueryingValue Value trying to unify with SimplifiedValue 4554 /// \param AccumulatedSimplifiedValue Current simplification result. 4555 static bool checkAndUpdate(Attributor &A, const AbstractAttribute &QueryingAA, 4556 Value &QueryingValue, 4557 Optional<Value *> &AccumulatedSimplifiedValue) { 4558 // FIXME: Add a typecast support. 4559 4560 auto &ValueSimplifyAA = A.getAAFor<AAValueSimplify>( 4561 QueryingAA, 4562 IRPosition::value(QueryingValue, QueryingAA.getCallBaseContext()), 4563 DepClassTy::REQUIRED); 4564 4565 Optional<Value *> QueryingValueSimplified = 4566 ValueSimplifyAA.getAssumedSimplifiedValue(A); 4567 4568 if (!QueryingValueSimplified.hasValue()) 4569 return true; 4570 4571 if (!QueryingValueSimplified.getValue()) 4572 return false; 4573 4574 Value &QueryingValueSimplifiedUnwrapped = 4575 *QueryingValueSimplified.getValue(); 4576 4577 if (AccumulatedSimplifiedValue.hasValue() && 4578 !isa<UndefValue>(AccumulatedSimplifiedValue.getValue()) && 4579 !isa<UndefValue>(QueryingValueSimplifiedUnwrapped)) 4580 return AccumulatedSimplifiedValue == QueryingValueSimplified; 4581 if (AccumulatedSimplifiedValue.hasValue() && 4582 isa<UndefValue>(QueryingValueSimplifiedUnwrapped)) 4583 return true; 4584 4585 LLVM_DEBUG(dbgs() << "[ValueSimplify] " << QueryingValue 4586 << " is assumed to be " 4587 << QueryingValueSimplifiedUnwrapped << "\n"); 4588 4589 AccumulatedSimplifiedValue = QueryingValueSimplified; 4590 return true; 4591 } 4592 4593 /// Returns a candidate is found or not 4594 template <typename AAType> bool askSimplifiedValueFor(Attributor &A) { 4595 if (!getAssociatedValue().getType()->isIntegerTy()) 4596 return false; 4597 4598 // This will also pass the call base context. 4599 const auto &AA = 4600 A.getAAFor<AAType>(*this, getIRPosition(), DepClassTy::NONE); 4601 4602 Optional<ConstantInt *> COpt = AA.getAssumedConstantInt(A); 4603 4604 if (!COpt.hasValue()) { 4605 SimplifiedAssociatedValue = llvm::None; 4606 A.recordDependence(AA, *this, DepClassTy::OPTIONAL); 4607 return true; 4608 } 4609 if (auto *C = COpt.getValue()) { 4610 SimplifiedAssociatedValue = C; 4611 A.recordDependence(AA, *this, DepClassTy::OPTIONAL); 4612 return true; 4613 } 4614 return false; 4615 } 4616 4617 bool askSimplifiedValueForOtherAAs(Attributor &A) { 4618 if (askSimplifiedValueFor<AAValueConstantRange>(A)) 4619 return true; 4620 if (askSimplifiedValueFor<AAPotentialValues>(A)) 4621 return true; 4622 return false; 4623 } 4624 4625 /// See AbstractAttribute::manifest(...). 4626 ChangeStatus manifest(Attributor &A) override { 4627 ChangeStatus Changed = ChangeStatus::UNCHANGED; 4628 4629 if (SimplifiedAssociatedValue.hasValue() && 4630 !SimplifiedAssociatedValue.getValue()) 4631 return Changed; 4632 4633 Value &V = getAssociatedValue(); 4634 auto *C = SimplifiedAssociatedValue.hasValue() 4635 ? dyn_cast<Constant>(SimplifiedAssociatedValue.getValue()) 4636 : UndefValue::get(V.getType()); 4637 if (C && C != &V) { 4638 Value *NewV = AA::getWithType(*C, *V.getType()); 4639 // We can replace the AssociatedValue with the constant. 4640 if (!V.user_empty() && &V != C && NewV) { 4641 LLVM_DEBUG(dbgs() << "[ValueSimplify] " << V << " -> " << *NewV 4642 << " :: " << *this << "\n"); 4643 if (A.changeValueAfterManifest(V, *NewV)) 4644 Changed = ChangeStatus::CHANGED; 4645 } 4646 } 4647 4648 return Changed | AAValueSimplify::manifest(A); 4649 } 4650 4651 /// See AbstractState::indicatePessimisticFixpoint(...). 4652 ChangeStatus indicatePessimisticFixpoint() override { 4653 // NOTE: Associated value will be returned in a pessimistic fixpoint and is 4654 // regarded as known. That's why`indicateOptimisticFixpoint` is called. 4655 SimplifiedAssociatedValue = &getAssociatedValue(); 4656 indicateOptimisticFixpoint(); 4657 return ChangeStatus::CHANGED; 4658 } 4659 4660 protected: 4661 // An assumed simplified value. Initially, it is set to Optional::None, which 4662 // means that the value is not clear under current assumption. If in the 4663 // pessimistic state, getAssumedSimplifiedValue doesn't return this value but 4664 // returns orignal associated value. 4665 Optional<Value *> SimplifiedAssociatedValue; 4666 }; 4667 4668 struct AAValueSimplifyArgument final : AAValueSimplifyImpl { 4669 AAValueSimplifyArgument(const IRPosition &IRP, Attributor &A) 4670 : AAValueSimplifyImpl(IRP, A) {} 4671 4672 void initialize(Attributor &A) override { 4673 AAValueSimplifyImpl::initialize(A); 4674 if (!getAnchorScope() || getAnchorScope()->isDeclaration()) 4675 indicatePessimisticFixpoint(); 4676 if (hasAttr({Attribute::InAlloca, Attribute::Preallocated, 4677 Attribute::StructRet, Attribute::Nest}, 4678 /* IgnoreSubsumingPositions */ true)) 4679 indicatePessimisticFixpoint(); 4680 4681 // FIXME: This is a hack to prevent us from propagating function poiner in 4682 // the new pass manager CGSCC pass as it creates call edges the 4683 // CallGraphUpdater cannot handle yet. 4684 Value &V = getAssociatedValue(); 4685 if (V.getType()->isPointerTy() && 4686 V.getType()->getPointerElementType()->isFunctionTy() && 4687 !A.isModulePass()) 4688 indicatePessimisticFixpoint(); 4689 } 4690 4691 /// See AbstractAttribute::updateImpl(...). 4692 ChangeStatus updateImpl(Attributor &A) override { 4693 // Byval is only replacable if it is readonly otherwise we would write into 4694 // the replaced value and not the copy that byval creates implicitly. 4695 Argument *Arg = getAssociatedArgument(); 4696 if (Arg->hasByValAttr()) { 4697 // TODO: We probably need to verify synchronization is not an issue, e.g., 4698 // there is no race by not copying a constant byval. 4699 const auto &MemAA = A.getAAFor<AAMemoryBehavior>(*this, getIRPosition(), 4700 DepClassTy::REQUIRED); 4701 if (!MemAA.isAssumedReadOnly()) 4702 return indicatePessimisticFixpoint(); 4703 } 4704 4705 auto Before = SimplifiedAssociatedValue; 4706 4707 auto PredForCallSite = [&](AbstractCallSite ACS) { 4708 const IRPosition &ACSArgPos = 4709 IRPosition::callsite_argument(ACS, getCallSiteArgNo()); 4710 // Check if a coresponding argument was found or if it is on not 4711 // associated (which can happen for callback calls). 4712 if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID) 4713 return false; 4714 4715 // We can only propagate thread independent values through callbacks. 4716 // This is different to direct/indirect call sites because for them we 4717 // know the thread executing the caller and callee is the same. For 4718 // callbacks this is not guaranteed, thus a thread dependent value could 4719 // be different for the caller and callee, making it invalid to propagate. 4720 Value &ArgOp = ACSArgPos.getAssociatedValue(); 4721 if (ACS.isCallbackCall()) 4722 if (auto *C = dyn_cast<Constant>(&ArgOp)) 4723 if (C->isThreadDependent()) 4724 return false; 4725 return checkAndUpdate(A, *this, ArgOp, SimplifiedAssociatedValue); 4726 }; 4727 4728 // Generate a answer specific to a call site context. 4729 bool Success; 4730 bool AllCallSitesKnown; 4731 if (hasCallBaseContext()) 4732 Success = PredForCallSite( 4733 AbstractCallSite(&getCallBaseContext()->getCalledOperandUse())); 4734 else 4735 Success = A.checkForAllCallSites(PredForCallSite, *this, true, 4736 AllCallSitesKnown); 4737 4738 if (!Success) 4739 if (!askSimplifiedValueForOtherAAs(A)) 4740 return indicatePessimisticFixpoint(); 4741 4742 // If a candicate was found in this update, return CHANGED. 4743 return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED 4744 : ChangeStatus ::CHANGED; 4745 } 4746 4747 /// See AbstractAttribute::trackStatistics() 4748 void trackStatistics() const override { 4749 STATS_DECLTRACK_ARG_ATTR(value_simplify) 4750 } 4751 }; 4752 4753 struct AAValueSimplifyReturned : AAValueSimplifyImpl { 4754 AAValueSimplifyReturned(const IRPosition &IRP, Attributor &A) 4755 : AAValueSimplifyImpl(IRP, A) {} 4756 4757 /// See AbstractAttribute::updateImpl(...). 4758 ChangeStatus updateImpl(Attributor &A) override { 4759 auto Before = SimplifiedAssociatedValue; 4760 4761 auto PredForReturned = [&](Value &V) { 4762 return checkAndUpdate(A, *this, V, SimplifiedAssociatedValue); 4763 }; 4764 4765 if (!A.checkForAllReturnedValues(PredForReturned, *this)) 4766 if (!askSimplifiedValueForOtherAAs(A)) 4767 return indicatePessimisticFixpoint(); 4768 4769 // If a candicate was found in this update, return CHANGED. 4770 return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED 4771 : ChangeStatus ::CHANGED; 4772 } 4773 4774 ChangeStatus manifest(Attributor &A) override { 4775 ChangeStatus Changed = ChangeStatus::UNCHANGED; 4776 4777 if (SimplifiedAssociatedValue.hasValue() && 4778 !SimplifiedAssociatedValue.getValue()) 4779 return Changed; 4780 4781 Value &V = getAssociatedValue(); 4782 auto *C = SimplifiedAssociatedValue.hasValue() 4783 ? dyn_cast<Constant>(SimplifiedAssociatedValue.getValue()) 4784 : UndefValue::get(V.getType()); 4785 if (C && C != &V) { 4786 auto PredForReturned = 4787 [&](Value &V, const SmallSetVector<ReturnInst *, 4> &RetInsts) { 4788 // We can replace the AssociatedValue with the constant. 4789 if (&V == C || isa<UndefValue>(V)) 4790 return true; 4791 4792 for (ReturnInst *RI : RetInsts) { 4793 if (RI->getFunction() != getAnchorScope()) 4794 continue; 4795 Value *NewV = 4796 AA::getWithType(*C, *RI->getReturnValue()->getType()); 4797 if (!NewV) 4798 continue; 4799 LLVM_DEBUG(dbgs() << "[ValueSimplify] " << V << " -> " << *NewV 4800 << " in " << *RI << " :: " << *this << "\n"); 4801 if (A.changeUseAfterManifest(RI->getOperandUse(0), *NewV)) 4802 Changed = ChangeStatus::CHANGED; 4803 } 4804 return true; 4805 }; 4806 A.checkForAllReturnedValuesAndReturnInsts(PredForReturned, *this); 4807 } 4808 4809 return Changed | AAValueSimplify::manifest(A); 4810 } 4811 4812 /// See AbstractAttribute::trackStatistics() 4813 void trackStatistics() const override { 4814 STATS_DECLTRACK_FNRET_ATTR(value_simplify) 4815 } 4816 }; 4817 4818 struct AAValueSimplifyFloating : AAValueSimplifyImpl { 4819 AAValueSimplifyFloating(const IRPosition &IRP, Attributor &A) 4820 : AAValueSimplifyImpl(IRP, A) {} 4821 4822 /// See AbstractAttribute::initialize(...). 4823 void initialize(Attributor &A) override { 4824 // FIXME: This might have exposed a SCC iterator update bug in the old PM. 4825 // Needs investigation. 4826 // AAValueSimplifyImpl::initialize(A); 4827 Value &V = getAnchorValue(); 4828 4829 // TODO: add other stuffs 4830 if (isa<Constant>(V)) 4831 indicatePessimisticFixpoint(); 4832 } 4833 4834 /// Check if \p ICmp is an equality comparison (==/!=) with at least one 4835 /// nullptr. If so, try to simplify it using AANonNull on the other operand. 4836 /// Return true if successful, in that case SimplifiedAssociatedValue will be 4837 /// updated and \p Changed is set appropriately. 4838 bool checkForNullPtrCompare(Attributor &A, ICmpInst *ICmp, 4839 ChangeStatus &Changed) { 4840 if (!ICmp) 4841 return false; 4842 if (!ICmp->isEquality()) 4843 return false; 4844 4845 // This is a comparison with == or !-. We check for nullptr now. 4846 bool Op0IsNull = isa<ConstantPointerNull>(ICmp->getOperand(0)); 4847 bool Op1IsNull = isa<ConstantPointerNull>(ICmp->getOperand(1)); 4848 if (!Op0IsNull && !Op1IsNull) 4849 return false; 4850 4851 LLVMContext &Ctx = ICmp->getContext(); 4852 // Check for `nullptr ==/!= nullptr` first: 4853 if (Op0IsNull && Op1IsNull) { 4854 Value *NewVal = ConstantInt::get( 4855 Type::getInt1Ty(Ctx), ICmp->getPredicate() == CmpInst::ICMP_EQ); 4856 assert(!SimplifiedAssociatedValue.hasValue() && 4857 "Did not expect non-fixed value for constant comparison"); 4858 SimplifiedAssociatedValue = NewVal; 4859 indicateOptimisticFixpoint(); 4860 Changed = ChangeStatus::CHANGED; 4861 return true; 4862 } 4863 4864 // Left is the nullptr ==/!= non-nullptr case. We'll use AANonNull on the 4865 // non-nullptr operand and if we assume it's non-null we can conclude the 4866 // result of the comparison. 4867 assert((Op0IsNull || Op1IsNull) && 4868 "Expected nullptr versus non-nullptr comparison at this point"); 4869 4870 // The index is the operand that we assume is not null. 4871 unsigned PtrIdx = Op0IsNull; 4872 auto &PtrNonNullAA = A.getAAFor<AANonNull>( 4873 *this, IRPosition::value(*ICmp->getOperand(PtrIdx)), 4874 DepClassTy::REQUIRED); 4875 if (!PtrNonNullAA.isAssumedNonNull()) 4876 return false; 4877 4878 // The new value depends on the predicate, true for != and false for ==. 4879 Value *NewVal = ConstantInt::get(Type::getInt1Ty(Ctx), 4880 ICmp->getPredicate() == CmpInst::ICMP_NE); 4881 4882 assert((!SimplifiedAssociatedValue.hasValue() || 4883 SimplifiedAssociatedValue == NewVal) && 4884 "Did not expect to change value for zero-comparison"); 4885 4886 auto Before = SimplifiedAssociatedValue; 4887 SimplifiedAssociatedValue = NewVal; 4888 4889 if (PtrNonNullAA.isKnownNonNull()) 4890 indicateOptimisticFixpoint(); 4891 4892 Changed = Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED 4893 : ChangeStatus ::CHANGED; 4894 return true; 4895 } 4896 4897 /// See AbstractAttribute::updateImpl(...). 4898 ChangeStatus updateImpl(Attributor &A) override { 4899 auto Before = SimplifiedAssociatedValue; 4900 4901 ChangeStatus Changed; 4902 if (checkForNullPtrCompare(A, dyn_cast<ICmpInst>(&getAnchorValue()), 4903 Changed)) 4904 return Changed; 4905 4906 auto VisitValueCB = [&](Value &V, const Instruction *CtxI, bool &, 4907 bool Stripped) -> bool { 4908 auto &AA = A.getAAFor<AAValueSimplify>( 4909 *this, IRPosition::value(V, getCallBaseContext()), 4910 DepClassTy::REQUIRED); 4911 if (!Stripped && this == &AA) { 4912 // TODO: Look the instruction and check recursively. 4913 4914 LLVM_DEBUG(dbgs() << "[ValueSimplify] Can't be stripped more : " << V 4915 << "\n"); 4916 return false; 4917 } 4918 return checkAndUpdate(A, *this, V, SimplifiedAssociatedValue); 4919 }; 4920 4921 bool Dummy = false; 4922 if (!genericValueTraversal<AAValueSimplify, bool>( 4923 A, getIRPosition(), *this, Dummy, VisitValueCB, getCtxI(), 4924 /* UseValueSimplify */ false)) 4925 if (!askSimplifiedValueForOtherAAs(A)) 4926 return indicatePessimisticFixpoint(); 4927 4928 // If a candicate was found in this update, return CHANGED. 4929 return Before == SimplifiedAssociatedValue ? ChangeStatus::UNCHANGED 4930 : ChangeStatus ::CHANGED; 4931 } 4932 4933 /// See AbstractAttribute::trackStatistics() 4934 void trackStatistics() const override { 4935 STATS_DECLTRACK_FLOATING_ATTR(value_simplify) 4936 } 4937 }; 4938 4939 struct AAValueSimplifyFunction : AAValueSimplifyImpl { 4940 AAValueSimplifyFunction(const IRPosition &IRP, Attributor &A) 4941 : AAValueSimplifyImpl(IRP, A) {} 4942 4943 /// See AbstractAttribute::initialize(...). 4944 void initialize(Attributor &A) override { 4945 SimplifiedAssociatedValue = &getAnchorValue(); 4946 indicateOptimisticFixpoint(); 4947 } 4948 /// See AbstractAttribute::initialize(...). 4949 ChangeStatus updateImpl(Attributor &A) override { 4950 llvm_unreachable( 4951 "AAValueSimplify(Function|CallSite)::updateImpl will not be called"); 4952 } 4953 /// See AbstractAttribute::trackStatistics() 4954 void trackStatistics() const override { 4955 STATS_DECLTRACK_FN_ATTR(value_simplify) 4956 } 4957 }; 4958 4959 struct AAValueSimplifyCallSite : AAValueSimplifyFunction { 4960 AAValueSimplifyCallSite(const IRPosition &IRP, Attributor &A) 4961 : AAValueSimplifyFunction(IRP, A) {} 4962 /// See AbstractAttribute::trackStatistics() 4963 void trackStatistics() const override { 4964 STATS_DECLTRACK_CS_ATTR(value_simplify) 4965 } 4966 }; 4967 4968 struct AAValueSimplifyCallSiteReturned : AAValueSimplifyReturned { 4969 AAValueSimplifyCallSiteReturned(const IRPosition &IRP, Attributor &A) 4970 : AAValueSimplifyReturned(IRP, A) {} 4971 4972 /// See AbstractAttribute::manifest(...). 4973 ChangeStatus manifest(Attributor &A) override { 4974 return AAValueSimplifyImpl::manifest(A); 4975 } 4976 4977 void trackStatistics() const override { 4978 STATS_DECLTRACK_CSRET_ATTR(value_simplify) 4979 } 4980 }; 4981 struct AAValueSimplifyCallSiteArgument : AAValueSimplifyFloating { 4982 AAValueSimplifyCallSiteArgument(const IRPosition &IRP, Attributor &A) 4983 : AAValueSimplifyFloating(IRP, A) {} 4984 4985 /// See AbstractAttribute::manifest(...). 4986 ChangeStatus manifest(Attributor &A) override { 4987 ChangeStatus Changed = ChangeStatus::UNCHANGED; 4988 4989 if (SimplifiedAssociatedValue.hasValue() && 4990 !SimplifiedAssociatedValue.getValue()) 4991 return Changed; 4992 4993 Value &V = getAssociatedValue(); 4994 auto *C = SimplifiedAssociatedValue.hasValue() 4995 ? dyn_cast<Constant>(SimplifiedAssociatedValue.getValue()) 4996 : UndefValue::get(V.getType()); 4997 if (C) { 4998 Use &U = cast<CallBase>(&getAnchorValue()) 4999 ->getArgOperandUse(getCallSiteArgNo()); 5000 // We can replace the AssociatedValue with the constant. 5001 if (&V != C) { 5002 if (Value *NewV = AA::getWithType(*C, *V.getType())) 5003 if (A.changeUseAfterManifest(U, *NewV)) 5004 Changed = ChangeStatus::CHANGED; 5005 } 5006 } 5007 5008 return Changed | AAValueSimplify::manifest(A); 5009 } 5010 5011 void trackStatistics() const override { 5012 STATS_DECLTRACK_CSARG_ATTR(value_simplify) 5013 } 5014 }; 5015 5016 /// ----------------------- Heap-To-Stack Conversion --------------------------- 5017 struct AAHeapToStackImpl : public AAHeapToStack { 5018 AAHeapToStackImpl(const IRPosition &IRP, Attributor &A) 5019 : AAHeapToStack(IRP, A) {} 5020 5021 const std::string getAsStr() const override { 5022 return "[H2S] Mallocs: " + std::to_string(MallocCalls.size()); 5023 } 5024 5025 bool isAssumedHeapToStack(CallBase &CB) const override { 5026 return isValidState() && MallocCalls.contains(&CB) && 5027 !BadMallocCalls.count(&CB); 5028 } 5029 5030 bool isKnownHeapToStack(CallBase &CB) const override { 5031 return isValidState() && MallocCalls.contains(&CB) && 5032 !BadMallocCalls.count(&CB); 5033 } 5034 5035 ChangeStatus manifest(Attributor &A) override { 5036 assert(getState().isValidState() && 5037 "Attempted to manifest an invalid state!"); 5038 5039 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 5040 Function *F = getAnchorScope(); 5041 const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F); 5042 5043 for (Instruction *MallocCall : MallocCalls) { 5044 // This malloc cannot be replaced. 5045 if (BadMallocCalls.count(MallocCall)) 5046 continue; 5047 5048 for (Instruction *FreeCall : FreesForMalloc[MallocCall]) { 5049 LLVM_DEBUG(dbgs() << "H2S: Removing free call: " << *FreeCall << "\n"); 5050 A.deleteAfterManifest(*FreeCall); 5051 HasChanged = ChangeStatus::CHANGED; 5052 } 5053 5054 LLVM_DEBUG(dbgs() << "H2S: Removing malloc call: " << *MallocCall 5055 << "\n"); 5056 5057 Align Alignment; 5058 Value *Size; 5059 if (isCallocLikeFn(MallocCall, TLI)) { 5060 auto *Num = MallocCall->getOperand(0); 5061 auto *SizeT = MallocCall->getOperand(1); 5062 IRBuilder<> B(MallocCall); 5063 Size = B.CreateMul(Num, SizeT, "h2s.calloc.size"); 5064 } else if (isAlignedAllocLikeFn(MallocCall, TLI)) { 5065 Size = MallocCall->getOperand(1); 5066 Alignment = MaybeAlign(cast<ConstantInt>(MallocCall->getOperand(0)) 5067 ->getValue() 5068 .getZExtValue()) 5069 .valueOrOne(); 5070 } else { 5071 Size = MallocCall->getOperand(0); 5072 } 5073 5074 unsigned AS = cast<PointerType>(MallocCall->getType())->getAddressSpace(); 5075 Instruction *AI = 5076 new AllocaInst(Type::getInt8Ty(F->getContext()), AS, Size, Alignment, 5077 "", MallocCall->getNextNode()); 5078 5079 if (AI->getType() != MallocCall->getType()) 5080 AI = new BitCastInst(AI, MallocCall->getType(), "malloc_bc", 5081 AI->getNextNode()); 5082 5083 A.changeValueAfterManifest(*MallocCall, *AI); 5084 5085 if (auto *II = dyn_cast<InvokeInst>(MallocCall)) { 5086 auto *NBB = II->getNormalDest(); 5087 BranchInst::Create(NBB, MallocCall->getParent()); 5088 A.deleteAfterManifest(*MallocCall); 5089 } else { 5090 A.deleteAfterManifest(*MallocCall); 5091 } 5092 5093 // Zero out the allocated memory if it was a calloc. 5094 if (isCallocLikeFn(MallocCall, TLI)) { 5095 auto *BI = new BitCastInst(AI, MallocCall->getType(), "calloc_bc", 5096 AI->getNextNode()); 5097 Value *Ops[] = { 5098 BI, ConstantInt::get(F->getContext(), APInt(8, 0, false)), Size, 5099 ConstantInt::get(Type::getInt1Ty(F->getContext()), false)}; 5100 5101 Type *Tys[] = {BI->getType(), MallocCall->getOperand(0)->getType()}; 5102 Module *M = F->getParent(); 5103 Function *Fn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys); 5104 CallInst::Create(Fn, Ops, "", BI->getNextNode()); 5105 } 5106 HasChanged = ChangeStatus::CHANGED; 5107 } 5108 5109 return HasChanged; 5110 } 5111 5112 /// Collection of all malloc calls in a function. 5113 SmallSetVector<Instruction *, 4> MallocCalls; 5114 5115 /// Collection of malloc calls that cannot be converted. 5116 DenseSet<const Instruction *> BadMallocCalls; 5117 5118 /// A map for each malloc call to the set of associated free calls. 5119 DenseMap<Instruction *, SmallPtrSet<Instruction *, 4>> FreesForMalloc; 5120 5121 ChangeStatus updateImpl(Attributor &A) override; 5122 }; 5123 5124 ChangeStatus AAHeapToStackImpl::updateImpl(Attributor &A) { 5125 const Function *F = getAnchorScope(); 5126 const auto *TLI = A.getInfoCache().getTargetLibraryInfoForFunction(*F); 5127 5128 MustBeExecutedContextExplorer &Explorer = 5129 A.getInfoCache().getMustBeExecutedContextExplorer(); 5130 5131 auto FreeCheck = [&](Instruction &I) { 5132 const auto &Frees = FreesForMalloc.lookup(&I); 5133 if (Frees.size() != 1) 5134 return false; 5135 Instruction *UniqueFree = *Frees.begin(); 5136 return Explorer.findInContextOf(UniqueFree, I.getNextNode()); 5137 }; 5138 5139 auto UsesCheck = [&](Instruction &I) { 5140 bool ValidUsesOnly = true; 5141 bool MustUse = true; 5142 auto Pred = [&](const Use &U, bool &Follow) -> bool { 5143 Instruction *UserI = cast<Instruction>(U.getUser()); 5144 if (isa<LoadInst>(UserI)) 5145 return true; 5146 if (auto *SI = dyn_cast<StoreInst>(UserI)) { 5147 if (SI->getValueOperand() == U.get()) { 5148 LLVM_DEBUG(dbgs() 5149 << "[H2S] escaping store to memory: " << *UserI << "\n"); 5150 ValidUsesOnly = false; 5151 } else { 5152 // A store into the malloc'ed memory is fine. 5153 } 5154 return true; 5155 } 5156 if (auto *CB = dyn_cast<CallBase>(UserI)) { 5157 if (!CB->isArgOperand(&U) || CB->isLifetimeStartOrEnd()) 5158 return true; 5159 // Record malloc. 5160 if (isFreeCall(UserI, TLI)) { 5161 if (MustUse) { 5162 FreesForMalloc[&I].insert(UserI); 5163 } else { 5164 LLVM_DEBUG(dbgs() << "[H2S] free potentially on different mallocs: " 5165 << *UserI << "\n"); 5166 ValidUsesOnly = false; 5167 } 5168 return true; 5169 } 5170 5171 unsigned ArgNo = CB->getArgOperandNo(&U); 5172 5173 const auto &NoCaptureAA = A.getAAFor<AANoCapture>( 5174 *this, IRPosition::callsite_argument(*CB, ArgNo), 5175 DepClassTy::REQUIRED); 5176 5177 // If a callsite argument use is nofree, we are fine. 5178 const auto &ArgNoFreeAA = A.getAAFor<AANoFree>( 5179 *this, IRPosition::callsite_argument(*CB, ArgNo), 5180 DepClassTy::REQUIRED); 5181 5182 if (!NoCaptureAA.isAssumedNoCapture() || 5183 !ArgNoFreeAA.isAssumedNoFree()) { 5184 LLVM_DEBUG(dbgs() << "[H2S] Bad user: " << *UserI << "\n"); 5185 ValidUsesOnly = false; 5186 } 5187 return true; 5188 } 5189 5190 if (isa<GetElementPtrInst>(UserI) || isa<BitCastInst>(UserI) || 5191 isa<PHINode>(UserI) || isa<SelectInst>(UserI)) { 5192 MustUse &= !(isa<PHINode>(UserI) || isa<SelectInst>(UserI)); 5193 Follow = true; 5194 return true; 5195 } 5196 // Unknown user for which we can not track uses further (in a way that 5197 // makes sense). 5198 LLVM_DEBUG(dbgs() << "[H2S] Unknown user: " << *UserI << "\n"); 5199 ValidUsesOnly = false; 5200 return true; 5201 }; 5202 A.checkForAllUses(Pred, *this, I); 5203 return ValidUsesOnly; 5204 }; 5205 5206 auto MallocCallocCheck = [&](Instruction &I) { 5207 if (BadMallocCalls.count(&I)) 5208 return true; 5209 5210 bool IsMalloc = isMallocLikeFn(&I, TLI); 5211 bool IsAlignedAllocLike = isAlignedAllocLikeFn(&I, TLI); 5212 bool IsCalloc = !IsMalloc && isCallocLikeFn(&I, TLI); 5213 if (!IsMalloc && !IsAlignedAllocLike && !IsCalloc) { 5214 BadMallocCalls.insert(&I); 5215 return true; 5216 } 5217 5218 if (IsMalloc) { 5219 if (MaxHeapToStackSize == -1) { 5220 if (UsesCheck(I) || FreeCheck(I)) { 5221 MallocCalls.insert(&I); 5222 return true; 5223 } 5224 } 5225 if (auto *Size = dyn_cast<ConstantInt>(I.getOperand(0))) 5226 if (Size->getValue().ule(MaxHeapToStackSize)) 5227 if (UsesCheck(I) || FreeCheck(I)) { 5228 MallocCalls.insert(&I); 5229 return true; 5230 } 5231 } else if (IsAlignedAllocLike && isa<ConstantInt>(I.getOperand(0))) { 5232 if (MaxHeapToStackSize == -1) { 5233 if (UsesCheck(I) || FreeCheck(I)) { 5234 MallocCalls.insert(&I); 5235 return true; 5236 } 5237 } 5238 // Only if the alignment and sizes are constant. 5239 if (auto *Size = dyn_cast<ConstantInt>(I.getOperand(1))) 5240 if (Size->getValue().ule(MaxHeapToStackSize)) 5241 if (UsesCheck(I) || FreeCheck(I)) { 5242 MallocCalls.insert(&I); 5243 return true; 5244 } 5245 } else if (IsCalloc) { 5246 if (MaxHeapToStackSize == -1) { 5247 if (UsesCheck(I) || FreeCheck(I)) { 5248 MallocCalls.insert(&I); 5249 return true; 5250 } 5251 } 5252 bool Overflow = false; 5253 if (auto *Num = dyn_cast<ConstantInt>(I.getOperand(0))) 5254 if (auto *Size = dyn_cast<ConstantInt>(I.getOperand(1))) 5255 if ((Size->getValue().umul_ov(Num->getValue(), Overflow)) 5256 .ule(MaxHeapToStackSize)) 5257 if (!Overflow && (UsesCheck(I) || FreeCheck(I))) { 5258 MallocCalls.insert(&I); 5259 return true; 5260 } 5261 } 5262 5263 BadMallocCalls.insert(&I); 5264 return true; 5265 }; 5266 5267 size_t NumBadMallocs = BadMallocCalls.size(); 5268 5269 A.checkForAllCallLikeInstructions(MallocCallocCheck, *this); 5270 5271 if (NumBadMallocs != BadMallocCalls.size()) 5272 return ChangeStatus::CHANGED; 5273 5274 return ChangeStatus::UNCHANGED; 5275 } 5276 5277 struct AAHeapToStackFunction final : public AAHeapToStackImpl { 5278 AAHeapToStackFunction(const IRPosition &IRP, Attributor &A) 5279 : AAHeapToStackImpl(IRP, A) {} 5280 5281 /// See AbstractAttribute::trackStatistics(). 5282 void trackStatistics() const override { 5283 STATS_DECL( 5284 MallocCalls, Function, 5285 "Number of malloc/calloc/aligned_alloc calls converted to allocas"); 5286 for (auto *C : MallocCalls) 5287 if (!BadMallocCalls.count(C)) 5288 ++BUILD_STAT_NAME(MallocCalls, Function); 5289 } 5290 }; 5291 5292 /// ----------------------- Privatizable Pointers ------------------------------ 5293 struct AAPrivatizablePtrImpl : public AAPrivatizablePtr { 5294 AAPrivatizablePtrImpl(const IRPosition &IRP, Attributor &A) 5295 : AAPrivatizablePtr(IRP, A), PrivatizableType(llvm::None) {} 5296 5297 ChangeStatus indicatePessimisticFixpoint() override { 5298 AAPrivatizablePtr::indicatePessimisticFixpoint(); 5299 PrivatizableType = nullptr; 5300 return ChangeStatus::CHANGED; 5301 } 5302 5303 /// Identify the type we can chose for a private copy of the underlying 5304 /// argument. None means it is not clear yet, nullptr means there is none. 5305 virtual Optional<Type *> identifyPrivatizableType(Attributor &A) = 0; 5306 5307 /// Return a privatizable type that encloses both T0 and T1. 5308 /// TODO: This is merely a stub for now as we should manage a mapping as well. 5309 Optional<Type *> combineTypes(Optional<Type *> T0, Optional<Type *> T1) { 5310 if (!T0.hasValue()) 5311 return T1; 5312 if (!T1.hasValue()) 5313 return T0; 5314 if (T0 == T1) 5315 return T0; 5316 return nullptr; 5317 } 5318 5319 Optional<Type *> getPrivatizableType() const override { 5320 return PrivatizableType; 5321 } 5322 5323 const std::string getAsStr() const override { 5324 return isAssumedPrivatizablePtr() ? "[priv]" : "[no-priv]"; 5325 } 5326 5327 protected: 5328 Optional<Type *> PrivatizableType; 5329 }; 5330 5331 // TODO: Do this for call site arguments (probably also other values) as well. 5332 5333 struct AAPrivatizablePtrArgument final : public AAPrivatizablePtrImpl { 5334 AAPrivatizablePtrArgument(const IRPosition &IRP, Attributor &A) 5335 : AAPrivatizablePtrImpl(IRP, A) {} 5336 5337 /// See AAPrivatizablePtrImpl::identifyPrivatizableType(...) 5338 Optional<Type *> identifyPrivatizableType(Attributor &A) override { 5339 // If this is a byval argument and we know all the call sites (so we can 5340 // rewrite them), there is no need to check them explicitly. 5341 bool AllCallSitesKnown; 5342 if (getIRPosition().hasAttr(Attribute::ByVal) && 5343 A.checkForAllCallSites([](AbstractCallSite ACS) { return true; }, *this, 5344 true, AllCallSitesKnown)) 5345 return getAssociatedValue().getType()->getPointerElementType(); 5346 5347 Optional<Type *> Ty; 5348 unsigned ArgNo = getIRPosition().getCallSiteArgNo(); 5349 5350 // Make sure the associated call site argument has the same type at all call 5351 // sites and it is an allocation we know is safe to privatize, for now that 5352 // means we only allow alloca instructions. 5353 // TODO: We can additionally analyze the accesses in the callee to create 5354 // the type from that information instead. That is a little more 5355 // involved and will be done in a follow up patch. 5356 auto CallSiteCheck = [&](AbstractCallSite ACS) { 5357 IRPosition ACSArgPos = IRPosition::callsite_argument(ACS, ArgNo); 5358 // Check if a coresponding argument was found or if it is one not 5359 // associated (which can happen for callback calls). 5360 if (ACSArgPos.getPositionKind() == IRPosition::IRP_INVALID) 5361 return false; 5362 5363 // Check that all call sites agree on a type. 5364 auto &PrivCSArgAA = 5365 A.getAAFor<AAPrivatizablePtr>(*this, ACSArgPos, DepClassTy::REQUIRED); 5366 Optional<Type *> CSTy = PrivCSArgAA.getPrivatizableType(); 5367 5368 LLVM_DEBUG({ 5369 dbgs() << "[AAPrivatizablePtr] ACSPos: " << ACSArgPos << ", CSTy: "; 5370 if (CSTy.hasValue() && CSTy.getValue()) 5371 CSTy.getValue()->print(dbgs()); 5372 else if (CSTy.hasValue()) 5373 dbgs() << "<nullptr>"; 5374 else 5375 dbgs() << "<none>"; 5376 }); 5377 5378 Ty = combineTypes(Ty, CSTy); 5379 5380 LLVM_DEBUG({ 5381 dbgs() << " : New Type: "; 5382 if (Ty.hasValue() && Ty.getValue()) 5383 Ty.getValue()->print(dbgs()); 5384 else if (Ty.hasValue()) 5385 dbgs() << "<nullptr>"; 5386 else 5387 dbgs() << "<none>"; 5388 dbgs() << "\n"; 5389 }); 5390 5391 return !Ty.hasValue() || Ty.getValue(); 5392 }; 5393 5394 if (!A.checkForAllCallSites(CallSiteCheck, *this, true, AllCallSitesKnown)) 5395 return nullptr; 5396 return Ty; 5397 } 5398 5399 /// See AbstractAttribute::updateImpl(...). 5400 ChangeStatus updateImpl(Attributor &A) override { 5401 PrivatizableType = identifyPrivatizableType(A); 5402 if (!PrivatizableType.hasValue()) 5403 return ChangeStatus::UNCHANGED; 5404 if (!PrivatizableType.getValue()) 5405 return indicatePessimisticFixpoint(); 5406 5407 // The dependence is optional so we don't give up once we give up on the 5408 // alignment. 5409 A.getAAFor<AAAlign>(*this, IRPosition::value(getAssociatedValue()), 5410 DepClassTy::OPTIONAL); 5411 5412 // Avoid arguments with padding for now. 5413 if (!getIRPosition().hasAttr(Attribute::ByVal) && 5414 !ArgumentPromotionPass::isDenselyPacked(PrivatizableType.getValue(), 5415 A.getInfoCache().getDL())) { 5416 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Padding detected\n"); 5417 return indicatePessimisticFixpoint(); 5418 } 5419 5420 // Verify callee and caller agree on how the promoted argument would be 5421 // passed. 5422 // TODO: The use of the ArgumentPromotion interface here is ugly, we need a 5423 // specialized form of TargetTransformInfo::areFunctionArgsABICompatible 5424 // which doesn't require the arguments ArgumentPromotion wanted to pass. 5425 Function &Fn = *getIRPosition().getAnchorScope(); 5426 SmallPtrSet<Argument *, 1> ArgsToPromote, Dummy; 5427 ArgsToPromote.insert(getAssociatedArgument()); 5428 const auto *TTI = 5429 A.getInfoCache().getAnalysisResultForFunction<TargetIRAnalysis>(Fn); 5430 if (!TTI || 5431 !ArgumentPromotionPass::areFunctionArgsABICompatible( 5432 Fn, *TTI, ArgsToPromote, Dummy) || 5433 ArgsToPromote.empty()) { 5434 LLVM_DEBUG( 5435 dbgs() << "[AAPrivatizablePtr] ABI incompatibility detected for " 5436 << Fn.getName() << "\n"); 5437 return indicatePessimisticFixpoint(); 5438 } 5439 5440 // Collect the types that will replace the privatizable type in the function 5441 // signature. 5442 SmallVector<Type *, 16> ReplacementTypes; 5443 identifyReplacementTypes(PrivatizableType.getValue(), ReplacementTypes); 5444 5445 // Register a rewrite of the argument. 5446 Argument *Arg = getAssociatedArgument(); 5447 if (!A.isValidFunctionSignatureRewrite(*Arg, ReplacementTypes)) { 5448 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Rewrite not valid\n"); 5449 return indicatePessimisticFixpoint(); 5450 } 5451 5452 unsigned ArgNo = Arg->getArgNo(); 5453 5454 // Helper to check if for the given call site the associated argument is 5455 // passed to a callback where the privatization would be different. 5456 auto IsCompatiblePrivArgOfCallback = [&](CallBase &CB) { 5457 SmallVector<const Use *, 4> CallbackUses; 5458 AbstractCallSite::getCallbackUses(CB, CallbackUses); 5459 for (const Use *U : CallbackUses) { 5460 AbstractCallSite CBACS(U); 5461 assert(CBACS && CBACS.isCallbackCall()); 5462 for (Argument &CBArg : CBACS.getCalledFunction()->args()) { 5463 int CBArgNo = CBACS.getCallArgOperandNo(CBArg); 5464 5465 LLVM_DEBUG({ 5466 dbgs() 5467 << "[AAPrivatizablePtr] Argument " << *Arg 5468 << "check if can be privatized in the context of its parent (" 5469 << Arg->getParent()->getName() 5470 << ")\n[AAPrivatizablePtr] because it is an argument in a " 5471 "callback (" 5472 << CBArgNo << "@" << CBACS.getCalledFunction()->getName() 5473 << ")\n[AAPrivatizablePtr] " << CBArg << " : " 5474 << CBACS.getCallArgOperand(CBArg) << " vs " 5475 << CB.getArgOperand(ArgNo) << "\n" 5476 << "[AAPrivatizablePtr] " << CBArg << " : " 5477 << CBACS.getCallArgOperandNo(CBArg) << " vs " << ArgNo << "\n"; 5478 }); 5479 5480 if (CBArgNo != int(ArgNo)) 5481 continue; 5482 const auto &CBArgPrivAA = A.getAAFor<AAPrivatizablePtr>( 5483 *this, IRPosition::argument(CBArg), DepClassTy::REQUIRED); 5484 if (CBArgPrivAA.isValidState()) { 5485 auto CBArgPrivTy = CBArgPrivAA.getPrivatizableType(); 5486 if (!CBArgPrivTy.hasValue()) 5487 continue; 5488 if (CBArgPrivTy.getValue() == PrivatizableType) 5489 continue; 5490 } 5491 5492 LLVM_DEBUG({ 5493 dbgs() << "[AAPrivatizablePtr] Argument " << *Arg 5494 << " cannot be privatized in the context of its parent (" 5495 << Arg->getParent()->getName() 5496 << ")\n[AAPrivatizablePtr] because it is an argument in a " 5497 "callback (" 5498 << CBArgNo << "@" << CBACS.getCalledFunction()->getName() 5499 << ").\n[AAPrivatizablePtr] for which the argument " 5500 "privatization is not compatible.\n"; 5501 }); 5502 return false; 5503 } 5504 } 5505 return true; 5506 }; 5507 5508 // Helper to check if for the given call site the associated argument is 5509 // passed to a direct call where the privatization would be different. 5510 auto IsCompatiblePrivArgOfDirectCS = [&](AbstractCallSite ACS) { 5511 CallBase *DC = cast<CallBase>(ACS.getInstruction()); 5512 int DCArgNo = ACS.getCallArgOperandNo(ArgNo); 5513 assert(DCArgNo >= 0 && unsigned(DCArgNo) < DC->getNumArgOperands() && 5514 "Expected a direct call operand for callback call operand"); 5515 5516 LLVM_DEBUG({ 5517 dbgs() << "[AAPrivatizablePtr] Argument " << *Arg 5518 << " check if be privatized in the context of its parent (" 5519 << Arg->getParent()->getName() 5520 << ")\n[AAPrivatizablePtr] because it is an argument in a " 5521 "direct call of (" 5522 << DCArgNo << "@" << DC->getCalledFunction()->getName() 5523 << ").\n"; 5524 }); 5525 5526 Function *DCCallee = DC->getCalledFunction(); 5527 if (unsigned(DCArgNo) < DCCallee->arg_size()) { 5528 const auto &DCArgPrivAA = A.getAAFor<AAPrivatizablePtr>( 5529 *this, IRPosition::argument(*DCCallee->getArg(DCArgNo)), 5530 DepClassTy::REQUIRED); 5531 if (DCArgPrivAA.isValidState()) { 5532 auto DCArgPrivTy = DCArgPrivAA.getPrivatizableType(); 5533 if (!DCArgPrivTy.hasValue()) 5534 return true; 5535 if (DCArgPrivTy.getValue() == PrivatizableType) 5536 return true; 5537 } 5538 } 5539 5540 LLVM_DEBUG({ 5541 dbgs() << "[AAPrivatizablePtr] Argument " << *Arg 5542 << " cannot be privatized in the context of its parent (" 5543 << Arg->getParent()->getName() 5544 << ")\n[AAPrivatizablePtr] because it is an argument in a " 5545 "direct call of (" 5546 << ACS.getInstruction()->getCalledFunction()->getName() 5547 << ").\n[AAPrivatizablePtr] for which the argument " 5548 "privatization is not compatible.\n"; 5549 }); 5550 return false; 5551 }; 5552 5553 // Helper to check if the associated argument is used at the given abstract 5554 // call site in a way that is incompatible with the privatization assumed 5555 // here. 5556 auto IsCompatiblePrivArgOfOtherCallSite = [&](AbstractCallSite ACS) { 5557 if (ACS.isDirectCall()) 5558 return IsCompatiblePrivArgOfCallback(*ACS.getInstruction()); 5559 if (ACS.isCallbackCall()) 5560 return IsCompatiblePrivArgOfDirectCS(ACS); 5561 return false; 5562 }; 5563 5564 bool AllCallSitesKnown; 5565 if (!A.checkForAllCallSites(IsCompatiblePrivArgOfOtherCallSite, *this, true, 5566 AllCallSitesKnown)) 5567 return indicatePessimisticFixpoint(); 5568 5569 return ChangeStatus::UNCHANGED; 5570 } 5571 5572 /// Given a type to private \p PrivType, collect the constituates (which are 5573 /// used) in \p ReplacementTypes. 5574 static void 5575 identifyReplacementTypes(Type *PrivType, 5576 SmallVectorImpl<Type *> &ReplacementTypes) { 5577 // TODO: For now we expand the privatization type to the fullest which can 5578 // lead to dead arguments that need to be removed later. 5579 assert(PrivType && "Expected privatizable type!"); 5580 5581 // Traverse the type, extract constituate types on the outermost level. 5582 if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) { 5583 for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) 5584 ReplacementTypes.push_back(PrivStructType->getElementType(u)); 5585 } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) { 5586 ReplacementTypes.append(PrivArrayType->getNumElements(), 5587 PrivArrayType->getElementType()); 5588 } else { 5589 ReplacementTypes.push_back(PrivType); 5590 } 5591 } 5592 5593 /// Initialize \p Base according to the type \p PrivType at position \p IP. 5594 /// The values needed are taken from the arguments of \p F starting at 5595 /// position \p ArgNo. 5596 static void createInitialization(Type *PrivType, Value &Base, Function &F, 5597 unsigned ArgNo, Instruction &IP) { 5598 assert(PrivType && "Expected privatizable type!"); 5599 5600 IRBuilder<NoFolder> IRB(&IP); 5601 const DataLayout &DL = F.getParent()->getDataLayout(); 5602 5603 // Traverse the type, build GEPs and stores. 5604 if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) { 5605 const StructLayout *PrivStructLayout = DL.getStructLayout(PrivStructType); 5606 for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) { 5607 Type *PointeeTy = PrivStructType->getElementType(u)->getPointerTo(); 5608 Value *Ptr = 5609 constructPointer(PointeeTy, PrivType, &Base, 5610 PrivStructLayout->getElementOffset(u), IRB, DL); 5611 new StoreInst(F.getArg(ArgNo + u), Ptr, &IP); 5612 } 5613 } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) { 5614 Type *PointeeTy = PrivArrayType->getElementType(); 5615 Type *PointeePtrTy = PointeeTy->getPointerTo(); 5616 uint64_t PointeeTySize = DL.getTypeStoreSize(PointeeTy); 5617 for (unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) { 5618 Value *Ptr = constructPointer(PointeePtrTy, PrivType, &Base, 5619 u * PointeeTySize, IRB, DL); 5620 new StoreInst(F.getArg(ArgNo + u), Ptr, &IP); 5621 } 5622 } else { 5623 new StoreInst(F.getArg(ArgNo), &Base, &IP); 5624 } 5625 } 5626 5627 /// Extract values from \p Base according to the type \p PrivType at the 5628 /// call position \p ACS. The values are appended to \p ReplacementValues. 5629 void createReplacementValues(Align Alignment, Type *PrivType, 5630 AbstractCallSite ACS, Value *Base, 5631 SmallVectorImpl<Value *> &ReplacementValues) { 5632 assert(Base && "Expected base value!"); 5633 assert(PrivType && "Expected privatizable type!"); 5634 Instruction *IP = ACS.getInstruction(); 5635 5636 IRBuilder<NoFolder> IRB(IP); 5637 const DataLayout &DL = IP->getModule()->getDataLayout(); 5638 5639 if (Base->getType()->getPointerElementType() != PrivType) 5640 Base = BitCastInst::CreateBitOrPointerCast(Base, PrivType->getPointerTo(), 5641 "", ACS.getInstruction()); 5642 5643 // Traverse the type, build GEPs and loads. 5644 if (auto *PrivStructType = dyn_cast<StructType>(PrivType)) { 5645 const StructLayout *PrivStructLayout = DL.getStructLayout(PrivStructType); 5646 for (unsigned u = 0, e = PrivStructType->getNumElements(); u < e; u++) { 5647 Type *PointeeTy = PrivStructType->getElementType(u); 5648 Value *Ptr = 5649 constructPointer(PointeeTy->getPointerTo(), PrivType, Base, 5650 PrivStructLayout->getElementOffset(u), IRB, DL); 5651 LoadInst *L = new LoadInst(PointeeTy, Ptr, "", IP); 5652 L->setAlignment(Alignment); 5653 ReplacementValues.push_back(L); 5654 } 5655 } else if (auto *PrivArrayType = dyn_cast<ArrayType>(PrivType)) { 5656 Type *PointeeTy = PrivArrayType->getElementType(); 5657 uint64_t PointeeTySize = DL.getTypeStoreSize(PointeeTy); 5658 Type *PointeePtrTy = PointeeTy->getPointerTo(); 5659 for (unsigned u = 0, e = PrivArrayType->getNumElements(); u < e; u++) { 5660 Value *Ptr = constructPointer(PointeePtrTy, PrivType, Base, 5661 u * PointeeTySize, IRB, DL); 5662 LoadInst *L = new LoadInst(PointeeTy, Ptr, "", IP); 5663 L->setAlignment(Alignment); 5664 ReplacementValues.push_back(L); 5665 } 5666 } else { 5667 LoadInst *L = new LoadInst(PrivType, Base, "", IP); 5668 L->setAlignment(Alignment); 5669 ReplacementValues.push_back(L); 5670 } 5671 } 5672 5673 /// See AbstractAttribute::manifest(...) 5674 ChangeStatus manifest(Attributor &A) override { 5675 if (!PrivatizableType.hasValue()) 5676 return ChangeStatus::UNCHANGED; 5677 assert(PrivatizableType.getValue() && "Expected privatizable type!"); 5678 5679 // Collect all tail calls in the function as we cannot allow new allocas to 5680 // escape into tail recursion. 5681 // TODO: Be smarter about new allocas escaping into tail calls. 5682 SmallVector<CallInst *, 16> TailCalls; 5683 if (!A.checkForAllInstructions( 5684 [&](Instruction &I) { 5685 CallInst &CI = cast<CallInst>(I); 5686 if (CI.isTailCall()) 5687 TailCalls.push_back(&CI); 5688 return true; 5689 }, 5690 *this, {Instruction::Call})) 5691 return ChangeStatus::UNCHANGED; 5692 5693 Argument *Arg = getAssociatedArgument(); 5694 // Query AAAlign attribute for alignment of associated argument to 5695 // determine the best alignment of loads. 5696 const auto &AlignAA = 5697 A.getAAFor<AAAlign>(*this, IRPosition::value(*Arg), DepClassTy::NONE); 5698 5699 // Callback to repair the associated function. A new alloca is placed at the 5700 // beginning and initialized with the values passed through arguments. The 5701 // new alloca replaces the use of the old pointer argument. 5702 Attributor::ArgumentReplacementInfo::CalleeRepairCBTy FnRepairCB = 5703 [=](const Attributor::ArgumentReplacementInfo &ARI, 5704 Function &ReplacementFn, Function::arg_iterator ArgIt) { 5705 BasicBlock &EntryBB = ReplacementFn.getEntryBlock(); 5706 Instruction *IP = &*EntryBB.getFirstInsertionPt(); 5707 Instruction *AI = new AllocaInst(PrivatizableType.getValue(), 0, 5708 Arg->getName() + ".priv", IP); 5709 createInitialization(PrivatizableType.getValue(), *AI, ReplacementFn, 5710 ArgIt->getArgNo(), *IP); 5711 5712 if (AI->getType() != Arg->getType()) 5713 AI = 5714 BitCastInst::CreateBitOrPointerCast(AI, Arg->getType(), "", IP); 5715 Arg->replaceAllUsesWith(AI); 5716 5717 for (CallInst *CI : TailCalls) 5718 CI->setTailCall(false); 5719 }; 5720 5721 // Callback to repair a call site of the associated function. The elements 5722 // of the privatizable type are loaded prior to the call and passed to the 5723 // new function version. 5724 Attributor::ArgumentReplacementInfo::ACSRepairCBTy ACSRepairCB = 5725 [=, &AlignAA](const Attributor::ArgumentReplacementInfo &ARI, 5726 AbstractCallSite ACS, 5727 SmallVectorImpl<Value *> &NewArgOperands) { 5728 // When no alignment is specified for the load instruction, 5729 // natural alignment is assumed. 5730 createReplacementValues( 5731 assumeAligned(AlignAA.getAssumedAlign()), 5732 PrivatizableType.getValue(), ACS, 5733 ACS.getCallArgOperand(ARI.getReplacedArg().getArgNo()), 5734 NewArgOperands); 5735 }; 5736 5737 // Collect the types that will replace the privatizable type in the function 5738 // signature. 5739 SmallVector<Type *, 16> ReplacementTypes; 5740 identifyReplacementTypes(PrivatizableType.getValue(), ReplacementTypes); 5741 5742 // Register a rewrite of the argument. 5743 if (A.registerFunctionSignatureRewrite(*Arg, ReplacementTypes, 5744 std::move(FnRepairCB), 5745 std::move(ACSRepairCB))) 5746 return ChangeStatus::CHANGED; 5747 return ChangeStatus::UNCHANGED; 5748 } 5749 5750 /// See AbstractAttribute::trackStatistics() 5751 void trackStatistics() const override { 5752 STATS_DECLTRACK_ARG_ATTR(privatizable_ptr); 5753 } 5754 }; 5755 5756 struct AAPrivatizablePtrFloating : public AAPrivatizablePtrImpl { 5757 AAPrivatizablePtrFloating(const IRPosition &IRP, Attributor &A) 5758 : AAPrivatizablePtrImpl(IRP, A) {} 5759 5760 /// See AbstractAttribute::initialize(...). 5761 virtual void initialize(Attributor &A) override { 5762 // TODO: We can privatize more than arguments. 5763 indicatePessimisticFixpoint(); 5764 } 5765 5766 ChangeStatus updateImpl(Attributor &A) override { 5767 llvm_unreachable("AAPrivatizablePtr(Floating|Returned|CallSiteReturned)::" 5768 "updateImpl will not be called"); 5769 } 5770 5771 /// See AAPrivatizablePtrImpl::identifyPrivatizableType(...) 5772 Optional<Type *> identifyPrivatizableType(Attributor &A) override { 5773 Value *Obj = getUnderlyingObject(&getAssociatedValue()); 5774 if (!Obj) { 5775 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] No underlying object found!\n"); 5776 return nullptr; 5777 } 5778 5779 if (auto *AI = dyn_cast<AllocaInst>(Obj)) 5780 if (auto *CI = dyn_cast<ConstantInt>(AI->getArraySize())) 5781 if (CI->isOne()) 5782 return Obj->getType()->getPointerElementType(); 5783 if (auto *Arg = dyn_cast<Argument>(Obj)) { 5784 auto &PrivArgAA = A.getAAFor<AAPrivatizablePtr>( 5785 *this, IRPosition::argument(*Arg), DepClassTy::REQUIRED); 5786 if (PrivArgAA.isAssumedPrivatizablePtr()) 5787 return Obj->getType()->getPointerElementType(); 5788 } 5789 5790 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] Underlying object neither valid " 5791 "alloca nor privatizable argument: " 5792 << *Obj << "!\n"); 5793 return nullptr; 5794 } 5795 5796 /// See AbstractAttribute::trackStatistics() 5797 void trackStatistics() const override { 5798 STATS_DECLTRACK_FLOATING_ATTR(privatizable_ptr); 5799 } 5800 }; 5801 5802 struct AAPrivatizablePtrCallSiteArgument final 5803 : public AAPrivatizablePtrFloating { 5804 AAPrivatizablePtrCallSiteArgument(const IRPosition &IRP, Attributor &A) 5805 : AAPrivatizablePtrFloating(IRP, A) {} 5806 5807 /// See AbstractAttribute::initialize(...). 5808 void initialize(Attributor &A) override { 5809 if (getIRPosition().hasAttr(Attribute::ByVal)) 5810 indicateOptimisticFixpoint(); 5811 } 5812 5813 /// See AbstractAttribute::updateImpl(...). 5814 ChangeStatus updateImpl(Attributor &A) override { 5815 PrivatizableType = identifyPrivatizableType(A); 5816 if (!PrivatizableType.hasValue()) 5817 return ChangeStatus::UNCHANGED; 5818 if (!PrivatizableType.getValue()) 5819 return indicatePessimisticFixpoint(); 5820 5821 const IRPosition &IRP = getIRPosition(); 5822 auto &NoCaptureAA = 5823 A.getAAFor<AANoCapture>(*this, IRP, DepClassTy::REQUIRED); 5824 if (!NoCaptureAA.isAssumedNoCapture()) { 5825 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer might be captured!\n"); 5826 return indicatePessimisticFixpoint(); 5827 } 5828 5829 auto &NoAliasAA = A.getAAFor<AANoAlias>(*this, IRP, DepClassTy::REQUIRED); 5830 if (!NoAliasAA.isAssumedNoAlias()) { 5831 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer might alias!\n"); 5832 return indicatePessimisticFixpoint(); 5833 } 5834 5835 const auto &MemBehaviorAA = 5836 A.getAAFor<AAMemoryBehavior>(*this, IRP, DepClassTy::REQUIRED); 5837 if (!MemBehaviorAA.isAssumedReadOnly()) { 5838 LLVM_DEBUG(dbgs() << "[AAPrivatizablePtr] pointer is written!\n"); 5839 return indicatePessimisticFixpoint(); 5840 } 5841 5842 return ChangeStatus::UNCHANGED; 5843 } 5844 5845 /// See AbstractAttribute::trackStatistics() 5846 void trackStatistics() const override { 5847 STATS_DECLTRACK_CSARG_ATTR(privatizable_ptr); 5848 } 5849 }; 5850 5851 struct AAPrivatizablePtrCallSiteReturned final 5852 : public AAPrivatizablePtrFloating { 5853 AAPrivatizablePtrCallSiteReturned(const IRPosition &IRP, Attributor &A) 5854 : AAPrivatizablePtrFloating(IRP, A) {} 5855 5856 /// See AbstractAttribute::initialize(...). 5857 void initialize(Attributor &A) override { 5858 // TODO: We can privatize more than arguments. 5859 indicatePessimisticFixpoint(); 5860 } 5861 5862 /// See AbstractAttribute::trackStatistics() 5863 void trackStatistics() const override { 5864 STATS_DECLTRACK_CSRET_ATTR(privatizable_ptr); 5865 } 5866 }; 5867 5868 struct AAPrivatizablePtrReturned final : public AAPrivatizablePtrFloating { 5869 AAPrivatizablePtrReturned(const IRPosition &IRP, Attributor &A) 5870 : AAPrivatizablePtrFloating(IRP, A) {} 5871 5872 /// See AbstractAttribute::initialize(...). 5873 void initialize(Attributor &A) override { 5874 // TODO: We can privatize more than arguments. 5875 indicatePessimisticFixpoint(); 5876 } 5877 5878 /// See AbstractAttribute::trackStatistics() 5879 void trackStatistics() const override { 5880 STATS_DECLTRACK_FNRET_ATTR(privatizable_ptr); 5881 } 5882 }; 5883 5884 /// -------------------- Memory Behavior Attributes ---------------------------- 5885 /// Includes read-none, read-only, and write-only. 5886 /// ---------------------------------------------------------------------------- 5887 struct AAMemoryBehaviorImpl : public AAMemoryBehavior { 5888 AAMemoryBehaviorImpl(const IRPosition &IRP, Attributor &A) 5889 : AAMemoryBehavior(IRP, A) {} 5890 5891 /// See AbstractAttribute::initialize(...). 5892 void initialize(Attributor &A) override { 5893 intersectAssumedBits(BEST_STATE); 5894 getKnownStateFromValue(getIRPosition(), getState()); 5895 AAMemoryBehavior::initialize(A); 5896 } 5897 5898 /// Return the memory behavior information encoded in the IR for \p IRP. 5899 static void getKnownStateFromValue(const IRPosition &IRP, 5900 BitIntegerState &State, 5901 bool IgnoreSubsumingPositions = false) { 5902 SmallVector<Attribute, 2> Attrs; 5903 IRP.getAttrs(AttrKinds, Attrs, IgnoreSubsumingPositions); 5904 for (const Attribute &Attr : Attrs) { 5905 switch (Attr.getKindAsEnum()) { 5906 case Attribute::ReadNone: 5907 State.addKnownBits(NO_ACCESSES); 5908 break; 5909 case Attribute::ReadOnly: 5910 State.addKnownBits(NO_WRITES); 5911 break; 5912 case Attribute::WriteOnly: 5913 State.addKnownBits(NO_READS); 5914 break; 5915 default: 5916 llvm_unreachable("Unexpected attribute!"); 5917 } 5918 } 5919 5920 if (auto *I = dyn_cast<Instruction>(&IRP.getAnchorValue())) { 5921 if (!I->mayReadFromMemory()) 5922 State.addKnownBits(NO_READS); 5923 if (!I->mayWriteToMemory()) 5924 State.addKnownBits(NO_WRITES); 5925 } 5926 } 5927 5928 /// See AbstractAttribute::getDeducedAttributes(...). 5929 void getDeducedAttributes(LLVMContext &Ctx, 5930 SmallVectorImpl<Attribute> &Attrs) const override { 5931 assert(Attrs.size() == 0); 5932 if (isAssumedReadNone()) 5933 Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone)); 5934 else if (isAssumedReadOnly()) 5935 Attrs.push_back(Attribute::get(Ctx, Attribute::ReadOnly)); 5936 else if (isAssumedWriteOnly()) 5937 Attrs.push_back(Attribute::get(Ctx, Attribute::WriteOnly)); 5938 assert(Attrs.size() <= 1); 5939 } 5940 5941 /// See AbstractAttribute::manifest(...). 5942 ChangeStatus manifest(Attributor &A) override { 5943 if (hasAttr(Attribute::ReadNone, /* IgnoreSubsumingPositions */ true)) 5944 return ChangeStatus::UNCHANGED; 5945 5946 const IRPosition &IRP = getIRPosition(); 5947 5948 // Check if we would improve the existing attributes first. 5949 SmallVector<Attribute, 4> DeducedAttrs; 5950 getDeducedAttributes(IRP.getAnchorValue().getContext(), DeducedAttrs); 5951 if (llvm::all_of(DeducedAttrs, [&](const Attribute &Attr) { 5952 return IRP.hasAttr(Attr.getKindAsEnum(), 5953 /* IgnoreSubsumingPositions */ true); 5954 })) 5955 return ChangeStatus::UNCHANGED; 5956 5957 // Clear existing attributes. 5958 IRP.removeAttrs(AttrKinds); 5959 5960 // Use the generic manifest method. 5961 return IRAttribute::manifest(A); 5962 } 5963 5964 /// See AbstractState::getAsStr(). 5965 const std::string getAsStr() const override { 5966 if (isAssumedReadNone()) 5967 return "readnone"; 5968 if (isAssumedReadOnly()) 5969 return "readonly"; 5970 if (isAssumedWriteOnly()) 5971 return "writeonly"; 5972 return "may-read/write"; 5973 } 5974 5975 /// The set of IR attributes AAMemoryBehavior deals with. 5976 static const Attribute::AttrKind AttrKinds[3]; 5977 }; 5978 5979 const Attribute::AttrKind AAMemoryBehaviorImpl::AttrKinds[] = { 5980 Attribute::ReadNone, Attribute::ReadOnly, Attribute::WriteOnly}; 5981 5982 /// Memory behavior attribute for a floating value. 5983 struct AAMemoryBehaviorFloating : AAMemoryBehaviorImpl { 5984 AAMemoryBehaviorFloating(const IRPosition &IRP, Attributor &A) 5985 : AAMemoryBehaviorImpl(IRP, A) {} 5986 5987 /// See AbstractAttribute::initialize(...). 5988 void initialize(Attributor &A) override { 5989 AAMemoryBehaviorImpl::initialize(A); 5990 addUsesOf(A, getAssociatedValue()); 5991 } 5992 5993 /// See AbstractAttribute::updateImpl(...). 5994 ChangeStatus updateImpl(Attributor &A) override; 5995 5996 /// See AbstractAttribute::trackStatistics() 5997 void trackStatistics() const override { 5998 if (isAssumedReadNone()) 5999 STATS_DECLTRACK_FLOATING_ATTR(readnone) 6000 else if (isAssumedReadOnly()) 6001 STATS_DECLTRACK_FLOATING_ATTR(readonly) 6002 else if (isAssumedWriteOnly()) 6003 STATS_DECLTRACK_FLOATING_ATTR(writeonly) 6004 } 6005 6006 private: 6007 /// Return true if users of \p UserI might access the underlying 6008 /// variable/location described by \p U and should therefore be analyzed. 6009 bool followUsersOfUseIn(Attributor &A, const Use *U, 6010 const Instruction *UserI); 6011 6012 /// Update the state according to the effect of use \p U in \p UserI. 6013 void analyzeUseIn(Attributor &A, const Use *U, const Instruction *UserI); 6014 6015 protected: 6016 /// Add the uses of \p V to the `Uses` set we look at during the update step. 6017 void addUsesOf(Attributor &A, const Value &V); 6018 6019 /// Container for (transitive) uses of the associated argument. 6020 SmallVector<const Use *, 8> Uses; 6021 6022 /// Set to remember the uses we already traversed. 6023 SmallPtrSet<const Use *, 8> Visited; 6024 }; 6025 6026 /// Memory behavior attribute for function argument. 6027 struct AAMemoryBehaviorArgument : AAMemoryBehaviorFloating { 6028 AAMemoryBehaviorArgument(const IRPosition &IRP, Attributor &A) 6029 : AAMemoryBehaviorFloating(IRP, A) {} 6030 6031 /// See AbstractAttribute::initialize(...). 6032 void initialize(Attributor &A) override { 6033 intersectAssumedBits(BEST_STATE); 6034 const IRPosition &IRP = getIRPosition(); 6035 // TODO: Make IgnoreSubsumingPositions a property of an IRAttribute so we 6036 // can query it when we use has/getAttr. That would allow us to reuse the 6037 // initialize of the base class here. 6038 bool HasByVal = 6039 IRP.hasAttr({Attribute::ByVal}, /* IgnoreSubsumingPositions */ true); 6040 getKnownStateFromValue(IRP, getState(), 6041 /* IgnoreSubsumingPositions */ HasByVal); 6042 6043 // Initialize the use vector with all direct uses of the associated value. 6044 Argument *Arg = getAssociatedArgument(); 6045 if (!Arg || !A.isFunctionIPOAmendable(*(Arg->getParent()))) { 6046 indicatePessimisticFixpoint(); 6047 } else { 6048 addUsesOf(A, *Arg); 6049 } 6050 } 6051 6052 ChangeStatus manifest(Attributor &A) override { 6053 // TODO: Pointer arguments are not supported on vectors of pointers yet. 6054 if (!getAssociatedValue().getType()->isPointerTy()) 6055 return ChangeStatus::UNCHANGED; 6056 6057 // TODO: From readattrs.ll: "inalloca parameters are always 6058 // considered written" 6059 if (hasAttr({Attribute::InAlloca, Attribute::Preallocated})) { 6060 removeKnownBits(NO_WRITES); 6061 removeAssumedBits(NO_WRITES); 6062 } 6063 return AAMemoryBehaviorFloating::manifest(A); 6064 } 6065 6066 /// See AbstractAttribute::trackStatistics() 6067 void trackStatistics() const override { 6068 if (isAssumedReadNone()) 6069 STATS_DECLTRACK_ARG_ATTR(readnone) 6070 else if (isAssumedReadOnly()) 6071 STATS_DECLTRACK_ARG_ATTR(readonly) 6072 else if (isAssumedWriteOnly()) 6073 STATS_DECLTRACK_ARG_ATTR(writeonly) 6074 } 6075 }; 6076 6077 struct AAMemoryBehaviorCallSiteArgument final : AAMemoryBehaviorArgument { 6078 AAMemoryBehaviorCallSiteArgument(const IRPosition &IRP, Attributor &A) 6079 : AAMemoryBehaviorArgument(IRP, A) {} 6080 6081 /// See AbstractAttribute::initialize(...). 6082 void initialize(Attributor &A) override { 6083 // If we don't have an associated attribute this is either a variadic call 6084 // or an indirect call, either way, nothing to do here. 6085 Argument *Arg = getAssociatedArgument(); 6086 if (!Arg) { 6087 indicatePessimisticFixpoint(); 6088 return; 6089 } 6090 if (Arg->hasByValAttr()) { 6091 addKnownBits(NO_WRITES); 6092 removeKnownBits(NO_READS); 6093 removeAssumedBits(NO_READS); 6094 } 6095 AAMemoryBehaviorArgument::initialize(A); 6096 if (getAssociatedFunction()->isDeclaration()) 6097 indicatePessimisticFixpoint(); 6098 } 6099 6100 /// See AbstractAttribute::updateImpl(...). 6101 ChangeStatus updateImpl(Attributor &A) override { 6102 // TODO: Once we have call site specific value information we can provide 6103 // call site specific liveness liveness information and then it makes 6104 // sense to specialize attributes for call sites arguments instead of 6105 // redirecting requests to the callee argument. 6106 Argument *Arg = getAssociatedArgument(); 6107 const IRPosition &ArgPos = IRPosition::argument(*Arg); 6108 auto &ArgAA = 6109 A.getAAFor<AAMemoryBehavior>(*this, ArgPos, DepClassTy::REQUIRED); 6110 return clampStateAndIndicateChange(getState(), ArgAA.getState()); 6111 } 6112 6113 /// See AbstractAttribute::trackStatistics() 6114 void trackStatistics() const override { 6115 if (isAssumedReadNone()) 6116 STATS_DECLTRACK_CSARG_ATTR(readnone) 6117 else if (isAssumedReadOnly()) 6118 STATS_DECLTRACK_CSARG_ATTR(readonly) 6119 else if (isAssumedWriteOnly()) 6120 STATS_DECLTRACK_CSARG_ATTR(writeonly) 6121 } 6122 }; 6123 6124 /// Memory behavior attribute for a call site return position. 6125 struct AAMemoryBehaviorCallSiteReturned final : AAMemoryBehaviorFloating { 6126 AAMemoryBehaviorCallSiteReturned(const IRPosition &IRP, Attributor &A) 6127 : AAMemoryBehaviorFloating(IRP, A) {} 6128 6129 /// See AbstractAttribute::initialize(...). 6130 void initialize(Attributor &A) override { 6131 AAMemoryBehaviorImpl::initialize(A); 6132 Function *F = getAssociatedFunction(); 6133 if (!F || F->isDeclaration()) 6134 indicatePessimisticFixpoint(); 6135 } 6136 6137 /// See AbstractAttribute::manifest(...). 6138 ChangeStatus manifest(Attributor &A) override { 6139 // We do not annotate returned values. 6140 return ChangeStatus::UNCHANGED; 6141 } 6142 6143 /// See AbstractAttribute::trackStatistics() 6144 void trackStatistics() const override {} 6145 }; 6146 6147 /// An AA to represent the memory behavior function attributes. 6148 struct AAMemoryBehaviorFunction final : public AAMemoryBehaviorImpl { 6149 AAMemoryBehaviorFunction(const IRPosition &IRP, Attributor &A) 6150 : AAMemoryBehaviorImpl(IRP, A) {} 6151 6152 /// See AbstractAttribute::updateImpl(Attributor &A). 6153 virtual ChangeStatus updateImpl(Attributor &A) override; 6154 6155 /// See AbstractAttribute::manifest(...). 6156 ChangeStatus manifest(Attributor &A) override { 6157 Function &F = cast<Function>(getAnchorValue()); 6158 if (isAssumedReadNone()) { 6159 F.removeFnAttr(Attribute::ArgMemOnly); 6160 F.removeFnAttr(Attribute::InaccessibleMemOnly); 6161 F.removeFnAttr(Attribute::InaccessibleMemOrArgMemOnly); 6162 } 6163 return AAMemoryBehaviorImpl::manifest(A); 6164 } 6165 6166 /// See AbstractAttribute::trackStatistics() 6167 void trackStatistics() const override { 6168 if (isAssumedReadNone()) 6169 STATS_DECLTRACK_FN_ATTR(readnone) 6170 else if (isAssumedReadOnly()) 6171 STATS_DECLTRACK_FN_ATTR(readonly) 6172 else if (isAssumedWriteOnly()) 6173 STATS_DECLTRACK_FN_ATTR(writeonly) 6174 } 6175 }; 6176 6177 /// AAMemoryBehavior attribute for call sites. 6178 struct AAMemoryBehaviorCallSite final : AAMemoryBehaviorImpl { 6179 AAMemoryBehaviorCallSite(const IRPosition &IRP, Attributor &A) 6180 : AAMemoryBehaviorImpl(IRP, A) {} 6181 6182 /// See AbstractAttribute::initialize(...). 6183 void initialize(Attributor &A) override { 6184 AAMemoryBehaviorImpl::initialize(A); 6185 Function *F = getAssociatedFunction(); 6186 if (!F || F->isDeclaration()) 6187 indicatePessimisticFixpoint(); 6188 } 6189 6190 /// See AbstractAttribute::updateImpl(...). 6191 ChangeStatus updateImpl(Attributor &A) override { 6192 // TODO: Once we have call site specific value information we can provide 6193 // call site specific liveness liveness information and then it makes 6194 // sense to specialize attributes for call sites arguments instead of 6195 // redirecting requests to the callee argument. 6196 Function *F = getAssociatedFunction(); 6197 const IRPosition &FnPos = IRPosition::function(*F); 6198 auto &FnAA = 6199 A.getAAFor<AAMemoryBehavior>(*this, FnPos, DepClassTy::REQUIRED); 6200 return clampStateAndIndicateChange(getState(), FnAA.getState()); 6201 } 6202 6203 /// See AbstractAttribute::trackStatistics() 6204 void trackStatistics() const override { 6205 if (isAssumedReadNone()) 6206 STATS_DECLTRACK_CS_ATTR(readnone) 6207 else if (isAssumedReadOnly()) 6208 STATS_DECLTRACK_CS_ATTR(readonly) 6209 else if (isAssumedWriteOnly()) 6210 STATS_DECLTRACK_CS_ATTR(writeonly) 6211 } 6212 }; 6213 6214 ChangeStatus AAMemoryBehaviorFunction::updateImpl(Attributor &A) { 6215 6216 // The current assumed state used to determine a change. 6217 auto AssumedState = getAssumed(); 6218 6219 auto CheckRWInst = [&](Instruction &I) { 6220 // If the instruction has an own memory behavior state, use it to restrict 6221 // the local state. No further analysis is required as the other memory 6222 // state is as optimistic as it gets. 6223 if (const auto *CB = dyn_cast<CallBase>(&I)) { 6224 const auto &MemBehaviorAA = A.getAAFor<AAMemoryBehavior>( 6225 *this, IRPosition::callsite_function(*CB), DepClassTy::REQUIRED); 6226 intersectAssumedBits(MemBehaviorAA.getAssumed()); 6227 return !isAtFixpoint(); 6228 } 6229 6230 // Remove access kind modifiers if necessary. 6231 if (I.mayReadFromMemory()) 6232 removeAssumedBits(NO_READS); 6233 if (I.mayWriteToMemory()) 6234 removeAssumedBits(NO_WRITES); 6235 return !isAtFixpoint(); 6236 }; 6237 6238 if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this)) 6239 return indicatePessimisticFixpoint(); 6240 6241 return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED 6242 : ChangeStatus::UNCHANGED; 6243 } 6244 6245 ChangeStatus AAMemoryBehaviorFloating::updateImpl(Attributor &A) { 6246 6247 const IRPosition &IRP = getIRPosition(); 6248 const IRPosition &FnPos = IRPosition::function_scope(IRP); 6249 AAMemoryBehavior::StateType &S = getState(); 6250 6251 // First, check the function scope. We take the known information and we avoid 6252 // work if the assumed information implies the current assumed information for 6253 // this attribute. This is a valid for all but byval arguments. 6254 Argument *Arg = IRP.getAssociatedArgument(); 6255 AAMemoryBehavior::base_t FnMemAssumedState = 6256 AAMemoryBehavior::StateType::getWorstState(); 6257 if (!Arg || !Arg->hasByValAttr()) { 6258 const auto &FnMemAA = 6259 A.getAAFor<AAMemoryBehavior>(*this, FnPos, DepClassTy::OPTIONAL); 6260 FnMemAssumedState = FnMemAA.getAssumed(); 6261 S.addKnownBits(FnMemAA.getKnown()); 6262 if ((S.getAssumed() & FnMemAA.getAssumed()) == S.getAssumed()) 6263 return ChangeStatus::UNCHANGED; 6264 } 6265 6266 // Make sure the value is not captured (except through "return"), if 6267 // it is, any information derived would be irrelevant anyway as we cannot 6268 // check the potential aliases introduced by the capture. However, no need 6269 // to fall back to anythign less optimistic than the function state. 6270 const auto &ArgNoCaptureAA = 6271 A.getAAFor<AANoCapture>(*this, IRP, DepClassTy::OPTIONAL); 6272 if (!ArgNoCaptureAA.isAssumedNoCaptureMaybeReturned()) { 6273 S.intersectAssumedBits(FnMemAssumedState); 6274 return ChangeStatus::CHANGED; 6275 } 6276 6277 // The current assumed state used to determine a change. 6278 auto AssumedState = S.getAssumed(); 6279 6280 // Liveness information to exclude dead users. 6281 // TODO: Take the FnPos once we have call site specific liveness information. 6282 const auto &LivenessAA = A.getAAFor<AAIsDead>( 6283 *this, IRPosition::function(*IRP.getAssociatedFunction()), 6284 DepClassTy::NONE); 6285 6286 // Visit and expand uses until all are analyzed or a fixpoint is reached. 6287 for (unsigned i = 0; i < Uses.size() && !isAtFixpoint(); i++) { 6288 const Use *U = Uses[i]; 6289 Instruction *UserI = cast<Instruction>(U->getUser()); 6290 LLVM_DEBUG(dbgs() << "[AAMemoryBehavior] Use: " << **U << " in " << *UserI 6291 << " [Dead: " << (A.isAssumedDead(*U, this, &LivenessAA)) 6292 << "]\n"); 6293 if (A.isAssumedDead(*U, this, &LivenessAA)) 6294 continue; 6295 6296 // Droppable users, e.g., llvm::assume does not actually perform any action. 6297 if (UserI->isDroppable()) 6298 continue; 6299 6300 // Check if the users of UserI should also be visited. 6301 if (followUsersOfUseIn(A, U, UserI)) 6302 addUsesOf(A, *UserI); 6303 6304 // If UserI might touch memory we analyze the use in detail. 6305 if (UserI->mayReadOrWriteMemory()) 6306 analyzeUseIn(A, U, UserI); 6307 } 6308 6309 return (AssumedState != getAssumed()) ? ChangeStatus::CHANGED 6310 : ChangeStatus::UNCHANGED; 6311 } 6312 6313 void AAMemoryBehaviorFloating::addUsesOf(Attributor &A, const Value &V) { 6314 SmallVector<const Use *, 8> WL; 6315 for (const Use &U : V.uses()) 6316 WL.push_back(&U); 6317 6318 while (!WL.empty()) { 6319 const Use *U = WL.pop_back_val(); 6320 if (!Visited.insert(U).second) 6321 continue; 6322 6323 const Instruction *UserI = cast<Instruction>(U->getUser()); 6324 if (UserI->mayReadOrWriteMemory()) { 6325 Uses.push_back(U); 6326 continue; 6327 } 6328 if (!followUsersOfUseIn(A, U, UserI)) 6329 continue; 6330 for (const Use &UU : UserI->uses()) 6331 WL.push_back(&UU); 6332 } 6333 } 6334 6335 bool AAMemoryBehaviorFloating::followUsersOfUseIn(Attributor &A, const Use *U, 6336 const Instruction *UserI) { 6337 // The loaded value is unrelated to the pointer argument, no need to 6338 // follow the users of the load. 6339 if (isa<LoadInst>(UserI)) 6340 return false; 6341 6342 // By default we follow all uses assuming UserI might leak information on U, 6343 // we have special handling for call sites operands though. 6344 const auto *CB = dyn_cast<CallBase>(UserI); 6345 if (!CB || !CB->isArgOperand(U)) 6346 return true; 6347 6348 // If the use is a call argument known not to be captured, the users of 6349 // the call do not need to be visited because they have to be unrelated to 6350 // the input. Note that this check is not trivial even though we disallow 6351 // general capturing of the underlying argument. The reason is that the 6352 // call might the argument "through return", which we allow and for which we 6353 // need to check call users. 6354 if (U->get()->getType()->isPointerTy()) { 6355 unsigned ArgNo = CB->getArgOperandNo(U); 6356 const auto &ArgNoCaptureAA = A.getAAFor<AANoCapture>( 6357 *this, IRPosition::callsite_argument(*CB, ArgNo), DepClassTy::OPTIONAL); 6358 return !ArgNoCaptureAA.isAssumedNoCapture(); 6359 } 6360 6361 return true; 6362 } 6363 6364 void AAMemoryBehaviorFloating::analyzeUseIn(Attributor &A, const Use *U, 6365 const Instruction *UserI) { 6366 assert(UserI->mayReadOrWriteMemory()); 6367 6368 switch (UserI->getOpcode()) { 6369 default: 6370 // TODO: Handle all atomics and other side-effect operations we know of. 6371 break; 6372 case Instruction::Load: 6373 // Loads cause the NO_READS property to disappear. 6374 removeAssumedBits(NO_READS); 6375 return; 6376 6377 case Instruction::Store: 6378 // Stores cause the NO_WRITES property to disappear if the use is the 6379 // pointer operand. Note that we do assume that capturing was taken care of 6380 // somewhere else. 6381 if (cast<StoreInst>(UserI)->getPointerOperand() == U->get()) 6382 removeAssumedBits(NO_WRITES); 6383 return; 6384 6385 case Instruction::Call: 6386 case Instruction::CallBr: 6387 case Instruction::Invoke: { 6388 // For call sites we look at the argument memory behavior attribute (this 6389 // could be recursive!) in order to restrict our own state. 6390 const auto *CB = cast<CallBase>(UserI); 6391 6392 // Give up on operand bundles. 6393 if (CB->isBundleOperand(U)) { 6394 indicatePessimisticFixpoint(); 6395 return; 6396 } 6397 6398 // Calling a function does read the function pointer, maybe write it if the 6399 // function is self-modifying. 6400 if (CB->isCallee(U)) { 6401 removeAssumedBits(NO_READS); 6402 break; 6403 } 6404 6405 // Adjust the possible access behavior based on the information on the 6406 // argument. 6407 IRPosition Pos; 6408 if (U->get()->getType()->isPointerTy()) 6409 Pos = IRPosition::callsite_argument(*CB, CB->getArgOperandNo(U)); 6410 else 6411 Pos = IRPosition::callsite_function(*CB); 6412 const auto &MemBehaviorAA = 6413 A.getAAFor<AAMemoryBehavior>(*this, Pos, DepClassTy::OPTIONAL); 6414 // "assumed" has at most the same bits as the MemBehaviorAA assumed 6415 // and at least "known". 6416 intersectAssumedBits(MemBehaviorAA.getAssumed()); 6417 return; 6418 } 6419 }; 6420 6421 // Generally, look at the "may-properties" and adjust the assumed state if we 6422 // did not trigger special handling before. 6423 if (UserI->mayReadFromMemory()) 6424 removeAssumedBits(NO_READS); 6425 if (UserI->mayWriteToMemory()) 6426 removeAssumedBits(NO_WRITES); 6427 } 6428 6429 } // namespace 6430 6431 /// -------------------- Memory Locations Attributes --------------------------- 6432 /// Includes read-none, argmemonly, inaccessiblememonly, 6433 /// inaccessiblememorargmemonly 6434 /// ---------------------------------------------------------------------------- 6435 6436 std::string AAMemoryLocation::getMemoryLocationsAsStr( 6437 AAMemoryLocation::MemoryLocationsKind MLK) { 6438 if (0 == (MLK & AAMemoryLocation::NO_LOCATIONS)) 6439 return "all memory"; 6440 if (MLK == AAMemoryLocation::NO_LOCATIONS) 6441 return "no memory"; 6442 std::string S = "memory:"; 6443 if (0 == (MLK & AAMemoryLocation::NO_LOCAL_MEM)) 6444 S += "stack,"; 6445 if (0 == (MLK & AAMemoryLocation::NO_CONST_MEM)) 6446 S += "constant,"; 6447 if (0 == (MLK & AAMemoryLocation::NO_GLOBAL_INTERNAL_MEM)) 6448 S += "internal global,"; 6449 if (0 == (MLK & AAMemoryLocation::NO_GLOBAL_EXTERNAL_MEM)) 6450 S += "external global,"; 6451 if (0 == (MLK & AAMemoryLocation::NO_ARGUMENT_MEM)) 6452 S += "argument,"; 6453 if (0 == (MLK & AAMemoryLocation::NO_INACCESSIBLE_MEM)) 6454 S += "inaccessible,"; 6455 if (0 == (MLK & AAMemoryLocation::NO_MALLOCED_MEM)) 6456 S += "malloced,"; 6457 if (0 == (MLK & AAMemoryLocation::NO_UNKOWN_MEM)) 6458 S += "unknown,"; 6459 S.pop_back(); 6460 return S; 6461 } 6462 6463 namespace { 6464 struct AAMemoryLocationImpl : public AAMemoryLocation { 6465 6466 AAMemoryLocationImpl(const IRPosition &IRP, Attributor &A) 6467 : AAMemoryLocation(IRP, A), Allocator(A.Allocator) { 6468 for (unsigned u = 0; u < llvm::CTLog2<VALID_STATE>(); ++u) 6469 AccessKind2Accesses[u] = nullptr; 6470 } 6471 6472 ~AAMemoryLocationImpl() { 6473 // The AccessSets are allocated via a BumpPtrAllocator, we call 6474 // the destructor manually. 6475 for (unsigned u = 0; u < llvm::CTLog2<VALID_STATE>(); ++u) 6476 if (AccessKind2Accesses[u]) 6477 AccessKind2Accesses[u]->~AccessSet(); 6478 } 6479 6480 /// See AbstractAttribute::initialize(...). 6481 void initialize(Attributor &A) override { 6482 intersectAssumedBits(BEST_STATE); 6483 getKnownStateFromValue(A, getIRPosition(), getState()); 6484 AAMemoryLocation::initialize(A); 6485 } 6486 6487 /// Return the memory behavior information encoded in the IR for \p IRP. 6488 static void getKnownStateFromValue(Attributor &A, const IRPosition &IRP, 6489 BitIntegerState &State, 6490 bool IgnoreSubsumingPositions = false) { 6491 // For internal functions we ignore `argmemonly` and 6492 // `inaccessiblememorargmemonly` as we might break it via interprocedural 6493 // constant propagation. It is unclear if this is the best way but it is 6494 // unlikely this will cause real performance problems. If we are deriving 6495 // attributes for the anchor function we even remove the attribute in 6496 // addition to ignoring it. 6497 bool UseArgMemOnly = true; 6498 Function *AnchorFn = IRP.getAnchorScope(); 6499 if (AnchorFn && A.isRunOn(*AnchorFn)) 6500 UseArgMemOnly = !AnchorFn->hasLocalLinkage(); 6501 6502 SmallVector<Attribute, 2> Attrs; 6503 IRP.getAttrs(AttrKinds, Attrs, IgnoreSubsumingPositions); 6504 for (const Attribute &Attr : Attrs) { 6505 switch (Attr.getKindAsEnum()) { 6506 case Attribute::ReadNone: 6507 State.addKnownBits(NO_LOCAL_MEM | NO_CONST_MEM); 6508 break; 6509 case Attribute::InaccessibleMemOnly: 6510 State.addKnownBits(inverseLocation(NO_INACCESSIBLE_MEM, true, true)); 6511 break; 6512 case Attribute::ArgMemOnly: 6513 if (UseArgMemOnly) 6514 State.addKnownBits(inverseLocation(NO_ARGUMENT_MEM, true, true)); 6515 else 6516 IRP.removeAttrs({Attribute::ArgMemOnly}); 6517 break; 6518 case Attribute::InaccessibleMemOrArgMemOnly: 6519 if (UseArgMemOnly) 6520 State.addKnownBits(inverseLocation( 6521 NO_INACCESSIBLE_MEM | NO_ARGUMENT_MEM, true, true)); 6522 else 6523 IRP.removeAttrs({Attribute::InaccessibleMemOrArgMemOnly}); 6524 break; 6525 default: 6526 llvm_unreachable("Unexpected attribute!"); 6527 } 6528 } 6529 } 6530 6531 /// See AbstractAttribute::getDeducedAttributes(...). 6532 void getDeducedAttributes(LLVMContext &Ctx, 6533 SmallVectorImpl<Attribute> &Attrs) const override { 6534 assert(Attrs.size() == 0); 6535 if (isAssumedReadNone()) { 6536 Attrs.push_back(Attribute::get(Ctx, Attribute::ReadNone)); 6537 } else if (getIRPosition().getPositionKind() == IRPosition::IRP_FUNCTION) { 6538 if (isAssumedInaccessibleMemOnly()) 6539 Attrs.push_back(Attribute::get(Ctx, Attribute::InaccessibleMemOnly)); 6540 else if (isAssumedArgMemOnly()) 6541 Attrs.push_back(Attribute::get(Ctx, Attribute::ArgMemOnly)); 6542 else if (isAssumedInaccessibleOrArgMemOnly()) 6543 Attrs.push_back( 6544 Attribute::get(Ctx, Attribute::InaccessibleMemOrArgMemOnly)); 6545 } 6546 assert(Attrs.size() <= 1); 6547 } 6548 6549 /// See AbstractAttribute::manifest(...). 6550 ChangeStatus manifest(Attributor &A) override { 6551 const IRPosition &IRP = getIRPosition(); 6552 6553 // Check if we would improve the existing attributes first. 6554 SmallVector<Attribute, 4> DeducedAttrs; 6555 getDeducedAttributes(IRP.getAnchorValue().getContext(), DeducedAttrs); 6556 if (llvm::all_of(DeducedAttrs, [&](const Attribute &Attr) { 6557 return IRP.hasAttr(Attr.getKindAsEnum(), 6558 /* IgnoreSubsumingPositions */ true); 6559 })) 6560 return ChangeStatus::UNCHANGED; 6561 6562 // Clear existing attributes. 6563 IRP.removeAttrs(AttrKinds); 6564 if (isAssumedReadNone()) 6565 IRP.removeAttrs(AAMemoryBehaviorImpl::AttrKinds); 6566 6567 // Use the generic manifest method. 6568 return IRAttribute::manifest(A); 6569 } 6570 6571 /// See AAMemoryLocation::checkForAllAccessesToMemoryKind(...). 6572 bool checkForAllAccessesToMemoryKind( 6573 function_ref<bool(const Instruction *, const Value *, AccessKind, 6574 MemoryLocationsKind)> 6575 Pred, 6576 MemoryLocationsKind RequestedMLK) const override { 6577 if (!isValidState()) 6578 return false; 6579 6580 MemoryLocationsKind AssumedMLK = getAssumedNotAccessedLocation(); 6581 if (AssumedMLK == NO_LOCATIONS) 6582 return true; 6583 6584 unsigned Idx = 0; 6585 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; 6586 CurMLK *= 2, ++Idx) { 6587 if (CurMLK & RequestedMLK) 6588 continue; 6589 6590 if (const AccessSet *Accesses = AccessKind2Accesses[Idx]) 6591 for (const AccessInfo &AI : *Accesses) 6592 if (!Pred(AI.I, AI.Ptr, AI.Kind, CurMLK)) 6593 return false; 6594 } 6595 6596 return true; 6597 } 6598 6599 ChangeStatus indicatePessimisticFixpoint() override { 6600 // If we give up and indicate a pessimistic fixpoint this instruction will 6601 // become an access for all potential access kinds: 6602 // TODO: Add pointers for argmemonly and globals to improve the results of 6603 // checkForAllAccessesToMemoryKind. 6604 bool Changed = false; 6605 MemoryLocationsKind KnownMLK = getKnown(); 6606 Instruction *I = dyn_cast<Instruction>(&getAssociatedValue()); 6607 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2) 6608 if (!(CurMLK & KnownMLK)) 6609 updateStateAndAccessesMap(getState(), CurMLK, I, nullptr, Changed, 6610 getAccessKindFromInst(I)); 6611 return AAMemoryLocation::indicatePessimisticFixpoint(); 6612 } 6613 6614 protected: 6615 /// Helper struct to tie together an instruction that has a read or write 6616 /// effect with the pointer it accesses (if any). 6617 struct AccessInfo { 6618 6619 /// The instruction that caused the access. 6620 const Instruction *I; 6621 6622 /// The base pointer that is accessed, or null if unknown. 6623 const Value *Ptr; 6624 6625 /// The kind of access (read/write/read+write). 6626 AccessKind Kind; 6627 6628 bool operator==(const AccessInfo &RHS) const { 6629 return I == RHS.I && Ptr == RHS.Ptr && Kind == RHS.Kind; 6630 } 6631 bool operator()(const AccessInfo &LHS, const AccessInfo &RHS) const { 6632 if (LHS.I != RHS.I) 6633 return LHS.I < RHS.I; 6634 if (LHS.Ptr != RHS.Ptr) 6635 return LHS.Ptr < RHS.Ptr; 6636 if (LHS.Kind != RHS.Kind) 6637 return LHS.Kind < RHS.Kind; 6638 return false; 6639 } 6640 }; 6641 6642 /// Mapping from *single* memory location kinds, e.g., LOCAL_MEM with the 6643 /// value of NO_LOCAL_MEM, to the accesses encountered for this memory kind. 6644 using AccessSet = SmallSet<AccessInfo, 2, AccessInfo>; 6645 AccessSet *AccessKind2Accesses[llvm::CTLog2<VALID_STATE>()]; 6646 6647 /// Categorize the pointer arguments of CB that might access memory in 6648 /// AccessedLoc and update the state and access map accordingly. 6649 void 6650 categorizeArgumentPointerLocations(Attributor &A, CallBase &CB, 6651 AAMemoryLocation::StateType &AccessedLocs, 6652 bool &Changed); 6653 6654 /// Return the kind(s) of location that may be accessed by \p V. 6655 AAMemoryLocation::MemoryLocationsKind 6656 categorizeAccessedLocations(Attributor &A, Instruction &I, bool &Changed); 6657 6658 /// Return the access kind as determined by \p I. 6659 AccessKind getAccessKindFromInst(const Instruction *I) { 6660 AccessKind AK = READ_WRITE; 6661 if (I) { 6662 AK = I->mayReadFromMemory() ? READ : NONE; 6663 AK = AccessKind(AK | (I->mayWriteToMemory() ? WRITE : NONE)); 6664 } 6665 return AK; 6666 } 6667 6668 /// Update the state \p State and the AccessKind2Accesses given that \p I is 6669 /// an access of kind \p AK to a \p MLK memory location with the access 6670 /// pointer \p Ptr. 6671 void updateStateAndAccessesMap(AAMemoryLocation::StateType &State, 6672 MemoryLocationsKind MLK, const Instruction *I, 6673 const Value *Ptr, bool &Changed, 6674 AccessKind AK = READ_WRITE) { 6675 6676 assert(isPowerOf2_32(MLK) && "Expected a single location set!"); 6677 auto *&Accesses = AccessKind2Accesses[llvm::Log2_32(MLK)]; 6678 if (!Accesses) 6679 Accesses = new (Allocator) AccessSet(); 6680 Changed |= Accesses->insert(AccessInfo{I, Ptr, AK}).second; 6681 State.removeAssumedBits(MLK); 6682 } 6683 6684 /// Determine the underlying locations kinds for \p Ptr, e.g., globals or 6685 /// arguments, and update the state and access map accordingly. 6686 void categorizePtrValue(Attributor &A, const Instruction &I, const Value &Ptr, 6687 AAMemoryLocation::StateType &State, bool &Changed); 6688 6689 /// Used to allocate access sets. 6690 BumpPtrAllocator &Allocator; 6691 6692 /// The set of IR attributes AAMemoryLocation deals with. 6693 static const Attribute::AttrKind AttrKinds[4]; 6694 }; 6695 6696 const Attribute::AttrKind AAMemoryLocationImpl::AttrKinds[] = { 6697 Attribute::ReadNone, Attribute::InaccessibleMemOnly, Attribute::ArgMemOnly, 6698 Attribute::InaccessibleMemOrArgMemOnly}; 6699 6700 void AAMemoryLocationImpl::categorizePtrValue( 6701 Attributor &A, const Instruction &I, const Value &Ptr, 6702 AAMemoryLocation::StateType &State, bool &Changed) { 6703 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize pointer locations for " 6704 << Ptr << " [" 6705 << getMemoryLocationsAsStr(State.getAssumed()) << "]\n"); 6706 6707 auto StripGEPCB = [](Value *V) -> Value * { 6708 auto *GEP = dyn_cast<GEPOperator>(V); 6709 while (GEP) { 6710 V = GEP->getPointerOperand(); 6711 GEP = dyn_cast<GEPOperator>(V); 6712 } 6713 return V; 6714 }; 6715 6716 auto VisitValueCB = [&](Value &V, const Instruction *, 6717 AAMemoryLocation::StateType &T, 6718 bool Stripped) -> bool { 6719 // TODO: recognize the TBAA used for constant accesses. 6720 MemoryLocationsKind MLK = NO_LOCATIONS; 6721 assert(!isa<GEPOperator>(V) && "GEPs should have been stripped."); 6722 if (isa<UndefValue>(V)) 6723 return true; 6724 if (auto *Arg = dyn_cast<Argument>(&V)) { 6725 if (Arg->hasByValAttr()) 6726 MLK = NO_LOCAL_MEM; 6727 else 6728 MLK = NO_ARGUMENT_MEM; 6729 } else if (auto *GV = dyn_cast<GlobalValue>(&V)) { 6730 // Reading constant memory is not treated as a read "effect" by the 6731 // function attr pass so we won't neither. Constants defined by TBAA are 6732 // similar. (We know we do not write it because it is constant.) 6733 if (auto *GVar = dyn_cast<GlobalVariable>(GV)) 6734 if (GVar->isConstant()) 6735 return true; 6736 6737 if (GV->hasLocalLinkage()) 6738 MLK = NO_GLOBAL_INTERNAL_MEM; 6739 else 6740 MLK = NO_GLOBAL_EXTERNAL_MEM; 6741 } else if (isa<ConstantPointerNull>(V) && 6742 !NullPointerIsDefined(getAssociatedFunction(), 6743 V.getType()->getPointerAddressSpace())) { 6744 return true; 6745 } else if (isa<AllocaInst>(V)) { 6746 MLK = NO_LOCAL_MEM; 6747 } else if (const auto *CB = dyn_cast<CallBase>(&V)) { 6748 const auto &NoAliasAA = A.getAAFor<AANoAlias>( 6749 *this, IRPosition::callsite_returned(*CB), DepClassTy::OPTIONAL); 6750 if (NoAliasAA.isAssumedNoAlias()) 6751 MLK = NO_MALLOCED_MEM; 6752 else 6753 MLK = NO_UNKOWN_MEM; 6754 } else { 6755 MLK = NO_UNKOWN_MEM; 6756 } 6757 6758 assert(MLK != NO_LOCATIONS && "No location specified!"); 6759 updateStateAndAccessesMap(T, MLK, &I, &V, Changed, 6760 getAccessKindFromInst(&I)); 6761 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Ptr value cannot be categorized: " 6762 << V << " -> " << getMemoryLocationsAsStr(T.getAssumed()) 6763 << "\n"); 6764 return true; 6765 }; 6766 6767 if (!genericValueTraversal<AAMemoryLocation, AAMemoryLocation::StateType>( 6768 A, IRPosition::value(Ptr), *this, State, VisitValueCB, getCtxI(), 6769 /* UseValueSimplify */ true, 6770 /* MaxValues */ 32, StripGEPCB)) { 6771 LLVM_DEBUG( 6772 dbgs() << "[AAMemoryLocation] Pointer locations not categorized\n"); 6773 updateStateAndAccessesMap(State, NO_UNKOWN_MEM, &I, nullptr, Changed, 6774 getAccessKindFromInst(&I)); 6775 } else { 6776 LLVM_DEBUG( 6777 dbgs() 6778 << "[AAMemoryLocation] Accessed locations with pointer locations: " 6779 << getMemoryLocationsAsStr(State.getAssumed()) << "\n"); 6780 } 6781 } 6782 6783 void AAMemoryLocationImpl::categorizeArgumentPointerLocations( 6784 Attributor &A, CallBase &CB, AAMemoryLocation::StateType &AccessedLocs, 6785 bool &Changed) { 6786 for (unsigned ArgNo = 0, E = CB.getNumArgOperands(); ArgNo < E; ++ArgNo) { 6787 6788 // Skip non-pointer arguments. 6789 const Value *ArgOp = CB.getArgOperand(ArgNo); 6790 if (!ArgOp->getType()->isPtrOrPtrVectorTy()) 6791 continue; 6792 6793 // Skip readnone arguments. 6794 const IRPosition &ArgOpIRP = IRPosition::callsite_argument(CB, ArgNo); 6795 const auto &ArgOpMemLocationAA = 6796 A.getAAFor<AAMemoryBehavior>(*this, ArgOpIRP, DepClassTy::OPTIONAL); 6797 6798 if (ArgOpMemLocationAA.isAssumedReadNone()) 6799 continue; 6800 6801 // Categorize potentially accessed pointer arguments as if there was an 6802 // access instruction with them as pointer. 6803 categorizePtrValue(A, CB, *ArgOp, AccessedLocs, Changed); 6804 } 6805 } 6806 6807 AAMemoryLocation::MemoryLocationsKind 6808 AAMemoryLocationImpl::categorizeAccessedLocations(Attributor &A, Instruction &I, 6809 bool &Changed) { 6810 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize accessed locations for " 6811 << I << "\n"); 6812 6813 AAMemoryLocation::StateType AccessedLocs; 6814 AccessedLocs.intersectAssumedBits(NO_LOCATIONS); 6815 6816 if (auto *CB = dyn_cast<CallBase>(&I)) { 6817 6818 // First check if we assume any memory is access is visible. 6819 const auto &CBMemLocationAA = A.getAAFor<AAMemoryLocation>( 6820 *this, IRPosition::callsite_function(*CB), DepClassTy::OPTIONAL); 6821 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Categorize call site: " << I 6822 << " [" << CBMemLocationAA << "]\n"); 6823 6824 if (CBMemLocationAA.isAssumedReadNone()) 6825 return NO_LOCATIONS; 6826 6827 if (CBMemLocationAA.isAssumedInaccessibleMemOnly()) { 6828 updateStateAndAccessesMap(AccessedLocs, NO_INACCESSIBLE_MEM, &I, nullptr, 6829 Changed, getAccessKindFromInst(&I)); 6830 return AccessedLocs.getAssumed(); 6831 } 6832 6833 uint32_t CBAssumedNotAccessedLocs = 6834 CBMemLocationAA.getAssumedNotAccessedLocation(); 6835 6836 // Set the argmemonly and global bit as we handle them separately below. 6837 uint32_t CBAssumedNotAccessedLocsNoArgMem = 6838 CBAssumedNotAccessedLocs | NO_ARGUMENT_MEM | NO_GLOBAL_MEM; 6839 6840 for (MemoryLocationsKind CurMLK = 1; CurMLK < NO_LOCATIONS; CurMLK *= 2) { 6841 if (CBAssumedNotAccessedLocsNoArgMem & CurMLK) 6842 continue; 6843 updateStateAndAccessesMap(AccessedLocs, CurMLK, &I, nullptr, Changed, 6844 getAccessKindFromInst(&I)); 6845 } 6846 6847 // Now handle global memory if it might be accessed. This is slightly tricky 6848 // as NO_GLOBAL_MEM has multiple bits set. 6849 bool HasGlobalAccesses = ((~CBAssumedNotAccessedLocs) & NO_GLOBAL_MEM); 6850 if (HasGlobalAccesses) { 6851 auto AccessPred = [&](const Instruction *, const Value *Ptr, 6852 AccessKind Kind, MemoryLocationsKind MLK) { 6853 updateStateAndAccessesMap(AccessedLocs, MLK, &I, Ptr, Changed, 6854 getAccessKindFromInst(&I)); 6855 return true; 6856 }; 6857 if (!CBMemLocationAA.checkForAllAccessesToMemoryKind( 6858 AccessPred, inverseLocation(NO_GLOBAL_MEM, false, false))) 6859 return AccessedLocs.getWorstState(); 6860 } 6861 6862 LLVM_DEBUG( 6863 dbgs() << "[AAMemoryLocation] Accessed state before argument handling: " 6864 << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n"); 6865 6866 // Now handle argument memory if it might be accessed. 6867 bool HasArgAccesses = ((~CBAssumedNotAccessedLocs) & NO_ARGUMENT_MEM); 6868 if (HasArgAccesses) 6869 categorizeArgumentPointerLocations(A, *CB, AccessedLocs, Changed); 6870 6871 LLVM_DEBUG( 6872 dbgs() << "[AAMemoryLocation] Accessed state after argument handling: " 6873 << getMemoryLocationsAsStr(AccessedLocs.getAssumed()) << "\n"); 6874 6875 return AccessedLocs.getAssumed(); 6876 } 6877 6878 if (const Value *Ptr = getPointerOperand(&I, /* AllowVolatile */ true)) { 6879 LLVM_DEBUG( 6880 dbgs() << "[AAMemoryLocation] Categorize memory access with pointer: " 6881 << I << " [" << *Ptr << "]\n"); 6882 categorizePtrValue(A, I, *Ptr, AccessedLocs, Changed); 6883 return AccessedLocs.getAssumed(); 6884 } 6885 6886 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Failed to categorize instruction: " 6887 << I << "\n"); 6888 updateStateAndAccessesMap(AccessedLocs, NO_UNKOWN_MEM, &I, nullptr, Changed, 6889 getAccessKindFromInst(&I)); 6890 return AccessedLocs.getAssumed(); 6891 } 6892 6893 /// An AA to represent the memory behavior function attributes. 6894 struct AAMemoryLocationFunction final : public AAMemoryLocationImpl { 6895 AAMemoryLocationFunction(const IRPosition &IRP, Attributor &A) 6896 : AAMemoryLocationImpl(IRP, A) {} 6897 6898 /// See AbstractAttribute::updateImpl(Attributor &A). 6899 virtual ChangeStatus updateImpl(Attributor &A) override { 6900 6901 const auto &MemBehaviorAA = 6902 A.getAAFor<AAMemoryBehavior>(*this, getIRPosition(), DepClassTy::NONE); 6903 if (MemBehaviorAA.isAssumedReadNone()) { 6904 if (MemBehaviorAA.isKnownReadNone()) 6905 return indicateOptimisticFixpoint(); 6906 assert(isAssumedReadNone() && 6907 "AAMemoryLocation was not read-none but AAMemoryBehavior was!"); 6908 A.recordDependence(MemBehaviorAA, *this, DepClassTy::OPTIONAL); 6909 return ChangeStatus::UNCHANGED; 6910 } 6911 6912 // The current assumed state used to determine a change. 6913 auto AssumedState = getAssumed(); 6914 bool Changed = false; 6915 6916 auto CheckRWInst = [&](Instruction &I) { 6917 MemoryLocationsKind MLK = categorizeAccessedLocations(A, I, Changed); 6918 LLVM_DEBUG(dbgs() << "[AAMemoryLocation] Accessed locations for " << I 6919 << ": " << getMemoryLocationsAsStr(MLK) << "\n"); 6920 removeAssumedBits(inverseLocation(MLK, false, false)); 6921 // Stop once only the valid bit set in the *not assumed location*, thus 6922 // once we don't actually exclude any memory locations in the state. 6923 return getAssumedNotAccessedLocation() != VALID_STATE; 6924 }; 6925 6926 if (!A.checkForAllReadWriteInstructions(CheckRWInst, *this)) 6927 return indicatePessimisticFixpoint(); 6928 6929 Changed |= AssumedState != getAssumed(); 6930 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 6931 } 6932 6933 /// See AbstractAttribute::trackStatistics() 6934 void trackStatistics() const override { 6935 if (isAssumedReadNone()) 6936 STATS_DECLTRACK_FN_ATTR(readnone) 6937 else if (isAssumedArgMemOnly()) 6938 STATS_DECLTRACK_FN_ATTR(argmemonly) 6939 else if (isAssumedInaccessibleMemOnly()) 6940 STATS_DECLTRACK_FN_ATTR(inaccessiblememonly) 6941 else if (isAssumedInaccessibleOrArgMemOnly()) 6942 STATS_DECLTRACK_FN_ATTR(inaccessiblememorargmemonly) 6943 } 6944 }; 6945 6946 /// AAMemoryLocation attribute for call sites. 6947 struct AAMemoryLocationCallSite final : AAMemoryLocationImpl { 6948 AAMemoryLocationCallSite(const IRPosition &IRP, Attributor &A) 6949 : AAMemoryLocationImpl(IRP, A) {} 6950 6951 /// See AbstractAttribute::initialize(...). 6952 void initialize(Attributor &A) override { 6953 AAMemoryLocationImpl::initialize(A); 6954 Function *F = getAssociatedFunction(); 6955 if (!F || F->isDeclaration()) 6956 indicatePessimisticFixpoint(); 6957 } 6958 6959 /// See AbstractAttribute::updateImpl(...). 6960 ChangeStatus updateImpl(Attributor &A) override { 6961 // TODO: Once we have call site specific value information we can provide 6962 // call site specific liveness liveness information and then it makes 6963 // sense to specialize attributes for call sites arguments instead of 6964 // redirecting requests to the callee argument. 6965 Function *F = getAssociatedFunction(); 6966 const IRPosition &FnPos = IRPosition::function(*F); 6967 auto &FnAA = 6968 A.getAAFor<AAMemoryLocation>(*this, FnPos, DepClassTy::REQUIRED); 6969 bool Changed = false; 6970 auto AccessPred = [&](const Instruction *I, const Value *Ptr, 6971 AccessKind Kind, MemoryLocationsKind MLK) { 6972 updateStateAndAccessesMap(getState(), MLK, I, Ptr, Changed, 6973 getAccessKindFromInst(I)); 6974 return true; 6975 }; 6976 if (!FnAA.checkForAllAccessesToMemoryKind(AccessPred, ALL_LOCATIONS)) 6977 return indicatePessimisticFixpoint(); 6978 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 6979 } 6980 6981 /// See AbstractAttribute::trackStatistics() 6982 void trackStatistics() const override { 6983 if (isAssumedReadNone()) 6984 STATS_DECLTRACK_CS_ATTR(readnone) 6985 } 6986 }; 6987 6988 /// ------------------ Value Constant Range Attribute ------------------------- 6989 6990 struct AAValueConstantRangeImpl : AAValueConstantRange { 6991 using StateType = IntegerRangeState; 6992 AAValueConstantRangeImpl(const IRPosition &IRP, Attributor &A) 6993 : AAValueConstantRange(IRP, A) {} 6994 6995 /// See AbstractAttribute::getAsStr(). 6996 const std::string getAsStr() const override { 6997 std::string Str; 6998 llvm::raw_string_ostream OS(Str); 6999 OS << "range(" << getBitWidth() << ")<"; 7000 getKnown().print(OS); 7001 OS << " / "; 7002 getAssumed().print(OS); 7003 OS << ">"; 7004 return OS.str(); 7005 } 7006 7007 /// Helper function to get a SCEV expr for the associated value at program 7008 /// point \p I. 7009 const SCEV *getSCEV(Attributor &A, const Instruction *I = nullptr) const { 7010 if (!getAnchorScope()) 7011 return nullptr; 7012 7013 ScalarEvolution *SE = 7014 A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>( 7015 *getAnchorScope()); 7016 7017 LoopInfo *LI = A.getInfoCache().getAnalysisResultForFunction<LoopAnalysis>( 7018 *getAnchorScope()); 7019 7020 if (!SE || !LI) 7021 return nullptr; 7022 7023 const SCEV *S = SE->getSCEV(&getAssociatedValue()); 7024 if (!I) 7025 return S; 7026 7027 return SE->getSCEVAtScope(S, LI->getLoopFor(I->getParent())); 7028 } 7029 7030 /// Helper function to get a range from SCEV for the associated value at 7031 /// program point \p I. 7032 ConstantRange getConstantRangeFromSCEV(Attributor &A, 7033 const Instruction *I = nullptr) const { 7034 if (!getAnchorScope()) 7035 return getWorstState(getBitWidth()); 7036 7037 ScalarEvolution *SE = 7038 A.getInfoCache().getAnalysisResultForFunction<ScalarEvolutionAnalysis>( 7039 *getAnchorScope()); 7040 7041 const SCEV *S = getSCEV(A, I); 7042 if (!SE || !S) 7043 return getWorstState(getBitWidth()); 7044 7045 return SE->getUnsignedRange(S); 7046 } 7047 7048 /// Helper function to get a range from LVI for the associated value at 7049 /// program point \p I. 7050 ConstantRange 7051 getConstantRangeFromLVI(Attributor &A, 7052 const Instruction *CtxI = nullptr) const { 7053 if (!getAnchorScope()) 7054 return getWorstState(getBitWidth()); 7055 7056 LazyValueInfo *LVI = 7057 A.getInfoCache().getAnalysisResultForFunction<LazyValueAnalysis>( 7058 *getAnchorScope()); 7059 7060 if (!LVI || !CtxI) 7061 return getWorstState(getBitWidth()); 7062 return LVI->getConstantRange(&getAssociatedValue(), 7063 const_cast<Instruction *>(CtxI)); 7064 } 7065 7066 /// See AAValueConstantRange::getKnownConstantRange(..). 7067 ConstantRange 7068 getKnownConstantRange(Attributor &A, 7069 const Instruction *CtxI = nullptr) const override { 7070 if (!CtxI || CtxI == getCtxI()) 7071 return getKnown(); 7072 7073 ConstantRange LVIR = getConstantRangeFromLVI(A, CtxI); 7074 ConstantRange SCEVR = getConstantRangeFromSCEV(A, CtxI); 7075 return getKnown().intersectWith(SCEVR).intersectWith(LVIR); 7076 } 7077 7078 /// See AAValueConstantRange::getAssumedConstantRange(..). 7079 ConstantRange 7080 getAssumedConstantRange(Attributor &A, 7081 const Instruction *CtxI = nullptr) const override { 7082 // TODO: Make SCEV use Attributor assumption. 7083 // We may be able to bound a variable range via assumptions in 7084 // Attributor. ex.) If x is assumed to be in [1, 3] and y is known to 7085 // evolve to x^2 + x, then we can say that y is in [2, 12]. 7086 7087 if (!CtxI || CtxI == getCtxI()) 7088 return getAssumed(); 7089 7090 ConstantRange LVIR = getConstantRangeFromLVI(A, CtxI); 7091 ConstantRange SCEVR = getConstantRangeFromSCEV(A, CtxI); 7092 return getAssumed().intersectWith(SCEVR).intersectWith(LVIR); 7093 } 7094 7095 /// See AbstractAttribute::initialize(..). 7096 void initialize(Attributor &A) override { 7097 // Intersect a range given by SCEV. 7098 intersectKnown(getConstantRangeFromSCEV(A, getCtxI())); 7099 7100 // Intersect a range given by LVI. 7101 intersectKnown(getConstantRangeFromLVI(A, getCtxI())); 7102 } 7103 7104 /// Helper function to create MDNode for range metadata. 7105 static MDNode * 7106 getMDNodeForConstantRange(Type *Ty, LLVMContext &Ctx, 7107 const ConstantRange &AssumedConstantRange) { 7108 Metadata *LowAndHigh[] = {ConstantAsMetadata::get(ConstantInt::get( 7109 Ty, AssumedConstantRange.getLower())), 7110 ConstantAsMetadata::get(ConstantInt::get( 7111 Ty, AssumedConstantRange.getUpper()))}; 7112 return MDNode::get(Ctx, LowAndHigh); 7113 } 7114 7115 /// Return true if \p Assumed is included in \p KnownRanges. 7116 static bool isBetterRange(const ConstantRange &Assumed, MDNode *KnownRanges) { 7117 7118 if (Assumed.isFullSet()) 7119 return false; 7120 7121 if (!KnownRanges) 7122 return true; 7123 7124 // If multiple ranges are annotated in IR, we give up to annotate assumed 7125 // range for now. 7126 7127 // TODO: If there exists a known range which containts assumed range, we 7128 // can say assumed range is better. 7129 if (KnownRanges->getNumOperands() > 2) 7130 return false; 7131 7132 ConstantInt *Lower = 7133 mdconst::extract<ConstantInt>(KnownRanges->getOperand(0)); 7134 ConstantInt *Upper = 7135 mdconst::extract<ConstantInt>(KnownRanges->getOperand(1)); 7136 7137 ConstantRange Known(Lower->getValue(), Upper->getValue()); 7138 return Known.contains(Assumed) && Known != Assumed; 7139 } 7140 7141 /// Helper function to set range metadata. 7142 static bool 7143 setRangeMetadataIfisBetterRange(Instruction *I, 7144 const ConstantRange &AssumedConstantRange) { 7145 auto *OldRangeMD = I->getMetadata(LLVMContext::MD_range); 7146 if (isBetterRange(AssumedConstantRange, OldRangeMD)) { 7147 if (!AssumedConstantRange.isEmptySet()) { 7148 I->setMetadata(LLVMContext::MD_range, 7149 getMDNodeForConstantRange(I->getType(), I->getContext(), 7150 AssumedConstantRange)); 7151 return true; 7152 } 7153 } 7154 return false; 7155 } 7156 7157 /// See AbstractAttribute::manifest() 7158 ChangeStatus manifest(Attributor &A) override { 7159 ChangeStatus Changed = ChangeStatus::UNCHANGED; 7160 ConstantRange AssumedConstantRange = getAssumedConstantRange(A); 7161 assert(!AssumedConstantRange.isFullSet() && "Invalid state"); 7162 7163 auto &V = getAssociatedValue(); 7164 if (!AssumedConstantRange.isEmptySet() && 7165 !AssumedConstantRange.isSingleElement()) { 7166 if (Instruction *I = dyn_cast<Instruction>(&V)) { 7167 assert(I == getCtxI() && "Should not annotate an instruction which is " 7168 "not the context instruction"); 7169 if (isa<CallInst>(I) || isa<LoadInst>(I)) 7170 if (setRangeMetadataIfisBetterRange(I, AssumedConstantRange)) 7171 Changed = ChangeStatus::CHANGED; 7172 } 7173 } 7174 7175 return Changed; 7176 } 7177 }; 7178 7179 struct AAValueConstantRangeArgument final 7180 : AAArgumentFromCallSiteArguments< 7181 AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState, 7182 true /* BridgeCallBaseContext */> { 7183 using Base = AAArgumentFromCallSiteArguments< 7184 AAValueConstantRange, AAValueConstantRangeImpl, IntegerRangeState, 7185 true /* BridgeCallBaseContext */>; 7186 AAValueConstantRangeArgument(const IRPosition &IRP, Attributor &A) 7187 : Base(IRP, A) {} 7188 7189 /// See AbstractAttribute::initialize(..). 7190 void initialize(Attributor &A) override { 7191 if (!getAnchorScope() || getAnchorScope()->isDeclaration()) { 7192 indicatePessimisticFixpoint(); 7193 } else { 7194 Base::initialize(A); 7195 } 7196 } 7197 7198 /// See AbstractAttribute::trackStatistics() 7199 void trackStatistics() const override { 7200 STATS_DECLTRACK_ARG_ATTR(value_range) 7201 } 7202 }; 7203 7204 struct AAValueConstantRangeReturned 7205 : AAReturnedFromReturnedValues<AAValueConstantRange, 7206 AAValueConstantRangeImpl, 7207 AAValueConstantRangeImpl::StateType, 7208 /* PropogateCallBaseContext */ true> { 7209 using Base = 7210 AAReturnedFromReturnedValues<AAValueConstantRange, 7211 AAValueConstantRangeImpl, 7212 AAValueConstantRangeImpl::StateType, 7213 /* PropogateCallBaseContext */ true>; 7214 AAValueConstantRangeReturned(const IRPosition &IRP, Attributor &A) 7215 : Base(IRP, A) {} 7216 7217 /// See AbstractAttribute::initialize(...). 7218 void initialize(Attributor &A) override {} 7219 7220 /// See AbstractAttribute::trackStatistics() 7221 void trackStatistics() const override { 7222 STATS_DECLTRACK_FNRET_ATTR(value_range) 7223 } 7224 }; 7225 7226 struct AAValueConstantRangeFloating : AAValueConstantRangeImpl { 7227 AAValueConstantRangeFloating(const IRPosition &IRP, Attributor &A) 7228 : AAValueConstantRangeImpl(IRP, A) {} 7229 7230 /// See AbstractAttribute::initialize(...). 7231 void initialize(Attributor &A) override { 7232 AAValueConstantRangeImpl::initialize(A); 7233 Value &V = getAssociatedValue(); 7234 7235 if (auto *C = dyn_cast<ConstantInt>(&V)) { 7236 unionAssumed(ConstantRange(C->getValue())); 7237 indicateOptimisticFixpoint(); 7238 return; 7239 } 7240 7241 if (isa<UndefValue>(&V)) { 7242 // Collapse the undef state to 0. 7243 unionAssumed(ConstantRange(APInt(getBitWidth(), 0))); 7244 indicateOptimisticFixpoint(); 7245 return; 7246 } 7247 7248 if (isa<CallBase>(&V)) 7249 return; 7250 7251 if (isa<BinaryOperator>(&V) || isa<CmpInst>(&V) || isa<CastInst>(&V)) 7252 return; 7253 // If it is a load instruction with range metadata, use it. 7254 if (LoadInst *LI = dyn_cast<LoadInst>(&V)) 7255 if (auto *RangeMD = LI->getMetadata(LLVMContext::MD_range)) { 7256 intersectKnown(getConstantRangeFromMetadata(*RangeMD)); 7257 return; 7258 } 7259 7260 // We can work with PHI and select instruction as we traverse their operands 7261 // during update. 7262 if (isa<SelectInst>(V) || isa<PHINode>(V)) 7263 return; 7264 7265 // Otherwise we give up. 7266 indicatePessimisticFixpoint(); 7267 7268 LLVM_DEBUG(dbgs() << "[AAValueConstantRange] We give up: " 7269 << getAssociatedValue() << "\n"); 7270 } 7271 7272 bool calculateBinaryOperator( 7273 Attributor &A, BinaryOperator *BinOp, IntegerRangeState &T, 7274 const Instruction *CtxI, 7275 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) { 7276 Value *LHS = BinOp->getOperand(0); 7277 Value *RHS = BinOp->getOperand(1); 7278 // TODO: Allow non integers as well. 7279 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy()) 7280 return false; 7281 7282 auto &LHSAA = A.getAAFor<AAValueConstantRange>( 7283 *this, IRPosition::value(*LHS, getCallBaseContext()), 7284 DepClassTy::REQUIRED); 7285 QuerriedAAs.push_back(&LHSAA); 7286 auto LHSAARange = LHSAA.getAssumedConstantRange(A, CtxI); 7287 7288 auto &RHSAA = A.getAAFor<AAValueConstantRange>( 7289 *this, IRPosition::value(*RHS, getCallBaseContext()), 7290 DepClassTy::REQUIRED); 7291 QuerriedAAs.push_back(&RHSAA); 7292 auto RHSAARange = RHSAA.getAssumedConstantRange(A, CtxI); 7293 7294 auto AssumedRange = LHSAARange.binaryOp(BinOp->getOpcode(), RHSAARange); 7295 7296 T.unionAssumed(AssumedRange); 7297 7298 // TODO: Track a known state too. 7299 7300 return T.isValidState(); 7301 } 7302 7303 bool calculateCastInst( 7304 Attributor &A, CastInst *CastI, IntegerRangeState &T, 7305 const Instruction *CtxI, 7306 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) { 7307 assert(CastI->getNumOperands() == 1 && "Expected cast to be unary!"); 7308 // TODO: Allow non integers as well. 7309 Value &OpV = *CastI->getOperand(0); 7310 if (!OpV.getType()->isIntegerTy()) 7311 return false; 7312 7313 auto &OpAA = A.getAAFor<AAValueConstantRange>( 7314 *this, IRPosition::value(OpV, getCallBaseContext()), 7315 DepClassTy::REQUIRED); 7316 QuerriedAAs.push_back(&OpAA); 7317 T.unionAssumed( 7318 OpAA.getAssumed().castOp(CastI->getOpcode(), getState().getBitWidth())); 7319 return T.isValidState(); 7320 } 7321 7322 bool 7323 calculateCmpInst(Attributor &A, CmpInst *CmpI, IntegerRangeState &T, 7324 const Instruction *CtxI, 7325 SmallVectorImpl<const AAValueConstantRange *> &QuerriedAAs) { 7326 Value *LHS = CmpI->getOperand(0); 7327 Value *RHS = CmpI->getOperand(1); 7328 // TODO: Allow non integers as well. 7329 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy()) 7330 return false; 7331 7332 auto &LHSAA = A.getAAFor<AAValueConstantRange>( 7333 *this, IRPosition::value(*LHS, getCallBaseContext()), 7334 DepClassTy::REQUIRED); 7335 QuerriedAAs.push_back(&LHSAA); 7336 auto &RHSAA = A.getAAFor<AAValueConstantRange>( 7337 *this, IRPosition::value(*RHS, getCallBaseContext()), 7338 DepClassTy::REQUIRED); 7339 auto LHSAARange = LHSAA.getAssumedConstantRange(A, CtxI); 7340 auto RHSAARange = RHSAA.getAssumedConstantRange(A, CtxI); 7341 7342 // If one of them is empty set, we can't decide. 7343 if (LHSAARange.isEmptySet() || RHSAARange.isEmptySet()) 7344 return true; 7345 7346 bool MustTrue = false, MustFalse = false; 7347 7348 auto AllowedRegion = 7349 ConstantRange::makeAllowedICmpRegion(CmpI->getPredicate(), RHSAARange); 7350 7351 if (AllowedRegion.intersectWith(LHSAARange).isEmptySet()) 7352 MustFalse = true; 7353 7354 if (LHSAARange.icmp(CmpI->getPredicate(), RHSAARange)) 7355 MustTrue = true; 7356 7357 assert((!MustTrue || !MustFalse) && 7358 "Either MustTrue or MustFalse should be false!"); 7359 7360 if (MustTrue) 7361 T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 1))); 7362 else if (MustFalse) 7363 T.unionAssumed(ConstantRange(APInt(/* numBits */ 1, /* val */ 0))); 7364 else 7365 T.unionAssumed(ConstantRange(/* BitWidth */ 1, /* isFullSet */ true)); 7366 7367 LLVM_DEBUG(dbgs() << "[AAValueConstantRange] " << *CmpI << " " << LHSAA 7368 << " " << RHSAA << "\n"); 7369 7370 // TODO: Track a known state too. 7371 return T.isValidState(); 7372 } 7373 7374 /// See AbstractAttribute::updateImpl(...). 7375 ChangeStatus updateImpl(Attributor &A) override { 7376 auto VisitValueCB = [&](Value &V, const Instruction *CtxI, 7377 IntegerRangeState &T, bool Stripped) -> bool { 7378 Instruction *I = dyn_cast<Instruction>(&V); 7379 if (!I || isa<CallBase>(I)) { 7380 7381 // If the value is not instruction, we query AA to Attributor. 7382 const auto &AA = A.getAAFor<AAValueConstantRange>( 7383 *this, IRPosition::value(V, getCallBaseContext()), 7384 DepClassTy::REQUIRED); 7385 7386 // Clamp operator is not used to utilize a program point CtxI. 7387 T.unionAssumed(AA.getAssumedConstantRange(A, CtxI)); 7388 7389 return T.isValidState(); 7390 } 7391 7392 SmallVector<const AAValueConstantRange *, 4> QuerriedAAs; 7393 if (auto *BinOp = dyn_cast<BinaryOperator>(I)) { 7394 if (!calculateBinaryOperator(A, BinOp, T, CtxI, QuerriedAAs)) 7395 return false; 7396 } else if (auto *CmpI = dyn_cast<CmpInst>(I)) { 7397 if (!calculateCmpInst(A, CmpI, T, CtxI, QuerriedAAs)) 7398 return false; 7399 } else if (auto *CastI = dyn_cast<CastInst>(I)) { 7400 if (!calculateCastInst(A, CastI, T, CtxI, QuerriedAAs)) 7401 return false; 7402 } else { 7403 // Give up with other instructions. 7404 // TODO: Add other instructions 7405 7406 T.indicatePessimisticFixpoint(); 7407 return false; 7408 } 7409 7410 // Catch circular reasoning in a pessimistic way for now. 7411 // TODO: Check how the range evolves and if we stripped anything, see also 7412 // AADereferenceable or AAAlign for similar situations. 7413 for (const AAValueConstantRange *QueriedAA : QuerriedAAs) { 7414 if (QueriedAA != this) 7415 continue; 7416 // If we are in a stady state we do not need to worry. 7417 if (T.getAssumed() == getState().getAssumed()) 7418 continue; 7419 T.indicatePessimisticFixpoint(); 7420 } 7421 7422 return T.isValidState(); 7423 }; 7424 7425 IntegerRangeState T(getBitWidth()); 7426 7427 if (!genericValueTraversal<AAValueConstantRange, IntegerRangeState>( 7428 A, getIRPosition(), *this, T, VisitValueCB, getCtxI(), 7429 /* UseValueSimplify */ false)) 7430 return indicatePessimisticFixpoint(); 7431 7432 return clampStateAndIndicateChange(getState(), T); 7433 } 7434 7435 /// See AbstractAttribute::trackStatistics() 7436 void trackStatistics() const override { 7437 STATS_DECLTRACK_FLOATING_ATTR(value_range) 7438 } 7439 }; 7440 7441 struct AAValueConstantRangeFunction : AAValueConstantRangeImpl { 7442 AAValueConstantRangeFunction(const IRPosition &IRP, Attributor &A) 7443 : AAValueConstantRangeImpl(IRP, A) {} 7444 7445 /// See AbstractAttribute::initialize(...). 7446 ChangeStatus updateImpl(Attributor &A) override { 7447 llvm_unreachable("AAValueConstantRange(Function|CallSite)::updateImpl will " 7448 "not be called"); 7449 } 7450 7451 /// See AbstractAttribute::trackStatistics() 7452 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(value_range) } 7453 }; 7454 7455 struct AAValueConstantRangeCallSite : AAValueConstantRangeFunction { 7456 AAValueConstantRangeCallSite(const IRPosition &IRP, Attributor &A) 7457 : AAValueConstantRangeFunction(IRP, A) {} 7458 7459 /// See AbstractAttribute::trackStatistics() 7460 void trackStatistics() const override { STATS_DECLTRACK_CS_ATTR(value_range) } 7461 }; 7462 7463 struct AAValueConstantRangeCallSiteReturned 7464 : AACallSiteReturnedFromReturned<AAValueConstantRange, 7465 AAValueConstantRangeImpl, 7466 AAValueConstantRangeImpl::StateType, 7467 /* IntroduceCallBaseContext */ true> { 7468 AAValueConstantRangeCallSiteReturned(const IRPosition &IRP, Attributor &A) 7469 : AACallSiteReturnedFromReturned<AAValueConstantRange, 7470 AAValueConstantRangeImpl, 7471 AAValueConstantRangeImpl::StateType, 7472 /* IntroduceCallBaseContext */ true>(IRP, 7473 A) { 7474 } 7475 7476 /// See AbstractAttribute::initialize(...). 7477 void initialize(Attributor &A) override { 7478 // If it is a load instruction with range metadata, use the metadata. 7479 if (CallInst *CI = dyn_cast<CallInst>(&getAssociatedValue())) 7480 if (auto *RangeMD = CI->getMetadata(LLVMContext::MD_range)) 7481 intersectKnown(getConstantRangeFromMetadata(*RangeMD)); 7482 7483 AAValueConstantRangeImpl::initialize(A); 7484 } 7485 7486 /// See AbstractAttribute::trackStatistics() 7487 void trackStatistics() const override { 7488 STATS_DECLTRACK_CSRET_ATTR(value_range) 7489 } 7490 }; 7491 struct AAValueConstantRangeCallSiteArgument : AAValueConstantRangeFloating { 7492 AAValueConstantRangeCallSiteArgument(const IRPosition &IRP, Attributor &A) 7493 : AAValueConstantRangeFloating(IRP, A) {} 7494 7495 /// See AbstractAttribute::manifest() 7496 ChangeStatus manifest(Attributor &A) override { 7497 return ChangeStatus::UNCHANGED; 7498 } 7499 7500 /// See AbstractAttribute::trackStatistics() 7501 void trackStatistics() const override { 7502 STATS_DECLTRACK_CSARG_ATTR(value_range) 7503 } 7504 }; 7505 7506 /// ------------------ Potential Values Attribute ------------------------- 7507 7508 struct AAPotentialValuesImpl : AAPotentialValues { 7509 using StateType = PotentialConstantIntValuesState; 7510 7511 AAPotentialValuesImpl(const IRPosition &IRP, Attributor &A) 7512 : AAPotentialValues(IRP, A) {} 7513 7514 /// See AbstractAttribute::getAsStr(). 7515 const std::string getAsStr() const override { 7516 std::string Str; 7517 llvm::raw_string_ostream OS(Str); 7518 OS << getState(); 7519 return OS.str(); 7520 } 7521 7522 /// See AbstractAttribute::updateImpl(...). 7523 ChangeStatus updateImpl(Attributor &A) override { 7524 return indicatePessimisticFixpoint(); 7525 } 7526 }; 7527 7528 struct AAPotentialValuesArgument final 7529 : AAArgumentFromCallSiteArguments<AAPotentialValues, AAPotentialValuesImpl, 7530 PotentialConstantIntValuesState> { 7531 using Base = 7532 AAArgumentFromCallSiteArguments<AAPotentialValues, AAPotentialValuesImpl, 7533 PotentialConstantIntValuesState>; 7534 AAPotentialValuesArgument(const IRPosition &IRP, Attributor &A) 7535 : Base(IRP, A) {} 7536 7537 /// See AbstractAttribute::initialize(..). 7538 void initialize(Attributor &A) override { 7539 if (!getAnchorScope() || getAnchorScope()->isDeclaration()) { 7540 indicatePessimisticFixpoint(); 7541 } else { 7542 Base::initialize(A); 7543 } 7544 } 7545 7546 /// See AbstractAttribute::trackStatistics() 7547 void trackStatistics() const override { 7548 STATS_DECLTRACK_ARG_ATTR(potential_values) 7549 } 7550 }; 7551 7552 struct AAPotentialValuesReturned 7553 : AAReturnedFromReturnedValues<AAPotentialValues, AAPotentialValuesImpl> { 7554 using Base = 7555 AAReturnedFromReturnedValues<AAPotentialValues, AAPotentialValuesImpl>; 7556 AAPotentialValuesReturned(const IRPosition &IRP, Attributor &A) 7557 : Base(IRP, A) {} 7558 7559 /// See AbstractAttribute::trackStatistics() 7560 void trackStatistics() const override { 7561 STATS_DECLTRACK_FNRET_ATTR(potential_values) 7562 } 7563 }; 7564 7565 struct AAPotentialValuesFloating : AAPotentialValuesImpl { 7566 AAPotentialValuesFloating(const IRPosition &IRP, Attributor &A) 7567 : AAPotentialValuesImpl(IRP, A) {} 7568 7569 /// See AbstractAttribute::initialize(..). 7570 void initialize(Attributor &A) override { 7571 Value &V = getAssociatedValue(); 7572 7573 if (auto *C = dyn_cast<ConstantInt>(&V)) { 7574 unionAssumed(C->getValue()); 7575 indicateOptimisticFixpoint(); 7576 return; 7577 } 7578 7579 if (isa<UndefValue>(&V)) { 7580 unionAssumedWithUndef(); 7581 indicateOptimisticFixpoint(); 7582 return; 7583 } 7584 7585 if (isa<BinaryOperator>(&V) || isa<ICmpInst>(&V) || isa<CastInst>(&V)) 7586 return; 7587 7588 if (isa<SelectInst>(V) || isa<PHINode>(V)) 7589 return; 7590 7591 indicatePessimisticFixpoint(); 7592 7593 LLVM_DEBUG(dbgs() << "[AAPotentialValues] We give up: " 7594 << getAssociatedValue() << "\n"); 7595 } 7596 7597 static bool calculateICmpInst(const ICmpInst *ICI, const APInt &LHS, 7598 const APInt &RHS) { 7599 ICmpInst::Predicate Pred = ICI->getPredicate(); 7600 switch (Pred) { 7601 case ICmpInst::ICMP_UGT: 7602 return LHS.ugt(RHS); 7603 case ICmpInst::ICMP_SGT: 7604 return LHS.sgt(RHS); 7605 case ICmpInst::ICMP_EQ: 7606 return LHS.eq(RHS); 7607 case ICmpInst::ICMP_UGE: 7608 return LHS.uge(RHS); 7609 case ICmpInst::ICMP_SGE: 7610 return LHS.sge(RHS); 7611 case ICmpInst::ICMP_ULT: 7612 return LHS.ult(RHS); 7613 case ICmpInst::ICMP_SLT: 7614 return LHS.slt(RHS); 7615 case ICmpInst::ICMP_NE: 7616 return LHS.ne(RHS); 7617 case ICmpInst::ICMP_ULE: 7618 return LHS.ule(RHS); 7619 case ICmpInst::ICMP_SLE: 7620 return LHS.sle(RHS); 7621 default: 7622 llvm_unreachable("Invalid ICmp predicate!"); 7623 } 7624 } 7625 7626 static APInt calculateCastInst(const CastInst *CI, const APInt &Src, 7627 uint32_t ResultBitWidth) { 7628 Instruction::CastOps CastOp = CI->getOpcode(); 7629 switch (CastOp) { 7630 default: 7631 llvm_unreachable("unsupported or not integer cast"); 7632 case Instruction::Trunc: 7633 return Src.trunc(ResultBitWidth); 7634 case Instruction::SExt: 7635 return Src.sext(ResultBitWidth); 7636 case Instruction::ZExt: 7637 return Src.zext(ResultBitWidth); 7638 case Instruction::BitCast: 7639 return Src; 7640 } 7641 } 7642 7643 static APInt calculateBinaryOperator(const BinaryOperator *BinOp, 7644 const APInt &LHS, const APInt &RHS, 7645 bool &SkipOperation, bool &Unsupported) { 7646 Instruction::BinaryOps BinOpcode = BinOp->getOpcode(); 7647 // Unsupported is set to true when the binary operator is not supported. 7648 // SkipOperation is set to true when UB occur with the given operand pair 7649 // (LHS, RHS). 7650 // TODO: we should look at nsw and nuw keywords to handle operations 7651 // that create poison or undef value. 7652 switch (BinOpcode) { 7653 default: 7654 Unsupported = true; 7655 return LHS; 7656 case Instruction::Add: 7657 return LHS + RHS; 7658 case Instruction::Sub: 7659 return LHS - RHS; 7660 case Instruction::Mul: 7661 return LHS * RHS; 7662 case Instruction::UDiv: 7663 if (RHS.isNullValue()) { 7664 SkipOperation = true; 7665 return LHS; 7666 } 7667 return LHS.udiv(RHS); 7668 case Instruction::SDiv: 7669 if (RHS.isNullValue()) { 7670 SkipOperation = true; 7671 return LHS; 7672 } 7673 return LHS.sdiv(RHS); 7674 case Instruction::URem: 7675 if (RHS.isNullValue()) { 7676 SkipOperation = true; 7677 return LHS; 7678 } 7679 return LHS.urem(RHS); 7680 case Instruction::SRem: 7681 if (RHS.isNullValue()) { 7682 SkipOperation = true; 7683 return LHS; 7684 } 7685 return LHS.srem(RHS); 7686 case Instruction::Shl: 7687 return LHS.shl(RHS); 7688 case Instruction::LShr: 7689 return LHS.lshr(RHS); 7690 case Instruction::AShr: 7691 return LHS.ashr(RHS); 7692 case Instruction::And: 7693 return LHS & RHS; 7694 case Instruction::Or: 7695 return LHS | RHS; 7696 case Instruction::Xor: 7697 return LHS ^ RHS; 7698 } 7699 } 7700 7701 bool calculateBinaryOperatorAndTakeUnion(const BinaryOperator *BinOp, 7702 const APInt &LHS, const APInt &RHS) { 7703 bool SkipOperation = false; 7704 bool Unsupported = false; 7705 APInt Result = 7706 calculateBinaryOperator(BinOp, LHS, RHS, SkipOperation, Unsupported); 7707 if (Unsupported) 7708 return false; 7709 // If SkipOperation is true, we can ignore this operand pair (L, R). 7710 if (!SkipOperation) 7711 unionAssumed(Result); 7712 return isValidState(); 7713 } 7714 7715 ChangeStatus updateWithICmpInst(Attributor &A, ICmpInst *ICI) { 7716 auto AssumedBefore = getAssumed(); 7717 Value *LHS = ICI->getOperand(0); 7718 Value *RHS = ICI->getOperand(1); 7719 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy()) 7720 return indicatePessimisticFixpoint(); 7721 7722 auto &LHSAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*LHS), 7723 DepClassTy::REQUIRED); 7724 if (!LHSAA.isValidState()) 7725 return indicatePessimisticFixpoint(); 7726 7727 auto &RHSAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*RHS), 7728 DepClassTy::REQUIRED); 7729 if (!RHSAA.isValidState()) 7730 return indicatePessimisticFixpoint(); 7731 7732 const DenseSet<APInt> &LHSAAPVS = LHSAA.getAssumedSet(); 7733 const DenseSet<APInt> &RHSAAPVS = RHSAA.getAssumedSet(); 7734 7735 // TODO: make use of undef flag to limit potential values aggressively. 7736 bool MaybeTrue = false, MaybeFalse = false; 7737 const APInt Zero(RHS->getType()->getIntegerBitWidth(), 0); 7738 if (LHSAA.undefIsContained() && RHSAA.undefIsContained()) { 7739 // The result of any comparison between undefs can be soundly replaced 7740 // with undef. 7741 unionAssumedWithUndef(); 7742 } else if (LHSAA.undefIsContained()) { 7743 for (const APInt &R : RHSAAPVS) { 7744 bool CmpResult = calculateICmpInst(ICI, Zero, R); 7745 MaybeTrue |= CmpResult; 7746 MaybeFalse |= !CmpResult; 7747 if (MaybeTrue & MaybeFalse) 7748 return indicatePessimisticFixpoint(); 7749 } 7750 } else if (RHSAA.undefIsContained()) { 7751 for (const APInt &L : LHSAAPVS) { 7752 bool CmpResult = calculateICmpInst(ICI, L, Zero); 7753 MaybeTrue |= CmpResult; 7754 MaybeFalse |= !CmpResult; 7755 if (MaybeTrue & MaybeFalse) 7756 return indicatePessimisticFixpoint(); 7757 } 7758 } else { 7759 for (const APInt &L : LHSAAPVS) { 7760 for (const APInt &R : RHSAAPVS) { 7761 bool CmpResult = calculateICmpInst(ICI, L, R); 7762 MaybeTrue |= CmpResult; 7763 MaybeFalse |= !CmpResult; 7764 if (MaybeTrue & MaybeFalse) 7765 return indicatePessimisticFixpoint(); 7766 } 7767 } 7768 } 7769 if (MaybeTrue) 7770 unionAssumed(APInt(/* numBits */ 1, /* val */ 1)); 7771 if (MaybeFalse) 7772 unionAssumed(APInt(/* numBits */ 1, /* val */ 0)); 7773 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED 7774 : ChangeStatus::CHANGED; 7775 } 7776 7777 ChangeStatus updateWithSelectInst(Attributor &A, SelectInst *SI) { 7778 auto AssumedBefore = getAssumed(); 7779 Value *LHS = SI->getTrueValue(); 7780 Value *RHS = SI->getFalseValue(); 7781 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy()) 7782 return indicatePessimisticFixpoint(); 7783 7784 // TODO: Use assumed simplified condition value 7785 auto &LHSAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*LHS), 7786 DepClassTy::REQUIRED); 7787 if (!LHSAA.isValidState()) 7788 return indicatePessimisticFixpoint(); 7789 7790 auto &RHSAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*RHS), 7791 DepClassTy::REQUIRED); 7792 if (!RHSAA.isValidState()) 7793 return indicatePessimisticFixpoint(); 7794 7795 if (LHSAA.undefIsContained() && RHSAA.undefIsContained()) 7796 // select i1 *, undef , undef => undef 7797 unionAssumedWithUndef(); 7798 else { 7799 unionAssumed(LHSAA); 7800 unionAssumed(RHSAA); 7801 } 7802 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED 7803 : ChangeStatus::CHANGED; 7804 } 7805 7806 ChangeStatus updateWithCastInst(Attributor &A, CastInst *CI) { 7807 auto AssumedBefore = getAssumed(); 7808 if (!CI->isIntegerCast()) 7809 return indicatePessimisticFixpoint(); 7810 assert(CI->getNumOperands() == 1 && "Expected cast to be unary!"); 7811 uint32_t ResultBitWidth = CI->getDestTy()->getIntegerBitWidth(); 7812 Value *Src = CI->getOperand(0); 7813 auto &SrcAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*Src), 7814 DepClassTy::REQUIRED); 7815 if (!SrcAA.isValidState()) 7816 return indicatePessimisticFixpoint(); 7817 const DenseSet<APInt> &SrcAAPVS = SrcAA.getAssumedSet(); 7818 if (SrcAA.undefIsContained()) 7819 unionAssumedWithUndef(); 7820 else { 7821 for (const APInt &S : SrcAAPVS) { 7822 APInt T = calculateCastInst(CI, S, ResultBitWidth); 7823 unionAssumed(T); 7824 } 7825 } 7826 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED 7827 : ChangeStatus::CHANGED; 7828 } 7829 7830 ChangeStatus updateWithBinaryOperator(Attributor &A, BinaryOperator *BinOp) { 7831 auto AssumedBefore = getAssumed(); 7832 Value *LHS = BinOp->getOperand(0); 7833 Value *RHS = BinOp->getOperand(1); 7834 if (!LHS->getType()->isIntegerTy() || !RHS->getType()->isIntegerTy()) 7835 return indicatePessimisticFixpoint(); 7836 7837 auto &LHSAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*LHS), 7838 DepClassTy::REQUIRED); 7839 if (!LHSAA.isValidState()) 7840 return indicatePessimisticFixpoint(); 7841 7842 auto &RHSAA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(*RHS), 7843 DepClassTy::REQUIRED); 7844 if (!RHSAA.isValidState()) 7845 return indicatePessimisticFixpoint(); 7846 7847 const DenseSet<APInt> &LHSAAPVS = LHSAA.getAssumedSet(); 7848 const DenseSet<APInt> &RHSAAPVS = RHSAA.getAssumedSet(); 7849 const APInt Zero = APInt(LHS->getType()->getIntegerBitWidth(), 0); 7850 7851 // TODO: make use of undef flag to limit potential values aggressively. 7852 if (LHSAA.undefIsContained() && RHSAA.undefIsContained()) { 7853 if (!calculateBinaryOperatorAndTakeUnion(BinOp, Zero, Zero)) 7854 return indicatePessimisticFixpoint(); 7855 } else if (LHSAA.undefIsContained()) { 7856 for (const APInt &R : RHSAAPVS) { 7857 if (!calculateBinaryOperatorAndTakeUnion(BinOp, Zero, R)) 7858 return indicatePessimisticFixpoint(); 7859 } 7860 } else if (RHSAA.undefIsContained()) { 7861 for (const APInt &L : LHSAAPVS) { 7862 if (!calculateBinaryOperatorAndTakeUnion(BinOp, L, Zero)) 7863 return indicatePessimisticFixpoint(); 7864 } 7865 } else { 7866 for (const APInt &L : LHSAAPVS) { 7867 for (const APInt &R : RHSAAPVS) { 7868 if (!calculateBinaryOperatorAndTakeUnion(BinOp, L, R)) 7869 return indicatePessimisticFixpoint(); 7870 } 7871 } 7872 } 7873 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED 7874 : ChangeStatus::CHANGED; 7875 } 7876 7877 ChangeStatus updateWithPHINode(Attributor &A, PHINode *PHI) { 7878 auto AssumedBefore = getAssumed(); 7879 for (unsigned u = 0, e = PHI->getNumIncomingValues(); u < e; u++) { 7880 Value *IncomingValue = PHI->getIncomingValue(u); 7881 auto &PotentialValuesAA = A.getAAFor<AAPotentialValues>( 7882 *this, IRPosition::value(*IncomingValue), DepClassTy::REQUIRED); 7883 if (!PotentialValuesAA.isValidState()) 7884 return indicatePessimisticFixpoint(); 7885 if (PotentialValuesAA.undefIsContained()) 7886 unionAssumedWithUndef(); 7887 else 7888 unionAssumed(PotentialValuesAA.getAssumed()); 7889 } 7890 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED 7891 : ChangeStatus::CHANGED; 7892 } 7893 7894 /// See AbstractAttribute::updateImpl(...). 7895 ChangeStatus updateImpl(Attributor &A) override { 7896 Value &V = getAssociatedValue(); 7897 Instruction *I = dyn_cast<Instruction>(&V); 7898 7899 if (auto *ICI = dyn_cast<ICmpInst>(I)) 7900 return updateWithICmpInst(A, ICI); 7901 7902 if (auto *SI = dyn_cast<SelectInst>(I)) 7903 return updateWithSelectInst(A, SI); 7904 7905 if (auto *CI = dyn_cast<CastInst>(I)) 7906 return updateWithCastInst(A, CI); 7907 7908 if (auto *BinOp = dyn_cast<BinaryOperator>(I)) 7909 return updateWithBinaryOperator(A, BinOp); 7910 7911 if (auto *PHI = dyn_cast<PHINode>(I)) 7912 return updateWithPHINode(A, PHI); 7913 7914 return indicatePessimisticFixpoint(); 7915 } 7916 7917 /// See AbstractAttribute::trackStatistics() 7918 void trackStatistics() const override { 7919 STATS_DECLTRACK_FLOATING_ATTR(potential_values) 7920 } 7921 }; 7922 7923 struct AAPotentialValuesFunction : AAPotentialValuesImpl { 7924 AAPotentialValuesFunction(const IRPosition &IRP, Attributor &A) 7925 : AAPotentialValuesImpl(IRP, A) {} 7926 7927 /// See AbstractAttribute::initialize(...). 7928 ChangeStatus updateImpl(Attributor &A) override { 7929 llvm_unreachable("AAPotentialValues(Function|CallSite)::updateImpl will " 7930 "not be called"); 7931 } 7932 7933 /// See AbstractAttribute::trackStatistics() 7934 void trackStatistics() const override { 7935 STATS_DECLTRACK_FN_ATTR(potential_values) 7936 } 7937 }; 7938 7939 struct AAPotentialValuesCallSite : AAPotentialValuesFunction { 7940 AAPotentialValuesCallSite(const IRPosition &IRP, Attributor &A) 7941 : AAPotentialValuesFunction(IRP, A) {} 7942 7943 /// See AbstractAttribute::trackStatistics() 7944 void trackStatistics() const override { 7945 STATS_DECLTRACK_CS_ATTR(potential_values) 7946 } 7947 }; 7948 7949 struct AAPotentialValuesCallSiteReturned 7950 : AACallSiteReturnedFromReturned<AAPotentialValues, AAPotentialValuesImpl> { 7951 AAPotentialValuesCallSiteReturned(const IRPosition &IRP, Attributor &A) 7952 : AACallSiteReturnedFromReturned<AAPotentialValues, 7953 AAPotentialValuesImpl>(IRP, A) {} 7954 7955 /// See AbstractAttribute::trackStatistics() 7956 void trackStatistics() const override { 7957 STATS_DECLTRACK_CSRET_ATTR(potential_values) 7958 } 7959 }; 7960 7961 struct AAPotentialValuesCallSiteArgument : AAPotentialValuesFloating { 7962 AAPotentialValuesCallSiteArgument(const IRPosition &IRP, Attributor &A) 7963 : AAPotentialValuesFloating(IRP, A) {} 7964 7965 /// See AbstractAttribute::initialize(..). 7966 void initialize(Attributor &A) override { 7967 Value &V = getAssociatedValue(); 7968 7969 if (auto *C = dyn_cast<ConstantInt>(&V)) { 7970 unionAssumed(C->getValue()); 7971 indicateOptimisticFixpoint(); 7972 return; 7973 } 7974 7975 if (isa<UndefValue>(&V)) { 7976 unionAssumedWithUndef(); 7977 indicateOptimisticFixpoint(); 7978 return; 7979 } 7980 } 7981 7982 /// See AbstractAttribute::updateImpl(...). 7983 ChangeStatus updateImpl(Attributor &A) override { 7984 Value &V = getAssociatedValue(); 7985 auto AssumedBefore = getAssumed(); 7986 auto &AA = A.getAAFor<AAPotentialValues>(*this, IRPosition::value(V), 7987 DepClassTy::REQUIRED); 7988 const auto &S = AA.getAssumed(); 7989 unionAssumed(S); 7990 return AssumedBefore == getAssumed() ? ChangeStatus::UNCHANGED 7991 : ChangeStatus::CHANGED; 7992 } 7993 7994 /// See AbstractAttribute::trackStatistics() 7995 void trackStatistics() const override { 7996 STATS_DECLTRACK_CSARG_ATTR(potential_values) 7997 } 7998 }; 7999 8000 /// ------------------------ NoUndef Attribute --------------------------------- 8001 struct AANoUndefImpl : AANoUndef { 8002 AANoUndefImpl(const IRPosition &IRP, Attributor &A) : AANoUndef(IRP, A) {} 8003 8004 /// See AbstractAttribute::initialize(...). 8005 void initialize(Attributor &A) override { 8006 if (getIRPosition().hasAttr({Attribute::NoUndef})) { 8007 indicateOptimisticFixpoint(); 8008 return; 8009 } 8010 Value &V = getAssociatedValue(); 8011 if (isa<UndefValue>(V)) 8012 indicatePessimisticFixpoint(); 8013 else if (isa<FreezeInst>(V)) 8014 indicateOptimisticFixpoint(); 8015 else if (getPositionKind() != IRPosition::IRP_RETURNED && 8016 isGuaranteedNotToBeUndefOrPoison(&V)) 8017 indicateOptimisticFixpoint(); 8018 else 8019 AANoUndef::initialize(A); 8020 } 8021 8022 /// See followUsesInMBEC 8023 bool followUseInMBEC(Attributor &A, const Use *U, const Instruction *I, 8024 AANoUndef::StateType &State) { 8025 const Value *UseV = U->get(); 8026 const DominatorTree *DT = nullptr; 8027 AssumptionCache *AC = nullptr; 8028 InformationCache &InfoCache = A.getInfoCache(); 8029 if (Function *F = getAnchorScope()) { 8030 DT = InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*F); 8031 AC = InfoCache.getAnalysisResultForFunction<AssumptionAnalysis>(*F); 8032 } 8033 State.setKnown(isGuaranteedNotToBeUndefOrPoison(UseV, AC, I, DT)); 8034 bool TrackUse = false; 8035 // Track use for instructions which must produce undef or poison bits when 8036 // at least one operand contains such bits. 8037 if (isa<CastInst>(*I) || isa<GetElementPtrInst>(*I)) 8038 TrackUse = true; 8039 return TrackUse; 8040 } 8041 8042 /// See AbstractAttribute::getAsStr(). 8043 const std::string getAsStr() const override { 8044 return getAssumed() ? "noundef" : "may-undef-or-poison"; 8045 } 8046 8047 ChangeStatus manifest(Attributor &A) override { 8048 // We don't manifest noundef attribute for dead positions because the 8049 // associated values with dead positions would be replaced with undef 8050 // values. 8051 if (A.isAssumedDead(getIRPosition(), nullptr, nullptr)) 8052 return ChangeStatus::UNCHANGED; 8053 // A position whose simplified value does not have any value is 8054 // considered to be dead. We don't manifest noundef in such positions for 8055 // the same reason above. 8056 auto &ValueSimplifyAA = 8057 A.getAAFor<AAValueSimplify>(*this, getIRPosition(), DepClassTy::NONE); 8058 if (!ValueSimplifyAA.getAssumedSimplifiedValue(A).hasValue()) 8059 return ChangeStatus::UNCHANGED; 8060 return AANoUndef::manifest(A); 8061 } 8062 }; 8063 8064 struct AANoUndefFloating : public AANoUndefImpl { 8065 AANoUndefFloating(const IRPosition &IRP, Attributor &A) 8066 : AANoUndefImpl(IRP, A) {} 8067 8068 /// See AbstractAttribute::initialize(...). 8069 void initialize(Attributor &A) override { 8070 AANoUndefImpl::initialize(A); 8071 if (!getState().isAtFixpoint()) 8072 if (Instruction *CtxI = getCtxI()) 8073 followUsesInMBEC(*this, A, getState(), *CtxI); 8074 } 8075 8076 /// See AbstractAttribute::updateImpl(...). 8077 ChangeStatus updateImpl(Attributor &A) override { 8078 auto VisitValueCB = [&](Value &V, const Instruction *CtxI, 8079 AANoUndef::StateType &T, bool Stripped) -> bool { 8080 const auto &AA = A.getAAFor<AANoUndef>(*this, IRPosition::value(V), 8081 DepClassTy::REQUIRED); 8082 if (!Stripped && this == &AA) { 8083 T.indicatePessimisticFixpoint(); 8084 } else { 8085 const AANoUndef::StateType &S = 8086 static_cast<const AANoUndef::StateType &>(AA.getState()); 8087 T ^= S; 8088 } 8089 return T.isValidState(); 8090 }; 8091 8092 StateType T; 8093 if (!genericValueTraversal<AANoUndef, StateType>( 8094 A, getIRPosition(), *this, T, VisitValueCB, getCtxI())) 8095 return indicatePessimisticFixpoint(); 8096 8097 return clampStateAndIndicateChange(getState(), T); 8098 } 8099 8100 /// See AbstractAttribute::trackStatistics() 8101 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noundef) } 8102 }; 8103 8104 struct AANoUndefReturned final 8105 : AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl> { 8106 AANoUndefReturned(const IRPosition &IRP, Attributor &A) 8107 : AAReturnedFromReturnedValues<AANoUndef, AANoUndefImpl>(IRP, A) {} 8108 8109 /// See AbstractAttribute::trackStatistics() 8110 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noundef) } 8111 }; 8112 8113 struct AANoUndefArgument final 8114 : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl> { 8115 AANoUndefArgument(const IRPosition &IRP, Attributor &A) 8116 : AAArgumentFromCallSiteArguments<AANoUndef, AANoUndefImpl>(IRP, A) {} 8117 8118 /// See AbstractAttribute::trackStatistics() 8119 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noundef) } 8120 }; 8121 8122 struct AANoUndefCallSiteArgument final : AANoUndefFloating { 8123 AANoUndefCallSiteArgument(const IRPosition &IRP, Attributor &A) 8124 : AANoUndefFloating(IRP, A) {} 8125 8126 /// See AbstractAttribute::trackStatistics() 8127 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(noundef) } 8128 }; 8129 8130 struct AANoUndefCallSiteReturned final 8131 : AACallSiteReturnedFromReturned<AANoUndef, AANoUndefImpl> { 8132 AANoUndefCallSiteReturned(const IRPosition &IRP, Attributor &A) 8133 : AACallSiteReturnedFromReturned<AANoUndef, AANoUndefImpl>(IRP, A) {} 8134 8135 /// See AbstractAttribute::trackStatistics() 8136 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(noundef) } 8137 }; 8138 8139 struct AACallEdgesFunction : public AACallEdges { 8140 AACallEdgesFunction(const IRPosition &IRP, Attributor &A) 8141 : AACallEdges(IRP, A) {} 8142 8143 /// See AbstractAttribute::updateImpl(...). 8144 ChangeStatus updateImpl(Attributor &A) override { 8145 ChangeStatus Change = ChangeStatus::UNCHANGED; 8146 bool OldHasUnknownCallee = HasUnknownCallee; 8147 8148 auto AddCalledFunction = [&](Function *Fn) { 8149 if (CalledFunctions.insert(Fn)) { 8150 Change = ChangeStatus::CHANGED; 8151 LLVM_DEBUG(dbgs() << "[AACallEdges] New call edge: " << Fn->getName() 8152 << "\n"); 8153 } 8154 }; 8155 8156 auto VisitValue = [&](Value &V, const Instruction *CtxI, bool &HasUnknown, 8157 bool Stripped) -> bool { 8158 if (Function *Fn = dyn_cast<Function>(&V)) { 8159 AddCalledFunction(Fn); 8160 } else { 8161 LLVM_DEBUG(dbgs() << "[AACallEdges] Unrecognized value: " << V << "\n"); 8162 HasUnknown = true; 8163 } 8164 8165 // Explore all values. 8166 return true; 8167 }; 8168 8169 // Process any value that we might call. 8170 auto ProcessCalledOperand = [&](Value *V, Instruction *Ctx) { 8171 if (!genericValueTraversal<AACallEdges, bool>(A, IRPosition::value(*V), 8172 *this, HasUnknownCallee, 8173 VisitValue, nullptr, false)) 8174 // If we haven't gone through all values, assume that there are unknown 8175 // callees. 8176 HasUnknownCallee = true; 8177 }; 8178 8179 auto ProcessCallInst = [&](Instruction &Inst) { 8180 CallBase &CB = static_cast<CallBase &>(Inst); 8181 8182 // Process callee metadata if available. 8183 if (auto *MD = Inst.getMetadata(LLVMContext::MD_callees)) { 8184 for (auto &Op : MD->operands()) { 8185 Function *Callee = mdconst::extract_or_null<Function>(Op); 8186 if (Callee) 8187 AddCalledFunction(Callee); 8188 } 8189 // Callees metadata grantees that the called function is one of its 8190 // operands, So we are done. 8191 return true; 8192 } 8193 8194 // The most simple case. 8195 ProcessCalledOperand(CB.getCalledOperand(), &Inst); 8196 8197 // Process callback functions. 8198 SmallVector<const Use *, 4u> CallbackUses; 8199 AbstractCallSite::getCallbackUses(CB, CallbackUses); 8200 for (const Use *U : CallbackUses) 8201 ProcessCalledOperand(U->get(), &Inst); 8202 8203 return true; 8204 }; 8205 8206 // Visit all callable instructions. 8207 if (!A.checkForAllCallLikeInstructions(ProcessCallInst, *this)) 8208 // If we haven't looked at all call like instructions, assume that there 8209 // are unknown callees. 8210 HasUnknownCallee = true; 8211 // Track changes. 8212 if (OldHasUnknownCallee != HasUnknownCallee) 8213 Change = ChangeStatus::CHANGED; 8214 8215 return Change; 8216 } 8217 8218 virtual const SetVector<Function *> &getOptimisticEdges() const override { 8219 return CalledFunctions; 8220 }; 8221 8222 virtual bool hasUnknownCallee() const override { return HasUnknownCallee; } 8223 8224 const std::string getAsStr() const override { 8225 return "CallEdges[" + std::to_string(HasUnknownCallee) + "," + 8226 std::to_string(CalledFunctions.size()) + "]"; 8227 } 8228 8229 void trackStatistics() const override {} 8230 8231 /// Optimistic set of functions that might be called by this function. 8232 SetVector<Function *> CalledFunctions; 8233 8234 /// Does this function have a call to a function that we don't know about. 8235 bool HasUnknownCallee; 8236 }; 8237 8238 } // namespace 8239 8240 AACallGraphNode *AACallEdgeIterator::operator*() const { 8241 return static_cast<AACallGraphNode *>(const_cast<AACallEdges *>( 8242 &A.getOrCreateAAFor<AACallEdges>(IRPosition::function(**I)))); 8243 } 8244 8245 void AttributorCallGraph::print() { 8246 std::string Filename = "AttributorCallGraph.dot"; 8247 std::error_code EC; 8248 8249 raw_fd_ostream File(Filename, EC, sys::fs::OF_TextWithCRLF); 8250 llvm::WriteGraph(File, this); 8251 } 8252 8253 const char AAReturnedValues::ID = 0; 8254 const char AANoUnwind::ID = 0; 8255 const char AANoSync::ID = 0; 8256 const char AANoFree::ID = 0; 8257 const char AANonNull::ID = 0; 8258 const char AANoRecurse::ID = 0; 8259 const char AAWillReturn::ID = 0; 8260 const char AAUndefinedBehavior::ID = 0; 8261 const char AANoAlias::ID = 0; 8262 const char AAReachability::ID = 0; 8263 const char AANoReturn::ID = 0; 8264 const char AAIsDead::ID = 0; 8265 const char AADereferenceable::ID = 0; 8266 const char AAAlign::ID = 0; 8267 const char AANoCapture::ID = 0; 8268 const char AAValueSimplify::ID = 0; 8269 const char AAHeapToStack::ID = 0; 8270 const char AAPrivatizablePtr::ID = 0; 8271 const char AAMemoryBehavior::ID = 0; 8272 const char AAMemoryLocation::ID = 0; 8273 const char AAValueConstantRange::ID = 0; 8274 const char AAPotentialValues::ID = 0; 8275 const char AANoUndef::ID = 0; 8276 const char AACallEdges::ID = 0; 8277 8278 // Macro magic to create the static generator function for attributes that 8279 // follow the naming scheme. 8280 8281 #define SWITCH_PK_INV(CLASS, PK, POS_NAME) \ 8282 case IRPosition::PK: \ 8283 llvm_unreachable("Cannot create " #CLASS " for a " POS_NAME " position!"); 8284 8285 #define SWITCH_PK_CREATE(CLASS, IRP, PK, SUFFIX) \ 8286 case IRPosition::PK: \ 8287 AA = new (A.Allocator) CLASS##SUFFIX(IRP, A); \ 8288 ++NumAAs; \ 8289 break; 8290 8291 #define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 8292 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 8293 CLASS *AA = nullptr; \ 8294 switch (IRP.getPositionKind()) { \ 8295 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 8296 SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \ 8297 SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \ 8298 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \ 8299 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \ 8300 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \ 8301 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 8302 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \ 8303 } \ 8304 return *AA; \ 8305 } 8306 8307 #define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 8308 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 8309 CLASS *AA = nullptr; \ 8310 switch (IRP.getPositionKind()) { \ 8311 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 8312 SWITCH_PK_INV(CLASS, IRP_FUNCTION, "function") \ 8313 SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \ 8314 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \ 8315 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \ 8316 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \ 8317 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \ 8318 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \ 8319 } \ 8320 return *AA; \ 8321 } 8322 8323 #define CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 8324 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 8325 CLASS *AA = nullptr; \ 8326 switch (IRP.getPositionKind()) { \ 8327 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 8328 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 8329 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \ 8330 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \ 8331 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \ 8332 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \ 8333 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \ 8334 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \ 8335 } \ 8336 return *AA; \ 8337 } 8338 8339 #define CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 8340 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 8341 CLASS *AA = nullptr; \ 8342 switch (IRP.getPositionKind()) { \ 8343 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 8344 SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \ 8345 SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \ 8346 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \ 8347 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \ 8348 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \ 8349 SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \ 8350 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 8351 } \ 8352 return *AA; \ 8353 } 8354 8355 #define CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 8356 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 8357 CLASS *AA = nullptr; \ 8358 switch (IRP.getPositionKind()) { \ 8359 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 8360 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \ 8361 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 8362 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \ 8363 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \ 8364 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \ 8365 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \ 8366 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \ 8367 } \ 8368 return *AA; \ 8369 } 8370 8371 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoUnwind) 8372 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoSync) 8373 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoRecurse) 8374 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAWillReturn) 8375 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoReturn) 8376 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReturnedValues) 8377 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAMemoryLocation) 8378 8379 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANonNull) 8380 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoAlias) 8381 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPrivatizablePtr) 8382 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AADereferenceable) 8383 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAAlign) 8384 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoCapture) 8385 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAValueConstantRange) 8386 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAPotentialValues) 8387 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoUndef) 8388 8389 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAValueSimplify) 8390 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAIsDead) 8391 CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoFree) 8392 8393 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAHeapToStack) 8394 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReachability) 8395 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAUndefinedBehavior) 8396 CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION(AACallEdges) 8397 8398 CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAMemoryBehavior) 8399 8400 #undef CREATE_FUNCTION_ONLY_ABSTRACT_ATTRIBUTE_FOR_POSITION 8401 #undef CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION 8402 #undef CREATE_NON_RET_ABSTRACT_ATTRIBUTE_FOR_POSITION 8403 #undef CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION 8404 #undef CREATE_ALL_ABSTRACT_ATTRIBUTE_FOR_POSITION 8405 #undef SWITCH_PK_CREATE 8406 #undef SWITCH_PK_INV 8407