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 addUsedAAAnalyses(AU); 72 CallGraphSCCPass::getAnalysisUsage(AU); 73 } 74 75 bool runOnSCC(CallGraphSCC &SCC) override; 76 static char ID; // Pass identification, replacement for typeid 77 explicit ArgPromotion(unsigned maxElements = 3) 78 : CallGraphSCCPass(ID), maxElements(maxElements) { 79 initializeArgPromotionPass(*PassRegistry::getPassRegistry()); 80 } 81 82 /// A vector used to hold the indices of a single GEP instruction 83 typedef std::vector<uint64_t> IndicesVector; 84 85 private: 86 bool isDenselyPacked(Type *type, const DataLayout &DL); 87 bool canPaddingBeAccessed(Argument *Arg); 88 CallGraphNode *PromoteArguments(CallGraphNode *CGN); 89 bool isSafeToPromoteArgument(Argument *Arg, bool isByVal, 90 AAResults &AAR) const; 91 CallGraphNode *DoPromotion(Function *F, 92 SmallPtrSetImpl<Argument*> &ArgsToPromote, 93 SmallPtrSetImpl<Argument*> &ByValArgsToTransform); 94 95 using llvm::Pass::doInitialization; 96 bool doInitialization(CallGraph &CG) override; 97 /// The maximum number of elements to expand, or 0 for unlimited. 98 unsigned maxElements; 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 (Argument &I : F->args()) 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()->front(); 472 // Declare this here so we can reuse it 473 IndicesVector Indices; 474 for (Instruction &I : EntryBlock) 475 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) { 476 Value *V = LI->getPointerOperand(); 477 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) { 478 V = GEP->getPointerOperand(); 479 if (V == Arg) { 480 // This load actually loads (part of) Arg? Check the indices then. 481 Indices.reserve(GEP->getNumIndices()); 482 for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end(); 483 II != IE; ++II) 484 if (ConstantInt *CI = dyn_cast<ConstantInt>(*II)) 485 Indices.push_back(CI->getSExtValue()); 486 else 487 // We found a non-constant GEP index for this argument? Bail out 488 // right away, can't promote this argument at all. 489 return false; 490 491 // Indices checked out, mark them as safe 492 MarkIndicesSafe(Indices, SafeToUnconditionallyLoad); 493 Indices.clear(); 494 } 495 } else if (V == Arg) { 496 // Direct loads are equivalent to a GEP with a single 0 index. 497 MarkIndicesSafe(IndicesVector(1, 0), SafeToUnconditionallyLoad); 498 } 499 } 500 501 // Now, iterate all uses of the argument to see if there are any uses that are 502 // not (GEP+)loads, or any (GEP+)loads that are not safe to promote. 503 SmallVector<LoadInst*, 16> Loads; 504 IndicesVector Operands; 505 for (Use &U : Arg->uses()) { 506 User *UR = U.getUser(); 507 Operands.clear(); 508 if (LoadInst *LI = dyn_cast<LoadInst>(UR)) { 509 // Don't hack volatile/atomic loads 510 if (!LI->isSimple()) return false; 511 Loads.push_back(LI); 512 // Direct loads are equivalent to a GEP with a zero index and then a load. 513 Operands.push_back(0); 514 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UR)) { 515 if (GEP->use_empty()) { 516 // Dead GEP's cause trouble later. Just remove them if we run into 517 // them. 518 GEP->eraseFromParent(); 519 // TODO: This runs the above loop over and over again for dead GEPs 520 // Couldn't we just do increment the UI iterator earlier and erase the 521 // use? 522 return isSafeToPromoteArgument(Arg, isByValOrInAlloca, AAR); 523 } 524 525 // Ensure that all of the indices are constants. 526 for (User::op_iterator i = GEP->idx_begin(), e = GEP->idx_end(); 527 i != e; ++i) 528 if (ConstantInt *C = dyn_cast<ConstantInt>(*i)) 529 Operands.push_back(C->getSExtValue()); 530 else 531 return false; // Not a constant operand GEP! 532 533 // Ensure that the only users of the GEP are load instructions. 534 for (User *GEPU : GEP->users()) 535 if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) { 536 // Don't hack volatile/atomic loads 537 if (!LI->isSimple()) return false; 538 Loads.push_back(LI); 539 } else { 540 // Other uses than load? 541 return false; 542 } 543 } else { 544 return false; // Not a load or a GEP. 545 } 546 547 // Now, see if it is safe to promote this load / loads of this GEP. Loading 548 // is safe if Operands, or a prefix of Operands, is marked as safe. 549 if (!PrefixIn(Operands, SafeToUnconditionallyLoad)) 550 return false; 551 552 // See if we are already promoting a load with these indices. If not, check 553 // to make sure that we aren't promoting too many elements. If so, nothing 554 // to do. 555 if (ToPromote.find(Operands) == ToPromote.end()) { 556 if (maxElements > 0 && ToPromote.size() == maxElements) { 557 DEBUG(dbgs() << "argpromotion not promoting argument '" 558 << Arg->getName() << "' because it would require adding more " 559 << "than " << maxElements << " arguments to the function.\n"); 560 // We limit aggregate promotion to only promoting up to a fixed number 561 // of elements of the aggregate. 562 return false; 563 } 564 ToPromote.insert(std::move(Operands)); 565 } 566 } 567 568 if (Loads.empty()) return true; // No users, this is a dead argument. 569 570 // Okay, now we know that the argument is only used by load instructions and 571 // it is safe to unconditionally perform all of them. Use alias analysis to 572 // check to see if the pointer is guaranteed to not be modified from entry of 573 // the function to each of the load instructions. 574 575 // Because there could be several/many load instructions, remember which 576 // blocks we know to be transparent to the load. 577 SmallPtrSet<BasicBlock*, 16> TranspBlocks; 578 579 for (unsigned i = 0, e = Loads.size(); i != e; ++i) { 580 // Check to see if the load is invalidated from the start of the block to 581 // the load itself. 582 LoadInst *Load = Loads[i]; 583 BasicBlock *BB = Load->getParent(); 584 585 MemoryLocation Loc = MemoryLocation::get(Load); 586 if (AAR.canInstructionRangeModRef(BB->front(), *Load, Loc, MRI_Mod)) 587 return false; // Pointer is invalidated! 588 589 // Now check every path from the entry block to the load for transparency. 590 // To do this, we perform a depth first search on the inverse CFG from the 591 // loading block. 592 for (BasicBlock *P : predecessors(BB)) { 593 for (BasicBlock *TranspBB : inverse_depth_first_ext(P, TranspBlocks)) 594 if (AAR.canBasicBlockModify(*TranspBB, Loc)) 595 return false; 596 } 597 } 598 599 // If the path from the entry of the function to each load is free of 600 // instructions that potentially invalidate the load, we can make the 601 // transformation! 602 return true; 603 } 604 605 /// DoPromotion - This method actually performs the promotion of the specified 606 /// arguments, and returns the new function. At this point, we know that it's 607 /// safe to do so. 608 CallGraphNode *ArgPromotion::DoPromotion(Function *F, 609 SmallPtrSetImpl<Argument*> &ArgsToPromote, 610 SmallPtrSetImpl<Argument*> &ByValArgsToTransform) { 611 612 // Start by computing a new prototype for the function, which is the same as 613 // the old function, but has modified arguments. 614 FunctionType *FTy = F->getFunctionType(); 615 std::vector<Type*> Params; 616 617 typedef std::set<std::pair<Type *, IndicesVector>> ScalarizeTable; 618 619 // ScalarizedElements - If we are promoting a pointer that has elements 620 // accessed out of it, keep track of which elements are accessed so that we 621 // can add one argument for each. 622 // 623 // Arguments that are directly loaded will have a zero element value here, to 624 // handle cases where there are both a direct load and GEP accesses. 625 // 626 std::map<Argument*, ScalarizeTable> ScalarizedElements; 627 628 // OriginalLoads - Keep track of a representative load instruction from the 629 // original function so that we can tell the alias analysis implementation 630 // what the new GEP/Load instructions we are inserting look like. 631 // We need to keep the original loads for each argument and the elements 632 // of the argument that are accessed. 633 std::map<std::pair<Argument*, IndicesVector>, LoadInst*> OriginalLoads; 634 635 // Attribute - Keep track of the parameter attributes for the arguments 636 // that we are *not* promoting. For the ones that we do promote, the parameter 637 // attributes are lost 638 SmallVector<AttributeSet, 8> AttributesVec; 639 const AttributeSet &PAL = F->getAttributes(); 640 641 // Add any return attributes. 642 if (PAL.hasAttributes(AttributeSet::ReturnIndex)) 643 AttributesVec.push_back(AttributeSet::get(F->getContext(), 644 PAL.getRetAttributes())); 645 646 // First, determine the new argument list 647 unsigned ArgIndex = 1; 648 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; 649 ++I, ++ArgIndex) { 650 if (ByValArgsToTransform.count(&*I)) { 651 // Simple byval argument? Just add all the struct element types. 652 Type *AgTy = cast<PointerType>(I->getType())->getElementType(); 653 StructType *STy = cast<StructType>(AgTy); 654 Params.insert(Params.end(), STy->element_begin(), STy->element_end()); 655 ++NumByValArgsPromoted; 656 } else if (!ArgsToPromote.count(&*I)) { 657 // Unchanged argument 658 Params.push_back(I->getType()); 659 AttributeSet attrs = PAL.getParamAttributes(ArgIndex); 660 if (attrs.hasAttributes(ArgIndex)) { 661 AttrBuilder B(attrs, ArgIndex); 662 AttributesVec. 663 push_back(AttributeSet::get(F->getContext(), Params.size(), B)); 664 } 665 } else if (I->use_empty()) { 666 // Dead argument (which are always marked as promotable) 667 ++NumArgumentsDead; 668 } else { 669 // Okay, this is being promoted. This means that the only uses are loads 670 // or GEPs which are only used by loads 671 672 // In this table, we will track which indices are loaded from the argument 673 // (where direct loads are tracked as no indices). 674 ScalarizeTable &ArgIndices = ScalarizedElements[&*I]; 675 for (User *U : I->users()) { 676 Instruction *UI = cast<Instruction>(U); 677 Type *SrcTy; 678 if (LoadInst *L = dyn_cast<LoadInst>(UI)) 679 SrcTy = L->getType(); 680 else 681 SrcTy = cast<GetElementPtrInst>(UI)->getSourceElementType(); 682 IndicesVector Indices; 683 Indices.reserve(UI->getNumOperands() - 1); 684 // Since loads will only have a single operand, and GEPs only a single 685 // non-index operand, this will record direct loads without any indices, 686 // and gep+loads with the GEP indices. 687 for (User::op_iterator II = UI->op_begin() + 1, IE = UI->op_end(); 688 II != IE; ++II) 689 Indices.push_back(cast<ConstantInt>(*II)->getSExtValue()); 690 // GEPs with a single 0 index can be merged with direct loads 691 if (Indices.size() == 1 && Indices.front() == 0) 692 Indices.clear(); 693 ArgIndices.insert(std::make_pair(SrcTy, Indices)); 694 LoadInst *OrigLoad; 695 if (LoadInst *L = dyn_cast<LoadInst>(UI)) 696 OrigLoad = L; 697 else 698 // Take any load, we will use it only to update Alias Analysis 699 OrigLoad = cast<LoadInst>(UI->user_back()); 700 OriginalLoads[std::make_pair(&*I, Indices)] = OrigLoad; 701 } 702 703 // Add a parameter to the function for each element passed in. 704 for (ScalarizeTable::iterator SI = ArgIndices.begin(), 705 E = ArgIndices.end(); SI != E; ++SI) { 706 // not allowed to dereference ->begin() if size() is 0 707 Params.push_back(GetElementPtrInst::getIndexedType( 708 cast<PointerType>(I->getType()->getScalarType())->getElementType(), 709 SI->second)); 710 assert(Params.back()); 711 } 712 713 if (ArgIndices.size() == 1 && ArgIndices.begin()->second.empty()) 714 ++NumArgumentsPromoted; 715 else 716 ++NumAggregatesPromoted; 717 } 718 } 719 720 // Add any function attributes. 721 if (PAL.hasAttributes(AttributeSet::FunctionIndex)) 722 AttributesVec.push_back(AttributeSet::get(FTy->getContext(), 723 PAL.getFnAttributes())); 724 725 Type *RetTy = FTy->getReturnType(); 726 727 // Construct the new function type using the new arguments. 728 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg()); 729 730 // Create the new function body and insert it into the module. 731 Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName()); 732 NF->copyAttributesFrom(F); 733 734 // Patch the pointer to LLVM function in debug info descriptor. 735 NF->setSubprogram(F->getSubprogram()); 736 F->setSubprogram(nullptr); 737 738 DEBUG(dbgs() << "ARG PROMOTION: Promoting to:" << *NF << "\n" 739 << "From: " << *F); 740 741 // Recompute the parameter attributes list based on the new arguments for 742 // the function. 743 NF->setAttributes(AttributeSet::get(F->getContext(), AttributesVec)); 744 AttributesVec.clear(); 745 746 F->getParent()->getFunctionList().insert(F->getIterator(), NF); 747 NF->takeName(F); 748 749 // Get the callgraph information that we need to update to reflect our 750 // changes. 751 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); 752 753 // Get a new callgraph node for NF. 754 CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF); 755 756 // Loop over all of the callers of the function, transforming the call sites 757 // to pass in the loaded pointers. 758 // 759 SmallVector<Value*, 16> Args; 760 while (!F->use_empty()) { 761 CallSite CS(F->user_back()); 762 assert(CS.getCalledFunction() == F); 763 Instruction *Call = CS.getInstruction(); 764 const AttributeSet &CallPAL = CS.getAttributes(); 765 766 // Add any return attributes. 767 if (CallPAL.hasAttributes(AttributeSet::ReturnIndex)) 768 AttributesVec.push_back(AttributeSet::get(F->getContext(), 769 CallPAL.getRetAttributes())); 770 771 // Loop over the operands, inserting GEP and loads in the caller as 772 // appropriate. 773 CallSite::arg_iterator AI = CS.arg_begin(); 774 ArgIndex = 1; 775 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); 776 I != E; ++I, ++AI, ++ArgIndex) 777 if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) { 778 Args.push_back(*AI); // Unmodified argument 779 780 if (CallPAL.hasAttributes(ArgIndex)) { 781 AttrBuilder B(CallPAL, ArgIndex); 782 AttributesVec. 783 push_back(AttributeSet::get(F->getContext(), Args.size(), B)); 784 } 785 } else if (ByValArgsToTransform.count(&*I)) { 786 // Emit a GEP and load for each element of the struct. 787 Type *AgTy = cast<PointerType>(I->getType())->getElementType(); 788 StructType *STy = cast<StructType>(AgTy); 789 Value *Idxs[2] = { 790 ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr }; 791 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 792 Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i); 793 Value *Idx = GetElementPtrInst::Create( 794 STy, *AI, Idxs, (*AI)->getName() + "." + Twine(i), Call); 795 // TODO: Tell AA about the new values? 796 Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call)); 797 } 798 } else if (!I->use_empty()) { 799 // Non-dead argument: insert GEPs and loads as appropriate. 800 ScalarizeTable &ArgIndices = ScalarizedElements[&*I]; 801 // Store the Value* version of the indices in here, but declare it now 802 // for reuse. 803 std::vector<Value*> Ops; 804 for (ScalarizeTable::iterator SI = ArgIndices.begin(), 805 E = ArgIndices.end(); SI != E; ++SI) { 806 Value *V = *AI; 807 LoadInst *OrigLoad = OriginalLoads[std::make_pair(&*I, SI->second)]; 808 if (!SI->second.empty()) { 809 Ops.reserve(SI->second.size()); 810 Type *ElTy = V->getType(); 811 for (IndicesVector::const_iterator II = SI->second.begin(), 812 IE = SI->second.end(); 813 II != IE; ++II) { 814 // Use i32 to index structs, and i64 for others (pointers/arrays). 815 // This satisfies GEP constraints. 816 Type *IdxTy = (ElTy->isStructTy() ? 817 Type::getInt32Ty(F->getContext()) : 818 Type::getInt64Ty(F->getContext())); 819 Ops.push_back(ConstantInt::get(IdxTy, *II)); 820 // Keep track of the type we're currently indexing. 821 ElTy = cast<CompositeType>(ElTy)->getTypeAtIndex(*II); 822 } 823 // And create a GEP to extract those indices. 824 V = GetElementPtrInst::Create(SI->first, V, Ops, 825 V->getName() + ".idx", Call); 826 Ops.clear(); 827 } 828 // Since we're replacing a load make sure we take the alignment 829 // of the previous load. 830 LoadInst *newLoad = new LoadInst(V, V->getName()+".val", Call); 831 newLoad->setAlignment(OrigLoad->getAlignment()); 832 // Transfer the AA info too. 833 AAMDNodes AAInfo; 834 OrigLoad->getAAMetadata(AAInfo); 835 newLoad->setAAMetadata(AAInfo); 836 837 Args.push_back(newLoad); 838 } 839 } 840 841 // Push any varargs arguments on the list. 842 for (; AI != CS.arg_end(); ++AI, ++ArgIndex) { 843 Args.push_back(*AI); 844 if (CallPAL.hasAttributes(ArgIndex)) { 845 AttrBuilder B(CallPAL, ArgIndex); 846 AttributesVec. 847 push_back(AttributeSet::get(F->getContext(), Args.size(), B)); 848 } 849 } 850 851 // Add any function attributes. 852 if (CallPAL.hasAttributes(AttributeSet::FunctionIndex)) 853 AttributesVec.push_back(AttributeSet::get(Call->getContext(), 854 CallPAL.getFnAttributes())); 855 856 Instruction *New; 857 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) { 858 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(), 859 Args, "", Call); 860 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv()); 861 cast<InvokeInst>(New)->setAttributes(AttributeSet::get(II->getContext(), 862 AttributesVec)); 863 } else { 864 New = CallInst::Create(NF, Args, "", Call); 865 cast<CallInst>(New)->setCallingConv(CS.getCallingConv()); 866 cast<CallInst>(New)->setAttributes(AttributeSet::get(New->getContext(), 867 AttributesVec)); 868 if (cast<CallInst>(Call)->isTailCall()) 869 cast<CallInst>(New)->setTailCall(); 870 } 871 New->setDebugLoc(Call->getDebugLoc()); 872 Args.clear(); 873 AttributesVec.clear(); 874 875 // Update the callgraph to know that the callsite has been transformed. 876 CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()]; 877 CalleeNode->replaceCallEdge(CS, CallSite(New), NF_CGN); 878 879 if (!Call->use_empty()) { 880 Call->replaceAllUsesWith(New); 881 New->takeName(Call); 882 } 883 884 // Finally, remove the old call from the program, reducing the use-count of 885 // F. 886 Call->eraseFromParent(); 887 } 888 889 // Since we have now created the new function, splice the body of the old 890 // function right into the new function, leaving the old rotting hulk of the 891 // function empty. 892 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList()); 893 894 // Loop over the argument list, transferring uses of the old arguments over to 895 // the new arguments, also transferring over the names as well. 896 // 897 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(), 898 I2 = NF->arg_begin(); I != E; ++I) { 899 if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) { 900 // If this is an unmodified argument, move the name and users over to the 901 // new version. 902 I->replaceAllUsesWith(&*I2); 903 I2->takeName(&*I); 904 ++I2; 905 continue; 906 } 907 908 if (ByValArgsToTransform.count(&*I)) { 909 // In the callee, we create an alloca, and store each of the new incoming 910 // arguments into the alloca. 911 Instruction *InsertPt = &NF->begin()->front(); 912 913 // Just add all the struct element types. 914 Type *AgTy = cast<PointerType>(I->getType())->getElementType(); 915 Value *TheAlloca = new AllocaInst(AgTy, nullptr, "", InsertPt); 916 StructType *STy = cast<StructType>(AgTy); 917 Value *Idxs[2] = { 918 ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr }; 919 920 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 921 Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i); 922 Value *Idx = GetElementPtrInst::Create( 923 AgTy, TheAlloca, Idxs, TheAlloca->getName() + "." + Twine(i), 924 InsertPt); 925 I2->setName(I->getName()+"."+Twine(i)); 926 new StoreInst(&*I2++, Idx, InsertPt); 927 } 928 929 // Anything that used the arg should now use the alloca. 930 I->replaceAllUsesWith(TheAlloca); 931 TheAlloca->takeName(&*I); 932 933 // If the alloca is used in a call, we must clear the tail flag since 934 // the callee now uses an alloca from the caller. 935 for (User *U : TheAlloca->users()) { 936 CallInst *Call = dyn_cast<CallInst>(U); 937 if (!Call) 938 continue; 939 Call->setTailCall(false); 940 } 941 continue; 942 } 943 944 if (I->use_empty()) 945 continue; 946 947 // Otherwise, if we promoted this argument, then all users are load 948 // instructions (or GEPs with only load users), and all loads should be 949 // using the new argument that we added. 950 ScalarizeTable &ArgIndices = ScalarizedElements[&*I]; 951 952 while (!I->use_empty()) { 953 if (LoadInst *LI = dyn_cast<LoadInst>(I->user_back())) { 954 assert(ArgIndices.begin()->second.empty() && 955 "Load element should sort to front!"); 956 I2->setName(I->getName()+".val"); 957 LI->replaceAllUsesWith(&*I2); 958 LI->eraseFromParent(); 959 DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName() 960 << "' in function '" << F->getName() << "'\n"); 961 } else { 962 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->user_back()); 963 IndicesVector Operands; 964 Operands.reserve(GEP->getNumIndices()); 965 for (User::op_iterator II = GEP->idx_begin(), IE = GEP->idx_end(); 966 II != IE; ++II) 967 Operands.push_back(cast<ConstantInt>(*II)->getSExtValue()); 968 969 // GEPs with a single 0 index can be merged with direct loads 970 if (Operands.size() == 1 && Operands.front() == 0) 971 Operands.clear(); 972 973 Function::arg_iterator TheArg = I2; 974 for (ScalarizeTable::iterator It = ArgIndices.begin(); 975 It->second != Operands; ++It, ++TheArg) { 976 assert(It != ArgIndices.end() && "GEP not handled??"); 977 } 978 979 std::string NewName = I->getName(); 980 for (unsigned i = 0, e = Operands.size(); i != e; ++i) { 981 NewName += "." + utostr(Operands[i]); 982 } 983 NewName += ".val"; 984 TheArg->setName(NewName); 985 986 DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName() 987 << "' of function '" << NF->getName() << "'\n"); 988 989 // All of the uses must be load instructions. Replace them all with 990 // the argument specified by ArgNo. 991 while (!GEP->use_empty()) { 992 LoadInst *L = cast<LoadInst>(GEP->user_back()); 993 L->replaceAllUsesWith(&*TheArg); 994 L->eraseFromParent(); 995 } 996 GEP->eraseFromParent(); 997 } 998 } 999 1000 // Increment I2 past all of the arguments added for this promoted pointer. 1001 std::advance(I2, ArgIndices.size()); 1002 } 1003 1004 NF_CGN->stealCalledFunctionsFrom(CG[F]); 1005 1006 // Now that the old function is dead, delete it. If there is a dangling 1007 // reference to the CallgraphNode, just leave the dead function around for 1008 // someone else to nuke. 1009 CallGraphNode *CGN = CG[F]; 1010 if (CGN->getNumReferences() == 0) 1011 delete CG.removeFunctionFromModule(CGN); 1012 else 1013 F->setLinkage(Function::ExternalLinkage); 1014 1015 return NF_CGN; 1016 } 1017 1018 bool ArgPromotion::doInitialization(CallGraph &CG) { 1019 return CallGraphSCCPass::doInitialization(CG); 1020 } 1021