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/GraphTraits.h" 19 #include "llvm/ADT/PointerIntPair.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/ADT/TinyPtrVector.h" 23 #include "llvm/Analysis/InlineCost.h" 24 #include "llvm/Analysis/LazyValueInfo.h" 25 #include "llvm/Analysis/MemorySSAUpdater.h" 26 #include "llvm/Analysis/MustExecute.h" 27 #include "llvm/Analysis/ValueTracking.h" 28 #include "llvm/IR/Attributes.h" 29 #include "llvm/IR/Constant.h" 30 #include "llvm/IR/Constants.h" 31 #include "llvm/IR/GlobalValue.h" 32 #include "llvm/IR/IRBuilder.h" 33 #include "llvm/IR/Instruction.h" 34 #include "llvm/IR/IntrinsicInst.h" 35 #include "llvm/IR/NoFolder.h" 36 #include "llvm/IR/ValueHandle.h" 37 #include "llvm/IR/Verifier.h" 38 #include "llvm/InitializePasses.h" 39 #include "llvm/Support/Casting.h" 40 #include "llvm/Support/CommandLine.h" 41 #include "llvm/Support/Debug.h" 42 #include "llvm/Support/DebugCounter.h" 43 #include "llvm/Support/FileSystem.h" 44 #include "llvm/Support/GraphWriter.h" 45 #include "llvm/Support/raw_ostream.h" 46 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 47 #include "llvm/Transforms/Utils/Cloning.h" 48 #include "llvm/Transforms/Utils/Local.h" 49 50 #include <cassert> 51 #include <string> 52 53 using namespace llvm; 54 55 #define DEBUG_TYPE "attributor" 56 57 DEBUG_COUNTER(ManifestDBGCounter, "attributor-manifest", 58 "Determine what attributes are manifested in the IR"); 59 60 STATISTIC(NumFnDeleted, "Number of function deleted"); 61 STATISTIC(NumFnWithExactDefinition, 62 "Number of functions with exact definitions"); 63 STATISTIC(NumFnWithoutExactDefinition, 64 "Number of functions without exact definitions"); 65 STATISTIC(NumFnShallowWrappersCreated, "Number of shallow wrappers created"); 66 STATISTIC(NumAttributesTimedOut, 67 "Number of abstract attributes timed out before fixpoint"); 68 STATISTIC(NumAttributesValidFixpoint, 69 "Number of abstract attributes in a valid fixpoint state"); 70 STATISTIC(NumAttributesManifested, 71 "Number of abstract attributes manifested in IR"); 72 73 // TODO: Determine a good default value. 74 // 75 // In the LLVM-TS and SPEC2006, 32 seems to not induce compile time overheads 76 // (when run with the first 5 abstract attributes). The results also indicate 77 // that we never reach 32 iterations but always find a fixpoint sooner. 78 // 79 // This will become more evolved once we perform two interleaved fixpoint 80 // iterations: bottom-up and top-down. 81 static cl::opt<unsigned> 82 SetFixpointIterations("attributor-max-iterations", cl::Hidden, 83 cl::desc("Maximal number of fixpoint iterations."), 84 cl::init(32)); 85 86 static cl::opt<unsigned, true> MaxInitializationChainLengthX( 87 "attributor-max-initialization-chain-length", cl::Hidden, 88 cl::desc( 89 "Maximal number of chained initializations (to avoid stack overflows)"), 90 cl::location(MaxInitializationChainLength), cl::init(1024)); 91 unsigned llvm::MaxInitializationChainLength; 92 93 static cl::opt<bool> VerifyMaxFixpointIterations( 94 "attributor-max-iterations-verify", cl::Hidden, 95 cl::desc("Verify that max-iterations is a tight bound for a fixpoint"), 96 cl::init(false)); 97 98 static cl::opt<bool> AnnotateDeclarationCallSites( 99 "attributor-annotate-decl-cs", cl::Hidden, 100 cl::desc("Annotate call sites of function declarations."), cl::init(false)); 101 102 static cl::opt<bool> EnableHeapToStack("enable-heap-to-stack-conversion", 103 cl::init(true), cl::Hidden); 104 105 static cl::opt<bool> 106 AllowShallowWrappers("attributor-allow-shallow-wrappers", cl::Hidden, 107 cl::desc("Allow the Attributor to create shallow " 108 "wrappers for non-exact definitions."), 109 cl::init(false)); 110 111 static cl::opt<bool> 112 AllowDeepWrapper("attributor-allow-deep-wrappers", cl::Hidden, 113 cl::desc("Allow the Attributor to use IP information " 114 "derived from non-exact functions via cloning"), 115 cl::init(false)); 116 117 // These options can only used for debug builds. 118 #ifndef NDEBUG 119 static cl::list<std::string> 120 SeedAllowList("attributor-seed-allow-list", cl::Hidden, 121 cl::desc("Comma seperated list of attribute names that are " 122 "allowed to be seeded."), 123 cl::ZeroOrMore, cl::CommaSeparated); 124 125 static cl::list<std::string> FunctionSeedAllowList( 126 "attributor-function-seed-allow-list", cl::Hidden, 127 cl::desc("Comma seperated list of function names that are " 128 "allowed to be seeded."), 129 cl::ZeroOrMore, cl::CommaSeparated); 130 #endif 131 132 static cl::opt<bool> 133 DumpDepGraph("attributor-dump-dep-graph", cl::Hidden, 134 cl::desc("Dump the dependency graph to dot files."), 135 cl::init(false)); 136 137 static cl::opt<std::string> DepGraphDotFileNamePrefix( 138 "attributor-depgraph-dot-filename-prefix", cl::Hidden, 139 cl::desc("The prefix used for the CallGraph dot file names.")); 140 141 static cl::opt<bool> ViewDepGraph("attributor-view-dep-graph", cl::Hidden, 142 cl::desc("View the dependency graph."), 143 cl::init(false)); 144 145 static cl::opt<bool> PrintDependencies("attributor-print-dep", cl::Hidden, 146 cl::desc("Print attribute dependencies"), 147 cl::init(false)); 148 149 static cl::opt<bool> EnableCallSiteSpecific( 150 "attributor-enable-call-site-specific-deduction", cl::Hidden, 151 cl::desc("Allow the Attributor to do call site specific analysis"), 152 cl::init(false)); 153 154 static cl::opt<bool> 155 PrintCallGraph("attributor-print-call-graph", cl::Hidden, 156 cl::desc("Print Attributor's internal call graph"), 157 cl::init(false)); 158 159 static cl::opt<bool> SimplifyAllLoads("attributor-simplify-all-loads", 160 cl::Hidden, 161 cl::desc("Try to simplify all loads."), 162 cl::init(true)); 163 164 /// Logic operators for the change status enum class. 165 /// 166 ///{ 167 ChangeStatus llvm::operator|(ChangeStatus L, ChangeStatus R) { 168 return L == ChangeStatus::CHANGED ? L : R; 169 } 170 ChangeStatus &llvm::operator|=(ChangeStatus &L, ChangeStatus R) { 171 L = L | R; 172 return L; 173 } 174 ChangeStatus llvm::operator&(ChangeStatus L, ChangeStatus R) { 175 return L == ChangeStatus::UNCHANGED ? L : R; 176 } 177 ChangeStatus &llvm::operator&=(ChangeStatus &L, ChangeStatus R) { 178 L = L & R; 179 return L; 180 } 181 ///} 182 183 bool AA::isDynamicallyUnique(Attributor &A, const AbstractAttribute &QueryingAA, 184 const Value &V) { 185 if (auto *C = dyn_cast<Constant>(&V)) 186 return !C->isThreadDependent(); 187 // TODO: Inspect and cache more complex instructions. 188 if (auto *CB = dyn_cast<CallBase>(&V)) 189 return CB->getNumOperands() == 0 && !CB->mayHaveSideEffects() && 190 !CB->mayReadFromMemory(); 191 const Function *Scope = nullptr; 192 if (auto *I = dyn_cast<Instruction>(&V)) 193 Scope = I->getFunction(); 194 if (auto *A = dyn_cast<Argument>(&V)) 195 Scope = A->getParent(); 196 if (!Scope) 197 return false; 198 auto &NoRecurseAA = A.getAAFor<AANoRecurse>( 199 QueryingAA, IRPosition::function(*Scope), DepClassTy::OPTIONAL); 200 return NoRecurseAA.isAssumedNoRecurse(); 201 } 202 203 Constant *AA::getInitialValueForObj(Value &Obj, Type &Ty) { 204 if (isa<AllocaInst>(Obj)) 205 return UndefValue::get(&Ty); 206 auto *GV = dyn_cast<GlobalVariable>(&Obj); 207 if (!GV || !GV->hasLocalLinkage()) 208 return nullptr; 209 if (!GV->hasInitializer()) 210 return UndefValue::get(&Ty); 211 return dyn_cast_or_null<Constant>(getWithType(*GV->getInitializer(), Ty)); 212 } 213 214 bool AA::isValidInScope(const Value &V, const Function *Scope) { 215 if (isa<Constant>(V)) 216 return true; 217 if (auto *I = dyn_cast<Instruction>(&V)) 218 return I->getFunction() == Scope; 219 if (auto *A = dyn_cast<Argument>(&V)) 220 return A->getParent() == Scope; 221 return false; 222 } 223 224 bool AA::isValidAtPosition(const Value &V, const Instruction &CtxI, 225 InformationCache &InfoCache) { 226 if (isa<Constant>(V)) 227 return true; 228 const Function *Scope = CtxI.getFunction(); 229 if (auto *A = dyn_cast<Argument>(&V)) 230 return A->getParent() == Scope; 231 if (auto *I = dyn_cast<Instruction>(&V)) 232 if (I->getFunction() == Scope) { 233 const DominatorTree *DT = 234 InfoCache.getAnalysisResultForFunction<DominatorTreeAnalysis>(*Scope); 235 return DT && DT->dominates(I, &CtxI); 236 } 237 return false; 238 } 239 240 Value *AA::getWithType(Value &V, Type &Ty) { 241 if (V.getType() == &Ty) 242 return &V; 243 if (isa<PoisonValue>(V)) 244 return PoisonValue::get(&Ty); 245 if (isa<UndefValue>(V)) 246 return UndefValue::get(&Ty); 247 if (auto *C = dyn_cast<Constant>(&V)) { 248 if (C->isNullValue()) 249 return Constant::getNullValue(&Ty); 250 if (C->getType()->isPointerTy() && Ty.isPointerTy()) 251 return ConstantExpr::getPointerCast(C, &Ty); 252 if (C->getType()->isIntegerTy() && Ty.isIntegerTy()) 253 return ConstantExpr::getTrunc(C, &Ty, /* OnlyIfReduced */ true); 254 if (C->getType()->isFloatingPointTy() && Ty.isFloatingPointTy()) 255 return ConstantExpr::getFPTrunc(C, &Ty, /* OnlyIfReduced */ true); 256 } 257 return nullptr; 258 } 259 260 Optional<Value *> 261 AA::combineOptionalValuesInAAValueLatice(const Optional<Value *> &A, 262 const Optional<Value *> &B, Type *Ty) { 263 if (A == B) 264 return A; 265 if (!B.hasValue()) 266 return A; 267 if (*B == nullptr) 268 return nullptr; 269 if (!A.hasValue()) 270 return Ty ? getWithType(**B, *Ty) : nullptr; 271 if (*A == nullptr) 272 return nullptr; 273 if (!Ty) 274 Ty = (*A)->getType(); 275 if (isa_and_nonnull<UndefValue>(*A)) 276 return getWithType(**B, *Ty); 277 if (isa<UndefValue>(*B)) 278 return A; 279 if (*A && *B && *A == getWithType(**B, *Ty)) 280 return A; 281 return nullptr; 282 } 283 284 /// Return true if \p New is equal or worse than \p Old. 285 static bool isEqualOrWorse(const Attribute &New, const Attribute &Old) { 286 if (!Old.isIntAttribute()) 287 return true; 288 289 return Old.getValueAsInt() >= New.getValueAsInt(); 290 } 291 292 /// Return true if the information provided by \p Attr was added to the 293 /// attribute list \p Attrs. This is only the case if it was not already present 294 /// in \p Attrs at the position describe by \p PK and \p AttrIdx. 295 static bool addIfNotExistent(LLVMContext &Ctx, const Attribute &Attr, 296 AttributeList &Attrs, int AttrIdx) { 297 298 if (Attr.isEnumAttribute()) { 299 Attribute::AttrKind Kind = Attr.getKindAsEnum(); 300 if (Attrs.hasAttribute(AttrIdx, Kind)) 301 if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) 302 return false; 303 Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); 304 return true; 305 } 306 if (Attr.isStringAttribute()) { 307 StringRef Kind = Attr.getKindAsString(); 308 if (Attrs.hasAttribute(AttrIdx, Kind)) 309 if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) 310 return false; 311 Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); 312 return true; 313 } 314 if (Attr.isIntAttribute()) { 315 Attribute::AttrKind Kind = Attr.getKindAsEnum(); 316 if (Attrs.hasAttribute(AttrIdx, Kind)) 317 if (isEqualOrWorse(Attr, Attrs.getAttribute(AttrIdx, Kind))) 318 return false; 319 Attrs = Attrs.removeAttribute(Ctx, AttrIdx, Kind); 320 Attrs = Attrs.addAttribute(Ctx, AttrIdx, Attr); 321 return true; 322 } 323 324 llvm_unreachable("Expected enum or string attribute!"); 325 } 326 327 Argument *IRPosition::getAssociatedArgument() const { 328 if (getPositionKind() == IRP_ARGUMENT) 329 return cast<Argument>(&getAnchorValue()); 330 331 // Not an Argument and no argument number means this is not a call site 332 // argument, thus we cannot find a callback argument to return. 333 int ArgNo = getCallSiteArgNo(); 334 if (ArgNo < 0) 335 return nullptr; 336 337 // Use abstract call sites to make the connection between the call site 338 // values and the ones in callbacks. If a callback was found that makes use 339 // of the underlying call site operand, we want the corresponding callback 340 // callee argument and not the direct callee argument. 341 Optional<Argument *> CBCandidateArg; 342 SmallVector<const Use *, 4> CallbackUses; 343 const auto &CB = cast<CallBase>(getAnchorValue()); 344 AbstractCallSite::getCallbackUses(CB, CallbackUses); 345 for (const Use *U : CallbackUses) { 346 AbstractCallSite ACS(U); 347 assert(ACS && ACS.isCallbackCall()); 348 if (!ACS.getCalledFunction()) 349 continue; 350 351 for (unsigned u = 0, e = ACS.getNumArgOperands(); u < e; u++) { 352 353 // Test if the underlying call site operand is argument number u of the 354 // callback callee. 355 if (ACS.getCallArgOperandNo(u) != ArgNo) 356 continue; 357 358 assert(ACS.getCalledFunction()->arg_size() > u && 359 "ACS mapped into var-args arguments!"); 360 if (CBCandidateArg.hasValue()) { 361 CBCandidateArg = nullptr; 362 break; 363 } 364 CBCandidateArg = ACS.getCalledFunction()->getArg(u); 365 } 366 } 367 368 // If we found a unique callback candidate argument, return it. 369 if (CBCandidateArg.hasValue() && CBCandidateArg.getValue()) 370 return CBCandidateArg.getValue(); 371 372 // If no callbacks were found, or none used the underlying call site operand 373 // exclusively, use the direct callee argument if available. 374 const Function *Callee = CB.getCalledFunction(); 375 if (Callee && Callee->arg_size() > unsigned(ArgNo)) 376 return Callee->getArg(ArgNo); 377 378 return nullptr; 379 } 380 381 ChangeStatus AbstractAttribute::update(Attributor &A) { 382 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 383 if (getState().isAtFixpoint()) 384 return HasChanged; 385 386 LLVM_DEBUG(dbgs() << "[Attributor] Update: " << *this << "\n"); 387 388 HasChanged = updateImpl(A); 389 390 LLVM_DEBUG(dbgs() << "[Attributor] Update " << HasChanged << " " << *this 391 << "\n"); 392 393 return HasChanged; 394 } 395 396 ChangeStatus 397 IRAttributeManifest::manifestAttrs(Attributor &A, const IRPosition &IRP, 398 const ArrayRef<Attribute> &DeducedAttrs) { 399 Function *ScopeFn = IRP.getAnchorScope(); 400 IRPosition::Kind PK = IRP.getPositionKind(); 401 402 // In the following some generic code that will manifest attributes in 403 // DeducedAttrs if they improve the current IR. Due to the different 404 // annotation positions we use the underlying AttributeList interface. 405 406 AttributeList Attrs; 407 switch (PK) { 408 case IRPosition::IRP_INVALID: 409 case IRPosition::IRP_FLOAT: 410 return ChangeStatus::UNCHANGED; 411 case IRPosition::IRP_ARGUMENT: 412 case IRPosition::IRP_FUNCTION: 413 case IRPosition::IRP_RETURNED: 414 Attrs = ScopeFn->getAttributes(); 415 break; 416 case IRPosition::IRP_CALL_SITE: 417 case IRPosition::IRP_CALL_SITE_RETURNED: 418 case IRPosition::IRP_CALL_SITE_ARGUMENT: 419 Attrs = cast<CallBase>(IRP.getAnchorValue()).getAttributes(); 420 break; 421 } 422 423 ChangeStatus HasChanged = ChangeStatus::UNCHANGED; 424 LLVMContext &Ctx = IRP.getAnchorValue().getContext(); 425 for (const Attribute &Attr : DeducedAttrs) { 426 if (!addIfNotExistent(Ctx, Attr, Attrs, IRP.getAttrIdx())) 427 continue; 428 429 HasChanged = ChangeStatus::CHANGED; 430 } 431 432 if (HasChanged == ChangeStatus::UNCHANGED) 433 return HasChanged; 434 435 switch (PK) { 436 case IRPosition::IRP_ARGUMENT: 437 case IRPosition::IRP_FUNCTION: 438 case IRPosition::IRP_RETURNED: 439 ScopeFn->setAttributes(Attrs); 440 break; 441 case IRPosition::IRP_CALL_SITE: 442 case IRPosition::IRP_CALL_SITE_RETURNED: 443 case IRPosition::IRP_CALL_SITE_ARGUMENT: 444 cast<CallBase>(IRP.getAnchorValue()).setAttributes(Attrs); 445 break; 446 case IRPosition::IRP_INVALID: 447 case IRPosition::IRP_FLOAT: 448 break; 449 } 450 451 return HasChanged; 452 } 453 454 const IRPosition IRPosition::EmptyKey(DenseMapInfo<void *>::getEmptyKey()); 455 const IRPosition 456 IRPosition::TombstoneKey(DenseMapInfo<void *>::getTombstoneKey()); 457 458 SubsumingPositionIterator::SubsumingPositionIterator(const IRPosition &IRP) { 459 IRPositions.emplace_back(IRP); 460 461 // Helper to determine if operand bundles on a call site are benin or 462 // potentially problematic. We handle only llvm.assume for now. 463 auto CanIgnoreOperandBundles = [](const CallBase &CB) { 464 return (isa<IntrinsicInst>(CB) && 465 cast<IntrinsicInst>(CB).getIntrinsicID() == Intrinsic ::assume); 466 }; 467 468 const auto *CB = dyn_cast<CallBase>(&IRP.getAnchorValue()); 469 switch (IRP.getPositionKind()) { 470 case IRPosition::IRP_INVALID: 471 case IRPosition::IRP_FLOAT: 472 case IRPosition::IRP_FUNCTION: 473 return; 474 case IRPosition::IRP_ARGUMENT: 475 case IRPosition::IRP_RETURNED: 476 IRPositions.emplace_back(IRPosition::function(*IRP.getAnchorScope())); 477 return; 478 case IRPosition::IRP_CALL_SITE: 479 assert(CB && "Expected call site!"); 480 // TODO: We need to look at the operand bundles similar to the redirection 481 // in CallBase. 482 if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB)) 483 if (const Function *Callee = CB->getCalledFunction()) 484 IRPositions.emplace_back(IRPosition::function(*Callee)); 485 return; 486 case IRPosition::IRP_CALL_SITE_RETURNED: 487 assert(CB && "Expected call site!"); 488 // TODO: We need to look at the operand bundles similar to the redirection 489 // in CallBase. 490 if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB)) { 491 if (const Function *Callee = CB->getCalledFunction()) { 492 IRPositions.emplace_back(IRPosition::returned(*Callee)); 493 IRPositions.emplace_back(IRPosition::function(*Callee)); 494 for (const Argument &Arg : Callee->args()) 495 if (Arg.hasReturnedAttr()) { 496 IRPositions.emplace_back( 497 IRPosition::callsite_argument(*CB, Arg.getArgNo())); 498 IRPositions.emplace_back( 499 IRPosition::value(*CB->getArgOperand(Arg.getArgNo()))); 500 IRPositions.emplace_back(IRPosition::argument(Arg)); 501 } 502 } 503 } 504 IRPositions.emplace_back(IRPosition::callsite_function(*CB)); 505 return; 506 case IRPosition::IRP_CALL_SITE_ARGUMENT: { 507 assert(CB && "Expected call site!"); 508 // TODO: We need to look at the operand bundles similar to the redirection 509 // in CallBase. 510 if (!CB->hasOperandBundles() || CanIgnoreOperandBundles(*CB)) { 511 const Function *Callee = CB->getCalledFunction(); 512 if (Callee) { 513 if (Argument *Arg = IRP.getAssociatedArgument()) 514 IRPositions.emplace_back(IRPosition::argument(*Arg)); 515 IRPositions.emplace_back(IRPosition::function(*Callee)); 516 } 517 } 518 IRPositions.emplace_back(IRPosition::value(IRP.getAssociatedValue())); 519 return; 520 } 521 } 522 } 523 524 bool IRPosition::hasAttr(ArrayRef<Attribute::AttrKind> AKs, 525 bool IgnoreSubsumingPositions, Attributor *A) const { 526 SmallVector<Attribute, 4> Attrs; 527 for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) { 528 for (Attribute::AttrKind AK : AKs) 529 if (EquivIRP.getAttrsFromIRAttr(AK, Attrs)) 530 return true; 531 // The first position returned by the SubsumingPositionIterator is 532 // always the position itself. If we ignore subsuming positions we 533 // are done after the first iteration. 534 if (IgnoreSubsumingPositions) 535 break; 536 } 537 if (A) 538 for (Attribute::AttrKind AK : AKs) 539 if (getAttrsFromAssumes(AK, Attrs, *A)) 540 return true; 541 return false; 542 } 543 544 void IRPosition::getAttrs(ArrayRef<Attribute::AttrKind> AKs, 545 SmallVectorImpl<Attribute> &Attrs, 546 bool IgnoreSubsumingPositions, Attributor *A) const { 547 for (const IRPosition &EquivIRP : SubsumingPositionIterator(*this)) { 548 for (Attribute::AttrKind AK : AKs) 549 EquivIRP.getAttrsFromIRAttr(AK, Attrs); 550 // The first position returned by the SubsumingPositionIterator is 551 // always the position itself. If we ignore subsuming positions we 552 // are done after the first iteration. 553 if (IgnoreSubsumingPositions) 554 break; 555 } 556 if (A) 557 for (Attribute::AttrKind AK : AKs) 558 getAttrsFromAssumes(AK, Attrs, *A); 559 } 560 561 bool IRPosition::getAttrsFromIRAttr(Attribute::AttrKind AK, 562 SmallVectorImpl<Attribute> &Attrs) const { 563 if (getPositionKind() == IRP_INVALID || getPositionKind() == IRP_FLOAT) 564 return false; 565 566 AttributeList AttrList; 567 if (const auto *CB = dyn_cast<CallBase>(&getAnchorValue())) 568 AttrList = CB->getAttributes(); 569 else 570 AttrList = getAssociatedFunction()->getAttributes(); 571 572 bool HasAttr = AttrList.hasAttribute(getAttrIdx(), AK); 573 if (HasAttr) 574 Attrs.push_back(AttrList.getAttribute(getAttrIdx(), AK)); 575 return HasAttr; 576 } 577 578 bool IRPosition::getAttrsFromAssumes(Attribute::AttrKind AK, 579 SmallVectorImpl<Attribute> &Attrs, 580 Attributor &A) const { 581 assert(getPositionKind() != IRP_INVALID && "Did expect a valid position!"); 582 Value &AssociatedValue = getAssociatedValue(); 583 584 const Assume2KnowledgeMap &A2K = 585 A.getInfoCache().getKnowledgeMap().lookup({&AssociatedValue, AK}); 586 587 // Check if we found any potential assume use, if not we don't need to create 588 // explorer iterators. 589 if (A2K.empty()) 590 return false; 591 592 LLVMContext &Ctx = AssociatedValue.getContext(); 593 unsigned AttrsSize = Attrs.size(); 594 MustBeExecutedContextExplorer &Explorer = 595 A.getInfoCache().getMustBeExecutedContextExplorer(); 596 auto EIt = Explorer.begin(getCtxI()), EEnd = Explorer.end(getCtxI()); 597 for (auto &It : A2K) 598 if (Explorer.findInContextOf(It.first, EIt, EEnd)) 599 Attrs.push_back(Attribute::get(Ctx, AK, It.second.Max)); 600 return AttrsSize != Attrs.size(); 601 } 602 603 void IRPosition::verify() { 604 #ifdef EXPENSIVE_CHECKS 605 switch (getPositionKind()) { 606 case IRP_INVALID: 607 assert((CBContext == nullptr) && 608 "Invalid position must not have CallBaseContext!"); 609 assert(!Enc.getOpaqueValue() && 610 "Expected a nullptr for an invalid position!"); 611 return; 612 case IRP_FLOAT: 613 assert((!isa<CallBase>(&getAssociatedValue()) && 614 !isa<Argument>(&getAssociatedValue())) && 615 "Expected specialized kind for call base and argument values!"); 616 return; 617 case IRP_RETURNED: 618 assert(isa<Function>(getAsValuePtr()) && 619 "Expected function for a 'returned' position!"); 620 assert(getAsValuePtr() == &getAssociatedValue() && 621 "Associated value mismatch!"); 622 return; 623 case IRP_CALL_SITE_RETURNED: 624 assert((CBContext == nullptr) && 625 "'call site returned' position must not have CallBaseContext!"); 626 assert((isa<CallBase>(getAsValuePtr())) && 627 "Expected call base for 'call site returned' position!"); 628 assert(getAsValuePtr() == &getAssociatedValue() && 629 "Associated value mismatch!"); 630 return; 631 case IRP_CALL_SITE: 632 assert((CBContext == nullptr) && 633 "'call site function' position must not have CallBaseContext!"); 634 assert((isa<CallBase>(getAsValuePtr())) && 635 "Expected call base for 'call site function' position!"); 636 assert(getAsValuePtr() == &getAssociatedValue() && 637 "Associated value mismatch!"); 638 return; 639 case IRP_FUNCTION: 640 assert(isa<Function>(getAsValuePtr()) && 641 "Expected function for a 'function' position!"); 642 assert(getAsValuePtr() == &getAssociatedValue() && 643 "Associated value mismatch!"); 644 return; 645 case IRP_ARGUMENT: 646 assert(isa<Argument>(getAsValuePtr()) && 647 "Expected argument for a 'argument' position!"); 648 assert(getAsValuePtr() == &getAssociatedValue() && 649 "Associated value mismatch!"); 650 return; 651 case IRP_CALL_SITE_ARGUMENT: { 652 assert((CBContext == nullptr) && 653 "'call site argument' position must not have CallBaseContext!"); 654 Use *U = getAsUsePtr(); 655 assert(U && "Expected use for a 'call site argument' position!"); 656 assert(isa<CallBase>(U->getUser()) && 657 "Expected call base user for a 'call site argument' position!"); 658 assert(cast<CallBase>(U->getUser())->isArgOperand(U) && 659 "Expected call base argument operand for a 'call site argument' " 660 "position"); 661 assert(cast<CallBase>(U->getUser())->getArgOperandNo(U) == 662 unsigned(getCallSiteArgNo()) && 663 "Argument number mismatch!"); 664 assert(U->get() == &getAssociatedValue() && "Associated value mismatch!"); 665 return; 666 } 667 } 668 #endif 669 } 670 671 Optional<Constant *> 672 Attributor::getAssumedConstant(const IRPosition &IRP, 673 const AbstractAttribute &AA, 674 bool &UsedAssumedInformation) { 675 // First check all callbacks provided by outside AAs. If any of them returns 676 // a non-null value that is different from the associated value, or None, we 677 // assume it's simpliied. 678 for (auto &CB : SimplificationCallbacks[IRP]) { 679 Optional<Value *> SimplifiedV = CB(IRP, &AA, UsedAssumedInformation); 680 if (!SimplifiedV.hasValue()) 681 return llvm::None; 682 if (isa_and_nonnull<Constant>(*SimplifiedV)) 683 return cast<Constant>(*SimplifiedV); 684 return nullptr; 685 } 686 const auto &ValueSimplifyAA = 687 getAAFor<AAValueSimplify>(AA, IRP, DepClassTy::NONE); 688 Optional<Value *> SimplifiedV = 689 ValueSimplifyAA.getAssumedSimplifiedValue(*this); 690 bool IsKnown = ValueSimplifyAA.isAtFixpoint(); 691 UsedAssumedInformation |= !IsKnown; 692 if (!SimplifiedV.hasValue()) { 693 recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL); 694 return llvm::None; 695 } 696 if (isa_and_nonnull<UndefValue>(SimplifiedV.getValue())) { 697 recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL); 698 return UndefValue::get(IRP.getAssociatedType()); 699 } 700 Constant *CI = dyn_cast_or_null<Constant>(SimplifiedV.getValue()); 701 if (CI) 702 CI = dyn_cast_or_null<Constant>( 703 AA::getWithType(*CI, *IRP.getAssociatedType())); 704 if (CI) 705 recordDependence(ValueSimplifyAA, AA, DepClassTy::OPTIONAL); 706 return CI; 707 } 708 709 Optional<Value *> 710 Attributor::getAssumedSimplified(const IRPosition &IRP, 711 const AbstractAttribute *AA, 712 bool &UsedAssumedInformation) { 713 // First check all callbacks provided by outside AAs. If any of them returns 714 // a non-null value that is different from the associated value, or None, we 715 // assume it's simpliied. 716 for (auto &CB : SimplificationCallbacks[IRP]) { 717 Optional<Value *> SimplifiedV = CB(IRP, AA, UsedAssumedInformation); 718 return SimplifiedV; 719 } 720 721 // If no high-level/outside simplification occured, use AAValueSimplify. 722 const auto &ValueSimplifyAA = 723 getOrCreateAAFor<AAValueSimplify>(IRP, AA, DepClassTy::NONE); 724 Optional<Value *> SimplifiedV = 725 ValueSimplifyAA.getAssumedSimplifiedValue(*this); 726 bool IsKnown = ValueSimplifyAA.isAtFixpoint(); 727 UsedAssumedInformation |= !IsKnown; 728 if (!SimplifiedV.hasValue()) { 729 if (AA) 730 recordDependence(ValueSimplifyAA, *AA, DepClassTy::OPTIONAL); 731 return llvm::None; 732 } 733 if (*SimplifiedV == nullptr) 734 return const_cast<Value *>(&IRP.getAssociatedValue()); 735 if (Value *SimpleV = 736 AA::getWithType(**SimplifiedV, *IRP.getAssociatedType())) { 737 if (AA) 738 recordDependence(ValueSimplifyAA, *AA, DepClassTy::OPTIONAL); 739 return SimpleV; 740 } 741 return const_cast<Value *>(&IRP.getAssociatedValue()); 742 } 743 744 Optional<Value *> Attributor::translateArgumentToCallSiteContent( 745 Optional<Value *> V, CallBase &CB, const AbstractAttribute &AA, 746 bool &UsedAssumedInformation) { 747 if (!V.hasValue()) 748 return V; 749 if (*V == nullptr || isa<Constant>(*V)) 750 return V; 751 if (auto *Arg = dyn_cast<Argument>(*V)) 752 if (CB.getCalledFunction() == Arg->getParent()) 753 if (!Arg->hasPointeeInMemoryValueAttr()) 754 return getAssumedSimplified( 755 IRPosition::callsite_argument(CB, Arg->getArgNo()), AA, 756 UsedAssumedInformation); 757 return nullptr; 758 } 759 760 Attributor::~Attributor() { 761 // The abstract attributes are allocated via the BumpPtrAllocator Allocator, 762 // thus we cannot delete them. We can, and want to, destruct them though. 763 for (auto &DepAA : DG.SyntheticRoot.Deps) { 764 AbstractAttribute *AA = cast<AbstractAttribute>(DepAA.getPointer()); 765 AA->~AbstractAttribute(); 766 } 767 } 768 769 bool Attributor::isAssumedDead(const AbstractAttribute &AA, 770 const AAIsDead *FnLivenessAA, 771 bool &UsedAssumedInformation, 772 bool CheckBBLivenessOnly, DepClassTy DepClass) { 773 const IRPosition &IRP = AA.getIRPosition(); 774 if (!Functions.count(IRP.getAnchorScope())) 775 return false; 776 return isAssumedDead(IRP, &AA, FnLivenessAA, UsedAssumedInformation, 777 CheckBBLivenessOnly, DepClass); 778 } 779 780 bool Attributor::isAssumedDead(const Use &U, 781 const AbstractAttribute *QueryingAA, 782 const AAIsDead *FnLivenessAA, 783 bool &UsedAssumedInformation, 784 bool CheckBBLivenessOnly, DepClassTy DepClass) { 785 Instruction *UserI = dyn_cast<Instruction>(U.getUser()); 786 if (!UserI) 787 return isAssumedDead(IRPosition::value(*U.get()), QueryingAA, FnLivenessAA, 788 UsedAssumedInformation, CheckBBLivenessOnly, DepClass); 789 790 if (auto *CB = dyn_cast<CallBase>(UserI)) { 791 // For call site argument uses we can check if the argument is 792 // unused/dead. 793 if (CB->isArgOperand(&U)) { 794 const IRPosition &CSArgPos = 795 IRPosition::callsite_argument(*CB, CB->getArgOperandNo(&U)); 796 return isAssumedDead(CSArgPos, QueryingAA, FnLivenessAA, 797 UsedAssumedInformation, CheckBBLivenessOnly, 798 DepClass); 799 } 800 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(UserI)) { 801 const IRPosition &RetPos = IRPosition::returned(*RI->getFunction()); 802 return isAssumedDead(RetPos, QueryingAA, FnLivenessAA, 803 UsedAssumedInformation, CheckBBLivenessOnly, DepClass); 804 } else if (PHINode *PHI = dyn_cast<PHINode>(UserI)) { 805 BasicBlock *IncomingBB = PHI->getIncomingBlock(U); 806 return isAssumedDead(*IncomingBB->getTerminator(), QueryingAA, FnLivenessAA, 807 UsedAssumedInformation, CheckBBLivenessOnly, DepClass); 808 } 809 810 return isAssumedDead(IRPosition::value(*UserI), QueryingAA, FnLivenessAA, 811 UsedAssumedInformation, CheckBBLivenessOnly, DepClass); 812 } 813 814 bool Attributor::isAssumedDead(const Instruction &I, 815 const AbstractAttribute *QueryingAA, 816 const AAIsDead *FnLivenessAA, 817 bool &UsedAssumedInformation, 818 bool CheckBBLivenessOnly, DepClassTy DepClass) { 819 const IRPosition::CallBaseContext *CBCtx = 820 QueryingAA ? QueryingAA->getCallBaseContext() : nullptr; 821 822 if (ManifestAddedBlocks.contains(I.getParent())) 823 return false; 824 825 if (!FnLivenessAA) 826 FnLivenessAA = 827 lookupAAFor<AAIsDead>(IRPosition::function(*I.getFunction(), CBCtx), 828 QueryingAA, DepClassTy::NONE); 829 830 // If we have a context instruction and a liveness AA we use it. 831 if (FnLivenessAA && 832 FnLivenessAA->getIRPosition().getAnchorScope() == I.getFunction() && 833 FnLivenessAA->isAssumedDead(&I)) { 834 if (QueryingAA) 835 recordDependence(*FnLivenessAA, *QueryingAA, DepClass); 836 if (!FnLivenessAA->isKnownDead(&I)) 837 UsedAssumedInformation = true; 838 return true; 839 } 840 841 if (CheckBBLivenessOnly) 842 return false; 843 844 const AAIsDead &IsDeadAA = getOrCreateAAFor<AAIsDead>( 845 IRPosition::value(I, CBCtx), QueryingAA, DepClassTy::NONE); 846 // Don't check liveness for AAIsDead. 847 if (QueryingAA == &IsDeadAA) 848 return false; 849 850 if (IsDeadAA.isAssumedDead()) { 851 if (QueryingAA) 852 recordDependence(IsDeadAA, *QueryingAA, DepClass); 853 if (!IsDeadAA.isKnownDead()) 854 UsedAssumedInformation = true; 855 return true; 856 } 857 858 return false; 859 } 860 861 bool Attributor::isAssumedDead(const IRPosition &IRP, 862 const AbstractAttribute *QueryingAA, 863 const AAIsDead *FnLivenessAA, 864 bool &UsedAssumedInformation, 865 bool CheckBBLivenessOnly, DepClassTy DepClass) { 866 Instruction *CtxI = IRP.getCtxI(); 867 if (CtxI && 868 isAssumedDead(*CtxI, QueryingAA, FnLivenessAA, UsedAssumedInformation, 869 /* CheckBBLivenessOnly */ true, 870 CheckBBLivenessOnly ? DepClass : DepClassTy::OPTIONAL)) 871 return true; 872 873 if (CheckBBLivenessOnly) 874 return false; 875 876 // If we haven't succeeded we query the specific liveness info for the IRP. 877 const AAIsDead *IsDeadAA; 878 if (IRP.getPositionKind() == IRPosition::IRP_CALL_SITE) 879 IsDeadAA = &getOrCreateAAFor<AAIsDead>( 880 IRPosition::callsite_returned(cast<CallBase>(IRP.getAssociatedValue())), 881 QueryingAA, DepClassTy::NONE); 882 else 883 IsDeadAA = &getOrCreateAAFor<AAIsDead>(IRP, QueryingAA, DepClassTy::NONE); 884 // Don't check liveness for AAIsDead. 885 if (QueryingAA == IsDeadAA) 886 return false; 887 888 if (IsDeadAA->isAssumedDead()) { 889 if (QueryingAA) 890 recordDependence(*IsDeadAA, *QueryingAA, DepClass); 891 if (!IsDeadAA->isKnownDead()) 892 UsedAssumedInformation = true; 893 return true; 894 } 895 896 return false; 897 } 898 899 bool Attributor::checkForAllUses(function_ref<bool(const Use &, bool &)> Pred, 900 const AbstractAttribute &QueryingAA, 901 const Value &V, bool CheckBBLivenessOnly, 902 DepClassTy LivenessDepClass) { 903 904 // Check the trivial case first as it catches void values. 905 if (V.use_empty()) 906 return true; 907 908 const IRPosition &IRP = QueryingAA.getIRPosition(); 909 SmallVector<const Use *, 16> Worklist; 910 SmallPtrSet<const Use *, 16> Visited; 911 912 for (const Use &U : V.uses()) 913 Worklist.push_back(&U); 914 915 LLVM_DEBUG(dbgs() << "[Attributor] Got " << Worklist.size() 916 << " initial uses to check\n"); 917 918 const Function *ScopeFn = IRP.getAnchorScope(); 919 const auto *LivenessAA = 920 ScopeFn ? &getAAFor<AAIsDead>(QueryingAA, IRPosition::function(*ScopeFn), 921 DepClassTy::NONE) 922 : nullptr; 923 924 while (!Worklist.empty()) { 925 const Use *U = Worklist.pop_back_val(); 926 if (!Visited.insert(U).second) 927 continue; 928 LLVM_DEBUG(dbgs() << "[Attributor] Check use: " << **U << " in " 929 << *U->getUser() << "\n"); 930 bool UsedAssumedInformation = false; 931 if (isAssumedDead(*U, &QueryingAA, LivenessAA, UsedAssumedInformation, 932 CheckBBLivenessOnly, LivenessDepClass)) { 933 LLVM_DEBUG(dbgs() << "[Attributor] Dead use, skip!\n"); 934 continue; 935 } 936 if (U->getUser()->isDroppable()) { 937 LLVM_DEBUG(dbgs() << "[Attributor] Droppable user, skip!\n"); 938 continue; 939 } 940 941 bool Follow = false; 942 if (!Pred(*U, Follow)) 943 return false; 944 if (!Follow) 945 continue; 946 for (const Use &UU : U->getUser()->uses()) 947 Worklist.push_back(&UU); 948 } 949 950 return true; 951 } 952 953 bool Attributor::checkForAllCallSites(function_ref<bool(AbstractCallSite)> Pred, 954 const AbstractAttribute &QueryingAA, 955 bool RequireAllCallSites, 956 bool &AllCallSitesKnown) { 957 // We can try to determine information from 958 // the call sites. However, this is only possible all call sites are known, 959 // hence the function has internal linkage. 960 const IRPosition &IRP = QueryingAA.getIRPosition(); 961 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 962 if (!AssociatedFunction) { 963 LLVM_DEBUG(dbgs() << "[Attributor] No function associated with " << IRP 964 << "\n"); 965 AllCallSitesKnown = false; 966 return false; 967 } 968 969 return checkForAllCallSites(Pred, *AssociatedFunction, RequireAllCallSites, 970 &QueryingAA, AllCallSitesKnown); 971 } 972 973 bool Attributor::checkForAllCallSites(function_ref<bool(AbstractCallSite)> Pred, 974 const Function &Fn, 975 bool RequireAllCallSites, 976 const AbstractAttribute *QueryingAA, 977 bool &AllCallSitesKnown) { 978 if (RequireAllCallSites && !Fn.hasLocalLinkage()) { 979 LLVM_DEBUG( 980 dbgs() 981 << "[Attributor] Function " << Fn.getName() 982 << " has no internal linkage, hence not all call sites are known\n"); 983 AllCallSitesKnown = false; 984 return false; 985 } 986 987 // If we do not require all call sites we might not see all. 988 AllCallSitesKnown = RequireAllCallSites; 989 990 SmallVector<const Use *, 8> Uses(make_pointer_range(Fn.uses())); 991 for (unsigned u = 0; u < Uses.size(); ++u) { 992 const Use &U = *Uses[u]; 993 LLVM_DEBUG(dbgs() << "[Attributor] Check use: " << *U << " in " 994 << *U.getUser() << "\n"); 995 bool UsedAssumedInformation = false; 996 if (isAssumedDead(U, QueryingAA, nullptr, UsedAssumedInformation, 997 /* CheckBBLivenessOnly */ true)) { 998 LLVM_DEBUG(dbgs() << "[Attributor] Dead use, skip!\n"); 999 continue; 1000 } 1001 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U.getUser())) { 1002 if (CE->isCast() && CE->getType()->isPointerTy() && 1003 CE->getType()->getPointerElementType()->isFunctionTy()) { 1004 for (const Use &CEU : CE->uses()) 1005 Uses.push_back(&CEU); 1006 continue; 1007 } 1008 } 1009 1010 AbstractCallSite ACS(&U); 1011 if (!ACS) { 1012 LLVM_DEBUG(dbgs() << "[Attributor] Function " << Fn.getName() 1013 << " has non call site use " << *U.get() << " in " 1014 << *U.getUser() << "\n"); 1015 // BlockAddress users are allowed. 1016 if (isa<BlockAddress>(U.getUser())) 1017 continue; 1018 return false; 1019 } 1020 1021 const Use *EffectiveUse = 1022 ACS.isCallbackCall() ? &ACS.getCalleeUseForCallback() : &U; 1023 if (!ACS.isCallee(EffectiveUse)) { 1024 if (!RequireAllCallSites) 1025 continue; 1026 LLVM_DEBUG(dbgs() << "[Attributor] User " << EffectiveUse->getUser() 1027 << " is an invalid use of " << Fn.getName() << "\n"); 1028 return false; 1029 } 1030 1031 // Make sure the arguments that can be matched between the call site and the 1032 // callee argee on their type. It is unlikely they do not and it doesn't 1033 // make sense for all attributes to know/care about this. 1034 assert(&Fn == ACS.getCalledFunction() && "Expected known callee"); 1035 unsigned MinArgsParams = 1036 std::min(size_t(ACS.getNumArgOperands()), Fn.arg_size()); 1037 for (unsigned u = 0; u < MinArgsParams; ++u) { 1038 Value *CSArgOp = ACS.getCallArgOperand(u); 1039 if (CSArgOp && Fn.getArg(u)->getType() != CSArgOp->getType()) { 1040 LLVM_DEBUG( 1041 dbgs() << "[Attributor] Call site / callee argument type mismatch [" 1042 << u << "@" << Fn.getName() << ": " 1043 << *Fn.getArg(u)->getType() << " vs. " 1044 << *ACS.getCallArgOperand(u)->getType() << "\n"); 1045 return false; 1046 } 1047 } 1048 1049 if (Pred(ACS)) 1050 continue; 1051 1052 LLVM_DEBUG(dbgs() << "[Attributor] Call site callback failed for " 1053 << *ACS.getInstruction() << "\n"); 1054 return false; 1055 } 1056 1057 return true; 1058 } 1059 1060 bool Attributor::shouldPropagateCallBaseContext(const IRPosition &IRP) { 1061 // TODO: Maintain a cache of Values that are 1062 // on the pathway from a Argument to a Instruction that would effect the 1063 // liveness/return state etc. 1064 return EnableCallSiteSpecific; 1065 } 1066 1067 bool Attributor::checkForAllReturnedValuesAndReturnInsts( 1068 function_ref<bool(Value &, const SmallSetVector<ReturnInst *, 4> &)> Pred, 1069 const AbstractAttribute &QueryingAA) { 1070 1071 const IRPosition &IRP = QueryingAA.getIRPosition(); 1072 // Since we need to provide return instructions we have to have an exact 1073 // definition. 1074 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 1075 if (!AssociatedFunction) 1076 return false; 1077 1078 // If this is a call site query we use the call site specific return values 1079 // and liveness information. 1080 // TODO: use the function scope once we have call site AAReturnedValues. 1081 const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction); 1082 const auto &AARetVal = 1083 getAAFor<AAReturnedValues>(QueryingAA, QueryIRP, DepClassTy::REQUIRED); 1084 if (!AARetVal.getState().isValidState()) 1085 return false; 1086 1087 return AARetVal.checkForAllReturnedValuesAndReturnInsts(Pred); 1088 } 1089 1090 bool Attributor::checkForAllReturnedValues( 1091 function_ref<bool(Value &)> Pred, const AbstractAttribute &QueryingAA) { 1092 1093 const IRPosition &IRP = QueryingAA.getIRPosition(); 1094 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 1095 if (!AssociatedFunction) 1096 return false; 1097 1098 // TODO: use the function scope once we have call site AAReturnedValues. 1099 const IRPosition &QueryIRP = IRPosition::function( 1100 *AssociatedFunction, QueryingAA.getCallBaseContext()); 1101 const auto &AARetVal = 1102 getAAFor<AAReturnedValues>(QueryingAA, QueryIRP, DepClassTy::REQUIRED); 1103 if (!AARetVal.getState().isValidState()) 1104 return false; 1105 1106 return AARetVal.checkForAllReturnedValuesAndReturnInsts( 1107 [&](Value &RV, const SmallSetVector<ReturnInst *, 4> &) { 1108 return Pred(RV); 1109 }); 1110 } 1111 1112 static bool checkForAllInstructionsImpl( 1113 Attributor *A, InformationCache::OpcodeInstMapTy &OpcodeInstMap, 1114 function_ref<bool(Instruction &)> Pred, const AbstractAttribute *QueryingAA, 1115 const AAIsDead *LivenessAA, const ArrayRef<unsigned> &Opcodes, 1116 bool &UsedAssumedInformation, bool CheckBBLivenessOnly = false, 1117 bool CheckPotentiallyDead = false) { 1118 for (unsigned Opcode : Opcodes) { 1119 // Check if we have instructions with this opcode at all first. 1120 auto *Insts = OpcodeInstMap.lookup(Opcode); 1121 if (!Insts) 1122 continue; 1123 1124 for (Instruction *I : *Insts) { 1125 // Skip dead instructions. 1126 if (A && !CheckPotentiallyDead && 1127 A->isAssumedDead(IRPosition::value(*I), QueryingAA, LivenessAA, 1128 UsedAssumedInformation, CheckBBLivenessOnly)) 1129 continue; 1130 1131 if (!Pred(*I)) 1132 return false; 1133 } 1134 } 1135 return true; 1136 } 1137 1138 bool Attributor::checkForAllInstructions(function_ref<bool(Instruction &)> Pred, 1139 const AbstractAttribute &QueryingAA, 1140 const ArrayRef<unsigned> &Opcodes, 1141 bool &UsedAssumedInformation, 1142 bool CheckBBLivenessOnly, 1143 bool CheckPotentiallyDead) { 1144 1145 const IRPosition &IRP = QueryingAA.getIRPosition(); 1146 // Since we need to provide instructions we have to have an exact definition. 1147 const Function *AssociatedFunction = IRP.getAssociatedFunction(); 1148 if (!AssociatedFunction) 1149 return false; 1150 1151 // TODO: use the function scope once we have call site AAReturnedValues. 1152 const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction); 1153 const auto *LivenessAA = 1154 (CheckBBLivenessOnly || CheckPotentiallyDead) 1155 ? nullptr 1156 : &(getAAFor<AAIsDead>(QueryingAA, QueryIRP, DepClassTy::NONE)); 1157 1158 auto &OpcodeInstMap = 1159 InfoCache.getOpcodeInstMapForFunction(*AssociatedFunction); 1160 if (!checkForAllInstructionsImpl(this, OpcodeInstMap, Pred, &QueryingAA, 1161 LivenessAA, Opcodes, UsedAssumedInformation, 1162 CheckBBLivenessOnly, CheckPotentiallyDead)) 1163 return false; 1164 1165 return true; 1166 } 1167 1168 bool Attributor::checkForAllReadWriteInstructions( 1169 function_ref<bool(Instruction &)> Pred, AbstractAttribute &QueryingAA, 1170 bool &UsedAssumedInformation) { 1171 1172 const Function *AssociatedFunction = 1173 QueryingAA.getIRPosition().getAssociatedFunction(); 1174 if (!AssociatedFunction) 1175 return false; 1176 1177 // TODO: use the function scope once we have call site AAReturnedValues. 1178 const IRPosition &QueryIRP = IRPosition::function(*AssociatedFunction); 1179 const auto &LivenessAA = 1180 getAAFor<AAIsDead>(QueryingAA, QueryIRP, DepClassTy::NONE); 1181 1182 for (Instruction *I : 1183 InfoCache.getReadOrWriteInstsForFunction(*AssociatedFunction)) { 1184 // Skip dead instructions. 1185 if (isAssumedDead(IRPosition::value(*I), &QueryingAA, &LivenessAA, 1186 UsedAssumedInformation)) 1187 continue; 1188 1189 if (!Pred(*I)) 1190 return false; 1191 } 1192 1193 return true; 1194 } 1195 1196 void Attributor::runTillFixpoint() { 1197 TimeTraceScope TimeScope("Attributor::runTillFixpoint"); 1198 LLVM_DEBUG(dbgs() << "[Attributor] Identified and initialized " 1199 << DG.SyntheticRoot.Deps.size() 1200 << " abstract attributes.\n"); 1201 1202 // Now that all abstract attributes are collected and initialized we start 1203 // the abstract analysis. 1204 1205 unsigned IterationCounter = 1; 1206 unsigned MaxFixedPointIterations; 1207 if (MaxFixpointIterations) 1208 MaxFixedPointIterations = MaxFixpointIterations.getValue(); 1209 else 1210 MaxFixedPointIterations = SetFixpointIterations; 1211 1212 SmallVector<AbstractAttribute *, 32> ChangedAAs; 1213 SetVector<AbstractAttribute *> Worklist, InvalidAAs; 1214 Worklist.insert(DG.SyntheticRoot.begin(), DG.SyntheticRoot.end()); 1215 1216 do { 1217 // Remember the size to determine new attributes. 1218 size_t NumAAs = DG.SyntheticRoot.Deps.size(); 1219 LLVM_DEBUG(dbgs() << "\n\n[Attributor] #Iteration: " << IterationCounter 1220 << ", Worklist size: " << Worklist.size() << "\n"); 1221 1222 // For invalid AAs we can fix dependent AAs that have a required dependence, 1223 // thereby folding long dependence chains in a single step without the need 1224 // to run updates. 1225 for (unsigned u = 0; u < InvalidAAs.size(); ++u) { 1226 AbstractAttribute *InvalidAA = InvalidAAs[u]; 1227 1228 // Check the dependences to fast track invalidation. 1229 LLVM_DEBUG(dbgs() << "[Attributor] InvalidAA: " << *InvalidAA << " has " 1230 << InvalidAA->Deps.size() 1231 << " required & optional dependences\n"); 1232 while (!InvalidAA->Deps.empty()) { 1233 const auto &Dep = InvalidAA->Deps.back(); 1234 InvalidAA->Deps.pop_back(); 1235 AbstractAttribute *DepAA = cast<AbstractAttribute>(Dep.getPointer()); 1236 if (Dep.getInt() == unsigned(DepClassTy::OPTIONAL)) { 1237 Worklist.insert(DepAA); 1238 continue; 1239 } 1240 DepAA->getState().indicatePessimisticFixpoint(); 1241 assert(DepAA->getState().isAtFixpoint() && "Expected fixpoint state!"); 1242 if (!DepAA->getState().isValidState()) 1243 InvalidAAs.insert(DepAA); 1244 else 1245 ChangedAAs.push_back(DepAA); 1246 } 1247 } 1248 1249 // Add all abstract attributes that are potentially dependent on one that 1250 // changed to the work list. 1251 for (AbstractAttribute *ChangedAA : ChangedAAs) 1252 while (!ChangedAA->Deps.empty()) { 1253 Worklist.insert( 1254 cast<AbstractAttribute>(ChangedAA->Deps.back().getPointer())); 1255 ChangedAA->Deps.pop_back(); 1256 } 1257 1258 LLVM_DEBUG(dbgs() << "[Attributor] #Iteration: " << IterationCounter 1259 << ", Worklist+Dependent size: " << Worklist.size() 1260 << "\n"); 1261 1262 // Reset the changed and invalid set. 1263 ChangedAAs.clear(); 1264 InvalidAAs.clear(); 1265 1266 // Update all abstract attribute in the work list and record the ones that 1267 // changed. 1268 for (AbstractAttribute *AA : Worklist) { 1269 const auto &AAState = AA->getState(); 1270 if (!AAState.isAtFixpoint()) 1271 if (updateAA(*AA) == ChangeStatus::CHANGED) 1272 ChangedAAs.push_back(AA); 1273 1274 // Use the InvalidAAs vector to propagate invalid states fast transitively 1275 // without requiring updates. 1276 if (!AAState.isValidState()) 1277 InvalidAAs.insert(AA); 1278 } 1279 1280 // Add attributes to the changed set if they have been created in the last 1281 // iteration. 1282 ChangedAAs.append(DG.SyntheticRoot.begin() + NumAAs, 1283 DG.SyntheticRoot.end()); 1284 1285 // Reset the work list and repopulate with the changed abstract attributes. 1286 // Note that dependent ones are added above. 1287 Worklist.clear(); 1288 Worklist.insert(ChangedAAs.begin(), ChangedAAs.end()); 1289 1290 } while (!Worklist.empty() && (IterationCounter++ < MaxFixedPointIterations || 1291 VerifyMaxFixpointIterations)); 1292 1293 LLVM_DEBUG(dbgs() << "\n[Attributor] Fixpoint iteration done after: " 1294 << IterationCounter << "/" << MaxFixpointIterations 1295 << " iterations\n"); 1296 1297 // Reset abstract arguments not settled in a sound fixpoint by now. This 1298 // happens when we stopped the fixpoint iteration early. Note that only the 1299 // ones marked as "changed" *and* the ones transitively depending on them 1300 // need to be reverted to a pessimistic state. Others might not be in a 1301 // fixpoint state but we can use the optimistic results for them anyway. 1302 SmallPtrSet<AbstractAttribute *, 32> Visited; 1303 for (unsigned u = 0; u < ChangedAAs.size(); u++) { 1304 AbstractAttribute *ChangedAA = ChangedAAs[u]; 1305 if (!Visited.insert(ChangedAA).second) 1306 continue; 1307 1308 AbstractState &State = ChangedAA->getState(); 1309 if (!State.isAtFixpoint()) { 1310 State.indicatePessimisticFixpoint(); 1311 1312 NumAttributesTimedOut++; 1313 } 1314 1315 while (!ChangedAA->Deps.empty()) { 1316 ChangedAAs.push_back( 1317 cast<AbstractAttribute>(ChangedAA->Deps.back().getPointer())); 1318 ChangedAA->Deps.pop_back(); 1319 } 1320 } 1321 1322 LLVM_DEBUG({ 1323 if (!Visited.empty()) 1324 dbgs() << "\n[Attributor] Finalized " << Visited.size() 1325 << " abstract attributes.\n"; 1326 }); 1327 1328 if (VerifyMaxFixpointIterations && 1329 IterationCounter != MaxFixedPointIterations) { 1330 errs() << "\n[Attributor] Fixpoint iteration done after: " 1331 << IterationCounter << "/" << MaxFixedPointIterations 1332 << " iterations\n"; 1333 llvm_unreachable("The fixpoint was not reached with exactly the number of " 1334 "specified iterations!"); 1335 } 1336 } 1337 1338 ChangeStatus Attributor::manifestAttributes() { 1339 TimeTraceScope TimeScope("Attributor::manifestAttributes"); 1340 size_t NumFinalAAs = DG.SyntheticRoot.Deps.size(); 1341 1342 unsigned NumManifested = 0; 1343 unsigned NumAtFixpoint = 0; 1344 ChangeStatus ManifestChange = ChangeStatus::UNCHANGED; 1345 for (auto &DepAA : DG.SyntheticRoot.Deps) { 1346 AbstractAttribute *AA = cast<AbstractAttribute>(DepAA.getPointer()); 1347 AbstractState &State = AA->getState(); 1348 1349 // If there is not already a fixpoint reached, we can now take the 1350 // optimistic state. This is correct because we enforced a pessimistic one 1351 // on abstract attributes that were transitively dependent on a changed one 1352 // already above. 1353 if (!State.isAtFixpoint()) 1354 State.indicateOptimisticFixpoint(); 1355 1356 // We must not manifest Attributes that use Callbase info. 1357 if (AA->hasCallBaseContext()) 1358 continue; 1359 // If the state is invalid, we do not try to manifest it. 1360 if (!State.isValidState()) 1361 continue; 1362 1363 // Skip dead code. 1364 bool UsedAssumedInformation = false; 1365 if (isAssumedDead(*AA, nullptr, UsedAssumedInformation, 1366 /* CheckBBLivenessOnly */ true)) 1367 continue; 1368 // Check if the manifest debug counter that allows skipping manifestation of 1369 // AAs 1370 if (!DebugCounter::shouldExecute(ManifestDBGCounter)) 1371 continue; 1372 // Manifest the state and record if we changed the IR. 1373 ChangeStatus LocalChange = AA->manifest(*this); 1374 if (LocalChange == ChangeStatus::CHANGED && AreStatisticsEnabled()) 1375 AA->trackStatistics(); 1376 LLVM_DEBUG(dbgs() << "[Attributor] Manifest " << LocalChange << " : " << *AA 1377 << "\n"); 1378 1379 ManifestChange = ManifestChange | LocalChange; 1380 1381 NumAtFixpoint++; 1382 NumManifested += (LocalChange == ChangeStatus::CHANGED); 1383 } 1384 1385 (void)NumManifested; 1386 (void)NumAtFixpoint; 1387 LLVM_DEBUG(dbgs() << "\n[Attributor] Manifested " << NumManifested 1388 << " arguments while " << NumAtFixpoint 1389 << " were in a valid fixpoint state\n"); 1390 1391 NumAttributesManifested += NumManifested; 1392 NumAttributesValidFixpoint += NumAtFixpoint; 1393 1394 (void)NumFinalAAs; 1395 if (NumFinalAAs != DG.SyntheticRoot.Deps.size()) { 1396 for (unsigned u = NumFinalAAs; u < DG.SyntheticRoot.Deps.size(); ++u) 1397 errs() << "Unexpected abstract attribute: " 1398 << cast<AbstractAttribute>(DG.SyntheticRoot.Deps[u].getPointer()) 1399 << " :: " 1400 << cast<AbstractAttribute>(DG.SyntheticRoot.Deps[u].getPointer()) 1401 ->getIRPosition() 1402 .getAssociatedValue() 1403 << "\n"; 1404 llvm_unreachable("Expected the final number of abstract attributes to " 1405 "remain unchanged!"); 1406 } 1407 return ManifestChange; 1408 } 1409 1410 void Attributor::identifyDeadInternalFunctions() { 1411 // Early exit if we don't intend to delete functions. 1412 if (!DeleteFns) 1413 return; 1414 1415 // Identify dead internal functions and delete them. This happens outside 1416 // the other fixpoint analysis as we might treat potentially dead functions 1417 // as live to lower the number of iterations. If they happen to be dead, the 1418 // below fixpoint loop will identify and eliminate them. 1419 SmallVector<Function *, 8> InternalFns; 1420 for (Function *F : Functions) 1421 if (F->hasLocalLinkage()) 1422 InternalFns.push_back(F); 1423 1424 SmallPtrSet<Function *, 8> LiveInternalFns; 1425 bool FoundLiveInternal = true; 1426 while (FoundLiveInternal) { 1427 FoundLiveInternal = false; 1428 for (unsigned u = 0, e = InternalFns.size(); u < e; ++u) { 1429 Function *F = InternalFns[u]; 1430 if (!F) 1431 continue; 1432 1433 bool AllCallSitesKnown; 1434 if (checkForAllCallSites( 1435 [&](AbstractCallSite ACS) { 1436 Function *Callee = ACS.getInstruction()->getFunction(); 1437 return ToBeDeletedFunctions.count(Callee) || 1438 (Functions.count(Callee) && Callee->hasLocalLinkage() && 1439 !LiveInternalFns.count(Callee)); 1440 }, 1441 *F, true, nullptr, AllCallSitesKnown)) { 1442 continue; 1443 } 1444 1445 LiveInternalFns.insert(F); 1446 InternalFns[u] = nullptr; 1447 FoundLiveInternal = true; 1448 } 1449 } 1450 1451 for (unsigned u = 0, e = InternalFns.size(); u < e; ++u) 1452 if (Function *F = InternalFns[u]) 1453 ToBeDeletedFunctions.insert(F); 1454 } 1455 1456 ChangeStatus Attributor::cleanupIR() { 1457 TimeTraceScope TimeScope("Attributor::cleanupIR"); 1458 // Delete stuff at the end to avoid invalid references and a nice order. 1459 LLVM_DEBUG(dbgs() << "\n[Attributor] Delete/replace at least " 1460 << ToBeDeletedFunctions.size() << " functions and " 1461 << ToBeDeletedBlocks.size() << " blocks and " 1462 << ToBeDeletedInsts.size() << " instructions and " 1463 << ToBeChangedValues.size() << " values and " 1464 << ToBeChangedUses.size() << " uses. " 1465 << "Preserve manifest added " << ManifestAddedBlocks.size() 1466 << " blocks\n"); 1467 1468 SmallVector<WeakTrackingVH, 32> DeadInsts; 1469 SmallVector<Instruction *, 32> TerminatorsToFold; 1470 1471 auto ReplaceUse = [&](Use *U, Value *NewV) { 1472 Value *OldV = U->get(); 1473 1474 // If we plan to replace NewV we need to update it at this point. 1475 do { 1476 const auto &Entry = ToBeChangedValues.lookup(NewV); 1477 if (!Entry.first) 1478 break; 1479 NewV = Entry.first; 1480 } while (true); 1481 1482 // Do not replace uses in returns if the value is a must-tail call we will 1483 // not delete. 1484 if (auto *RI = dyn_cast<ReturnInst>(U->getUser())) { 1485 if (auto *CI = dyn_cast<CallInst>(OldV->stripPointerCasts())) 1486 if (CI->isMustTailCall() && 1487 (!ToBeDeletedInsts.count(CI) || !isRunOn(*CI->getCaller()))) 1488 return; 1489 // If we rewrite a return and the new value is not an argument, strip the 1490 // `returned` attribute as it is wrong now. 1491 if (!isa<Argument>(NewV)) 1492 for (auto &Arg : RI->getFunction()->args()) 1493 Arg.removeAttr(Attribute::Returned); 1494 } 1495 1496 // Do not perform call graph altering changes outside the SCC. 1497 if (auto *CB = dyn_cast<CallBase>(U->getUser())) 1498 if (CB->isCallee(U) && !isRunOn(*CB->getCaller())) 1499 return; 1500 1501 LLVM_DEBUG(dbgs() << "Use " << *NewV << " in " << *U->getUser() 1502 << " instead of " << *OldV << "\n"); 1503 U->set(NewV); 1504 1505 if (Instruction *I = dyn_cast<Instruction>(OldV)) { 1506 CGModifiedFunctions.insert(I->getFunction()); 1507 if (!isa<PHINode>(I) && !ToBeDeletedInsts.count(I) && 1508 isInstructionTriviallyDead(I)) 1509 DeadInsts.push_back(I); 1510 } 1511 if (isa<UndefValue>(NewV) && isa<CallBase>(U->getUser())) { 1512 auto *CB = cast<CallBase>(U->getUser()); 1513 if (CB->isArgOperand(U)) { 1514 unsigned Idx = CB->getArgOperandNo(U); 1515 CB->removeParamAttr(Idx, Attribute::NoUndef); 1516 Function *Fn = CB->getCalledFunction(); 1517 if (Fn && Fn->arg_size() > Idx) 1518 Fn->removeParamAttr(Idx, Attribute::NoUndef); 1519 } 1520 } 1521 if (isa<Constant>(NewV) && isa<BranchInst>(U->getUser())) { 1522 Instruction *UserI = cast<Instruction>(U->getUser()); 1523 if (isa<UndefValue>(NewV)) { 1524 ToBeChangedToUnreachableInsts.insert(UserI); 1525 } else { 1526 TerminatorsToFold.push_back(UserI); 1527 } 1528 } 1529 }; 1530 1531 for (auto &It : ToBeChangedUses) { 1532 Use *U = It.first; 1533 Value *NewV = It.second; 1534 ReplaceUse(U, NewV); 1535 } 1536 1537 SmallVector<Use *, 4> Uses; 1538 for (auto &It : ToBeChangedValues) { 1539 Value *OldV = It.first; 1540 auto &Entry = It.second; 1541 Value *NewV = Entry.first; 1542 Uses.clear(); 1543 for (auto &U : OldV->uses()) 1544 if (Entry.second || !U.getUser()->isDroppable()) 1545 Uses.push_back(&U); 1546 for (Use *U : Uses) 1547 ReplaceUse(U, NewV); 1548 } 1549 1550 for (auto &V : InvokeWithDeadSuccessor) 1551 if (InvokeInst *II = dyn_cast_or_null<InvokeInst>(V)) { 1552 assert(isRunOn(*II->getFunction()) && 1553 "Cannot replace an invoke outside the current SCC!"); 1554 bool UnwindBBIsDead = II->hasFnAttr(Attribute::NoUnwind); 1555 bool NormalBBIsDead = II->hasFnAttr(Attribute::NoReturn); 1556 bool Invoke2CallAllowed = 1557 !AAIsDead::mayCatchAsynchronousExceptions(*II->getFunction()); 1558 assert((UnwindBBIsDead || NormalBBIsDead) && 1559 "Invoke does not have dead successors!"); 1560 BasicBlock *BB = II->getParent(); 1561 BasicBlock *NormalDestBB = II->getNormalDest(); 1562 if (UnwindBBIsDead) { 1563 Instruction *NormalNextIP = &NormalDestBB->front(); 1564 if (Invoke2CallAllowed) { 1565 changeToCall(II); 1566 NormalNextIP = BB->getTerminator(); 1567 } 1568 if (NormalBBIsDead) 1569 ToBeChangedToUnreachableInsts.insert(NormalNextIP); 1570 } else { 1571 assert(NormalBBIsDead && "Broken invariant!"); 1572 if (!NormalDestBB->getUniquePredecessor()) 1573 NormalDestBB = SplitBlockPredecessors(NormalDestBB, {BB}, ".dead"); 1574 ToBeChangedToUnreachableInsts.insert(&NormalDestBB->front()); 1575 } 1576 } 1577 for (Instruction *I : TerminatorsToFold) { 1578 if (!isRunOn(*I->getFunction())) 1579 continue; 1580 CGModifiedFunctions.insert(I->getFunction()); 1581 ConstantFoldTerminator(I->getParent()); 1582 } 1583 for (auto &V : ToBeChangedToUnreachableInsts) 1584 if (Instruction *I = dyn_cast_or_null<Instruction>(V)) { 1585 if (!isRunOn(*I->getFunction())) 1586 continue; 1587 CGModifiedFunctions.insert(I->getFunction()); 1588 changeToUnreachable(I, /* UseLLVMTrap */ false); 1589 } 1590 1591 for (auto &V : ToBeDeletedInsts) { 1592 if (Instruction *I = dyn_cast_or_null<Instruction>(V)) { 1593 if (auto *CB = dyn_cast<CallBase>(I)) { 1594 if (!isRunOn(*I->getFunction())) 1595 continue; 1596 if (!isa<IntrinsicInst>(CB)) 1597 CGUpdater.removeCallSite(*CB); 1598 } 1599 I->dropDroppableUses(); 1600 CGModifiedFunctions.insert(I->getFunction()); 1601 if (!I->getType()->isVoidTy()) 1602 I->replaceAllUsesWith(UndefValue::get(I->getType())); 1603 if (!isa<PHINode>(I) && isInstructionTriviallyDead(I)) 1604 DeadInsts.push_back(I); 1605 else 1606 I->eraseFromParent(); 1607 } 1608 } 1609 1610 llvm::erase_if(DeadInsts, [&](WeakTrackingVH I) { 1611 return !I || !isRunOn(*cast<Instruction>(I)->getFunction()); 1612 }); 1613 1614 LLVM_DEBUG({ 1615 dbgs() << "[Attributor] DeadInsts size: " << DeadInsts.size() << "\n"; 1616 for (auto &I : DeadInsts) 1617 if (I) 1618 dbgs() << " - " << *I << "\n"; 1619 }); 1620 1621 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts); 1622 1623 if (unsigned NumDeadBlocks = ToBeDeletedBlocks.size()) { 1624 SmallVector<BasicBlock *, 8> ToBeDeletedBBs; 1625 ToBeDeletedBBs.reserve(NumDeadBlocks); 1626 for (BasicBlock *BB : ToBeDeletedBlocks) { 1627 assert(isRunOn(*BB->getParent()) && 1628 "Cannot delete a block outside the current SCC!"); 1629 CGModifiedFunctions.insert(BB->getParent()); 1630 // Do not delete BBs added during manifests of AAs. 1631 if (ManifestAddedBlocks.contains(BB)) 1632 continue; 1633 ToBeDeletedBBs.push_back(BB); 1634 } 1635 // Actually we do not delete the blocks but squash them into a single 1636 // unreachable but untangling branches that jump here is something we need 1637 // to do in a more generic way. 1638 DetatchDeadBlocks(ToBeDeletedBBs, nullptr); 1639 } 1640 1641 identifyDeadInternalFunctions(); 1642 1643 // Rewrite the functions as requested during manifest. 1644 ChangeStatus ManifestChange = rewriteFunctionSignatures(CGModifiedFunctions); 1645 1646 for (Function *Fn : CGModifiedFunctions) 1647 if (!ToBeDeletedFunctions.count(Fn) && Functions.count(Fn)) 1648 CGUpdater.reanalyzeFunction(*Fn); 1649 1650 for (Function *Fn : ToBeDeletedFunctions) { 1651 if (!Functions.count(Fn)) 1652 continue; 1653 CGUpdater.removeFunction(*Fn); 1654 } 1655 1656 if (!ToBeChangedUses.empty()) 1657 ManifestChange = ChangeStatus::CHANGED; 1658 1659 if (!ToBeChangedToUnreachableInsts.empty()) 1660 ManifestChange = ChangeStatus::CHANGED; 1661 1662 if (!ToBeDeletedFunctions.empty()) 1663 ManifestChange = ChangeStatus::CHANGED; 1664 1665 if (!ToBeDeletedBlocks.empty()) 1666 ManifestChange = ChangeStatus::CHANGED; 1667 1668 if (!ToBeDeletedInsts.empty()) 1669 ManifestChange = ChangeStatus::CHANGED; 1670 1671 if (!InvokeWithDeadSuccessor.empty()) 1672 ManifestChange = ChangeStatus::CHANGED; 1673 1674 if (!DeadInsts.empty()) 1675 ManifestChange = ChangeStatus::CHANGED; 1676 1677 NumFnDeleted += ToBeDeletedFunctions.size(); 1678 1679 LLVM_DEBUG(dbgs() << "[Attributor] Deleted " << ToBeDeletedFunctions.size() 1680 << " functions after manifest.\n"); 1681 1682 #ifdef EXPENSIVE_CHECKS 1683 for (Function *F : Functions) { 1684 if (ToBeDeletedFunctions.count(F)) 1685 continue; 1686 assert(!verifyFunction(*F, &errs()) && "Module verification failed!"); 1687 } 1688 #endif 1689 1690 return ManifestChange; 1691 } 1692 1693 ChangeStatus Attributor::run() { 1694 TimeTraceScope TimeScope("Attributor::run"); 1695 AttributorCallGraph ACallGraph(*this); 1696 1697 if (PrintCallGraph) 1698 ACallGraph.populateAll(); 1699 1700 Phase = AttributorPhase::UPDATE; 1701 runTillFixpoint(); 1702 1703 // dump graphs on demand 1704 if (DumpDepGraph) 1705 DG.dumpGraph(); 1706 1707 if (ViewDepGraph) 1708 DG.viewGraph(); 1709 1710 if (PrintDependencies) 1711 DG.print(); 1712 1713 Phase = AttributorPhase::MANIFEST; 1714 ChangeStatus ManifestChange = manifestAttributes(); 1715 1716 Phase = AttributorPhase::CLEANUP; 1717 ChangeStatus CleanupChange = cleanupIR(); 1718 1719 if (PrintCallGraph) 1720 ACallGraph.print(); 1721 1722 return ManifestChange | CleanupChange; 1723 } 1724 1725 ChangeStatus Attributor::updateAA(AbstractAttribute &AA) { 1726 TimeTraceScope TimeScope( 1727 AA.getName() + std::to_string(AA.getIRPosition().getPositionKind()) + 1728 "::updateAA"); 1729 assert(Phase == AttributorPhase::UPDATE && 1730 "We can update AA only in the update stage!"); 1731 1732 // Use a new dependence vector for this update. 1733 DependenceVector DV; 1734 DependenceStack.push_back(&DV); 1735 1736 auto &AAState = AA.getState(); 1737 ChangeStatus CS = ChangeStatus::UNCHANGED; 1738 bool UsedAssumedInformation = false; 1739 if (!isAssumedDead(AA, nullptr, UsedAssumedInformation, 1740 /* CheckBBLivenessOnly */ true)) 1741 CS = AA.update(*this); 1742 1743 if (DV.empty()) { 1744 // If the attribute did not query any non-fix information, the state 1745 // will not change and we can indicate that right away. 1746 AAState.indicateOptimisticFixpoint(); 1747 } 1748 1749 if (!AAState.isAtFixpoint()) 1750 rememberDependences(); 1751 1752 // Verify the stack was used properly, that is we pop the dependence vector we 1753 // put there earlier. 1754 DependenceVector *PoppedDV = DependenceStack.pop_back_val(); 1755 (void)PoppedDV; 1756 assert(PoppedDV == &DV && "Inconsistent usage of the dependence stack!"); 1757 1758 return CS; 1759 } 1760 1761 void Attributor::createShallowWrapper(Function &F) { 1762 assert(!F.isDeclaration() && "Cannot create a wrapper around a declaration!"); 1763 1764 Module &M = *F.getParent(); 1765 LLVMContext &Ctx = M.getContext(); 1766 FunctionType *FnTy = F.getFunctionType(); 1767 1768 Function *Wrapper = 1769 Function::Create(FnTy, F.getLinkage(), F.getAddressSpace(), F.getName()); 1770 F.setName(""); // set the inside function anonymous 1771 M.getFunctionList().insert(F.getIterator(), Wrapper); 1772 1773 F.setLinkage(GlobalValue::InternalLinkage); 1774 1775 F.replaceAllUsesWith(Wrapper); 1776 assert(F.use_empty() && "Uses remained after wrapper was created!"); 1777 1778 // Move the COMDAT section to the wrapper. 1779 // TODO: Check if we need to keep it for F as well. 1780 Wrapper->setComdat(F.getComdat()); 1781 F.setComdat(nullptr); 1782 1783 // Copy all metadata and attributes but keep them on F as well. 1784 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs; 1785 F.getAllMetadata(MDs); 1786 for (auto MDIt : MDs) 1787 Wrapper->addMetadata(MDIt.first, *MDIt.second); 1788 Wrapper->setAttributes(F.getAttributes()); 1789 1790 // Create the call in the wrapper. 1791 BasicBlock *EntryBB = BasicBlock::Create(Ctx, "entry", Wrapper); 1792 1793 SmallVector<Value *, 8> Args; 1794 Argument *FArgIt = F.arg_begin(); 1795 for (Argument &Arg : Wrapper->args()) { 1796 Args.push_back(&Arg); 1797 Arg.setName((FArgIt++)->getName()); 1798 } 1799 1800 CallInst *CI = CallInst::Create(&F, Args, "", EntryBB); 1801 CI->setTailCall(true); 1802 CI->addAttribute(AttributeList::FunctionIndex, Attribute::NoInline); 1803 ReturnInst::Create(Ctx, CI->getType()->isVoidTy() ? nullptr : CI, EntryBB); 1804 1805 NumFnShallowWrappersCreated++; 1806 } 1807 1808 Function *Attributor::internalizeFunction(Function &F, bool Force) { 1809 if (!AllowDeepWrapper && !Force) 1810 return nullptr; 1811 if (F.isDeclaration() || F.hasLocalLinkage() || 1812 GlobalValue::isInterposableLinkage(F.getLinkage())) 1813 return nullptr; 1814 1815 Module &M = *F.getParent(); 1816 FunctionType *FnTy = F.getFunctionType(); 1817 1818 // create a copy of the current function 1819 Function *Copied = Function::Create(FnTy, F.getLinkage(), F.getAddressSpace(), 1820 F.getName() + ".internalized"); 1821 ValueToValueMapTy VMap; 1822 auto *NewFArgIt = Copied->arg_begin(); 1823 for (auto &Arg : F.args()) { 1824 auto ArgName = Arg.getName(); 1825 NewFArgIt->setName(ArgName); 1826 VMap[&Arg] = &(*NewFArgIt++); 1827 } 1828 SmallVector<ReturnInst *, 8> Returns; 1829 1830 // Copy the body of the original function to the new one 1831 CloneFunctionInto(Copied, &F, VMap, CloneFunctionChangeType::LocalChangesOnly, 1832 Returns); 1833 1834 // Set the linakage and visibility late as CloneFunctionInto has some implicit 1835 // requirements. 1836 Copied->setVisibility(GlobalValue::DefaultVisibility); 1837 Copied->setLinkage(GlobalValue::PrivateLinkage); 1838 1839 // Copy metadata 1840 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs; 1841 F.getAllMetadata(MDs); 1842 for (auto MDIt : MDs) 1843 if (!Copied->hasMetadata()) 1844 Copied->addMetadata(MDIt.first, *MDIt.second); 1845 1846 M.getFunctionList().insert(F.getIterator(), Copied); 1847 F.replaceAllUsesWith(Copied); 1848 Copied->setDSOLocal(true); 1849 1850 return Copied; 1851 } 1852 1853 bool Attributor::isValidFunctionSignatureRewrite( 1854 Argument &Arg, ArrayRef<Type *> ReplacementTypes) { 1855 1856 if (!RewriteSignatures) 1857 return false; 1858 1859 auto CallSiteCanBeChanged = [](AbstractCallSite ACS) { 1860 // Forbid the call site to cast the function return type. If we need to 1861 // rewrite these functions we need to re-create a cast for the new call site 1862 // (if the old had uses). 1863 if (!ACS.getCalledFunction() || 1864 ACS.getInstruction()->getType() != 1865 ACS.getCalledFunction()->getReturnType()) 1866 return false; 1867 // Forbid must-tail calls for now. 1868 return !ACS.isCallbackCall() && !ACS.getInstruction()->isMustTailCall(); 1869 }; 1870 1871 Function *Fn = Arg.getParent(); 1872 // Avoid var-arg functions for now. 1873 if (Fn->isVarArg()) { 1874 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite var-args functions\n"); 1875 return false; 1876 } 1877 1878 // Avoid functions with complicated argument passing semantics. 1879 AttributeList FnAttributeList = Fn->getAttributes(); 1880 if (FnAttributeList.hasAttrSomewhere(Attribute::Nest) || 1881 FnAttributeList.hasAttrSomewhere(Attribute::StructRet) || 1882 FnAttributeList.hasAttrSomewhere(Attribute::InAlloca) || 1883 FnAttributeList.hasAttrSomewhere(Attribute::Preallocated)) { 1884 LLVM_DEBUG( 1885 dbgs() << "[Attributor] Cannot rewrite due to complex attribute\n"); 1886 return false; 1887 } 1888 1889 // Avoid callbacks for now. 1890 bool AllCallSitesKnown; 1891 if (!checkForAllCallSites(CallSiteCanBeChanged, *Fn, true, nullptr, 1892 AllCallSitesKnown)) { 1893 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite all call sites\n"); 1894 return false; 1895 } 1896 1897 auto InstPred = [](Instruction &I) { 1898 if (auto *CI = dyn_cast<CallInst>(&I)) 1899 return !CI->isMustTailCall(); 1900 return true; 1901 }; 1902 1903 // Forbid must-tail calls for now. 1904 // TODO: 1905 bool UsedAssumedInformation = false; 1906 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(*Fn); 1907 if (!checkForAllInstructionsImpl(nullptr, OpcodeInstMap, InstPred, nullptr, 1908 nullptr, {Instruction::Call}, 1909 UsedAssumedInformation)) { 1910 LLVM_DEBUG(dbgs() << "[Attributor] Cannot rewrite due to instructions\n"); 1911 return false; 1912 } 1913 1914 return true; 1915 } 1916 1917 bool Attributor::registerFunctionSignatureRewrite( 1918 Argument &Arg, ArrayRef<Type *> ReplacementTypes, 1919 ArgumentReplacementInfo::CalleeRepairCBTy &&CalleeRepairCB, 1920 ArgumentReplacementInfo::ACSRepairCBTy &&ACSRepairCB) { 1921 LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in " 1922 << Arg.getParent()->getName() << " with " 1923 << ReplacementTypes.size() << " replacements\n"); 1924 assert(isValidFunctionSignatureRewrite(Arg, ReplacementTypes) && 1925 "Cannot register an invalid rewrite"); 1926 1927 Function *Fn = Arg.getParent(); 1928 SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs = 1929 ArgumentReplacementMap[Fn]; 1930 if (ARIs.empty()) 1931 ARIs.resize(Fn->arg_size()); 1932 1933 // If we have a replacement already with less than or equal new arguments, 1934 // ignore this request. 1935 std::unique_ptr<ArgumentReplacementInfo> &ARI = ARIs[Arg.getArgNo()]; 1936 if (ARI && ARI->getNumReplacementArgs() <= ReplacementTypes.size()) { 1937 LLVM_DEBUG(dbgs() << "[Attributor] Existing rewrite is preferred\n"); 1938 return false; 1939 } 1940 1941 // If we have a replacement already but we like the new one better, delete 1942 // the old. 1943 ARI.reset(); 1944 1945 LLVM_DEBUG(dbgs() << "[Attributor] Register new rewrite of " << Arg << " in " 1946 << Arg.getParent()->getName() << " with " 1947 << ReplacementTypes.size() << " replacements\n"); 1948 1949 // Remember the replacement. 1950 ARI.reset(new ArgumentReplacementInfo(*this, Arg, ReplacementTypes, 1951 std::move(CalleeRepairCB), 1952 std::move(ACSRepairCB))); 1953 1954 return true; 1955 } 1956 1957 bool Attributor::shouldSeedAttribute(AbstractAttribute &AA) { 1958 bool Result = true; 1959 #ifndef NDEBUG 1960 if (SeedAllowList.size() != 0) 1961 Result = 1962 std::count(SeedAllowList.begin(), SeedAllowList.end(), AA.getName()); 1963 Function *Fn = AA.getAnchorScope(); 1964 if (FunctionSeedAllowList.size() != 0 && Fn) 1965 Result &= std::count(FunctionSeedAllowList.begin(), 1966 FunctionSeedAllowList.end(), Fn->getName()); 1967 #endif 1968 return Result; 1969 } 1970 1971 ChangeStatus Attributor::rewriteFunctionSignatures( 1972 SmallPtrSetImpl<Function *> &ModifiedFns) { 1973 ChangeStatus Changed = ChangeStatus::UNCHANGED; 1974 1975 for (auto &It : ArgumentReplacementMap) { 1976 Function *OldFn = It.getFirst(); 1977 1978 // Deleted functions do not require rewrites. 1979 if (!Functions.count(OldFn) || ToBeDeletedFunctions.count(OldFn)) 1980 continue; 1981 1982 const SmallVectorImpl<std::unique_ptr<ArgumentReplacementInfo>> &ARIs = 1983 It.getSecond(); 1984 assert(ARIs.size() == OldFn->arg_size() && "Inconsistent state!"); 1985 1986 SmallVector<Type *, 16> NewArgumentTypes; 1987 SmallVector<AttributeSet, 16> NewArgumentAttributes; 1988 1989 // Collect replacement argument types and copy over existing attributes. 1990 AttributeList OldFnAttributeList = OldFn->getAttributes(); 1991 for (Argument &Arg : OldFn->args()) { 1992 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI = 1993 ARIs[Arg.getArgNo()]) { 1994 NewArgumentTypes.append(ARI->ReplacementTypes.begin(), 1995 ARI->ReplacementTypes.end()); 1996 NewArgumentAttributes.append(ARI->getNumReplacementArgs(), 1997 AttributeSet()); 1998 } else { 1999 NewArgumentTypes.push_back(Arg.getType()); 2000 NewArgumentAttributes.push_back( 2001 OldFnAttributeList.getParamAttributes(Arg.getArgNo())); 2002 } 2003 } 2004 2005 FunctionType *OldFnTy = OldFn->getFunctionType(); 2006 Type *RetTy = OldFnTy->getReturnType(); 2007 2008 // Construct the new function type using the new arguments types. 2009 FunctionType *NewFnTy = 2010 FunctionType::get(RetTy, NewArgumentTypes, OldFnTy->isVarArg()); 2011 2012 LLVM_DEBUG(dbgs() << "[Attributor] Function rewrite '" << OldFn->getName() 2013 << "' from " << *OldFn->getFunctionType() << " to " 2014 << *NewFnTy << "\n"); 2015 2016 // Create the new function body and insert it into the module. 2017 Function *NewFn = Function::Create(NewFnTy, OldFn->getLinkage(), 2018 OldFn->getAddressSpace(), ""); 2019 Functions.insert(NewFn); 2020 OldFn->getParent()->getFunctionList().insert(OldFn->getIterator(), NewFn); 2021 NewFn->takeName(OldFn); 2022 NewFn->copyAttributesFrom(OldFn); 2023 2024 // Patch the pointer to LLVM function in debug info descriptor. 2025 NewFn->setSubprogram(OldFn->getSubprogram()); 2026 OldFn->setSubprogram(nullptr); 2027 2028 // Recompute the parameter attributes list based on the new arguments for 2029 // the function. 2030 LLVMContext &Ctx = OldFn->getContext(); 2031 NewFn->setAttributes(AttributeList::get( 2032 Ctx, OldFnAttributeList.getFnAttributes(), 2033 OldFnAttributeList.getRetAttributes(), NewArgumentAttributes)); 2034 2035 // Since we have now created the new function, splice the body of the old 2036 // function right into the new function, leaving the old rotting hulk of the 2037 // function empty. 2038 NewFn->getBasicBlockList().splice(NewFn->begin(), 2039 OldFn->getBasicBlockList()); 2040 2041 // Fixup block addresses to reference new function. 2042 SmallVector<BlockAddress *, 8u> BlockAddresses; 2043 for (User *U : OldFn->users()) 2044 if (auto *BA = dyn_cast<BlockAddress>(U)) 2045 BlockAddresses.push_back(BA); 2046 for (auto *BA : BlockAddresses) 2047 BA->replaceAllUsesWith(BlockAddress::get(NewFn, BA->getBasicBlock())); 2048 2049 // Set of all "call-like" instructions that invoke the old function mapped 2050 // to their new replacements. 2051 SmallVector<std::pair<CallBase *, CallBase *>, 8> CallSitePairs; 2052 2053 // Callback to create a new "call-like" instruction for a given one. 2054 auto CallSiteReplacementCreator = [&](AbstractCallSite ACS) { 2055 CallBase *OldCB = cast<CallBase>(ACS.getInstruction()); 2056 const AttributeList &OldCallAttributeList = OldCB->getAttributes(); 2057 2058 // Collect the new argument operands for the replacement call site. 2059 SmallVector<Value *, 16> NewArgOperands; 2060 SmallVector<AttributeSet, 16> NewArgOperandAttributes; 2061 for (unsigned OldArgNum = 0; OldArgNum < ARIs.size(); ++OldArgNum) { 2062 unsigned NewFirstArgNum = NewArgOperands.size(); 2063 (void)NewFirstArgNum; // only used inside assert. 2064 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI = 2065 ARIs[OldArgNum]) { 2066 if (ARI->ACSRepairCB) 2067 ARI->ACSRepairCB(*ARI, ACS, NewArgOperands); 2068 assert(ARI->getNumReplacementArgs() + NewFirstArgNum == 2069 NewArgOperands.size() && 2070 "ACS repair callback did not provide as many operand as new " 2071 "types were registered!"); 2072 // TODO: Exose the attribute set to the ACS repair callback 2073 NewArgOperandAttributes.append(ARI->ReplacementTypes.size(), 2074 AttributeSet()); 2075 } else { 2076 NewArgOperands.push_back(ACS.getCallArgOperand(OldArgNum)); 2077 NewArgOperandAttributes.push_back( 2078 OldCallAttributeList.getParamAttributes(OldArgNum)); 2079 } 2080 } 2081 2082 assert(NewArgOperands.size() == NewArgOperandAttributes.size() && 2083 "Mismatch # argument operands vs. # argument operand attributes!"); 2084 assert(NewArgOperands.size() == NewFn->arg_size() && 2085 "Mismatch # argument operands vs. # function arguments!"); 2086 2087 SmallVector<OperandBundleDef, 4> OperandBundleDefs; 2088 OldCB->getOperandBundlesAsDefs(OperandBundleDefs); 2089 2090 // Create a new call or invoke instruction to replace the old one. 2091 CallBase *NewCB; 2092 if (InvokeInst *II = dyn_cast<InvokeInst>(OldCB)) { 2093 NewCB = 2094 InvokeInst::Create(NewFn, II->getNormalDest(), II->getUnwindDest(), 2095 NewArgOperands, OperandBundleDefs, "", OldCB); 2096 } else { 2097 auto *NewCI = CallInst::Create(NewFn, NewArgOperands, OperandBundleDefs, 2098 "", OldCB); 2099 NewCI->setTailCallKind(cast<CallInst>(OldCB)->getTailCallKind()); 2100 NewCB = NewCI; 2101 } 2102 2103 // Copy over various properties and the new attributes. 2104 NewCB->copyMetadata(*OldCB, {LLVMContext::MD_prof, LLVMContext::MD_dbg}); 2105 NewCB->setCallingConv(OldCB->getCallingConv()); 2106 NewCB->takeName(OldCB); 2107 NewCB->setAttributes(AttributeList::get( 2108 Ctx, OldCallAttributeList.getFnAttributes(), 2109 OldCallAttributeList.getRetAttributes(), NewArgOperandAttributes)); 2110 2111 CallSitePairs.push_back({OldCB, NewCB}); 2112 return true; 2113 }; 2114 2115 // Use the CallSiteReplacementCreator to create replacement call sites. 2116 bool AllCallSitesKnown; 2117 bool Success = checkForAllCallSites(CallSiteReplacementCreator, *OldFn, 2118 true, nullptr, AllCallSitesKnown); 2119 (void)Success; 2120 assert(Success && "Assumed call site replacement to succeed!"); 2121 2122 // Rewire the arguments. 2123 Argument *OldFnArgIt = OldFn->arg_begin(); 2124 Argument *NewFnArgIt = NewFn->arg_begin(); 2125 for (unsigned OldArgNum = 0; OldArgNum < ARIs.size(); 2126 ++OldArgNum, ++OldFnArgIt) { 2127 if (const std::unique_ptr<ArgumentReplacementInfo> &ARI = 2128 ARIs[OldArgNum]) { 2129 if (ARI->CalleeRepairCB) 2130 ARI->CalleeRepairCB(*ARI, *NewFn, NewFnArgIt); 2131 NewFnArgIt += ARI->ReplacementTypes.size(); 2132 } else { 2133 NewFnArgIt->takeName(&*OldFnArgIt); 2134 OldFnArgIt->replaceAllUsesWith(&*NewFnArgIt); 2135 ++NewFnArgIt; 2136 } 2137 } 2138 2139 // Eliminate the instructions *after* we visited all of them. 2140 for (auto &CallSitePair : CallSitePairs) { 2141 CallBase &OldCB = *CallSitePair.first; 2142 CallBase &NewCB = *CallSitePair.second; 2143 assert(OldCB.getType() == NewCB.getType() && 2144 "Cannot handle call sites with different types!"); 2145 ModifiedFns.insert(OldCB.getFunction()); 2146 CGUpdater.replaceCallSite(OldCB, NewCB); 2147 OldCB.replaceAllUsesWith(&NewCB); 2148 OldCB.eraseFromParent(); 2149 } 2150 2151 // Replace the function in the call graph (if any). 2152 CGUpdater.replaceFunctionWith(*OldFn, *NewFn); 2153 2154 // If the old function was modified and needed to be reanalyzed, the new one 2155 // does now. 2156 if (ModifiedFns.erase(OldFn)) 2157 ModifiedFns.insert(NewFn); 2158 2159 Changed = ChangeStatus::CHANGED; 2160 } 2161 2162 return Changed; 2163 } 2164 2165 void InformationCache::initializeInformationCache(const Function &CF, 2166 FunctionInfo &FI) { 2167 // As we do not modify the function here we can remove the const 2168 // withouth breaking implicit assumptions. At the end of the day, we could 2169 // initialize the cache eagerly which would look the same to the users. 2170 Function &F = const_cast<Function &>(CF); 2171 2172 // Walk all instructions to find interesting instructions that might be 2173 // queried by abstract attributes during their initialization or update. 2174 // This has to happen before we create attributes. 2175 2176 for (Instruction &I : instructions(&F)) { 2177 bool IsInterestingOpcode = false; 2178 2179 // To allow easy access to all instructions in a function with a given 2180 // opcode we store them in the InfoCache. As not all opcodes are interesting 2181 // to concrete attributes we only cache the ones that are as identified in 2182 // the following switch. 2183 // Note: There are no concrete attributes now so this is initially empty. 2184 switch (I.getOpcode()) { 2185 default: 2186 assert(!isa<CallBase>(&I) && 2187 "New call base instruction type needs to be known in the " 2188 "Attributor."); 2189 break; 2190 case Instruction::Call: 2191 // Calls are interesting on their own, additionally: 2192 // For `llvm.assume` calls we also fill the KnowledgeMap as we find them. 2193 // For `must-tail` calls we remember the caller and callee. 2194 if (auto *Assume = dyn_cast<AssumeInst>(&I)) { 2195 fillMapFromAssume(*Assume, KnowledgeMap); 2196 } else if (cast<CallInst>(I).isMustTailCall()) { 2197 FI.ContainsMustTailCall = true; 2198 if (const Function *Callee = cast<CallInst>(I).getCalledFunction()) 2199 getFunctionInfo(*Callee).CalledViaMustTail = true; 2200 } 2201 LLVM_FALLTHROUGH; 2202 case Instruction::CallBr: 2203 case Instruction::Invoke: 2204 case Instruction::CleanupRet: 2205 case Instruction::CatchSwitch: 2206 case Instruction::AtomicRMW: 2207 case Instruction::AtomicCmpXchg: 2208 case Instruction::Br: 2209 case Instruction::Resume: 2210 case Instruction::Ret: 2211 case Instruction::Load: 2212 // The alignment of a pointer is interesting for loads. 2213 case Instruction::Store: 2214 // The alignment of a pointer is interesting for stores. 2215 IsInterestingOpcode = true; 2216 } 2217 if (IsInterestingOpcode) { 2218 auto *&Insts = FI.OpcodeInstMap[I.getOpcode()]; 2219 if (!Insts) 2220 Insts = new (Allocator) InstructionVectorTy(); 2221 Insts->push_back(&I); 2222 } 2223 if (I.mayReadOrWriteMemory()) 2224 FI.RWInsts.push_back(&I); 2225 } 2226 2227 if (F.hasFnAttribute(Attribute::AlwaysInline) && 2228 isInlineViable(F).isSuccess()) 2229 InlineableFunctions.insert(&F); 2230 } 2231 2232 AAResults *InformationCache::getAAResultsForFunction(const Function &F) { 2233 return AG.getAnalysis<AAManager>(F); 2234 } 2235 2236 InformationCache::FunctionInfo::~FunctionInfo() { 2237 // The instruction vectors are allocated using a BumpPtrAllocator, we need to 2238 // manually destroy them. 2239 for (auto &It : OpcodeInstMap) 2240 It.getSecond()->~InstructionVectorTy(); 2241 } 2242 2243 void Attributor::recordDependence(const AbstractAttribute &FromAA, 2244 const AbstractAttribute &ToAA, 2245 DepClassTy DepClass) { 2246 if (DepClass == DepClassTy::NONE) 2247 return; 2248 // If we are outside of an update, thus before the actual fixpoint iteration 2249 // started (= when we create AAs), we do not track dependences because we will 2250 // put all AAs into the initial worklist anyway. 2251 if (DependenceStack.empty()) 2252 return; 2253 if (FromAA.getState().isAtFixpoint()) 2254 return; 2255 DependenceStack.back()->push_back({&FromAA, &ToAA, DepClass}); 2256 } 2257 2258 void Attributor::rememberDependences() { 2259 assert(!DependenceStack.empty() && "No dependences to remember!"); 2260 2261 for (DepInfo &DI : *DependenceStack.back()) { 2262 assert((DI.DepClass == DepClassTy::REQUIRED || 2263 DI.DepClass == DepClassTy::OPTIONAL) && 2264 "Expected required or optional dependence (1 bit)!"); 2265 auto &DepAAs = const_cast<AbstractAttribute &>(*DI.FromAA).Deps; 2266 DepAAs.push_back(AbstractAttribute::DepTy( 2267 const_cast<AbstractAttribute *>(DI.ToAA), unsigned(DI.DepClass))); 2268 } 2269 } 2270 2271 void Attributor::identifyDefaultAbstractAttributes(Function &F) { 2272 if (!VisitedFunctions.insert(&F).second) 2273 return; 2274 if (F.isDeclaration()) 2275 return; 2276 2277 // In non-module runs we need to look at the call sites of a function to 2278 // determine if it is part of a must-tail call edge. This will influence what 2279 // attributes we can derive. 2280 InformationCache::FunctionInfo &FI = InfoCache.getFunctionInfo(F); 2281 if (!isModulePass() && !FI.CalledViaMustTail) { 2282 for (const Use &U : F.uses()) 2283 if (const auto *CB = dyn_cast<CallBase>(U.getUser())) 2284 if (CB->isCallee(&U) && CB->isMustTailCall()) 2285 FI.CalledViaMustTail = true; 2286 } 2287 2288 IRPosition FPos = IRPosition::function(F); 2289 2290 // Check for dead BasicBlocks in every function. 2291 // We need dead instruction detection because we do not want to deal with 2292 // broken IR in which SSA rules do not apply. 2293 getOrCreateAAFor<AAIsDead>(FPos); 2294 2295 // Every function might be "will-return". 2296 getOrCreateAAFor<AAWillReturn>(FPos); 2297 2298 // Every function might contain instructions that cause "undefined behavior". 2299 getOrCreateAAFor<AAUndefinedBehavior>(FPos); 2300 2301 // Every function can be nounwind. 2302 getOrCreateAAFor<AANoUnwind>(FPos); 2303 2304 // Every function might be marked "nosync" 2305 getOrCreateAAFor<AANoSync>(FPos); 2306 2307 // Every function might be "no-free". 2308 getOrCreateAAFor<AANoFree>(FPos); 2309 2310 // Every function might be "no-return". 2311 getOrCreateAAFor<AANoReturn>(FPos); 2312 2313 // Every function might be "no-recurse". 2314 getOrCreateAAFor<AANoRecurse>(FPos); 2315 2316 // Every function might be "readnone/readonly/writeonly/...". 2317 getOrCreateAAFor<AAMemoryBehavior>(FPos); 2318 2319 // Every function can be "readnone/argmemonly/inaccessiblememonly/...". 2320 getOrCreateAAFor<AAMemoryLocation>(FPos); 2321 2322 // Every function might be applicable for Heap-To-Stack conversion. 2323 if (EnableHeapToStack) 2324 getOrCreateAAFor<AAHeapToStack>(FPos); 2325 2326 // Return attributes are only appropriate if the return type is non void. 2327 Type *ReturnType = F.getReturnType(); 2328 if (!ReturnType->isVoidTy()) { 2329 // Argument attribute "returned" --- Create only one per function even 2330 // though it is an argument attribute. 2331 getOrCreateAAFor<AAReturnedValues>(FPos); 2332 2333 IRPosition RetPos = IRPosition::returned(F); 2334 2335 // Every returned value might be dead. 2336 getOrCreateAAFor<AAIsDead>(RetPos); 2337 2338 // Every function might be simplified. 2339 getOrCreateAAFor<AAValueSimplify>(RetPos); 2340 2341 // Every returned value might be marked noundef. 2342 getOrCreateAAFor<AANoUndef>(RetPos); 2343 2344 if (ReturnType->isPointerTy()) { 2345 2346 // Every function with pointer return type might be marked align. 2347 getOrCreateAAFor<AAAlign>(RetPos); 2348 2349 // Every function with pointer return type might be marked nonnull. 2350 getOrCreateAAFor<AANonNull>(RetPos); 2351 2352 // Every function with pointer return type might be marked noalias. 2353 getOrCreateAAFor<AANoAlias>(RetPos); 2354 2355 // Every function with pointer return type might be marked 2356 // dereferenceable. 2357 getOrCreateAAFor<AADereferenceable>(RetPos); 2358 } 2359 } 2360 2361 for (Argument &Arg : F.args()) { 2362 IRPosition ArgPos = IRPosition::argument(Arg); 2363 2364 // Every argument might be simplified. We have to go through the Attributor 2365 // interface though as outside AAs can register custom simplification 2366 // callbacks. 2367 bool UsedAssumedInformation = false; 2368 getAssumedSimplified(ArgPos, /* AA */ nullptr, UsedAssumedInformation); 2369 2370 // Every argument might be dead. 2371 getOrCreateAAFor<AAIsDead>(ArgPos); 2372 2373 // Every argument might be marked noundef. 2374 getOrCreateAAFor<AANoUndef>(ArgPos); 2375 2376 if (Arg.getType()->isPointerTy()) { 2377 // Every argument with pointer type might be marked nonnull. 2378 getOrCreateAAFor<AANonNull>(ArgPos); 2379 2380 // Every argument with pointer type might be marked noalias. 2381 getOrCreateAAFor<AANoAlias>(ArgPos); 2382 2383 // Every argument with pointer type might be marked dereferenceable. 2384 getOrCreateAAFor<AADereferenceable>(ArgPos); 2385 2386 // Every argument with pointer type might be marked align. 2387 getOrCreateAAFor<AAAlign>(ArgPos); 2388 2389 // Every argument with pointer type might be marked nocapture. 2390 getOrCreateAAFor<AANoCapture>(ArgPos); 2391 2392 // Every argument with pointer type might be marked 2393 // "readnone/readonly/writeonly/..." 2394 getOrCreateAAFor<AAMemoryBehavior>(ArgPos); 2395 2396 // Every argument with pointer type might be marked nofree. 2397 getOrCreateAAFor<AANoFree>(ArgPos); 2398 2399 // Every argument with pointer type might be privatizable (or promotable) 2400 getOrCreateAAFor<AAPrivatizablePtr>(ArgPos); 2401 } 2402 } 2403 2404 auto CallSitePred = [&](Instruction &I) -> bool { 2405 auto &CB = cast<CallBase>(I); 2406 IRPosition CBRetPos = IRPosition::callsite_returned(CB); 2407 2408 // Call sites might be dead if they do not have side effects and no live 2409 // users. The return value might be dead if there are no live users. 2410 getOrCreateAAFor<AAIsDead>(CBRetPos); 2411 2412 Function *Callee = CB.getCalledFunction(); 2413 // TODO: Even if the callee is not known now we might be able to simplify 2414 // the call/callee. 2415 if (!Callee) 2416 return true; 2417 2418 // Skip declarations except if annotations on their call sites were 2419 // explicitly requested. 2420 if (!AnnotateDeclarationCallSites && Callee->isDeclaration() && 2421 !Callee->hasMetadata(LLVMContext::MD_callback)) 2422 return true; 2423 2424 if (!Callee->getReturnType()->isVoidTy() && !CB.use_empty()) { 2425 2426 IRPosition CBRetPos = IRPosition::callsite_returned(CB); 2427 getOrCreateAAFor<AAValueSimplify>(CBRetPos); 2428 } 2429 2430 for (int I = 0, E = CB.getNumArgOperands(); I < E; ++I) { 2431 2432 IRPosition CBArgPos = IRPosition::callsite_argument(CB, I); 2433 2434 // Every call site argument might be dead. 2435 getOrCreateAAFor<AAIsDead>(CBArgPos); 2436 2437 // Call site argument might be simplified. We have to go through the 2438 // Attributor interface though as outside AAs can register custom 2439 // simplification callbacks. 2440 bool UsedAssumedInformation = false; 2441 getAssumedSimplified(CBArgPos, /* AA */ nullptr, UsedAssumedInformation); 2442 2443 // Every call site argument might be marked "noundef". 2444 getOrCreateAAFor<AANoUndef>(CBArgPos); 2445 2446 if (!CB.getArgOperand(I)->getType()->isPointerTy()) 2447 continue; 2448 2449 // Call site argument attribute "non-null". 2450 getOrCreateAAFor<AANonNull>(CBArgPos); 2451 2452 // Call site argument attribute "nocapture". 2453 getOrCreateAAFor<AANoCapture>(CBArgPos); 2454 2455 // Call site argument attribute "no-alias". 2456 getOrCreateAAFor<AANoAlias>(CBArgPos); 2457 2458 // Call site argument attribute "dereferenceable". 2459 getOrCreateAAFor<AADereferenceable>(CBArgPos); 2460 2461 // Call site argument attribute "align". 2462 getOrCreateAAFor<AAAlign>(CBArgPos); 2463 2464 // Call site argument attribute 2465 // "readnone/readonly/writeonly/..." 2466 getOrCreateAAFor<AAMemoryBehavior>(CBArgPos); 2467 2468 // Call site argument attribute "nofree". 2469 getOrCreateAAFor<AANoFree>(CBArgPos); 2470 } 2471 return true; 2472 }; 2473 2474 auto &OpcodeInstMap = InfoCache.getOpcodeInstMapForFunction(F); 2475 bool Success; 2476 bool UsedAssumedInformation = false; 2477 Success = checkForAllInstructionsImpl( 2478 nullptr, OpcodeInstMap, CallSitePred, nullptr, nullptr, 2479 {(unsigned)Instruction::Invoke, (unsigned)Instruction::CallBr, 2480 (unsigned)Instruction::Call}, 2481 UsedAssumedInformation); 2482 (void)Success; 2483 assert(Success && "Expected the check call to be successful!"); 2484 2485 auto LoadStorePred = [&](Instruction &I) -> bool { 2486 if (isa<LoadInst>(I)) { 2487 getOrCreateAAFor<AAAlign>( 2488 IRPosition::value(*cast<LoadInst>(I).getPointerOperand())); 2489 if (SimplifyAllLoads) 2490 getOrCreateAAFor<AAValueSimplify>(IRPosition::value(I)); 2491 } else 2492 getOrCreateAAFor<AAAlign>( 2493 IRPosition::value(*cast<StoreInst>(I).getPointerOperand())); 2494 return true; 2495 }; 2496 Success = checkForAllInstructionsImpl( 2497 nullptr, OpcodeInstMap, LoadStorePred, nullptr, nullptr, 2498 {(unsigned)Instruction::Load, (unsigned)Instruction::Store}, 2499 UsedAssumedInformation); 2500 (void)Success; 2501 assert(Success && "Expected the check call to be successful!"); 2502 } 2503 2504 /// Helpers to ease debugging through output streams and print calls. 2505 /// 2506 ///{ 2507 raw_ostream &llvm::operator<<(raw_ostream &OS, ChangeStatus S) { 2508 return OS << (S == ChangeStatus::CHANGED ? "changed" : "unchanged"); 2509 } 2510 2511 raw_ostream &llvm::operator<<(raw_ostream &OS, IRPosition::Kind AP) { 2512 switch (AP) { 2513 case IRPosition::IRP_INVALID: 2514 return OS << "inv"; 2515 case IRPosition::IRP_FLOAT: 2516 return OS << "flt"; 2517 case IRPosition::IRP_RETURNED: 2518 return OS << "fn_ret"; 2519 case IRPosition::IRP_CALL_SITE_RETURNED: 2520 return OS << "cs_ret"; 2521 case IRPosition::IRP_FUNCTION: 2522 return OS << "fn"; 2523 case IRPosition::IRP_CALL_SITE: 2524 return OS << "cs"; 2525 case IRPosition::IRP_ARGUMENT: 2526 return OS << "arg"; 2527 case IRPosition::IRP_CALL_SITE_ARGUMENT: 2528 return OS << "cs_arg"; 2529 } 2530 llvm_unreachable("Unknown attribute position!"); 2531 } 2532 2533 raw_ostream &llvm::operator<<(raw_ostream &OS, const IRPosition &Pos) { 2534 const Value &AV = Pos.getAssociatedValue(); 2535 OS << "{" << Pos.getPositionKind() << ":" << AV.getName() << " [" 2536 << Pos.getAnchorValue().getName() << "@" << Pos.getCallSiteArgNo() << "]"; 2537 2538 if (Pos.hasCallBaseContext()) 2539 OS << "[cb_context:" << *Pos.getCallBaseContext() << "]"; 2540 return OS << "}"; 2541 } 2542 2543 raw_ostream &llvm::operator<<(raw_ostream &OS, const IntegerRangeState &S) { 2544 OS << "range-state(" << S.getBitWidth() << ")<"; 2545 S.getKnown().print(OS); 2546 OS << " / "; 2547 S.getAssumed().print(OS); 2548 OS << ">"; 2549 2550 return OS << static_cast<const AbstractState &>(S); 2551 } 2552 2553 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractState &S) { 2554 return OS << (!S.isValidState() ? "top" : (S.isAtFixpoint() ? "fix" : "")); 2555 } 2556 2557 raw_ostream &llvm::operator<<(raw_ostream &OS, const AbstractAttribute &AA) { 2558 AA.print(OS); 2559 return OS; 2560 } 2561 2562 raw_ostream &llvm::operator<<(raw_ostream &OS, 2563 const PotentialConstantIntValuesState &S) { 2564 OS << "set-state(< {"; 2565 if (!S.isValidState()) 2566 OS << "full-set"; 2567 else { 2568 for (auto &it : S.getAssumedSet()) 2569 OS << it << ", "; 2570 if (S.undefIsContained()) 2571 OS << "undef "; 2572 } 2573 OS << "} >)"; 2574 2575 return OS; 2576 } 2577 2578 void AbstractAttribute::print(raw_ostream &OS) const { 2579 OS << "["; 2580 OS << getName(); 2581 OS << "] for CtxI "; 2582 2583 if (auto *I = getCtxI()) { 2584 OS << "'"; 2585 I->print(OS); 2586 OS << "'"; 2587 } else 2588 OS << "<<null inst>>"; 2589 2590 OS << " at position " << getIRPosition() << " with state " << getAsStr() 2591 << '\n'; 2592 } 2593 2594 void AbstractAttribute::printWithDeps(raw_ostream &OS) const { 2595 print(OS); 2596 2597 for (const auto &DepAA : Deps) { 2598 auto *AA = DepAA.getPointer(); 2599 OS << " updates "; 2600 AA->print(OS); 2601 } 2602 2603 OS << '\n'; 2604 } 2605 2606 raw_ostream &llvm::operator<<(raw_ostream &OS, 2607 const AAPointerInfo::Access &Acc) { 2608 OS << " [" << Acc.getKind() << "] " << *Acc.getRemoteInst(); 2609 if (Acc.getLocalInst() != Acc.getRemoteInst()) 2610 OS << " via " << *Acc.getLocalInst() << "\n"; 2611 return OS; 2612 } 2613 ///} 2614 2615 /// ---------------------------------------------------------------------------- 2616 /// Pass (Manager) Boilerplate 2617 /// ---------------------------------------------------------------------------- 2618 2619 static bool runAttributorOnFunctions(InformationCache &InfoCache, 2620 SetVector<Function *> &Functions, 2621 AnalysisGetter &AG, 2622 CallGraphUpdater &CGUpdater, 2623 bool DeleteFns) { 2624 if (Functions.empty()) 2625 return false; 2626 2627 LLVM_DEBUG({ 2628 dbgs() << "[Attributor] Run on module with " << Functions.size() 2629 << " functions:\n"; 2630 for (Function *Fn : Functions) 2631 dbgs() << " - " << Fn->getName() << "\n"; 2632 }); 2633 2634 // Create an Attributor and initially empty information cache that is filled 2635 // while we identify default attribute opportunities. 2636 Attributor A(Functions, InfoCache, CGUpdater, /* Allowed */ nullptr, 2637 DeleteFns); 2638 2639 // Create shallow wrappers for all functions that are not IPO amendable 2640 if (AllowShallowWrappers) 2641 for (Function *F : Functions) 2642 if (!A.isFunctionIPOAmendable(*F)) 2643 Attributor::createShallowWrapper(*F); 2644 2645 // Internalize non-exact functions 2646 // TODO: for now we eagerly internalize functions without calculating the 2647 // cost, we need a cost interface to determine whether internalizing 2648 // a function is "benefitial" 2649 if (AllowDeepWrapper) { 2650 unsigned FunSize = Functions.size(); 2651 for (unsigned u = 0; u < FunSize; u++) { 2652 Function *F = Functions[u]; 2653 if (!F->isDeclaration() && !F->isDefinitionExact() && F->getNumUses() && 2654 !GlobalValue::isInterposableLinkage(F->getLinkage())) { 2655 Function *NewF = Attributor::internalizeFunction(*F); 2656 assert(NewF && "Could not internalize function."); 2657 Functions.insert(NewF); 2658 2659 // Update call graph 2660 CGUpdater.replaceFunctionWith(*F, *NewF); 2661 for (const Use &U : NewF->uses()) 2662 if (CallBase *CB = dyn_cast<CallBase>(U.getUser())) { 2663 auto *CallerF = CB->getCaller(); 2664 CGUpdater.reanalyzeFunction(*CallerF); 2665 } 2666 } 2667 } 2668 } 2669 2670 for (Function *F : Functions) { 2671 if (F->hasExactDefinition()) 2672 NumFnWithExactDefinition++; 2673 else 2674 NumFnWithoutExactDefinition++; 2675 2676 // We look at internal functions only on-demand but if any use is not a 2677 // direct call or outside the current set of analyzed functions, we have 2678 // to do it eagerly. 2679 if (F->hasLocalLinkage()) { 2680 if (llvm::all_of(F->uses(), [&Functions](const Use &U) { 2681 const auto *CB = dyn_cast<CallBase>(U.getUser()); 2682 return CB && CB->isCallee(&U) && 2683 Functions.count(const_cast<Function *>(CB->getCaller())); 2684 })) 2685 continue; 2686 } 2687 2688 // Populate the Attributor with abstract attribute opportunities in the 2689 // function and the information cache with IR information. 2690 A.identifyDefaultAbstractAttributes(*F); 2691 } 2692 2693 ChangeStatus Changed = A.run(); 2694 2695 LLVM_DEBUG(dbgs() << "[Attributor] Done with " << Functions.size() 2696 << " functions, result: " << Changed << ".\n"); 2697 return Changed == ChangeStatus::CHANGED; 2698 } 2699 2700 void AADepGraph::viewGraph() { llvm::ViewGraph(this, "Dependency Graph"); } 2701 2702 void AADepGraph::dumpGraph() { 2703 static std::atomic<int> CallTimes; 2704 std::string Prefix; 2705 2706 if (!DepGraphDotFileNamePrefix.empty()) 2707 Prefix = DepGraphDotFileNamePrefix; 2708 else 2709 Prefix = "dep_graph"; 2710 std::string Filename = 2711 Prefix + "_" + std::to_string(CallTimes.load()) + ".dot"; 2712 2713 outs() << "Dependency graph dump to " << Filename << ".\n"; 2714 2715 std::error_code EC; 2716 2717 raw_fd_ostream File(Filename, EC, sys::fs::OF_TextWithCRLF); 2718 if (!EC) 2719 llvm::WriteGraph(File, this); 2720 2721 CallTimes++; 2722 } 2723 2724 void AADepGraph::print() { 2725 for (auto DepAA : SyntheticRoot.Deps) 2726 cast<AbstractAttribute>(DepAA.getPointer())->printWithDeps(outs()); 2727 } 2728 2729 PreservedAnalyses AttributorPass::run(Module &M, ModuleAnalysisManager &AM) { 2730 FunctionAnalysisManager &FAM = 2731 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 2732 AnalysisGetter AG(FAM); 2733 2734 SetVector<Function *> Functions; 2735 for (Function &F : M) 2736 Functions.insert(&F); 2737 2738 CallGraphUpdater CGUpdater; 2739 BumpPtrAllocator Allocator; 2740 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr); 2741 if (runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater, 2742 /* DeleteFns */ true)) { 2743 // FIXME: Think about passes we will preserve and add them here. 2744 return PreservedAnalyses::none(); 2745 } 2746 return PreservedAnalyses::all(); 2747 } 2748 2749 PreservedAnalyses AttributorCGSCCPass::run(LazyCallGraph::SCC &C, 2750 CGSCCAnalysisManager &AM, 2751 LazyCallGraph &CG, 2752 CGSCCUpdateResult &UR) { 2753 FunctionAnalysisManager &FAM = 2754 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager(); 2755 AnalysisGetter AG(FAM); 2756 2757 SetVector<Function *> Functions; 2758 for (LazyCallGraph::Node &N : C) 2759 Functions.insert(&N.getFunction()); 2760 2761 if (Functions.empty()) 2762 return PreservedAnalyses::all(); 2763 2764 Module &M = *Functions.back()->getParent(); 2765 CallGraphUpdater CGUpdater; 2766 CGUpdater.initialize(CG, C, AM, UR); 2767 BumpPtrAllocator Allocator; 2768 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions); 2769 if (runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater, 2770 /* DeleteFns */ false)) { 2771 // FIXME: Think about passes we will preserve and add them here. 2772 PreservedAnalyses PA; 2773 PA.preserve<FunctionAnalysisManagerCGSCCProxy>(); 2774 return PA; 2775 } 2776 return PreservedAnalyses::all(); 2777 } 2778 2779 namespace llvm { 2780 2781 template <> struct GraphTraits<AADepGraphNode *> { 2782 using NodeRef = AADepGraphNode *; 2783 using DepTy = PointerIntPair<AADepGraphNode *, 1>; 2784 using EdgeRef = PointerIntPair<AADepGraphNode *, 1>; 2785 2786 static NodeRef getEntryNode(AADepGraphNode *DGN) { return DGN; } 2787 static NodeRef DepGetVal(DepTy &DT) { return DT.getPointer(); } 2788 2789 using ChildIteratorType = 2790 mapped_iterator<TinyPtrVector<DepTy>::iterator, decltype(&DepGetVal)>; 2791 using ChildEdgeIteratorType = TinyPtrVector<DepTy>::iterator; 2792 2793 static ChildIteratorType child_begin(NodeRef N) { return N->child_begin(); } 2794 2795 static ChildIteratorType child_end(NodeRef N) { return N->child_end(); } 2796 }; 2797 2798 template <> 2799 struct GraphTraits<AADepGraph *> : public GraphTraits<AADepGraphNode *> { 2800 static NodeRef getEntryNode(AADepGraph *DG) { return DG->GetEntryNode(); } 2801 2802 using nodes_iterator = 2803 mapped_iterator<TinyPtrVector<DepTy>::iterator, decltype(&DepGetVal)>; 2804 2805 static nodes_iterator nodes_begin(AADepGraph *DG) { return DG->begin(); } 2806 2807 static nodes_iterator nodes_end(AADepGraph *DG) { return DG->end(); } 2808 }; 2809 2810 template <> struct DOTGraphTraits<AADepGraph *> : public DefaultDOTGraphTraits { 2811 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 2812 2813 static std::string getNodeLabel(const AADepGraphNode *Node, 2814 const AADepGraph *DG) { 2815 std::string AAString; 2816 raw_string_ostream O(AAString); 2817 Node->print(O); 2818 return AAString; 2819 } 2820 }; 2821 2822 } // end namespace llvm 2823 2824 namespace { 2825 2826 struct AttributorLegacyPass : public ModulePass { 2827 static char ID; 2828 2829 AttributorLegacyPass() : ModulePass(ID) { 2830 initializeAttributorLegacyPassPass(*PassRegistry::getPassRegistry()); 2831 } 2832 2833 bool runOnModule(Module &M) override { 2834 if (skipModule(M)) 2835 return false; 2836 2837 AnalysisGetter AG; 2838 SetVector<Function *> Functions; 2839 for (Function &F : M) 2840 Functions.insert(&F); 2841 2842 CallGraphUpdater CGUpdater; 2843 BumpPtrAllocator Allocator; 2844 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ nullptr); 2845 return runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater, 2846 /* DeleteFns*/ true); 2847 } 2848 2849 void getAnalysisUsage(AnalysisUsage &AU) const override { 2850 // FIXME: Think about passes we will preserve and add them here. 2851 AU.addRequired<TargetLibraryInfoWrapperPass>(); 2852 } 2853 }; 2854 2855 struct AttributorCGSCCLegacyPass : public CallGraphSCCPass { 2856 static char ID; 2857 2858 AttributorCGSCCLegacyPass() : CallGraphSCCPass(ID) { 2859 initializeAttributorCGSCCLegacyPassPass(*PassRegistry::getPassRegistry()); 2860 } 2861 2862 bool runOnSCC(CallGraphSCC &SCC) override { 2863 if (skipSCC(SCC)) 2864 return false; 2865 2866 SetVector<Function *> Functions; 2867 for (CallGraphNode *CGN : SCC) 2868 if (Function *Fn = CGN->getFunction()) 2869 if (!Fn->isDeclaration()) 2870 Functions.insert(Fn); 2871 2872 if (Functions.empty()) 2873 return false; 2874 2875 AnalysisGetter AG; 2876 CallGraph &CG = const_cast<CallGraph &>(SCC.getCallGraph()); 2877 CallGraphUpdater CGUpdater; 2878 CGUpdater.initialize(CG, SCC); 2879 Module &M = *Functions.back()->getParent(); 2880 BumpPtrAllocator Allocator; 2881 InformationCache InfoCache(M, AG, Allocator, /* CGSCC */ &Functions); 2882 return runAttributorOnFunctions(InfoCache, Functions, AG, CGUpdater, 2883 /* DeleteFns */ false); 2884 } 2885 2886 void getAnalysisUsage(AnalysisUsage &AU) const override { 2887 // FIXME: Think about passes we will preserve and add them here. 2888 AU.addRequired<TargetLibraryInfoWrapperPass>(); 2889 CallGraphSCCPass::getAnalysisUsage(AU); 2890 } 2891 }; 2892 2893 } // end anonymous namespace 2894 2895 Pass *llvm::createAttributorLegacyPass() { return new AttributorLegacyPass(); } 2896 Pass *llvm::createAttributorCGSCCLegacyPass() { 2897 return new AttributorCGSCCLegacyPass(); 2898 } 2899 2900 char AttributorLegacyPass::ID = 0; 2901 char AttributorCGSCCLegacyPass::ID = 0; 2902 2903 INITIALIZE_PASS_BEGIN(AttributorLegacyPass, "attributor", 2904 "Deduce and propagate attributes", false, false) 2905 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 2906 INITIALIZE_PASS_END(AttributorLegacyPass, "attributor", 2907 "Deduce and propagate attributes", false, false) 2908 INITIALIZE_PASS_BEGIN(AttributorCGSCCLegacyPass, "attributor-cgscc", 2909 "Deduce and propagate attributes (CGSCC pass)", false, 2910 false) 2911 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 2912 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) 2913 INITIALIZE_PASS_END(AttributorCGSCCLegacyPass, "attributor-cgscc", 2914 "Deduce and propagate attributes (CGSCC pass)", false, 2915 false) 2916