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