blob: 9acd516123dad9d0d219b8029a16b8f34de30acb [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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
Gordon Henriksen9adadb42007-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
Dan Gohmanf17a25c2007-07-18 16:29:46 +000014// 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
Gordon Henriksen9adadb42007-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!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000023//
24// Note that this transformation could also be done for arguments that are only
Gordon Henriksen9adadb42007-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.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000028//
29//===----------------------------------------------------------------------===//
30
31#define DEBUG_TYPE "argpromotion"
32#include "llvm/Transforms/IPO.h"
33#include "llvm/Constants.h"
34#include "llvm/DerivedTypes.h"
35#include "llvm/Module.h"
36#include "llvm/CallGraphSCCPass.h"
37#include "llvm/Instructions.h"
Duncan Sandsf5588dc2007-11-27 13:23:08 +000038#include "llvm/ParameterAttributes.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039#include "llvm/Analysis/AliasAnalysis.h"
40#include "llvm/Analysis/CallGraph.h"
41#include "llvm/Target/TargetData.h"
42#include "llvm/Support/CallSite.h"
43#include "llvm/Support/CFG.h"
44#include "llvm/Support/Debug.h"
45#include "llvm/ADT/DepthFirstIterator.h"
46#include "llvm/ADT/Statistic.h"
47#include "llvm/ADT/StringExtras.h"
48#include "llvm/Support/Compiler.h"
49#include <set>
50using namespace llvm;
51
52STATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted");
53STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
Chris Lattnera1dde2b2008-01-11 22:31:41 +000054STATISTIC(NumByValArgsPromoted , "Number of byval arguments promoted");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055STATISTIC(NumArgumentsDead , "Number of dead pointer args eliminated");
56
57namespace {
58 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
59 ///
60 struct VISIBILITY_HIDDEN ArgPromotion : public CallGraphSCCPass {
61 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
62 AU.addRequired<AliasAnalysis>();
63 AU.addRequired<TargetData>();
64 CallGraphSCCPass::getAnalysisUsage(AU);
65 }
66
67 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
68 static char ID; // Pass identification, replacement for typeid
69 ArgPromotion() : CallGraphSCCPass((intptr_t)&ID) {}
70
71 private:
72 bool PromoteArguments(CallGraphNode *CGN);
Chris Lattner09ddfda2008-01-11 19:20:39 +000073 bool isSafeToPromoteArgument(Argument *Arg, bool isByVal) const;
Chris Lattner7ec41402008-01-11 18:43:58 +000074 Function *DoPromotion(Function *F,
Chris Lattnera1dde2b2008-01-11 22:31:41 +000075 SmallPtrSet<Argument*, 8> &ArgsToPromote,
76 SmallPtrSet<Argument*, 8> &ByValArgsToTransform);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000077 };
78
79 char ArgPromotion::ID = 0;
80 RegisterPass<ArgPromotion> X("argpromotion",
81 "Promote 'by reference' arguments to scalars");
82}
83
84Pass *llvm::createArgumentPromotionPass() {
85 return new ArgPromotion();
86}
87
88bool ArgPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
89 bool Changed = false, LocalChange;
90
91 do { // Iterate until we stop promoting from this SCC.
92 LocalChange = false;
93 // Attempt to promote arguments from all functions in this SCC.
94 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
95 LocalChange |= PromoteArguments(SCC[i]);
96 Changed |= LocalChange; // Remember that we changed something.
97 } while (LocalChange);
98
99 return Changed;
100}
101
102/// PromoteArguments - This method checks the specified function to see if there
103/// are any promotable arguments and if it is safe to promote the function (for
104/// example, all callers are direct). If safe to promote some arguments, it
105/// calls the DoPromotion method.
106///
107bool ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
108 Function *F = CGN->getFunction();
109
110 // Make sure that it is local to this module.
111 if (!F || !F->hasInternalLinkage()) return false;
112
113 // First check: see if there are any pointer arguments! If not, quick exit.
Chris Lattner09ddfda2008-01-11 19:20:39 +0000114 SmallVector<std::pair<Argument*, unsigned>, 16> PointerArgs;
115 unsigned ArgNo = 0;
116 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
117 I != E; ++I, ++ArgNo)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000118 if (isa<PointerType>(I->getType()))
Chris Lattner09ddfda2008-01-11 19:20:39 +0000119 PointerArgs.push_back(std::pair<Argument*, unsigned>(I, ArgNo));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000120 if (PointerArgs.empty()) return false;
121
122 // Second check: make sure that all callers are direct callers. We can't
123 // transform functions that have indirect callers.
124 for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
125 UI != E; ++UI) {
126 CallSite CS = CallSite::get(*UI);
127 if (!CS.getInstruction()) // "Taking the address" of the function
128 return false;
129
130 // Ensure that this call site is CALLING the function, not passing it as
131 // an argument.
Chris Lattner16d8bdd2008-01-11 18:55:10 +0000132 if (UI.getOperandNo() != 0)
133 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000134 }
135
Chris Lattner09ddfda2008-01-11 19:20:39 +0000136 // Check to see which arguments are promotable. If an argument is promotable,
137 // add it to ArgsToPromote.
138 SmallPtrSet<Argument*, 8> ArgsToPromote;
Chris Lattnera1dde2b2008-01-11 22:31:41 +0000139 SmallPtrSet<Argument*, 8> ByValArgsToTransform;
Chris Lattner09ddfda2008-01-11 19:20:39 +0000140 for (unsigned i = 0; i != PointerArgs.size(); ++i) {
Chris Lattnera1dde2b2008-01-11 22:31:41 +0000141 bool isByVal = F->paramHasAttr(PointerArgs[i].second+1, ParamAttr::ByVal);
142
143 // If this is a byval argument, and if the aggregate type is small, just
144 // pass the elements, which is always safe.
145 Argument *PtrArg = PointerArgs[i].first;
146 if (isByVal) {
147 const Type *AgTy = cast<PointerType>(PtrArg->getType())->getElementType();
148 if (const StructType *STy = dyn_cast<StructType>(AgTy))
149 if (STy->getNumElements() <= 3) {
150 // If all the elements are first class types, we can promote it.
151 bool AllSimple = true;
152 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
153 if (!STy->getElementType(i)->isFirstClassType()) {
154 AllSimple = false;
155 break;
156 }
157
158 // Safe to transform, don't even bother trying to "promote" it.
159 // Passing the elements as a scalar will allow scalarrepl to hack on
160 // the new alloca we introduce.
161 if (AllSimple) {
162 ByValArgsToTransform.insert(PtrArg);
163 continue;
164 }
165 }
166 }
167
168 // Otherwise, see if we can promote the pointer to its value.
169 if (isSafeToPromoteArgument(PtrArg, isByVal))
170 ArgsToPromote.insert(PtrArg);
Chris Lattner09ddfda2008-01-11 19:20:39 +0000171 }
172
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000173 // No promotable pointer arguments.
Chris Lattnera1dde2b2008-01-11 22:31:41 +0000174 if (ArgsToPromote.empty() && ByValArgsToTransform.empty()) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000175
Chris Lattnera1dde2b2008-01-11 22:31:41 +0000176 Function *NewF = DoPromotion(F, ArgsToPromote, ByValArgsToTransform);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000178 // Update the call graph to know that the function has been transformed.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 getAnalysis<CallGraph>().changeFunction(F, NewF);
180 return true;
181}
182
183/// IsAlwaysValidPointer - Return true if the specified pointer is always legal
184/// to load.
185static bool IsAlwaysValidPointer(Value *V) {
186 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
187 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V))
188 return IsAlwaysValidPointer(GEP->getOperand(0));
189 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
190 if (CE->getOpcode() == Instruction::GetElementPtr)
191 return IsAlwaysValidPointer(CE->getOperand(0));
192
193 return false;
194}
195
196/// AllCalleesPassInValidPointerForArgument - Return true if we can prove that
197/// all callees pass in a valid pointer for the specified function argument.
198static bool AllCalleesPassInValidPointerForArgument(Argument *Arg) {
199 Function *Callee = Arg->getParent();
200
201 unsigned ArgNo = std::distance(Callee->arg_begin(),
202 Function::arg_iterator(Arg));
203
204 // Look at all call sites of the function. At this pointer we know we only
205 // have direct callees.
206 for (Value::use_iterator UI = Callee->use_begin(), E = Callee->use_end();
207 UI != E; ++UI) {
208 CallSite CS = CallSite::get(*UI);
209 assert(CS.getInstruction() && "Should only have direct calls!");
210
211 if (!IsAlwaysValidPointer(CS.getArgument(ArgNo)))
212 return false;
213 }
214 return true;
215}
216
217
218/// isSafeToPromoteArgument - As you might guess from the name of this method,
219/// it checks to see if it is both safe and useful to promote the argument.
220/// This method limits promotion of aggregates to only promote up to three
221/// elements of the aggregate in order to avoid exploding the number of
222/// arguments passed in.
Chris Lattner09ddfda2008-01-11 19:20:39 +0000223bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg, bool isByVal) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224 // We can only promote this argument if all of the uses are loads, or are GEP
225 // instructions (with constant indices) that are subsequently loaded.
Chris Lattner41e0d202008-01-11 19:34:32 +0000226
227 // We can also only promote the load if we can guarantee that it will happen.
228 // Promoting a load causes the load to be unconditionally executed in the
229 // caller, so we can't turn a conditional load into an unconditional load in
230 // general.
231 bool SafeToUnconditionallyLoad = false;
232 if (isByVal) // ByVal arguments are always safe to load from.
233 SafeToUnconditionallyLoad = true;
234
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000235 BasicBlock *EntryBlock = Arg->getParent()->begin();
Chris Lattner7ec41402008-01-11 18:43:58 +0000236 SmallVector<LoadInst*, 16> Loads;
237 std::vector<SmallVector<ConstantInt*, 8> > GEPIndices;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238 for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
239 UI != E; ++UI)
240 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
241 if (LI->isVolatile()) return false; // Don't hack volatile loads
242 Loads.push_back(LI);
Chris Lattner41e0d202008-01-11 19:34:32 +0000243
244 // If this load occurs in the entry block, then the pointer is
245 // unconditionally loaded.
246 SafeToUnconditionallyLoad |= LI->getParent() == EntryBlock;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
248 if (GEP->use_empty()) {
249 // Dead GEP's cause trouble later. Just remove them if we run into
250 // them.
251 getAnalysis<AliasAnalysis>().deleteValue(GEP);
Chris Lattner09ddfda2008-01-11 19:20:39 +0000252 GEP->eraseFromParent();
253 return isSafeToPromoteArgument(Arg, isByVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254 }
255 // Ensure that all of the indices are constants.
Chris Lattner7ec41402008-01-11 18:43:58 +0000256 SmallVector<ConstantInt*, 8> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
258 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
259 Operands.push_back(C);
260 else
261 return false; // Not a constant operand GEP!
262
263 // Ensure that the only users of the GEP are load instructions.
264 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
265 UI != E; ++UI)
266 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
267 if (LI->isVolatile()) return false; // Don't hack volatile loads
268 Loads.push_back(LI);
Chris Lattner41e0d202008-01-11 19:34:32 +0000269
270 // If this load occurs in the entry block, then the pointer is
271 // unconditionally loaded.
272 SafeToUnconditionallyLoad |= LI->getParent() == EntryBlock;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273 } else {
274 return false;
275 }
276
277 // See if there is already a GEP with these indices. If not, check to
278 // make sure that we aren't promoting too many elements. If so, nothing
279 // to do.
280 if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
281 GEPIndices.end()) {
282 if (GEPIndices.size() == 3) {
283 DOUT << "argpromotion disable promoting argument '"
284 << Arg->getName() << "' because it would require adding more "
285 << "than 3 arguments to the function.\n";
286 // We limit aggregate promotion to only promoting up to three elements
287 // of the aggregate.
288 return false;
289 }
290 GEPIndices.push_back(Operands);
291 }
292 } else {
293 return false; // Not a load or a GEP.
294 }
295
296 if (Loads.empty()) return true; // No users, this is a dead argument.
297
298 // If we decide that we want to promote this argument, the value is going to
299 // be unconditionally loaded in all callees. This is only safe to do if the
300 // pointer was going to be unconditionally loaded anyway (i.e. there is a load
301 // of the pointer in the entry block of the function) or if we can prove that
302 // all pointers passed in are always to legal locations (for example, no null
303 // pointers are passed in, no pointers to free'd memory, etc).
Chris Lattner41e0d202008-01-11 19:34:32 +0000304 if (!SafeToUnconditionallyLoad &&
305 !AllCalleesPassInValidPointerForArgument(Arg))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000306 return false; // Cannot prove that this is safe!!
307
308 // Okay, now we know that the argument is only used by load instructions and
309 // it is safe to unconditionally load the pointer. Use alias analysis to
310 // check to see if the pointer is guaranteed to not be modified from entry of
311 // the function to each of the load instructions.
312
313 // Because there could be several/many load instructions, remember which
314 // blocks we know to be transparent to the load.
Chris Lattnerba799be2008-01-11 19:36:30 +0000315 SmallPtrSet<BasicBlock*, 16> TranspBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316
317 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
318 TargetData &TD = getAnalysis<TargetData>();
319
320 for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
321 // Check to see if the load is invalidated from the start of the block to
322 // the load itself.
323 LoadInst *Load = Loads[i];
324 BasicBlock *BB = Load->getParent();
325
326 const PointerType *LoadTy =
327 cast<PointerType>(Load->getOperand(0)->getType());
Duncan Sandsf99fdc62007-11-01 20:53:16 +0000328 unsigned LoadSize = (unsigned)TD.getTypeStoreSize(LoadTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000329
330 if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
331 return false; // Pointer is invalidated!
332
333 // Now check every path from the entry block to the load for transparency.
334 // To do this, we perform a depth first search on the inverse CFG from the
335 // loading block.
336 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
Chris Lattnerba799be2008-01-11 19:36:30 +0000337 for (idf_ext_iterator<BasicBlock*, SmallPtrSet<BasicBlock*, 16> >
338 I = idf_ext_begin(*PI, TranspBlocks),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000339 E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
340 if (AA.canBasicBlockModify(**I, Arg, LoadSize))
341 return false;
342 }
343
344 // If the path from the entry of the function to each load is free of
345 // instructions that potentially invalidate the load, we can make the
346 // transformation!
347 return true;
348}
349
350namespace {
351 /// GEPIdxComparator - Provide a strong ordering for GEP indices. All Value*
352 /// elements are instances of ConstantInt.
353 ///
354 struct GEPIdxComparator {
355 bool operator()(const std::vector<Value*> &LHS,
356 const std::vector<Value*> &RHS) const {
357 unsigned idx = 0;
358 for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
359 if (LHS[idx] != RHS[idx]) {
360 return cast<ConstantInt>(LHS[idx])->getZExtValue() <
361 cast<ConstantInt>(RHS[idx])->getZExtValue();
362 }
363 }
364
365 // Return less than if we ran out of stuff in LHS and we didn't run out of
366 // stuff in RHS.
367 return idx == LHS.size() && idx != RHS.size();
368 }
369 };
370}
371
372
373/// DoPromotion - This method actually performs the promotion of the specified
374/// arguments, and returns the new function. At this point, we know that it's
375/// safe to do so.
376Function *ArgPromotion::DoPromotion(Function *F,
Chris Lattnera1dde2b2008-01-11 22:31:41 +0000377 SmallPtrSet<Argument*, 8> &ArgsToPromote,
378 SmallPtrSet<Argument*, 8> &ByValArgsToTransform) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000379
380 // Start by computing a new prototype for the function, which is the same as
381 // the old function, but has modified arguments.
382 const FunctionType *FTy = F->getFunctionType();
383 std::vector<const Type*> Params;
384
385 typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
386
387 // ScalarizedElements - If we are promoting a pointer that has elements
388 // accessed out of it, keep track of which elements are accessed so that we
389 // can add one argument for each.
390 //
391 // Arguments that are directly loaded will have a zero element value here, to
392 // handle cases where there are both a direct load and GEP accesses.
393 //
394 std::map<Argument*, ScalarizeTable> ScalarizedElements;
395
396 // OriginalLoads - Keep track of a representative load instruction from the
397 // original function so that we can tell the alias analysis implementation
398 // what the new GEP/Load instructions we are inserting look like.
399 std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
400
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000401 // ParamAttrs - Keep track of the parameter attributes for the arguments
402 // that we are *not* promoting. For the ones that we do promote, the parameter
403 // attributes are lost
404 ParamAttrsVector ParamAttrsVec;
405 const ParamAttrsList *PAL = F->getParamAttrs();
406
407 unsigned index = 1;
408 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
Chris Lattnera1dde2b2008-01-11 22:31:41 +0000409 ++I, ++index) {
410 if (ByValArgsToTransform.count(I)) {
411 // Just add all the struct element types.
412 const Type *AgTy = cast<PointerType>(I->getType())->getElementType();
413 const StructType *STy = cast<StructType>(AgTy);
414 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
415 Params.push_back(STy->getElementType(i));
416 ++NumByValArgsPromoted;
417 } else if (!ArgsToPromote.count(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000418 Params.push_back(I->getType());
Chris Lattnera1dde2b2008-01-11 22:31:41 +0000419 if (unsigned attrs = PAL ? PAL->getParamAttrs(index) : 0)
420 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(), attrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000421 } else if (I->use_empty()) {
422 ++NumArgumentsDead;
423 } else {
424 // Okay, this is being promoted. Check to see if there are any GEP uses
425 // of the argument.
426 ScalarizeTable &ArgIndices = ScalarizedElements[I];
427 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
428 ++UI) {
429 Instruction *User = cast<Instruction>(*UI);
430 assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
431 std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
432 ArgIndices.insert(Indices);
433 LoadInst *OrigLoad;
434 if (LoadInst *L = dyn_cast<LoadInst>(User))
435 OrigLoad = L;
436 else
437 OrigLoad = cast<LoadInst>(User->use_back());
438 OriginalLoads[Indices] = OrigLoad;
439 }
440
441 // Add a parameter to the function for each element passed in.
442 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
443 E = ArgIndices.end(); SI != E; ++SI)
444 Params.push_back(GetElementPtrInst::getIndexedType(I->getType(),
David Greene393be882007-09-04 15:46:09 +0000445 SI->begin(),
446 SI->end()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000447
448 if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
449 ++NumArgumentsPromoted;
450 else
451 ++NumAggregatesPromoted;
452 }
Chris Lattnera1dde2b2008-01-11 22:31:41 +0000453 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000454
455 const Type *RetTy = FTy->getReturnType();
456
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000457 // Recompute the parameter attributes list based on the new arguments for
458 // the function.
459 if (ParamAttrsVec.empty())
460 PAL = 0;
461 else
462 PAL = ParamAttrsList::get(ParamAttrsVec);
463
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000464 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
465 // have zero fixed arguments.
466 bool ExtraArgHack = false;
467 if (Params.empty() && FTy->isVarArg()) {
468 ExtraArgHack = true;
469 Params.push_back(Type::Int32Ty);
470 }
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000471
472 // Construct the new function type using the new arguments.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000473 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
474
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000475 // Create the new function body and insert it into the module...
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000476 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
477 NF->setCallingConv(F->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000478 NF->setParamAttrs(PAL);
Gordon Henriksen3e7ea1e2007-12-25 22:16:06 +0000479 if (F->hasCollector())
480 NF->setCollector(F->getCollector());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000481 F->getParent()->getFunctionList().insert(F, NF);
482
483 // Get the alias analysis information that we need to update to reflect our
484 // changes.
485 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
486
487 // Loop over all of the callers of the function, transforming the call sites
488 // to pass in the loaded pointers.
489 //
490 std::vector<Value*> Args;
491 while (!F->use_empty()) {
492 CallSite CS = CallSite::get(F->use_back());
493 Instruction *Call = CS.getInstruction();
494
495 // Loop over the operands, inserting GEP and loads in the caller as
496 // appropriate.
497 CallSite::arg_iterator AI = CS.arg_begin();
498 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
499 I != E; ++I, ++AI)
Chris Lattnera1dde2b2008-01-11 22:31:41 +0000500 if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000501 Args.push_back(*AI); // Unmodified argument
Chris Lattnera1dde2b2008-01-11 22:31:41 +0000502 } else if (ByValArgsToTransform.count(I)) {
503 // Emit a GEP and load for each element of the struct.
504 const Type *AgTy = cast<PointerType>(I->getType())->getElementType();
505 const StructType *STy = cast<StructType>(AgTy);
506 Value *Idxs[2] = { ConstantInt::get(Type::Int32Ty, 0), 0 };
507 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
508 Idxs[1] = ConstantInt::get(Type::Int32Ty, i);
509 Value *Idx = new GetElementPtrInst(*AI, Idxs, Idxs+2,
510 (*AI)->getName()+"."+utostr(i),
511 Call);
512 // TODO: Tell AA about the new values?
513 Args.push_back(new LoadInst(Idx, Idx->getName()+".val", Call));
514 }
515 } else if (!I->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000516 // Non-dead argument: insert GEPs and loads as appropriate.
517 ScalarizeTable &ArgIndices = ScalarizedElements[I];
518 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
519 E = ArgIndices.end(); SI != E; ++SI) {
520 Value *V = *AI;
521 LoadInst *OrigLoad = OriginalLoads[*SI];
522 if (!SI->empty()) {
David Greene393be882007-09-04 15:46:09 +0000523 V = new GetElementPtrInst(V, SI->begin(), SI->end(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000524 V->getName()+".idx", Call);
525 AA.copyValue(OrigLoad->getOperand(0), V);
526 }
527 Args.push_back(new LoadInst(V, V->getName()+".val", Call));
528 AA.copyValue(OrigLoad, Args.back());
529 }
530 }
531
532 if (ExtraArgHack)
533 Args.push_back(Constant::getNullValue(Type::Int32Ty));
534
535 // Push any varargs arguments on the list
536 for (; AI != CS.arg_end(); ++AI)
537 Args.push_back(*AI);
538
539 Instruction *New;
540 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
541 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
David Greene8278ef52007-08-27 19:04:21 +0000542 Args.begin(), Args.end(), "", Call);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000543 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000544 cast<InvokeInst>(New)->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000545 } else {
David Greeneb1c4a7b2007-08-01 03:43:44 +0000546 New = new CallInst(NF, Args.begin(), Args.end(), "", Call);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000547 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +0000548 cast<CallInst>(New)->setParamAttrs(PAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000549 if (cast<CallInst>(Call)->isTailCall())
550 cast<CallInst>(New)->setTailCall();
551 }
552 Args.clear();
553
554 // Update the alias analysis implementation to know that we are replacing
555 // the old call with a new one.
556 AA.replaceWithNewValue(Call, New);
557
558 if (!Call->use_empty()) {
559 Call->replaceAllUsesWith(New);
560 New->takeName(Call);
561 }
562
563 // Finally, remove the old call from the program, reducing the use-count of
564 // F.
Chris Lattner09ddfda2008-01-11 19:20:39 +0000565 Call->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000566 }
567
568 // Since we have now created the new function, splice the body of the old
569 // function right into the new function, leaving the old rotting hulk of the
570 // function empty.
571 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
572
573 // Loop over the argument list, transfering uses of the old arguments over to
574 // the new arguments, also transfering over the names as well.
575 //
576 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
Chris Lattnera1dde2b2008-01-11 22:31:41 +0000577 I2 = NF->arg_begin(); I != E; ++I) {
578 if (!ArgsToPromote.count(I) && !ByValArgsToTransform.count(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000579 // If this is an unmodified argument, move the name and users over to the
580 // new version.
581 I->replaceAllUsesWith(I2);
582 I2->takeName(I);
583 AA.replaceWithNewValue(I, I2);
584 ++I2;
Chris Lattnera1dde2b2008-01-11 22:31:41 +0000585 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586 }
Chris Lattnera1dde2b2008-01-11 22:31:41 +0000587
588 if (ByValArgsToTransform.count(I)) {
589 // In the callee, we create an alloca, and store each of the new incoming
590 // arguments into the alloca.
591 Instruction *InsertPt = NF->begin()->begin();
592
593 // Just add all the struct element types.
594 const Type *AgTy = cast<PointerType>(I->getType())->getElementType();
595 Value *TheAlloca = new AllocaInst(AgTy, 0, "", InsertPt);
596 const StructType *STy = cast<StructType>(AgTy);
597 Value *Idxs[2] = { ConstantInt::get(Type::Int32Ty, 0), 0 };
598
599 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
600 Idxs[1] = ConstantInt::get(Type::Int32Ty, i);
601 Value *Idx = new GetElementPtrInst(TheAlloca, Idxs, Idxs+2,
602 TheAlloca->getName()+"."+utostr(i),
603 InsertPt);
604 I2->setName(I->getName()+"."+utostr(i));
605 new StoreInst(I2++, Idx, InsertPt);
606 }
607
608 // Anything that used the arg should now use the alloca.
609 I->replaceAllUsesWith(TheAlloca);
610 TheAlloca->takeName(I);
611 AA.replaceWithNewValue(I, TheAlloca);
612 continue;
613 }
614
615 if (I->use_empty()) {
616 AA.deleteValue(I);
617 continue;
618 }
619
620 // Otherwise, if we promoted this argument, then all users are load
621 // instructions, and all loads should be using the new argument that we
622 // added.
623 ScalarizeTable &ArgIndices = ScalarizedElements[I];
624
625 while (!I->use_empty()) {
626 if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
627 assert(ArgIndices.begin()->empty() &&
628 "Load element should sort to front!");
629 I2->setName(I->getName()+".val");
630 LI->replaceAllUsesWith(I2);
631 AA.replaceWithNewValue(LI, I2);
632 LI->eraseFromParent();
633 DOUT << "*** Promoted load of argument '" << I->getName()
634 << "' in function '" << F->getName() << "'\n";
635 } else {
636 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
637 std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
638
639 Function::arg_iterator TheArg = I2;
640 for (ScalarizeTable::iterator It = ArgIndices.begin();
641 *It != Operands; ++It, ++TheArg) {
642 assert(It != ArgIndices.end() && "GEP not handled??");
643 }
644
645 std::string NewName = I->getName();
646 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
647 if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
648 NewName += "." + CI->getValue().toStringUnsigned(10);
649 else
650 NewName += ".x";
651 TheArg->setName(NewName+".val");
652
653 DOUT << "*** Promoted agg argument '" << TheArg->getName()
654 << "' of function '" << F->getName() << "'\n";
655
656 // All of the uses must be load instructions. Replace them all with
657 // the argument specified by ArgNo.
658 while (!GEP->use_empty()) {
659 LoadInst *L = cast<LoadInst>(GEP->use_back());
660 L->replaceAllUsesWith(TheArg);
661 AA.replaceWithNewValue(L, TheArg);
662 L->eraseFromParent();
663 }
664 AA.deleteValue(GEP);
665 GEP->eraseFromParent();
666 }
667 }
668
669 // Increment I2 past all of the arguments added for this promoted pointer.
670 for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i)
671 ++I2;
672 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673
674 // Notify the alias analysis implementation that we inserted a new argument.
675 if (ExtraArgHack)
676 AA.copyValue(Constant::getNullValue(Type::Int32Ty), NF->arg_begin());
677
678
679 // Tell the alias analysis that the old function is about to disappear.
680 AA.replaceWithNewValue(F, NF);
681
682 // Now that the old function is dead, delete it.
Chris Lattner09ddfda2008-01-11 19:20:39 +0000683 F->eraseFromParent();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684 return NF;
685}