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