blob: dc61a883542051abd72db75e5853d3b511275549 [file] [log] [blame]
Chris Lattner254f8f82004-05-23 21:21:17 +00001//===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
Chris Lattner483ae012004-03-07 21:29:54 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
Chris Lattner483ae012004-03-07 21:29:54 +00008//===----------------------------------------------------------------------===//
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
Gordon Henriksen78c63ac2007-10-26 03:03:51 +000012// 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
Chris Lattner483ae012004-03-07 21:29:54 +000014// instead of the address of the value. This can cause recursive simplification
Chris Lattner254f8f82004-05-23 21:21:17 +000015// of code and lead to the elimination of allocas (especially in C++ template
16// code like the STL).
Chris Lattner483ae012004-03-07 21:29:54 +000017//
Chris Lattnerfe6f2e32004-03-08 01:04:36 +000018// 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
Gordon Henriksen78c63ac2007-10-26 03:03:51 +000020// it refuses to scalarize aggregates which would require passing in more than
21// three operands to the function, because passing thousands of operands for a
22// large array or structure is unprofitable!
Chris Lattnerfe6f2e32004-03-08 01:04:36 +000023//
Chris Lattner483ae012004-03-07 21:29:54 +000024// Note that this transformation could also be done for arguments that are only
Gordon Henriksen78c63ac2007-10-26 03:03:51 +000025// 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.
Chris Lattner483ae012004-03-07 21:29:54 +000028//
29//===----------------------------------------------------------------------===//
30
Chris Lattner254f8f82004-05-23 21:21:17 +000031#define DEBUG_TYPE "argpromotion"
Chris Lattner483ae012004-03-07 21:29:54 +000032#include "llvm/Transforms/IPO.h"
33#include "llvm/Constants.h"
34#include "llvm/DerivedTypes.h"
35#include "llvm/Module.h"
Chris Lattner37b6c4f2004-09-18 00:34:13 +000036#include "llvm/CallGraphSCCPass.h"
Chris Lattner483ae012004-03-07 21:29:54 +000037#include "llvm/Instructions.h"
Duncan Sandsad0ea2d2007-11-27 13:23:08 +000038#include "llvm/ParameterAttributes.h"
Chris Lattner483ae012004-03-07 21:29:54 +000039#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner37b6c4f2004-09-18 00:34:13 +000040#include "llvm/Analysis/CallGraph.h"
Chris Lattner483ae012004-03-07 21:29:54 +000041#include "llvm/Target/TargetData.h"
42#include "llvm/Support/CallSite.h"
43#include "llvm/Support/CFG.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000044#include "llvm/Support/Debug.h"
45#include "llvm/ADT/DepthFirstIterator.h"
46#include "llvm/ADT/Statistic.h"
47#include "llvm/ADT/StringExtras.h"
Reid Spencer557ab152007-02-05 23:32:05 +000048#include "llvm/Support/Compiler.h"
Chris Lattner483ae012004-03-07 21:29:54 +000049#include <set>
50using namespace llvm;
51
Chris Lattner1631bcb2006-12-19 22:09:18 +000052STATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted");
53STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
54STATISTIC(NumArgumentsDead , "Number of dead pointer args eliminated");
Chris Lattner483ae012004-03-07 21:29:54 +000055
Chris Lattner1631bcb2006-12-19 22:09:18 +000056namespace {
Chris Lattner483ae012004-03-07 21:29:54 +000057 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
58 ///
Reid Spencer557ab152007-02-05 23:32:05 +000059 struct VISIBILITY_HIDDEN ArgPromotion : public CallGraphSCCPass {
Chris Lattner483ae012004-03-07 21:29:54 +000060 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
61 AU.addRequired<AliasAnalysis>();
62 AU.addRequired<TargetData>();
Chris Lattner37b6c4f2004-09-18 00:34:13 +000063 CallGraphSCCPass::getAnalysisUsage(AU);
Chris Lattner483ae012004-03-07 21:29:54 +000064 }
65
Chris Lattner37b6c4f2004-09-18 00:34:13 +000066 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
Nick Lewyckye7da2d62007-05-06 13:37:16 +000067 static char ID; // Pass identification, replacement for typeid
Devang Patel09f162c2007-05-01 21:15:47 +000068 ArgPromotion() : CallGraphSCCPass((intptr_t)&ID) {}
69
Chris Lattner483ae012004-03-07 21:29:54 +000070 private:
Chris Lattner37b6c4f2004-09-18 00:34:13 +000071 bool PromoteArguments(CallGraphNode *CGN);
Chris Lattner4062a622008-01-11 19:20:39 +000072 bool isSafeToPromoteArgument(Argument *Arg, bool isByVal) const;
Chris Lattnera8ba28f2008-01-11 18:43:58 +000073 Function *DoPromotion(Function *F,
Chris Lattner4062a622008-01-11 19:20:39 +000074 SmallPtrSet<Argument*, 8> &ArgsToPromote);
Chris Lattner483ae012004-03-07 21:29:54 +000075 };
76
Devang Patel8c78a0b2007-05-03 01:11:54 +000077 char ArgPromotion::ID = 0;
Chris Lattnerc2d3d312006-08-27 22:42:52 +000078 RegisterPass<ArgPromotion> X("argpromotion",
79 "Promote 'by reference' arguments to scalars");
Chris Lattner483ae012004-03-07 21:29:54 +000080}
81
Devang Patel13058a52007-01-26 00:47:38 +000082Pass *llvm::createArgumentPromotionPass() {
Chris Lattner483ae012004-03-07 21:29:54 +000083 return new ArgPromotion();
84}
85
Chris Lattner37b6c4f2004-09-18 00:34:13 +000086bool ArgPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
87 bool Changed = false, LocalChange;
Chris Lattner483ae012004-03-07 21:29:54 +000088
Chris Lattner9864df92004-09-19 01:05:16 +000089 do { // Iterate until we stop promoting from this SCC.
Chris Lattner37b6c4f2004-09-18 00:34:13 +000090 LocalChange = false;
91 // Attempt to promote arguments from all functions in this SCC.
92 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
93 LocalChange |= PromoteArguments(SCC[i]);
94 Changed |= LocalChange; // Remember that we changed something.
95 } while (LocalChange);
Misha Brukmanb1c93172005-04-21 23:48:37 +000096
Chris Lattner483ae012004-03-07 21:29:54 +000097 return Changed;
98}
99
Chris Lattner254f8f82004-05-23 21:21:17 +0000100/// PromoteArguments - This method checks the specified function to see if there
101/// are any promotable arguments and if it is safe to promote the function (for
102/// example, all callers are direct). If safe to promote some arguments, it
103/// calls the DoPromotion method.
104///
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000105bool ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
106 Function *F = CGN->getFunction();
107
108 // Make sure that it is local to this module.
109 if (!F || !F->hasInternalLinkage()) return false;
Chris Lattner483ae012004-03-07 21:29:54 +0000110
111 // First check: see if there are any pointer arguments! If not, quick exit.
Chris Lattner4062a622008-01-11 19:20:39 +0000112 SmallVector<std::pair<Argument*, unsigned>, 16> PointerArgs;
113 unsigned ArgNo = 0;
114 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
115 I != E; ++I, ++ArgNo)
Chris Lattner483ae012004-03-07 21:29:54 +0000116 if (isa<PointerType>(I->getType()))
Chris Lattner4062a622008-01-11 19:20:39 +0000117 PointerArgs.push_back(std::pair<Argument*, unsigned>(I, ArgNo));
Chris Lattner483ae012004-03-07 21:29:54 +0000118 if (PointerArgs.empty()) return false;
119
120 // Second check: make sure that all callers are direct callers. We can't
121 // transform functions that have indirect callers.
122 for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
Chris Lattner64b8d692004-03-07 22:43:27 +0000123 UI != E; ++UI) {
124 CallSite CS = CallSite::get(*UI);
Chris Lattner254f8f82004-05-23 21:21:17 +0000125 if (!CS.getInstruction()) // "Taking the address" of the function
126 return false;
127
128 // Ensure that this call site is CALLING the function, not passing it as
129 // an argument.
Chris Lattnere736e552008-01-11 18:55:10 +0000130 if (UI.getOperandNo() != 0)
131 return false;
Chris Lattner64b8d692004-03-07 22:43:27 +0000132 }
Chris Lattner483ae012004-03-07 21:29:54 +0000133
Chris Lattner4062a622008-01-11 19:20:39 +0000134 // Check to see which arguments are promotable. If an argument is promotable,
135 // add it to ArgsToPromote.
136 SmallPtrSet<Argument*, 8> ArgsToPromote;
137 for (unsigned i = 0; i != PointerArgs.size(); ++i) {
138 bool isByVal = F->paramHasAttr(PointerArgs[i].second, ParamAttr::ByVal);
139 if (isSafeToPromoteArgument(PointerArgs[i].first, isByVal))
140 ArgsToPromote.insert(PointerArgs[i].first);
141 }
142
Chris Lattner483ae012004-03-07 21:29:54 +0000143 // No promotable pointer arguments.
Chris Lattner4062a622008-01-11 19:20:39 +0000144 if (ArgsToPromote.empty()) return false;
Chris Lattner483ae012004-03-07 21:29:54 +0000145
Chris Lattner4062a622008-01-11 19:20:39 +0000146 Function *NewF = DoPromotion(F, ArgsToPromote);
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000147
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000148 // Update the call graph to know that the function has been transformed.
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000149 getAnalysis<CallGraph>().changeFunction(F, NewF);
Chris Lattner483ae012004-03-07 21:29:54 +0000150 return true;
151}
152
Chris Lattner244031d2004-11-13 23:31:34 +0000153/// IsAlwaysValidPointer - Return true if the specified pointer is always legal
154/// to load.
155static bool IsAlwaysValidPointer(Value *V) {
156 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
157 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V))
158 return IsAlwaysValidPointer(GEP->getOperand(0));
159 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
160 if (CE->getOpcode() == Instruction::GetElementPtr)
161 return IsAlwaysValidPointer(CE->getOperand(0));
162
163 return false;
164}
165
166/// AllCalleesPassInValidPointerForArgument - Return true if we can prove that
167/// all callees pass in a valid pointer for the specified function argument.
168static bool AllCalleesPassInValidPointerForArgument(Argument *Arg) {
169 Function *Callee = Arg->getParent();
170
Chris Lattnera06a8fd2007-02-13 02:10:56 +0000171 unsigned ArgNo = std::distance(Callee->arg_begin(),
172 Function::arg_iterator(Arg));
Chris Lattner244031d2004-11-13 23:31:34 +0000173
174 // Look at all call sites of the function. At this pointer we know we only
175 // have direct callees.
176 for (Value::use_iterator UI = Callee->use_begin(), E = Callee->use_end();
177 UI != E; ++UI) {
178 CallSite CS = CallSite::get(*UI);
179 assert(CS.getInstruction() && "Should only have direct calls!");
180
181 if (!IsAlwaysValidPointer(CS.getArgument(ArgNo)))
182 return false;
183 }
184 return true;
185}
186
Chris Lattner254f8f82004-05-23 21:21:17 +0000187
188/// isSafeToPromoteArgument - As you might guess from the name of this method,
189/// it checks to see if it is both safe and useful to promote the argument.
190/// This method limits promotion of aggregates to only promote up to three
191/// elements of the aggregate in order to avoid exploding the number of
192/// arguments passed in.
Chris Lattner4062a622008-01-11 19:20:39 +0000193bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg, bool isByVal) const {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000194 // We can only promote this argument if all of the uses are loads, or are GEP
195 // instructions (with constant indices) that are subsequently loaded.
Chris Lattner4a702612008-01-11 19:34:32 +0000196
197 // We can also only promote the load if we can guarantee that it will happen.
198 // Promoting a load causes the load to be unconditionally executed in the
199 // caller, so we can't turn a conditional load into an unconditional load in
200 // general.
201 bool SafeToUnconditionallyLoad = false;
202 if (isByVal) // ByVal arguments are always safe to load from.
203 SafeToUnconditionallyLoad = true;
204
Chris Lattner244031d2004-11-13 23:31:34 +0000205 BasicBlock *EntryBlock = Arg->getParent()->begin();
Chris Lattnera8ba28f2008-01-11 18:43:58 +0000206 SmallVector<LoadInst*, 16> Loads;
207 std::vector<SmallVector<ConstantInt*, 8> > GEPIndices;
Chris Lattner483ae012004-03-07 21:29:54 +0000208 for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
209 UI != E; ++UI)
210 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
211 if (LI->isVolatile()) return false; // Don't hack volatile loads
212 Loads.push_back(LI);
Chris Lattner4a702612008-01-11 19:34:32 +0000213
214 // If this load occurs in the entry block, then the pointer is
215 // unconditionally loaded.
216 SafeToUnconditionallyLoad |= LI->getParent() == EntryBlock;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000217 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
218 if (GEP->use_empty()) {
219 // Dead GEP's cause trouble later. Just remove them if we run into
220 // them.
Chris Lattner254f8f82004-05-23 21:21:17 +0000221 getAnalysis<AliasAnalysis>().deleteValue(GEP);
Chris Lattner4062a622008-01-11 19:20:39 +0000222 GEP->eraseFromParent();
223 return isSafeToPromoteArgument(Arg, isByVal);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000224 }
225 // Ensure that all of the indices are constants.
Chris Lattnera8ba28f2008-01-11 18:43:58 +0000226 SmallVector<ConstantInt*, 8> Operands;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000227 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
Chris Lattner1c676f72004-06-21 00:07:58 +0000228 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000229 Operands.push_back(C);
230 else
231 return false; // Not a constant operand GEP!
232
233 // Ensure that the only users of the GEP are load instructions.
234 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
235 UI != E; ++UI)
236 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
237 if (LI->isVolatile()) return false; // Don't hack volatile loads
238 Loads.push_back(LI);
Chris Lattner4a702612008-01-11 19:34:32 +0000239
240 // If this load occurs in the entry block, then the pointer is
241 // unconditionally loaded.
242 SafeToUnconditionallyLoad |= LI->getParent() == EntryBlock;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000243 } else {
244 return false;
245 }
246
Chris Lattner254f8f82004-05-23 21:21:17 +0000247 // See if there is already a GEP with these indices. If not, check to
248 // make sure that we aren't promoting too many elements. If so, nothing
249 // to do.
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000250 if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
251 GEPIndices.end()) {
252 if (GEPIndices.size() == 3) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000253 DOUT << "argpromotion disable promoting argument '"
254 << Arg->getName() << "' because it would require adding more "
255 << "than 3 arguments to the function.\n";
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000256 // We limit aggregate promotion to only promoting up to three elements
257 // of the aggregate.
258 return false;
259 }
260 GEPIndices.push_back(Operands);
261 }
262 } else {
263 return false; // Not a load or a GEP.
264 }
Chris Lattner483ae012004-03-07 21:29:54 +0000265
Chris Lattner254f8f82004-05-23 21:21:17 +0000266 if (Loads.empty()) return true; // No users, this is a dead argument.
Chris Lattner483ae012004-03-07 21:29:54 +0000267
Chris Lattner244031d2004-11-13 23:31:34 +0000268 // If we decide that we want to promote this argument, the value is going to
269 // be unconditionally loaded in all callees. This is only safe to do if the
270 // pointer was going to be unconditionally loaded anyway (i.e. there is a load
271 // of the pointer in the entry block of the function) or if we can prove that
272 // all pointers passed in are always to legal locations (for example, no null
273 // pointers are passed in, no pointers to free'd memory, etc).
Chris Lattner4a702612008-01-11 19:34:32 +0000274 if (!SafeToUnconditionallyLoad &&
275 !AllCalleesPassInValidPointerForArgument(Arg))
Chris Lattner244031d2004-11-13 23:31:34 +0000276 return false; // Cannot prove that this is safe!!
277
278 // Okay, now we know that the argument is only used by load instructions and
279 // it is safe to unconditionally load the pointer. Use alias analysis to
280 // check to see if the pointer is guaranteed to not be modified from entry of
281 // the function to each of the load instructions.
Chris Lattner483ae012004-03-07 21:29:54 +0000282
283 // Because there could be several/many load instructions, remember which
284 // blocks we know to be transparent to the load.
Chris Lattnerb66fbdd2008-01-11 19:36:30 +0000285 SmallPtrSet<BasicBlock*, 16> TranspBlocks;
Owen Andersonedadd3f2006-09-15 05:22:51 +0000286
287 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000288 TargetData &TD = getAnalysis<TargetData>();
Chris Lattner483ae012004-03-07 21:29:54 +0000289
290 for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
291 // Check to see if the load is invalidated from the start of the block to
292 // the load itself.
293 LoadInst *Load = Loads[i];
294 BasicBlock *BB = Load->getParent();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000295
296 const PointerType *LoadTy =
297 cast<PointerType>(Load->getOperand(0)->getType());
Duncan Sands44b87212007-11-01 20:53:16 +0000298 unsigned LoadSize = (unsigned)TD.getTypeStoreSize(LoadTy->getElementType());
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000299
Chris Lattner483ae012004-03-07 21:29:54 +0000300 if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
301 return false; // Pointer is invalidated!
302
303 // Now check every path from the entry block to the load for transparency.
304 // To do this, we perform a depth first search on the inverse CFG from the
305 // loading block.
306 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
Chris Lattnerb66fbdd2008-01-11 19:36:30 +0000307 for (idf_ext_iterator<BasicBlock*, SmallPtrSet<BasicBlock*, 16> >
308 I = idf_ext_begin(*PI, TranspBlocks),
Chris Lattner483ae012004-03-07 21:29:54 +0000309 E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
310 if (AA.canBasicBlockModify(**I, Arg, LoadSize))
311 return false;
312 }
313
314 // If the path from the entry of the function to each load is free of
315 // instructions that potentially invalidate the load, we can make the
316 // transformation!
317 return true;
318}
319
Chris Lattner1c676f72004-06-21 00:07:58 +0000320namespace {
321 /// GEPIdxComparator - Provide a strong ordering for GEP indices. All Value*
322 /// elements are instances of ConstantInt.
323 ///
324 struct GEPIdxComparator {
325 bool operator()(const std::vector<Value*> &LHS,
326 const std::vector<Value*> &RHS) const {
327 unsigned idx = 0;
328 for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
329 if (LHS[idx] != RHS[idx]) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000330 return cast<ConstantInt>(LHS[idx])->getZExtValue() <
331 cast<ConstantInt>(RHS[idx])->getZExtValue();
Chris Lattner1c676f72004-06-21 00:07:58 +0000332 }
333 }
334
335 // Return less than if we ran out of stuff in LHS and we didn't run out of
336 // stuff in RHS.
337 return idx == LHS.size() && idx != RHS.size();
338 }
339 };
340}
341
342
Chris Lattner254f8f82004-05-23 21:21:17 +0000343/// DoPromotion - This method actually performs the promotion of the specified
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000344/// arguments, and returns the new function. At this point, we know that it's
345/// safe to do so.
346Function *ArgPromotion::DoPromotion(Function *F,
Chris Lattner4062a622008-01-11 19:20:39 +0000347 SmallPtrSet<Argument*, 8> &ArgsToPromote) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000348
Chris Lattner483ae012004-03-07 21:29:54 +0000349 // Start by computing a new prototype for the function, which is the same as
350 // the old function, but has modified arguments.
351 const FunctionType *FTy = F->getFunctionType();
352 std::vector<const Type*> Params;
353
Chris Lattner1c676f72004-06-21 00:07:58 +0000354 typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
355
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000356 // ScalarizedElements - If we are promoting a pointer that has elements
357 // accessed out of it, keep track of which elements are accessed so that we
358 // can add one argument for each.
359 //
360 // Arguments that are directly loaded will have a zero element value here, to
361 // handle cases where there are both a direct load and GEP accesses.
362 //
Chris Lattner1c676f72004-06-21 00:07:58 +0000363 std::map<Argument*, ScalarizeTable> ScalarizedElements;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000364
Chris Lattner254f8f82004-05-23 21:21:17 +0000365 // OriginalLoads - Keep track of a representative load instruction from the
366 // original function so that we can tell the alias analysis implementation
367 // what the new GEP/Load instructions we are inserting look like.
368 std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
369
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000370 // ParamAttrs - Keep track of the parameter attributes for the arguments
371 // that we are *not* promoting. For the ones that we do promote, the parameter
372 // attributes are lost
373 ParamAttrsVector ParamAttrsVec;
374 const ParamAttrsList *PAL = F->getParamAttrs();
375
376 unsigned index = 1;
377 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
378 ++I, ++index)
Chris Lattner483ae012004-03-07 21:29:54 +0000379 if (!ArgsToPromote.count(I)) {
380 Params.push_back(I->getType());
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000381 if (PAL) {
382 unsigned attrs = PAL->getParamAttrs(index);
383 if (attrs)
384 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(),
385 attrs));
386 }
Chris Lattner254f8f82004-05-23 21:21:17 +0000387 } else if (I->use_empty()) {
388 ++NumArgumentsDead;
389 } else {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000390 // Okay, this is being promoted. Check to see if there are any GEP uses
391 // of the argument.
Chris Lattner1c676f72004-06-21 00:07:58 +0000392 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000393 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
394 ++UI) {
395 Instruction *User = cast<Instruction>(*UI);
Owen Andersonedadd3f2006-09-15 05:22:51 +0000396 assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
397 std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
398 ArgIndices.insert(Indices);
399 LoadInst *OrigLoad;
400 if (LoadInst *L = dyn_cast<LoadInst>(User))
401 OrigLoad = L;
402 else
403 OrigLoad = cast<LoadInst>(User->use_back());
404 OriginalLoads[Indices] = OrigLoad;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000405 }
406
407 // Add a parameter to the function for each element passed in.
Chris Lattner1c676f72004-06-21 00:07:58 +0000408 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000409 E = ArgIndices.end(); SI != E; ++SI)
Chris Lattnera7315132007-02-12 22:56:41 +0000410 Params.push_back(GetElementPtrInst::getIndexedType(I->getType(),
David Greenec656cbb2007-09-04 15:46:09 +0000411 SI->begin(),
412 SI->end()));
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000413
414 if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
415 ++NumArgumentsPromoted;
416 else
417 ++NumAggregatesPromoted;
Chris Lattner483ae012004-03-07 21:29:54 +0000418 }
419
420 const Type *RetTy = FTy->getReturnType();
421
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000422 // Recompute the parameter attributes list based on the new arguments for
423 // the function.
424 if (ParamAttrsVec.empty())
425 PAL = 0;
426 else
427 PAL = ParamAttrsList::get(ParamAttrsVec);
428
Chris Lattner483ae012004-03-07 21:29:54 +0000429 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
430 // have zero fixed arguments.
431 bool ExtraArgHack = false;
432 if (Params.empty() && FTy->isVarArg()) {
433 ExtraArgHack = true;
Reid Spencerc635f472006-12-31 05:48:39 +0000434 Params.push_back(Type::Int32Ty);
Chris Lattner483ae012004-03-07 21:29:54 +0000435 }
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000436
437 // Construct the new function type using the new arguments.
Chris Lattner483ae012004-03-07 21:29:54 +0000438 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000439
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000440 // Create the new function body and insert it into the module...
Chris Lattner483ae012004-03-07 21:29:54 +0000441 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
Chris Lattnerd0525a22005-05-09 01:05:50 +0000442 NF->setCallingConv(F->getCallingConv());
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000443 NF->setParamAttrs(PAL);
Gordon Henriksen520e64c2007-12-25 22:16:06 +0000444 if (F->hasCollector())
445 NF->setCollector(F->getCollector());
Chris Lattner483ae012004-03-07 21:29:54 +0000446 F->getParent()->getFunctionList().insert(F, NF);
Chris Lattner254f8f82004-05-23 21:21:17 +0000447
448 // Get the alias analysis information that we need to update to reflect our
449 // changes.
450 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
451
Chris Lattner483ae012004-03-07 21:29:54 +0000452 // Loop over all of the callers of the function, transforming the call sites
453 // to pass in the loaded pointers.
454 //
455 std::vector<Value*> Args;
456 while (!F->use_empty()) {
457 CallSite CS = CallSite::get(F->use_back());
458 Instruction *Call = CS.getInstruction();
459
Chris Lattner254f8f82004-05-23 21:21:17 +0000460 // Loop over the operands, inserting GEP and loads in the caller as
461 // appropriate.
Chris Lattner483ae012004-03-07 21:29:54 +0000462 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattnerd0525a22005-05-09 01:05:50 +0000463 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
464 I != E; ++I, ++AI)
Chris Lattner483ae012004-03-07 21:29:54 +0000465 if (!ArgsToPromote.count(I))
466 Args.push_back(*AI); // Unmodified argument
467 else if (!I->use_empty()) {
Chris Lattner254f8f82004-05-23 21:21:17 +0000468 // Non-dead argument: insert GEPs and loads as appropriate.
Chris Lattner1c676f72004-06-21 00:07:58 +0000469 ScalarizeTable &ArgIndices = ScalarizedElements[I];
470 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000471 E = ArgIndices.end(); SI != E; ++SI) {
472 Value *V = *AI;
Chris Lattner254f8f82004-05-23 21:21:17 +0000473 LoadInst *OrigLoad = OriginalLoads[*SI];
474 if (!SI->empty()) {
David Greenec656cbb2007-09-04 15:46:09 +0000475 V = new GetElementPtrInst(V, SI->begin(), SI->end(),
Chris Lattnera7315132007-02-12 22:56:41 +0000476 V->getName()+".idx", Call);
Chris Lattner254f8f82004-05-23 21:21:17 +0000477 AA.copyValue(OrigLoad->getOperand(0), V);
478 }
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000479 Args.push_back(new LoadInst(V, V->getName()+".val", Call));
Chris Lattner254f8f82004-05-23 21:21:17 +0000480 AA.copyValue(OrigLoad, Args.back());
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000481 }
Chris Lattner483ae012004-03-07 21:29:54 +0000482 }
483
484 if (ExtraArgHack)
Reid Spencerc635f472006-12-31 05:48:39 +0000485 Args.push_back(Constant::getNullValue(Type::Int32Ty));
Chris Lattner483ae012004-03-07 21:29:54 +0000486
487 // Push any varargs arguments on the list
488 for (; AI != CS.arg_end(); ++AI)
489 Args.push_back(*AI);
490
491 Instruction *New;
492 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
493 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
David Greene703623d2007-08-27 19:04:21 +0000494 Args.begin(), Args.end(), "", Call);
Chris Lattnerd0525a22005-05-09 01:05:50 +0000495 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000496 cast<InvokeInst>(New)->setParamAttrs(PAL);
Chris Lattner483ae012004-03-07 21:29:54 +0000497 } else {
David Greene17a5dfe2007-08-01 03:43:44 +0000498 New = new CallInst(NF, Args.begin(), Args.end(), "", Call);
Chris Lattnerd0525a22005-05-09 01:05:50 +0000499 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Duncan Sandsad0ea2d2007-11-27 13:23:08 +0000500 cast<CallInst>(New)->setParamAttrs(PAL);
Chris Lattner324d2ee2005-05-06 06:46:58 +0000501 if (cast<CallInst>(Call)->isTailCall())
502 cast<CallInst>(New)->setTailCall();
Chris Lattner483ae012004-03-07 21:29:54 +0000503 }
504 Args.clear();
505
Chris Lattner254f8f82004-05-23 21:21:17 +0000506 // Update the alias analysis implementation to know that we are replacing
507 // the old call with a new one.
508 AA.replaceWithNewValue(Call, New);
509
Chris Lattner483ae012004-03-07 21:29:54 +0000510 if (!Call->use_empty()) {
511 Call->replaceAllUsesWith(New);
Chris Lattner8d4c36b2007-02-11 01:08:35 +0000512 New->takeName(Call);
Chris Lattner483ae012004-03-07 21:29:54 +0000513 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000514
Chris Lattner483ae012004-03-07 21:29:54 +0000515 // Finally, remove the old call from the program, reducing the use-count of
516 // F.
Chris Lattner4062a622008-01-11 19:20:39 +0000517 Call->eraseFromParent();
Chris Lattner483ae012004-03-07 21:29:54 +0000518 }
519
520 // Since we have now created the new function, splice the body of the old
521 // function right into the new function, leaving the old rotting hulk of the
522 // function empty.
523 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
524
525 // Loop over the argument list, transfering uses of the old arguments over to
526 // the new arguments, also transfering over the names as well.
527 //
Chris Lattnera06a8fd2007-02-13 02:10:56 +0000528 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
529 I2 = NF->arg_begin(); I != E; ++I)
Chris Lattner483ae012004-03-07 21:29:54 +0000530 if (!ArgsToPromote.count(I)) {
531 // If this is an unmodified argument, move the name and users over to the
532 // new version.
533 I->replaceAllUsesWith(I2);
Chris Lattner8d4c36b2007-02-11 01:08:35 +0000534 I2->takeName(I);
Chris Lattner254f8f82004-05-23 21:21:17 +0000535 AA.replaceWithNewValue(I, I2);
Chris Lattner483ae012004-03-07 21:29:54 +0000536 ++I2;
Chris Lattner254f8f82004-05-23 21:21:17 +0000537 } else if (I->use_empty()) {
538 AA.deleteValue(I);
539 } else {
Chris Lattner483ae012004-03-07 21:29:54 +0000540 // Otherwise, if we promoted this argument, then all users are load
541 // instructions, and all loads should be using the new argument that we
542 // added.
Chris Lattner1c676f72004-06-21 00:07:58 +0000543 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000544
Chris Lattner483ae012004-03-07 21:29:54 +0000545 while (!I->use_empty()) {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000546 if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
547 assert(ArgIndices.begin()->empty() &&
548 "Load element should sort to front!");
549 I2->setName(I->getName()+".val");
550 LI->replaceAllUsesWith(I2);
Chris Lattner254f8f82004-05-23 21:21:17 +0000551 AA.replaceWithNewValue(LI, I2);
Chris Lattner4062a622008-01-11 19:20:39 +0000552 LI->eraseFromParent();
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000553 DOUT << "*** Promoted load of argument '" << I->getName()
554 << "' in function '" << F->getName() << "'\n";
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000555 } else {
556 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
557 std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
558
Chris Lattner531f9e92005-03-15 04:54:21 +0000559 Function::arg_iterator TheArg = I2;
Chris Lattner1c676f72004-06-21 00:07:58 +0000560 for (ScalarizeTable::iterator It = ArgIndices.begin();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000561 *It != Operands; ++It, ++TheArg) {
562 assert(It != ArgIndices.end() && "GEP not handled??");
563 }
564
565 std::string NewName = I->getName();
566 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
567 if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
Chris Lattnerb0f158c2007-08-23 05:15:32 +0000568 NewName += "." + CI->getValue().toStringUnsigned(10);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000569 else
570 NewName += ".x";
571 TheArg->setName(NewName+".val");
572
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000573 DOUT << "*** Promoted agg argument '" << TheArg->getName()
574 << "' of function '" << F->getName() << "'\n";
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000575
576 // All of the uses must be load instructions. Replace them all with
577 // the argument specified by ArgNo.
578 while (!GEP->use_empty()) {
579 LoadInst *L = cast<LoadInst>(GEP->use_back());
580 L->replaceAllUsesWith(TheArg);
Chris Lattner254f8f82004-05-23 21:21:17 +0000581 AA.replaceWithNewValue(L, TheArg);
Chris Lattner4062a622008-01-11 19:20:39 +0000582 L->eraseFromParent();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000583 }
Chris Lattner254f8f82004-05-23 21:21:17 +0000584 AA.deleteValue(GEP);
Chris Lattner4062a622008-01-11 19:20:39 +0000585 GEP->eraseFromParent();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000586 }
Chris Lattner483ae012004-03-07 21:29:54 +0000587 }
Chris Lattnercc544e52004-03-07 22:52:53 +0000588
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000589 // Increment I2 past all of the arguments added for this promoted pointer.
590 for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i)
591 ++I2;
Chris Lattner483ae012004-03-07 21:29:54 +0000592 }
593
Chris Lattner254f8f82004-05-23 21:21:17 +0000594 // Notify the alias analysis implementation that we inserted a new argument.
595 if (ExtraArgHack)
Reid Spencerc635f472006-12-31 05:48:39 +0000596 AA.copyValue(Constant::getNullValue(Type::Int32Ty), NF->arg_begin());
Chris Lattner254f8f82004-05-23 21:21:17 +0000597
598
599 // Tell the alias analysis that the old function is about to disappear.
600 AA.replaceWithNewValue(F, NF);
601
Chris Lattner483ae012004-03-07 21:29:54 +0000602 // Now that the old function is dead, delete it.
Chris Lattner4062a622008-01-11 19:20:39 +0000603 F->eraseFromParent();
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000604 return NF;
Chris Lattner483ae012004-03-07 21:29:54 +0000605}