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/TargetLibraryInfo.h" 42 #include "llvm/Analysis/ValueTracking.h" 43 #include "llvm/IR/CFG.h" 44 #include "llvm/IR/CallSite.h" 45 #include "llvm/IR/Constants.h" 46 #include "llvm/IR/DataLayout.h" 47 #include "llvm/IR/DebugInfo.h" 48 #include "llvm/IR/DerivedTypes.h" 49 #include "llvm/IR/Instructions.h" 50 #include "llvm/IR/LLVMContext.h" 51 #include "llvm/IR/Module.h" 52 #include "llvm/Support/Debug.h" 53 #include "llvm/Support/raw_ostream.h" 54 #include <set> 55 using namespace llvm; 56 57 #define DEBUG_TYPE "argpromotion" 58 59 STATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted"); 60 STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted"); 61 STATISTIC(NumByValArgsPromoted , "Number of byval arguments promoted"); 62 STATISTIC(NumArgumentsDead , "Number of dead pointer args eliminated"); 63 64 namespace { 65 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass. 66 /// 67 struct ArgPromotion : public CallGraphSCCPass { 68 void getAnalysisUsage(AnalysisUsage &AU) const override { 69 AU.addRequired<AssumptionCacheTracker>(); 70 AU.addRequired<TargetLibraryInfoWrapperPass>(); 71 CallGraphSCCPass::getAnalysisUsage(AU); 72 } 73 74 bool runOnSCC(CallGraphSCC &SCC) override; 75 static char ID; // Pass identification, replacement for typeid 76 explicit ArgPromotion(unsigned maxElements = 3) 77 : CallGraphSCCPass(ID), maxElements(maxElements) { 78 initializeArgPromotionPass(*PassRegistry::getPassRegistry()); 79 } 80 81 /// A vector used to hold the indices of a single GEP instruction 82 typedef std::vector<uint64_t> IndicesVector; 83 84 private: 85 bool isDenselyPacked(Type *type, const DataLayout &DL); 86 bool canPaddingBeAccessed(Argument *Arg); 87 CallGraphNode *PromoteArguments(CallGraphNode *CGN); 88 bool isSafeToPromoteArgument(Argument *Arg, bool isByVal, 89 AAResults &AAR) const; 90 CallGraphNode *DoPromotion(Function *F, 91 SmallPtrSetImpl<Argument*> &ArgsToPromote, 92 SmallPtrSetImpl<Argument*> &ByValArgsToTransform); 93 94 using llvm::Pass::doInitialization; 95 bool doInitialization(CallGraph &CG) override; 96 /// The maximum number of elements to expand, or 0 for unlimited. 97 unsigned maxElements; 98 DenseMap<const Function *, DISubprogram *> FunctionDIs; 99 }; 100 } 101 102 char ArgPromotion::ID = 0; 103 INITIALIZE_PASS_BEGIN(ArgPromotion, "argpromotion", 104 "Promote 'by reference' arguments to scalars", false, false) 105 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 106 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) 107 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 108 INITIALIZE_PASS_END(ArgPromotion, "argpromotion", 109 "Promote 'by reference' arguments to scalars", false, false) 110 111 Pass *llvm::createArgumentPromotionPass(unsigned maxElements) { 112 return new ArgPromotion(maxElements); 113 } 114 115 bool ArgPromotion::runOnSCC(CallGraphSCC &SCC) { 116 bool Changed = false, LocalChange; 117 118 do { // Iterate until we stop promoting from this SCC. 119 LocalChange = false; 120 // Attempt to promote arguments from all functions in this SCC. 121 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) { 122 if (CallGraphNode *CGN = PromoteArguments(*I)) { 123 LocalChange = true; 124 SCC.ReplaceNode(*I, CGN); 125 } 126 } 127 Changed |= LocalChange; // Remember that we changed something. 128 } while (LocalChange); 129 130 return Changed; 131 } 132 133 /// \brief Checks if a type could have padding bytes. 134 bool ArgPromotion::isDenselyPacked(Type *type, const DataLayout &DL) { 135 136 // There is no size information, so be conservative. 137 if (!type->isSized()) 138 return false; 139 140 // If the alloc size is not equal to the storage size, then there are padding 141 // bytes. For x86_fp80 on x86-64, size: 80 alloc size: 128. 142 if (DL.getTypeSizeInBits(type) != DL.getTypeAllocSizeInBits(type)) 143 return false; 144 145 if (!isa<CompositeType>(type)) 146 return true; 147 148 // For homogenous sequential types, check for padding within members. 149 if (SequentialType *seqTy = dyn_cast<SequentialType>(type)) 150 return isa<PointerType>(seqTy) || 151 isDenselyPacked(seqTy->getElementType(), DL); 152 153 // Check for padding within and between elements of a struct. 154 StructType *StructTy = cast<StructType>(type); 155 const StructLayout *Layout = DL.getStructLayout(StructTy); 156 uint64_t StartPos = 0; 157 for (unsigned i = 0, E = StructTy->getNumElements(); i < E; ++i) { 158 Type *ElTy = StructTy->getElementType(i); 159 if (!isDenselyPacked(ElTy, DL)) 160 return false; 161 if (StartPos != Layout->getElementOffsetInBits(i)) 162 return false; 163 StartPos += DL.getTypeAllocSizeInBits(ElTy); 164 } 165 166 return true; 167 } 168 169 /// \brief Checks if the padding bytes of an argument could be accessed. 170 bool ArgPromotion::canPaddingBeAccessed(Argument *arg) { 171 172 assert(arg->hasByValAttr()); 173 174 // Track all the pointers to the argument to make sure they are not captured. 175 SmallPtrSet<Value *, 16> PtrValues; 176 PtrValues.insert(arg); 177 178 // Track all of the stores. 179 SmallVector<StoreInst *, 16> Stores; 180 181 // Scan through the uses recursively to make sure the pointer is always used 182 // sanely. 183 SmallVector<Value *, 16> WorkList; 184 WorkList.insert(WorkList.end(), arg->user_begin(), arg->user_end()); 185 while (!WorkList.empty()) { 186 Value *V = WorkList.back(); 187 WorkList.pop_back(); 188 if (isa<GetElementPtrInst>(V) || isa<PHINode>(V)) { 189 if (PtrValues.insert(V).second) 190 WorkList.insert(WorkList.end(), V->user_begin(), V->user_end()); 191 } else if (StoreInst *Store = dyn_cast<StoreInst>(V)) { 192 Stores.push_back(Store); 193 } else if (!isa<LoadInst>(V)) { 194 return true; 195 } 196 } 197 198 // Check to make sure the pointers aren't captured 199 for (StoreInst *Store : Stores) 200 if (PtrValues.count(Store->getValueOperand())) 201 return true; 202 203 return false; 204 } 205 206 /// PromoteArguments - This method checks the specified function to see if there 207 /// are any promotable arguments and if it is safe to promote the function (for 208 /// example, all callers are direct). If safe to promote some arguments, it 209 /// calls the DoPromotion method. 210 /// 211 CallGraphNode *ArgPromotion::PromoteArguments(CallGraphNode *CGN) { 212 Function *F = CGN->getFunction(); 213 214 // Make sure that it is local to this module. 215 if (!F || !F->hasLocalLinkage()) return nullptr; 216 217 // Don't promote arguments for variadic functions. Adding, removing, or 218 // changing non-pack parameters can change the classification of pack 219 // parameters. Frontends encode that classification at the call site in the 220 // IR, while in the callee the classification is determined dynamically based 221 // on the number of registers consumed so far. 222 if (F->isVarArg()) return nullptr; 223 224 // First check: see if there are any pointer arguments! If not, quick exit. 225 SmallVector<Argument*, 16> PointerArgs; 226 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) 227 if (I->getType()->isPointerTy()) 228 PointerArgs.push_back(I); 229 if (PointerArgs.empty()) return nullptr; 230 231 // Second check: make sure that all callers are direct callers. We can't 232 // transform functions that have indirect callers. Also see if the function 233 // is self-recursive. 234 bool isSelfRecursive = false; 235 for (Use &U : F->uses()) { 236 CallSite CS(U.getUser()); 237 // Must be a direct call. 238 if (CS.getInstruction() == nullptr || !CS.isCallee(&U)) return nullptr; 239 240 if (CS.getInstruction()->getParent()->getParent() == F) 241 isSelfRecursive = true; 242 } 243 244 const DataLayout &DL = F->getParent()->getDataLayout(); 245 246 // We need to manually construct BasicAA directly in order to disable its use 247 // of other function analyses. 248 BasicAAResult BAR(createLegacyPMBasicAAResult(*this, *F)); 249 250 // Construct our own AA results for this function. We do this manually to 251 // work around the limitations of the legacy pass manager. 252 AAResults AAR(createLegacyPMAAResults(*this, *F, BAR)); 253 254 // Check to see which arguments are promotable. If an argument is promotable, 255 // add it to ArgsToPromote. 256 SmallPtrSet<Argument*, 8> ArgsToPromote; 257 SmallPtrSet<Argument*, 8> ByValArgsToTransform; 258 for (unsigned i = 0, e = PointerArgs.size(); i != e; ++i) { 259 Argument *PtrArg = PointerArgs[i]; 260 Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType(); 261 262 // Replace sret attribute with noalias. This reduces register pressure by 263 // avoiding a register copy. 264 if (PtrArg->hasStructRetAttr()) { 265 unsigned ArgNo = PtrArg->getArgNo(); 266 F->setAttributes( 267 F->getAttributes() 268 .removeAttribute(F->getContext(), ArgNo + 1, Attribute::StructRet) 269 .addAttribute(F->getContext(), ArgNo + 1, Attribute::NoAlias)); 270 for (Use &U : F->uses()) { 271 CallSite CS(U.getUser()); 272 CS.setAttributes( 273 CS.getAttributes() 274 .removeAttribute(F->getContext(), ArgNo + 1, 275 Attribute::StructRet) 276 .addAttribute(F->getContext(), ArgNo + 1, Attribute::NoAlias)); 277 } 278 } 279 280 // If this is a byval argument, and if the aggregate type is small, just 281 // pass the elements, which is always safe, if the passed value is densely 282 // packed or if we can prove the padding bytes are never accessed. This does 283 // not apply to inalloca. 284 bool isSafeToPromote = 285 PtrArg->hasByValAttr() && 286 (isDenselyPacked(AgTy, DL) || !canPaddingBeAccessed(PtrArg)); 287 if (isSafeToPromote) { 288 if (StructType *STy = dyn_cast<StructType>(AgTy)) { 289 if (maxElements > 0 && STy->getNumElements() > maxElements) { 290 DEBUG(dbgs() << "argpromotion disable promoting argument '" 291 << PtrArg->getName() << "' because it would require adding more" 292 << " than " << maxElements << " arguments to the function.\n"); 293 continue; 294 } 295 296 // If all the elements are single-value types, we can promote it. 297 bool AllSimple = true; 298 for (const auto *EltTy : STy->elements()) { 299 if (!EltTy->isSingleValueType()) { 300 AllSimple = false; 301 break; 302 } 303 } 304 305 // Safe to transform, don't even bother trying to "promote" it. 306 // Passing the elements as a scalar will allow scalarrepl to hack on 307 // the new alloca we introduce. 308 if (AllSimple) { 309 ByValArgsToTransform.insert(PtrArg); 310 continue; 311 } 312 } 313 } 314 315 // If the argument is a recursive type and we're in a recursive 316 // function, we could end up infinitely peeling the function argument. 317 if (isSelfRecursive) { 318 if (StructType *STy = dyn_cast<StructType>(AgTy)) { 319 bool RecursiveType = false; 320 for (const auto *EltTy : STy->elements()) { 321 if (EltTy == PtrArg->getType()) { 322 RecursiveType = true; 323 break; 324 } 325 } 326 if (RecursiveType) 327 continue; 328 } 329 } 330 331 // Otherwise, see if we can promote the pointer to its value. 332 if (isSafeToPromoteArgument(PtrArg, PtrArg->hasByValOrInAllocaAttr(), AAR)) 333 ArgsToPromote.insert(PtrArg); 334 } 335 336 // No promotable pointer arguments. 337 if (ArgsToPromote.empty() && ByValArgsToTransform.empty()) 338 return nullptr; 339 340 return DoPromotion(F, ArgsToPromote, ByValArgsToTransform); 341 } 342 343 /// AllCallersPassInValidPointerForArgument - Return true if we can prove that 344 /// all callees pass in a valid pointer for the specified function argument. 345 static bool AllCallersPassInValidPointerForArgument(Argument *Arg) { 346 Function *Callee = Arg->getParent(); 347 const DataLayout &DL = Callee->getParent()->getDataLayout(); 348 349 unsigned ArgNo = Arg->getArgNo(); 350 351 // Look at all call sites of the function. At this pointer we know we only 352 // have direct callees. 353 for (User *U : Callee->users()) { 354 CallSite CS(U); 355 assert(CS && "Should only have direct calls!"); 356 357 if (!isDereferenceablePointer(CS.getArgument(ArgNo), DL)) 358 return false; 359 } 360 return true; 361 } 362 363 /// Returns true if Prefix is a prefix of longer. That means, Longer has a size 364 /// that is greater than or equal to the size of prefix, and each of the 365 /// elements in Prefix is the same as the corresponding elements in Longer. 366 /// 367 /// This means it also returns true when Prefix and Longer are equal! 368 static bool IsPrefix(const ArgPromotion::IndicesVector &Prefix, 369 const ArgPromotion::IndicesVector &Longer) { 370 if (Prefix.size() > Longer.size()) 371 return false; 372 return std::equal(Prefix.begin(), Prefix.end(), Longer.begin()); 373 } 374 375 376 /// Checks if Indices, or a prefix of Indices, is in Set. 377 static bool PrefixIn(const ArgPromotion::IndicesVector &Indices, 378 std::set<ArgPromotion::IndicesVector> &Set) { 379 std::set<ArgPromotion::IndicesVector>::iterator Low; 380 Low = Set.upper_bound(Indices); 381 if (Low != Set.begin()) 382 Low--; 383 // Low is now the last element smaller than or equal to Indices. This means 384 // it points to a prefix of Indices (possibly Indices itself), if such 385 // prefix exists. 386 // 387 // This load is safe if any prefix of its operands is safe to load. 388 return Low != Set.end() && IsPrefix(*Low, Indices); 389 } 390 391 /// Mark the given indices (ToMark) as safe in the given set of indices 392 /// (Safe). Marking safe usually means adding ToMark to Safe. However, if there 393 /// is already a prefix of Indices in Safe, Indices are implicitely marked safe 394 /// already. Furthermore, any indices that Indices is itself a prefix of, are 395 /// removed from Safe (since they are implicitely safe because of Indices now). 396 static void MarkIndicesSafe(const ArgPromotion::IndicesVector &ToMark, 397 std::set<ArgPromotion::IndicesVector> &Safe) { 398 std::set<ArgPromotion::IndicesVector>::iterator Low; 399 Low = Safe.upper_bound(ToMark); 400 // Guard against the case where Safe is empty 401 if (Low != Safe.begin()) 402 Low--; 403 // Low is now the last element smaller than or equal to Indices. This 404 // means it points to a prefix of Indices (possibly Indices itself), if 405 // such prefix exists. 406 if (Low != Safe.end()) { 407 if (IsPrefix(*Low, ToMark)) 408 // If there is already a prefix of these indices (or exactly these 409 // indices) marked a safe, don't bother adding these indices 410 return; 411 412 // Increment Low, so we can use it as a "insert before" hint 413 ++Low; 414 } 415 // Insert 416 Low = Safe.insert(Low, ToMark); 417 ++Low; 418 // If there we're a prefix of longer index list(s), remove those 419 std::set<ArgPromotion::IndicesVector>::iterator End = Safe.end(); 420 while (Low != End && IsPrefix(ToMark, *Low)) { 421 std::set<ArgPromotion::IndicesVector>::iterator Remove = Low; 422 ++Low; 423 Safe.erase(Remove); 424 } 425 } 426 427 /// isSafeToPromoteArgument - As you might guess from the name of this method, 428 /// it checks to see if it is both safe and useful to promote the argument. 429 /// This method limits promotion of aggregates to only promote up to three 430 /// elements of the aggregate in order to avoid exploding the number of 431 /// arguments passed in. 432 bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg, 433 bool isByValOrInAlloca, 434 AAResults &AAR) const { 435 typedef std::set<IndicesVector> GEPIndicesSet; 436 437 // Quick exit for unused arguments 438 if (Arg->use_empty()) 439 return true; 440 441 // We can only promote this argument if all of the uses are loads, or are GEP 442 // instructions (with constant indices) that are subsequently loaded. 443 // 444 // Promoting the argument causes it to be loaded in the caller 445 // unconditionally. This is only safe if we can prove that either the load 446 // would have happened in the callee anyway (ie, there is a load in the entry 447 // block) or the pointer passed in at every call site is guaranteed to be 448 // valid. 449 // In the former case, invalid loads can happen, but would have happened 450 // anyway, in the latter case, invalid loads won't happen. This prevents us 451 // from introducing an invalid load that wouldn't have happened in the 452 // original code. 453 // 454 // This set will contain all sets of indices that are loaded in the entry 455 // block, and thus are safe to unconditionally load in the caller. 456 // 457 // This optimization is also safe for InAlloca parameters, because it verifies 458 // that the address isn't captured. 459 GEPIndicesSet SafeToUnconditionallyLoad; 460 461 // This set contains all the sets of indices that we are planning to promote. 462 // This makes it possible to limit the number of arguments added. 463 GEPIndicesSet ToPromote; 464 465 // If the pointer is always valid, any load with first index 0 is valid. 466 if (isByValOrInAlloca || AllCallersPassInValidPointerForArgument(Arg)) 467 SafeToUnconditionallyLoad.insert(IndicesVector(1, 0)); 468 469 // First, iterate the entry block and mark loads of (geps of) arguments as 470 // safe. 471 BasicBlock *EntryBlock = Arg->getParent()->begin(); 472 // Declare this here so we can reuse it 473 IndicesVector Indices; 474 for (BasicBlock::iterator I = EntryBlock->begin(), E = EntryBlock->end(); 475 I != E; ++I) 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 auto DI = FunctionDIs.find(F); 737 if (DI != FunctionDIs.end()) { 738 DISubprogram *SP = DI->second; 739 SP->replaceFunction(NF); 740 // Ensure the map is updated so it can be reused on subsequent argument 741 // promotions of the same function. 742 FunctionDIs.erase(DI); 743 FunctionDIs[NF] = SP; 744 } 745 746 DEBUG(dbgs() << "ARG PROMOTION: Promoting to:" << *NF << "\n" 747 << "From: " << *F); 748 749 // Recompute the parameter attributes list based on the new arguments for 750 // the function. 751 NF->setAttributes(AttributeSet::get(F->getContext(), AttributesVec)); 752 AttributesVec.clear(); 753 754 F->getParent()->getFunctionList().insert(F, NF); 755 NF->takeName(F); 756 757 // Get the callgraph information that we need to update to reflect our 758 // changes. 759 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); 760 761 // Get a new callgraph node for NF. 762 CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF); 763 764 // Loop over all of the callers of the function, transforming the call sites 765 // to pass in the loaded pointers. 766 // 767 SmallVector<Value*, 16> Args; 768 while (!F->use_empty()) { 769 CallSite CS(F->user_back()); 770 assert(CS.getCalledFunction() == F); 771 Instruction *Call = CS.getInstruction(); 772 const AttributeSet &CallPAL = CS.getAttributes(); 773 774 // Add any return attributes. 775 if (CallPAL.hasAttributes(AttributeSet::ReturnIndex)) 776 AttributesVec.push_back(AttributeSet::get(F->getContext(), 777 CallPAL.getRetAttributes())); 778 779 // Loop over the operands, inserting GEP and loads in the caller as 780 // appropriate. 781 CallSite::arg_iterator AI = CS.arg_begin(); 782 ArgIndex = 1; 783 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); 784 I != E; ++I, ++AI, ++ArgIndex) 785 if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) { 786 Args.push_back(*AI); // Unmodified argument 787 788 if (CallPAL.hasAttributes(ArgIndex)) { 789 AttrBuilder B(CallPAL, ArgIndex); 790 AttributesVec. 791 push_back(AttributeSet::get(F->getContext(), Args.size(), B)); 792 } 793 } else if (ByValArgsToTransform.count(I)) { 794 // Emit a GEP and load for each element of the struct. 795 Type *AgTy = cast<PointerType>(I->getType())->getElementType(); 796 StructType *STy = cast<StructType>(AgTy); 797 Value *Idxs[2] = { 798 ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr }; 799 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 800 Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i); 801 Value *Idx = GetElementPtrInst::Create( 802 STy, *AI, Idxs, (*AI)->getName() + "." + Twine(i), Call); 803 // TODO: Tell AA about the new values? 804 Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call)); 805 } 806 } else if (!I->use_empty()) { 807 // Non-dead argument: insert GEPs and loads as appropriate. 808 ScalarizeTable &ArgIndices = ScalarizedElements[I]; 809 // Store the Value* version of the indices in here, but declare it now 810 // for reuse. 811 std::vector<Value*> Ops; 812 for (ScalarizeTable::iterator SI = ArgIndices.begin(), 813 E = ArgIndices.end(); SI != E; ++SI) { 814 Value *V = *AI; 815 LoadInst *OrigLoad = OriginalLoads[std::make_pair(I, SI->second)]; 816 if (!SI->second.empty()) { 817 Ops.reserve(SI->second.size()); 818 Type *ElTy = V->getType(); 819 for (IndicesVector::const_iterator II = SI->second.begin(), 820 IE = SI->second.end(); 821 II != IE; ++II) { 822 // Use i32 to index structs, and i64 for others (pointers/arrays). 823 // This satisfies GEP constraints. 824 Type *IdxTy = (ElTy->isStructTy() ? 825 Type::getInt32Ty(F->getContext()) : 826 Type::getInt64Ty(F->getContext())); 827 Ops.push_back(ConstantInt::get(IdxTy, *II)); 828 // Keep track of the type we're currently indexing. 829 ElTy = cast<CompositeType>(ElTy)->getTypeAtIndex(*II); 830 } 831 // And create a GEP to extract those indices. 832 V = GetElementPtrInst::Create(SI->first, V, Ops, 833 V->getName() + ".idx", Call); 834 Ops.clear(); 835 } 836 // Since we're replacing a load make sure we take the alignment 837 // of the previous load. 838 LoadInst *newLoad = new LoadInst(V, V->getName()+".val", Call); 839 newLoad->setAlignment(OrigLoad->getAlignment()); 840 // Transfer the AA info too. 841 AAMDNodes AAInfo; 842 OrigLoad->getAAMetadata(AAInfo); 843 newLoad->setAAMetadata(AAInfo); 844 845 Args.push_back(newLoad); 846 } 847 } 848 849 // Push any varargs arguments on the list. 850 for (; AI != CS.arg_end(); ++AI, ++ArgIndex) { 851 Args.push_back(*AI); 852 if (CallPAL.hasAttributes(ArgIndex)) { 853 AttrBuilder B(CallPAL, ArgIndex); 854 AttributesVec. 855 push_back(AttributeSet::get(F->getContext(), Args.size(), B)); 856 } 857 } 858 859 // Add any function attributes. 860 if (CallPAL.hasAttributes(AttributeSet::FunctionIndex)) 861 AttributesVec.push_back(AttributeSet::get(Call->getContext(), 862 CallPAL.getFnAttributes())); 863 864 Instruction *New; 865 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) { 866 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(), 867 Args, "", Call); 868 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv()); 869 cast<InvokeInst>(New)->setAttributes(AttributeSet::get(II->getContext(), 870 AttributesVec)); 871 } else { 872 New = CallInst::Create(NF, Args, "", Call); 873 cast<CallInst>(New)->setCallingConv(CS.getCallingConv()); 874 cast<CallInst>(New)->setAttributes(AttributeSet::get(New->getContext(), 875 AttributesVec)); 876 if (cast<CallInst>(Call)->isTailCall()) 877 cast<CallInst>(New)->setTailCall(); 878 } 879 New->setDebugLoc(Call->getDebugLoc()); 880 Args.clear(); 881 AttributesVec.clear(); 882 883 // Update the callgraph to know that the callsite has been transformed. 884 CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()]; 885 CalleeNode->replaceCallEdge(CS, CallSite(New), NF_CGN); 886 887 if (!Call->use_empty()) { 888 Call->replaceAllUsesWith(New); 889 New->takeName(Call); 890 } 891 892 // Finally, remove the old call from the program, reducing the use-count of 893 // F. 894 Call->eraseFromParent(); 895 } 896 897 // Since we have now created the new function, splice the body of the old 898 // function right into the new function, leaving the old rotting hulk of the 899 // function empty. 900 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList()); 901 902 // Loop over the argument list, transferring uses of the old arguments over to 903 // the new arguments, also transferring over the names as well. 904 // 905 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(), 906 I2 = NF->arg_begin(); I != E; ++I) { 907 if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) { 908 // If this is an unmodified argument, move the name and users over to the 909 // new version. 910 I->replaceAllUsesWith(I2); 911 I2->takeName(I); 912 ++I2; 913 continue; 914 } 915 916 if (ByValArgsToTransform.count(I)) { 917 // In the callee, we create an alloca, and store each of the new incoming 918 // arguments into the alloca. 919 Instruction *InsertPt = NF->begin()->begin(); 920 921 // Just add all the struct element types. 922 Type *AgTy = cast<PointerType>(I->getType())->getElementType(); 923 Value *TheAlloca = new AllocaInst(AgTy, nullptr, "", InsertPt); 924 StructType *STy = cast<StructType>(AgTy); 925 Value *Idxs[2] = { 926 ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr }; 927 928 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 929 Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i); 930 Value *Idx = GetElementPtrInst::Create( 931 AgTy, TheAlloca, Idxs, TheAlloca->getName() + "." + Twine(i), 932 InsertPt); 933 I2->setName(I->getName()+"."+Twine(i)); 934 new StoreInst(I2++, Idx, InsertPt); 935 } 936 937 // Anything that used the arg should now use the alloca. 938 I->replaceAllUsesWith(TheAlloca); 939 TheAlloca->takeName(I); 940 941 // If the alloca is used in a call, we must clear the tail flag since 942 // the callee now uses an alloca from the caller. 943 for (User *U : TheAlloca->users()) { 944 CallInst *Call = dyn_cast<CallInst>(U); 945 if (!Call) 946 continue; 947 Call->setTailCall(false); 948 } 949 continue; 950 } 951 952 if (I->use_empty()) 953 continue; 954 955 // Otherwise, if we promoted this argument, then all users are load 956 // instructions (or GEPs with only load users), and all loads should be 957 // using the new argument that we added. 958 ScalarizeTable &ArgIndices = ScalarizedElements[I]; 959 960 while (!I->use_empty()) { 961 if (LoadInst *LI = dyn_cast<LoadInst>(I->user_back())) { 962 assert(ArgIndices.begin()->second.empty() && 963 "Load element should sort to front!"); 964 I2->setName(I->getName()+".val"); 965 LI->replaceAllUsesWith(I2); 966 LI->eraseFromParent(); 967 DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName() 968 << "' in function '" << F->getName() << "'\n"); 969 } else { 970 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->user_back()); 971 IndicesVector Operands; 972 Operands.reserve(GEP->getNumIndices()); 973 for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end(); 974 II != IE; ++II) 975 Operands.push_back(cast<ConstantInt>(*II)->getSExtValue()); 976 977 // GEPs with a single 0 index can be merged with direct loads 978 if (Operands.size() == 1 && Operands.front() == 0) 979 Operands.clear(); 980 981 Function::arg_iterator TheArg = I2; 982 for (ScalarizeTable::iterator It = ArgIndices.begin(); 983 It->second != Operands; ++It, ++TheArg) { 984 assert(It != ArgIndices.end() && "GEP not handled??"); 985 } 986 987 std::string NewName = I->getName(); 988 for (unsigned i = 0, e = Operands.size(); i != e; ++i) { 989 NewName += "." + utostr(Operands[i]); 990 } 991 NewName += ".val"; 992 TheArg->setName(NewName); 993 994 DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName() 995 << "' of function '" << NF->getName() << "'\n"); 996 997 // All of the uses must be load instructions. Replace them all with 998 // the argument specified by ArgNo. 999 while (!GEP->use_empty()) { 1000 LoadInst *L = cast<LoadInst>(GEP->user_back()); 1001 L->replaceAllUsesWith(TheArg); 1002 L->eraseFromParent(); 1003 } 1004 GEP->eraseFromParent(); 1005 } 1006 } 1007 1008 // Increment I2 past all of the arguments added for this promoted pointer. 1009 std::advance(I2, ArgIndices.size()); 1010 } 1011 1012 NF_CGN->stealCalledFunctionsFrom(CG[F]); 1013 1014 // Now that the old function is dead, delete it. If there is a dangling 1015 // reference to the CallgraphNode, just leave the dead function around for 1016 // someone else to nuke. 1017 CallGraphNode *CGN = CG[F]; 1018 if (CGN->getNumReferences() == 0) 1019 delete CG.removeFunctionFromModule(CGN); 1020 else 1021 F->setLinkage(Function::ExternalLinkage); 1022 1023 return NF_CGN; 1024 } 1025 1026 bool ArgPromotion::doInitialization(CallGraph &CG) { 1027 FunctionDIs = makeSubprogramMap(CG.getModule()); 1028 return CallGraphSCCPass::doInitialization(CG); 1029 } 1030