1 //===- ArgumentPromotion.cpp - Promote by-reference arguments -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This pass promotes "by reference" arguments to be "by value" arguments. In 10 // practice, this means looking for internal functions that have pointer 11 // arguments. If it can prove, through the use of alias analysis, that an 12 // argument is *only* loaded, then it can pass the value into the function 13 // instead of the address of the value. This can cause recursive simplification 14 // of code and lead to the elimination of allocas (especially in C++ template 15 // code like the STL). 16 // 17 // This pass also handles aggregate arguments that are passed into a function, 18 // scalarizing them if the elements of the aggregate are only loaded. Note that 19 // by default it refuses to scalarize aggregates which would require passing in 20 // more than three operands to the function, because passing thousands of 21 // operands for a large array or structure is unprofitable! This limit can be 22 // configured or disabled, however. 23 // 24 // Note that this transformation could also be done for arguments that are only 25 // stored to (returning the value instead), but does not currently. This case 26 // would be best handled when and if LLVM begins supporting multiple return 27 // values from functions. 28 // 29 //===----------------------------------------------------------------------===// 30 31 #include "llvm/Transforms/IPO/ArgumentPromotion.h" 32 #include "llvm/ADT/DepthFirstIterator.h" 33 #include "llvm/ADT/None.h" 34 #include "llvm/ADT/Optional.h" 35 #include "llvm/ADT/STLExtras.h" 36 #include "llvm/ADT/ScopeExit.h" 37 #include "llvm/ADT/SmallPtrSet.h" 38 #include "llvm/ADT/SmallVector.h" 39 #include "llvm/ADT/Statistic.h" 40 #include "llvm/ADT/Twine.h" 41 #include "llvm/Analysis/AssumptionCache.h" 42 #include "llvm/Analysis/BasicAliasAnalysis.h" 43 #include "llvm/Analysis/CGSCCPassManager.h" 44 #include "llvm/Analysis/CallGraph.h" 45 #include "llvm/Analysis/CallGraphSCCPass.h" 46 #include "llvm/Analysis/LazyCallGraph.h" 47 #include "llvm/Analysis/Loads.h" 48 #include "llvm/Analysis/MemoryLocation.h" 49 #include "llvm/Analysis/TargetLibraryInfo.h" 50 #include "llvm/Analysis/TargetTransformInfo.h" 51 #include "llvm/IR/Argument.h" 52 #include "llvm/IR/Attributes.h" 53 #include "llvm/IR/BasicBlock.h" 54 #include "llvm/IR/CFG.h" 55 #include "llvm/IR/Constants.h" 56 #include "llvm/IR/DataLayout.h" 57 #include "llvm/IR/DerivedTypes.h" 58 #include "llvm/IR/Function.h" 59 #include "llvm/IR/IRBuilder.h" 60 #include "llvm/IR/InstrTypes.h" 61 #include "llvm/IR/Instruction.h" 62 #include "llvm/IR/Instructions.h" 63 #include "llvm/IR/Metadata.h" 64 #include "llvm/IR/Module.h" 65 #include "llvm/IR/NoFolder.h" 66 #include "llvm/IR/PassManager.h" 67 #include "llvm/IR/Type.h" 68 #include "llvm/IR/Use.h" 69 #include "llvm/IR/User.h" 70 #include "llvm/IR/Value.h" 71 #include "llvm/InitializePasses.h" 72 #include "llvm/Pass.h" 73 #include "llvm/Support/Casting.h" 74 #include "llvm/Support/Debug.h" 75 #include "llvm/Support/FormatVariadic.h" 76 #include "llvm/Support/raw_ostream.h" 77 #include "llvm/Transforms/IPO.h" 78 #include <algorithm> 79 #include <cassert> 80 #include <cstdint> 81 #include <functional> 82 #include <iterator> 83 #include <map> 84 #include <set> 85 #include <utility> 86 #include <vector> 87 88 using namespace llvm; 89 90 #define DEBUG_TYPE "argpromotion" 91 92 STATISTIC(NumArgumentsPromoted, "Number of pointer arguments promoted"); 93 STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted"); 94 STATISTIC(NumByValArgsPromoted, "Number of byval arguments promoted"); 95 STATISTIC(NumArgumentsDead, "Number of dead pointer args eliminated"); 96 97 /// A vector used to hold the indices of a single GEP instruction 98 using IndicesVector = std::vector<uint64_t>; 99 100 /// DoPromotion - This method actually performs the promotion of the specified 101 /// arguments, and returns the new function. At this point, we know that it's 102 /// safe to do so. 103 static Function * 104 doPromotion(Function *F, SmallPtrSetImpl<Argument *> &ArgsToPromote, 105 SmallPtrSetImpl<Argument *> &ByValArgsToTransform, 106 Optional<function_ref<void(CallBase &OldCS, CallBase &NewCS)>> 107 ReplaceCallSite) { 108 // Start by computing a new prototype for the function, which is the same as 109 // the old function, but has modified arguments. 110 FunctionType *FTy = F->getFunctionType(); 111 std::vector<Type *> Params; 112 113 using ScalarizeTable = std::set<std::pair<Type *, IndicesVector>>; 114 115 // ScalarizedElements - If we are promoting a pointer that has elements 116 // accessed out of it, keep track of which elements are accessed so that we 117 // can add one argument for each. 118 // 119 // Arguments that are directly loaded will have a zero element value here, to 120 // handle cases where there are both a direct load and GEP accesses. 121 std::map<Argument *, ScalarizeTable> ScalarizedElements; 122 123 // OriginalLoads - Keep track of a representative load instruction from the 124 // original function so that we can tell the alias analysis implementation 125 // what the new GEP/Load instructions we are inserting look like. 126 // We need to keep the original loads for each argument and the elements 127 // of the argument that are accessed. 128 std::map<std::pair<Argument *, IndicesVector>, LoadInst *> OriginalLoads; 129 130 // Attribute - Keep track of the parameter attributes for the arguments 131 // that we are *not* promoting. For the ones that we do promote, the parameter 132 // attributes are lost 133 SmallVector<AttributeSet, 8> ArgAttrVec; 134 AttributeList PAL = F->getAttributes(); 135 136 // First, determine the new argument list 137 unsigned ArgNo = 0; 138 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; 139 ++I, ++ArgNo) { 140 if (ByValArgsToTransform.count(&*I)) { 141 // Simple byval argument? Just add all the struct element types. 142 Type *AgTy = I->getParamByValType(); 143 StructType *STy = cast<StructType>(AgTy); 144 llvm::append_range(Params, STy->elements()); 145 ArgAttrVec.insert(ArgAttrVec.end(), STy->getNumElements(), 146 AttributeSet()); 147 ++NumByValArgsPromoted; 148 } else if (!ArgsToPromote.count(&*I)) { 149 // Unchanged argument 150 Params.push_back(I->getType()); 151 ArgAttrVec.push_back(PAL.getParamAttrs(ArgNo)); 152 } else if (I->use_empty()) { 153 // Dead argument (which are always marked as promotable) 154 ++NumArgumentsDead; 155 } else { 156 // Okay, this is being promoted. This means that the only uses are loads 157 // or GEPs which are only used by loads 158 159 // In this table, we will track which indices are loaded from the argument 160 // (where direct loads are tracked as no indices). 161 ScalarizeTable &ArgIndices = ScalarizedElements[&*I]; 162 for (User *U : make_early_inc_range(I->users())) { 163 Instruction *UI = cast<Instruction>(U); 164 Type *SrcTy; 165 if (LoadInst *L = dyn_cast<LoadInst>(UI)) 166 SrcTy = L->getType(); 167 else 168 SrcTy = cast<GetElementPtrInst>(UI)->getSourceElementType(); 169 // Skip dead GEPs and remove them. 170 if (isa<GetElementPtrInst>(UI) && UI->use_empty()) { 171 UI->eraseFromParent(); 172 continue; 173 } 174 175 IndicesVector Indices; 176 Indices.reserve(UI->getNumOperands() - 1); 177 // Since loads will only have a single operand, and GEPs only a single 178 // non-index operand, this will record direct loads without any indices, 179 // and gep+loads with the GEP indices. 180 for (const Use &I : llvm::drop_begin(UI->operands())) 181 Indices.push_back(cast<ConstantInt>(I)->getSExtValue()); 182 // GEPs with a single 0 index can be merged with direct loads 183 if (Indices.size() == 1 && Indices.front() == 0) 184 Indices.clear(); 185 ArgIndices.insert(std::make_pair(SrcTy, Indices)); 186 LoadInst *OrigLoad; 187 if (LoadInst *L = dyn_cast<LoadInst>(UI)) 188 OrigLoad = L; 189 else 190 // Take any load, we will use it only to update Alias Analysis 191 OrigLoad = cast<LoadInst>(UI->user_back()); 192 OriginalLoads[std::make_pair(&*I, Indices)] = OrigLoad; 193 } 194 195 // Add a parameter to the function for each element passed in. 196 for (const auto &ArgIndex : ArgIndices) { 197 // not allowed to dereference ->begin() if size() is 0 198 Params.push_back(GetElementPtrInst::getIndexedType( 199 I->getType()->getPointerElementType(), ArgIndex.second)); 200 ArgAttrVec.push_back(AttributeSet()); 201 assert(Params.back()); 202 } 203 204 if (ArgIndices.size() == 1 && ArgIndices.begin()->second.empty()) 205 ++NumArgumentsPromoted; 206 else 207 ++NumAggregatesPromoted; 208 } 209 } 210 211 Type *RetTy = FTy->getReturnType(); 212 213 // Construct the new function type using the new arguments. 214 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg()); 215 216 // Create the new function body and insert it into the module. 217 Function *NF = Function::Create(NFTy, F->getLinkage(), F->getAddressSpace(), 218 F->getName()); 219 NF->copyAttributesFrom(F); 220 NF->copyMetadata(F, 0); 221 222 // The new function will have the !dbg metadata copied from the original 223 // function. The original function may not be deleted, and dbg metadata need 224 // to be unique so we need to drop it. 225 F->setSubprogram(nullptr); 226 227 LLVM_DEBUG(dbgs() << "ARG PROMOTION: Promoting to:" << *NF << "\n" 228 << "From: " << *F); 229 230 // Recompute the parameter attributes list based on the new arguments for 231 // the function. 232 NF->setAttributes(AttributeList::get(F->getContext(), PAL.getFnAttrs(), 233 PAL.getRetAttrs(), ArgAttrVec)); 234 ArgAttrVec.clear(); 235 236 F->getParent()->getFunctionList().insert(F->getIterator(), NF); 237 NF->takeName(F); 238 239 // Loop over all of the callers of the function, transforming the call sites 240 // to pass in the loaded pointers. 241 // 242 SmallVector<Value *, 16> Args; 243 const DataLayout &DL = F->getParent()->getDataLayout(); 244 while (!F->use_empty()) { 245 CallBase &CB = cast<CallBase>(*F->user_back()); 246 assert(CB.getCalledFunction() == F); 247 const AttributeList &CallPAL = CB.getAttributes(); 248 IRBuilder<NoFolder> IRB(&CB); 249 250 // Loop over the operands, inserting GEP and loads in the caller as 251 // appropriate. 252 auto AI = CB.arg_begin(); 253 ArgNo = 0; 254 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; 255 ++I, ++AI, ++ArgNo) 256 if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) { 257 Args.push_back(*AI); // Unmodified argument 258 ArgAttrVec.push_back(CallPAL.getParamAttrs(ArgNo)); 259 } else if (ByValArgsToTransform.count(&*I)) { 260 // Emit a GEP and load for each element of the struct. 261 Type *AgTy = I->getParamByValType(); 262 StructType *STy = cast<StructType>(AgTy); 263 Value *Idxs[2] = { 264 ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr}; 265 const StructLayout *SL = DL.getStructLayout(STy); 266 Align StructAlign = *I->getParamAlign(); 267 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 268 Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i); 269 auto *Idx = 270 IRB.CreateGEP(STy, *AI, Idxs, (*AI)->getName() + "." + Twine(i)); 271 // TODO: Tell AA about the new values? 272 Align Alignment = 273 commonAlignment(StructAlign, SL->getElementOffset(i)); 274 Args.push_back(IRB.CreateAlignedLoad( 275 STy->getElementType(i), Idx, Alignment, Idx->getName() + ".val")); 276 ArgAttrVec.push_back(AttributeSet()); 277 } 278 } else if (!I->use_empty()) { 279 // Non-dead argument: insert GEPs and loads as appropriate. 280 ScalarizeTable &ArgIndices = ScalarizedElements[&*I]; 281 // Store the Value* version of the indices in here, but declare it now 282 // for reuse. 283 std::vector<Value *> Ops; 284 for (const auto &ArgIndex : ArgIndices) { 285 Value *V = *AI; 286 LoadInst *OrigLoad = 287 OriginalLoads[std::make_pair(&*I, ArgIndex.second)]; 288 if (!ArgIndex.second.empty()) { 289 Ops.reserve(ArgIndex.second.size()); 290 Type *ElTy = V->getType(); 291 for (auto II : ArgIndex.second) { 292 // Use i32 to index structs, and i64 for others (pointers/arrays). 293 // This satisfies GEP constraints. 294 Type *IdxTy = 295 (ElTy->isStructTy() ? Type::getInt32Ty(F->getContext()) 296 : Type::getInt64Ty(F->getContext())); 297 Ops.push_back(ConstantInt::get(IdxTy, II)); 298 // Keep track of the type we're currently indexing. 299 if (auto *ElPTy = dyn_cast<PointerType>(ElTy)) 300 ElTy = ElPTy->getPointerElementType(); 301 else 302 ElTy = GetElementPtrInst::getTypeAtIndex(ElTy, II); 303 } 304 // And create a GEP to extract those indices. 305 V = IRB.CreateGEP(ArgIndex.first, V, Ops, V->getName() + ".idx"); 306 Ops.clear(); 307 } 308 // Since we're replacing a load make sure we take the alignment 309 // of the previous load. 310 LoadInst *newLoad = 311 IRB.CreateLoad(OrigLoad->getType(), V, V->getName() + ".val"); 312 newLoad->setAlignment(OrigLoad->getAlign()); 313 // Transfer the AA info too. 314 newLoad->setAAMetadata(OrigLoad->getAAMetadata()); 315 316 Args.push_back(newLoad); 317 ArgAttrVec.push_back(AttributeSet()); 318 } 319 } 320 321 // Push any varargs arguments on the list. 322 for (; AI != CB.arg_end(); ++AI, ++ArgNo) { 323 Args.push_back(*AI); 324 ArgAttrVec.push_back(CallPAL.getParamAttrs(ArgNo)); 325 } 326 327 SmallVector<OperandBundleDef, 1> OpBundles; 328 CB.getOperandBundlesAsDefs(OpBundles); 329 330 CallBase *NewCS = nullptr; 331 if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) { 332 NewCS = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(), 333 Args, OpBundles, "", &CB); 334 } else { 335 auto *NewCall = CallInst::Create(NF, Args, OpBundles, "", &CB); 336 NewCall->setTailCallKind(cast<CallInst>(&CB)->getTailCallKind()); 337 NewCS = NewCall; 338 } 339 NewCS->setCallingConv(CB.getCallingConv()); 340 NewCS->setAttributes(AttributeList::get(F->getContext(), 341 CallPAL.getFnAttrs(), 342 CallPAL.getRetAttrs(), ArgAttrVec)); 343 NewCS->copyMetadata(CB, {LLVMContext::MD_prof, LLVMContext::MD_dbg}); 344 Args.clear(); 345 ArgAttrVec.clear(); 346 347 // Update the callgraph to know that the callsite has been transformed. 348 if (ReplaceCallSite) 349 (*ReplaceCallSite)(CB, *NewCS); 350 351 if (!CB.use_empty()) { 352 CB.replaceAllUsesWith(NewCS); 353 NewCS->takeName(&CB); 354 } 355 356 // Finally, remove the old call from the program, reducing the use-count of 357 // F. 358 CB.eraseFromParent(); 359 } 360 361 // Since we have now created the new function, splice the body of the old 362 // function right into the new function, leaving the old rotting hulk of the 363 // function empty. 364 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList()); 365 366 // Loop over the argument list, transferring uses of the old arguments over to 367 // the new arguments, also transferring over the names as well. 368 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(), 369 I2 = NF->arg_begin(); 370 I != E; ++I) { 371 if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) { 372 // If this is an unmodified argument, move the name and users over to the 373 // new version. 374 I->replaceAllUsesWith(&*I2); 375 I2->takeName(&*I); 376 ++I2; 377 continue; 378 } 379 380 if (ByValArgsToTransform.count(&*I)) { 381 // In the callee, we create an alloca, and store each of the new incoming 382 // arguments into the alloca. 383 Instruction *InsertPt = &NF->begin()->front(); 384 385 // Just add all the struct element types. 386 Type *AgTy = I->getParamByValType(); 387 Align StructAlign = *I->getParamAlign(); 388 Value *TheAlloca = new AllocaInst(AgTy, DL.getAllocaAddrSpace(), nullptr, 389 StructAlign, "", InsertPt); 390 StructType *STy = cast<StructType>(AgTy); 391 Value *Idxs[2] = {ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), 392 nullptr}; 393 const StructLayout *SL = DL.getStructLayout(STy); 394 395 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 396 Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i); 397 Value *Idx = GetElementPtrInst::Create( 398 AgTy, TheAlloca, Idxs, TheAlloca->getName() + "." + Twine(i), 399 InsertPt); 400 I2->setName(I->getName() + "." + Twine(i)); 401 Align Alignment = commonAlignment(StructAlign, SL->getElementOffset(i)); 402 new StoreInst(&*I2++, Idx, false, Alignment, InsertPt); 403 } 404 405 // Anything that used the arg should now use the alloca. 406 I->replaceAllUsesWith(TheAlloca); 407 TheAlloca->takeName(&*I); 408 continue; 409 } 410 411 // There potentially are metadata uses for things like llvm.dbg.value. 412 // Replace them with undef, after handling the other regular uses. 413 auto RauwUndefMetadata = make_scope_exit( 414 [&]() { I->replaceAllUsesWith(UndefValue::get(I->getType())); }); 415 416 if (I->use_empty()) 417 continue; 418 419 // Otherwise, if we promoted this argument, then all users are load 420 // instructions (or GEPs with only load users), and all loads should be 421 // using the new argument that we added. 422 ScalarizeTable &ArgIndices = ScalarizedElements[&*I]; 423 424 while (!I->use_empty()) { 425 if (LoadInst *LI = dyn_cast<LoadInst>(I->user_back())) { 426 assert(ArgIndices.begin()->second.empty() && 427 "Load element should sort to front!"); 428 I2->setName(I->getName() + ".val"); 429 LI->replaceAllUsesWith(&*I2); 430 LI->eraseFromParent(); 431 LLVM_DEBUG(dbgs() << "*** Promoted load of argument '" << I->getName() 432 << "' in function '" << F->getName() << "'\n"); 433 } else { 434 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->user_back()); 435 assert(!GEP->use_empty() && 436 "GEPs without uses should be cleaned up already"); 437 IndicesVector Operands; 438 Operands.reserve(GEP->getNumIndices()); 439 for (const Use &Idx : GEP->indices()) 440 Operands.push_back(cast<ConstantInt>(Idx)->getSExtValue()); 441 442 // GEPs with a single 0 index can be merged with direct loads 443 if (Operands.size() == 1 && Operands.front() == 0) 444 Operands.clear(); 445 446 Function::arg_iterator TheArg = I2; 447 for (ScalarizeTable::iterator It = ArgIndices.begin(); 448 It->second != Operands; ++It, ++TheArg) { 449 assert(It != ArgIndices.end() && "GEP not handled??"); 450 } 451 452 TheArg->setName(formatv("{0}.{1:$[.]}.val", I->getName(), 453 make_range(Operands.begin(), Operands.end()))); 454 455 LLVM_DEBUG(dbgs() << "*** Promoted agg argument '" << TheArg->getName() 456 << "' of function '" << NF->getName() << "'\n"); 457 458 // All of the uses must be load instructions. Replace them all with 459 // the argument specified by ArgNo. 460 while (!GEP->use_empty()) { 461 LoadInst *L = cast<LoadInst>(GEP->user_back()); 462 L->replaceAllUsesWith(&*TheArg); 463 L->eraseFromParent(); 464 } 465 GEP->eraseFromParent(); 466 } 467 } 468 // Increment I2 past all of the arguments added for this promoted pointer. 469 std::advance(I2, ArgIndices.size()); 470 } 471 472 return NF; 473 } 474 475 /// Return true if we can prove that all callees pass in a valid pointer for the 476 /// specified function argument. 477 static bool allCallersPassValidPointerForArgument(Argument *Arg, Type *Ty) { 478 Function *Callee = Arg->getParent(); 479 const DataLayout &DL = Callee->getParent()->getDataLayout(); 480 481 unsigned ArgNo = Arg->getArgNo(); 482 483 // Look at all call sites of the function. At this point we know we only have 484 // direct callees. 485 for (User *U : Callee->users()) { 486 CallBase &CB = cast<CallBase>(*U); 487 488 if (!isDereferenceablePointer(CB.getArgOperand(ArgNo), Ty, DL)) 489 return false; 490 } 491 return true; 492 } 493 494 /// Returns true if Prefix is a prefix of longer. That means, Longer has a size 495 /// that is greater than or equal to the size of prefix, and each of the 496 /// elements in Prefix is the same as the corresponding elements in Longer. 497 /// 498 /// This means it also returns true when Prefix and Longer are equal! 499 static bool isPrefix(const IndicesVector &Prefix, const IndicesVector &Longer) { 500 if (Prefix.size() > Longer.size()) 501 return false; 502 return std::equal(Prefix.begin(), Prefix.end(), Longer.begin()); 503 } 504 505 /// Checks if Indices, or a prefix of Indices, is in Set. 506 static bool prefixIn(const IndicesVector &Indices, 507 std::set<IndicesVector> &Set) { 508 std::set<IndicesVector>::iterator Low; 509 Low = Set.upper_bound(Indices); 510 if (Low != Set.begin()) 511 Low--; 512 // Low is now the last element smaller than or equal to Indices. This means 513 // it points to a prefix of Indices (possibly Indices itself), if such 514 // prefix exists. 515 // 516 // This load is safe if any prefix of its operands is safe to load. 517 return Low != Set.end() && isPrefix(*Low, Indices); 518 } 519 520 /// Mark the given indices (ToMark) as safe in the given set of indices 521 /// (Safe). Marking safe usually means adding ToMark to Safe. However, if there 522 /// is already a prefix of Indices in Safe, Indices are implicitely marked safe 523 /// already. Furthermore, any indices that Indices is itself a prefix of, are 524 /// removed from Safe (since they are implicitely safe because of Indices now). 525 static void markIndicesSafe(const IndicesVector &ToMark, 526 std::set<IndicesVector> &Safe) { 527 std::set<IndicesVector>::iterator Low; 528 Low = Safe.upper_bound(ToMark); 529 // Guard against the case where Safe is empty 530 if (Low != Safe.begin()) 531 Low--; 532 // Low is now the last element smaller than or equal to Indices. This 533 // means it points to a prefix of Indices (possibly Indices itself), if 534 // such prefix exists. 535 if (Low != Safe.end()) { 536 if (isPrefix(*Low, ToMark)) 537 // If there is already a prefix of these indices (or exactly these 538 // indices) marked a safe, don't bother adding these indices 539 return; 540 541 // Increment Low, so we can use it as a "insert before" hint 542 ++Low; 543 } 544 // Insert 545 Low = Safe.insert(Low, ToMark); 546 ++Low; 547 // If there we're a prefix of longer index list(s), remove those 548 std::set<IndicesVector>::iterator End = Safe.end(); 549 while (Low != End && isPrefix(ToMark, *Low)) { 550 std::set<IndicesVector>::iterator Remove = Low; 551 ++Low; 552 Safe.erase(Remove); 553 } 554 } 555 556 /// isSafeToPromoteArgument - As you might guess from the name of this method, 557 /// it checks to see if it is both safe and useful to promote the argument. 558 /// This method limits promotion of aggregates to only promote up to three 559 /// elements of the aggregate in order to avoid exploding the number of 560 /// arguments passed in. 561 static bool isSafeToPromoteArgument(Argument *Arg, Type *ByValTy, AAResults &AAR, 562 unsigned MaxElements) { 563 using GEPIndicesSet = std::set<IndicesVector>; 564 565 // Quick exit for unused arguments 566 if (Arg->use_empty()) 567 return true; 568 569 // We can only promote this argument if all of the uses are loads, or are GEP 570 // instructions (with constant indices) that are subsequently loaded. 571 // 572 // Promoting the argument causes it to be loaded in the caller 573 // unconditionally. This is only safe if we can prove that either the load 574 // would have happened in the callee anyway (ie, there is a load in the entry 575 // block) or the pointer passed in at every call site is guaranteed to be 576 // valid. 577 // In the former case, invalid loads can happen, but would have happened 578 // anyway, in the latter case, invalid loads won't happen. This prevents us 579 // from introducing an invalid load that wouldn't have happened in the 580 // original code. 581 // 582 // This set will contain all sets of indices that are loaded in the entry 583 // block, and thus are safe to unconditionally load in the caller. 584 GEPIndicesSet SafeToUnconditionallyLoad; 585 586 // This set contains all the sets of indices that we are planning to promote. 587 // This makes it possible to limit the number of arguments added. 588 GEPIndicesSet ToPromote; 589 590 // If the pointer is always valid, any load with first index 0 is valid. 591 592 if (ByValTy) 593 SafeToUnconditionallyLoad.insert(IndicesVector(1, 0)); 594 595 // Whenever a new underlying type for the operand is found, make sure it's 596 // consistent with the GEPs and loads we've already seen and, if necessary, 597 // use it to see if all incoming pointers are valid (which implies the 0-index 598 // is safe). 599 Type *BaseTy = ByValTy; 600 auto UpdateBaseTy = [&](Type *NewBaseTy) { 601 if (BaseTy) 602 return BaseTy == NewBaseTy; 603 604 BaseTy = NewBaseTy; 605 if (allCallersPassValidPointerForArgument(Arg, BaseTy)) { 606 assert(SafeToUnconditionallyLoad.empty()); 607 SafeToUnconditionallyLoad.insert(IndicesVector(1, 0)); 608 } 609 610 return true; 611 }; 612 613 // First, iterate the entry block and mark loads of (geps of) arguments as 614 // safe. 615 BasicBlock &EntryBlock = Arg->getParent()->front(); 616 // Declare this here so we can reuse it 617 IndicesVector Indices; 618 for (Instruction &I : EntryBlock) 619 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) { 620 Value *V = LI->getPointerOperand(); 621 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) { 622 V = GEP->getPointerOperand(); 623 if (V == Arg) { 624 // This load actually loads (part of) Arg? Check the indices then. 625 Indices.reserve(GEP->getNumIndices()); 626 for (Use &Idx : GEP->indices()) 627 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) 628 Indices.push_back(CI->getSExtValue()); 629 else 630 // We found a non-constant GEP index for this argument? Bail out 631 // right away, can't promote this argument at all. 632 return false; 633 634 if (!UpdateBaseTy(GEP->getSourceElementType())) 635 return false; 636 637 // Indices checked out, mark them as safe 638 markIndicesSafe(Indices, SafeToUnconditionallyLoad); 639 Indices.clear(); 640 } 641 } else if (V == Arg) { 642 // Direct loads are equivalent to a GEP with a single 0 index. 643 markIndicesSafe(IndicesVector(1, 0), SafeToUnconditionallyLoad); 644 645 if (BaseTy && LI->getType() != BaseTy) 646 return false; 647 648 BaseTy = LI->getType(); 649 } 650 } 651 652 // Now, iterate all uses of the argument to see if there are any uses that are 653 // not (GEP+)loads, or any (GEP+)loads that are not safe to promote. 654 SmallVector<LoadInst *, 16> Loads; 655 IndicesVector Operands; 656 for (Use &U : Arg->uses()) { 657 User *UR = U.getUser(); 658 Operands.clear(); 659 if (LoadInst *LI = dyn_cast<LoadInst>(UR)) { 660 // Don't hack volatile/atomic loads 661 if (!LI->isSimple()) 662 return false; 663 Loads.push_back(LI); 664 // Direct loads are equivalent to a GEP with a zero index and then a load. 665 Operands.push_back(0); 666 667 if (!UpdateBaseTy(LI->getType())) 668 return false; 669 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UR)) { 670 if (GEP->use_empty()) { 671 // Dead GEP's cause trouble later. Just remove them if we run into 672 // them. 673 continue; 674 } 675 676 if (!UpdateBaseTy(GEP->getSourceElementType())) 677 return false; 678 679 // Ensure that all of the indices are constants. 680 for (Use &Idx : GEP->indices()) 681 if (ConstantInt *C = dyn_cast<ConstantInt>(Idx)) 682 Operands.push_back(C->getSExtValue()); 683 else 684 return false; // Not a constant operand GEP! 685 686 // Ensure that the only users of the GEP are load instructions. 687 for (User *GEPU : GEP->users()) 688 if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) { 689 // Don't hack volatile/atomic loads 690 if (!LI->isSimple()) 691 return false; 692 Loads.push_back(LI); 693 } else { 694 // Other uses than load? 695 return false; 696 } 697 } else { 698 return false; // Not a load or a GEP. 699 } 700 701 // Now, see if it is safe to promote this load / loads of this GEP. Loading 702 // is safe if Operands, or a prefix of Operands, is marked as safe. 703 if (!prefixIn(Operands, SafeToUnconditionallyLoad)) 704 return false; 705 706 // See if we are already promoting a load with these indices. If not, check 707 // to make sure that we aren't promoting too many elements. If so, nothing 708 // to do. 709 if (ToPromote.find(Operands) == ToPromote.end()) { 710 if (MaxElements > 0 && ToPromote.size() == MaxElements) { 711 LLVM_DEBUG(dbgs() << "argpromotion not promoting argument '" 712 << Arg->getName() 713 << "' because it would require adding more " 714 << "than " << MaxElements 715 << " arguments to the function.\n"); 716 // We limit aggregate promotion to only promoting up to a fixed number 717 // of elements of the aggregate. 718 return false; 719 } 720 ToPromote.insert(std::move(Operands)); 721 } 722 } 723 724 if (Loads.empty()) 725 return true; // No users, this is a dead argument. 726 727 // Okay, now we know that the argument is only used by load instructions and 728 // it is safe to unconditionally perform all of them. Use alias analysis to 729 // check to see if the pointer is guaranteed to not be modified from entry of 730 // the function to each of the load instructions. 731 732 // Because there could be several/many load instructions, remember which 733 // blocks we know to be transparent to the load. 734 df_iterator_default_set<BasicBlock *, 16> TranspBlocks; 735 736 for (LoadInst *Load : Loads) { 737 // Check to see if the load is invalidated from the start of the block to 738 // the load itself. 739 BasicBlock *BB = Load->getParent(); 740 741 MemoryLocation Loc = MemoryLocation::get(Load); 742 if (AAR.canInstructionRangeModRef(BB->front(), *Load, Loc, ModRefInfo::Mod)) 743 return false; // Pointer is invalidated! 744 745 // Now check every path from the entry block to the load for transparency. 746 // To do this, we perform a depth first search on the inverse CFG from the 747 // loading block. 748 for (BasicBlock *P : predecessors(BB)) { 749 for (BasicBlock *TranspBB : inverse_depth_first_ext(P, TranspBlocks)) 750 if (AAR.canBasicBlockModify(*TranspBB, Loc)) 751 return false; 752 } 753 } 754 755 // If the path from the entry of the function to each load is free of 756 // instructions that potentially invalidate the load, we can make the 757 // transformation! 758 return true; 759 } 760 761 bool ArgumentPromotionPass::isDenselyPacked(Type *type, const DataLayout &DL) { 762 // There is no size information, so be conservative. 763 if (!type->isSized()) 764 return false; 765 766 // If the alloc size is not equal to the storage size, then there are padding 767 // bytes. For x86_fp80 on x86-64, size: 80 alloc size: 128. 768 if (DL.getTypeSizeInBits(type) != DL.getTypeAllocSizeInBits(type)) 769 return false; 770 771 // FIXME: This isn't the right way to check for padding in vectors with 772 // non-byte-size elements. 773 if (VectorType *seqTy = dyn_cast<VectorType>(type)) 774 return isDenselyPacked(seqTy->getElementType(), DL); 775 776 // For array types, check for padding within members. 777 if (ArrayType *seqTy = dyn_cast<ArrayType>(type)) 778 return isDenselyPacked(seqTy->getElementType(), DL); 779 780 if (!isa<StructType>(type)) 781 return true; 782 783 // Check for padding within and between elements of a struct. 784 StructType *StructTy = cast<StructType>(type); 785 const StructLayout *Layout = DL.getStructLayout(StructTy); 786 uint64_t StartPos = 0; 787 for (unsigned i = 0, E = StructTy->getNumElements(); i < E; ++i) { 788 Type *ElTy = StructTy->getElementType(i); 789 if (!isDenselyPacked(ElTy, DL)) 790 return false; 791 if (StartPos != Layout->getElementOffsetInBits(i)) 792 return false; 793 StartPos += DL.getTypeAllocSizeInBits(ElTy); 794 } 795 796 return true; 797 } 798 799 /// Checks if the padding bytes of an argument could be accessed. 800 static bool canPaddingBeAccessed(Argument *arg) { 801 assert(arg->hasByValAttr()); 802 803 // Track all the pointers to the argument to make sure they are not captured. 804 SmallPtrSet<Value *, 16> PtrValues; 805 PtrValues.insert(arg); 806 807 // Track all of the stores. 808 SmallVector<StoreInst *, 16> Stores; 809 810 // Scan through the uses recursively to make sure the pointer is always used 811 // sanely. 812 SmallVector<Value *, 16> WorkList(arg->users()); 813 while (!WorkList.empty()) { 814 Value *V = WorkList.pop_back_val(); 815 if (isa<GetElementPtrInst>(V) || isa<PHINode>(V)) { 816 if (PtrValues.insert(V).second) 817 llvm::append_range(WorkList, V->users()); 818 } else if (StoreInst *Store = dyn_cast<StoreInst>(V)) { 819 Stores.push_back(Store); 820 } else if (!isa<LoadInst>(V)) { 821 return true; 822 } 823 } 824 825 // Check to make sure the pointers aren't captured 826 for (StoreInst *Store : Stores) 827 if (PtrValues.count(Store->getValueOperand())) 828 return true; 829 830 return false; 831 } 832 833 bool ArgumentPromotionPass::areFunctionArgsABICompatible( 834 const Function &F, const TargetTransformInfo &TTI, 835 SmallPtrSetImpl<Argument *> &ArgsToPromote, 836 SmallPtrSetImpl<Argument *> &ByValArgsToTransform) { 837 // TODO: Check individual arguments so we can promote a subset? 838 SmallVector<Type *, 32> Types; 839 for (Argument *Arg : ArgsToPromote) 840 Types.push_back(Arg->getType()->getPointerElementType()); 841 for (Argument *Arg : ByValArgsToTransform) 842 Types.push_back(Arg->getParamByValType()); 843 844 for (const Use &U : F.uses()) { 845 CallBase *CB = dyn_cast<CallBase>(U.getUser()); 846 if (!CB) 847 return false; 848 const Function *Caller = CB->getCaller(); 849 const Function *Callee = CB->getCalledFunction(); 850 if (!TTI.areTypesABICompatible(Caller, Callee, Types)) 851 return false; 852 } 853 return true; 854 } 855 856 /// PromoteArguments - This method checks the specified function to see if there 857 /// are any promotable arguments and if it is safe to promote the function (for 858 /// example, all callers are direct). If safe to promote some arguments, it 859 /// calls the DoPromotion method. 860 static Function * 861 promoteArguments(Function *F, function_ref<AAResults &(Function &F)> AARGetter, 862 unsigned MaxElements, 863 Optional<function_ref<void(CallBase &OldCS, CallBase &NewCS)>> 864 ReplaceCallSite, 865 const TargetTransformInfo &TTI) { 866 // Don't perform argument promotion for naked functions; otherwise we can end 867 // up removing parameters that are seemingly 'not used' as they are referred 868 // to in the assembly. 869 if(F->hasFnAttribute(Attribute::Naked)) 870 return nullptr; 871 872 // Make sure that it is local to this module. 873 if (!F->hasLocalLinkage()) 874 return nullptr; 875 876 // Don't promote arguments for variadic functions. Adding, removing, or 877 // changing non-pack parameters can change the classification of pack 878 // parameters. Frontends encode that classification at the call site in the 879 // IR, while in the callee the classification is determined dynamically based 880 // on the number of registers consumed so far. 881 if (F->isVarArg()) 882 return nullptr; 883 884 // Don't transform functions that receive inallocas, as the transformation may 885 // not be safe depending on calling convention. 886 if (F->getAttributes().hasAttrSomewhere(Attribute::InAlloca)) 887 return nullptr; 888 889 // First check: see if there are any pointer arguments! If not, quick exit. 890 SmallVector<Argument *, 16> PointerArgs; 891 for (Argument &I : F->args()) 892 if (I.getType()->isPointerTy()) 893 PointerArgs.push_back(&I); 894 if (PointerArgs.empty()) 895 return nullptr; 896 897 // Second check: make sure that all callers are direct callers. We can't 898 // transform functions that have indirect callers. Also see if the function 899 // is self-recursive and check that target features are compatible. 900 bool isSelfRecursive = false; 901 for (Use &U : F->uses()) { 902 CallBase *CB = dyn_cast<CallBase>(U.getUser()); 903 // Must be a direct call. 904 if (CB == nullptr || !CB->isCallee(&U)) 905 return nullptr; 906 907 // Can't change signature of musttail callee 908 if (CB->isMustTailCall()) 909 return nullptr; 910 911 if (CB->getParent()->getParent() == F) 912 isSelfRecursive = true; 913 } 914 915 // Can't change signature of musttail caller 916 // FIXME: Support promoting whole chain of musttail functions 917 for (BasicBlock &BB : *F) 918 if (BB.getTerminatingMustTailCall()) 919 return nullptr; 920 921 const DataLayout &DL = F->getParent()->getDataLayout(); 922 923 AAResults &AAR = AARGetter(*F); 924 925 // Check to see which arguments are promotable. If an argument is promotable, 926 // add it to ArgsToPromote. 927 SmallPtrSet<Argument *, 8> ArgsToPromote; 928 SmallPtrSet<Argument *, 8> ByValArgsToTransform; 929 for (Argument *PtrArg : PointerArgs) { 930 Type *AgTy = PtrArg->getType()->getPointerElementType(); 931 932 // Replace sret attribute with noalias. This reduces register pressure by 933 // avoiding a register copy. 934 if (PtrArg->hasStructRetAttr()) { 935 unsigned ArgNo = PtrArg->getArgNo(); 936 F->removeParamAttr(ArgNo, Attribute::StructRet); 937 F->addParamAttr(ArgNo, Attribute::NoAlias); 938 for (Use &U : F->uses()) { 939 CallBase &CB = cast<CallBase>(*U.getUser()); 940 CB.removeParamAttr(ArgNo, Attribute::StructRet); 941 CB.addParamAttr(ArgNo, Attribute::NoAlias); 942 } 943 } 944 945 // If this is a byval argument, and if the aggregate type is small, just 946 // pass the elements, which is always safe, if the passed value is densely 947 // packed or if we can prove the padding bytes are never accessed. 948 // 949 // Only handle arguments with specified alignment; if it's unspecified, the 950 // actual alignment of the argument is target-specific. 951 bool isSafeToPromote = PtrArg->hasByValAttr() && PtrArg->getParamAlign() && 952 (ArgumentPromotionPass::isDenselyPacked(AgTy, DL) || 953 !canPaddingBeAccessed(PtrArg)); 954 if (isSafeToPromote) { 955 if (StructType *STy = dyn_cast<StructType>(AgTy)) { 956 if (MaxElements > 0 && STy->getNumElements() > MaxElements) { 957 LLVM_DEBUG(dbgs() << "argpromotion disable promoting argument '" 958 << PtrArg->getName() 959 << "' because it would require adding more" 960 << " than " << MaxElements 961 << " arguments to the function.\n"); 962 continue; 963 } 964 965 // If all the elements are single-value types, we can promote it. 966 bool AllSimple = true; 967 for (const auto *EltTy : STy->elements()) { 968 if (!EltTy->isSingleValueType()) { 969 AllSimple = false; 970 break; 971 } 972 } 973 974 // Safe to transform, don't even bother trying to "promote" it. 975 // Passing the elements as a scalar will allow sroa to hack on 976 // the new alloca we introduce. 977 if (AllSimple) { 978 ByValArgsToTransform.insert(PtrArg); 979 continue; 980 } 981 } 982 } 983 984 // If the argument is a recursive type and we're in a recursive 985 // function, we could end up infinitely peeling the function argument. 986 if (isSelfRecursive) { 987 if (StructType *STy = dyn_cast<StructType>(AgTy)) { 988 bool RecursiveType = 989 llvm::is_contained(STy->elements(), PtrArg->getType()); 990 if (RecursiveType) 991 continue; 992 } 993 } 994 995 // Otherwise, see if we can promote the pointer to its value. 996 Type *ByValTy = 997 PtrArg->hasByValAttr() ? PtrArg->getParamByValType() : nullptr; 998 if (isSafeToPromoteArgument(PtrArg, ByValTy, AAR, MaxElements)) 999 ArgsToPromote.insert(PtrArg); 1000 } 1001 1002 // No promotable pointer arguments. 1003 if (ArgsToPromote.empty() && ByValArgsToTransform.empty()) 1004 return nullptr; 1005 1006 if (!ArgumentPromotionPass::areFunctionArgsABICompatible( 1007 *F, TTI, ArgsToPromote, ByValArgsToTransform)) 1008 return nullptr; 1009 1010 return doPromotion(F, ArgsToPromote, ByValArgsToTransform, ReplaceCallSite); 1011 } 1012 1013 PreservedAnalyses ArgumentPromotionPass::run(LazyCallGraph::SCC &C, 1014 CGSCCAnalysisManager &AM, 1015 LazyCallGraph &CG, 1016 CGSCCUpdateResult &UR) { 1017 bool Changed = false, LocalChange; 1018 1019 // Iterate until we stop promoting from this SCC. 1020 do { 1021 LocalChange = false; 1022 1023 FunctionAnalysisManager &FAM = 1024 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager(); 1025 1026 for (LazyCallGraph::Node &N : C) { 1027 Function &OldF = N.getFunction(); 1028 1029 // FIXME: This lambda must only be used with this function. We should 1030 // skip the lambda and just get the AA results directly. 1031 auto AARGetter = [&](Function &F) -> AAResults & { 1032 assert(&F == &OldF && "Called with an unexpected function!"); 1033 return FAM.getResult<AAManager>(F); 1034 }; 1035 1036 const TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(OldF); 1037 Function *NewF = 1038 promoteArguments(&OldF, AARGetter, MaxElements, None, TTI); 1039 if (!NewF) 1040 continue; 1041 LocalChange = true; 1042 1043 // Directly substitute the functions in the call graph. Note that this 1044 // requires the old function to be completely dead and completely 1045 // replaced by the new function. It does no call graph updates, it merely 1046 // swaps out the particular function mapped to a particular node in the 1047 // graph. 1048 C.getOuterRefSCC().replaceNodeFunction(N, *NewF); 1049 FAM.clear(OldF, OldF.getName()); 1050 OldF.eraseFromParent(); 1051 1052 PreservedAnalyses FuncPA; 1053 FuncPA.preserveSet<CFGAnalyses>(); 1054 for (auto *U : NewF->users()) { 1055 auto *UserF = cast<CallBase>(U)->getFunction(); 1056 FAM.invalidate(*UserF, FuncPA); 1057 } 1058 } 1059 1060 Changed |= LocalChange; 1061 } while (LocalChange); 1062 1063 if (!Changed) 1064 return PreservedAnalyses::all(); 1065 1066 PreservedAnalyses PA; 1067 // We've cleared out analyses for deleted functions. 1068 PA.preserve<FunctionAnalysisManagerCGSCCProxy>(); 1069 // We've manually invalidated analyses for functions we've modified. 1070 PA.preserveSet<AllAnalysesOn<Function>>(); 1071 return PA; 1072 } 1073 1074 namespace { 1075 1076 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass. 1077 struct ArgPromotion : public CallGraphSCCPass { 1078 // Pass identification, replacement for typeid 1079 static char ID; 1080 1081 explicit ArgPromotion(unsigned MaxElements = 3) 1082 : CallGraphSCCPass(ID), MaxElements(MaxElements) { 1083 initializeArgPromotionPass(*PassRegistry::getPassRegistry()); 1084 } 1085 1086 void getAnalysisUsage(AnalysisUsage &AU) const override { 1087 AU.addRequired<AssumptionCacheTracker>(); 1088 AU.addRequired<TargetLibraryInfoWrapperPass>(); 1089 AU.addRequired<TargetTransformInfoWrapperPass>(); 1090 getAAResultsAnalysisUsage(AU); 1091 CallGraphSCCPass::getAnalysisUsage(AU); 1092 } 1093 1094 bool runOnSCC(CallGraphSCC &SCC) override; 1095 1096 private: 1097 using llvm::Pass::doInitialization; 1098 1099 bool doInitialization(CallGraph &CG) override; 1100 1101 /// The maximum number of elements to expand, or 0 for unlimited. 1102 unsigned MaxElements; 1103 }; 1104 1105 } // end anonymous namespace 1106 1107 char ArgPromotion::ID = 0; 1108 1109 INITIALIZE_PASS_BEGIN(ArgPromotion, "argpromotion", 1110 "Promote 'by reference' arguments to scalars", false, 1111 false) 1112 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1113 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) 1114 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1115 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 1116 INITIALIZE_PASS_END(ArgPromotion, "argpromotion", 1117 "Promote 'by reference' arguments to scalars", false, false) 1118 1119 Pass *llvm::createArgumentPromotionPass(unsigned MaxElements) { 1120 return new ArgPromotion(MaxElements); 1121 } 1122 1123 bool ArgPromotion::runOnSCC(CallGraphSCC &SCC) { 1124 if (skipSCC(SCC)) 1125 return false; 1126 1127 // Get the callgraph information that we need to update to reflect our 1128 // changes. 1129 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); 1130 1131 LegacyAARGetter AARGetter(*this); 1132 1133 bool Changed = false, LocalChange; 1134 1135 // Iterate until we stop promoting from this SCC. 1136 do { 1137 LocalChange = false; 1138 // Attempt to promote arguments from all functions in this SCC. 1139 for (CallGraphNode *OldNode : SCC) { 1140 Function *OldF = OldNode->getFunction(); 1141 if (!OldF) 1142 continue; 1143 1144 auto ReplaceCallSite = [&](CallBase &OldCS, CallBase &NewCS) { 1145 Function *Caller = OldCS.getParent()->getParent(); 1146 CallGraphNode *NewCalleeNode = 1147 CG.getOrInsertFunction(NewCS.getCalledFunction()); 1148 CallGraphNode *CallerNode = CG[Caller]; 1149 CallerNode->replaceCallEdge(cast<CallBase>(OldCS), 1150 cast<CallBase>(NewCS), NewCalleeNode); 1151 }; 1152 1153 const TargetTransformInfo &TTI = 1154 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(*OldF); 1155 if (Function *NewF = promoteArguments(OldF, AARGetter, MaxElements, 1156 {ReplaceCallSite}, TTI)) { 1157 LocalChange = true; 1158 1159 // Update the call graph for the newly promoted function. 1160 CallGraphNode *NewNode = CG.getOrInsertFunction(NewF); 1161 NewNode->stealCalledFunctionsFrom(OldNode); 1162 if (OldNode->getNumReferences() == 0) 1163 delete CG.removeFunctionFromModule(OldNode); 1164 else 1165 OldF->setLinkage(Function::ExternalLinkage); 1166 1167 // And updat ethe SCC we're iterating as well. 1168 SCC.ReplaceNode(OldNode, NewNode); 1169 } 1170 } 1171 // Remember that we changed something. 1172 Changed |= LocalChange; 1173 } while (LocalChange); 1174 1175 return Changed; 1176 } 1177 1178 bool ArgPromotion::doInitialization(CallGraph &CG) { 1179 return CallGraphSCCPass::doInitialization(CG); 1180 } 1181