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