1 //===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass promotes "by reference" arguments to be "by value" arguments. In 11 // practice, this means looking for internal functions that have pointer 12 // arguments. If it can prove, through the use of alias analysis, that an 13 // argument is *only* loaded, then it can pass the value into the function 14 // instead of the address of the value. This can cause recursive simplification 15 // of code and lead to the elimination of allocas (especially in C++ template 16 // code like the STL). 17 // 18 // This pass also handles aggregate arguments that are passed into a function, 19 // scalarizing them if the elements of the aggregate are only loaded. Note that 20 // by default it refuses to scalarize aggregates which would require passing in 21 // more than three operands to the function, because passing thousands of 22 // operands for a large array or structure is unprofitable! This limit can be 23 // configured or disabled, however. 24 // 25 // Note that this transformation could also be done for arguments that are only 26 // stored to (returning the value instead), but does not currently. This case 27 // would be best handled when and if LLVM begins supporting multiple return 28 // values from functions. 29 // 30 //===----------------------------------------------------------------------===// 31 32 #include "llvm/Transforms/IPO.h" 33 #include "llvm/ADT/DepthFirstIterator.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringExtras.h" 36 #include "llvm/Analysis/AliasAnalysis.h" 37 #include "llvm/Analysis/AssumptionCache.h" 38 #include "llvm/Analysis/BasicAliasAnalysis.h" 39 #include "llvm/Analysis/CallGraph.h" 40 #include "llvm/Analysis/CallGraphSCCPass.h" 41 #include "llvm/Analysis/Loads.h" 42 #include "llvm/Analysis/TargetLibraryInfo.h" 43 #include "llvm/Analysis/ValueTracking.h" 44 #include "llvm/IR/CFG.h" 45 #include "llvm/IR/CallSite.h" 46 #include "llvm/IR/Constants.h" 47 #include "llvm/IR/DataLayout.h" 48 #include "llvm/IR/DebugInfo.h" 49 #include "llvm/IR/DerivedTypes.h" 50 #include "llvm/IR/Instructions.h" 51 #include "llvm/IR/LLVMContext.h" 52 #include "llvm/IR/Module.h" 53 #include "llvm/Support/Debug.h" 54 #include "llvm/Support/raw_ostream.h" 55 #include <set> 56 using namespace llvm; 57 58 #define DEBUG_TYPE "argpromotion" 59 60 STATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted"); 61 STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted"); 62 STATISTIC(NumByValArgsPromoted , "Number of byval arguments promoted"); 63 STATISTIC(NumArgumentsDead , "Number of dead pointer args eliminated"); 64 65 namespace { 66 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass. 67 /// 68 struct ArgPromotion : public CallGraphSCCPass { 69 void getAnalysisUsage(AnalysisUsage &AU) const override { 70 AU.addRequired<AssumptionCacheTracker>(); 71 AU.addRequired<TargetLibraryInfoWrapperPass>(); 72 getAAResultsAnalysisUsage(AU); 73 CallGraphSCCPass::getAnalysisUsage(AU); 74 } 75 76 bool runOnSCC(CallGraphSCC &SCC) override; 77 static char ID; // Pass identification, replacement for typeid 78 explicit ArgPromotion(unsigned maxElements = 3) 79 : CallGraphSCCPass(ID), maxElements(maxElements) { 80 initializeArgPromotionPass(*PassRegistry::getPassRegistry()); 81 } 82 83 /// A vector used to hold the indices of a single GEP instruction 84 typedef std::vector<uint64_t> IndicesVector; 85 86 private: 87 bool isDenselyPacked(Type *type, const DataLayout &DL); 88 bool canPaddingBeAccessed(Argument *Arg); 89 CallGraphNode *PromoteArguments(CallGraphNode *CGN); 90 bool isSafeToPromoteArgument(Argument *Arg, bool isByVal, 91 AAResults &AAR) const; 92 CallGraphNode *DoPromotion(Function *F, 93 SmallPtrSetImpl<Argument*> &ArgsToPromote, 94 SmallPtrSetImpl<Argument*> &ByValArgsToTransform); 95 96 using llvm::Pass::doInitialization; 97 bool doInitialization(CallGraph &CG) override; 98 /// The maximum number of elements to expand, or 0 for unlimited. 99 unsigned maxElements; 100 }; 101 } 102 103 char ArgPromotion::ID = 0; 104 INITIALIZE_PASS_BEGIN(ArgPromotion, "argpromotion", 105 "Promote 'by reference' arguments to scalars", false, false) 106 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 107 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) 108 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 109 INITIALIZE_PASS_END(ArgPromotion, "argpromotion", 110 "Promote 'by reference' arguments to scalars", false, false) 111 112 Pass *llvm::createArgumentPromotionPass(unsigned maxElements) { 113 return new ArgPromotion(maxElements); 114 } 115 116 bool ArgPromotion::runOnSCC(CallGraphSCC &SCC) { 117 bool Changed = false, LocalChange; 118 119 do { // Iterate until we stop promoting from this SCC. 120 LocalChange = false; 121 // Attempt to promote arguments from all functions in this SCC. 122 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) { 123 if (CallGraphNode *CGN = PromoteArguments(*I)) { 124 LocalChange = true; 125 SCC.ReplaceNode(*I, CGN); 126 } 127 } 128 Changed |= LocalChange; // Remember that we changed something. 129 } while (LocalChange); 130 131 return Changed; 132 } 133 134 /// \brief Checks if a type could have padding bytes. 135 bool ArgPromotion::isDenselyPacked(Type *type, const DataLayout &DL) { 136 137 // There is no size information, so be conservative. 138 if (!type->isSized()) 139 return false; 140 141 // If the alloc size is not equal to the storage size, then there are padding 142 // bytes. For x86_fp80 on x86-64, size: 80 alloc size: 128. 143 if (DL.getTypeSizeInBits(type) != DL.getTypeAllocSizeInBits(type)) 144 return false; 145 146 if (!isa<CompositeType>(type)) 147 return true; 148 149 // For homogenous sequential types, check for padding within members. 150 if (SequentialType *seqTy = dyn_cast<SequentialType>(type)) 151 return isa<PointerType>(seqTy) || 152 isDenselyPacked(seqTy->getElementType(), DL); 153 154 // Check for padding within and between elements of a struct. 155 StructType *StructTy = cast<StructType>(type); 156 const StructLayout *Layout = DL.getStructLayout(StructTy); 157 uint64_t StartPos = 0; 158 for (unsigned i = 0, E = StructTy->getNumElements(); i < E; ++i) { 159 Type *ElTy = StructTy->getElementType(i); 160 if (!isDenselyPacked(ElTy, DL)) 161 return false; 162 if (StartPos != Layout->getElementOffsetInBits(i)) 163 return false; 164 StartPos += DL.getTypeAllocSizeInBits(ElTy); 165 } 166 167 return true; 168 } 169 170 /// \brief Checks if the padding bytes of an argument could be accessed. 171 bool ArgPromotion::canPaddingBeAccessed(Argument *arg) { 172 173 assert(arg->hasByValAttr()); 174 175 // Track all the pointers to the argument to make sure they are not captured. 176 SmallPtrSet<Value *, 16> PtrValues; 177 PtrValues.insert(arg); 178 179 // Track all of the stores. 180 SmallVector<StoreInst *, 16> Stores; 181 182 // Scan through the uses recursively to make sure the pointer is always used 183 // sanely. 184 SmallVector<Value *, 16> WorkList; 185 WorkList.insert(WorkList.end(), arg->user_begin(), arg->user_end()); 186 while (!WorkList.empty()) { 187 Value *V = WorkList.back(); 188 WorkList.pop_back(); 189 if (isa<GetElementPtrInst>(V) || isa<PHINode>(V)) { 190 if (PtrValues.insert(V).second) 191 WorkList.insert(WorkList.end(), V->user_begin(), V->user_end()); 192 } else if (StoreInst *Store = dyn_cast<StoreInst>(V)) { 193 Stores.push_back(Store); 194 } else if (!isa<LoadInst>(V)) { 195 return true; 196 } 197 } 198 199 // Check to make sure the pointers aren't captured 200 for (StoreInst *Store : Stores) 201 if (PtrValues.count(Store->getValueOperand())) 202 return true; 203 204 return false; 205 } 206 207 /// PromoteArguments - This method checks the specified function to see if there 208 /// are any promotable arguments and if it is safe to promote the function (for 209 /// example, all callers are direct). If safe to promote some arguments, it 210 /// calls the DoPromotion method. 211 /// 212 CallGraphNode *ArgPromotion::PromoteArguments(CallGraphNode *CGN) { 213 Function *F = CGN->getFunction(); 214 215 // Make sure that it is local to this module. 216 if (!F || !F->hasLocalLinkage()) return nullptr; 217 218 // Don't promote arguments for variadic functions. Adding, removing, or 219 // changing non-pack parameters can change the classification of pack 220 // parameters. Frontends encode that classification at the call site in the 221 // IR, while in the callee the classification is determined dynamically based 222 // on the number of registers consumed so far. 223 if (F->isVarArg()) return nullptr; 224 225 // First check: see if there are any pointer arguments! If not, quick exit. 226 SmallVector<Argument*, 16> PointerArgs; 227 for (Argument &I : F->args()) 228 if (I.getType()->isPointerTy()) 229 PointerArgs.push_back(&I); 230 if (PointerArgs.empty()) return nullptr; 231 232 // Second check: make sure that all callers are direct callers. We can't 233 // transform functions that have indirect callers. Also see if the function 234 // is self-recursive. 235 bool isSelfRecursive = false; 236 for (Use &U : F->uses()) { 237 CallSite CS(U.getUser()); 238 // Must be a direct call. 239 if (CS.getInstruction() == nullptr || !CS.isCallee(&U)) return nullptr; 240 241 if (CS.getInstruction()->getParent()->getParent() == F) 242 isSelfRecursive = true; 243 } 244 245 const DataLayout &DL = F->getParent()->getDataLayout(); 246 247 // We need to manually construct BasicAA directly in order to disable its use 248 // of other function analyses. 249 BasicAAResult BAR(createLegacyPMBasicAAResult(*this, *F)); 250 251 // Construct our own AA results for this function. We do this manually to 252 // work around the limitations of the legacy pass manager. 253 AAResults AAR(createLegacyPMAAResults(*this, *F, BAR)); 254 255 // Check to see which arguments are promotable. If an argument is promotable, 256 // add it to ArgsToPromote. 257 SmallPtrSet<Argument*, 8> ArgsToPromote; 258 SmallPtrSet<Argument*, 8> ByValArgsToTransform; 259 for (unsigned i = 0, e = PointerArgs.size(); i != e; ++i) { 260 Argument *PtrArg = PointerArgs[i]; 261 Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType(); 262 263 // Replace sret attribute with noalias. This reduces register pressure by 264 // avoiding a register copy. 265 if (PtrArg->hasStructRetAttr()) { 266 unsigned ArgNo = PtrArg->getArgNo(); 267 F->setAttributes( 268 F->getAttributes() 269 .removeAttribute(F->getContext(), ArgNo + 1, Attribute::StructRet) 270 .addAttribute(F->getContext(), ArgNo + 1, Attribute::NoAlias)); 271 for (Use &U : F->uses()) { 272 CallSite CS(U.getUser()); 273 CS.setAttributes( 274 CS.getAttributes() 275 .removeAttribute(F->getContext(), ArgNo + 1, 276 Attribute::StructRet) 277 .addAttribute(F->getContext(), ArgNo + 1, Attribute::NoAlias)); 278 } 279 } 280 281 // If this is a byval argument, and if the aggregate type is small, just 282 // pass the elements, which is always safe, if the passed value is densely 283 // packed or if we can prove the padding bytes are never accessed. This does 284 // not apply to inalloca. 285 bool isSafeToPromote = 286 PtrArg->hasByValAttr() && 287 (isDenselyPacked(AgTy, DL) || !canPaddingBeAccessed(PtrArg)); 288 if (isSafeToPromote) { 289 if (StructType *STy = dyn_cast<StructType>(AgTy)) { 290 if (maxElements > 0 && STy->getNumElements() > maxElements) { 291 DEBUG(dbgs() << "argpromotion disable promoting argument '" 292 << PtrArg->getName() << "' because it would require adding more" 293 << " than " << maxElements << " arguments to the function.\n"); 294 continue; 295 } 296 297 // If all the elements are single-value types, we can promote it. 298 bool AllSimple = true; 299 for (const auto *EltTy : STy->elements()) { 300 if (!EltTy->isSingleValueType()) { 301 AllSimple = false; 302 break; 303 } 304 } 305 306 // Safe to transform, don't even bother trying to "promote" it. 307 // Passing the elements as a scalar will allow scalarrepl to hack on 308 // the new alloca we introduce. 309 if (AllSimple) { 310 ByValArgsToTransform.insert(PtrArg); 311 continue; 312 } 313 } 314 } 315 316 // If the argument is a recursive type and we're in a recursive 317 // function, we could end up infinitely peeling the function argument. 318 if (isSelfRecursive) { 319 if (StructType *STy = dyn_cast<StructType>(AgTy)) { 320 bool RecursiveType = false; 321 for (const auto *EltTy : STy->elements()) { 322 if (EltTy == PtrArg->getType()) { 323 RecursiveType = true; 324 break; 325 } 326 } 327 if (RecursiveType) 328 continue; 329 } 330 } 331 332 // Otherwise, see if we can promote the pointer to its value. 333 if (isSafeToPromoteArgument(PtrArg, PtrArg->hasByValOrInAllocaAttr(), AAR)) 334 ArgsToPromote.insert(PtrArg); 335 } 336 337 // No promotable pointer arguments. 338 if (ArgsToPromote.empty() && ByValArgsToTransform.empty()) 339 return nullptr; 340 341 return DoPromotion(F, ArgsToPromote, ByValArgsToTransform); 342 } 343 344 /// AllCallersPassInValidPointerForArgument - Return true if we can prove that 345 /// all callees pass in a valid pointer for the specified function argument. 346 static bool AllCallersPassInValidPointerForArgument(Argument *Arg) { 347 Function *Callee = Arg->getParent(); 348 const DataLayout &DL = Callee->getParent()->getDataLayout(); 349 350 unsigned ArgNo = Arg->getArgNo(); 351 352 // Look at all call sites of the function. At this pointer we know we only 353 // have direct callees. 354 for (User *U : Callee->users()) { 355 CallSite CS(U); 356 assert(CS && "Should only have direct calls!"); 357 358 if (!isDereferenceablePointer(CS.getArgument(ArgNo), DL)) 359 return false; 360 } 361 return true; 362 } 363 364 /// Returns true if Prefix is a prefix of longer. That means, Longer has a size 365 /// that is greater than or equal to the size of prefix, and each of the 366 /// elements in Prefix is the same as the corresponding elements in Longer. 367 /// 368 /// This means it also returns true when Prefix and Longer are equal! 369 static bool IsPrefix(const ArgPromotion::IndicesVector &Prefix, 370 const ArgPromotion::IndicesVector &Longer) { 371 if (Prefix.size() > Longer.size()) 372 return false; 373 return std::equal(Prefix.begin(), Prefix.end(), Longer.begin()); 374 } 375 376 377 /// Checks if Indices, or a prefix of Indices, is in Set. 378 static bool PrefixIn(const ArgPromotion::IndicesVector &Indices, 379 std::set<ArgPromotion::IndicesVector> &Set) { 380 std::set<ArgPromotion::IndicesVector>::iterator Low; 381 Low = Set.upper_bound(Indices); 382 if (Low != Set.begin()) 383 Low--; 384 // Low is now the last element smaller than or equal to Indices. This means 385 // it points to a prefix of Indices (possibly Indices itself), if such 386 // prefix exists. 387 // 388 // This load is safe if any prefix of its operands is safe to load. 389 return Low != Set.end() && IsPrefix(*Low, Indices); 390 } 391 392 /// Mark the given indices (ToMark) as safe in the given set of indices 393 /// (Safe). Marking safe usually means adding ToMark to Safe. However, if there 394 /// is already a prefix of Indices in Safe, Indices are implicitely marked safe 395 /// already. Furthermore, any indices that Indices is itself a prefix of, are 396 /// removed from Safe (since they are implicitely safe because of Indices now). 397 static void MarkIndicesSafe(const ArgPromotion::IndicesVector &ToMark, 398 std::set<ArgPromotion::IndicesVector> &Safe) { 399 std::set<ArgPromotion::IndicesVector>::iterator Low; 400 Low = Safe.upper_bound(ToMark); 401 // Guard against the case where Safe is empty 402 if (Low != Safe.begin()) 403 Low--; 404 // Low is now the last element smaller than or equal to Indices. This 405 // means it points to a prefix of Indices (possibly Indices itself), if 406 // such prefix exists. 407 if (Low != Safe.end()) { 408 if (IsPrefix(*Low, ToMark)) 409 // If there is already a prefix of these indices (or exactly these 410 // indices) marked a safe, don't bother adding these indices 411 return; 412 413 // Increment Low, so we can use it as a "insert before" hint 414 ++Low; 415 } 416 // Insert 417 Low = Safe.insert(Low, ToMark); 418 ++Low; 419 // If there we're a prefix of longer index list(s), remove those 420 std::set<ArgPromotion::IndicesVector>::iterator End = Safe.end(); 421 while (Low != End && IsPrefix(ToMark, *Low)) { 422 std::set<ArgPromotion::IndicesVector>::iterator Remove = Low; 423 ++Low; 424 Safe.erase(Remove); 425 } 426 } 427 428 /// isSafeToPromoteArgument - As you might guess from the name of this method, 429 /// it checks to see if it is both safe and useful to promote the argument. 430 /// This method limits promotion of aggregates to only promote up to three 431 /// elements of the aggregate in order to avoid exploding the number of 432 /// arguments passed in. 433 bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg, 434 bool isByValOrInAlloca, 435 AAResults &AAR) const { 436 typedef std::set<IndicesVector> GEPIndicesSet; 437 438 // Quick exit for unused arguments 439 if (Arg->use_empty()) 440 return true; 441 442 // We can only promote this argument if all of the uses are loads, or are GEP 443 // instructions (with constant indices) that are subsequently loaded. 444 // 445 // Promoting the argument causes it to be loaded in the caller 446 // unconditionally. This is only safe if we can prove that either the load 447 // would have happened in the callee anyway (ie, there is a load in the entry 448 // block) or the pointer passed in at every call site is guaranteed to be 449 // valid. 450 // In the former case, invalid loads can happen, but would have happened 451 // anyway, in the latter case, invalid loads won't happen. This prevents us 452 // from introducing an invalid load that wouldn't have happened in the 453 // original code. 454 // 455 // This set will contain all sets of indices that are loaded in the entry 456 // block, and thus are safe to unconditionally load in the caller. 457 // 458 // This optimization is also safe for InAlloca parameters, because it verifies 459 // that the address isn't captured. 460 GEPIndicesSet SafeToUnconditionallyLoad; 461 462 // This set contains all the sets of indices that we are planning to promote. 463 // This makes it possible to limit the number of arguments added. 464 GEPIndicesSet ToPromote; 465 466 // If the pointer is always valid, any load with first index 0 is valid. 467 if (isByValOrInAlloca || AllCallersPassInValidPointerForArgument(Arg)) 468 SafeToUnconditionallyLoad.insert(IndicesVector(1, 0)); 469 470 // First, iterate the entry block and mark loads of (geps of) arguments as 471 // safe. 472 BasicBlock &EntryBlock = Arg->getParent()->front(); 473 // Declare this here so we can reuse it 474 IndicesVector Indices; 475 for (Instruction &I : EntryBlock) 476 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) { 477 Value *V = LI->getPointerOperand(); 478 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) { 479 V = GEP->getPointerOperand(); 480 if (V == Arg) { 481 // This load actually loads (part of) Arg? Check the indices then. 482 Indices.reserve(GEP->getNumIndices()); 483 for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end(); 484 II != IE; ++II) 485 if (ConstantInt *CI = dyn_cast<ConstantInt>(*II)) 486 Indices.push_back(CI->getSExtValue()); 487 else 488 // We found a non-constant GEP index for this argument? Bail out 489 // right away, can't promote this argument at all. 490 return false; 491 492 // Indices checked out, mark them as safe 493 MarkIndicesSafe(Indices, SafeToUnconditionallyLoad); 494 Indices.clear(); 495 } 496 } else if (V == Arg) { 497 // Direct loads are equivalent to a GEP with a single 0 index. 498 MarkIndicesSafe(IndicesVector(1, 0), SafeToUnconditionallyLoad); 499 } 500 } 501 502 // Now, iterate all uses of the argument to see if there are any uses that are 503 // not (GEP+)loads, or any (GEP+)loads that are not safe to promote. 504 SmallVector<LoadInst*, 16> Loads; 505 IndicesVector Operands; 506 for (Use &U : Arg->uses()) { 507 User *UR = U.getUser(); 508 Operands.clear(); 509 if (LoadInst *LI = dyn_cast<LoadInst>(UR)) { 510 // Don't hack volatile/atomic loads 511 if (!LI->isSimple()) return false; 512 Loads.push_back(LI); 513 // Direct loads are equivalent to a GEP with a zero index and then a load. 514 Operands.push_back(0); 515 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UR)) { 516 if (GEP->use_empty()) { 517 // Dead GEP's cause trouble later. Just remove them if we run into 518 // them. 519 GEP->eraseFromParent(); 520 // TODO: This runs the above loop over and over again for dead GEPs 521 // Couldn't we just do increment the UI iterator earlier and erase the 522 // use? 523 return isSafeToPromoteArgument(Arg, isByValOrInAlloca, AAR); 524 } 525 526 // Ensure that all of the indices are constants. 527 for (User::op_iterator i = GEP->idx_begin(), e = GEP->idx_end(); 528 i != e; ++i) 529 if (ConstantInt *C = dyn_cast<ConstantInt>(*i)) 530 Operands.push_back(C->getSExtValue()); 531 else 532 return false; // Not a constant operand GEP! 533 534 // Ensure that the only users of the GEP are load instructions. 535 for (User *GEPU : GEP->users()) 536 if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) { 537 // Don't hack volatile/atomic loads 538 if (!LI->isSimple()) return false; 539 Loads.push_back(LI); 540 } else { 541 // Other uses than load? 542 return false; 543 } 544 } else { 545 return false; // Not a load or a GEP. 546 } 547 548 // Now, see if it is safe to promote this load / loads of this GEP. Loading 549 // is safe if Operands, or a prefix of Operands, is marked as safe. 550 if (!PrefixIn(Operands, SafeToUnconditionallyLoad)) 551 return false; 552 553 // See if we are already promoting a load with these indices. If not, check 554 // to make sure that we aren't promoting too many elements. If so, nothing 555 // to do. 556 if (ToPromote.find(Operands) == ToPromote.end()) { 557 if (maxElements > 0 && ToPromote.size() == maxElements) { 558 DEBUG(dbgs() << "argpromotion not promoting argument '" 559 << Arg->getName() << "' because it would require adding more " 560 << "than " << maxElements << " arguments to the function.\n"); 561 // We limit aggregate promotion to only promoting up to a fixed number 562 // of elements of the aggregate. 563 return false; 564 } 565 ToPromote.insert(std::move(Operands)); 566 } 567 } 568 569 if (Loads.empty()) return true; // No users, this is a dead argument. 570 571 // Okay, now we know that the argument is only used by load instructions and 572 // it is safe to unconditionally perform all of them. Use alias analysis to 573 // check to see if the pointer is guaranteed to not be modified from entry of 574 // the function to each of the load instructions. 575 576 // Because there could be several/many load instructions, remember which 577 // blocks we know to be transparent to the load. 578 SmallPtrSet<BasicBlock*, 16> TranspBlocks; 579 580 for (unsigned i = 0, e = Loads.size(); i != e; ++i) { 581 // Check to see if the load is invalidated from the start of the block to 582 // the load itself. 583 LoadInst *Load = Loads[i]; 584 BasicBlock *BB = Load->getParent(); 585 586 MemoryLocation Loc = MemoryLocation::get(Load); 587 if (AAR.canInstructionRangeModRef(BB->front(), *Load, Loc, MRI_Mod)) 588 return false; // Pointer is invalidated! 589 590 // Now check every path from the entry block to the load for transparency. 591 // To do this, we perform a depth first search on the inverse CFG from the 592 // loading block. 593 for (BasicBlock *P : predecessors(BB)) { 594 for (BasicBlock *TranspBB : inverse_depth_first_ext(P, TranspBlocks)) 595 if (AAR.canBasicBlockModify(*TranspBB, Loc)) 596 return false; 597 } 598 } 599 600 // If the path from the entry of the function to each load is free of 601 // instructions that potentially invalidate the load, we can make the 602 // transformation! 603 return true; 604 } 605 606 /// DoPromotion - This method actually performs the promotion of the specified 607 /// arguments, and returns the new function. At this point, we know that it's 608 /// safe to do so. 609 CallGraphNode *ArgPromotion::DoPromotion(Function *F, 610 SmallPtrSetImpl<Argument*> &ArgsToPromote, 611 SmallPtrSetImpl<Argument*> &ByValArgsToTransform) { 612 613 // Start by computing a new prototype for the function, which is the same as 614 // the old function, but has modified arguments. 615 FunctionType *FTy = F->getFunctionType(); 616 std::vector<Type*> Params; 617 618 typedef std::set<std::pair<Type *, IndicesVector>> ScalarizeTable; 619 620 // ScalarizedElements - If we are promoting a pointer that has elements 621 // accessed out of it, keep track of which elements are accessed so that we 622 // can add one argument for each. 623 // 624 // Arguments that are directly loaded will have a zero element value here, to 625 // handle cases where there are both a direct load and GEP accesses. 626 // 627 std::map<Argument*, ScalarizeTable> ScalarizedElements; 628 629 // OriginalLoads - Keep track of a representative load instruction from the 630 // original function so that we can tell the alias analysis implementation 631 // what the new GEP/Load instructions we are inserting look like. 632 // We need to keep the original loads for each argument and the elements 633 // of the argument that are accessed. 634 std::map<std::pair<Argument*, IndicesVector>, LoadInst*> OriginalLoads; 635 636 // Attribute - Keep track of the parameter attributes for the arguments 637 // that we are *not* promoting. For the ones that we do promote, the parameter 638 // attributes are lost 639 SmallVector<AttributeSet, 8> AttributesVec; 640 const AttributeSet &PAL = F->getAttributes(); 641 642 // Add any return attributes. 643 if (PAL.hasAttributes(AttributeSet::ReturnIndex)) 644 AttributesVec.push_back(AttributeSet::get(F->getContext(), 645 PAL.getRetAttributes())); 646 647 // First, determine the new argument list 648 unsigned ArgIndex = 1; 649 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; 650 ++I, ++ArgIndex) { 651 if (ByValArgsToTransform.count(&*I)) { 652 // Simple byval argument? Just add all the struct element types. 653 Type *AgTy = cast<PointerType>(I->getType())->getElementType(); 654 StructType *STy = cast<StructType>(AgTy); 655 Params.insert(Params.end(), STy->element_begin(), STy->element_end()); 656 ++NumByValArgsPromoted; 657 } else if (!ArgsToPromote.count(&*I)) { 658 // Unchanged argument 659 Params.push_back(I->getType()); 660 AttributeSet attrs = PAL.getParamAttributes(ArgIndex); 661 if (attrs.hasAttributes(ArgIndex)) { 662 AttrBuilder B(attrs, ArgIndex); 663 AttributesVec. 664 push_back(AttributeSet::get(F->getContext(), Params.size(), B)); 665 } 666 } else if (I->use_empty()) { 667 // Dead argument (which are always marked as promotable) 668 ++NumArgumentsDead; 669 } else { 670 // Okay, this is being promoted. This means that the only uses are loads 671 // or GEPs which are only used by loads 672 673 // In this table, we will track which indices are loaded from the argument 674 // (where direct loads are tracked as no indices). 675 ScalarizeTable &ArgIndices = ScalarizedElements[&*I]; 676 for (User *U : I->users()) { 677 Instruction *UI = cast<Instruction>(U); 678 Type *SrcTy; 679 if (LoadInst *L = dyn_cast<LoadInst>(UI)) 680 SrcTy = L->getType(); 681 else 682 SrcTy = cast<GetElementPtrInst>(UI)->getSourceElementType(); 683 IndicesVector Indices; 684 Indices.reserve(UI->getNumOperands() - 1); 685 // Since loads will only have a single operand, and GEPs only a single 686 // non-index operand, this will record direct loads without any indices, 687 // and gep+loads with the GEP indices. 688 for (User::op_iterator II = UI->op_begin() + 1, IE = UI->op_end(); 689 II != IE; ++II) 690 Indices.push_back(cast<ConstantInt>(*II)->getSExtValue()); 691 // GEPs with a single 0 index can be merged with direct loads 692 if (Indices.size() == 1 && Indices.front() == 0) 693 Indices.clear(); 694 ArgIndices.insert(std::make_pair(SrcTy, Indices)); 695 LoadInst *OrigLoad; 696 if (LoadInst *L = dyn_cast<LoadInst>(UI)) 697 OrigLoad = L; 698 else 699 // Take any load, we will use it only to update Alias Analysis 700 OrigLoad = cast<LoadInst>(UI->user_back()); 701 OriginalLoads[std::make_pair(&*I, Indices)] = OrigLoad; 702 } 703 704 // Add a parameter to the function for each element passed in. 705 for (ScalarizeTable::iterator SI = ArgIndices.begin(), 706 E = ArgIndices.end(); SI != E; ++SI) { 707 // not allowed to dereference ->begin() if size() is 0 708 Params.push_back(GetElementPtrInst::getIndexedType( 709 cast<PointerType>(I->getType()->getScalarType())->getElementType(), 710 SI->second)); 711 assert(Params.back()); 712 } 713 714 if (ArgIndices.size() == 1 && ArgIndices.begin()->second.empty()) 715 ++NumArgumentsPromoted; 716 else 717 ++NumAggregatesPromoted; 718 } 719 } 720 721 // Add any function attributes. 722 if (PAL.hasAttributes(AttributeSet::FunctionIndex)) 723 AttributesVec.push_back(AttributeSet::get(FTy->getContext(), 724 PAL.getFnAttributes())); 725 726 Type *RetTy = FTy->getReturnType(); 727 728 // Construct the new function type using the new arguments. 729 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg()); 730 731 // Create the new function body and insert it into the module. 732 Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName()); 733 NF->copyAttributesFrom(F); 734 735 // Patch the pointer to LLVM function in debug info descriptor. 736 NF->setSubprogram(F->getSubprogram()); 737 F->setSubprogram(nullptr); 738 739 DEBUG(dbgs() << "ARG PROMOTION: Promoting to:" << *NF << "\n" 740 << "From: " << *F); 741 742 // Recompute the parameter attributes list based on the new arguments for 743 // the function. 744 NF->setAttributes(AttributeSet::get(F->getContext(), AttributesVec)); 745 AttributesVec.clear(); 746 747 F->getParent()->getFunctionList().insert(F->getIterator(), NF); 748 NF->takeName(F); 749 750 // Get the callgraph information that we need to update to reflect our 751 // changes. 752 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); 753 754 // Get a new callgraph node for NF. 755 CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF); 756 757 // Loop over all of the callers of the function, transforming the call sites 758 // to pass in the loaded pointers. 759 // 760 SmallVector<Value*, 16> Args; 761 while (!F->use_empty()) { 762 CallSite CS(F->user_back()); 763 assert(CS.getCalledFunction() == F); 764 Instruction *Call = CS.getInstruction(); 765 const AttributeSet &CallPAL = CS.getAttributes(); 766 767 // Add any return attributes. 768 if (CallPAL.hasAttributes(AttributeSet::ReturnIndex)) 769 AttributesVec.push_back(AttributeSet::get(F->getContext(), 770 CallPAL.getRetAttributes())); 771 772 // Loop over the operands, inserting GEP and loads in the caller as 773 // appropriate. 774 CallSite::arg_iterator AI = CS.arg_begin(); 775 ArgIndex = 1; 776 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); 777 I != E; ++I, ++AI, ++ArgIndex) 778 if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) { 779 Args.push_back(*AI); // Unmodified argument 780 781 if (CallPAL.hasAttributes(ArgIndex)) { 782 AttrBuilder B(CallPAL, ArgIndex); 783 AttributesVec. 784 push_back(AttributeSet::get(F->getContext(), Args.size(), B)); 785 } 786 } else if (ByValArgsToTransform.count(&*I)) { 787 // Emit a GEP and load for each element of the struct. 788 Type *AgTy = cast<PointerType>(I->getType())->getElementType(); 789 StructType *STy = cast<StructType>(AgTy); 790 Value *Idxs[2] = { 791 ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr }; 792 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 793 Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i); 794 Value *Idx = GetElementPtrInst::Create( 795 STy, *AI, Idxs, (*AI)->getName() + "." + Twine(i), Call); 796 // TODO: Tell AA about the new values? 797 Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call)); 798 } 799 } else if (!I->use_empty()) { 800 // Non-dead argument: insert GEPs and loads as appropriate. 801 ScalarizeTable &ArgIndices = ScalarizedElements[&*I]; 802 // Store the Value* version of the indices in here, but declare it now 803 // for reuse. 804 std::vector<Value*> Ops; 805 for (ScalarizeTable::iterator SI = ArgIndices.begin(), 806 E = ArgIndices.end(); SI != E; ++SI) { 807 Value *V = *AI; 808 LoadInst *OrigLoad = OriginalLoads[std::make_pair(&*I, SI->second)]; 809 if (!SI->second.empty()) { 810 Ops.reserve(SI->second.size()); 811 Type *ElTy = V->getType(); 812 for (IndicesVector::const_iterator II = SI->second.begin(), 813 IE = SI->second.end(); 814 II != IE; ++II) { 815 // Use i32 to index structs, and i64 for others (pointers/arrays). 816 // This satisfies GEP constraints. 817 Type *IdxTy = (ElTy->isStructTy() ? 818 Type::getInt32Ty(F->getContext()) : 819 Type::getInt64Ty(F->getContext())); 820 Ops.push_back(ConstantInt::get(IdxTy, *II)); 821 // Keep track of the type we're currently indexing. 822 ElTy = cast<CompositeType>(ElTy)->getTypeAtIndex(*II); 823 } 824 // And create a GEP to extract those indices. 825 V = GetElementPtrInst::Create(SI->first, V, Ops, 826 V->getName() + ".idx", Call); 827 Ops.clear(); 828 } 829 // Since we're replacing a load make sure we take the alignment 830 // of the previous load. 831 LoadInst *newLoad = new LoadInst(V, V->getName()+".val", Call); 832 newLoad->setAlignment(OrigLoad->getAlignment()); 833 // Transfer the AA info too. 834 AAMDNodes AAInfo; 835 OrigLoad->getAAMetadata(AAInfo); 836 newLoad->setAAMetadata(AAInfo); 837 838 Args.push_back(newLoad); 839 } 840 } 841 842 // Push any varargs arguments on the list. 843 for (; AI != CS.arg_end(); ++AI, ++ArgIndex) { 844 Args.push_back(*AI); 845 if (CallPAL.hasAttributes(ArgIndex)) { 846 AttrBuilder B(CallPAL, ArgIndex); 847 AttributesVec. 848 push_back(AttributeSet::get(F->getContext(), Args.size(), B)); 849 } 850 } 851 852 // Add any function attributes. 853 if (CallPAL.hasAttributes(AttributeSet::FunctionIndex)) 854 AttributesVec.push_back(AttributeSet::get(Call->getContext(), 855 CallPAL.getFnAttributes())); 856 857 Instruction *New; 858 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) { 859 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(), 860 Args, "", Call); 861 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv()); 862 cast<InvokeInst>(New)->setAttributes(AttributeSet::get(II->getContext(), 863 AttributesVec)); 864 } else { 865 New = CallInst::Create(NF, Args, "", Call); 866 cast<CallInst>(New)->setCallingConv(CS.getCallingConv()); 867 cast<CallInst>(New)->setAttributes(AttributeSet::get(New->getContext(), 868 AttributesVec)); 869 if (cast<CallInst>(Call)->isTailCall()) 870 cast<CallInst>(New)->setTailCall(); 871 } 872 New->setDebugLoc(Call->getDebugLoc()); 873 Args.clear(); 874 AttributesVec.clear(); 875 876 // Update the callgraph to know that the callsite has been transformed. 877 CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()]; 878 CalleeNode->replaceCallEdge(CS, CallSite(New), NF_CGN); 879 880 if (!Call->use_empty()) { 881 Call->replaceAllUsesWith(New); 882 New->takeName(Call); 883 } 884 885 // Finally, remove the old call from the program, reducing the use-count of 886 // F. 887 Call->eraseFromParent(); 888 } 889 890 // Since we have now created the new function, splice the body of the old 891 // function right into the new function, leaving the old rotting hulk of the 892 // function empty. 893 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList()); 894 895 // Loop over the argument list, transferring uses of the old arguments over to 896 // the new arguments, also transferring over the names as well. 897 // 898 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(), 899 I2 = NF->arg_begin(); I != E; ++I) { 900 if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) { 901 // If this is an unmodified argument, move the name and users over to the 902 // new version. 903 I->replaceAllUsesWith(&*I2); 904 I2->takeName(&*I); 905 ++I2; 906 continue; 907 } 908 909 if (ByValArgsToTransform.count(&*I)) { 910 // In the callee, we create an alloca, and store each of the new incoming 911 // arguments into the alloca. 912 Instruction *InsertPt = &NF->begin()->front(); 913 914 // Just add all the struct element types. 915 Type *AgTy = cast<PointerType>(I->getType())->getElementType(); 916 Value *TheAlloca = new AllocaInst(AgTy, nullptr, "", InsertPt); 917 StructType *STy = cast<StructType>(AgTy); 918 Value *Idxs[2] = { 919 ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr }; 920 921 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 922 Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i); 923 Value *Idx = GetElementPtrInst::Create( 924 AgTy, TheAlloca, Idxs, TheAlloca->getName() + "." + Twine(i), 925 InsertPt); 926 I2->setName(I->getName()+"."+Twine(i)); 927 new StoreInst(&*I2++, Idx, InsertPt); 928 } 929 930 // Anything that used the arg should now use the alloca. 931 I->replaceAllUsesWith(TheAlloca); 932 TheAlloca->takeName(&*I); 933 934 // If the alloca is used in a call, we must clear the tail flag since 935 // the callee now uses an alloca from the caller. 936 for (User *U : TheAlloca->users()) { 937 CallInst *Call = dyn_cast<CallInst>(U); 938 if (!Call) 939 continue; 940 Call->setTailCall(false); 941 } 942 continue; 943 } 944 945 if (I->use_empty()) 946 continue; 947 948 // Otherwise, if we promoted this argument, then all users are load 949 // instructions (or GEPs with only load users), and all loads should be 950 // using the new argument that we added. 951 ScalarizeTable &ArgIndices = ScalarizedElements[&*I]; 952 953 while (!I->use_empty()) { 954 if (LoadInst *LI = dyn_cast<LoadInst>(I->user_back())) { 955 assert(ArgIndices.begin()->second.empty() && 956 "Load element should sort to front!"); 957 I2->setName(I->getName()+".val"); 958 LI->replaceAllUsesWith(&*I2); 959 LI->eraseFromParent(); 960 DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName() 961 << "' in function '" << F->getName() << "'\n"); 962 } else { 963 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->user_back()); 964 IndicesVector Operands; 965 Operands.reserve(GEP->getNumIndices()); 966 for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end(); 967 II != IE; ++II) 968 Operands.push_back(cast<ConstantInt>(*II)->getSExtValue()); 969 970 // GEPs with a single 0 index can be merged with direct loads 971 if (Operands.size() == 1 && Operands.front() == 0) 972 Operands.clear(); 973 974 Function::arg_iterator TheArg = I2; 975 for (ScalarizeTable::iterator It = ArgIndices.begin(); 976 It->second != Operands; ++It, ++TheArg) { 977 assert(It != ArgIndices.end() && "GEP not handled??"); 978 } 979 980 std::string NewName = I->getName(); 981 for (unsigned i = 0, e = Operands.size(); i != e; ++i) { 982 NewName += "." + utostr(Operands[i]); 983 } 984 NewName += ".val"; 985 TheArg->setName(NewName); 986 987 DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName() 988 << "' of function '" << NF->getName() << "'\n"); 989 990 // All of the uses must be load instructions. Replace them all with 991 // the argument specified by ArgNo. 992 while (!GEP->use_empty()) { 993 LoadInst *L = cast<LoadInst>(GEP->user_back()); 994 L->replaceAllUsesWith(&*TheArg); 995 L->eraseFromParent(); 996 } 997 GEP->eraseFromParent(); 998 } 999 } 1000 1001 // Increment I2 past all of the arguments added for this promoted pointer. 1002 std::advance(I2, ArgIndices.size()); 1003 } 1004 1005 NF_CGN->stealCalledFunctionsFrom(CG[F]); 1006 1007 // Now that the old function is dead, delete it. If there is a dangling 1008 // reference to the CallgraphNode, just leave the dead function around for 1009 // someone else to nuke. 1010 CallGraphNode *CGN = CG[F]; 1011 if (CGN->getNumReferences() == 0) 1012 delete CG.removeFunctionFromModule(CGN); 1013 else 1014 F->setLinkage(Function::ExternalLinkage); 1015 1016 return NF_CGN; 1017 } 1018 1019 bool ArgPromotion::doInitialization(CallGraph &CG) { 1020 return CallGraphSCCPass::doInitialization(CG); 1021 } 1022