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 interprocedural pass that deduces and/or propagates 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/Statistic.h" 19 #include "llvm/Analysis/LazyValueInfo.h" 20 #include "llvm/Analysis/MustExecute.h" 21 #include "llvm/Analysis/ValueTracking.h" 22 #include "llvm/IR/IRBuilder.h" 23 #include "llvm/IR/NoFolder.h" 24 #include "llvm/IR/Verifier.h" 25 #include "llvm/InitializePasses.h" 26 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 27 #include "llvm/Transforms/Utils/Local.h" 28 29 #include <cassert> 30 31 using namespace llvm; 32 33 #define DEBUG_TYPE "attributor" 34 35 STATISTIC(NumFnDeleted, "Number of function deleted"); 36 STATISTIC(NumFnWithExactDefinition, 37 "Number of functions with exact definitions"); 38 STATISTIC(NumFnWithoutExactDefinition, 39 "Number of functions without exact definitions"); 40 STATISTIC(NumFnShallowWrapperCreated, "Number of shallow wrappers created"); 41 STATISTIC(NumAttributesTimedOut, 42 "Number of abstract attributes timed out before fixpoint"); 43 STATISTIC(NumAttributesValidFixpoint, 44 "Number of abstract attributes in a valid fixpoint state"); 45 STATISTIC(NumAttributesManifested, 46 "Number of abstract attributes manifested in IR"); 47 STATISTIC(NumAttributesFixedDueToRequiredDependences, 48 "Number of abstract attributes fixed due to required dependences"); 49 50 // TODO: Determine a good default value. 51 // 52 // In the LLVM-TS and SPEC2006, 32 seems to not induce compile time overheads 53 // (when run with the first 5 abstract attributes). The results also indicate 54 // that we never reach 32 iterations but always find a fixpoint sooner. 55 // 56 // This will become more evolved once we perform two interleaved fixpoint 57 // iterations: bottom-up and top-down. 58 static cl::opt<unsigned> 59 MaxFixpointIterations("attributor-max-iterations", cl::Hidden, 60 cl::desc("Maximal number of fixpoint iterations."), 61 cl::init(32)); 62 static cl::opt<bool> VerifyMaxFixpointIterations( 63 "attributor-max-iterations-verify", cl::Hidden, 64 cl::desc("Verify that max-iterations is a tight bound for a fixpoint"), 65 cl::init(false)); 66 67 static cl::opt<bool> AnnotateDeclarationCallSites( 68 "attributor-annotate-decl-cs", cl::Hidden, 69 cl::desc("Annotate call sites of function declarations."), cl::init(false)); 70 71 static cl::opt<bool> EnableHeapToStack("enable-heap-to-stack-conversion", 72 cl::init(true), cl::Hidden); 73 74 static cl::opt<bool> 75 AllowShallowWrappers("attributor-allow-shallow-wrappers", cl::Hidden, 76 cl::desc("Allow the Attributor to create shallow " 77 "wrappers for non-exact definitions."), 78 cl::init(false)); 79 80 /// Logic operators for the change status enum class. 81 /// 82 ///{ 83 ChangeStatus llvm::operator|(ChangeStatus l, ChangeStatus r) { 84 return l == ChangeStatus::CHANGED ? l : r; 85 } 86 ChangeStatus llvm::operator&(ChangeStatus l, ChangeStatus r) { 87 return l == ChangeStatus::UNCHANGED ? l : r; 88 } 89 ///} 90 91 /// Return true if \p New is equal or worse than \p Old. 92 static bool isEqualOrWorse(const Attribute &New, const Attribute &Old) { 93 if (!Old.isIntAttribute()) 94 return true; 95 96 return Old.getValueAsInt() >= New.getValueAsInt(); 97 } 98 99 /// Return true if the information provided by \p Attr was added to the 100 /// attribute list \p Attrs. This is only the case if it was not already present 101 /// in \p Attrs at the position describe by \p PK and \p AttrIdx. 102 static bool addIfNotExistent(LLVMContext &Ctx, const Attribute &Attr, 103 AttributeList &Attrs, int AttrIdx) { 104 105 if (Attr.isEnumAttribute()) { 106 Attribute::AttrKind Kind = Attr.getKindAsEnum(); 107 if (Attrs.hasAttribute(AttrIdx, Kind)) 108 if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) 109 return false; 110 Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); 111 return true; 112 } 113 if (Attr.isStringAttribute()) { 114 StringRef Kind = Attr.getKindAsString(); 115 if (Attrs.hasAttribute(AttrIdx, Kind)) 116 if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) 117 return false; 118 Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); 119 return true; 120 } 121 if (Attr.isIntAttribute()) { 122 Attribute::AttrKind Kind = Attr.getKindAsEnum(); 123 if (Attrs.hasAttribute(AttrIdx, Kind)) 124 if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) 125 return false; 126 Attrs = Attrs.removeAttribute(Ctx, AttrIdx, Kind); 127 Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); 128 return true; 129 } 130 131 llvm_unreachable("Expected enum or string attribute!"); 132 } 133 134 Argument *IRPosition::getAssociatedArgument() const { 135 if (getPositionKind() == IRP_ARGUMENT) 136 return cast<Argument>(&getAnchorValue()); 137 138 // Not an Argument and no argument number means this is not a call site 139 // argument, thus we cannot find a callback argument to return. 140 int ArgNo = getArgNo(); 141 if (ArgNo < 0) 142 return nullptr; 143 144 // Use abstract call sites to make the connection between the call site 145 // values and the ones in callbacks. If a callback was found that makes use 146 // of the underlying call site operand, we want the corresponding callback 147 // callee argument and not the direct callee argument. 148 Optional<Argument *> CBCandidateArg; 149 SmallVector<const Use *, 4> CallbackUses; 150 const auto &CB = cast<CallBase>(getAnchorValue()); 151 AbstractCallSite::getCallbackUses(CB, CallbackUses); 152 for (const Use *U : CallbackUses) { 153 AbstractCallSite ACS(U); 154 assert(ACS && ACS.isCallbackCall()); 155 if (!ACS.getCalledFunction()) 156 continue; 157 158 for (unsigned u = 0, e = ACS.getNumArgOperands(); u < e; u++) { 159 160 // Test if the underlying call site operand is argument number u of the 161 // callback callee. 162 if (ACS.getCallArgOperandNo(u) != ArgNo) 163 continue; 164 165 assert(ACS.getCalledFunction()->arg_size() > u && 166 "ACS mapped into var-args arguments!"); 167 if (CBCandidateArg.hasValue()) { 168 CBCandidateArg = nullptr; 169 break; 170 } 171 CBCandidateArg = ACS.getCalledFunction()->getArg(u); 172 } 173 } 174 175 // If we found a unique callback candidate argument, return it. 176 if (CBCandidateArg.hasValue() && CBCandidateArg.getValue()) 177 return CBCandidateArg.getValue(); 178 179 // If no callbacks were found, or none used the underlying call site operand 180 // exclusively, use the direct callee argument if available. 181 const Function *Callee = CB.getCalledFunction(); 182 if (Callee && Callee->arg_size() > unsigned(ArgNo)) 183 return Callee->getArg(ArgNo); 184 185 return nullptr; 186 } 187 188 ChangeStatus AbstractAttribute::update(Attributor &A) { 189 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 190 if (getState().isAtFixpoint()) 191 return HasChanged; 192 193 LLVM_DEBUG(dbgs() << "[Attributor] Update: " << *this << "\n"); 194 195 HasChanged = updateImpl(A); 196 197 LLVM_DEBUG(dbgs() << "[Attributor] Update " << HasChanged << " " << *this 198 << "\n"); 199 200 return HasChanged; 201 } 202 203 ChangeStatus 204 IRAttributeManifest::manifestAttrs(Attributor &A, const IRPosition &IRP, 205 const ArrayRef<Attribute> &DeducedAttrs) { 206 Function *ScopeFn = IRP.getAnchorScope(); 207 IRPosition::Kind PK = IRP.getPositionKind(); 208 209 // In the following some generic code that will manifest attributes in 210 // DeducedAttrs if they improve the current IR. Due to the different 211 // annotation positions we use the underlying AttributeList interface. 212 213 AttributeList Attrs; 214 switch (PK) { 215 case IRPosition::IRP_INVALID: 216 case IRPosition::IRP_FLOAT: 217 return ChangeStatus::UNCHANGED; 218 case IRPosition::IRP_ARGUMENT: 219 case IRPosition::IRP_FUNCTION: 220 case IRPosition::IRP_RETURNED: 221 Attrs = ScopeFn->getAttributes(); 222 break; 223 case IRPosition::IRP_CALL_SITE: 224 case IRPosition::IRP_CALL_SITE_RETURNED: 225 case IRPosition::IRP_CALL_SITE_ARGUMENT: 226 Attrs = cast<CallBase>(IRP.getAnchorValue()).getAttributes(); 227 break; 228 } 229 230 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 231 LLVMContext &Ctx = IRP.getAnchorValue().getContext(); 232 for (const Attribute &Attr : DeducedAttrs) { 233 if (!addIfNotExistent(Ctx, Attr, Attrs, IRP.getAttrIdx())) 234 continue; 235 236 HasChanged = ChangeStatus::CHANGED; 237 } 238 239 if (HasChanged == ChangeStatus::UNCHANGED) 240 return HasChanged; 241 242 switch (PK) { 243 case IRPosition::IRP_ARGUMENT: 244 case IRPosition::IRP_FUNCTION: 245 case IRPosition::IRP_RETURNED: 246 ScopeFn->setAttributes(Attrs); 247 break; 248 case IRPosition::IRP_CALL_SITE: 249 case IRPosition::IRP_CALL_SITE_RETURNED: 250 case IRPosition::IRP_CALL_SITE_ARGUMENT: 251 cast<CallBase>(IRP.getAnchorValue()).setAttributes(Attrs); 252 break; 253 case IRPosition::IRP_INVALID: 254 case IRPosition::IRP_FLOAT: 255 break; 256 } 257 258 return HasChanged; 259 } 260 261 const IRPosition IRPosition::EmptyKey(DenseMapInfo<void *>::getEmptyKey()); 262 const IRPosition 263 IRPosition::TombstoneKey(DenseMapInfo<void *>::getTombstoneKey()); 264 265 SubsumingPositionIterator::SubsumingPositionIterator(const IRPosition &IRP) { 266 IRPositions.emplace_back(IRP); 267 268 const auto *CB = dyn_cast<CallBase>(&IRP.getAnchorValue()); 269 switch (IRP.getPositionKind()) { 270 case IRPosition::IRP_INVALID: 271 case IRPosition::IRP_FLOAT: 272 case IRPosition::IRP_FUNCTION: 273 return; 274 case IRPosition::IRP_ARGUMENT: 275 case IRPosition::IRP_RETURNED: 276 IRPositions.emplace_back(IRPosition::function(*IRP.getAnchorScope())); 277 return; 278 case IRPosition::IRP_CALL_SITE: 279 assert(CB && "Expected call site!"); 280 // TODO: We need to look at the operand bundles similar to the redirection 281 // in CallBase. 282 if (!CB->hasOperandBundles()) 283 if (const Function *Callee = CB->getCalledFunction()) 284 IRPositions.emplace_back(IRPosition::function(*Callee)); 285 return; 286 case IRPosition::IRP_CALL_SITE_RETURNED: 287 assert(CB && "Expected call site!"); 288 // TODO: We need to look at the operand bundles similar to the redirection 289 // in CallBase. 290 if (!CB->hasOperandBundles()) { 291 if (const Function *Callee = CB->getCalledFunction()) { 292 IRPositions.emplace_back(IRPosition::returned(*Callee)); 293 IRPositions.emplace_back(IRPosition::function(*Callee)); 294 for (const Argument &Arg : Callee->args()) 295 if (Arg.hasReturnedAttr()) { 296 IRPositions.emplace_back( 297 IRPosition::callsite_argument(*CB, Arg.getArgNo())); 298 IRPositions.emplace_back( 299 IRPosition::value(*CB->getArgOperand(Arg.getArgNo()))); 300 IRPositions.emplace_back(IRPosition::argument(Arg)); 301 } 302 } 303 } 304 IRPositions.emplace_back(IRPosition::callsite_function(*CB)); 305 return; 306 case IRPosition::IRP_CALL_SITE_ARGUMENT: { 307 int ArgNo = IRP.getArgNo(); 308 assert(CB && ArgNo >= 0 && "Expected call site!"); 309 // TODO: We need to look at the operand bundles similar to the redirection 310 // in CallBase. 311 if (!CB->hasOperandBundles()) { 312 const Function *Callee = CB->getCalledFunction(); 313 if (Callee && Callee->arg_size() > unsigned(ArgNo)) 314 IRPositions.emplace_back(IRPosition::argument(*Callee->getArg(ArgNo))); 315 if (Callee) 316 IRPositions.emplace_back(IRPosition::function(*Callee)); 317 } 318 IRPositions.emplace_back(IRPosition::value(IRP.getAssociatedValue())); 319 return; 320 } 321 } 322 } 323 324 bool IRPosition::hasAttr(ArrayRef<Attribute::AttrKind> AKs, 325 bool IgnoreSubsumingPositions, Attributor *A) const { 326 SmallVector<Attribute, 4> Attrs; 327 for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) { 328 for (Attribute::AttrKind AK : AKs) 329 if (EquivIRP.getAttrsFromIRAttr(AK, Attrs)) 330 return true; 331 // The first position returned by the SubsumingPositionIterator is 332 // always the position itself. If we ignore subsuming positions we 333 // are done after the first iteration. 334 if (IgnoreSubsumingPositions) 335 break; 336 } 337 if (A) 338 for (Attribute::AttrKind AK : AKs) 339 if (getAttrsFromAssumes(AK, Attrs, *A)) 340 return true; 341 return false; 342 } 343 344 void IRPosition::getAttrs(ArrayRef<Attribute::AttrKind> AKs, 345 SmallVectorImpl<Attribute> &Attrs, 346 bool IgnoreSubsumingPositions, Attributor *A) const { 347 for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) { 348 for (Attribute::AttrKind AK : AKs) 349 EquivIRP.getAttrsFromIRAttr(AK, Attrs); 350 // The first position returned by the SubsumingPositionIterator is 351 // always the position itself. If we ignore subsuming positions we 352 // are done after the first iteration. 353 if (IgnoreSubsumingPositions) 354 break; 355 } 356 if (A) 357 for (Attribute::AttrKind AK : AKs) 358 getAttrsFromAssumes(AK, Attrs, *A); 359 } 360 361 bool IRPosition::getAttrsFromIRAttr(Attribute::AttrKind AK, 362 SmallVectorImpl<Attribute> &Attrs) const { 363 if (getPositionKind() == IRP_INVALID || getPositionKind() == IRP_FLOAT) 364 return false; 365 366 AttributeList AttrList; 367 if (const auto *CB = dyn_cast<CallBase>(&getAnchorValue())) 368 AttrList = CB->getAttributes(); 369 else 370 AttrList = getAssociatedFunction()->getAttributes(); 371 372 bool HasAttr = AttrList.hasAttribute(getAttrIdx(), AK); 373 if (HasAttr) 374 Attrs.push_back(AttrList.getAttribute(getAttrIdx(), AK)); 375 return HasAttr; 376 } 377 378 bool IRPosition::getAttrsFromAssumes(Attribute::AttrKind AK, 379 SmallVectorImpl<Attribute> &Attrs, 380 Attributor &A) const { 381 assert(getPositionKind() != IRP_INVALID && "Did expect a valid position!"); 382 Value &AssociatedValue = getAssociatedValue(); 383 384 const Assume2KnowledgeMap &A2K = 385 A.getInfoCache().getKnowledgeMap().lookup({&AssociatedValue, AK}); 386 387 // Check if we found any potential assume use, if not we don't need to create 388 // explorer iterators. 389 if (A2K.empty()) 390 return false; 391 392 LLVMContext &Ctx = AssociatedValue.getContext(); 393 unsigned AttrsSize = Attrs.size(); 394 MustBeExecutedContextExplorer &Explorer = 395 A.getInfoCache().getMustBeExecutedContextExplorer(); 396 auto EIt = Explorer.begin(getCtxI()), EEnd = Explorer.end(getCtxI()); 397 for (auto &It : A2K) 398 if (Explorer.findInContextOf(It.first, EIt, EEnd)) 399 Attrs.push_back(Attribute::get(Ctx, AK, It.second.Max)); 400 return AttrsSize != Attrs.size(); 401 } 402 403 void IRPosition::verify() { 404 #ifdef EXPENSIVE_CHECKS 405 switch (getPositionKind()) { 406 case IRP_INVALID: 407 assert(!Enc.getOpaqueValue() && 408 "Expected a nullptr for an invalid position!"); 409 return; 410 case IRP_FLOAT: 411 assert((!isa<CallBase>(&getAssociatedValue()) && 412 !isa<Argument>(&getAssociatedValue())) && 413 "Expected specialized kind for call base and argument values!"); 414 return; 415 case IRP_RETURNED: 416 assert(isa<Function>(getAsValuePtr()) && 417 "Expected function for a 'returned' position!"); 418 assert(getAsValuePtr() == &getAssociatedValue() && 419 "Associated value mismatch!"); 420 return; 421 case IRP_CALL_SITE_RETURNED: 422 assert((isa<CallBase>(getAsValuePtr())) && 423 "Expected call base for 'call site returned' position!"); 424 assert(getAsValuePtr() == &getAssociatedValue() && 425 "Associated value mismatch!"); 426 return; 427 case IRP_CALL_SITE: 428 assert((isa<CallBase>(getAsValuePtr())) && 429 "Expected call base for 'call site function' position!"); 430 assert(getAsValuePtr() == &getAssociatedValue() && 431 "Associated value mismatch!"); 432 return; 433 case IRP_FUNCTION: 434 assert(isa<Function>(getAsValuePtr()) && 435 "Expected function for a 'function' position!"); 436 assert(getAsValuePtr() == &getAssociatedValue() && 437 "Associated value mismatch!"); 438 return; 439 case IRP_ARGUMENT: 440 assert(isa<Argument>(getAsValuePtr()) && 441 "Expected argument for a 'argument' position!"); 442 assert(getAsValuePtr() == &getAssociatedValue() && 443 "Associated value mismatch!"); 444 return; 445 case IRP_CALL_SITE_ARGUMENT: { 446 Use *U = getAsUsePtr(); 447 assert(U && "Expected use for a 'call site argument' position!"); 448 assert(isa<CallBase>(U->getUser()) && 449 "Expected call base user for a 'call site argument' position!"); 450 assert(cast<CallBase>(U->getUser())->isArgOperand(U) && 451 "Expected call base argument operand for a 'call site argument' " 452 "position"); 453 assert(cast<CallBase>(U->getUser())->getArgOperandNo(U) == 454 unsigned(getArgNo()) && 455 "Argument number mismatch!"); 456 assert(U->get() == &getAssociatedValue() && "Associated value mismatch!"); 457 return; 458 } 459 } 460 #endif 461 } 462 463 Optional<Constant *> 464 Attributor::getAssumedConstant(const Value &V, const AbstractAttribute &AA, 465 bool &UsedAssumedInformation) { 466 const auto &ValueSimplifyAA = getAAFor<AAValueSimplify>( 467 AA, IRPosition::value(V), /* TrackDependence */ false); 468 Optional<Value *> SimplifiedV = 469 ValueSimplifyAA.getAssumedSimplifiedValue(*this); 470 bool IsKnown = ValueSimplifyAA.isKnown(); 471 UsedAssumedInformation |= !IsKnown; 472 if (!SimplifiedV.hasValue()) { 473 recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL); 474 return llvm::None; 475 } 476 if (isa_and_nonnull<UndefValue>(SimplifiedV.getValue())) { 477 recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL); 478 return llvm::None; 479 } 480 Constant *CI = dyn_cast_or_null<Constant>(SimplifiedV.getValue()); 481 if (CI && CI->getType() != V.getType()) { 482 // TODO: Check for a save conversion. 483 return nullptr; 484 } 485 if (CI) 486 recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL); 487 return CI; 488 } 489 490 Attributor::~Attributor() { 491 // The abstract attributes are allocated via the BumpPtrAllocator Allocator, 492 // thus we cannot delete them. We can, and want to, destruct them though. 493 for (AbstractAttribute *AA : AllAbstractAttributes) 494 AA->~AbstractAttribute(); 495 496 // The QueryMapValueTy objects are allocated via a BumpPtrAllocator, we call 497 // the destructor manually. 498 for (auto &It : QueryMap) 499 It.getSecond()->~QueryMapValueTy(); 500 } 501 502 bool Attributor::isAssumedDead(const AbstractAttribute &AA, 503 const AAIsDead *FnLivenessAA, 504 bool CheckBBLivenessOnly, DepClassTy DepClass) { 505 const IRPosition &IRP = AA.getIRPosition(); 506 if (!Functions.count(IRP.getAnchorScope())) 507 return false; 508 return isAssumedDead(IRP, &AA, FnLivenessAA, CheckBBLivenessOnly, DepClass); 509 } 510 511 bool Attributor::isAssumedDead(const Use &U, 512 const AbstractAttribute *QueryingAA, 513 const AAIsDead *FnLivenessAA, 514 bool CheckBBLivenessOnly, DepClassTy DepClass) { 515 Instruction *UserI = dyn_cast<Instruction>(U.getUser()); 516 if (!UserI) 517 return isAssumedDead(IRPosition::value(*U.get()), QueryingAA, FnLivenessAA, 518 CheckBBLivenessOnly, DepClass); 519 520 if (auto *CB = dyn_cast<CallBase>(UserI)) { 521 // For call site argument uses we can check if the argument is 522 // unused/dead. 523 if (CB->isArgOperand(&U)) { 524 const IRPosition &CSArgPos = 525 IRPosition::callsite_argument(*CB, CB->getArgOperandNo(&U)); 526 return isAssumedDead(CSArgPos, QueryingAA, FnLivenessAA, 527 CheckBBLivenessOnly, DepClass); 528 } 529 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(UserI)) { 530 const IRPosition &RetPos = IRPosition::returned(*RI->getFunction()); 531 return isAssumedDead(RetPos, QueryingAA, FnLivenessAA, CheckBBLivenessOnly, 532 DepClass); 533 } else if (PHINode *PHI = dyn_cast<PHINode>(UserI)) { 534 BasicBlock *IncomingBB = PHI->getIncomingBlock(U); 535 return isAssumedDead(*IncomingBB->getTerminator(), QueryingAA, FnLivenessAA, 536 CheckBBLivenessOnly, DepClass); 537 } 538 539 return isAssumedDead(IRPosition::value(*UserI), QueryingAA, FnLivenessAA, 540 CheckBBLivenessOnly, DepClass); 541 } 542 543 bool Attributor::isAssumedDead(const Instruction &I, 544 const AbstractAttribute *QueryingAA, 545 const AAIsDead *FnLivenessAA, 546 bool CheckBBLivenessOnly, DepClassTy DepClass) { 547 if (!FnLivenessAA) 548 FnLivenessAA = lookupAAFor<AAIsDead>(IRPosition::function(*I.getFunction()), 549 QueryingAA, 550 /* TrackDependence */ false); 551 552 // If we have a context instruction and a liveness AA we use it. 553 if (FnLivenessAA && 554 FnLivenessAA->getIRPosition().getAnchorScope() == I.getFunction() && 555 FnLivenessAA->isAssumedDead(&I)) { 556 if (QueryingAA) 557 recordDependence(*FnLivenessAA, *QueryingAA, DepClass); 558 return true; 559 } 560 561 if (CheckBBLivenessOnly) 562 return false; 563 564 const AAIsDead &IsDeadAA = getOrCreateAAFor<AAIsDead>( 565 IRPosition::value(I), QueryingAA, /* TrackDependence */ false); 566 // Don't check liveness for AAIsDead. 567 if (QueryingAA == &IsDeadAA) 568 return false; 569 570 if (IsDeadAA.isAssumedDead()) { 571 if (QueryingAA) 572 recordDependence(IsDeadAA, *QueryingAA, DepClass); 573 return true; 574 } 575 576 return false; 577 } 578 579 bool Attributor::isAssumedDead(const IRPosition &IRP, 580 const AbstractAttribute *QueryingAA, 581 const AAIsDead *FnLivenessAA, 582 bool CheckBBLivenessOnly, DepClassTy DepClass) { 583 Instruction *CtxI = IRP.getCtxI(); 584 if (CtxI && 585 isAssumedDead(*CtxI, QueryingAA, FnLivenessAA, 586 /* CheckBBLivenessOnly */ true, 587 CheckBBLivenessOnly ? DepClass : DepClassTy::OPTIONAL)) 588 return true; 589 590 if (CheckBBLivenessOnly) 591 return false; 592 593 // If we haven't succeeded we query the specific liveness info for the IRP. 594 const AAIsDead *IsDeadAA; 595 if (IRP.getPositionKind() == IRPosition::IRP_CALL_SITE) 596 IsDeadAA = &getOrCreateAAFor<AAIsDead>( 597 IRPosition::callsite_returned(cast<CallBase>(IRP.getAssociatedValue())), 598 QueryingAA, /* TrackDependence */ false); 599 else 600 IsDeadAA = &getOrCreateAAFor<AAIsDead>(IRP, QueryingAA, 601 /* TrackDependence */ false); 602 // Don't check liveness for AAIsDead. 603 if (QueryingAA == IsDeadAA) 604 return false; 605 606 if (IsDeadAA->isAssumedDead()) { 607 if (QueryingAA) 608 recordDependence(*IsDeadAA, *QueryingAA, DepClass); 609 return true; 610 } 611 612 return false; 613 } 614 615 bool Attributor::checkForAllUses(function_ref<bool(const Use &, bool &)> Pred, 616 const AbstractAttribute &QueryingAA, 617 const Value &V, DepClassTy LivenessDepClass) { 618 619 // Check the trivial case first as it catches void values. 620 if (V.use_empty()) 621 return true; 622 623 // If the value is replaced by another one, for now a constant, we do not have 624 // uses. Note that this requires users of `checkForAllUses` to not recurse but 625 // instead use the `follow` callback argument to look at transitive users, 626 // however, that should be clear from the presence of the argument. 627 bool UsedAssumedInformation = false; 628 Optional<Constant *> C = 629 getAssumedConstant(V, QueryingAA, UsedAssumedInformation); 630 if (C.hasValue() && C.getValue()) { 631 LLVM_DEBUG(dbgs() << "[Attributor] Value is simplified, uses skipped: " << V 632 << " -> " << *C.getValue() << "\n"); 633 return true; 634 } 635 636 const IRPosition &IRP = QueryingAA.getIRPosition(); 637 SmallVector<const Use *, 16> Worklist; 638 SmallPtrSet<const Use *, 16> Visited; 639 640 for (const Use &U : V.uses()) 641 Worklist.push_back(&U); 642 643 LLVM_DEBUG(dbgs() << "[Attributor] Got " << Worklist.size() 644 << " initial uses to check\n"); 645 646 const Function *ScopeFn = IRP.getAnchorScope(); 647 const auto *LivenessAA = 648 ScopeFn ? &getAAFor<AAIsDead>(QueryingAA, IRPosition::function(*ScopeFn), 649 /* TrackDependence */ false) 650 : nullptr; 651 652 while (!Worklist.empty()) { 653 const Use *U = Worklist.pop_back_val(); 654 if (!Visited.insert(U).second) 655 continue; 656 LLVM_DEBUG(dbgs() << "[Attributor] Check use: " << **U << " in " 657 << *U->getUser() << "\n"); 658 if (isAssumedDead(*U, &QueryingAA, LivenessAA, 659 /* CheckBBLivenessOnly */ false, LivenessDepClass)) { 660 LLVM_DEBUG(dbgs() << "[Attributor] Dead use, skip!\n"); 661 continue; 662 } 663 if (U->getUser()->isDroppable()) { 664 LLVM_DEBUG(dbgs() << "[Attributor] Droppable user, skip!\n"); 665 continue; 666 } 667 668 bool Follow = false; 669 if (!Pred(*U, Follow)) 670 return false; 671 if (!Follow) 672 continue; 673 for (const Use &UU : U->getUser()->uses()) 674 Worklist.push_back(&UU); 675 } 676 677 return true; 678 } 679 680 bool Attributor::checkForAllCallSites(function_ref<bool(AbstractCallSite)> Pred, 681 const AbstractAttribute &QueryingAA, 682 bool RequireAllCallSites, 683 bool &AllCallSitesKnown) { 684 // We can try to determine information from 685 // the call sites. However, this is only possible all call sites are known, 686 // hence the function has internal linkage. 687 const IRPosition &IRP = QueryingAA.getIRPosition(); 688 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 689 if (!AssociatedFunction) { 690 LLVM_DEBUG(dbgs() << "[Attributor] No function associated with " << IRP 691 << "\n"); 692 AllCallSitesKnown = false; 693 return false; 694 } 695 696 return checkForAllCallSites(Pred, *AssociatedFunction, RequireAllCallSites, 697 &QueryingAA, AllCallSitesKnown); 698 } 699 700 bool Attributor::checkForAllCallSites(function_ref<bool(AbstractCallSite)> Pred, 701 const Function &Fn, 702 bool RequireAllCallSites, 703 const AbstractAttribute *QueryingAA, 704 bool &AllCallSitesKnown) { 705 if (RequireAllCallSites && !Fn.hasLocalLinkage()) { 706 LLVM_DEBUG( 707 dbgs() 708 << "[Attributor] Function " << Fn.getName() 709 << " has no internal linkage, hence not all call sites are known\n"); 710 AllCallSitesKnown = false; 711 return false; 712 } 713 714 // If we do not require all call sites we might not see all. 715 AllCallSitesKnown = RequireAllCallSites; 716 717 SmallVector<const Use *, 8> Uses(make_pointer_range(Fn.uses())); 718 for (unsigned u = 0; u < Uses.size(); ++u) { 719 const Use &U = *Uses[u]; 720 LLVM_DEBUG(dbgs() << "[Attributor] Check use: " << *U << " in " 721 << *U.getUser() << "\n"); 722 if (isAssumedDead(U, QueryingAA, nullptr, /* CheckBBLivenessOnly */ true)) { 723 LLVM_DEBUG(dbgs() << "[Attributor] Dead use, skip!\n"); 724 continue; 725 } 726 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U.getUser())) { 727 if (CE->isCast() && CE->getType()->isPointerTy() && 728 CE->getType()->getPointerElementType()->isFunctionTy()) { 729 for (const Use &CEU : CE->uses()) 730 Uses.push_back(&CEU); 731 continue; 732 } 733 } 734 735 AbstractCallSite ACS(&U); 736 if (!ACS) { 737 LLVM_DEBUG(dbgs() << "[Attributor] Function " << Fn.getName() 738 << " has non call site use " << *U.get() << " in " 739 << *U.getUser() << "\n"); 740 // BlockAddress users are allowed. 741 if (isa<BlockAddress>(U.getUser())) 742 continue; 743 return false; 744 } 745 746 const Use *EffectiveUse = 747 ACS.isCallbackCall() ? &ACS.getCalleeUseForCallback() : &U; 748 if (!ACS.isCallee(EffectiveUse)) { 749 if (!RequireAllCallSites) 750 continue; 751 LLVM_DEBUG(dbgs() << "[Attributor] User " << EffectiveUse->getUser() 752 << " is an invalid use of " << Fn.getName() << "\n"); 753 return false; 754 } 755 756 // Make sure the arguments that can be matched between the call site and the 757 // callee argee on their type. It is unlikely they do not and it doesn't 758 // make sense for all attributes to know/care about this. 759 assert(&Fn == ACS.getCalledFunction() && "Expected known callee"); 760 unsigned MinArgsParams = 761 std::min(size_t(ACS.getNumArgOperands()), Fn.arg_size()); 762 for (unsigned u = 0; u < MinArgsParams; ++u) { 763 Value *CSArgOp = ACS.getCallArgOperand(u); 764 if (CSArgOp && Fn.getArg(u)->getType() != CSArgOp->getType()) { 765 LLVM_DEBUG( 766 dbgs() << "[Attributor] Call site / callee argument type mismatch [" 767 << u << "@" << Fn.getName() << ": " 768 << *Fn.getArg(u)->getType() << " vs. " 769 << *ACS.getCallArgOperand(u)->getType() << "\n"); 770 return false; 771 } 772 } 773 774 if (Pred(ACS)) 775 continue; 776 777 LLVM_DEBUG(dbgs() << "[Attributor] Call site callback failed for " 778 << *ACS.getInstruction() << "\n"); 779 return false; 780 } 781 782 return true; 783 } 784 785 bool Attributor::checkForAllReturnedValuesAndReturnInsts( 786 function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred, 787 const AbstractAttribute &QueryingAA) { 788 789 const IRPosition &IRP = QueryingAA.getIRPosition(); 790 // Since we need to provide return instructions we have to have an exact 791 // definition. 792 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 793 if (!AssociatedFunction) 794 return false; 795 796 // If this is a call site query we use the call site specific return values 797 // and liveness information. 798 // TODO: use the function scope once we have call site AAReturnedValues. 799 const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction); 800 const auto &AARetVal = getAAFor<AAReturnedValues>(QueryingAA, QueryIRP); 801 if (!AARetVal.getState().isValidState()) 802 return false; 803 804 return AARetVal.checkForAllReturnedValuesAndReturnInsts(Pred); 805 } 806 807 bool Attributor::checkForAllReturnedValues( 808 function_ref<bool(Value &)> Pred, const AbstractAttribute &QueryingAA) { 809 810 const IRPosition &IRP = QueryingAA.getIRPosition(); 811 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 812 if (!AssociatedFunction) 813 return false; 814 815 // TODO: use the function scope once we have call site AAReturnedValues. 816 const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction); 817 const auto &AARetVal = getAAFor<AAReturnedValues>(QueryingAA, QueryIRP); 818 if (!AARetVal.getState().isValidState()) 819 return false; 820 821 return AARetVal.checkForAllReturnedValuesAndReturnInsts( 822 [&](Value &RV, const SmallSetVector<ReturnInst *, 4> &) { 823 return Pred(RV); 824 }); 825 } 826 827 static bool checkForAllInstructionsImpl( 828 Attributor *A, InformationCache::OpcodeInstMapTy &OpcodeInstMap, 829 function_ref<bool(Instruction &)> Pred, const AbstractAttribute *QueryingAA, 830 const AAIsDead *LivenessAA, const ArrayRef<unsigned> &Opcodes, 831 bool CheckBBLivenessOnly = false) { 832 for (unsigned Opcode : Opcodes) { 833 // Check if we have instructions with this opcode at all first. 834 auto *Insts = OpcodeInstMap.lookup(Opcode); 835 if (!Insts) 836 continue; 837 838 for (Instruction *I : *Insts) { 839 // Skip dead instructions. 840 if (A && A->isAssumedDead(IRPosition::value(*I), QueryingAA, LivenessAA, 841 CheckBBLivenessOnly)) 842 continue; 843 844 if (!Pred(*I)) 845 return false; 846 } 847 } 848 return true; 849 } 850 851 bool Attributor::checkForAllInstructions(function_ref<bool(Instruction &)> Pred, 852 const AbstractAttribute &QueryingAA, 853 const ArrayRef<unsigned> &Opcodes, 854 bool CheckBBLivenessOnly) { 855 856 const IRPosition &IRP = QueryingAA.getIRPosition(); 857 // Since we need to provide instructions we have to have an exact definition. 858 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 859 if (!AssociatedFunction) 860 return false; 861 862 // TODO: use the function scope once we have call site AAReturnedValues. 863 const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction); 864 const auto &LivenessAA = 865 getAAFor<AAIsDead>(QueryingAA, QueryIRP, /* TrackDependence */ false); 866 867 auto &OpcodeInstMap = 868 InfoCache.getOpcodeInstMapForFunction(*AssociatedFunction); 869 if (!checkForAllInstructionsImpl(this, OpcodeInstMap, Pred, &QueryingAA, 870 &LivenessAA, Opcodes, CheckBBLivenessOnly)) 871 return false; 872 873 return true; 874 } 875 876 bool Attributor::checkForAllReadWriteInstructions( 877 function_ref<bool(Instruction &)> Pred, AbstractAttribute &QueryingAA) { 878 879 const Function *AssociatedFunction = 880 QueryingAA.getIRPosition().getAssociatedFunction(); 881 if (!AssociatedFunction) 882 return false; 883 884 // TODO: use the function scope once we have call site AAReturnedValues. 885 const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction); 886 const auto &LivenessAA = 887 getAAFor<AAIsDead>(QueryingAA, QueryIRP, /* TrackDependence */ false); 888 889 for (Instruction *I : 890 InfoCache.getReadOrWriteInstsForFunction(*AssociatedFunction)) { 891 // Skip dead instructions. 892 if (isAssumedDead(IRPosition::value(*I), &QueryingAA, &LivenessAA)) 893 continue; 894 895 if (!Pred(*I)) 896 return false; 897 } 898 899 return true; 900 } 901 902 ChangeStatus Attributor::run() { 903 LLVM_DEBUG(dbgs() << "[Attributor] Identified and initialized " 904 << AllAbstractAttributes.size() 905 << " abstract attributes.\n"); 906 907 // Now that all abstract attributes are collected and initialized we start 908 // the abstract analysis. 909 910 unsigned IterationCounter = 1; 911 912 SmallVector<AbstractAttribute *, 32> ChangedAAs; 913 SetVector<AbstractAttribute *> Worklist, InvalidAAs; 914 Worklist.insert(AllAbstractAttributes.begin(), AllAbstractAttributes.end()); 915 916 do { 917 // Remember the size to determine new attributes. 918 size_t NumAAs = AllAbstractAttributes.size(); 919 LLVM_DEBUG(dbgs() << "\n\n[Attributor] #Iteration: " << IterationCounter 920 << ", Worklist size: " << Worklist.size() << "\n"); 921 922 // For invalid AAs we can fix dependent AAs that have a required dependence, 923 // thereby folding long dependence chains in a single step without the need 924 // to run updates. 925 for (unsigned u = 0; u < InvalidAAs.size(); ++u) { 926 AbstractAttribute *InvalidAA = InvalidAAs[u]; 927 928 // Check the dependences to fast track invalidation. 929 auto *QuerriedAAs = QueryMap.lookup(InvalidAA); 930 if (!QuerriedAAs) 931 continue; 932 933 LLVM_DEBUG(dbgs() << "[Attributor] InvalidAA: " << *InvalidAA << " has " 934 << QuerriedAAs->RequiredAAs.size() << "/" 935 << QuerriedAAs->OptionalAAs.size() 936 << " required/optional dependences\n"); 937 for (AbstractAttribute *DepOnInvalidAA : QuerriedAAs->RequiredAAs) { 938 AbstractState &DOIAAState = DepOnInvalidAA->getState(); 939 DOIAAState.indicatePessimisticFixpoint(); 940 ++NumAttributesFixedDueToRequiredDependences; 941 assert(DOIAAState.isAtFixpoint() && "Expected fixpoint state!"); 942 if (!DOIAAState.isValidState()) 943 InvalidAAs.insert(DepOnInvalidAA); 944 else 945 ChangedAAs.push_back(DepOnInvalidAA); 946 } 947 Worklist.insert(QuerriedAAs->OptionalAAs.begin(), 948 QuerriedAAs->OptionalAAs.end()); 949 QuerriedAAs->clear(); 950 } 951 952 // Add all abstract attributes that are potentially dependent on one that 953 // changed to the work list. 954 for (AbstractAttribute *ChangedAA : ChangedAAs) { 955 if (auto *QuerriedAAs = QueryMap.lookup(ChangedAA)) { 956 Worklist.insert(QuerriedAAs->OptionalAAs.begin(), 957 QuerriedAAs->OptionalAAs.end()); 958 Worklist.insert(QuerriedAAs->RequiredAAs.begin(), 959 QuerriedAAs->RequiredAAs.end()); 960 QuerriedAAs->clear(); 961 } 962 } 963 964 LLVM_DEBUG(dbgs() << "[Attributor] #Iteration: " << IterationCounter 965 << ", Worklist+Dependent size: " << Worklist.size() 966 << "\n"); 967 968 // Reset the changed and invalid set. 969 ChangedAAs.clear(); 970 InvalidAAs.clear(); 971 972 // Update all abstract attribute in the work list and record the ones that 973 // changed. 974 for (AbstractAttribute *AA : Worklist) { 975 const auto &AAState = AA->getState(); 976 if (!AAState.isAtFixpoint() && 977 !isAssumedDead(*AA, nullptr, /* CheckBBLivenessOnly */ true)) { 978 if (updateAA(*AA) == ChangeStatus::CHANGED) { 979 ChangedAAs.push_back(AA); 980 } 981 } 982 // Use the InvalidAAs vector to propagate invalid states fast transitively 983 // without requiring updates. 984 if (!AAState.isValidState()) 985 InvalidAAs.insert(AA); 986 } 987 988 // Add attributes to the changed set if they have been created in the last 989 // iteration. 990 ChangedAAs.append(AllAbstractAttributes.begin() + NumAAs, 991 AllAbstractAttributes.end()); 992 993 // Reset the work list and repopulate with the changed abstract attributes. 994 // Note that dependent ones are added above. 995 Worklist.clear(); 996 Worklist.insert(ChangedAAs.begin(), ChangedAAs.end()); 997 998 } while (!Worklist.empty() && (IterationCounter++ < MaxFixpointIterations || 999 VerifyMaxFixpointIterations)); 1000 1001 LLVM_DEBUG(dbgs() << "\n[Attributor] Fixpoint iteration done after: " 1002 << IterationCounter << "/" << MaxFixpointIterations 1003 << " iterations\n"); 1004 1005 size_t NumFinalAAs = AllAbstractAttributes.size(); 1006 1007 // Reset abstract arguments not settled in a sound fixpoint by now. This 1008 // happens when we stopped the fixpoint iteration early. Note that only the 1009 // ones marked as "changed" *and* the ones transitively depending on them 1010 // need to be reverted to a pessimistic state. Others might not be in a 1011 // fixpoint state but we can use the optimistic results for them anyway. 1012 SmallPtrSet<AbstractAttribute *, 32> Visited; 1013 for (unsigned u = 0; u < ChangedAAs.size(); u++) { 1014 AbstractAttribute *ChangedAA = ChangedAAs[u]; 1015 if (!Visited.insert(ChangedAA).second) 1016 continue; 1017 1018 AbstractState &State = ChangedAA->getState(); 1019 if (!State.isAtFixpoint()) { 1020 State.indicatePessimisticFixpoint(); 1021 1022 NumAttributesTimedOut++; 1023 } 1024 1025 if (auto *QuerriedAAs = QueryMap.lookup(ChangedAA)) { 1026 ChangedAAs.append(QuerriedAAs->OptionalAAs.begin(), 1027 QuerriedAAs->OptionalAAs.end()); 1028 ChangedAAs.append(QuerriedAAs->RequiredAAs.begin(), 1029 QuerriedAAs->RequiredAAs.end()); 1030 // Release the memory early. 1031 QuerriedAAs->clear(); 1032 } 1033 } 1034 1035 LLVM_DEBUG({ 1036 if (!Visited.empty()) 1037 dbgs() << "\n[Attributor] Finalized " << Visited.size() 1038 << " abstract attributes.\n"; 1039 }); 1040 1041 unsigned NumManifested = 0; 1042 unsigned NumAtFixpoint = 0; 1043 ChangeStatus ManifestChange = ChangeStatus::UNCHANGED; 1044 for (AbstractAttribute *AA : AllAbstractAttributes) { 1045 AbstractState &State = AA->getState(); 1046 1047 // If there is not already a fixpoint reached, we can now take the 1048 // optimistic state. This is correct because we enforced a pessimistic one 1049 // on abstract attributes that were transitively dependent on a changed one 1050 // already above. 1051 if (!State.isAtFixpoint()) 1052 State.indicateOptimisticFixpoint(); 1053 1054 // If the state is invalid, we do not try to manifest it. 1055 if (!State.isValidState()) 1056 continue; 1057 1058 // Skip dead code. 1059 if (isAssumedDead(*AA, nullptr, /* CheckBBLivenessOnly */ true)) 1060 continue; 1061 // Manifest the state and record if we changed the IR. 1062 ChangeStatus LocalChange = AA->manifest(*this); 1063 if (LocalChange == ChangeStatus::CHANGED && AreStatisticsEnabled()) 1064 AA->trackStatistics(); 1065 LLVM_DEBUG(dbgs() << "[Attributor] Manifest " << LocalChange << " : " << *AA 1066 << "\n"); 1067 1068 ManifestChange = ManifestChange | LocalChange; 1069 1070 NumAtFixpoint++; 1071 NumManifested += (LocalChange == ChangeStatus::CHANGED); 1072 } 1073 1074 (void)NumManifested; 1075 (void)NumAtFixpoint; 1076 LLVM_DEBUG(dbgs() << "\n[Attributor] Manifested " << NumManifested 1077 << " arguments while " << NumAtFixpoint 1078 << " were in a valid fixpoint state\n"); 1079 1080 NumAttributesManifested += NumManifested; 1081 NumAttributesValidFixpoint += NumAtFixpoint; 1082 1083 (void)NumFinalAAs; 1084 if (NumFinalAAs != AllAbstractAttributes.size()) { 1085 for (unsigned u = NumFinalAAs; u < AllAbstractAttributes.size(); ++u) 1086 errs() << "Unexpected abstract attribute: " << *AllAbstractAttributes[u] 1087 << " :: " 1088 << AllAbstractAttributes[u]->getIRPosition().getAssociatedValue() 1089 << "\n"; 1090 llvm_unreachable("Expected the final number of abstract attributes to " 1091 "remain unchanged!"); 1092 } 1093 1094 // Delete stuff at the end to avoid invalid references and a nice order. 1095 { 1096 LLVM_DEBUG(dbgs() << "\n[Attributor] Delete at least " 1097 << ToBeDeletedFunctions.size() << " functions and " 1098 << ToBeDeletedBlocks.size() << " blocks and " 1099 << ToBeDeletedInsts.size() << " instructions and " 1100 << ToBeChangedUses.size() << " uses\n"); 1101 1102 SmallVector<WeakTrackingVH, 32> DeadInsts; 1103 SmallVector<Instruction *, 32> TerminatorsToFold; 1104 1105 for (auto &It : ToBeChangedUses) { 1106 Use *U = It.first; 1107 Value *NewV = It.second; 1108 Value *OldV = U->get(); 1109 1110 // Do not replace uses in returns if the value is a must-tail call we will 1111 // not delete. 1112 if (isa<ReturnInst>(U->getUser())) 1113 if (auto *CI = dyn_cast<CallInst>(OldV->stripPointerCasts())) 1114 if (CI->isMustTailCall() && !ToBeDeletedInsts.count(CI)) 1115 continue; 1116 1117 LLVM_DEBUG(dbgs() << "Use " << *NewV << " in " << *U->getUser() 1118 << " instead of " << *OldV << "\n"); 1119 U->set(NewV); 1120 // Do not modify call instructions outside the SCC. 1121 if (auto *CB = dyn_cast<CallBase>(OldV)) 1122 if (!Functions.count(CB->getCaller())) 1123 continue; 1124 if (Instruction *I = dyn_cast<Instruction>(OldV)) { 1125 CGModifiedFunctions.insert(I->getFunction()); 1126 if (!isa<PHINode>(I) && !ToBeDeletedInsts.count(I) && 1127 isInstructionTriviallyDead(I)) 1128 DeadInsts.push_back(I); 1129 } 1130 if (isa<Constant>(NewV) && isa<BranchInst>(U->getUser())) { 1131 Instruction *UserI = cast<Instruction>(U->getUser()); 1132 if (isa<UndefValue>(NewV)) { 1133 ToBeChangedToUnreachableInsts.insert(UserI); 1134 } else { 1135 TerminatorsToFold.push_back(UserI); 1136 } 1137 } 1138 } 1139 for (auto &V : InvokeWithDeadSuccessor) 1140 if (InvokeInst *II = dyn_cast_or_null<InvokeInst>(V)) { 1141 bool UnwindBBIsDead = II->hasFnAttr(Attribute::NoUnwind); 1142 bool NormalBBIsDead = II->hasFnAttr(Attribute::NoReturn); 1143 bool Invoke2CallAllowed = 1144 !AAIsDead::mayCatchAsynchronousExceptions(*II->getFunction()); 1145 assert((UnwindBBIsDead || NormalBBIsDead) && 1146 "Invoke does not have dead successors!"); 1147 BasicBlock *BB = II->getParent(); 1148 BasicBlock *NormalDestBB = II->getNormalDest(); 1149 if (UnwindBBIsDead) { 1150 Instruction *NormalNextIP = &NormalDestBB->front(); 1151 if (Invoke2CallAllowed) { 1152 changeToCall(II); 1153 NormalNextIP = BB->getTerminator(); 1154 } 1155 if (NormalBBIsDead) 1156 ToBeChangedToUnreachableInsts.insert(NormalNextIP); 1157 } else { 1158 assert(NormalBBIsDead && "Broken invariant!"); 1159 if (!NormalDestBB->getUniquePredecessor()) 1160 NormalDestBB = SplitBlockPredecessors(NormalDestBB, {BB}, ".dead"); 1161 ToBeChangedToUnreachableInsts.insert(&NormalDestBB->front()); 1162 } 1163 } 1164 for (Instruction *I : TerminatorsToFold) { 1165 CGModifiedFunctions.insert(I->getFunction()); 1166 ConstantFoldTerminator(I->getParent()); 1167 } 1168 for (auto &V : ToBeChangedToUnreachableInsts) 1169 if (Instruction *I = dyn_cast_or_null<Instruction>(V)) { 1170 CGModifiedFunctions.insert(I->getFunction()); 1171 changeToUnreachable(I, /* UseLLVMTrap */ false); 1172 } 1173 1174 for (auto &V : ToBeDeletedInsts) { 1175 if (Instruction *I = dyn_cast_or_null<Instruction>(V)) { 1176 I->dropDroppableUses(); 1177 CGModifiedFunctions.insert(I->getFunction()); 1178 if (!I->getType()->isVoidTy()) 1179 I->replaceAllUsesWith(UndefValue::get(I->getType())); 1180 if (!isa<PHINode>(I) && isInstructionTriviallyDead(I)) 1181 DeadInsts.push_back(I); 1182 else 1183 I->eraseFromParent(); 1184 } 1185 } 1186 1187 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts); 1188 1189 if (unsigned NumDeadBlocks = ToBeDeletedBlocks.size()) { 1190 SmallVector<BasicBlock *, 8> ToBeDeletedBBs; 1191 ToBeDeletedBBs.reserve(NumDeadBlocks); 1192 for (BasicBlock *BB : ToBeDeletedBlocks) { 1193 CGModifiedFunctions.insert(BB->getParent()); 1194 ToBeDeletedBBs.push_back(BB); 1195 } 1196 // Actually we do not delete the blocks but squash them into a single 1197 // unreachable but untangling branches that jump here is something we need 1198 // to do in a more generic way. 1199 DetatchDeadBlocks(ToBeDeletedBBs, nullptr); 1200 } 1201 1202 // Identify dead internal functions and delete them. This happens outside 1203 // the other fixpoint analysis as we might treat potentially dead functions 1204 // as live to lower the number of iterations. If they happen to be dead, the 1205 // below fixpoint loop will identify and eliminate them. 1206 SmallVector<Function *, 8> InternalFns; 1207 for (Function *F : Functions) 1208 if (F->hasLocalLinkage()) 1209 InternalFns.push_back(F); 1210 1211 bool FoundDeadFn = true; 1212 while (FoundDeadFn) { 1213 FoundDeadFn = false; 1214 for (unsigned u = 0, e = InternalFns.size(); u < e; ++u) { 1215 Function *F = InternalFns[u]; 1216 if (!F) 1217 continue; 1218 1219 bool AllCallSitesKnown; 1220 if (!checkForAllCallSites( 1221 [this](AbstractCallSite ACS) { 1222 return ToBeDeletedFunctions.count( 1223 ACS.getInstruction()->getFunction()); 1224 }, 1225 *F, true, nullptr, AllCallSitesKnown)) 1226 continue; 1227 1228 ToBeDeletedFunctions.insert(F); 1229 InternalFns[u] = nullptr; 1230 FoundDeadFn = true; 1231 } 1232 } 1233 } 1234 1235 // Rewrite the functions as requested during manifest. 1236 ManifestChange = 1237 ManifestChange | rewriteFunctionSignatures(CGModifiedFunctions); 1238 1239 for (Function *Fn : CGModifiedFunctions) 1240 CGUpdater.reanalyzeFunction(*Fn); 1241 1242 for (Function *Fn : ToBeDeletedFunctions) 1243 CGUpdater.removeFunction(*Fn); 1244 1245 NumFnDeleted += ToBeDeletedFunctions.size(); 1246 1247 if (VerifyMaxFixpointIterations && 1248 IterationCounter != MaxFixpointIterations) { 1249 errs() << "\n[Attributor] Fixpoint iteration done after: " 1250 << IterationCounter << "/" << MaxFixpointIterations 1251 << " iterations\n"; 1252 llvm_unreachable("The fixpoint was not reached with exactly the number of " 1253 "specified iterations!"); 1254 } 1255 1256 #ifdef EXPENSIVE_CHECKS 1257 for (Function *F : Functions) { 1258 if (ToBeDeletedFunctions.count(F)) 1259 continue; 1260 assert(!verifyFunction(*F, &errs()) && "Module verification failed!"); 1261 } 1262 #endif 1263 1264 return ManifestChange; 1265 } 1266 1267 ChangeStatus Attributor::updateAA(AbstractAttribute &AA) { 1268 // Use a new dependence vector for this update. 1269 DependenceVector DV; 1270 DependenceStack.push_back(&DV); 1271 1272 auto &AAState = AA.getState(); 1273 ChangeStatus CS = AA.update(*this); 1274 if (DV.empty()) { 1275 // If the attribute did not query any non-fix information, the state 1276 // will not change and we can indicate that right away. 1277 AAState.indicateOptimisticFixpoint(); 1278 } 1279 1280 if (!AAState.isAtFixpoint()) 1281 rememberDependences(); 1282 1283 // Verify the stack was used properly, that is we pop the dependence vector we 1284 // put there earlier. 1285 DependenceVector *PoppedDV = DependenceStack.pop_back_val(); 1286 (void)PoppedDV; 1287 assert(PoppedDV == &DV && "Inconsistent usage of the dependence stack!"); 1288 1289 return CS; 1290 } 1291 1292 /// Create a shallow wrapper for \p F such that \p F has internal linkage 1293 /// afterwards. It also sets the original \p F 's name to anonymous 1294 /// 1295 /// A wrapper is a function with the same type (and attributes) as \p F 1296 /// that will only call \p F and return the result, if any. 1297 /// 1298 /// Assuming the declaration of looks like: 1299 /// rty F(aty0 arg0, ..., atyN argN); 1300 /// 1301 /// The wrapper will then look as follows: 1302 /// rty wrapper(aty0 arg0, ..., atyN argN) { 1303 /// return F(arg0, ..., argN); 1304 /// } 1305 /// 1306 static void createShallowWrapper(Function &F) { 1307 assert(AllowShallowWrappers && 1308 "Cannot create a wrapper if it is not allowed!"); 1309 assert(!F.isDeclaration() && "Cannot create a wrapper around a declaration!"); 1310 1311 Module &M = *F.getParent(); 1312 LLVMContext &Ctx = M.getContext(); 1313 FunctionType *FnTy = F.getFunctionType(); 1314 1315 Function *Wrapper = 1316 Function::Create(FnTy, F.getLinkage(), F.getAddressSpace(), F.getName()); 1317 F.setName(""); // set the inside function anonymous 1318 M.getFunctionList().insert(F.getIterator(), Wrapper); 1319 1320 F.setLinkage(GlobalValue::InternalLinkage); 1321 1322 F.replaceAllUsesWith(Wrapper); 1323 assert(F.use_empty() && "Uses remained after wrapper was created!"); 1324 1325 // Move the COMDAT section to the wrapper. 1326 // TODO: Check if we need to keep it for F as well. 1327 Wrapper->setComdat(F.getComdat()); 1328 F.setComdat(nullptr); 1329 1330 // Copy all metadata and attributes but keep them on F as well. 1331 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs; 1332 F.getAllMetadata(MDs); 1333 for (auto MDIt : MDs) 1334 Wrapper->addMetadata(MDIt.first, *MDIt.second); 1335 Wrapper->setAttributes(F.getAttributes()); 1336 1337 // Create the call in the wrapper. 1338 BasicBlock *EntryBB = BasicBlock::Create(Ctx, "entry", Wrapper); 1339 1340 SmallVector<Value *, 8> Args; 1341 auto FArgIt = F.arg_begin(); 1342 for (Argument &Arg : Wrapper->args()) { 1343 Args.push_back(&Arg); 1344 Arg.setName((FArgIt++)->getName()); 1345 } 1346 1347 CallInst *CI = CallInst::Create(&F, Args, "", EntryBB); 1348 CI->setTailCall(true); 1349 CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoInline); 1350 ReturnInst::Create(Ctx, CI->getType()->isVoidTy() ? nullptr : CI, EntryBB); 1351 1352 NumFnShallowWrapperCreated++; 1353 } 1354 1355 bool Attributor::isValidFunctionSignatureRewrite( 1356 Argument &Arg, ArrayRef<Type *> ReplacementTypes) { 1357 1358 auto CallSiteCanBeChanged = [](AbstractCallSite ACS) { 1359 // Forbid must-tail calls for now. 1360 return !ACS.isCallbackCall() && !ACS.getInstruction()->isMustTailCall(); 1361 }; 1362 1363 Function *Fn = Arg.getParent(); 1364 // Avoid var-arg functions for now. 1365 if (Fn->isVarArg()) { 1366 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite var-args functions\n"); 1367 return false; 1368 } 1369 1370 // Avoid functions with complicated argument passing semantics. 1371 AttributeList FnAttributeList = Fn->getAttributes(); 1372 if (FnAttributeList.hasAttrSomewhere(Attribute::Nest) || 1373 FnAttributeList.hasAttrSomewhere(Attribute::StructRet) || 1374 FnAttributeList.hasAttrSomewhere(Attribute::InAlloca)) { 1375 LLVM_DEBUG( 1376 dbgs() << "[Attributor] Cannot rewrite due to complex attribute\n"); 1377 return false; 1378 } 1379 1380 // Avoid callbacks for now. 1381 bool AllCallSitesKnown; 1382 if (!checkForAllCallSites(CallSiteCanBeChanged, *Fn, true, nullptr, 1383 AllCallSitesKnown)) { 1384 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite all call sites\n"); 1385 return false; 1386 } 1387 1388 auto InstPred = [](Instruction &I) { 1389 if (auto *CI = dyn_cast<CallInst>(&I)) 1390 return !CI->isMustTailCall(); 1391 return true; 1392 }; 1393 1394 // Forbid must-tail calls for now. 1395 // TODO: 1396 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(*Fn); 1397 if (!checkForAllInstructionsImpl(nullptr, OpcodeInstMap, InstPred, nullptr, 1398 nullptr, {Instruction::Call})) { 1399 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite due to instructions\n"); 1400 return false; 1401 } 1402 1403 return true; 1404 } 1405 1406 bool Attributor::registerFunctionSignatureRewrite( 1407 Argument &Arg, ArrayRef<Type *> ReplacementTypes, 1408 ArgumentReplacementInfo::CalleeRepairCBTy &&CalleeRepairCB, 1409 ArgumentReplacementInfo::ACSRepairCBTy &&ACSRepairCB) { 1410 LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in " 1411 << Arg.getParent()->getName() << " with " 1412 << ReplacementTypes.size() << " replacements\n"); 1413 assert(isValidFunctionSignatureRewrite(Arg, ReplacementTypes) && 1414 "Cannot register an invalid rewrite"); 1415 1416 Function *Fn = Arg.getParent(); 1417 SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs = 1418 ArgumentReplacementMap[Fn]; 1419 if (ARIs.empty()) 1420 ARIs.resize(Fn->arg_size()); 1421 1422 // If we have a replacement already with less than or equal new arguments, 1423 // ignore this request. 1424 std::unique_ptr<ArgumentReplacementInfo> &ARI = ARIs[Arg.getArgNo()]; 1425 if (ARI && ARI->getNumReplacementArgs() <= ReplacementTypes.size()) { 1426 LLVM_DEBUG(dbgs() << "[Attributor] Existing rewrite is preferred\n"); 1427 return false; 1428 } 1429 1430 // If we have a replacement already but we like the new one better, delete 1431 // the old. 1432 ARI.reset(); 1433 1434 LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in " 1435 << Arg.getParent()->getName() << " with " 1436 << ReplacementTypes.size() << " replacements\n"); 1437 1438 // Remember the replacement. 1439 ARI.reset(new ArgumentReplacementInfo(*this, Arg, ReplacementTypes, 1440 std::move(CalleeRepairCB), 1441 std::move(ACSRepairCB))); 1442 1443 return true; 1444 } 1445 1446 ChangeStatus Attributor::rewriteFunctionSignatures( 1447 SmallPtrSetImpl<Function *> &ModifiedFns) { 1448 ChangeStatus Changed = ChangeStatus::UNCHANGED; 1449 1450 for (auto &It : ArgumentReplacementMap) { 1451 Function *OldFn = It.getFirst(); 1452 1453 // Deleted functions do not require rewrites. 1454 if (ToBeDeletedFunctions.count(OldFn)) 1455 continue; 1456 1457 const SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs = It.getSecond(); 1458 assert(ARIs.size() == OldFn->arg_size() && "Inconsistent state!"); 1459 1460 SmallVector<Type *, 16> NewArgumentTypes; 1461 SmallVector<AttributeSet, 16> NewArgumentAttributes; 1462 1463 // Collect replacement argument types and copy over existing attributes. 1464 AttributeList OldFnAttributeList = OldFn->getAttributes(); 1465 for (Argument &Arg : OldFn->args()) { 1466 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI = ARIs[Arg.getArgNo()]) { 1467 NewArgumentTypes.append(ARI->ReplacementTypes.begin(), 1468 ARI->ReplacementTypes.end()); 1469 NewArgumentAttributes.append(ARI->getNumReplacementArgs(), 1470 AttributeSet()); 1471 } else { 1472 NewArgumentTypes.push_back(Arg.getType()); 1473 NewArgumentAttributes.push_back( 1474 OldFnAttributeList.getParamAttributes(Arg.getArgNo())); 1475 } 1476 } 1477 1478 FunctionType *OldFnTy = OldFn->getFunctionType(); 1479 Type *RetTy = OldFnTy->getReturnType(); 1480 1481 // Construct the new function type using the new arguments types. 1482 FunctionType *NewFnTy = 1483 FunctionType::get(RetTy, NewArgumentTypes, OldFnTy->isVarArg()); 1484 1485 LLVM_DEBUG(dbgs() << "[Attributor] Function rewrite '" << OldFn->getName() 1486 << "' from " << *OldFn->getFunctionType() << " to " 1487 << *NewFnTy << "\n"); 1488 1489 // Create the new function body and insert it into the module. 1490 Function *NewFn = Function::Create(NewFnTy, OldFn->getLinkage(), 1491 OldFn->getAddressSpace(), ""); 1492 OldFn->getParent()->getFunctionList().insert(OldFn->getIterator(), NewFn); 1493 NewFn->takeName(OldFn); 1494 NewFn->copyAttributesFrom(OldFn); 1495 1496 // Patch the pointer to LLVM function in debug info descriptor. 1497 NewFn->setSubprogram(OldFn->getSubprogram()); 1498 OldFn->setSubprogram(nullptr); 1499 1500 // Recompute the parameter attributes list based on the new arguments for 1501 // the function. 1502 LLVMContext &Ctx = OldFn->getContext(); 1503 NewFn->setAttributes(AttributeList::get( 1504 Ctx, OldFnAttributeList.getFnAttributes(), 1505 OldFnAttributeList.getRetAttributes(), NewArgumentAttributes)); 1506 1507 // Since we have now created the new function, splice the body of the old 1508 // function right into the new function, leaving the old rotting hulk of the 1509 // function empty. 1510 NewFn->getBasicBlockList().splice(NewFn->begin(), 1511 OldFn->getBasicBlockList()); 1512 1513 // Set of all "call-like" instructions that invoke the old function mapped 1514 // to their new replacements. 1515 SmallVector<std::pair<CallBase *, CallBase *>, 8> CallSitePairs; 1516 1517 // Callback to create a new "call-like" instruction for a given one. 1518 auto CallSiteReplacementCreator = [&](AbstractCallSite ACS) { 1519 CallBase *OldCB = cast<CallBase>(ACS.getInstruction()); 1520 const AttributeList &OldCallAttributeList = OldCB->getAttributes(); 1521 1522 // Collect the new argument operands for the replacement call site. 1523 SmallVector<Value *, 16> NewArgOperands; 1524 SmallVector<AttributeSet, 16> NewArgOperandAttributes; 1525 for (unsigned OldArgNum = 0; OldArgNum < ARIs.size(); ++OldArgNum) { 1526 unsigned NewFirstArgNum = NewArgOperands.size(); 1527 (void)NewFirstArgNum; // only used inside assert. 1528 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI = ARIs[OldArgNum]) { 1529 if (ARI->ACSRepairCB) 1530 ARI->ACSRepairCB(*ARI, ACS, NewArgOperands); 1531 assert(ARI->getNumReplacementArgs() + NewFirstArgNum == 1532 NewArgOperands.size() && 1533 "ACS repair callback did not provide as many operand as new " 1534 "types were registered!"); 1535 // TODO: Exose the attribute set to the ACS repair callback 1536 NewArgOperandAttributes.append(ARI->ReplacementTypes.size(), 1537 AttributeSet()); 1538 } else { 1539 NewArgOperands.push_back(ACS.getCallArgOperand(OldArgNum)); 1540 NewArgOperandAttributes.push_back( 1541 OldCallAttributeList.getParamAttributes(OldArgNum)); 1542 } 1543 } 1544 1545 assert(NewArgOperands.size() == NewArgOperandAttributes.size() && 1546 "Mismatch # argument operands vs. # argument operand attributes!"); 1547 assert(NewArgOperands.size() == NewFn->arg_size() && 1548 "Mismatch # argument operands vs. # function arguments!"); 1549 1550 SmallVector<OperandBundleDef, 4> OperandBundleDefs; 1551 OldCB->getOperandBundlesAsDefs(OperandBundleDefs); 1552 1553 // Create a new call or invoke instruction to replace the old one. 1554 CallBase *NewCB; 1555 if (InvokeInst *II = dyn_cast<InvokeInst>(OldCB)) { 1556 NewCB = 1557 InvokeInst::Create(NewFn, II->getNormalDest(), II->getUnwindDest(), 1558 NewArgOperands, OperandBundleDefs, "", OldCB); 1559 } else { 1560 auto *NewCI = CallInst::Create(NewFn, NewArgOperands, OperandBundleDefs, 1561 "", OldCB); 1562 NewCI->setTailCallKind(cast<CallInst>(OldCB)->getTailCallKind()); 1563 NewCB = NewCI; 1564 } 1565 1566 // Copy over various properties and the new attributes. 1567 uint64_t W; 1568 if (OldCB->extractProfTotalWeight(W)) 1569 NewCB->setProfWeight(W); 1570 NewCB->setCallingConv(OldCB->getCallingConv()); 1571 NewCB->setDebugLoc(OldCB->getDebugLoc()); 1572 NewCB->takeName(OldCB); 1573 NewCB->setAttributes(AttributeList::get( 1574 Ctx, OldCallAttributeList.getFnAttributes(), 1575 OldCallAttributeList.getRetAttributes(), NewArgOperandAttributes)); 1576 1577 CallSitePairs.push_back({OldCB, NewCB}); 1578 return true; 1579 }; 1580 1581 // Use the CallSiteReplacementCreator to create replacement call sites. 1582 bool AllCallSitesKnown; 1583 bool Success = checkForAllCallSites(CallSiteReplacementCreator, *OldFn, 1584 true, nullptr, AllCallSitesKnown); 1585 (void)Success; 1586 assert(Success && "Assumed call site replacement to succeed!"); 1587 1588 // Rewire the arguments. 1589 auto OldFnArgIt = OldFn->arg_begin(); 1590 auto NewFnArgIt = NewFn->arg_begin(); 1591 for (unsigned OldArgNum = 0; OldArgNum < ARIs.size(); 1592 ++OldArgNum, ++OldFnArgIt) { 1593 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI = 1594 ARIs[OldArgNum]) { 1595 if (ARI->CalleeRepairCB) 1596 ARI->CalleeRepairCB(*ARI, *NewFn, NewFnArgIt); 1597 NewFnArgIt += ARI->ReplacementTypes.size(); 1598 } else { 1599 NewFnArgIt->takeName(&*OldFnArgIt); 1600 OldFnArgIt->replaceAllUsesWith(&*NewFnArgIt); 1601 ++NewFnArgIt; 1602 } 1603 } 1604 1605 // Eliminate the instructions *after* we visited all of them. 1606 for (auto &CallSitePair : CallSitePairs) { 1607 CallBase &OldCB = *CallSitePair.first; 1608 CallBase &NewCB = *CallSitePair.second; 1609 ModifiedFns.insert(OldCB.getFunction()); 1610 CGUpdater.replaceCallSite(OldCB, NewCB); 1611 OldCB.replaceAllUsesWith(&NewCB); 1612 OldCB.eraseFromParent(); 1613 } 1614 1615 // Replace the function in the call graph (if any). 1616 CGUpdater.replaceFunctionWith(*OldFn, *NewFn); 1617 1618 // If the old function was modified and needed to be reanalyzed, the new one 1619 // does now. 1620 if (ModifiedFns.erase(OldFn)) 1621 ModifiedFns.insert(NewFn); 1622 1623 Changed = ChangeStatus::CHANGED; 1624 } 1625 1626 return Changed; 1627 } 1628 1629 void InformationCache::initializeInformationCache(const Function &CF, 1630 FunctionInfo &FI) { 1631 // As we do not modify the function here we can remove the const 1632 // withouth breaking implicit assumptions. At the end of the day, we could 1633 // initialize the cache eagerly which would look the same to the users. 1634 Function &F = const_cast<Function &>(CF); 1635 1636 // Walk all instructions to find interesting instructions that might be 1637 // queried by abstract attributes during their initialization or update. 1638 // This has to happen before we create attributes. 1639 1640 for (Instruction &I : instructions(&F)) { 1641 bool IsInterestingOpcode = false; 1642 1643 // To allow easy access to all instructions in a function with a given 1644 // opcode we store them in the InfoCache. As not all opcodes are interesting 1645 // to concrete attributes we only cache the ones that are as identified in 1646 // the following switch. 1647 // Note: There are no concrete attributes now so this is initially empty. 1648 switch (I.getOpcode()) { 1649 default: 1650 assert(!isa<CallBase>(&I) && 1651 "New call base instruction type needs to be known in the " 1652 "Attributor."); 1653 break; 1654 case Instruction::Call: 1655 // Calls are interesting on their own, additionally: 1656 // For `llvm.assume` calls we also fill the KnowledgeMap as we find them. 1657 // For `must-tail` calls we remember the caller and callee. 1658 if (IntrinsicInst *Assume = dyn_cast<IntrinsicInst>(&I)) { 1659 if (Assume->getIntrinsicID() == Intrinsic::assume) 1660 fillMapFromAssume(*Assume, KnowledgeMap); 1661 } else if (cast<CallInst>(I).isMustTailCall()) { 1662 FI.ContainsMustTailCall = true; 1663 if (const Function *Callee = cast<CallInst>(I).getCalledFunction()) 1664 getFunctionInfo(*Callee).CalledViaMustTail = true; 1665 } 1666 LLVM_FALLTHROUGH; 1667 case Instruction::CallBr: 1668 case Instruction::Invoke: 1669 case Instruction::CleanupRet: 1670 case Instruction::CatchSwitch: 1671 case Instruction::AtomicRMW: 1672 case Instruction::AtomicCmpXchg: 1673 case Instruction::Br: 1674 case Instruction::Resume: 1675 case Instruction::Ret: 1676 case Instruction::Load: 1677 // The alignment of a pointer is interesting for loads. 1678 case Instruction::Store: 1679 // The alignment of a pointer is interesting for stores. 1680 IsInterestingOpcode = true; 1681 } 1682 if (IsInterestingOpcode) { 1683 auto *&Insts = FI.OpcodeInstMap[I.getOpcode()]; 1684 if (!Insts) 1685 Insts = new (Allocator) InstructionVectorTy(); 1686 Insts->push_back(&I); 1687 } 1688 if (I.mayReadOrWriteMemory()) 1689 FI.RWInsts.push_back(&I); 1690 } 1691 1692 if (F.hasFnAttribute(Attribute::AlwaysInline) && 1693 isInlineViable(F).isSuccess()) 1694 InlineableFunctions.insert(&F); 1695 } 1696 1697 InformationCache::FunctionInfo::~FunctionInfo() { 1698 // The instruction vectors are allocated using a BumpPtrAllocator, we need to 1699 // manually destroy them. 1700 for (auto &It : OpcodeInstMap) 1701 It.getSecond()->~InstructionVectorTy(); 1702 } 1703 1704 void Attributor::recordDependence(const AbstractAttribute &FromAA, 1705 const AbstractAttribute &ToAA, 1706 DepClassTy DepClass) { 1707 // If we are outside of an update, thus before the actual fixpoint iteration 1708 // started (= when we create AAs), we do not track dependences because we will 1709 // put all AAs into the initial worklist anyway. 1710 if (DependenceStack.empty()) 1711 return; 1712 if (FromAA.getState().isAtFixpoint()) 1713 return; 1714 DependenceStack.back()->push_back({&FromAA, &ToAA, DepClass}); 1715 } 1716 1717 void Attributor::rememberDependences() { 1718 assert(!DependenceStack.empty() && "No dependences to remember!"); 1719 1720 for (DepInfo &DI : *DependenceStack.back()) { 1721 QueryMapValueTy *&DepAAs = QueryMap[DI.FromAA]; 1722 if (!DepAAs) 1723 DepAAs = new (Allocator) QueryMapValueTy(); 1724 1725 if (DI.DepClass == DepClassTy::REQUIRED) 1726 DepAAs->RequiredAAs.insert(const_cast<AbstractAttribute *>(DI.ToAA)); 1727 else 1728 DepAAs->OptionalAAs.insert(const_cast<AbstractAttribute *>(DI.ToAA)); 1729 } 1730 } 1731 1732 void Attributor::identifyDefaultAbstractAttributes(Function &F) { 1733 if (!VisitedFunctions.insert(&F).second) 1734 return; 1735 if (F.isDeclaration()) 1736 return; 1737 1738 // In non-module runs we need to look at the call sites of a function to 1739 // determine if it is part of a must-tail call edge. This will influence what 1740 // attributes we can derive. 1741 InformationCache::FunctionInfo &FI = InfoCache.getFunctionInfo(F); 1742 if (!isModulePass() && !FI.CalledViaMustTail) { 1743 for (const Use &U : F.uses()) 1744 if (const auto *CB = dyn_cast<CallBase>(U.getUser())) 1745 if (CB->isCallee(&U) && CB->isMustTailCall()) 1746 FI.CalledViaMustTail = true; 1747 } 1748 1749 IRPosition FPos = IRPosition::function(F); 1750 1751 // Check for dead BasicBlocks in every function. 1752 // We need dead instruction detection because we do not want to deal with 1753 // broken IR in which SSA rules do not apply. 1754 getOrCreateAAFor<AAIsDead>(FPos); 1755 1756 // Every function might be "will-return". 1757 getOrCreateAAFor<AAWillReturn>(FPos); 1758 1759 // Every function might contain instructions that cause "undefined behavior". 1760 getOrCreateAAFor<AAUndefinedBehavior>(FPos); 1761 1762 // Every function can be nounwind. 1763 getOrCreateAAFor<AANoUnwind>(FPos); 1764 1765 // Every function might be marked "nosync" 1766 getOrCreateAAFor<AANoSync>(FPos); 1767 1768 // Every function might be "no-free". 1769 getOrCreateAAFor<AANoFree>(FPos); 1770 1771 // Every function might be "no-return". 1772 getOrCreateAAFor<AANoReturn>(FPos); 1773 1774 // Every function might be "no-recurse". 1775 getOrCreateAAFor<AANoRecurse>(FPos); 1776 1777 // Every function might be "readnone/readonly/writeonly/...". 1778 getOrCreateAAFor<AAMemoryBehavior>(FPos); 1779 1780 // Every function can be "readnone/argmemonly/inaccessiblememonly/...". 1781 getOrCreateAAFor<AAMemoryLocation>(FPos); 1782 1783 // Every function might be applicable for Heap-To-Stack conversion. 1784 if (EnableHeapToStack) 1785 getOrCreateAAFor<AAHeapToStack>(FPos); 1786 1787 // Return attributes are only appropriate if the return type is non void. 1788 Type *ReturnType = F.getReturnType(); 1789 if (!ReturnType->isVoidTy()) { 1790 // Argument attribute "returned" --- Create only one per function even 1791 // though it is an argument attribute. 1792 getOrCreateAAFor<AAReturnedValues>(FPos); 1793 1794 IRPosition RetPos = IRPosition::returned(F); 1795 1796 // Every returned value might be dead. 1797 getOrCreateAAFor<AAIsDead>(RetPos); 1798 1799 // Every function might be simplified. 1800 getOrCreateAAFor<AAValueSimplify>(RetPos); 1801 1802 if (ReturnType->isPointerTy()) { 1803 1804 // Every function with pointer return type might be marked align. 1805 getOrCreateAAFor<AAAlign>(RetPos); 1806 1807 // Every function with pointer return type might be marked nonnull. 1808 getOrCreateAAFor<AANonNull>(RetPos); 1809 1810 // Every function with pointer return type might be marked noalias. 1811 getOrCreateAAFor<AANoAlias>(RetPos); 1812 1813 // Every function with pointer return type might be marked 1814 // dereferenceable. 1815 getOrCreateAAFor<AADereferenceable>(RetPos); 1816 } 1817 } 1818 1819 for (Argument &Arg : F.args()) { 1820 IRPosition ArgPos = IRPosition::argument(Arg); 1821 1822 // Every argument might be simplified. 1823 getOrCreateAAFor<AAValueSimplify>(ArgPos); 1824 1825 // Every argument might be dead. 1826 getOrCreateAAFor<AAIsDead>(ArgPos); 1827 1828 if (Arg.getType()->isPointerTy()) { 1829 // Every argument with pointer type might be marked nonnull. 1830 getOrCreateAAFor<AANonNull>(ArgPos); 1831 1832 // Every argument with pointer type might be marked noalias. 1833 getOrCreateAAFor<AANoAlias>(ArgPos); 1834 1835 // Every argument with pointer type might be marked dereferenceable. 1836 getOrCreateAAFor<AADereferenceable>(ArgPos); 1837 1838 // Every argument with pointer type might be marked align. 1839 getOrCreateAAFor<AAAlign>(ArgPos); 1840 1841 // Every argument with pointer type might be marked nocapture. 1842 getOrCreateAAFor<AANoCapture>(ArgPos); 1843 1844 // Every argument with pointer type might be marked 1845 // "readnone/readonly/writeonly/..." 1846 getOrCreateAAFor<AAMemoryBehavior>(ArgPos); 1847 1848 // Every argument with pointer type might be marked nofree. 1849 getOrCreateAAFor<AANoFree>(ArgPos); 1850 1851 // Every argument with pointer type might be privatizable (or promotable) 1852 getOrCreateAAFor<AAPrivatizablePtr>(ArgPos); 1853 } 1854 } 1855 1856 auto CallSitePred = [&](Instruction &I) -> bool { 1857 auto &CB = cast<CallBase>(I); 1858 IRPosition CBRetPos = IRPosition::callsite_returned(CB); 1859 1860 // Call sites might be dead if they do not have side effects and no live 1861 // users. The return value might be dead if there are no live users. 1862 getOrCreateAAFor<AAIsDead>(CBRetPos); 1863 1864 Function *Callee = CB.getCalledFunction(); 1865 // TODO: Even if the callee is not known now we might be able to simplify 1866 // the call/callee. 1867 if (!Callee) 1868 return true; 1869 1870 // Skip declarations except if annotations on their call sites were 1871 // explicitly requested. 1872 if (!AnnotateDeclarationCallSites && Callee->isDeclaration() && 1873 !Callee->hasMetadata(LLVMContext::MD_callback)) 1874 return true; 1875 1876 if (!Callee->getReturnType()->isVoidTy() && !CB.use_empty()) { 1877 1878 IRPosition CBRetPos = IRPosition::callsite_returned(CB); 1879 1880 // Call site return integer values might be limited by a constant range. 1881 if (Callee->getReturnType()->isIntegerTy()) 1882 getOrCreateAAFor<AAValueConstantRange>(CBRetPos); 1883 } 1884 1885 for (int I = 0, E = CB.getNumArgOperands(); I < E; ++I) { 1886 1887 IRPosition CBArgPos = IRPosition::callsite_argument(CB, I); 1888 1889 // Every call site argument might be dead. 1890 getOrCreateAAFor<AAIsDead>(CBArgPos); 1891 1892 // Call site argument might be simplified. 1893 getOrCreateAAFor<AAValueSimplify>(CBArgPos); 1894 1895 if (!CB.getArgOperand(I)->getType()->isPointerTy()) 1896 continue; 1897 1898 // Call site argument attribute "non-null". 1899 getOrCreateAAFor<AANonNull>(CBArgPos); 1900 1901 // Call site argument attribute "nocapture". 1902 getOrCreateAAFor<AANoCapture>(CBArgPos); 1903 1904 // Call site argument attribute "no-alias". 1905 getOrCreateAAFor<AANoAlias>(CBArgPos); 1906 1907 // Call site argument attribute "dereferenceable". 1908 getOrCreateAAFor<AADereferenceable>(CBArgPos); 1909 1910 // Call site argument attribute "align". 1911 getOrCreateAAFor<AAAlign>(CBArgPos); 1912 1913 // Call site argument attribute 1914 // "readnone/readonly/writeonly/..." 1915 getOrCreateAAFor<AAMemoryBehavior>(CBArgPos); 1916 1917 // Call site argument attribute "nofree". 1918 getOrCreateAAFor<AANoFree>(CBArgPos); 1919 } 1920 return true; 1921 }; 1922 1923 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F); 1924 bool Success; 1925 Success = checkForAllInstructionsImpl( 1926 nullptr, OpcodeInstMap, CallSitePred, nullptr, nullptr, 1927 {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr, 1928 (unsigned)Instruction::Call}); 1929 (void)Success; 1930 assert(Success && "Expected the check call to be successful!"); 1931 1932 auto LoadStorePred = [&](Instruction &I) -> bool { 1933 if (isa<LoadInst>(I)) 1934 getOrCreateAAFor<AAAlign>( 1935 IRPosition::value(*cast<LoadInst>(I).getPointerOperand())); 1936 else 1937 getOrCreateAAFor<AAAlign>( 1938 IRPosition::value(*cast<StoreInst>(I).getPointerOperand())); 1939 return true; 1940 }; 1941 Success = checkForAllInstructionsImpl( 1942 nullptr, OpcodeInstMap, LoadStorePred, nullptr, nullptr, 1943 {(unsigned)Instruction::Load, (unsigned)Instruction::Store}); 1944 (void)Success; 1945 assert(Success && "Expected the check call to be successful!"); 1946 } 1947 1948 /// Helpers to ease debugging through output streams and print calls. 1949 /// 1950 ///{ 1951 raw_ostream &llvm::operator<<(raw_ostream &OS, ChangeStatus S) { 1952 return OS << (S == ChangeStatus::CHANGED ? "changed" : "unchanged"); 1953 } 1954 1955 raw_ostream &llvm::operator<<(raw_ostream &OS, IRPosition::Kind AP) { 1956 switch (AP) { 1957 case IRPosition::IRP_INVALID: 1958 return OS << "inv"; 1959 case IRPosition::IRP_FLOAT: 1960 return OS << "flt"; 1961 case IRPosition::IRP_RETURNED: 1962 return OS << "fn_ret"; 1963 case IRPosition::IRP_CALL_SITE_RETURNED: 1964 return OS << "cs_ret"; 1965 case IRPosition::IRP_FUNCTION: 1966 return OS << "fn"; 1967 case IRPosition::IRP_CALL_SITE: 1968 return OS << "cs"; 1969 case IRPosition::IRP_ARGUMENT: 1970 return OS << "arg"; 1971 case IRPosition::IRP_CALL_SITE_ARGUMENT: 1972 return OS << "cs_arg"; 1973 } 1974 llvm_unreachable("Unknown attribute position!"); 1975 } 1976 1977 raw_ostream &llvm::operator<<(raw_ostream &OS, const IRPosition &Pos) { 1978 const Value &AV = Pos.getAssociatedValue(); 1979 return OS << "{" << Pos.getPositionKind() << ":" << AV.getName() << " [" 1980 << Pos.getAnchorValue().getName() << "@" << Pos.getArgNo() << "]}"; 1981 } 1982 1983 raw_ostream &llvm::operator<<(raw_ostream &OS, const IntegerRangeState &S) { 1984 OS << "range-state(" << S.getBitWidth() << ")<"; 1985 S.getKnown().print(OS); 1986 OS << " / "; 1987 S.getAssumed().print(OS); 1988 OS << ">"; 1989 1990 return OS << static_cast<const AbstractState &>(S); 1991 } 1992 1993 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractState &S) { 1994 return OS << (!S.isValidState() ? "top" : (S.isAtFixpoint() ? "fix" : "")); 1995 } 1996 1997 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractAttribute &AA) { 1998 AA.print(OS); 1999 return OS; 2000 } 2001 2002 void AbstractAttribute::print(raw_ostream &OS) const { 2003 OS << "[P: " << getIRPosition() << "][" << getAsStr() << "][S: " << getState() 2004 << "]"; 2005 } 2006 ///} 2007 2008 /// ---------------------------------------------------------------------------- 2009 /// Pass (Manager) Boilerplate 2010 /// ---------------------------------------------------------------------------- 2011 2012 static bool runAttributorOnFunctions(InformationCache &InfoCache, 2013 SetVector<Function *> &Functions, 2014 AnalysisGetter &AG, 2015 CallGraphUpdater &CGUpdater) { 2016 if (Functions.empty()) 2017 return false; 2018 2019 LLVM_DEBUG(dbgs() << "[Attributor] Run on module with " << Functions.size() 2020 << " functions.\n"); 2021 2022 // Create an Attributor and initially empty information cache that is filled 2023 // while we identify default attribute opportunities. 2024 Attributor A(Functions, InfoCache, CGUpdater); 2025 2026 // Create shallow wrappers for all functions that are not IPO amendable 2027 if (AllowShallowWrappers) 2028 for (Function *F : Functions) 2029 if (!A.isFunctionIPOAmendable(*F)) 2030 createShallowWrapper(*F); 2031 2032 for (Function *F : Functions) { 2033 if (F->hasExactDefinition()) 2034 NumFnWithExactDefinition++; 2035 else 2036 NumFnWithoutExactDefinition++; 2037 2038 // We look at internal functions only on-demand but if any use is not a 2039 // direct call or outside the current set of analyzed functions, we have to 2040 // do it eagerly. 2041 if (F->hasLocalLinkage()) { 2042 if (llvm::all_of(F->uses(), [&Functions](const Use &U) { 2043 const auto *CB = dyn_cast<CallBase>(U.getUser()); 2044 return CB && CB->isCallee(&U) && 2045 Functions.count(const_cast<Function *>(CB->getCaller())); 2046 })) 2047 continue; 2048 } 2049 2050 // Populate the Attributor with abstract attribute opportunities in the 2051 // function and the information cache with IR information. 2052 A.identifyDefaultAbstractAttributes(*F); 2053 } 2054 2055 ChangeStatus Changed = A.run(); 2056 LLVM_DEBUG(dbgs() << "[Attributor] Done with " << Functions.size() 2057 << " functions, result: " << Changed << ".\n"); 2058 return Changed == ChangeStatus::CHANGED; 2059 } 2060 2061 PreservedAnalyses AttributorPass::run(Module &M, ModuleAnalysisManager &AM) { 2062 FunctionAnalysisManager &FAM = 2063 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 2064 AnalysisGetter AG(FAM); 2065 2066 SetVector<Function *> Functions; 2067 for (Function &F : M) 2068 Functions.insert(&F); 2069 2070 CallGraphUpdater CGUpdater; 2071 BumpPtrAllocator Allocator; 2072 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr); 2073 if (runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater)) { 2074 // FIXME: Think about passes we will preserve and add them here. 2075 return PreservedAnalyses::none(); 2076 } 2077 return PreservedAnalyses::all(); 2078 } 2079 2080 PreservedAnalyses AttributorCGSCCPass::run(LazyCallGraph::SCC &C, 2081 CGSCCAnalysisManager &AM, 2082 LazyCallGraph &CG, 2083 CGSCCUpdateResult &UR) { 2084 FunctionAnalysisManager &FAM = 2085 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager(); 2086 AnalysisGetter AG(FAM); 2087 2088 SetVector<Function *> Functions; 2089 for (LazyCallGraph::Node &N : C) 2090 Functions.insert(&N.getFunction()); 2091 2092 if (Functions.empty()) 2093 return PreservedAnalyses::all(); 2094 2095 Module &M = *Functions.back()->getParent(); 2096 CallGraphUpdater CGUpdater; 2097 CGUpdater.initialize(CG, C, AM, UR); 2098 BumpPtrAllocator Allocator; 2099 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions); 2100 if (runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater)) { 2101 // FIXME: Think about passes we will preserve and add them here. 2102 return PreservedAnalyses::none(); 2103 } 2104 return PreservedAnalyses::all(); 2105 } 2106 2107 namespace { 2108 2109 struct AttributorLegacyPass : public ModulePass { 2110 static char ID; 2111 2112 AttributorLegacyPass() : ModulePass(ID) { 2113 initializeAttributorLegacyPassPass(*PassRegistry::getPassRegistry()); 2114 } 2115 2116 bool runOnModule(Module &M) override { 2117 if (skipModule(M)) 2118 return false; 2119 2120 AnalysisGetter AG; 2121 SetVector<Function *> Functions; 2122 for (Function &F : M) 2123 Functions.insert(&F); 2124 2125 CallGraphUpdater CGUpdater; 2126 BumpPtrAllocator Allocator; 2127 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr); 2128 return runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater); 2129 } 2130 2131 void getAnalysisUsage(AnalysisUsage &AU) const override { 2132 // FIXME: Think about passes we will preserve and add them here. 2133 AU.addRequired<TargetLibraryInfoWrapperPass>(); 2134 } 2135 }; 2136 2137 struct AttributorCGSCCLegacyPass : public CallGraphSCCPass { 2138 CallGraphUpdater CGUpdater; 2139 static char ID; 2140 2141 AttributorCGSCCLegacyPass() : CallGraphSCCPass(ID) { 2142 initializeAttributorCGSCCLegacyPassPass(*PassRegistry::getPassRegistry()); 2143 } 2144 2145 bool runOnSCC(CallGraphSCC &SCC) override { 2146 if (skipSCC(SCC)) 2147 return false; 2148 2149 SetVector<Function *> Functions; 2150 for (CallGraphNode *CGN : SCC) 2151 if (Function *Fn = CGN->getFunction()) 2152 if (!Fn->isDeclaration()) 2153 Functions.insert(Fn); 2154 2155 if (Functions.empty()) 2156 return false; 2157 2158 AnalysisGetter AG; 2159 CallGraph &CG = const_cast<CallGraph &>(SCC.getCallGraph()); 2160 CGUpdater.initialize(CG, SCC); 2161 Module &M = *Functions.back()->getParent(); 2162 BumpPtrAllocator Allocator; 2163 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions); 2164 return runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater); 2165 } 2166 2167 bool doFinalization(CallGraph &CG) override { return CGUpdater.finalize(); } 2168 2169 void getAnalysisUsage(AnalysisUsage &AU) const override { 2170 // FIXME: Think about passes we will preserve and add them here. 2171 AU.addRequired<TargetLibraryInfoWrapperPass>(); 2172 CallGraphSCCPass::getAnalysisUsage(AU); 2173 } 2174 }; 2175 2176 } // end anonymous namespace 2177 2178 Pass *llvm::createAttributorLegacyPass() { return new AttributorLegacyPass(); } 2179 Pass *llvm::createAttributorCGSCCLegacyPass() { 2180 return new AttributorCGSCCLegacyPass(); 2181 } 2182 2183 char AttributorLegacyPass::ID = 0; 2184 char AttributorCGSCCLegacyPass::ID = 0; 2185 2186 INITIALIZE_PASS_BEGIN(AttributorLegacyPass, "attributor", 2187 "Deduce and propagate attributes", false, false) 2188 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 2189 INITIALIZE_PASS_END(AttributorLegacyPass, "attributor", 2190 "Deduce and propagate attributes", false, false) 2191 INITIALIZE_PASS_BEGIN(AttributorCGSCCLegacyPass, "attributor-cgscc", 2192 "Deduce and propagate attributes (CGSCC pass)", false, 2193 false) 2194 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 2195 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) 2196 INITIALIZE_PASS_END(AttributorCGSCCLegacyPass, "attributor-cgscc", 2197 "Deduce and propagate attributes (CGSCC pass)", false, 2198 false) 2199