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/ValueTracking.h" 50 #include "llvm/Analysis/TargetLibraryInfo.h" 51 #include "llvm/Analysis/TargetTransformInfo.h" 52 #include "llvm/IR/Argument.h" 53 #include "llvm/IR/Attributes.h" 54 #include "llvm/IR/BasicBlock.h" 55 #include "llvm/IR/CFG.h" 56 #include "llvm/IR/Constants.h" 57 #include "llvm/IR/DataLayout.h" 58 #include "llvm/IR/DerivedTypes.h" 59 #include "llvm/IR/Function.h" 60 #include "llvm/IR/IRBuilder.h" 61 #include "llvm/IR/InstrTypes.h" 62 #include "llvm/IR/Instruction.h" 63 #include "llvm/IR/Instructions.h" 64 #include "llvm/IR/Metadata.h" 65 #include "llvm/IR/Module.h" 66 #include "llvm/IR/NoFolder.h" 67 #include "llvm/IR/PassManager.h" 68 #include "llvm/IR/Type.h" 69 #include "llvm/IR/Use.h" 70 #include "llvm/IR/User.h" 71 #include "llvm/IR/Value.h" 72 #include "llvm/InitializePasses.h" 73 #include "llvm/Pass.h" 74 #include "llvm/Support/Casting.h" 75 #include "llvm/Support/Debug.h" 76 #include "llvm/Support/FormatVariadic.h" 77 #include "llvm/Support/raw_ostream.h" 78 #include "llvm/Transforms/IPO.h" 79 #include <algorithm> 80 #include <cassert> 81 #include <cstdint> 82 #include <functional> 83 #include <iterator> 84 #include <map> 85 #include <set> 86 #include <utility> 87 #include <vector> 88 89 using namespace llvm; 90 91 #define DEBUG_TYPE "argpromotion" 92 93 STATISTIC(NumArgumentsPromoted, "Number of pointer arguments promoted"); 94 STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted"); 95 STATISTIC(NumByValArgsPromoted, "Number of byval arguments promoted"); 96 STATISTIC(NumArgumentsDead, "Number of dead pointer args eliminated"); 97 98 /// A vector used to hold the indices of a single GEP instruction 99 using IndicesVector = std::vector<uint64_t>; 100 101 /// DoPromotion - This method actually performs the promotion of the specified 102 /// arguments, and returns the new function. At this point, we know that it's 103 /// safe to do so. 104 static Function * 105 doPromotion(Function *F, SmallPtrSetImpl<Argument *> &ArgsToPromote, 106 SmallPtrSetImpl<Argument *> &ByValArgsToTransform, 107 Optional<function_ref<void(CallBase &OldCS, CallBase &NewCS)>> 108 ReplaceCallSite) { 109 // Start by computing a new prototype for the function, which is the same as 110 // the old function, but has modified arguments. 111 FunctionType *FTy = F->getFunctionType(); 112 std::vector<Type *> Params; 113 114 using ScalarizeTable = std::set<std::pair<Type *, IndicesVector>>; 115 116 // ScalarizedElements - If we are promoting a pointer that has elements 117 // accessed out of it, keep track of which elements are accessed so that we 118 // can add one argument for each. 119 // 120 // Arguments that are directly loaded will have a zero element value here, to 121 // handle cases where there are both a direct load and GEP accesses. 122 std::map<Argument *, ScalarizeTable> ScalarizedElements; 123 124 // OriginalLoads - Keep track of a representative load instruction from the 125 // original function so that we can tell the alias analysis implementation 126 // what the new GEP/Load instructions we are inserting look like. 127 // We need to keep the original loads for each argument and the elements 128 // of the argument that are accessed. 129 std::map<std::pair<Argument *, IndicesVector>, LoadInst *> OriginalLoads; 130 131 // Attribute - Keep track of the parameter attributes for the arguments 132 // that we are *not* promoting. For the ones that we do promote, the parameter 133 // attributes are lost 134 SmallVector<AttributeSet, 8> ArgAttrVec; 135 AttributeList PAL = F->getAttributes(); 136 137 // First, determine the new argument list 138 unsigned ArgNo = 0; 139 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; 140 ++I, ++ArgNo) { 141 if (ByValArgsToTransform.count(&*I)) { 142 // Simple byval argument? Just add all the struct element types. 143 Type *AgTy = I->getParamByValType(); 144 StructType *STy = cast<StructType>(AgTy); 145 llvm::append_range(Params, STy->elements()); 146 ArgAttrVec.insert(ArgAttrVec.end(), STy->getNumElements(), 147 AttributeSet()); 148 ++NumByValArgsPromoted; 149 } else if (!ArgsToPromote.count(&*I)) { 150 // Unchanged argument 151 Params.push_back(I->getType()); 152 ArgAttrVec.push_back(PAL.getParamAttrs(ArgNo)); 153 } else if (I->use_empty()) { 154 // Dead argument (which are always marked as promotable) 155 ++NumArgumentsDead; 156 } else { 157 // Okay, this is being promoted. This means that the only uses are loads 158 // or GEPs which are only used by loads 159 160 // In this table, we will track which indices are loaded from the argument 161 // (where direct loads are tracked as no indices). 162 ScalarizeTable &ArgIndices = ScalarizedElements[&*I]; 163 for (User *U : make_early_inc_range(I->users())) { 164 Instruction *UI = cast<Instruction>(U); 165 Type *SrcTy; 166 if (LoadInst *L = dyn_cast<LoadInst>(UI)) 167 SrcTy = L->getType(); 168 else 169 SrcTy = cast<GetElementPtrInst>(UI)->getSourceElementType(); 170 // Skip dead GEPs and remove them. 171 if (isa<GetElementPtrInst>(UI) && UI->use_empty()) { 172 UI->eraseFromParent(); 173 continue; 174 } 175 176 IndicesVector Indices; 177 Indices.reserve(UI->getNumOperands() - 1); 178 // Since loads will only have a single operand, and GEPs only a single 179 // non-index operand, this will record direct loads without any indices, 180 // and gep+loads with the GEP indices. 181 for (const Use &I : llvm::drop_begin(UI->operands())) 182 Indices.push_back(cast<ConstantInt>(I)->getSExtValue()); 183 // GEPs with a single 0 index can be merged with direct loads 184 if (Indices.size() == 1 && Indices.front() == 0) 185 Indices.clear(); 186 ArgIndices.insert(std::make_pair(SrcTy, Indices)); 187 LoadInst *OrigLoad; 188 if (LoadInst *L = dyn_cast<LoadInst>(UI)) 189 OrigLoad = L; 190 else 191 // Take any load, we will use it only to update Alias Analysis 192 OrigLoad = cast<LoadInst>(UI->user_back()); 193 OriginalLoads[std::make_pair(&*I, Indices)] = OrigLoad; 194 } 195 196 // Add a parameter to the function for each element passed in. 197 for (const auto &ArgIndex : ArgIndices) { 198 // not allowed to dereference ->begin() if size() is 0 199 Params.push_back(GetElementPtrInst::getIndexedType( 200 I->getType()->getPointerElementType(), ArgIndex.second)); 201 ArgAttrVec.push_back(AttributeSet()); 202 assert(Params.back()); 203 } 204 205 if (ArgIndices.size() == 1 && ArgIndices.begin()->second.empty()) 206 ++NumArgumentsPromoted; 207 else 208 ++NumAggregatesPromoted; 209 } 210 } 211 212 Type *RetTy = FTy->getReturnType(); 213 214 // Construct the new function type using the new arguments. 215 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg()); 216 217 // Create the new function body and insert it into the module. 218 Function *NF = Function::Create(NFTy, F->getLinkage(), F->getAddressSpace(), 219 F->getName()); 220 NF->copyAttributesFrom(F); 221 NF->copyMetadata(F, 0); 222 223 // The new function will have the !dbg metadata copied from the original 224 // function. The original function may not be deleted, and dbg metadata need 225 // to be unique so we need to drop it. 226 F->setSubprogram(nullptr); 227 228 LLVM_DEBUG(dbgs() << "ARG PROMOTION: Promoting to:" << *NF << "\n" 229 << "From: " << *F); 230 231 // Recompute the parameter attributes list based on the new arguments for 232 // the function. 233 NF->setAttributes(AttributeList::get(F->getContext(), PAL.getFnAttrs(), 234 PAL.getRetAttrs(), ArgAttrVec)); 235 ArgAttrVec.clear(); 236 237 F->getParent()->getFunctionList().insert(F->getIterator(), NF); 238 NF->takeName(F); 239 240 // Loop over all of the callers of the function, transforming the call sites 241 // to pass in the loaded pointers. 242 // 243 SmallVector<Value *, 16> Args; 244 const DataLayout &DL = F->getParent()->getDataLayout(); 245 while (!F->use_empty()) { 246 CallBase &CB = cast<CallBase>(*F->user_back()); 247 assert(CB.getCalledFunction() == F); 248 const AttributeList &CallPAL = CB.getAttributes(); 249 IRBuilder<NoFolder> IRB(&CB); 250 251 // Loop over the operands, inserting GEP and loads in the caller as 252 // appropriate. 253 auto AI = CB.arg_begin(); 254 ArgNo = 0; 255 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; 256 ++I, ++AI, ++ArgNo) 257 if (!ArgsToPromote.count(&*I) && !ByValArgsToTransform.count(&*I)) { 258 Args.push_back(*AI); // Unmodified argument 259 ArgAttrVec.push_back(CallPAL.getParamAttrs(ArgNo)); 260 } else if (ByValArgsToTransform.count(&*I)) { 261 // Emit a GEP and load for each element of the struct. 262 Type *AgTy = I->getParamByValType(); 263 StructType *STy = cast<StructType>(AgTy); 264 Value *Idxs[2] = { 265 ConstantInt::get(Type::getInt32Ty(F->getContext()), 0), nullptr}; 266 const StructLayout *SL = DL.getStructLayout(STy); 267 Align StructAlign = *I->getParamAlign(); 268 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 269 Idxs[1] = ConstantInt::get(Type::getInt32Ty(F->getContext()), i); 270 auto *Idx = 271 IRB.CreateGEP(STy, *AI, Idxs, (*AI)->getName() + "." + Twine(i)); 272 // TODO: Tell AA about the new values? 273 Align Alignment = 274 commonAlignment(StructAlign, SL->getElementOffset(i)); 275 Args.push_back(IRB.CreateAlignedLoad( 276 STy->getElementType(i), Idx, Alignment, Idx->getName() + ".val")); 277 ArgAttrVec.push_back(AttributeSet()); 278 } 279 } else if (!I->use_empty()) { 280 // Non-dead argument: insert GEPs and loads as appropriate. 281 ScalarizeTable &ArgIndices = ScalarizedElements[&*I]; 282 // Store the Value* version of the indices in here, but declare it now 283 // for reuse. 284 std::vector<Value *> Ops; 285 for (const auto &ArgIndex : ArgIndices) { 286 Value *V = *AI; 287 LoadInst *OrigLoad = 288 OriginalLoads[std::make_pair(&*I, ArgIndex.second)]; 289 if (!ArgIndex.second.empty()) { 290 Ops.reserve(ArgIndex.second.size()); 291 Type *ElTy = V->getType(); 292 for (auto II : ArgIndex.second) { 293 // Use i32 to index structs, and i64 for others (pointers/arrays). 294 // This satisfies GEP constraints. 295 Type *IdxTy = 296 (ElTy->isStructTy() ? Type::getInt32Ty(F->getContext()) 297 : Type::getInt64Ty(F->getContext())); 298 Ops.push_back(ConstantInt::get(IdxTy, II)); 299 // Keep track of the type we're currently indexing. 300 if (auto *ElPTy = dyn_cast<PointerType>(ElTy)) 301 ElTy = ElPTy->getPointerElementType(); 302 else 303 ElTy = GetElementPtrInst::getTypeAtIndex(ElTy, II); 304 } 305 // And create a GEP to extract those indices. 306 V = IRB.CreateGEP(ArgIndex.first, V, Ops, V->getName() + ".idx"); 307 Ops.clear(); 308 } 309 // Since we're replacing a load make sure we take the alignment 310 // of the previous load. 311 LoadInst *newLoad = 312 IRB.CreateLoad(OrigLoad->getType(), V, V->getName() + ".val"); 313 newLoad->setAlignment(OrigLoad->getAlign()); 314 // Transfer the AA info too. 315 newLoad->setAAMetadata(OrigLoad->getAAMetadata()); 316 317 Args.push_back(newLoad); 318 ArgAttrVec.push_back(AttributeSet()); 319 } 320 } 321 322 // Push any varargs arguments on the list. 323 for (; AI != CB.arg_end(); ++AI, ++ArgNo) { 324 Args.push_back(*AI); 325 ArgAttrVec.push_back(CallPAL.getParamAttrs(ArgNo)); 326 } 327 328 SmallVector<OperandBundleDef, 1> OpBundles; 329 CB.getOperandBundlesAsDefs(OpBundles); 330 331 CallBase *NewCS = nullptr; 332 if (InvokeInst *II = dyn_cast<InvokeInst>(&CB)) { 333 NewCS = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(), 334 Args, OpBundles, "", &CB); 335 } else { 336 auto *NewCall = CallInst::Create(NF, Args, OpBundles, "", &CB); 337 NewCall->setTailCallKind(cast<CallInst>(&CB)->getTailCallKind()); 338 NewCS = NewCall; 339 } 340 NewCS->setCallingConv(CB.getCallingConv()); 341 NewCS->setAttributes(AttributeList::get(F->getContext(), 342 CallPAL.getFnAttrs(), 343 CallPAL.getRetAttrs(), ArgAttrVec)); 344 NewCS->copyMetadata(CB, {LLVMContext::MD_prof, LLVMContext::MD_dbg}); 345 Args.clear(); 346 ArgAttrVec.clear(); 347 348 // Update the callgraph to know that the callsite has been transformed. 349 if (ReplaceCallSite) 350 (*ReplaceCallSite)(CB, *NewCS); 351 352 if (!CB.use_empty()) { 353 CB.replaceAllUsesWith(NewCS); 354 NewCS->takeName(&CB); 355 } 356 357 // Finally, remove the old call from the program, reducing the use-count of 358 // F. 359 CB.eraseFromParent(); 360 } 361 362 // Since we have now created the new function, splice the body of the old 363 // function right into the new function, leaving the old rotting hulk of the 364 // function empty. 365 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList()); 366 367 // Loop over the argument list, transferring uses of the old arguments over to 368 // the new arguments, also transferring over the names as well. 369 Function::arg_iterator I2 = NF->arg_begin(); 370 for (Argument &Arg : F->args()) { 371 if (!ArgsToPromote.count(&Arg) && !ByValArgsToTransform.count(&Arg)) { 372 // If this is an unmodified argument, move the name and users over to the 373 // new version. 374 Arg.replaceAllUsesWith(&*I2); 375 I2->takeName(&Arg); 376 ++I2; 377 continue; 378 } 379 380 if (ByValArgsToTransform.count(&Arg)) { 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 = Arg.getParamByValType(); 387 Align StructAlign = *Arg.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(Arg.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 Arg.replaceAllUsesWith(TheAlloca); 407 TheAlloca->takeName(&Arg); 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 [&]() { Arg.replaceAllUsesWith(UndefValue::get(Arg.getType())); }); 415 416 if (Arg.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[&Arg]; 423 424 while (!Arg.use_empty()) { 425 if (LoadInst *LI = dyn_cast<LoadInst>(Arg.user_back())) { 426 assert(ArgIndices.begin()->second.empty() && 427 "Load element should sort to front!"); 428 I2->setName(Arg.getName() + ".val"); 429 LI->replaceAllUsesWith(&*I2); 430 LI->eraseFromParent(); 431 LLVM_DEBUG(dbgs() << "*** Promoted load of argument '" << Arg.getName() 432 << "' in function '" << F->getName() << "'\n"); 433 } else { 434 GetElementPtrInst *GEP = cast<GetElementPtrInst>(Arg.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", Arg.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 functions that are guaranteed to execution on function 614 // entry and mark loads of (geps of) arguments as 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 if (!isGuaranteedToTransferExecutionToSuccessor(&I)) 653 break; 654 } 655 656 // Now, iterate all uses of the argument to see if there are any uses that are 657 // not (GEP+)loads, or any (GEP+)loads that are not safe to promote. 658 SmallVector<LoadInst *, 16> Loads; 659 IndicesVector Operands; 660 for (Use &U : Arg->uses()) { 661 User *UR = U.getUser(); 662 Operands.clear(); 663 if (LoadInst *LI = dyn_cast<LoadInst>(UR)) { 664 // Don't hack volatile/atomic loads 665 if (!LI->isSimple()) 666 return false; 667 Loads.push_back(LI); 668 // Direct loads are equivalent to a GEP with a zero index and then a load. 669 Operands.push_back(0); 670 671 if (!UpdateBaseTy(LI->getType())) 672 return false; 673 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UR)) { 674 if (GEP->use_empty()) { 675 // Dead GEP's cause trouble later. Just remove them if we run into 676 // them. 677 continue; 678 } 679 680 if (!UpdateBaseTy(GEP->getSourceElementType())) 681 return false; 682 683 // Ensure that all of the indices are constants. 684 for (Use &Idx : GEP->indices()) 685 if (ConstantInt *C = dyn_cast<ConstantInt>(Idx)) 686 Operands.push_back(C->getSExtValue()); 687 else 688 return false; // Not a constant operand GEP! 689 690 // Ensure that the only users of the GEP are load instructions. 691 for (User *GEPU : GEP->users()) 692 if (LoadInst *LI = dyn_cast<LoadInst>(GEPU)) { 693 // Don't hack volatile/atomic loads 694 if (!LI->isSimple()) 695 return false; 696 Loads.push_back(LI); 697 } else { 698 // Other uses than load? 699 return false; 700 } 701 } else { 702 return false; // Not a load or a GEP. 703 } 704 705 // Now, see if it is safe to promote this load / loads of this GEP. Loading 706 // is safe if Operands, or a prefix of Operands, is marked as safe. 707 if (!prefixIn(Operands, SafeToUnconditionallyLoad)) 708 return false; 709 710 // See if we are already promoting a load with these indices. If not, check 711 // to make sure that we aren't promoting too many elements. If so, nothing 712 // to do. 713 if (ToPromote.find(Operands) == ToPromote.end()) { 714 if (MaxElements > 0 && ToPromote.size() == MaxElements) { 715 LLVM_DEBUG(dbgs() << "argpromotion not promoting argument '" 716 << Arg->getName() 717 << "' because it would require adding more " 718 << "than " << MaxElements 719 << " arguments to the function.\n"); 720 // We limit aggregate promotion to only promoting up to a fixed number 721 // of elements of the aggregate. 722 return false; 723 } 724 ToPromote.insert(std::move(Operands)); 725 } 726 } 727 728 if (Loads.empty()) 729 return true; // No users, this is a dead argument. 730 731 // Okay, now we know that the argument is only used by load instructions and 732 // it is safe to unconditionally perform all of them. Use alias analysis to 733 // check to see if the pointer is guaranteed to not be modified from entry of 734 // the function to each of the load instructions. 735 736 // Because there could be several/many load instructions, remember which 737 // blocks we know to be transparent to the load. 738 df_iterator_default_set<BasicBlock *, 16> TranspBlocks; 739 740 for (LoadInst *Load : Loads) { 741 // Check to see if the load is invalidated from the start of the block to 742 // the load itself. 743 BasicBlock *BB = Load->getParent(); 744 745 MemoryLocation Loc = MemoryLocation::get(Load); 746 if (AAR.canInstructionRangeModRef(BB->front(), *Load, Loc, ModRefInfo::Mod)) 747 return false; // Pointer is invalidated! 748 749 // Now check every path from the entry block to the load for transparency. 750 // To do this, we perform a depth first search on the inverse CFG from the 751 // loading block. 752 for (BasicBlock *P : predecessors(BB)) { 753 for (BasicBlock *TranspBB : inverse_depth_first_ext(P, TranspBlocks)) 754 if (AAR.canBasicBlockModify(*TranspBB, Loc)) 755 return false; 756 } 757 } 758 759 // If the path from the entry of the function to each load is free of 760 // instructions that potentially invalidate the load, we can make the 761 // transformation! 762 return true; 763 } 764 765 bool ArgumentPromotionPass::isDenselyPacked(Type *type, const DataLayout &DL) { 766 // There is no size information, so be conservative. 767 if (!type->isSized()) 768 return false; 769 770 // If the alloc size is not equal to the storage size, then there are padding 771 // bytes. For x86_fp80 on x86-64, size: 80 alloc size: 128. 772 if (DL.getTypeSizeInBits(type) != DL.getTypeAllocSizeInBits(type)) 773 return false; 774 775 // FIXME: This isn't the right way to check for padding in vectors with 776 // non-byte-size elements. 777 if (VectorType *seqTy = dyn_cast<VectorType>(type)) 778 return isDenselyPacked(seqTy->getElementType(), DL); 779 780 // For array types, check for padding within members. 781 if (ArrayType *seqTy = dyn_cast<ArrayType>(type)) 782 return isDenselyPacked(seqTy->getElementType(), DL); 783 784 if (!isa<StructType>(type)) 785 return true; 786 787 // Check for padding within and between elements of a struct. 788 StructType *StructTy = cast<StructType>(type); 789 const StructLayout *Layout = DL.getStructLayout(StructTy); 790 uint64_t StartPos = 0; 791 for (unsigned i = 0, E = StructTy->getNumElements(); i < E; ++i) { 792 Type *ElTy = StructTy->getElementType(i); 793 if (!isDenselyPacked(ElTy, DL)) 794 return false; 795 if (StartPos != Layout->getElementOffsetInBits(i)) 796 return false; 797 StartPos += DL.getTypeAllocSizeInBits(ElTy); 798 } 799 800 return true; 801 } 802 803 /// Checks if the padding bytes of an argument could be accessed. 804 static bool canPaddingBeAccessed(Argument *arg) { 805 assert(arg->hasByValAttr()); 806 807 // Track all the pointers to the argument to make sure they are not captured. 808 SmallPtrSet<Value *, 16> PtrValues; 809 PtrValues.insert(arg); 810 811 // Track all of the stores. 812 SmallVector<StoreInst *, 16> Stores; 813 814 // Scan through the uses recursively to make sure the pointer is always used 815 // sanely. 816 SmallVector<Value *, 16> WorkList(arg->users()); 817 while (!WorkList.empty()) { 818 Value *V = WorkList.pop_back_val(); 819 if (isa<GetElementPtrInst>(V) || isa<PHINode>(V)) { 820 if (PtrValues.insert(V).second) 821 llvm::append_range(WorkList, V->users()); 822 } else if (StoreInst *Store = dyn_cast<StoreInst>(V)) { 823 Stores.push_back(Store); 824 } else if (!isa<LoadInst>(V)) { 825 return true; 826 } 827 } 828 829 // Check to make sure the pointers aren't captured 830 for (StoreInst *Store : Stores) 831 if (PtrValues.count(Store->getValueOperand())) 832 return true; 833 834 return false; 835 } 836 837 /// Check if callers and the callee \p F agree how promoted arguments would be 838 /// passed. The ones that they do not agree on are eliminated from the sets but 839 /// the return value has to be observed as well. 840 static bool areFunctionArgsABICompatible( 841 const Function &F, const TargetTransformInfo &TTI, 842 SmallPtrSetImpl<Argument *> &ArgsToPromote, 843 SmallPtrSetImpl<Argument *> &ByValArgsToTransform) { 844 // TODO: Check individual arguments so we can promote a subset? 845 SmallVector<Type *, 32> Types; 846 for (Argument *Arg : ArgsToPromote) 847 Types.push_back(Arg->getType()->getPointerElementType()); 848 for (Argument *Arg : ByValArgsToTransform) 849 Types.push_back(Arg->getParamByValType()); 850 851 for (const Use &U : F.uses()) { 852 CallBase *CB = dyn_cast<CallBase>(U.getUser()); 853 if (!CB) 854 return false; 855 const Function *Caller = CB->getCaller(); 856 const Function *Callee = CB->getCalledFunction(); 857 if (!TTI.areTypesABICompatible(Caller, Callee, Types)) 858 return false; 859 } 860 return true; 861 } 862 863 /// PromoteArguments - This method checks the specified function to see if there 864 /// are any promotable arguments and if it is safe to promote the function (for 865 /// example, all callers are direct). If safe to promote some arguments, it 866 /// calls the DoPromotion method. 867 static Function * 868 promoteArguments(Function *F, function_ref<AAResults &(Function &F)> AARGetter, 869 unsigned MaxElements, 870 Optional<function_ref<void(CallBase &OldCS, CallBase &NewCS)>> 871 ReplaceCallSite, 872 const TargetTransformInfo &TTI) { 873 // Don't perform argument promotion for naked functions; otherwise we can end 874 // up removing parameters that are seemingly 'not used' as they are referred 875 // to in the assembly. 876 if(F->hasFnAttribute(Attribute::Naked)) 877 return nullptr; 878 879 // Make sure that it is local to this module. 880 if (!F->hasLocalLinkage()) 881 return nullptr; 882 883 // Don't promote arguments for variadic functions. Adding, removing, or 884 // changing non-pack parameters can change the classification of pack 885 // parameters. Frontends encode that classification at the call site in the 886 // IR, while in the callee the classification is determined dynamically based 887 // on the number of registers consumed so far. 888 if (F->isVarArg()) 889 return nullptr; 890 891 // Don't transform functions that receive inallocas, as the transformation may 892 // not be safe depending on calling convention. 893 if (F->getAttributes().hasAttrSomewhere(Attribute::InAlloca)) 894 return nullptr; 895 896 // First check: see if there are any pointer arguments! If not, quick exit. 897 SmallVector<Argument *, 16> PointerArgs; 898 for (Argument &I : F->args()) 899 if (I.getType()->isPointerTy()) 900 PointerArgs.push_back(&I); 901 if (PointerArgs.empty()) 902 return nullptr; 903 904 // Second check: make sure that all callers are direct callers. We can't 905 // transform functions that have indirect callers. Also see if the function 906 // is self-recursive and check that target features are compatible. 907 bool isSelfRecursive = false; 908 for (Use &U : F->uses()) { 909 CallBase *CB = dyn_cast<CallBase>(U.getUser()); 910 // Must be a direct call. 911 if (CB == nullptr || !CB->isCallee(&U)) 912 return nullptr; 913 914 // Can't change signature of musttail callee 915 if (CB->isMustTailCall()) 916 return nullptr; 917 918 if (CB->getParent()->getParent() == F) 919 isSelfRecursive = true; 920 } 921 922 // Can't change signature of musttail caller 923 // FIXME: Support promoting whole chain of musttail functions 924 for (BasicBlock &BB : *F) 925 if (BB.getTerminatingMustTailCall()) 926 return nullptr; 927 928 const DataLayout &DL = F->getParent()->getDataLayout(); 929 930 AAResults &AAR = AARGetter(*F); 931 932 // Check to see which arguments are promotable. If an argument is promotable, 933 // add it to ArgsToPromote. 934 SmallPtrSet<Argument *, 8> ArgsToPromote; 935 SmallPtrSet<Argument *, 8> ByValArgsToTransform; 936 for (Argument *PtrArg : PointerArgs) { 937 Type *AgTy = PtrArg->getType()->getPointerElementType(); 938 939 // Replace sret attribute with noalias. This reduces register pressure by 940 // avoiding a register copy. 941 if (PtrArg->hasStructRetAttr()) { 942 unsigned ArgNo = PtrArg->getArgNo(); 943 F->removeParamAttr(ArgNo, Attribute::StructRet); 944 F->addParamAttr(ArgNo, Attribute::NoAlias); 945 for (Use &U : F->uses()) { 946 CallBase &CB = cast<CallBase>(*U.getUser()); 947 CB.removeParamAttr(ArgNo, Attribute::StructRet); 948 CB.addParamAttr(ArgNo, Attribute::NoAlias); 949 } 950 } 951 952 // If this is a byval argument, and if the aggregate type is small, just 953 // pass the elements, which is always safe, if the passed value is densely 954 // packed or if we can prove the padding bytes are never accessed. 955 // 956 // Only handle arguments with specified alignment; if it's unspecified, the 957 // actual alignment of the argument is target-specific. 958 bool isSafeToPromote = PtrArg->hasByValAttr() && PtrArg->getParamAlign() && 959 (ArgumentPromotionPass::isDenselyPacked(AgTy, DL) || 960 !canPaddingBeAccessed(PtrArg)); 961 if (isSafeToPromote) { 962 if (StructType *STy = dyn_cast<StructType>(AgTy)) { 963 if (MaxElements > 0 && STy->getNumElements() > MaxElements) { 964 LLVM_DEBUG(dbgs() << "argpromotion disable promoting argument '" 965 << PtrArg->getName() 966 << "' because it would require adding more" 967 << " than " << MaxElements 968 << " arguments to the function.\n"); 969 continue; 970 } 971 972 // If all the elements are single-value types, we can promote it. 973 bool AllSimple = true; 974 for (const auto *EltTy : STy->elements()) { 975 if (!EltTy->isSingleValueType()) { 976 AllSimple = false; 977 break; 978 } 979 } 980 981 // Safe to transform, don't even bother trying to "promote" it. 982 // Passing the elements as a scalar will allow sroa to hack on 983 // the new alloca we introduce. 984 if (AllSimple) { 985 ByValArgsToTransform.insert(PtrArg); 986 continue; 987 } 988 } 989 } 990 991 // If the argument is a recursive type and we're in a recursive 992 // function, we could end up infinitely peeling the function argument. 993 if (isSelfRecursive) { 994 if (StructType *STy = dyn_cast<StructType>(AgTy)) { 995 bool RecursiveType = 996 llvm::is_contained(STy->elements(), PtrArg->getType()); 997 if (RecursiveType) 998 continue; 999 } 1000 } 1001 1002 // Otherwise, see if we can promote the pointer to its value. 1003 Type *ByValTy = 1004 PtrArg->hasByValAttr() ? PtrArg->getParamByValType() : nullptr; 1005 if (isSafeToPromoteArgument(PtrArg, ByValTy, AAR, MaxElements)) 1006 ArgsToPromote.insert(PtrArg); 1007 } 1008 1009 // No promotable pointer arguments. 1010 if (ArgsToPromote.empty() && ByValArgsToTransform.empty()) 1011 return nullptr; 1012 1013 if (!areFunctionArgsABICompatible( 1014 *F, TTI, ArgsToPromote, ByValArgsToTransform)) 1015 return nullptr; 1016 1017 return doPromotion(F, ArgsToPromote, ByValArgsToTransform, ReplaceCallSite); 1018 } 1019 1020 PreservedAnalyses ArgumentPromotionPass::run(LazyCallGraph::SCC &C, 1021 CGSCCAnalysisManager &AM, 1022 LazyCallGraph &CG, 1023 CGSCCUpdateResult &UR) { 1024 bool Changed = false, LocalChange; 1025 1026 // Iterate until we stop promoting from this SCC. 1027 do { 1028 LocalChange = false; 1029 1030 FunctionAnalysisManager &FAM = 1031 AM.getResult<FunctionAnalysisManagerCGSCCProxy>(C, CG).getManager(); 1032 1033 for (LazyCallGraph::Node &N : C) { 1034 Function &OldF = N.getFunction(); 1035 1036 // FIXME: This lambda must only be used with this function. We should 1037 // skip the lambda and just get the AA results directly. 1038 auto AARGetter = [&](Function &F) -> AAResults & { 1039 assert(&F == &OldF && "Called with an unexpected function!"); 1040 return FAM.getResult<AAManager>(F); 1041 }; 1042 1043 const TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(OldF); 1044 Function *NewF = 1045 promoteArguments(&OldF, AARGetter, MaxElements, None, TTI); 1046 if (!NewF) 1047 continue; 1048 LocalChange = true; 1049 1050 // Directly substitute the functions in the call graph. Note that this 1051 // requires the old function to be completely dead and completely 1052 // replaced by the new function. It does no call graph updates, it merely 1053 // swaps out the particular function mapped to a particular node in the 1054 // graph. 1055 C.getOuterRefSCC().replaceNodeFunction(N, *NewF); 1056 FAM.clear(OldF, OldF.getName()); 1057 OldF.eraseFromParent(); 1058 1059 PreservedAnalyses FuncPA; 1060 FuncPA.preserveSet<CFGAnalyses>(); 1061 for (auto *U : NewF->users()) { 1062 auto *UserF = cast<CallBase>(U)->getFunction(); 1063 FAM.invalidate(*UserF, FuncPA); 1064 } 1065 } 1066 1067 Changed |= LocalChange; 1068 } while (LocalChange); 1069 1070 if (!Changed) 1071 return PreservedAnalyses::all(); 1072 1073 PreservedAnalyses PA; 1074 // We've cleared out analyses for deleted functions. 1075 PA.preserve<FunctionAnalysisManagerCGSCCProxy>(); 1076 // We've manually invalidated analyses for functions we've modified. 1077 PA.preserveSet<AllAnalysesOn<Function>>(); 1078 return PA; 1079 } 1080 1081 namespace { 1082 1083 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass. 1084 struct ArgPromotion : public CallGraphSCCPass { 1085 // Pass identification, replacement for typeid 1086 static char ID; 1087 1088 explicit ArgPromotion(unsigned MaxElements = 3) 1089 : CallGraphSCCPass(ID), MaxElements(MaxElements) { 1090 initializeArgPromotionPass(*PassRegistry::getPassRegistry()); 1091 } 1092 1093 void getAnalysisUsage(AnalysisUsage &AU) const override { 1094 AU.addRequired<AssumptionCacheTracker>(); 1095 AU.addRequired<TargetLibraryInfoWrapperPass>(); 1096 AU.addRequired<TargetTransformInfoWrapperPass>(); 1097 getAAResultsAnalysisUsage(AU); 1098 CallGraphSCCPass::getAnalysisUsage(AU); 1099 } 1100 1101 bool runOnSCC(CallGraphSCC &SCC) override; 1102 1103 private: 1104 using llvm::Pass::doInitialization; 1105 1106 bool doInitialization(CallGraph &CG) override; 1107 1108 /// The maximum number of elements to expand, or 0 for unlimited. 1109 unsigned MaxElements; 1110 }; 1111 1112 } // end anonymous namespace 1113 1114 char ArgPromotion::ID = 0; 1115 1116 INITIALIZE_PASS_BEGIN(ArgPromotion, "argpromotion", 1117 "Promote 'by reference' arguments to scalars", false, 1118 false) 1119 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 1120 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass) 1121 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 1122 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 1123 INITIALIZE_PASS_END(ArgPromotion, "argpromotion", 1124 "Promote 'by reference' arguments to scalars", false, false) 1125 1126 Pass *llvm::createArgumentPromotionPass(unsigned MaxElements) { 1127 return new ArgPromotion(MaxElements); 1128 } 1129 1130 bool ArgPromotion::runOnSCC(CallGraphSCC &SCC) { 1131 if (skipSCC(SCC)) 1132 return false; 1133 1134 // Get the callgraph information that we need to update to reflect our 1135 // changes. 1136 CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph(); 1137 1138 LegacyAARGetter AARGetter(*this); 1139 1140 bool Changed = false, LocalChange; 1141 1142 // Iterate until we stop promoting from this SCC. 1143 do { 1144 LocalChange = false; 1145 // Attempt to promote arguments from all functions in this SCC. 1146 for (CallGraphNode *OldNode : SCC) { 1147 Function *OldF = OldNode->getFunction(); 1148 if (!OldF) 1149 continue; 1150 1151 auto ReplaceCallSite = [&](CallBase &OldCS, CallBase &NewCS) { 1152 Function *Caller = OldCS.getParent()->getParent(); 1153 CallGraphNode *NewCalleeNode = 1154 CG.getOrInsertFunction(NewCS.getCalledFunction()); 1155 CallGraphNode *CallerNode = CG[Caller]; 1156 CallerNode->replaceCallEdge(cast<CallBase>(OldCS), 1157 cast<CallBase>(NewCS), NewCalleeNode); 1158 }; 1159 1160 const TargetTransformInfo &TTI = 1161 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(*OldF); 1162 if (Function *NewF = promoteArguments(OldF, AARGetter, MaxElements, 1163 {ReplaceCallSite}, TTI)) { 1164 LocalChange = true; 1165 1166 // Update the call graph for the newly promoted function. 1167 CallGraphNode *NewNode = CG.getOrInsertFunction(NewF); 1168 NewNode->stealCalledFunctionsFrom(OldNode); 1169 if (OldNode->getNumReferences() == 0) 1170 delete CG.removeFunctionFromModule(OldNode); 1171 else 1172 OldF->setLinkage(Function::ExternalLinkage); 1173 1174 // And updat ethe SCC we're iterating as well. 1175 SCC.ReplaceNode(OldNode, NewNode); 1176 } 1177 } 1178 // Remember that we changed something. 1179 Changed |= LocalChange; 1180 } while (LocalChange); 1181 1182 return Changed; 1183 } 1184 1185 bool ArgPromotion::doInitialization(CallGraph &CG) { 1186 return CallGraphSCCPass::doInitialization(CG); 1187 } 1188