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