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/SetVector.h" 21 #include "llvm/ADT/SmallPtrSet.h" 22 #include "llvm/ADT/SmallVector.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/Analysis/CaptureTracking.h" 25 #include "llvm/Analysis/EHPersonalities.h" 26 #include "llvm/Analysis/GlobalsModRef.h" 27 #include "llvm/Analysis/Loads.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/Support/CommandLine.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 38 #include "llvm/Transforms/Utils/Local.h" 39 40 #include <cassert> 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "attributor" 45 46 STATISTIC(NumFnWithExactDefinition, 47 "Number of function with exact definitions"); 48 STATISTIC(NumFnWithoutExactDefinition, 49 "Number of function without exact definitions"); 50 STATISTIC(NumAttributesTimedOut, 51 "Number of abstract attributes timed out before fixpoint"); 52 STATISTIC(NumAttributesValidFixpoint, 53 "Number of abstract attributes in a valid fixpoint state"); 54 STATISTIC(NumAttributesManifested, 55 "Number of abstract attributes manifested in IR"); 56 57 // Some helper macros to deal with statistics tracking. 58 // 59 // Usage: 60 // For simple IR attribute tracking overload trackStatistics in the abstract 61 // attribute and choose the right STATS_DECLTRACK_********* macro, 62 // e.g.,: 63 // void trackStatistics() const override { 64 // STATS_DECLTRACK_ARG_ATTR(returned) 65 // } 66 // If there is a single "increment" side one can use the macro 67 // STATS_DECLTRACK with a custom message. If there are multiple increment 68 // sides, STATS_DECL and STATS_TRACK can also be used separatly. 69 // 70 #define BUILD_STAT_MSG_IR_ATTR(TYPE, NAME) \ 71 ("Number of " #TYPE " marked '" #NAME "'") 72 #define BUILD_STAT_NAME(NAME, TYPE) NumIR##TYPE##_##NAME 73 #define STATS_DECL(NAME, TYPE, MSG) STATISTIC(BUILD_STAT_NAME(NAME, TYPE), MSG); 74 #define STATS_TRACK(NAME, TYPE) ++(BUILD_STAT_NAME(NAME, TYPE)); 75 #define STATS_DECLTRACK(NAME, TYPE, MSG) \ 76 { \ 77 STATS_DECL(NAME, TYPE, MSG) \ 78 STATS_TRACK(NAME, TYPE) \ 79 } 80 #define STATS_DECLTRACK_ARG_ATTR(NAME) \ 81 STATS_DECLTRACK(NAME, Arguments, BUILD_STAT_MSG_IR_ATTR(arguments, NAME)) 82 #define STATS_DECLTRACK_CSARG_ATTR(NAME) \ 83 STATS_DECLTRACK(NAME, CSArguments, \ 84 BUILD_STAT_MSG_IR_ATTR(call site arguments, NAME)) 85 #define STATS_DECLTRACK_FN_ATTR(NAME) \ 86 STATS_DECLTRACK(NAME, Function, BUILD_STAT_MSG_IR_ATTR(functions, NAME)) 87 #define STATS_DECLTRACK_CS_ATTR(NAME) \ 88 STATS_DECLTRACK(NAME, CS, BUILD_STAT_MSG_IR_ATTR(call site, NAME)) 89 #define STATS_DECLTRACK_FNRET_ATTR(NAME) \ 90 STATS_DECLTRACK(NAME, FunctionReturn, \ 91 BUILD_STAT_MSG_IR_ATTR(function returns, NAME)) 92 #define STATS_DECLTRACK_CSRET_ATTR(NAME) \ 93 STATS_DECLTRACK(NAME, CSReturn, \ 94 BUILD_STAT_MSG_IR_ATTR(call site returns, NAME)) 95 #define STATS_DECLTRACK_FLOATING_ATTR(NAME) \ 96 STATS_DECLTRACK(NAME, Floating, \ 97 ("Number of floating values known to be '" #NAME "'")) 98 99 // TODO: Determine a good default value. 100 // 101 // In the LLVM-TS and SPEC2006, 32 seems to not induce compile time overheads 102 // (when run with the first 5 abstract attributes). The results also indicate 103 // that we never reach 32 iterations but always find a fixpoint sooner. 104 // 105 // This will become more evolved once we perform two interleaved fixpoint 106 // iterations: bottom-up and top-down. 107 static cl::opt<unsigned> 108 MaxFixpointIterations("attributor-max-iterations", cl::Hidden, 109 cl::desc("Maximal number of fixpoint iterations."), 110 cl::init(32)); 111 112 static cl::opt<bool> DisableAttributor( 113 "attributor-disable", cl::Hidden, 114 cl::desc("Disable the attributor inter-procedural deduction pass."), 115 cl::init(true)); 116 117 static cl::opt<bool> VerifyAttributor( 118 "attributor-verify", cl::Hidden, 119 cl::desc("Verify the Attributor deduction and " 120 "manifestation of attributes -- may issue false-positive errors"), 121 cl::init(false)); 122 123 /// Logic operators for the change status enum class. 124 /// 125 ///{ 126 ChangeStatus llvm::operator|(ChangeStatus l, ChangeStatus r) { 127 return l == ChangeStatus::CHANGED ? l : r; 128 } 129 ChangeStatus llvm::operator&(ChangeStatus l, ChangeStatus r) { 130 return l == ChangeStatus::UNCHANGED ? l : r; 131 } 132 ///} 133 134 /// Recursively visit all values that might become \p IRP at some point. This 135 /// will be done by looking through cast instructions, selects, phis, and calls 136 /// with the "returned" attribute. Once we cannot look through the value any 137 /// further, the callback \p VisitValueCB is invoked and passed the current 138 /// value, the \p State, and a flag to indicate if we stripped anything. To 139 /// limit how much effort is invested, we will never visit more values than 140 /// specified by \p MaxValues. 141 template <typename AAType, typename StateTy> 142 bool genericValueTraversal( 143 Attributor &A, IRPosition IRP, const AAType &QueryingAA, StateTy &State, 144 const function_ref<bool(Value &, StateTy &, bool)> &VisitValueCB, 145 int MaxValues = 8) { 146 147 const AAIsDead *LivenessAA = nullptr; 148 if (IRP.getAnchorScope()) 149 LivenessAA = &A.getAAFor<AAIsDead>( 150 QueryingAA, IRPosition::function(*IRP.getAnchorScope())); 151 152 // TODO: Use Positions here to allow context sensitivity in VisitValueCB 153 SmallPtrSet<Value *, 16> Visited; 154 SmallVector<Value *, 16> Worklist; 155 Worklist.push_back(&IRP.getAssociatedValue()); 156 157 int Iteration = 0; 158 do { 159 Value *V = Worklist.pop_back_val(); 160 161 // Check if we should process the current value. To prevent endless 162 // recursion keep a record of the values we followed! 163 if (!Visited.insert(V).second) 164 continue; 165 166 // Make sure we limit the compile time for complex expressions. 167 if (Iteration++ >= MaxValues) 168 return false; 169 170 // Explicitly look through calls with a "returned" attribute if we do 171 // not have a pointer as stripPointerCasts only works on them. 172 Value *NewV = nullptr; 173 if (V->getType()->isPointerTy()) { 174 NewV = V->stripPointerCasts(); 175 } else { 176 CallSite CS(V); 177 if (CS && CS.getCalledFunction()) { 178 for (Argument &Arg : CS.getCalledFunction()->args()) 179 if (Arg.hasReturnedAttr()) { 180 NewV = CS.getArgOperand(Arg.getArgNo()); 181 break; 182 } 183 } 184 } 185 if (NewV && NewV != V) { 186 Worklist.push_back(NewV); 187 continue; 188 } 189 190 // Look through select instructions, visit both potential values. 191 if (auto *SI = dyn_cast<SelectInst>(V)) { 192 Worklist.push_back(SI->getTrueValue()); 193 Worklist.push_back(SI->getFalseValue()); 194 continue; 195 } 196 197 // Look through phi nodes, visit all live operands. 198 if (auto *PHI = dyn_cast<PHINode>(V)) { 199 assert(LivenessAA && 200 "Expected liveness in the presence of instructions!"); 201 for (unsigned u = 0, e = PHI->getNumIncomingValues(); u < e; u++) { 202 const BasicBlock *IncomingBB = PHI->getIncomingBlock(u); 203 if (!LivenessAA->isAssumedDead(IncomingBB->getTerminator())) 204 Worklist.push_back(PHI->getIncomingValue(u)); 205 } 206 continue; 207 } 208 209 // Once a leaf is reached we inform the user through the callback. 210 if (!VisitValueCB(*V, State, Iteration > 1)) 211 return false; 212 } while (!Worklist.empty()); 213 214 // All values have been visited. 215 return true; 216 } 217 218 /// Return true if \p New is equal or worse than \p Old. 219 static bool isEqualOrWorse(const Attribute &New, const Attribute &Old) { 220 if (!Old.isIntAttribute()) 221 return true; 222 223 return Old.getValueAsInt() >= New.getValueAsInt(); 224 } 225 226 /// Return true if the information provided by \p Attr was added to the 227 /// attribute list \p Attrs. This is only the case if it was not already present 228 /// in \p Attrs at the position describe by \p PK and \p AttrIdx. 229 static bool addIfNotExistent(LLVMContext &Ctx, const Attribute &Attr, 230 AttributeList &Attrs, int AttrIdx) { 231 232 if (Attr.isEnumAttribute()) { 233 Attribute::AttrKind Kind = Attr.getKindAsEnum(); 234 if (Attrs.hasAttribute(AttrIdx, Kind)) 235 if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) 236 return false; 237 Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); 238 return true; 239 } 240 if (Attr.isStringAttribute()) { 241 StringRef Kind = Attr.getKindAsString(); 242 if (Attrs.hasAttribute(AttrIdx, Kind)) 243 if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) 244 return false; 245 Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); 246 return true; 247 } 248 if (Attr.isIntAttribute()) { 249 Attribute::AttrKind Kind = Attr.getKindAsEnum(); 250 if (Attrs.hasAttribute(AttrIdx, Kind)) 251 if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) 252 return false; 253 Attrs = Attrs.removeAttribute(Ctx, AttrIdx, Kind); 254 Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); 255 return true; 256 } 257 258 llvm_unreachable("Expected enum or string attribute!"); 259 } 260 261 ChangeStatus AbstractAttribute::update(Attributor &A) { 262 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 263 if (getState().isAtFixpoint()) 264 return HasChanged; 265 266 LLVM_DEBUG(dbgs() << "[Attributor] Update: " << *this << "\n"); 267 268 HasChanged = updateImpl(A); 269 270 LLVM_DEBUG(dbgs() << "[Attributor] Update " << HasChanged << " " << *this 271 << "\n"); 272 273 return HasChanged; 274 } 275 276 ChangeStatus 277 IRAttributeManifest::manifestAttrs(Attributor &A, IRPosition &IRP, 278 const ArrayRef<Attribute> &DeducedAttrs) { 279 Function *ScopeFn = IRP.getAssociatedFunction(); 280 IRPosition::Kind PK = IRP.getPositionKind(); 281 282 // In the following some generic code that will manifest attributes in 283 // DeducedAttrs if they improve the current IR. Due to the different 284 // annotation positions we use the underlying AttributeList interface. 285 286 AttributeList Attrs; 287 switch (PK) { 288 case IRPosition::IRP_INVALID: 289 case IRPosition::IRP_FLOAT: 290 return ChangeStatus::UNCHANGED; 291 case IRPosition::IRP_ARGUMENT: 292 case IRPosition::IRP_FUNCTION: 293 case IRPosition::IRP_RETURNED: 294 Attrs = ScopeFn->getAttributes(); 295 break; 296 case IRPosition::IRP_CALL_SITE: 297 case IRPosition::IRP_CALL_SITE_RETURNED: 298 case IRPosition::IRP_CALL_SITE_ARGUMENT: 299 Attrs = ImmutableCallSite(&IRP.getAnchorValue()).getAttributes(); 300 break; 301 } 302 303 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 304 LLVMContext &Ctx = IRP.getAnchorValue().getContext(); 305 for (const Attribute &Attr : DeducedAttrs) { 306 if (!addIfNotExistent(Ctx, Attr, Attrs, IRP.getAttrIdx())) 307 continue; 308 309 HasChanged = ChangeStatus::CHANGED; 310 } 311 312 if (HasChanged == ChangeStatus::UNCHANGED) 313 return HasChanged; 314 315 switch (PK) { 316 case IRPosition::IRP_ARGUMENT: 317 case IRPosition::IRP_FUNCTION: 318 case IRPosition::IRP_RETURNED: 319 ScopeFn->setAttributes(Attrs); 320 break; 321 case IRPosition::IRP_CALL_SITE: 322 case IRPosition::IRP_CALL_SITE_RETURNED: 323 case IRPosition::IRP_CALL_SITE_ARGUMENT: 324 CallSite(&IRP.getAnchorValue()).setAttributes(Attrs); 325 break; 326 case IRPosition::IRP_INVALID: 327 case IRPosition::IRP_FLOAT: 328 break; 329 } 330 331 return HasChanged; 332 } 333 334 const IRPosition IRPosition::EmptyKey(255); 335 const IRPosition IRPosition::TombstoneKey(256); 336 337 SubsumingPositionIterator::SubsumingPositionIterator(const IRPosition &IRP) { 338 IRPositions.emplace_back(IRP); 339 340 ImmutableCallSite ICS(&IRP.getAnchorValue()); 341 switch (IRP.getPositionKind()) { 342 case IRPosition::IRP_INVALID: 343 case IRPosition::IRP_FLOAT: 344 case IRPosition::IRP_FUNCTION: 345 return; 346 case IRPosition::IRP_ARGUMENT: 347 case IRPosition::IRP_RETURNED: 348 IRPositions.emplace_back( 349 IRPosition::function(*IRP.getAssociatedFunction())); 350 return; 351 case IRPosition::IRP_CALL_SITE: 352 assert(ICS && "Expected call site!"); 353 // TODO: We need to look at the operand bundles similar to the redirection 354 // in CallBase. 355 if (!ICS.hasOperandBundles()) 356 if (const Function *Callee = ICS.getCalledFunction()) 357 IRPositions.emplace_back(IRPosition::function(*Callee)); 358 return; 359 case IRPosition::IRP_CALL_SITE_RETURNED: 360 assert(ICS && "Expected call site!"); 361 // TODO: We need to look at the operand bundles similar to the redirection 362 // in CallBase. 363 if (!ICS.hasOperandBundles()) { 364 if (const Function *Callee = ICS.getCalledFunction()) { 365 IRPositions.emplace_back(IRPosition::returned(*Callee)); 366 IRPositions.emplace_back(IRPosition::function(*Callee)); 367 } 368 } 369 IRPositions.emplace_back( 370 IRPosition::callsite_function(cast<CallBase>(*ICS.getInstruction()))); 371 return; 372 case IRPosition::IRP_CALL_SITE_ARGUMENT: { 373 int ArgNo = IRP.getArgNo(); 374 assert(ICS && ArgNo >= 0 && "Expected call site!"); 375 // TODO: We need to look at the operand bundles similar to the redirection 376 // in CallBase. 377 if (!ICS.hasOperandBundles()) { 378 const Function *Callee = ICS.getCalledFunction(); 379 if (Callee && Callee->arg_size() > unsigned(ArgNo)) 380 IRPositions.emplace_back(IRPosition::argument(*Callee->getArg(ArgNo))); 381 if (Callee) 382 IRPositions.emplace_back(IRPosition::function(*Callee)); 383 } 384 IRPositions.emplace_back(IRPosition::value(IRP.getAssociatedValue())); 385 return; 386 } 387 } 388 } 389 390 bool IRPosition::hasAttr(ArrayRef<Attribute::AttrKind> AKs) const { 391 for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) 392 for (Attribute::AttrKind AK : AKs) 393 if (EquivIRP.getAttr(AK).getKindAsEnum() == AK) 394 return true; 395 return false; 396 } 397 398 void IRPosition::getAttrs(ArrayRef<Attribute::AttrKind> AKs, 399 SmallVectorImpl<Attribute> &Attrs) const { 400 for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) 401 for (Attribute::AttrKind AK : AKs) { 402 const Attribute &Attr = EquivIRP.getAttr(AK); 403 if (Attr.getKindAsEnum() == AK) 404 Attrs.push_back(Attr); 405 } 406 } 407 408 void IRPosition::verify() { 409 switch (KindOrArgNo) { 410 default: 411 assert(KindOrArgNo >= 0 && "Expected argument or call site argument!"); 412 assert((isa<CallBase>(AnchorVal) || isa<Argument>(AnchorVal)) && 413 "Expected call base or argument for positive attribute index!"); 414 if (auto *Arg = dyn_cast<Argument>(AnchorVal)) { 415 assert(Arg->getArgNo() == unsigned(getArgNo()) && 416 "Argument number mismatch!"); 417 assert(Arg == &getAssociatedValue() && "Associated value mismatch!"); 418 } else { 419 auto &CB = cast<CallBase>(*AnchorVal); 420 (void)CB; 421 assert(CB.arg_size() > unsigned(getArgNo()) && 422 "Call site argument number mismatch!"); 423 assert(CB.getArgOperand(getArgNo()) == &getAssociatedValue() && 424 "Associated value mismatch!"); 425 } 426 break; 427 case IRP_INVALID: 428 assert(!AnchorVal && "Expected no value for an invalid position!"); 429 break; 430 case IRP_FLOAT: 431 assert((!isa<CallBase>(&getAssociatedValue()) && 432 !isa<Argument>(&getAssociatedValue())) && 433 "Expected specialized kind for call base and argument values!"); 434 break; 435 case IRP_RETURNED: 436 assert(isa<Function>(AnchorVal) && 437 "Expected function for a 'returned' position!"); 438 assert(AnchorVal == &getAssociatedValue() && "Associated value mismatch!"); 439 break; 440 case IRP_CALL_SITE_RETURNED: 441 assert((isa<CallBase>(AnchorVal)) && 442 "Expected call base for 'call site returned' position!"); 443 assert(AnchorVal == &getAssociatedValue() && "Associated value mismatch!"); 444 break; 445 case IRP_CALL_SITE: 446 assert((isa<CallBase>(AnchorVal)) && 447 "Expected call base for 'call site function' position!"); 448 assert(AnchorVal == &getAssociatedValue() && "Associated value mismatch!"); 449 break; 450 case IRP_FUNCTION: 451 assert(isa<Function>(AnchorVal) && 452 "Expected function for a 'function' position!"); 453 assert(AnchorVal == &getAssociatedValue() && "Associated value mismatch!"); 454 break; 455 } 456 } 457 458 /// Helper functions to clamp a state \p S of type \p StateType with the 459 /// information in \p R and indicate/return if \p S did change (as-in update is 460 /// required to be run again). 461 /// 462 ///{ 463 template <typename StateType> 464 ChangeStatus clampStateAndIndicateChange(StateType &S, const StateType &R); 465 466 template <> 467 ChangeStatus clampStateAndIndicateChange<IntegerState>(IntegerState &S, 468 const IntegerState &R) { 469 auto Assumed = S.getAssumed(); 470 S ^= R; 471 return Assumed == S.getAssumed() ? ChangeStatus::UNCHANGED 472 : ChangeStatus::CHANGED; 473 } 474 475 template <> 476 ChangeStatus clampStateAndIndicateChange<BooleanState>(BooleanState &S, 477 const BooleanState &R) { 478 return clampStateAndIndicateChange<IntegerState>(S, R); 479 } 480 ///} 481 482 /// Clamp the information known for all returned values of a function 483 /// (identified by \p QueryingAA) into \p S. 484 template <typename AAType, typename StateType = typename AAType::StateType> 485 static void clampReturnedValueStates(Attributor &A, const AAType &QueryingAA, 486 StateType &S) { 487 LLVM_DEBUG(dbgs() << "[Attributor] Clamp return value states for " 488 << static_cast<const AbstractAttribute &>(QueryingAA) 489 << " into " << S << "\n"); 490 491 assert((QueryingAA.getIRPosition().getPositionKind() == 492 IRPosition::IRP_RETURNED || 493 QueryingAA.getIRPosition().getPositionKind() == 494 IRPosition::IRP_CALL_SITE_RETURNED) && 495 "Can only clamp returned value states for a function returned or call " 496 "site returned position!"); 497 498 // Use an optional state as there might not be any return values and we want 499 // to join (IntegerState::operator&) the state of all there are. 500 Optional<StateType> T; 501 502 // Callback for each possibly returned value. 503 auto CheckReturnValue = [&](Value &RV) -> bool { 504 const IRPosition &RVPos = IRPosition::value(RV); 505 const AAType &AA = A.getAAFor<AAType>(QueryingAA, RVPos); 506 LLVM_DEBUG(dbgs() << "[Attributor] RV: " << RV << " AA: " << AA.getAsStr() 507 << " @ " << RVPos << "\n"); 508 const StateType &AAS = static_cast<const StateType &>(AA.getState()); 509 if (T.hasValue()) 510 *T &= AAS; 511 else 512 T = AAS; 513 LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " RV State: " << T 514 << "\n"); 515 return T->isValidState(); 516 }; 517 518 if (!A.checkForAllReturnedValues(CheckReturnValue, QueryingAA)) 519 S.indicatePessimisticFixpoint(); 520 else if (T.hasValue()) 521 S ^= *T; 522 } 523 524 /// Helper class for generic deduction: return value -> returned position. 525 template <typename AAType, typename Base, 526 typename StateType = typename AAType::StateType> 527 struct AAReturnedFromReturnedValues : public Base { 528 AAReturnedFromReturnedValues(const IRPosition &IRP) : Base(IRP) {} 529 530 /// See AbstractAttribute::updateImpl(...). 531 ChangeStatus updateImpl(Attributor &A) override { 532 StateType S; 533 clampReturnedValueStates<AAType, StateType>(A, *this, S); 534 // TODO: If we know we visited all returned values, thus no are assumed 535 // dead, we can take the known information from the state T. 536 return clampStateAndIndicateChange<StateType>(this->getState(), S); 537 } 538 }; 539 540 /// Clamp the information known at all call sites for a given argument 541 /// (identified by \p QueryingAA) into \p S. 542 template <typename AAType, typename StateType = typename AAType::StateType> 543 static void clampCallSiteArgumentStates(Attributor &A, const AAType &QueryingAA, 544 StateType &S) { 545 LLVM_DEBUG(dbgs() << "[Attributor] Clamp call site argument states for " 546 << static_cast<const AbstractAttribute &>(QueryingAA) 547 << " into " << S << "\n"); 548 549 assert(QueryingAA.getIRPosition().getPositionKind() == 550 IRPosition::IRP_ARGUMENT && 551 "Can only clamp call site argument states for an argument position!"); 552 553 // Use an optional state as there might not be any return values and we want 554 // to join (IntegerState::operator&) the state of all there are. 555 Optional<StateType> T; 556 557 // The argument number which is also the call site argument number. 558 unsigned ArgNo = QueryingAA.getIRPosition().getArgNo(); 559 560 auto CallSiteCheck = [&](CallSite CS) { 561 const IRPosition &CSArgPos = IRPosition::callsite_argument(CS, ArgNo); 562 const AAType &AA = A.getAAFor<AAType>(QueryingAA, CSArgPos); 563 LLVM_DEBUG(dbgs() << "[Attributor] CS: " << *CS.getInstruction() 564 << " AA: " << AA.getAsStr() << " @" << CSArgPos << "\n"); 565 const StateType &AAS = static_cast<const StateType &>(AA.getState()); 566 if (T.hasValue()) 567 *T &= AAS; 568 else 569 T = AAS; 570 LLVM_DEBUG(dbgs() << "[Attributor] AA State: " << AAS << " CSA State: " << T 571 << "\n"); 572 return T->isValidState(); 573 }; 574 575 if (!A.checkForAllCallSites(CallSiteCheck, QueryingAA, true)) 576 S.indicatePessimisticFixpoint(); 577 else if (T.hasValue()) 578 S ^= *T; 579 } 580 581 /// Helper class for generic deduction: call site argument -> argument position. 582 template <typename AAType, typename Base, 583 typename StateType = typename AAType::StateType> 584 struct AAArgumentFromCallSiteArguments : public Base { 585 AAArgumentFromCallSiteArguments(const IRPosition &IRP) : Base(IRP) {} 586 587 /// See AbstractAttribute::updateImpl(...). 588 ChangeStatus updateImpl(Attributor &A) override { 589 StateType S; 590 clampCallSiteArgumentStates<AAType, StateType>(A, *this, S); 591 // TODO: If we know we visited all incoming values, thus no are assumed 592 // dead, we can take the known information from the state T. 593 return clampStateAndIndicateChange<StateType>(this->getState(), S); 594 } 595 }; 596 597 /// Helper class for generic replication: function returned -> cs returned. 598 template <typename AAType, typename Base> 599 struct AACallSiteReturnedFromReturned : public Base { 600 AACallSiteReturnedFromReturned(const IRPosition &IRP) : Base(IRP) {} 601 602 /// See AbstractAttribute::updateImpl(...). 603 ChangeStatus updateImpl(Attributor &A) override { 604 assert(this->getIRPosition().getPositionKind() == 605 IRPosition::IRP_CALL_SITE_RETURNED && 606 "Can only wrap function returned positions for call site returned " 607 "positions!"); 608 auto &S = this->getState(); 609 610 const Function *AssociatedFunction = 611 this->getIRPosition().getAssociatedFunction(); 612 if (!AssociatedFunction) 613 return S.indicatePessimisticFixpoint(); 614 615 IRPosition FnPos = IRPosition::returned(*AssociatedFunction); 616 const AAType &AA = A.getAAFor<AAType>(*this, FnPos); 617 return clampStateAndIndicateChange( 618 S, static_cast<const typename AAType::StateType &>(AA.getState())); 619 } 620 }; 621 622 /// -----------------------NoUnwind Function Attribute-------------------------- 623 624 struct AANoUnwindImpl : AANoUnwind { 625 AANoUnwindImpl(const IRPosition &IRP) : AANoUnwind(IRP) {} 626 627 /// See AbstractAttribute::initialize(...). 628 void initialize(Attributor &A) override { 629 if (hasAttr({Attribute::NoUnwind})) 630 indicateOptimisticFixpoint(); 631 } 632 633 const std::string getAsStr() const override { 634 return getAssumed() ? "nounwind" : "may-unwind"; 635 } 636 637 /// See AbstractAttribute::updateImpl(...). 638 ChangeStatus updateImpl(Attributor &A) override { 639 auto Opcodes = { 640 (unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr, 641 (unsigned)Instruction::Call, (unsigned)Instruction::CleanupRet, 642 (unsigned)Instruction::CatchSwitch, (unsigned)Instruction::Resume}; 643 644 auto CheckForNoUnwind = [&](Instruction &I) { 645 if (!I.mayThrow()) 646 return true; 647 648 if (ImmutableCallSite ICS = ImmutableCallSite(&I)) { 649 const auto &NoUnwindAA = 650 A.getAAFor<AANoUnwind>(*this, IRPosition::callsite_function(ICS)); 651 return NoUnwindAA.isAssumedNoUnwind(); 652 } 653 return false; 654 }; 655 656 if (!A.checkForAllInstructions(CheckForNoUnwind, *this, Opcodes)) 657 return indicatePessimisticFixpoint(); 658 659 return ChangeStatus::UNCHANGED; 660 } 661 }; 662 663 struct AANoUnwindFunction final : public AANoUnwindImpl { 664 AANoUnwindFunction(const IRPosition &IRP) : AANoUnwindImpl(IRP) {} 665 666 /// See AbstractAttribute::trackStatistics() 667 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nounwind) } 668 }; 669 670 /// NoUnwind attribute deduction for a call sites. 671 using AANoUnwindCallSite = AANoUnwindFunction; 672 673 /// --------------------- Function Return Values ------------------------------- 674 675 /// "Attribute" that collects all potential returned values and the return 676 /// instructions that they arise from. 677 /// 678 /// If there is a unique returned value R, the manifest method will: 679 /// - mark R with the "returned" attribute, if R is an argument. 680 class AAReturnedValuesImpl : public AAReturnedValues, public AbstractState { 681 682 /// Mapping of values potentially returned by the associated function to the 683 /// return instructions that might return them. 684 DenseMap<Value *, SmallPtrSet<ReturnInst *, 2>> ReturnedValues; 685 686 SmallPtrSet<CallBase *, 8> UnresolvedCalls; 687 688 /// State flags 689 /// 690 ///{ 691 bool IsFixed; 692 bool IsValidState; 693 ///} 694 695 public: 696 AAReturnedValuesImpl(const IRPosition &IRP) : AAReturnedValues(IRP) {} 697 698 /// See AbstractAttribute::initialize(...). 699 void initialize(Attributor &A) override { 700 // Reset the state. 701 IsFixed = false; 702 IsValidState = true; 703 ReturnedValues.clear(); 704 705 Function *F = getAssociatedFunction(); 706 if (!F || !F->hasExactDefinition()) { 707 indicatePessimisticFixpoint(); 708 return; 709 } 710 711 // The map from instruction opcodes to those instructions in the function. 712 auto &OpcodeInstMap = A.getInfoCache().getOpcodeInstMapForFunction(*F); 713 714 // Look through all arguments, if one is marked as returned we are done. 715 for (Argument &Arg : F->args()) { 716 if (Arg.hasReturnedAttr()) { 717 auto &ReturnInstSet = ReturnedValues[&Arg]; 718 for (Instruction *RI : OpcodeInstMap[Instruction::Ret]) 719 ReturnInstSet.insert(cast<ReturnInst>(RI)); 720 721 indicateOptimisticFixpoint(); 722 return; 723 } 724 } 725 } 726 727 /// See AbstractAttribute::manifest(...). 728 ChangeStatus manifest(Attributor &A) override; 729 730 /// See AbstractAttribute::getState(...). 731 AbstractState &getState() override { return *this; } 732 733 /// See AbstractAttribute::getState(...). 734 const AbstractState &getState() const override { return *this; } 735 736 /// See AbstractAttribute::updateImpl(Attributor &A). 737 ChangeStatus updateImpl(Attributor &A) override; 738 739 llvm::iterator_range<iterator> returned_values() override { 740 return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end()); 741 } 742 743 llvm::iterator_range<const_iterator> returned_values() const override { 744 return llvm::make_range(ReturnedValues.begin(), ReturnedValues.end()); 745 } 746 747 const SmallPtrSetImpl<CallBase *> &getUnresolvedCalls() const override { 748 return UnresolvedCalls; 749 } 750 751 /// Return the number of potential return values, -1 if unknown. 752 size_t getNumReturnValues() const override { 753 return isValidState() ? ReturnedValues.size() : -1; 754 } 755 756 /// Return an assumed unique return value if a single candidate is found. If 757 /// there cannot be one, return a nullptr. If it is not clear yet, return the 758 /// Optional::NoneType. 759 Optional<Value *> getAssumedUniqueReturnValue(Attributor &A) const; 760 761 /// See AbstractState::checkForAllReturnedValues(...). 762 bool checkForAllReturnedValuesAndReturnInsts( 763 const function_ref<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)> 764 &Pred) const override; 765 766 /// Pretty print the attribute similar to the IR representation. 767 const std::string getAsStr() const override; 768 769 /// See AbstractState::isAtFixpoint(). 770 bool isAtFixpoint() const override { return IsFixed; } 771 772 /// See AbstractState::isValidState(). 773 bool isValidState() const override { return IsValidState; } 774 775 /// See AbstractState::indicateOptimisticFixpoint(...). 776 ChangeStatus indicateOptimisticFixpoint() override { 777 IsFixed = true; 778 IsValidState &= true; 779 return ChangeStatus::UNCHANGED; 780 } 781 782 ChangeStatus indicatePessimisticFixpoint() override { 783 IsFixed = true; 784 IsValidState = false; 785 return ChangeStatus::CHANGED; 786 } 787 }; 788 789 ChangeStatus AAReturnedValuesImpl::manifest(Attributor &A) { 790 ChangeStatus Changed = ChangeStatus::UNCHANGED; 791 792 // Bookkeeping. 793 assert(isValidState()); 794 STATS_DECLTRACK(KnownReturnValues, FunctionReturn, 795 "Number of function with known return values"); 796 797 // Check if we have an assumed unique return value that we could manifest. 798 Optional<Value *> UniqueRV = getAssumedUniqueReturnValue(A); 799 800 if (!UniqueRV.hasValue() || !UniqueRV.getValue()) 801 return Changed; 802 803 // Bookkeeping. 804 STATS_DECLTRACK(UniqueReturnValue, FunctionReturn, 805 "Number of function with unique return"); 806 807 // If the assumed unique return value is an argument, annotate it. 808 if (auto *UniqueRVArg = dyn_cast<Argument>(UniqueRV.getValue())) { 809 getIRPosition() = IRPosition::argument(*UniqueRVArg); 810 Changed = IRAttribute::manifest(A) | Changed; 811 } 812 813 return Changed; 814 } 815 816 const std::string AAReturnedValuesImpl::getAsStr() const { 817 return (isAtFixpoint() ? "returns(#" : "may-return(#") + 818 (isValidState() ? std::to_string(getNumReturnValues()) : "?") + 819 ")[#UC: " + std::to_string(UnresolvedCalls.size()) + "]"; 820 } 821 822 Optional<Value *> 823 AAReturnedValuesImpl::getAssumedUniqueReturnValue(Attributor &A) const { 824 // If checkForAllReturnedValues provides a unique value, ignoring potential 825 // undef values that can also be present, it is assumed to be the actual 826 // return value and forwarded to the caller of this method. If there are 827 // multiple, a nullptr is returned indicating there cannot be a unique 828 // returned value. 829 Optional<Value *> UniqueRV; 830 831 auto Pred = [&](Value &RV) -> bool { 832 // If we found a second returned value and neither the current nor the saved 833 // one is an undef, there is no unique returned value. Undefs are special 834 // since we can pretend they have any value. 835 if (UniqueRV.hasValue() && UniqueRV != &RV && 836 !(isa<UndefValue>(RV) || isa<UndefValue>(UniqueRV.getValue()))) { 837 UniqueRV = nullptr; 838 return false; 839 } 840 841 // Do not overwrite a value with an undef. 842 if (!UniqueRV.hasValue() || !isa<UndefValue>(RV)) 843 UniqueRV = &RV; 844 845 return true; 846 }; 847 848 if (!A.checkForAllReturnedValues(Pred, *this)) 849 UniqueRV = nullptr; 850 851 return UniqueRV; 852 } 853 854 bool AAReturnedValuesImpl::checkForAllReturnedValuesAndReturnInsts( 855 const function_ref<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)> 856 &Pred) const { 857 if (!isValidState()) 858 return false; 859 860 // Check all returned values but ignore call sites as long as we have not 861 // encountered an overdefined one during an update. 862 for (auto &It : ReturnedValues) { 863 Value *RV = It.first; 864 const SmallPtrSetImpl<ReturnInst *> &RetInsts = It.second; 865 866 CallBase *CB = dyn_cast<CallBase>(RV); 867 if (CB && !UnresolvedCalls.count(CB)) 868 continue; 869 870 if (!Pred(*RV, RetInsts)) 871 return false; 872 } 873 874 return true; 875 } 876 877 ChangeStatus AAReturnedValuesImpl::updateImpl(Attributor &A) { 878 size_t NumUnresolvedCalls = UnresolvedCalls.size(); 879 bool Changed = false; 880 881 // State used in the value traversals starting in returned values. 882 struct RVState { 883 // The map in which we collect return values -> return instrs. 884 decltype(ReturnedValues) &RetValsMap; 885 // The flag to indicate a change. 886 bool &Changed; 887 // The return instrs we come from. 888 SmallPtrSet<ReturnInst *, 2> RetInsts; 889 }; 890 891 // Callback for a leaf value returned by the associated function. 892 auto VisitValueCB = [](Value &Val, RVState &RVS, bool) -> bool { 893 auto Size = RVS.RetValsMap[&Val].size(); 894 RVS.RetValsMap[&Val].insert(RVS.RetInsts.begin(), RVS.RetInsts.end()); 895 bool Inserted = RVS.RetValsMap[&Val].size() != Size; 896 RVS.Changed |= Inserted; 897 LLVM_DEBUG({ 898 if (Inserted) 899 dbgs() << "[AAReturnedValues] 1 Add new returned value " << Val 900 << " => " << RVS.RetInsts.size() << "\n"; 901 }); 902 return true; 903 }; 904 905 // Helper method to invoke the generic value traversal. 906 auto VisitReturnedValue = [&](Value &RV, RVState &RVS) { 907 IRPosition RetValPos = IRPosition::value(RV); 908 return genericValueTraversal<AAReturnedValues, RVState>(A, RetValPos, *this, 909 RVS, VisitValueCB); 910 }; 911 912 // Callback for all "return intructions" live in the associated function. 913 auto CheckReturnInst = [this, &VisitReturnedValue, &Changed](Instruction &I) { 914 ReturnInst &Ret = cast<ReturnInst>(I); 915 RVState RVS({ReturnedValues, Changed, {}}); 916 RVS.RetInsts.insert(&Ret); 917 return VisitReturnedValue(*Ret.getReturnValue(), RVS); 918 }; 919 920 // Start by discovering returned values from all live returned instructions in 921 // the associated function. 922 if (!A.checkForAllInstructions(CheckReturnInst, *this, {Instruction::Ret})) 923 return indicatePessimisticFixpoint(); 924 925 // Once returned values "directly" present in the code are handled we try to 926 // resolve returned calls. 927 decltype(ReturnedValues) NewRVsMap; 928 for (auto &It : ReturnedValues) { 929 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Returned value: " << *It.first 930 << " by #" << It.second.size() << " RIs\n"); 931 CallBase *CB = dyn_cast<CallBase>(It.first); 932 if (!CB || UnresolvedCalls.count(CB)) 933 continue; 934 935 const auto &RetValAA = 936 A.getAAFor<AAReturnedValues>(*this, IRPosition::callsite_function(*CB)); 937 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Found another AAReturnedValues: " 938 << static_cast<const AbstractAttribute &>(RetValAA) 939 << "\n"); 940 941 // Skip dead ends, thus if we do not know anything about the returned 942 // call we mark it as unresolved and it will stay that way. 943 if (!RetValAA.getState().isValidState()) { 944 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Unresolved call: " << *CB 945 << "\n"); 946 UnresolvedCalls.insert(CB); 947 continue; 948 } 949 950 // Do not try to learn partial information. If the callee has unresolved 951 // return values we will treat the call as unresolved/opaque. 952 auto &RetValAAUnresolvedCalls = RetValAA.getUnresolvedCalls(); 953 if (!RetValAAUnresolvedCalls.empty()) { 954 UnresolvedCalls.insert(CB); 955 continue; 956 } 957 958 // Now check if we can track transitively returned values. If possible, thus 959 // if all return value can be represented in the current scope, do so. 960 bool Unresolved = false; 961 for (auto &RetValAAIt : RetValAA.returned_values()) { 962 Value *RetVal = RetValAAIt.first; 963 if (isa<Argument>(RetVal) || isa<CallBase>(RetVal) || 964 isa<Constant>(RetVal)) 965 continue; 966 // Anything that did not fit in the above categories cannot be resolved, 967 // mark the call as unresolved. 968 LLVM_DEBUG(dbgs() << "[AAReturnedValues] transitively returned value " 969 "cannot be translated: " 970 << *RetVal << "\n"); 971 UnresolvedCalls.insert(CB); 972 Unresolved = true; 973 break; 974 } 975 976 if (Unresolved) 977 continue; 978 979 for (auto &RetValAAIt : RetValAA.returned_values()) { 980 Value *RetVal = RetValAAIt.first; 981 if (Argument *Arg = dyn_cast<Argument>(RetVal)) { 982 // Arguments are mapped to call site operands and we begin the traversal 983 // again. 984 bool Unused = false; 985 RVState RVS({NewRVsMap, Unused, RetValAAIt.second}); 986 VisitReturnedValue(*CB->getArgOperand(Arg->getArgNo()), RVS); 987 continue; 988 } else if (isa<CallBase>(RetVal)) { 989 // Call sites are resolved by the callee attribute over time, no need to 990 // do anything for us. 991 continue; 992 } else if (isa<Constant>(RetVal)) { 993 // Constants are valid everywhere, we can simply take them. 994 NewRVsMap[RetVal].insert(It.second.begin(), It.second.end()); 995 continue; 996 } 997 } 998 } 999 1000 // To avoid modifications to the ReturnedValues map while we iterate over it 1001 // we kept record of potential new entries in a copy map, NewRVsMap. 1002 for (auto &It : NewRVsMap) { 1003 assert(!It.second.empty() && "Entry does not add anything."); 1004 auto &ReturnInsts = ReturnedValues[It.first]; 1005 for (ReturnInst *RI : It.second) 1006 if (ReturnInsts.insert(RI).second) { 1007 LLVM_DEBUG(dbgs() << "[AAReturnedValues] Add new returned value " 1008 << *It.first << " => " << *RI << "\n"); 1009 Changed = true; 1010 } 1011 } 1012 1013 Changed |= (NumUnresolvedCalls != UnresolvedCalls.size()); 1014 return Changed ? ChangeStatus::CHANGED : ChangeStatus::UNCHANGED; 1015 } 1016 1017 struct AAReturnedValuesFunction final : public AAReturnedValuesImpl { 1018 AAReturnedValuesFunction(const IRPosition &IRP) : AAReturnedValuesImpl(IRP) {} 1019 1020 /// See AbstractAttribute::trackStatistics() 1021 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(returned) } 1022 }; 1023 1024 /// Returned values information for a call sites. 1025 using AAReturnedValuesCallSite = AAReturnedValuesFunction; 1026 1027 /// ------------------------ NoSync Function Attribute ------------------------- 1028 1029 struct AANoSyncImpl : AANoSync { 1030 AANoSyncImpl(const IRPosition &IRP) : AANoSync(IRP) {} 1031 1032 /// See AbstractAttribute::initialize(...). 1033 void initialize(Attributor &A) override { 1034 if (hasAttr({Attribute::NoSync})) 1035 indicateOptimisticFixpoint(); 1036 } 1037 1038 const std::string getAsStr() const override { 1039 return getAssumed() ? "nosync" : "may-sync"; 1040 } 1041 1042 /// See AbstractAttribute::updateImpl(...). 1043 ChangeStatus updateImpl(Attributor &A) override; 1044 1045 /// Helper function used to determine whether an instruction is non-relaxed 1046 /// atomic. In other words, if an atomic instruction does not have unordered 1047 /// or monotonic ordering 1048 static bool isNonRelaxedAtomic(Instruction *I); 1049 1050 /// Helper function used to determine whether an instruction is volatile. 1051 static bool isVolatile(Instruction *I); 1052 1053 /// Helper function uset to check if intrinsic is volatile (memcpy, memmove, 1054 /// memset). 1055 static bool isNoSyncIntrinsic(Instruction *I); 1056 }; 1057 1058 bool AANoSyncImpl::isNonRelaxedAtomic(Instruction *I) { 1059 if (!I->isAtomic()) 1060 return false; 1061 1062 AtomicOrdering Ordering; 1063 switch (I->getOpcode()) { 1064 case Instruction::AtomicRMW: 1065 Ordering = cast<AtomicRMWInst>(I)->getOrdering(); 1066 break; 1067 case Instruction::Store: 1068 Ordering = cast<StoreInst>(I)->getOrdering(); 1069 break; 1070 case Instruction::Load: 1071 Ordering = cast<LoadInst>(I)->getOrdering(); 1072 break; 1073 case Instruction::Fence: { 1074 auto *FI = cast<FenceInst>(I); 1075 if (FI->getSyncScopeID() == SyncScope::SingleThread) 1076 return false; 1077 Ordering = FI->getOrdering(); 1078 break; 1079 } 1080 case Instruction::AtomicCmpXchg: { 1081 AtomicOrdering Success = cast<AtomicCmpXchgInst>(I)->getSuccessOrdering(); 1082 AtomicOrdering Failure = cast<AtomicCmpXchgInst>(I)->getFailureOrdering(); 1083 // Only if both are relaxed, than it can be treated as relaxed. 1084 // Otherwise it is non-relaxed. 1085 if (Success != AtomicOrdering::Unordered && 1086 Success != AtomicOrdering::Monotonic) 1087 return true; 1088 if (Failure != AtomicOrdering::Unordered && 1089 Failure != AtomicOrdering::Monotonic) 1090 return true; 1091 return false; 1092 } 1093 default: 1094 llvm_unreachable( 1095 "New atomic operations need to be known in the attributor."); 1096 } 1097 1098 // Relaxed. 1099 if (Ordering == AtomicOrdering::Unordered || 1100 Ordering == AtomicOrdering::Monotonic) 1101 return false; 1102 return true; 1103 } 1104 1105 /// Checks if an intrinsic is nosync. Currently only checks mem* intrinsics. 1106 /// FIXME: We should ipmrove the handling of intrinsics. 1107 bool AANoSyncImpl::isNoSyncIntrinsic(Instruction *I) { 1108 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1109 switch (II->getIntrinsicID()) { 1110 /// Element wise atomic memory intrinsics are can only be unordered, 1111 /// therefore nosync. 1112 case Intrinsic::memset_element_unordered_atomic: 1113 case Intrinsic::memmove_element_unordered_atomic: 1114 case Intrinsic::memcpy_element_unordered_atomic: 1115 return true; 1116 case Intrinsic::memset: 1117 case Intrinsic::memmove: 1118 case Intrinsic::memcpy: 1119 if (!cast<MemIntrinsic>(II)->isVolatile()) 1120 return true; 1121 return false; 1122 default: 1123 return false; 1124 } 1125 } 1126 return false; 1127 } 1128 1129 bool AANoSyncImpl::isVolatile(Instruction *I) { 1130 assert(!ImmutableCallSite(I) && !isa<CallBase>(I) && 1131 "Calls should not be checked here"); 1132 1133 switch (I->getOpcode()) { 1134 case Instruction::AtomicRMW: 1135 return cast<AtomicRMWInst>(I)->isVolatile(); 1136 case Instruction::Store: 1137 return cast<StoreInst>(I)->isVolatile(); 1138 case Instruction::Load: 1139 return cast<LoadInst>(I)->isVolatile(); 1140 case Instruction::AtomicCmpXchg: 1141 return cast<AtomicCmpXchgInst>(I)->isVolatile(); 1142 default: 1143 return false; 1144 } 1145 } 1146 1147 ChangeStatus AANoSyncImpl::updateImpl(Attributor &A) { 1148 1149 auto CheckRWInstForNoSync = [&](Instruction &I) { 1150 /// We are looking for volatile instructions or Non-Relaxed atomics. 1151 /// FIXME: We should ipmrove the handling of intrinsics. 1152 1153 if (isa<IntrinsicInst>(&I) && isNoSyncIntrinsic(&I)) 1154 return true; 1155 1156 if (ImmutableCallSite ICS = ImmutableCallSite(&I)) { 1157 if (ICS.hasFnAttr(Attribute::NoSync)) 1158 return true; 1159 1160 const auto &NoSyncAA = 1161 A.getAAFor<AANoSync>(*this, IRPosition::callsite_function(ICS)); 1162 if (NoSyncAA.isAssumedNoSync()) 1163 return true; 1164 return false; 1165 } 1166 1167 if (!isVolatile(&I) && !isNonRelaxedAtomic(&I)) 1168 return true; 1169 1170 return false; 1171 }; 1172 1173 auto CheckForNoSync = [&](Instruction &I) { 1174 // At this point we handled all read/write effects and they are all 1175 // nosync, so they can be skipped. 1176 if (I.mayReadOrWriteMemory()) 1177 return true; 1178 1179 // non-convergent and readnone imply nosync. 1180 return !ImmutableCallSite(&I).isConvergent(); 1181 }; 1182 1183 if (!A.checkForAllReadWriteInstructions(CheckRWInstForNoSync, *this) || 1184 !A.checkForAllCallLikeInstructions(CheckForNoSync, *this)) 1185 return indicatePessimisticFixpoint(); 1186 1187 return ChangeStatus::UNCHANGED; 1188 } 1189 1190 struct AANoSyncFunction final : public AANoSyncImpl { 1191 AANoSyncFunction(const IRPosition &IRP) : AANoSyncImpl(IRP) {} 1192 1193 /// See AbstractAttribute::trackStatistics() 1194 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nosync) } 1195 }; 1196 1197 /// NoSync attribute deduction for a call sites. 1198 using AANoSyncCallSite = AANoSyncFunction; 1199 1200 /// ------------------------ No-Free Attributes ---------------------------- 1201 1202 struct AANoFreeImpl : public AANoFree { 1203 AANoFreeImpl(const IRPosition &IRP) : AANoFree(IRP) {} 1204 1205 /// See AbstractAttribute::initialize(...). 1206 void initialize(Attributor &A) override { 1207 if (hasAttr({Attribute::NoFree})) 1208 indicateOptimisticFixpoint(); 1209 } 1210 1211 /// See AbstractAttribute::updateImpl(...). 1212 ChangeStatus updateImpl(Attributor &A) override { 1213 auto CheckForNoFree = [&](Instruction &I) { 1214 ImmutableCallSite ICS(&I); 1215 if (ICS.hasFnAttr(Attribute::NoFree)) 1216 return true; 1217 1218 const auto &NoFreeAA = 1219 A.getAAFor<AANoFree>(*this, IRPosition::callsite_function(ICS)); 1220 return NoFreeAA.isAssumedNoFree(); 1221 }; 1222 1223 if (!A.checkForAllCallLikeInstructions(CheckForNoFree, *this)) 1224 return indicatePessimisticFixpoint(); 1225 return ChangeStatus::UNCHANGED; 1226 } 1227 1228 /// See AbstractAttribute::getAsStr(). 1229 const std::string getAsStr() const override { 1230 return getAssumed() ? "nofree" : "may-free"; 1231 } 1232 }; 1233 1234 struct AANoFreeFunction final : public AANoFreeImpl { 1235 AANoFreeFunction(const IRPosition &IRP) : AANoFreeImpl(IRP) {} 1236 1237 /// See AbstractAttribute::trackStatistics() 1238 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(nofree) } 1239 }; 1240 1241 /// NoFree attribute deduction for a call sites. 1242 using AANoFreeCallSite = AANoFreeFunction; 1243 1244 /// ------------------------ NonNull Argument Attribute ------------------------ 1245 struct AANonNullImpl : AANonNull { 1246 AANonNullImpl(const IRPosition &IRP) : AANonNull(IRP) {} 1247 1248 /// See AbstractAttribute::initialize(...). 1249 void initialize(Attributor &A) override { 1250 if (hasAttr({Attribute::NonNull, Attribute::Dereferenceable})) 1251 indicateOptimisticFixpoint(); 1252 } 1253 1254 /// See AbstractAttribute::getAsStr(). 1255 const std::string getAsStr() const override { 1256 return getAssumed() ? "nonnull" : "may-null"; 1257 } 1258 }; 1259 1260 /// NonNull attribute for a floating value. 1261 struct AANonNullFloating : AANonNullImpl { 1262 AANonNullFloating(const IRPosition &IRP) : AANonNullImpl(IRP) {} 1263 1264 /// See AbstractAttribute::initialize(...). 1265 void initialize(Attributor &A) override { 1266 AANonNullImpl::initialize(A); 1267 1268 if (isAtFixpoint()) 1269 return; 1270 1271 const IRPosition &IRP = getIRPosition(); 1272 const Value &V = IRP.getAssociatedValue(); 1273 const DataLayout &DL = A.getDataLayout(); 1274 1275 // TODO: This context sensitive query should be removed once we can do 1276 // context sensitive queries in the genericValueTraversal below. 1277 if (isKnownNonZero(&V, DL, 0, /* TODO: AC */ nullptr, IRP.getCtxI(), 1278 /* TODO: DT */ nullptr)) 1279 indicateOptimisticFixpoint(); 1280 } 1281 1282 /// See AbstractAttribute::updateImpl(...). 1283 ChangeStatus updateImpl(Attributor &A) override { 1284 const DataLayout &DL = A.getDataLayout(); 1285 1286 auto VisitValueCB = [&](Value &V, AAAlign::StateType &T, 1287 bool Stripped) -> bool { 1288 const auto &AA = A.getAAFor<AANonNull>(*this, IRPosition::value(V)); 1289 if (!Stripped && this == &AA) { 1290 if (!isKnownNonZero(&V, DL, 0, /* TODO: AC */ nullptr, 1291 /* TODO: CtxI */ nullptr, 1292 /* TODO: DT */ nullptr)) 1293 T.indicatePessimisticFixpoint(); 1294 } else { 1295 // Use abstract attribute information. 1296 const AANonNull::StateType &NS = 1297 static_cast<const AANonNull::StateType &>(AA.getState()); 1298 T ^= NS; 1299 } 1300 return T.isValidState(); 1301 }; 1302 1303 StateType T; 1304 if (!genericValueTraversal<AANonNull, StateType>(A, getIRPosition(), *this, 1305 T, VisitValueCB)) 1306 return indicatePessimisticFixpoint(); 1307 1308 return clampStateAndIndicateChange(getState(), T); 1309 } 1310 1311 /// See AbstractAttribute::trackStatistics() 1312 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) } 1313 }; 1314 1315 /// NonNull attribute for function return value. 1316 struct AANonNullReturned final 1317 : AAReturnedFromReturnedValues<AANonNull, AANonNullImpl> { 1318 AANonNullReturned(const IRPosition &IRP) 1319 : AAReturnedFromReturnedValues<AANonNull, AANonNullImpl>(IRP) {} 1320 1321 /// See AbstractAttribute::trackStatistics() 1322 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(nonnull) } 1323 }; 1324 1325 /// NonNull attribute for function argument. 1326 struct AANonNullArgument final 1327 : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl> { 1328 AANonNullArgument(const IRPosition &IRP) 1329 : AAArgumentFromCallSiteArguments<AANonNull, AANonNullImpl>(IRP) {} 1330 1331 /// See AbstractAttribute::trackStatistics() 1332 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(nonnull) } 1333 }; 1334 1335 struct AANonNullCallSiteArgument final : AANonNullFloating { 1336 AANonNullCallSiteArgument(const IRPosition &IRP) : AANonNullFloating(IRP) {} 1337 1338 /// See AbstractAttribute::trackStatistics() 1339 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(nonnul) } 1340 }; 1341 1342 /// NonNull attribute for a call site return position. 1343 struct AANonNullCallSiteReturned final 1344 : AACallSiteReturnedFromReturned<AANonNull, AANonNullImpl> { 1345 AANonNullCallSiteReturned(const IRPosition &IRP) 1346 : AACallSiteReturnedFromReturned<AANonNull, AANonNullImpl>(IRP) {} 1347 1348 /// See AbstractAttribute::trackStatistics() 1349 void trackStatistics() const override { STATS_DECLTRACK_CSRET_ATTR(nonnull) } 1350 }; 1351 1352 /// ------------------------ No-Recurse Attributes ---------------------------- 1353 1354 struct AANoRecurseImpl : public AANoRecurse { 1355 AANoRecurseImpl(const IRPosition &IRP) : AANoRecurse(IRP) {} 1356 1357 /// See AbstractAttribute::initialize(...). 1358 void initialize(Attributor &A) override { 1359 if (hasAttr({getAttrKind()})) { 1360 indicateOptimisticFixpoint(); 1361 return; 1362 } 1363 } 1364 1365 /// See AbstractAttribute::getAsStr() 1366 const std::string getAsStr() const override { 1367 return getAssumed() ? "norecurse" : "may-recurse"; 1368 } 1369 }; 1370 1371 struct AANoRecurseFunction final : AANoRecurseImpl { 1372 AANoRecurseFunction(const IRPosition &IRP) : AANoRecurseImpl(IRP) {} 1373 1374 /// See AbstractAttribute::updateImpl(...). 1375 ChangeStatus updateImpl(Attributor &A) override { 1376 // TODO: Implement this. 1377 return indicatePessimisticFixpoint(); 1378 } 1379 1380 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(norecurse) } 1381 }; 1382 1383 using AANoRecurseCallSite = AANoRecurseFunction; 1384 1385 /// ------------------------ Will-Return Attributes ---------------------------- 1386 1387 // Helper function that checks whether a function has any cycle. 1388 // TODO: Replace with more efficent code 1389 static bool containsCycle(Function &F) { 1390 SmallPtrSet<BasicBlock *, 32> Visited; 1391 1392 // Traverse BB by dfs and check whether successor is already visited. 1393 for (BasicBlock *BB : depth_first(&F)) { 1394 Visited.insert(BB); 1395 for (auto *SuccBB : successors(BB)) { 1396 if (Visited.count(SuccBB)) 1397 return true; 1398 } 1399 } 1400 return false; 1401 } 1402 1403 // Helper function that checks the function have a loop which might become an 1404 // endless loop 1405 // FIXME: Any cycle is regarded as endless loop for now. 1406 // We have to allow some patterns. 1407 static bool containsPossiblyEndlessLoop(Function *F) { 1408 return !F || !F->hasExactDefinition() || containsCycle(*F); 1409 } 1410 1411 struct AAWillReturnImpl : public AAWillReturn { 1412 AAWillReturnImpl(const IRPosition &IRP) : AAWillReturn(IRP) {} 1413 1414 /// See AbstractAttribute::initialize(...). 1415 void initialize(Attributor &A) override { 1416 if (hasAttr({Attribute::WillReturn})) { 1417 indicateOptimisticFixpoint(); 1418 return; 1419 } 1420 1421 Function *F = getAssociatedFunction(); 1422 if (containsPossiblyEndlessLoop(F)) 1423 indicatePessimisticFixpoint(); 1424 } 1425 1426 /// See AbstractAttribute::updateImpl(...). 1427 ChangeStatus updateImpl(Attributor &A) override { 1428 auto CheckForWillReturn = [&](Instruction &I) { 1429 IRPosition IPos = IRPosition::callsite_function(ImmutableCallSite(&I)); 1430 const auto &WillReturnAA = A.getAAFor<AAWillReturn>(*this, IPos); 1431 if (WillReturnAA.isKnownWillReturn()) 1432 return true; 1433 if (!WillReturnAA.isAssumedWillReturn()) 1434 return false; 1435 const auto &NoRecurseAA = A.getAAFor<AANoRecurse>(*this, IPos); 1436 return NoRecurseAA.isAssumedNoRecurse(); 1437 }; 1438 1439 if (!A.checkForAllCallLikeInstructions(CheckForWillReturn, *this)) 1440 return indicatePessimisticFixpoint(); 1441 1442 return ChangeStatus::UNCHANGED; 1443 } 1444 1445 /// See AbstractAttribute::getAsStr() 1446 const std::string getAsStr() const override { 1447 return getAssumed() ? "willreturn" : "may-noreturn"; 1448 } 1449 }; 1450 1451 struct AAWillReturnFunction final : AAWillReturnImpl { 1452 AAWillReturnFunction(const IRPosition &IRP) : AAWillReturnImpl(IRP) {} 1453 1454 /// See AbstractAttribute::trackStatistics() 1455 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(willreturn) } 1456 }; 1457 1458 /// WillReturn attribute deduction for a call sites. 1459 using AAWillReturnCallSite = AAWillReturnFunction; 1460 1461 /// ------------------------ NoAlias Argument Attribute ------------------------ 1462 1463 struct AANoAliasImpl : AANoAlias { 1464 AANoAliasImpl(const IRPosition &IRP) : AANoAlias(IRP) {} 1465 1466 /// See AbstractAttribute::initialize(...). 1467 void initialize(Attributor &A) override { 1468 if (hasAttr({Attribute::NoAlias})) 1469 indicateOptimisticFixpoint(); 1470 } 1471 1472 const std::string getAsStr() const override { 1473 return getAssumed() ? "noalias" : "may-alias"; 1474 } 1475 }; 1476 1477 /// NoAlias attribute for a floating value. 1478 struct AANoAliasFloating final : AANoAliasImpl { 1479 AANoAliasFloating(const IRPosition &IRP) : AANoAliasImpl(IRP) {} 1480 1481 /// See AbstractAttribute::updateImpl(...). 1482 ChangeStatus updateImpl(Attributor &A) override { 1483 // TODO: Implement this. 1484 return indicatePessimisticFixpoint(); 1485 } 1486 1487 /// See AbstractAttribute::trackStatistics() 1488 void trackStatistics() const override { 1489 STATS_DECLTRACK_FLOATING_ATTR(noalias) 1490 } 1491 }; 1492 1493 /// NoAlias attribute for an argument. 1494 struct AANoAliasArgument final : AANoAliasImpl { 1495 AANoAliasArgument(const IRPosition &IRP) : AANoAliasImpl(IRP) {} 1496 1497 /// See AbstractAttribute::updateImpl(...). 1498 ChangeStatus updateImpl(Attributor &A) override { 1499 // TODO: Implement this. 1500 return indicatePessimisticFixpoint(); 1501 } 1502 1503 /// See AbstractAttribute::trackStatistics() 1504 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noalias) } 1505 }; 1506 1507 struct AANoAliasCallSiteArgument final : AANoAliasImpl { 1508 AANoAliasCallSiteArgument(const IRPosition &IRP) : AANoAliasImpl(IRP) {} 1509 1510 /// See AbstractAttribute::updateImpl(...). 1511 ChangeStatus updateImpl(Attributor &A) override { 1512 // TODO: Implement this. 1513 return indicatePessimisticFixpoint(); 1514 } 1515 1516 /// See AbstractAttribute::trackStatistics() 1517 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(noalias) } 1518 }; 1519 1520 /// NoAlias attribute for function return value. 1521 struct AANoAliasReturned final : AANoAliasImpl { 1522 AANoAliasReturned(const IRPosition &IRP) : AANoAliasImpl(IRP) {} 1523 1524 /// See AbstractAttribute::updateImpl(...). 1525 virtual ChangeStatus updateImpl(Attributor &A) override { 1526 1527 auto CheckReturnValue = [&](Value &RV) -> bool { 1528 if (Constant *C = dyn_cast<Constant>(&RV)) 1529 if (C->isNullValue() || isa<UndefValue>(C)) 1530 return true; 1531 1532 /// For now, we can only deduce noalias if we have call sites. 1533 /// FIXME: add more support. 1534 ImmutableCallSite ICS(&RV); 1535 if (!ICS) 1536 return false; 1537 1538 const auto &NoAliasAA = 1539 A.getAAFor<AANoAlias>(*this, IRPosition::callsite_returned(ICS)); 1540 if (!NoAliasAA.isAssumedNoAlias()) 1541 return false; 1542 1543 /// FIXME: We can improve capture check in two ways: 1544 /// 1. Use the AANoCapture facilities. 1545 /// 2. Use the location of return insts for escape queries. 1546 if (PointerMayBeCaptured(&RV, /* ReturnCaptures */ false, 1547 /* StoreCaptures */ true)) 1548 return false; 1549 1550 return true; 1551 }; 1552 1553 if (!A.checkForAllReturnedValues(CheckReturnValue, *this)) 1554 return indicatePessimisticFixpoint(); 1555 1556 return ChangeStatus::UNCHANGED; 1557 } 1558 1559 /// See AbstractAttribute::trackStatistics() 1560 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(noalias) } 1561 }; 1562 1563 /// NoAlias attribute deduction for a call site return value. 1564 using AANoAliasCallSiteReturned = AANoAliasReturned; 1565 1566 /// -------------------AAIsDead Function Attribute----------------------- 1567 1568 struct AAIsDeadImpl : public AAIsDead { 1569 AAIsDeadImpl(const IRPosition &IRP) : AAIsDead(IRP) {} 1570 1571 void initialize(Attributor &A) override { 1572 const Function *F = getAssociatedFunction(); 1573 1574 if (F->hasInternalLinkage()) 1575 return; 1576 1577 if (!F || !F->hasExactDefinition()) { 1578 indicatePessimisticFixpoint(); 1579 return; 1580 } 1581 1582 exploreFromEntry(A, F); 1583 } 1584 1585 void exploreFromEntry(Attributor &A, const Function *F) { 1586 ToBeExploredPaths.insert(&(F->getEntryBlock().front())); 1587 AssumedLiveBlocks.insert(&(F->getEntryBlock())); 1588 1589 for (size_t i = 0; i < ToBeExploredPaths.size(); ++i) 1590 if (const Instruction *NextNoReturnI = 1591 findNextNoReturn(A, ToBeExploredPaths[i])) 1592 NoReturnCalls.insert(NextNoReturnI); 1593 } 1594 1595 /// Find the next assumed noreturn instruction in the block of \p I starting 1596 /// from, thus including, \p I. 1597 /// 1598 /// The caller is responsible to monitor the ToBeExploredPaths set as new 1599 /// instructions discovered in other basic block will be placed in there. 1600 /// 1601 /// \returns The next assumed noreturn instructions in the block of \p I 1602 /// starting from, thus including, \p I. 1603 const Instruction *findNextNoReturn(Attributor &A, const Instruction *I); 1604 1605 /// See AbstractAttribute::getAsStr(). 1606 const std::string getAsStr() const override { 1607 return "Live[#BB " + std::to_string(AssumedLiveBlocks.size()) + "/" + 1608 std::to_string(getAssociatedFunction()->size()) + "][#NRI " + 1609 std::to_string(NoReturnCalls.size()) + "]"; 1610 } 1611 1612 /// See AbstractAttribute::manifest(...). 1613 ChangeStatus manifest(Attributor &A) override { 1614 assert(getState().isValidState() && 1615 "Attempted to manifest an invalid state!"); 1616 1617 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 1618 Function &F = *getAssociatedFunction(); 1619 1620 if (AssumedLiveBlocks.empty()) { 1621 F.replaceAllUsesWith(UndefValue::get(F.getType())); 1622 return ChangeStatus::CHANGED; 1623 } 1624 1625 // Flag to determine if we can change an invoke to a call assuming the 1626 // callee is nounwind. This is not possible if the personality of the 1627 // function allows to catch asynchronous exceptions. 1628 bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F); 1629 1630 for (const Instruction *NRC : NoReturnCalls) { 1631 Instruction *I = const_cast<Instruction *>(NRC); 1632 BasicBlock *BB = I->getParent(); 1633 Instruction *SplitPos = I->getNextNode(); 1634 // TODO: mark stuff before unreachable instructions as dead. 1635 if (isa_and_nonnull<UnreachableInst>(SplitPos)) 1636 continue; 1637 1638 if (auto *II = dyn_cast<InvokeInst>(I)) { 1639 // If we keep the invoke the split position is at the beginning of the 1640 // normal desitination block (it invokes a noreturn function after all). 1641 BasicBlock *NormalDestBB = II->getNormalDest(); 1642 SplitPos = &NormalDestBB->front(); 1643 1644 /// Invoke is replaced with a call and unreachable is placed after it if 1645 /// the callee is nounwind and noreturn. Otherwise, we keep the invoke 1646 /// and only place an unreachable in the normal successor. 1647 if (Invoke2CallAllowed) { 1648 if (II->getCalledFunction()) { 1649 const IRPosition &IPos = IRPosition::callsite_function(*II); 1650 const auto &AANoUnw = A.getAAFor<AANoUnwind>(*this, IPos); 1651 if (AANoUnw.isAssumedNoUnwind()) { 1652 LLVM_DEBUG(dbgs() 1653 << "[AAIsDead] Replace invoke with call inst\n"); 1654 // We do not need an invoke (II) but instead want a call followed 1655 // by an unreachable. However, we do not remove II as other 1656 // abstract attributes might have it cached as part of their 1657 // results. Given that we modify the CFG anyway, we simply keep II 1658 // around but in a new dead block. To avoid II being live through 1659 // a different edge we have to ensure the block we place it in is 1660 // only reached from the current block of II and then not reached 1661 // at all when we insert the unreachable. 1662 SplitBlockPredecessors(NormalDestBB, {BB}, ".i2c"); 1663 CallInst *CI = createCallMatchingInvoke(II); 1664 CI->insertBefore(II); 1665 CI->takeName(II); 1666 II->replaceAllUsesWith(CI); 1667 SplitPos = CI->getNextNode(); 1668 } 1669 } 1670 } 1671 } 1672 1673 BB = SplitPos->getParent(); 1674 SplitBlock(BB, SplitPos); 1675 changeToUnreachable(BB->getTerminator(), /* UseLLVMTrap */ false); 1676 HasChanged = ChangeStatus::CHANGED; 1677 } 1678 1679 return HasChanged; 1680 } 1681 1682 /// See AbstractAttribute::updateImpl(...). 1683 ChangeStatus updateImpl(Attributor &A) override; 1684 1685 /// See AAIsDead::isAssumedDead(BasicBlock *). 1686 bool isAssumedDead(const BasicBlock *BB) const override { 1687 assert(BB->getParent() == getAssociatedFunction() && 1688 "BB must be in the same anchor scope function."); 1689 1690 if (!getAssumed()) 1691 return false; 1692 return !AssumedLiveBlocks.count(BB); 1693 } 1694 1695 /// See AAIsDead::isKnownDead(BasicBlock *). 1696 bool isKnownDead(const BasicBlock *BB) const override { 1697 return getKnown() && isAssumedDead(BB); 1698 } 1699 1700 /// See AAIsDead::isAssumed(Instruction *I). 1701 bool isAssumedDead(const Instruction *I) const override { 1702 assert(I->getParent()->getParent() == getAssociatedFunction() && 1703 "Instruction must be in the same anchor scope function."); 1704 1705 if (!getAssumed()) 1706 return false; 1707 1708 // If it is not in AssumedLiveBlocks then it for sure dead. 1709 // Otherwise, it can still be after noreturn call in a live block. 1710 if (!AssumedLiveBlocks.count(I->getParent())) 1711 return true; 1712 1713 // If it is not after a noreturn call, than it is live. 1714 return isAfterNoReturn(I); 1715 } 1716 1717 /// See AAIsDead::isKnownDead(Instruction *I). 1718 bool isKnownDead(const Instruction *I) const override { 1719 return getKnown() && isAssumedDead(I); 1720 } 1721 1722 /// Check if instruction is after noreturn call, in other words, assumed dead. 1723 bool isAfterNoReturn(const Instruction *I) const; 1724 1725 /// Determine if \p F might catch asynchronous exceptions. 1726 static bool mayCatchAsynchronousExceptions(const Function &F) { 1727 return F.hasPersonalityFn() && !canSimplifyInvokeNoUnwind(&F); 1728 } 1729 1730 /// Collection of to be explored paths. 1731 SmallSetVector<const Instruction *, 8> ToBeExploredPaths; 1732 1733 /// Collection of all assumed live BasicBlocks. 1734 DenseSet<const BasicBlock *> AssumedLiveBlocks; 1735 1736 /// Collection of calls with noreturn attribute, assumed or knwon. 1737 SmallSetVector<const Instruction *, 4> NoReturnCalls; 1738 }; 1739 1740 struct AAIsDeadFunction final : public AAIsDeadImpl { 1741 AAIsDeadFunction(const IRPosition &IRP) : AAIsDeadImpl(IRP) {} 1742 1743 /// See AbstractAttribute::trackStatistics() 1744 void trackStatistics() const override { 1745 STATS_DECL(DeadInternalFunction, Function, 1746 "Number of internal functions classified as dead (no live callsite)"); 1747 BUILD_STAT_NAME(DeadInternalFunction, Function) += 1748 (getAssociatedFunction()->hasInternalLinkage() && 1749 AssumedLiveBlocks.empty()) 1750 ? 1 1751 : 0; 1752 STATS_DECL(DeadBlocks, Function, 1753 "Number of basic blocks classified as dead"); 1754 BUILD_STAT_NAME(DeadBlocks, Function) += 1755 getAssociatedFunction()->size() - AssumedLiveBlocks.size(); 1756 STATS_DECL(PartiallyDeadBlocks, Function, 1757 "Number of basic blocks classified as partially dead"); 1758 BUILD_STAT_NAME(PartiallyDeadBlocks, Function) += NoReturnCalls.size(); 1759 } 1760 }; 1761 1762 bool AAIsDeadImpl::isAfterNoReturn(const Instruction *I) const { 1763 const Instruction *PrevI = I->getPrevNode(); 1764 while (PrevI) { 1765 if (NoReturnCalls.count(PrevI)) 1766 return true; 1767 PrevI = PrevI->getPrevNode(); 1768 } 1769 return false; 1770 } 1771 1772 const Instruction *AAIsDeadImpl::findNextNoReturn(Attributor &A, 1773 const Instruction *I) { 1774 const BasicBlock *BB = I->getParent(); 1775 const Function &F = *BB->getParent(); 1776 1777 // Flag to determine if we can change an invoke to a call assuming the callee 1778 // is nounwind. This is not possible if the personality of the function allows 1779 // to catch asynchronous exceptions. 1780 bool Invoke2CallAllowed = !mayCatchAsynchronousExceptions(F); 1781 1782 // TODO: We should have a function that determines if an "edge" is dead. 1783 // Edges could be from an instruction to the next or from a terminator 1784 // to the successor. For now, we need to special case the unwind block 1785 // of InvokeInst below. 1786 1787 while (I) { 1788 ImmutableCallSite ICS(I); 1789 1790 if (ICS) { 1791 const IRPosition &IPos = IRPosition::callsite_function(ICS); 1792 // Regarless of the no-return property of an invoke instruction we only 1793 // learn that the regular successor is not reachable through this 1794 // instruction but the unwind block might still be. 1795 if (auto *Invoke = dyn_cast<InvokeInst>(I)) { 1796 // Use nounwind to justify the unwind block is dead as well. 1797 const auto &AANoUnw = A.getAAFor<AANoUnwind>(*this, IPos); 1798 if (!Invoke2CallAllowed || !AANoUnw.isAssumedNoUnwind()) { 1799 AssumedLiveBlocks.insert(Invoke->getUnwindDest()); 1800 ToBeExploredPaths.insert(&Invoke->getUnwindDest()->front()); 1801 } 1802 } 1803 1804 const auto &NoReturnAA = A.getAAFor<AANoReturn>(*this, IPos); 1805 if (NoReturnAA.isAssumedNoReturn()) 1806 return I; 1807 } 1808 1809 I = I->getNextNode(); 1810 } 1811 1812 // get new paths (reachable blocks). 1813 for (const BasicBlock *SuccBB : successors(BB)) { 1814 AssumedLiveBlocks.insert(SuccBB); 1815 ToBeExploredPaths.insert(&SuccBB->front()); 1816 } 1817 1818 // No noreturn instruction found. 1819 return nullptr; 1820 } 1821 1822 ChangeStatus AAIsDeadImpl::updateImpl(Attributor &A) { 1823 const Function *F = getAssociatedFunction(); 1824 ChangeStatus Status = ChangeStatus::UNCHANGED; 1825 1826 if (F->hasInternalLinkage() && AssumedLiveBlocks.empty()) { 1827 auto CallSiteCheck = [&](CallSite) { return false; }; 1828 1829 // All callsites of F are dead. 1830 if (A.checkForAllCallSites(CallSiteCheck, *this, true)) 1831 return ChangeStatus::UNCHANGED; 1832 1833 // There exists at least one live call site, so we explore the function. 1834 Status = ChangeStatus::CHANGED; 1835 1836 exploreFromEntry(A, F); 1837 } 1838 1839 // Temporary collection to iterate over existing noreturn instructions. This 1840 // will alow easier modification of NoReturnCalls collection 1841 SmallVector<const Instruction *, 8> NoReturnChanged; 1842 1843 for (const Instruction *I : NoReturnCalls) 1844 NoReturnChanged.push_back(I); 1845 1846 for (const Instruction *I : NoReturnChanged) { 1847 size_t Size = ToBeExploredPaths.size(); 1848 1849 const Instruction *NextNoReturnI = findNextNoReturn(A, I); 1850 if (NextNoReturnI != I) { 1851 Status = ChangeStatus::CHANGED; 1852 NoReturnCalls.remove(I); 1853 if (NextNoReturnI) 1854 NoReturnCalls.insert(NextNoReturnI); 1855 } 1856 1857 // Explore new paths. 1858 while (Size != ToBeExploredPaths.size()) { 1859 Status = ChangeStatus::CHANGED; 1860 if (const Instruction *NextNoReturnI = 1861 findNextNoReturn(A, ToBeExploredPaths[Size++])) 1862 NoReturnCalls.insert(NextNoReturnI); 1863 } 1864 } 1865 1866 LLVM_DEBUG(dbgs() << "[AAIsDead] AssumedLiveBlocks: " 1867 << AssumedLiveBlocks.size() << " Total number of blocks: " 1868 << getAssociatedFunction()->size() << "\n"); 1869 1870 // If we know everything is live there is no need to query for liveness. 1871 if (NoReturnCalls.empty() && 1872 getAssociatedFunction()->size() == AssumedLiveBlocks.size()) { 1873 // Indicating a pessimistic fixpoint will cause the state to be "invalid" 1874 // which will cause the Attributor to not return the AAIsDead on request, 1875 // which will prevent us from querying isAssumedDead(). 1876 indicatePessimisticFixpoint(); 1877 assert(!isValidState() && "Expected an invalid state!"); 1878 } 1879 1880 return Status; 1881 } 1882 1883 /// Liveness information for a call sites. 1884 // 1885 // TODO: Once we have call site specific value information we can provide call 1886 // site specific liveness liveness information and then it makes sense to 1887 // specialize attributes for call sites instead of redirecting requests to 1888 // the callee. 1889 using AAIsDeadCallSite = AAIsDeadFunction; 1890 1891 /// -------------------- Dereferenceable Argument Attribute -------------------- 1892 1893 struct DerefState : AbstractState { 1894 1895 /// State representing for dereferenceable bytes. 1896 IntegerState DerefBytesState; 1897 1898 /// State representing that whether the value is globaly dereferenceable. 1899 BooleanState GlobalState; 1900 1901 /// See AbstractState::isValidState() 1902 bool isValidState() const override { return DerefBytesState.isValidState(); } 1903 1904 /// See AbstractState::isAtFixpoint() 1905 bool isAtFixpoint() const override { 1906 return !isValidState() || 1907 (DerefBytesState.isAtFixpoint() && GlobalState.isAtFixpoint()); 1908 } 1909 1910 /// See AbstractState::indicateOptimisticFixpoint(...) 1911 ChangeStatus indicateOptimisticFixpoint() override { 1912 DerefBytesState.indicateOptimisticFixpoint(); 1913 GlobalState.indicateOptimisticFixpoint(); 1914 return ChangeStatus::UNCHANGED; 1915 } 1916 1917 /// See AbstractState::indicatePessimisticFixpoint(...) 1918 ChangeStatus indicatePessimisticFixpoint() override { 1919 DerefBytesState.indicatePessimisticFixpoint(); 1920 GlobalState.indicatePessimisticFixpoint(); 1921 return ChangeStatus::CHANGED; 1922 } 1923 1924 /// Update known dereferenceable bytes. 1925 void takeKnownDerefBytesMaximum(uint64_t Bytes) { 1926 DerefBytesState.takeKnownMaximum(Bytes); 1927 } 1928 1929 /// Update assumed dereferenceable bytes. 1930 void takeAssumedDerefBytesMinimum(uint64_t Bytes) { 1931 DerefBytesState.takeAssumedMinimum(Bytes); 1932 } 1933 1934 /// Equality for DerefState. 1935 bool operator==(const DerefState &R) { 1936 return this->DerefBytesState == R.DerefBytesState && 1937 this->GlobalState == R.GlobalState; 1938 } 1939 1940 /// Inequality for IntegerState. 1941 bool operator!=(const DerefState &R) { return !(*this == R); } 1942 1943 /// See IntegerState::operator^= 1944 DerefState operator^=(const DerefState &R) { 1945 DerefBytesState ^= R.DerefBytesState; 1946 GlobalState ^= R.GlobalState; 1947 return *this; 1948 } 1949 1950 /// See IntegerState::operator&= 1951 DerefState operator&=(const DerefState &R) { 1952 DerefBytesState &= R.DerefBytesState; 1953 GlobalState &= R.GlobalState; 1954 return *this; 1955 } 1956 1957 /// See IntegerState::operator|= 1958 DerefState operator|=(const DerefState &R) { 1959 DerefBytesState |= R.DerefBytesState; 1960 GlobalState |= R.GlobalState; 1961 return *this; 1962 } 1963 }; 1964 1965 template <> 1966 ChangeStatus clampStateAndIndicateChange<DerefState>(DerefState &S, 1967 const DerefState &R) { 1968 ChangeStatus CS0 = clampStateAndIndicateChange<IntegerState>( 1969 S.DerefBytesState, R.DerefBytesState); 1970 ChangeStatus CS1 = 1971 clampStateAndIndicateChange<IntegerState>(S.GlobalState, R.GlobalState); 1972 return CS0 | CS1; 1973 } 1974 1975 struct AADereferenceableImpl : AADereferenceable, DerefState { 1976 AADereferenceableImpl(const IRPosition &IRP) : AADereferenceable(IRP) {} 1977 using StateType = DerefState; 1978 1979 void initialize(Attributor &A) override { 1980 SmallVector<Attribute, 4> Attrs; 1981 getAttrs({Attribute::Dereferenceable, Attribute::DereferenceableOrNull}, 1982 Attrs); 1983 for (const Attribute &Attr : Attrs) 1984 takeKnownDerefBytesMaximum(Attr.getValueAsInt()); 1985 1986 NonNullAA = &A.getAAFor<AANonNull>(*this, getIRPosition()); 1987 } 1988 1989 /// See AbstractAttribute::getState() 1990 /// { 1991 StateType &getState() override { return *this; } 1992 const StateType &getState() const override { return *this; } 1993 /// } 1994 1995 /// See AADereferenceable::getAssumedDereferenceableBytes(). 1996 uint32_t getAssumedDereferenceableBytes() const override { 1997 return DerefBytesState.getAssumed(); 1998 } 1999 2000 /// See AADereferenceable::getKnownDereferenceableBytes(). 2001 uint32_t getKnownDereferenceableBytes() const override { 2002 return DerefBytesState.getKnown(); 2003 } 2004 2005 /// See AADereferenceable::isAssumedGlobal(). 2006 bool isAssumedGlobal() const override { return GlobalState.getAssumed(); } 2007 2008 /// See AADereferenceable::isKnownGlobal(). 2009 bool isKnownGlobal() const override { return GlobalState.getKnown(); } 2010 2011 bool isAssumedNonNull() const override { 2012 return NonNullAA && NonNullAA->isAssumedNonNull(); 2013 } 2014 2015 void getDeducedAttributes(LLVMContext &Ctx, 2016 SmallVectorImpl<Attribute> &Attrs) const override { 2017 // TODO: Add *_globally support 2018 if (isAssumedNonNull()) 2019 Attrs.emplace_back(Attribute::getWithDereferenceableBytes( 2020 Ctx, getAssumedDereferenceableBytes())); 2021 else 2022 Attrs.emplace_back(Attribute::getWithDereferenceableOrNullBytes( 2023 Ctx, getAssumedDereferenceableBytes())); 2024 } 2025 2026 /// See AbstractAttribute::getAsStr(). 2027 const std::string getAsStr() const override { 2028 if (!getAssumedDereferenceableBytes()) 2029 return "unknown-dereferenceable"; 2030 return std::string("dereferenceable") + 2031 (isAssumedNonNull() ? "" : "_or_null") + 2032 (isAssumedGlobal() ? "_globally" : "") + "<" + 2033 std::to_string(getKnownDereferenceableBytes()) + "-" + 2034 std::to_string(getAssumedDereferenceableBytes()) + ">"; 2035 } 2036 2037 private: 2038 const AANonNull *NonNullAA = nullptr; 2039 }; 2040 2041 /// Dereferenceable attribute for a floating value. 2042 struct AADereferenceableFloating : AADereferenceableImpl { 2043 AADereferenceableFloating(const IRPosition &IRP) 2044 : AADereferenceableImpl(IRP) {} 2045 2046 /// See AbstractAttribute::updateImpl(...). 2047 ChangeStatus updateImpl(Attributor &A) override { 2048 const DataLayout &DL = A.getDataLayout(); 2049 2050 auto VisitValueCB = [&](Value &V, DerefState &T, bool Stripped) -> bool { 2051 unsigned IdxWidth = 2052 DL.getIndexSizeInBits(V.getType()->getPointerAddressSpace()); 2053 APInt Offset(IdxWidth, 0); 2054 const Value *Base = 2055 V.stripAndAccumulateInBoundsConstantOffsets(DL, Offset); 2056 2057 const auto &AA = 2058 A.getAAFor<AADereferenceable>(*this, IRPosition::value(*Base)); 2059 int64_t DerefBytes = 0; 2060 if (!Stripped && this == &AA) { 2061 // Use IR information if we did not strip anything. 2062 // TODO: track globally. 2063 bool CanBeNull; 2064 DerefBytes = Base->getPointerDereferenceableBytes(DL, CanBeNull); 2065 T.GlobalState.indicatePessimisticFixpoint(); 2066 } else { 2067 const DerefState &DS = static_cast<const DerefState &>(AA.getState()); 2068 DerefBytes = DS.DerefBytesState.getAssumed(); 2069 T.GlobalState &= DS.GlobalState; 2070 } 2071 2072 T.takeAssumedDerefBytesMinimum( 2073 std::max(int64_t(0), DerefBytes - Offset.getSExtValue())); 2074 2075 if (!Stripped && this == &AA) { 2076 T.takeKnownDerefBytesMaximum( 2077 std::max(int64_t(0), DerefBytes - Offset.getSExtValue())); 2078 T.indicatePessimisticFixpoint(); 2079 } 2080 2081 return T.isValidState(); 2082 }; 2083 2084 DerefState T; 2085 if (!genericValueTraversal<AADereferenceable, DerefState>( 2086 A, getIRPosition(), *this, T, VisitValueCB)) 2087 return indicatePessimisticFixpoint(); 2088 2089 return clampStateAndIndicateChange(getState(), T); 2090 } 2091 2092 /// See AbstractAttribute::trackStatistics() 2093 void trackStatistics() const override { 2094 STATS_DECLTRACK_FLOATING_ATTR(dereferenceable) 2095 } 2096 }; 2097 2098 /// Dereferenceable attribute for a return value. 2099 struct AADereferenceableReturned final 2100 : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl, 2101 DerefState> { 2102 AADereferenceableReturned(const IRPosition &IRP) 2103 : AAReturnedFromReturnedValues<AADereferenceable, AADereferenceableImpl, 2104 DerefState>(IRP) {} 2105 2106 /// See AbstractAttribute::trackStatistics() 2107 void trackStatistics() const override { 2108 STATS_DECLTRACK_FNRET_ATTR(dereferenceable) 2109 } 2110 }; 2111 2112 /// Dereferenceable attribute for an argument 2113 struct AADereferenceableArgument final 2114 : AAArgumentFromCallSiteArguments<AADereferenceable, AADereferenceableImpl, 2115 DerefState> { 2116 AADereferenceableArgument(const IRPosition &IRP) 2117 : AAArgumentFromCallSiteArguments<AADereferenceable, 2118 AADereferenceableImpl, DerefState>( 2119 IRP) {} 2120 2121 /// See AbstractAttribute::trackStatistics() 2122 void trackStatistics() const override{ 2123 STATS_DECLTRACK_ARG_ATTR(dereferenceable) 2124 } 2125 }; 2126 2127 /// Dereferenceable attribute for a call site argument. 2128 struct AADereferenceableCallSiteArgument final : AADereferenceableFloating { 2129 AADereferenceableCallSiteArgument(const IRPosition &IRP) 2130 : AADereferenceableFloating(IRP) {} 2131 2132 /// See AbstractAttribute::trackStatistics() 2133 void trackStatistics() const override { 2134 STATS_DECLTRACK_CSARG_ATTR(dereferenceable) 2135 } 2136 }; 2137 2138 /// Dereferenceable attribute deduction for a call site return value. 2139 using AADereferenceableCallSiteReturned = AADereferenceableReturned; 2140 2141 // ------------------------ Align Argument Attribute ------------------------ 2142 2143 struct AAAlignImpl : AAAlign { 2144 AAAlignImpl(const IRPosition &IRP) : AAAlign(IRP) {} 2145 2146 // Max alignemnt value allowed in IR 2147 static const unsigned MAX_ALIGN = 1U << 29; 2148 2149 /// See AbstractAttribute::initialize(...). 2150 void initialize(Attributor &A) override { 2151 takeAssumedMinimum(MAX_ALIGN); 2152 2153 SmallVector<Attribute, 4> Attrs; 2154 getAttrs({Attribute::Alignment}, Attrs); 2155 for (const Attribute &Attr : Attrs) 2156 takeKnownMaximum(Attr.getValueAsInt()); 2157 } 2158 2159 /// See AbstractAttribute::getDeducedAttributes 2160 virtual void 2161 getDeducedAttributes(LLVMContext &Ctx, 2162 SmallVectorImpl<Attribute> &Attrs) const override { 2163 if (getAssumedAlign() > 1) 2164 Attrs.emplace_back(Attribute::getWithAlignment(Ctx, getAssumedAlign())); 2165 } 2166 2167 /// See AbstractAttribute::getAsStr(). 2168 const std::string getAsStr() const override { 2169 return getAssumedAlign() ? ("align<" + std::to_string(getKnownAlign()) + 2170 "-" + std::to_string(getAssumedAlign()) + ">") 2171 : "unknown-align"; 2172 } 2173 }; 2174 2175 /// Align attribute for a floating value. 2176 struct AAAlignFloating : AAAlignImpl { 2177 AAAlignFloating(const IRPosition &IRP) : AAAlignImpl(IRP) {} 2178 2179 /// See AbstractAttribute::updateImpl(...). 2180 ChangeStatus updateImpl(Attributor &A) override { 2181 const DataLayout &DL = A.getDataLayout(); 2182 2183 auto VisitValueCB = [&](Value &V, AAAlign::StateType &T, 2184 bool Stripped) -> bool { 2185 const auto &AA = A.getAAFor<AAAlign>(*this, IRPosition::value(V)); 2186 if (!Stripped && this == &AA) { 2187 // Use only IR information if we did not strip anything. 2188 T.takeKnownMaximum(V.getPointerAlignment(DL)); 2189 T.indicatePessimisticFixpoint(); 2190 } else { 2191 // Use abstract attribute information. 2192 const AAAlign::StateType &DS = 2193 static_cast<const AAAlign::StateType &>(AA.getState()); 2194 T ^= DS; 2195 } 2196 return T.isValidState(); 2197 }; 2198 2199 StateType T; 2200 if (!genericValueTraversal<AAAlign, StateType>(A, getIRPosition(), *this, T, 2201 VisitValueCB)) 2202 return indicatePessimisticFixpoint(); 2203 2204 // TODO: If we know we visited all incoming values, thus no are assumed 2205 // dead, we can take the known information from the state T. 2206 return clampStateAndIndicateChange(getState(), T); 2207 } 2208 2209 /// See AbstractAttribute::trackStatistics() 2210 void trackStatistics() const override { STATS_DECLTRACK_FLOATING_ATTR(align) } 2211 }; 2212 2213 /// Align attribute for function return value. 2214 struct AAAlignReturned final 2215 : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl> { 2216 AAAlignReturned(const IRPosition &IRP) 2217 : AAReturnedFromReturnedValues<AAAlign, AAAlignImpl>(IRP) {} 2218 2219 /// See AbstractAttribute::trackStatistics() 2220 void trackStatistics() const override { STATS_DECLTRACK_FNRET_ATTR(aligned) } 2221 }; 2222 2223 /// Align attribute for function argument. 2224 struct AAAlignArgument final 2225 : AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl> { 2226 AAAlignArgument(const IRPosition &IRP) 2227 : AAArgumentFromCallSiteArguments<AAAlign, AAAlignImpl>(IRP) {} 2228 2229 /// See AbstractAttribute::trackStatistics() 2230 void trackStatistics() const override { STATS_DECLTRACK_ARG_ATTR(aligned) } 2231 }; 2232 2233 struct AAAlignCallSiteArgument final : AAAlignFloating { 2234 AAAlignCallSiteArgument(const IRPosition &IRP) : AAAlignFloating(IRP) {} 2235 2236 /// See AbstractAttribute::trackStatistics() 2237 void trackStatistics() const override { STATS_DECLTRACK_CSARG_ATTR(aligned) } 2238 }; 2239 2240 /// Align attribute deduction for a call site return value. 2241 using AAAlignCallSiteReturned = AAAlignReturned; 2242 2243 /// ------------------ Function No-Return Attribute ---------------------------- 2244 struct AANoReturnImpl : public AANoReturn { 2245 AANoReturnImpl(const IRPosition &IRP) : AANoReturn(IRP) {} 2246 2247 /// See AbstractAttribute::getAsStr(). 2248 const std::string getAsStr() const override { 2249 return getAssumed() ? "noreturn" : "may-return"; 2250 } 2251 2252 /// See AbstractAttribute::initialize(...). 2253 void initialize(Attributor &A) override { 2254 if (hasAttr({getAttrKind()})) 2255 indicateOptimisticFixpoint(); 2256 } 2257 2258 /// See AbstractAttribute::updateImpl(Attributor &A). 2259 virtual ChangeStatus updateImpl(Attributor &A) override { 2260 auto CheckForNoReturn = [](Instruction &) { return false; }; 2261 if (!A.checkForAllInstructions(CheckForNoReturn, *this, 2262 {(unsigned)Instruction::Ret})) 2263 return indicatePessimisticFixpoint(); 2264 return ChangeStatus::UNCHANGED; 2265 } 2266 }; 2267 2268 struct AANoReturnFunction final : AANoReturnImpl { 2269 AANoReturnFunction(const IRPosition &IRP) : AANoReturnImpl(IRP) {} 2270 2271 /// See AbstractAttribute::trackStatistics() 2272 void trackStatistics() const override { STATS_DECLTRACK_FN_ATTR(noreturn) } 2273 }; 2274 2275 /// NoReturn attribute deduction for a call sites. 2276 using AANoReturnCallSite = AANoReturnFunction; 2277 2278 /// ---------------------------------------------------------------------------- 2279 /// Attributor 2280 /// ---------------------------------------------------------------------------- 2281 2282 bool Attributor::isAssumedDead(const AbstractAttribute &AA, 2283 const AAIsDead *LivenessAA) { 2284 const Instruction *CtxI = AA.getIRPosition().getCtxI(); 2285 if (!CtxI) 2286 return false; 2287 2288 if (!LivenessAA) 2289 LivenessAA = 2290 &getAAFor<AAIsDead>(AA, IRPosition::function(*CtxI->getFunction())); 2291 2292 // Don't check liveness for AAIsDead. 2293 if (&AA == LivenessAA) 2294 return false; 2295 2296 if (!LivenessAA->isAssumedDead(CtxI)) 2297 return false; 2298 2299 // TODO: Do not track dependences automatically but add it here as only a 2300 // "is-assumed-dead" result causes a dependence. 2301 return true; 2302 } 2303 2304 bool Attributor::checkForAllCallSites(const function_ref<bool(CallSite)> &Pred, 2305 const AbstractAttribute &QueryingAA, 2306 bool RequireAllCallSites) { 2307 // We can try to determine information from 2308 // the call sites. However, this is only possible all call sites are known, 2309 // hence the function has internal linkage. 2310 const IRPosition &IRP = QueryingAA.getIRPosition(); 2311 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 2312 if (!AssociatedFunction) 2313 return false; 2314 2315 if (RequireAllCallSites && !AssociatedFunction->hasInternalLinkage()) { 2316 LLVM_DEBUG( 2317 dbgs() 2318 << "[Attributor] Function " << AssociatedFunction->getName() 2319 << " has no internal linkage, hence not all call sites are known\n"); 2320 return false; 2321 } 2322 2323 for (const Use &U : AssociatedFunction->uses()) { 2324 Instruction *I = dyn_cast<Instruction>(U.getUser()); 2325 // TODO: Deal with abstract call sites here. 2326 if (!I) 2327 return false; 2328 2329 Function *Caller = I->getFunction(); 2330 2331 const auto &LivenessAA = 2332 getAAFor<AAIsDead>(QueryingAA, IRPosition::function(*Caller)); 2333 2334 // Skip dead calls. 2335 if (LivenessAA.isAssumedDead(I)) 2336 continue; 2337 2338 CallSite CS(U.getUser()); 2339 if (!CS || !CS.isCallee(&U) || !CS.getCaller()->hasExactDefinition()) { 2340 if (!RequireAllCallSites) 2341 continue; 2342 2343 LLVM_DEBUG(dbgs() << "[Attributor] User " << *U.getUser() 2344 << " is an invalid use of " 2345 << AssociatedFunction->getName() << "\n"); 2346 return false; 2347 } 2348 2349 if (Pred(CS)) 2350 continue; 2351 2352 LLVM_DEBUG(dbgs() << "[Attributor] Call site callback failed for " 2353 << *CS.getInstruction() << "\n"); 2354 return false; 2355 } 2356 2357 return true; 2358 } 2359 2360 bool Attributor::checkForAllReturnedValuesAndReturnInsts( 2361 const function_ref<bool(Value &, const SmallPtrSetImpl<ReturnInst *> &)> 2362 &Pred, 2363 const AbstractAttribute &QueryingAA) { 2364 2365 const IRPosition &IRP = QueryingAA.getIRPosition(); 2366 // Since we need to provide return instructions we have to have an exact 2367 // definition. 2368 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 2369 if (!AssociatedFunction || !AssociatedFunction->hasExactDefinition()) 2370 return false; 2371 2372 // If this is a call site query we use the call site specific return values 2373 // and liveness information. 2374 const IRPosition &QueryIRP = IRPosition::function_scope(IRP); 2375 const auto &AARetVal = getAAFor<AAReturnedValues>(QueryingAA, QueryIRP); 2376 if (!AARetVal.getState().isValidState()) 2377 return false; 2378 2379 return AARetVal.checkForAllReturnedValuesAndReturnInsts(Pred); 2380 } 2381 2382 bool Attributor::checkForAllReturnedValues( 2383 const function_ref<bool(Value &)> &Pred, 2384 const AbstractAttribute &QueryingAA) { 2385 2386 const IRPosition &IRP = QueryingAA.getIRPosition(); 2387 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 2388 if (!AssociatedFunction || !AssociatedFunction->hasExactDefinition()) 2389 return false; 2390 2391 const IRPosition &QueryIRP = IRPosition::function_scope(IRP); 2392 const auto &AARetVal = getAAFor<AAReturnedValues>(QueryingAA, QueryIRP); 2393 if (!AARetVal.getState().isValidState()) 2394 return false; 2395 2396 return AARetVal.checkForAllReturnedValuesAndReturnInsts( 2397 [&](Value &RV, const SmallPtrSetImpl<ReturnInst *> &) { 2398 return Pred(RV); 2399 }); 2400 } 2401 2402 bool Attributor::checkForAllInstructions( 2403 const llvm::function_ref<bool(Instruction &)> &Pred, 2404 const AbstractAttribute &QueryingAA, const ArrayRef<unsigned> &Opcodes) { 2405 2406 const IRPosition &IRP = QueryingAA.getIRPosition(); 2407 // Since we need to provide instructions we have to have an exact definition. 2408 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 2409 if (!AssociatedFunction || !AssociatedFunction->hasExactDefinition()) 2410 return false; 2411 2412 const IRPosition &QueryIRP = IRPosition::function_scope(IRP); 2413 const auto &LivenessAA = getAAFor<AAIsDead>(QueryingAA, QueryIRP); 2414 2415 auto &OpcodeInstMap = 2416 InfoCache.getOpcodeInstMapForFunction(*AssociatedFunction); 2417 for (unsigned Opcode : Opcodes) { 2418 for (Instruction *I : OpcodeInstMap[Opcode]) { 2419 // Skip dead instructions. 2420 if (LivenessAA.isAssumedDead(I)) 2421 continue; 2422 2423 if (!Pred(*I)) 2424 return false; 2425 } 2426 } 2427 2428 return true; 2429 } 2430 2431 bool Attributor::checkForAllReadWriteInstructions( 2432 const llvm::function_ref<bool(Instruction &)> &Pred, 2433 AbstractAttribute &QueryingAA) { 2434 2435 const Function *AssociatedFunction = 2436 QueryingAA.getIRPosition().getAssociatedFunction(); 2437 if (!AssociatedFunction) 2438 return false; 2439 2440 const auto &LivenessAA = 2441 getAAFor<AAIsDead>(QueryingAA, QueryingAA.getIRPosition()); 2442 2443 for (Instruction *I : 2444 InfoCache.getReadOrWriteInstsForFunction(*AssociatedFunction)) { 2445 // Skip dead instructions. 2446 if (LivenessAA.isAssumedDead(I)) 2447 continue; 2448 2449 if (!Pred(*I)) 2450 return false; 2451 } 2452 2453 return true; 2454 } 2455 2456 ChangeStatus Attributor::run() { 2457 // Initialize all abstract attributes, allow new ones to be created. 2458 for (unsigned u = 0; u < AllAbstractAttributes.size(); u++) 2459 AllAbstractAttributes[u]->initialize(*this); 2460 2461 LLVM_DEBUG(dbgs() << "[Attributor] Identified and initialized " 2462 << AllAbstractAttributes.size() 2463 << " abstract attributes.\n"); 2464 2465 // Now that all abstract attributes are collected and initialized we start 2466 // the abstract analysis. 2467 2468 unsigned IterationCounter = 1; 2469 2470 SmallVector<AbstractAttribute *, 64> ChangedAAs; 2471 SetVector<AbstractAttribute *> Worklist; 2472 Worklist.insert(AllAbstractAttributes.begin(), AllAbstractAttributes.end()); 2473 2474 do { 2475 // Remember the size to determine new attributes. 2476 size_t NumAAs = AllAbstractAttributes.size(); 2477 LLVM_DEBUG(dbgs() << "\n\n[Attributor] #Iteration: " << IterationCounter 2478 << ", Worklist size: " << Worklist.size() << "\n"); 2479 2480 // Add all abstract attributes that are potentially dependent on one that 2481 // changed to the work list. 2482 for (AbstractAttribute *ChangedAA : ChangedAAs) { 2483 auto &QuerriedAAs = QueryMap[ChangedAA]; 2484 Worklist.insert(QuerriedAAs.begin(), QuerriedAAs.end()); 2485 } 2486 2487 // Reset the changed set. 2488 ChangedAAs.clear(); 2489 2490 // Update all abstract attribute in the work list and record the ones that 2491 // changed. 2492 for (AbstractAttribute *AA : Worklist) 2493 if (!isAssumedDead(*AA, nullptr)) 2494 if (AA->update(*this) == ChangeStatus::CHANGED) 2495 ChangedAAs.push_back(AA); 2496 2497 // Reset the work list and repopulate with the changed abstract attributes. 2498 // Note that dependent ones are added above. 2499 Worklist.clear(); 2500 Worklist.insert(ChangedAAs.begin(), ChangedAAs.end()); 2501 2502 // Add attributes to the worklist that have been created in the last 2503 // iteration. 2504 Worklist.insert(AllAbstractAttributes.begin() + NumAAs, 2505 AllAbstractAttributes.end()); 2506 2507 } while (!Worklist.empty() && ++IterationCounter < MaxFixpointIterations); 2508 2509 size_t NumFinalAAs = AllAbstractAttributes.size(); 2510 2511 LLVM_DEBUG(dbgs() << "\n[Attributor] Fixpoint iteration done after: " 2512 << IterationCounter << "/" << MaxFixpointIterations 2513 << " iterations\n"); 2514 2515 bool FinishedAtFixpoint = Worklist.empty(); 2516 2517 // Reset abstract arguments not settled in a sound fixpoint by now. This 2518 // happens when we stopped the fixpoint iteration early. Note that only the 2519 // ones marked as "changed" *and* the ones transitively depending on them 2520 // need to be reverted to a pessimistic state. Others might not be in a 2521 // fixpoint state but we can use the optimistic results for them anyway. 2522 SmallPtrSet<AbstractAttribute *, 32> Visited; 2523 for (unsigned u = 0; u < ChangedAAs.size(); u++) { 2524 AbstractAttribute *ChangedAA = ChangedAAs[u]; 2525 if (!Visited.insert(ChangedAA).second) 2526 continue; 2527 2528 AbstractState &State = ChangedAA->getState(); 2529 if (!State.isAtFixpoint()) { 2530 State.indicatePessimisticFixpoint(); 2531 2532 NumAttributesTimedOut++; 2533 } 2534 2535 auto &QuerriedAAs = QueryMap[ChangedAA]; 2536 ChangedAAs.append(QuerriedAAs.begin(), QuerriedAAs.end()); 2537 } 2538 2539 LLVM_DEBUG({ 2540 if (!Visited.empty()) 2541 dbgs() << "\n[Attributor] Finalized " << Visited.size() 2542 << " abstract attributes.\n"; 2543 }); 2544 2545 unsigned NumManifested = 0; 2546 unsigned NumAtFixpoint = 0; 2547 ChangeStatus ManifestChange = ChangeStatus::UNCHANGED; 2548 for (AbstractAttribute *AA : AllAbstractAttributes) { 2549 AbstractState &State = AA->getState(); 2550 2551 // If there is not already a fixpoint reached, we can now take the 2552 // optimistic state. This is correct because we enforced a pessimistic one 2553 // on abstract attributes that were transitively dependent on a changed one 2554 // already above. 2555 if (!State.isAtFixpoint()) 2556 State.indicateOptimisticFixpoint(); 2557 2558 // If the state is invalid, we do not try to manifest it. 2559 if (!State.isValidState()) 2560 continue; 2561 2562 // Skip dead code. 2563 if (isAssumedDead(*AA, nullptr)) 2564 continue; 2565 // Manifest the state and record if we changed the IR. 2566 ChangeStatus LocalChange = AA->manifest(*this); 2567 if (LocalChange == ChangeStatus::CHANGED && AreStatisticsEnabled()) 2568 AA->trackStatistics(); 2569 2570 ManifestChange = ManifestChange | LocalChange; 2571 2572 NumAtFixpoint++; 2573 NumManifested += (LocalChange == ChangeStatus::CHANGED); 2574 } 2575 2576 (void)NumManifested; 2577 (void)NumAtFixpoint; 2578 LLVM_DEBUG(dbgs() << "\n[Attributor] Manifested " << NumManifested 2579 << " arguments while " << NumAtFixpoint 2580 << " were in a valid fixpoint state\n"); 2581 2582 // If verification is requested, we finished this run at a fixpoint, and the 2583 // IR was changed, we re-run the whole fixpoint analysis, starting at 2584 // re-initialization of the arguments. This re-run should not result in an IR 2585 // change. Though, the (virtual) state of attributes at the end of the re-run 2586 // might be more optimistic than the known state or the IR state if the better 2587 // state cannot be manifested. 2588 if (VerifyAttributor && FinishedAtFixpoint && 2589 ManifestChange == ChangeStatus::CHANGED) { 2590 VerifyAttributor = false; 2591 ChangeStatus VerifyStatus = run(); 2592 if (VerifyStatus != ChangeStatus::UNCHANGED) 2593 llvm_unreachable( 2594 "Attributor verification failed, re-run did result in an IR change " 2595 "even after a fixpoint was reached in the original run. (False " 2596 "positives possible!)"); 2597 VerifyAttributor = true; 2598 } 2599 2600 NumAttributesManifested += NumManifested; 2601 NumAttributesValidFixpoint += NumAtFixpoint; 2602 2603 (void)NumFinalAAs; 2604 assert( 2605 NumFinalAAs == AllAbstractAttributes.size() && 2606 "Expected the final number of abstract attributes to remain unchanged!"); 2607 return ManifestChange; 2608 } 2609 2610 /// Helper function that checks if an abstract attribute of type \p AAType 2611 /// should be created for IR position \p IRP and if so creates and registers it 2612 /// with the Attributor \p A. 2613 /// 2614 /// This method will look at the provided whitelist. If one is given and the 2615 /// kind \p AAType::ID is not contained, no abstract attribute is created. 2616 /// 2617 /// \returns The created abstract argument, or nullptr if none was created. 2618 template <typename AAType> 2619 static const AAType *checkAndRegisterAA(const IRPosition &IRP, Attributor &A, 2620 DenseSet<const char *> *Whitelist) { 2621 if (Whitelist && !Whitelist->count(&AAType::ID)) 2622 return nullptr; 2623 2624 return &A.registerAA<AAType>(*new AAType(IRP)); 2625 } 2626 2627 void Attributor::identifyDefaultAbstractAttributes( 2628 Function &F, DenseSet<const char *> *Whitelist) { 2629 2630 IRPosition FPos = IRPosition::function(F); 2631 2632 // Check for dead BasicBlocks in every function. 2633 // We need dead instruction detection because we do not want to deal with 2634 // broken IR in which SSA rules do not apply. 2635 checkAndRegisterAA<AAIsDeadFunction>(FPos, *this, /* Whitelist */ nullptr); 2636 2637 // Every function might be "will-return". 2638 checkAndRegisterAA<AAWillReturnFunction>(FPos, *this, Whitelist); 2639 2640 // Every function can be nounwind. 2641 checkAndRegisterAA<AANoUnwindFunction>(FPos, *this, Whitelist); 2642 2643 // Every function might be marked "nosync" 2644 checkAndRegisterAA<AANoSyncFunction>(FPos, *this, Whitelist); 2645 2646 // Every function might be "no-free". 2647 checkAndRegisterAA<AANoFreeFunction>(FPos, *this, Whitelist); 2648 2649 // Every function might be "no-return". 2650 checkAndRegisterAA<AANoReturnFunction>(FPos, *this, Whitelist); 2651 2652 // Return attributes are only appropriate if the return type is non void. 2653 Type *ReturnType = F.getReturnType(); 2654 if (!ReturnType->isVoidTy()) { 2655 // Argument attribute "returned" --- Create only one per function even 2656 // though it is an argument attribute. 2657 checkAndRegisterAA<AAReturnedValuesFunction>(FPos, *this, Whitelist); 2658 2659 if (ReturnType->isPointerTy()) { 2660 IRPosition RetPos = IRPosition::returned(F); 2661 2662 // Every function with pointer return type might be marked align. 2663 checkAndRegisterAA<AAAlignReturned>(RetPos, *this, Whitelist); 2664 2665 // Every function with pointer return type might be marked nonnull. 2666 checkAndRegisterAA<AANonNullReturned>(RetPos, *this, Whitelist); 2667 2668 // Every function with pointer return type might be marked noalias. 2669 checkAndRegisterAA<AANoAliasReturned>(RetPos, *this, Whitelist); 2670 2671 // Every function with pointer return type might be marked 2672 // dereferenceable. 2673 checkAndRegisterAA<AADereferenceableReturned>(RetPos, *this, Whitelist); 2674 } 2675 } 2676 2677 for (Argument &Arg : F.args()) { 2678 if (Arg.getType()->isPointerTy()) { 2679 IRPosition ArgPos = IRPosition::argument(Arg); 2680 // Every argument with pointer type might be marked nonnull. 2681 checkAndRegisterAA<AANonNullArgument>(ArgPos, *this, Whitelist); 2682 2683 // Every argument with pointer type might be marked dereferenceable. 2684 checkAndRegisterAA<AADereferenceableArgument>(ArgPos, *this, Whitelist); 2685 2686 // Every argument with pointer type might be marked align. 2687 checkAndRegisterAA<AAAlignArgument>(ArgPos, *this, Whitelist); 2688 } 2689 } 2690 2691 // Walk all instructions to find more attribute opportunities and also 2692 // interesting instructions that might be queried by abstract attributes 2693 // during their initialization or update. 2694 auto &ReadOrWriteInsts = InfoCache.FuncRWInstsMap[&F]; 2695 auto &InstOpcodeMap = InfoCache.FuncInstOpcodeMap[&F]; 2696 2697 for (Instruction &I : instructions(&F)) { 2698 bool IsInterestingOpcode = false; 2699 2700 // To allow easy access to all instructions in a function with a given 2701 // opcode we store them in the InfoCache. As not all opcodes are interesting 2702 // to concrete attributes we only cache the ones that are as identified in 2703 // the following switch. 2704 // Note: There are no concrete attributes now so this is initially empty. 2705 switch (I.getOpcode()) { 2706 default: 2707 assert((!ImmutableCallSite(&I)) && (!isa<CallBase>(&I)) && 2708 "New call site/base instruction type needs to be known int the " 2709 "attributor."); 2710 break; 2711 case Instruction::Call: 2712 case Instruction::CallBr: 2713 case Instruction::Invoke: 2714 case Instruction::CleanupRet: 2715 case Instruction::CatchSwitch: 2716 case Instruction::Resume: 2717 case Instruction::Ret: 2718 IsInterestingOpcode = true; 2719 } 2720 if (IsInterestingOpcode) 2721 InstOpcodeMap[I.getOpcode()].push_back(&I); 2722 if (I.mayReadOrWriteMemory()) 2723 ReadOrWriteInsts.push_back(&I); 2724 2725 CallSite CS(&I); 2726 if (CS && CS.getCalledFunction()) { 2727 for (int i = 0, e = CS.getCalledFunction()->arg_size(); i < e; i++) { 2728 if (!CS.getArgument(i)->getType()->isPointerTy()) 2729 continue; 2730 IRPosition CSArgPos = IRPosition::callsite_argument(CS, i); 2731 2732 // Call site argument attribute "non-null". 2733 checkAndRegisterAA<AANonNullCallSiteArgument>(CSArgPos, *this, 2734 Whitelist); 2735 2736 // Call site argument attribute "dereferenceable". 2737 checkAndRegisterAA<AADereferenceableCallSiteArgument>(CSArgPos, *this, 2738 Whitelist); 2739 2740 // Call site argument attribute "align". 2741 checkAndRegisterAA<AAAlignCallSiteArgument>(CSArgPos, *this, Whitelist); 2742 } 2743 } 2744 } 2745 } 2746 2747 /// Helpers to ease debugging through output streams and print calls. 2748 /// 2749 ///{ 2750 raw_ostream &llvm::operator<<(raw_ostream &OS, ChangeStatus S) { 2751 return OS << (S == ChangeStatus::CHANGED ? "changed" : "unchanged"); 2752 } 2753 2754 raw_ostream &llvm::operator<<(raw_ostream &OS, IRPosition::Kind AP) { 2755 switch (AP) { 2756 case IRPosition::IRP_INVALID: 2757 return OS << "inv"; 2758 case IRPosition::IRP_FLOAT: 2759 return OS << "flt"; 2760 case IRPosition::IRP_RETURNED: 2761 return OS << "fn_ret"; 2762 case IRPosition::IRP_CALL_SITE_RETURNED: 2763 return OS << "cs_ret"; 2764 case IRPosition::IRP_FUNCTION: 2765 return OS << "fn"; 2766 case IRPosition::IRP_CALL_SITE: 2767 return OS << "cs"; 2768 case IRPosition::IRP_ARGUMENT: 2769 return OS << "arg"; 2770 case IRPosition::IRP_CALL_SITE_ARGUMENT: 2771 return OS << "cs_arg"; 2772 } 2773 llvm_unreachable("Unknown attribute position!"); 2774 } 2775 2776 raw_ostream &llvm::operator<<(raw_ostream &OS, const IRPosition &Pos) { 2777 const Value &AV = Pos.getAssociatedValue(); 2778 return OS << "{" << Pos.getPositionKind() << ":" << AV.getName() << " [" 2779 << Pos.getAnchorValue().getName() << "@" << Pos.getArgNo() << "]}"; 2780 } 2781 2782 raw_ostream &llvm::operator<<(raw_ostream &OS, const IntegerState &S) { 2783 return OS << "(" << S.getKnown() << "-" << S.getAssumed() << ")" 2784 << static_cast<const AbstractState &>(S); 2785 } 2786 2787 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractState &S) { 2788 return OS << (!S.isValidState() ? "top" : (S.isAtFixpoint() ? "fix" : "")); 2789 } 2790 2791 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractAttribute &AA) { 2792 AA.print(OS); 2793 return OS; 2794 } 2795 2796 void AbstractAttribute::print(raw_ostream &OS) const { 2797 OS << "[P: " << getIRPosition() << "][" << getAsStr() << "][S: " << getState() 2798 << "]"; 2799 } 2800 ///} 2801 2802 /// ---------------------------------------------------------------------------- 2803 /// Pass (Manager) Boilerplate 2804 /// ---------------------------------------------------------------------------- 2805 2806 static bool runAttributorOnModule(Module &M) { 2807 if (DisableAttributor) 2808 return false; 2809 2810 LLVM_DEBUG(dbgs() << "[Attributor] Run on module with " << M.size() 2811 << " functions.\n"); 2812 2813 // Create an Attributor and initially empty information cache that is filled 2814 // while we identify default attribute opportunities. 2815 InformationCache InfoCache(M.getDataLayout()); 2816 Attributor A(InfoCache); 2817 2818 for (Function &F : M) { 2819 // TODO: Not all attributes require an exact definition. Find a way to 2820 // enable deduction for some but not all attributes in case the 2821 // definition might be changed at runtime, see also 2822 // http://lists.llvm.org/pipermail/llvm-dev/2018-February/121275.html. 2823 // TODO: We could always determine abstract attributes and if sufficient 2824 // information was found we could duplicate the functions that do not 2825 // have an exact definition. 2826 if (!F.hasExactDefinition()) { 2827 NumFnWithoutExactDefinition++; 2828 continue; 2829 } 2830 2831 // For now we ignore naked and optnone functions. 2832 if (F.hasFnAttribute(Attribute::Naked) || 2833 F.hasFnAttribute(Attribute::OptimizeNone)) 2834 continue; 2835 2836 NumFnWithExactDefinition++; 2837 2838 // Populate the Attributor with abstract attribute opportunities in the 2839 // function and the information cache with IR information. 2840 A.identifyDefaultAbstractAttributes(F); 2841 } 2842 2843 return A.run() == ChangeStatus::CHANGED; 2844 } 2845 2846 PreservedAnalyses AttributorPass::run(Module &M, ModuleAnalysisManager &AM) { 2847 if (runAttributorOnModule(M)) { 2848 // FIXME: Think about passes we will preserve and add them here. 2849 return PreservedAnalyses::none(); 2850 } 2851 return PreservedAnalyses::all(); 2852 } 2853 2854 namespace { 2855 2856 struct AttributorLegacyPass : public ModulePass { 2857 static char ID; 2858 2859 AttributorLegacyPass() : ModulePass(ID) { 2860 initializeAttributorLegacyPassPass(*PassRegistry::getPassRegistry()); 2861 } 2862 2863 bool runOnModule(Module &M) override { 2864 if (skipModule(M)) 2865 return false; 2866 return runAttributorOnModule(M); 2867 } 2868 2869 void getAnalysisUsage(AnalysisUsage &AU) const override { 2870 // FIXME: Think about passes we will preserve and add them here. 2871 AU.setPreservesCFG(); 2872 } 2873 }; 2874 2875 } // end anonymous namespace 2876 2877 Pass *llvm::createAttributorLegacyPass() { return new AttributorLegacyPass(); } 2878 2879 char AttributorLegacyPass::ID = 0; 2880 2881 const char AAReturnedValues::ID = 0; 2882 const char AANoUnwind::ID = 0; 2883 const char AANoSync::ID = 0; 2884 const char AANoFree::ID = 0; 2885 const char AANonNull::ID = 0; 2886 const char AANoRecurse::ID = 0; 2887 const char AAWillReturn::ID = 0; 2888 const char AANoAlias::ID = 0; 2889 const char AANoReturn::ID = 0; 2890 const char AAIsDead::ID = 0; 2891 const char AADereferenceable::ID = 0; 2892 const char AAAlign::ID = 0; 2893 2894 // Macro magic to create the static generator function for attributes that 2895 // follow the naming scheme. 2896 2897 #define SWITCH_PK_INV(CLASS, PK, POS_NAME) \ 2898 case IRPosition::PK: \ 2899 llvm_unreachable("Cannot create " #CLASS " for a " POS_NAME " position!"); 2900 2901 #define SWITCH_PK_CREATE(CLASS, IRP, PK, SUFFIX) \ 2902 case IRPosition::PK: \ 2903 AA = new CLASS##SUFFIX(IRP); \ 2904 break; 2905 2906 #define CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 2907 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 2908 CLASS *AA = nullptr; \ 2909 switch (IRP.getPositionKind()) { \ 2910 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 2911 SWITCH_PK_INV(CLASS, IRP_FLOAT, "floating") \ 2912 SWITCH_PK_INV(CLASS, IRP_ARGUMENT, "argument") \ 2913 SWITCH_PK_INV(CLASS, IRP_RETURNED, "returned") \ 2914 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_RETURNED, "call site returned") \ 2915 SWITCH_PK_INV(CLASS, IRP_CALL_SITE_ARGUMENT, "call site argument") \ 2916 SWITCH_PK_CREATE(CLASS, IRP, IRP_FUNCTION, Function) \ 2917 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE, CallSite) \ 2918 } \ 2919 AA->initialize(A); \ 2920 return *AA; \ 2921 } 2922 2923 #define CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(CLASS) \ 2924 CLASS &CLASS::createForPosition(const IRPosition &IRP, Attributor &A) { \ 2925 CLASS *AA = nullptr; \ 2926 switch (IRP.getPositionKind()) { \ 2927 SWITCH_PK_INV(CLASS, IRP_INVALID, "invalid") \ 2928 SWITCH_PK_INV(CLASS, IRP_FUNCTION, "function") \ 2929 SWITCH_PK_INV(CLASS, IRP_CALL_SITE, "call site") \ 2930 SWITCH_PK_CREATE(CLASS, IRP, IRP_FLOAT, Floating) \ 2931 SWITCH_PK_CREATE(CLASS, IRP, IRP_ARGUMENT, Argument) \ 2932 SWITCH_PK_CREATE(CLASS, IRP, IRP_RETURNED, Returned) \ 2933 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_RETURNED, CallSiteReturned) \ 2934 SWITCH_PK_CREATE(CLASS, IRP, IRP_CALL_SITE_ARGUMENT, CallSiteArgument) \ 2935 } \ 2936 AA->initialize(A); \ 2937 return *AA; \ 2938 } 2939 2940 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoUnwind) 2941 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoSync) 2942 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoFree) 2943 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoRecurse) 2944 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAWillReturn) 2945 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoReturn) 2946 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAIsDead) 2947 CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAReturnedValues) 2948 2949 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANonNull) 2950 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AANoAlias) 2951 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AADereferenceable) 2952 CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION(AAAlign) 2953 2954 #undef CREATE_FUNCTION_ABSTRACT_ATTRIBUTE_FOR_POSITION 2955 #undef CREATE_VALUE_ABSTRACT_ATTRIBUTE_FOR_POSITION 2956 #undef SWITCH_PK_CREATE 2957 #undef SWITCH_PK_INV 2958 2959 INITIALIZE_PASS_BEGIN(AttributorLegacyPass, "attributor", 2960 "Deduce and propagate attributes", false, false) 2961 INITIALIZE_PASS_END(AttributorLegacyPass, "attributor", 2962 "Deduce and propagate attributes", false, false) 2963