ArgumentPromotion.cpp 41 KB

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