blob: 927c60a23fb5ba301910c92916dd20f491092821 [file] [log] [blame]
Chris Lattner254f8f82004-05-23 21:21:17 +00001//===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
Chris Lattner483ae012004-03-07 21:29:54 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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
Chris Lattner5065b242004-09-17 03:58:39 +000012// arguments. If we can prove, through the use of alias analysis, that an
Chris Lattner483ae012004-03-07 21:29:54 +000013// argument is *only* loaded, then we can pass the value into the function
14// 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
20// we refuse to scalarize aggregates which would require passing in more than
21// three operands to the function, because we don't want to pass thousands of
Chris Lattner254f8f82004-05-23 21:21:17 +000022// operands for a large array or structure!
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
25// stored to (returning the value instead), but we do not currently handle that
Chris Lattnerfe6f2e32004-03-08 01:04:36 +000026// case. This case would be best handled when and if we start supporting
27// multiple return 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"
38#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner37b6c4f2004-09-18 00:34:13 +000039#include "llvm/Analysis/CallGraph.h"
Chris Lattner483ae012004-03-07 21:29:54 +000040#include "llvm/Target/TargetData.h"
41#include "llvm/Support/CallSite.h"
42#include "llvm/Support/CFG.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000043#include "llvm/Support/Debug.h"
44#include "llvm/ADT/DepthFirstIterator.h"
45#include "llvm/ADT/Statistic.h"
46#include "llvm/ADT/StringExtras.h"
Chris Lattner483ae012004-03-07 21:29:54 +000047#include <set>
48using namespace llvm;
49
50namespace {
51 Statistic<> NumArgumentsPromoted("argpromotion",
52 "Number of pointer arguments promoted");
Chris Lattnerfe6f2e32004-03-08 01:04:36 +000053 Statistic<> NumAggregatesPromoted("argpromotion",
54 "Number of aggregate arguments promoted");
Chris Lattner483ae012004-03-07 21:29:54 +000055 Statistic<> NumArgumentsDead("argpromotion",
56 "Number of dead pointer args eliminated");
57
58 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
59 ///
Chris Lattner37b6c4f2004-09-18 00:34:13 +000060 struct ArgPromotion : public CallGraphSCCPass {
Chris Lattner483ae012004-03-07 21:29:54 +000061 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
62 AU.addRequired<AliasAnalysis>();
63 AU.addRequired<TargetData>();
Chris Lattner37b6c4f2004-09-18 00:34:13 +000064 CallGraphSCCPass::getAnalysisUsage(AU);
Chris Lattner483ae012004-03-07 21:29:54 +000065 }
66
Chris Lattner37b6c4f2004-09-18 00:34:13 +000067 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
Chris Lattner483ae012004-03-07 21:29:54 +000068 private:
Chris Lattner37b6c4f2004-09-18 00:34:13 +000069 bool PromoteArguments(CallGraphNode *CGN);
Chris Lattner483ae012004-03-07 21:29:54 +000070 bool isSafeToPromoteArgument(Argument *Arg) const;
Chris Lattner37b6c4f2004-09-18 00:34:13 +000071 Function *DoPromotion(Function *F, std::vector<Argument*> &ArgsToPromote);
Chris Lattner483ae012004-03-07 21:29:54 +000072 };
73
74 RegisterOpt<ArgPromotion> X("argpromotion",
75 "Promote 'by reference' arguments to scalars");
76}
77
Chris Lattner4f2cf032004-09-20 04:48:05 +000078ModulePass *llvm::createArgumentPromotionPass() {
Chris Lattner483ae012004-03-07 21:29:54 +000079 return new ArgPromotion();
80}
81
Chris Lattner37b6c4f2004-09-18 00:34:13 +000082bool ArgPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
83 bool Changed = false, LocalChange;
Chris Lattner483ae012004-03-07 21:29:54 +000084
Chris Lattner9864df92004-09-19 01:05:16 +000085 do { // Iterate until we stop promoting from this SCC.
Chris Lattner37b6c4f2004-09-18 00:34:13 +000086 LocalChange = false;
87 // Attempt to promote arguments from all functions in this SCC.
88 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
89 LocalChange |= PromoteArguments(SCC[i]);
Chris Lattner244031d2004-11-13 23:31:34 +000090 if (LocalChange) return true;
Chris Lattner37b6c4f2004-09-18 00:34:13 +000091 Changed |= LocalChange; // Remember that we changed something.
92 } while (LocalChange);
Chris Lattner483ae012004-03-07 21:29:54 +000093
94 return Changed;
95}
96
Chris Lattner254f8f82004-05-23 21:21:17 +000097/// PromoteArguments - This method checks the specified function to see if there
98/// are any promotable arguments and if it is safe to promote the function (for
99/// example, all callers are direct). If safe to promote some arguments, it
100/// calls the DoPromotion method.
101///
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000102bool ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
103 Function *F = CGN->getFunction();
104
105 // Make sure that it is local to this module.
106 if (!F || !F->hasInternalLinkage()) return false;
Chris Lattner483ae012004-03-07 21:29:54 +0000107
108 // First check: see if there are any pointer arguments! If not, quick exit.
109 std::vector<Argument*> PointerArgs;
110 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
111 if (isa<PointerType>(I->getType()))
112 PointerArgs.push_back(I);
113 if (PointerArgs.empty()) return false;
114
115 // Second check: make sure that all callers are direct callers. We can't
116 // transform functions that have indirect callers.
117 for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
Chris Lattner64b8d692004-03-07 22:43:27 +0000118 UI != E; ++UI) {
119 CallSite CS = CallSite::get(*UI);
Chris Lattner254f8f82004-05-23 21:21:17 +0000120 if (!CS.getInstruction()) // "Taking the address" of the function
121 return false;
122
123 // Ensure that this call site is CALLING the function, not passing it as
124 // an argument.
125 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
126 AI != E; ++AI)
127 if (*AI == F) return false; // Passing the function address in!
Chris Lattner64b8d692004-03-07 22:43:27 +0000128 }
Chris Lattner483ae012004-03-07 21:29:54 +0000129
130 // Check to see which arguments are promotable. If an argument is not
131 // promotable, remove it from the PointerArgs vector.
132 for (unsigned i = 0; i != PointerArgs.size(); ++i)
133 if (!isSafeToPromoteArgument(PointerArgs[i])) {
134 std::swap(PointerArgs[i--], PointerArgs.back());
135 PointerArgs.pop_back();
136 }
137
138 // No promotable pointer arguments.
139 if (PointerArgs.empty()) return false;
140
141 // Okay, promote all of the arguments are rewrite the callees!
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000142 Function *NewF = DoPromotion(F, PointerArgs);
143
144 // Update the call graph to know that the old function is gone.
145 getAnalysis<CallGraph>().changeFunction(F, NewF);
Chris Lattner483ae012004-03-07 21:29:54 +0000146 return true;
147}
148
Chris Lattner244031d2004-11-13 23:31:34 +0000149/// IsAlwaysValidPointer - Return true if the specified pointer is always legal
150/// to load.
151static bool IsAlwaysValidPointer(Value *V) {
152 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
153 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V))
154 return IsAlwaysValidPointer(GEP->getOperand(0));
155 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
156 if (CE->getOpcode() == Instruction::GetElementPtr)
157 return IsAlwaysValidPointer(CE->getOperand(0));
158
159 return false;
160}
161
162/// AllCalleesPassInValidPointerForArgument - Return true if we can prove that
163/// all callees pass in a valid pointer for the specified function argument.
164static bool AllCalleesPassInValidPointerForArgument(Argument *Arg) {
165 Function *Callee = Arg->getParent();
166
167 unsigned ArgNo = std::distance(Callee->abegin(), Function::aiterator(Arg));
168
169 // Look at all call sites of the function. At this pointer we know we only
170 // have direct callees.
171 for (Value::use_iterator UI = Callee->use_begin(), E = Callee->use_end();
172 UI != E; ++UI) {
173 CallSite CS = CallSite::get(*UI);
174 assert(CS.getInstruction() && "Should only have direct calls!");
175
176 if (!IsAlwaysValidPointer(CS.getArgument(ArgNo)))
177 return false;
178 }
179 return true;
180}
181
Chris Lattner254f8f82004-05-23 21:21:17 +0000182
183/// isSafeToPromoteArgument - As you might guess from the name of this method,
184/// it checks to see if it is both safe and useful to promote the argument.
185/// This method limits promotion of aggregates to only promote up to three
186/// elements of the aggregate in order to avoid exploding the number of
187/// arguments passed in.
Chris Lattner483ae012004-03-07 21:29:54 +0000188bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg) const {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000189 // We can only promote this argument if all of the uses are loads, or are GEP
190 // instructions (with constant indices) that are subsequently loaded.
Chris Lattner244031d2004-11-13 23:31:34 +0000191 bool HasLoadInEntryBlock = false;
192 BasicBlock *EntryBlock = Arg->getParent()->begin();
Chris Lattner483ae012004-03-07 21:29:54 +0000193 std::vector<LoadInst*> Loads;
Chris Lattner1c676f72004-06-21 00:07:58 +0000194 std::vector<std::vector<ConstantInt*> > GEPIndices;
Chris Lattner483ae012004-03-07 21:29:54 +0000195 for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
196 UI != E; ++UI)
197 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
198 if (LI->isVolatile()) return false; // Don't hack volatile loads
199 Loads.push_back(LI);
Chris Lattner244031d2004-11-13 23:31:34 +0000200 HasLoadInEntryBlock |= LI->getParent() == EntryBlock;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000201 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
202 if (GEP->use_empty()) {
203 // Dead GEP's cause trouble later. Just remove them if we run into
204 // them.
Chris Lattner254f8f82004-05-23 21:21:17 +0000205 getAnalysis<AliasAnalysis>().deleteValue(GEP);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000206 GEP->getParent()->getInstList().erase(GEP);
207 return isSafeToPromoteArgument(Arg);
208 }
209 // Ensure that all of the indices are constants.
Chris Lattner1c676f72004-06-21 00:07:58 +0000210 std::vector<ConstantInt*> Operands;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000211 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
Chris Lattner1c676f72004-06-21 00:07:58 +0000212 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000213 Operands.push_back(C);
214 else
215 return false; // Not a constant operand GEP!
216
217 // Ensure that the only users of the GEP are load instructions.
218 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
219 UI != E; ++UI)
220 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
221 if (LI->isVolatile()) return false; // Don't hack volatile loads
222 Loads.push_back(LI);
Chris Lattner244031d2004-11-13 23:31:34 +0000223 HasLoadInEntryBlock |= LI->getParent() == EntryBlock;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000224 } else {
225 return false;
226 }
227
Chris Lattner254f8f82004-05-23 21:21:17 +0000228 // See if there is already a GEP with these indices. If not, check to
229 // make sure that we aren't promoting too many elements. If so, nothing
230 // to do.
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000231 if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
232 GEPIndices.end()) {
233 if (GEPIndices.size() == 3) {
Chris Lattner254f8f82004-05-23 21:21:17 +0000234 DEBUG(std::cerr << "argpromotion disable promoting argument '"
235 << Arg->getName() << "' because it would require adding more "
236 << "than 3 arguments to the function.\n");
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000237 // We limit aggregate promotion to only promoting up to three elements
238 // of the aggregate.
239 return false;
240 }
241 GEPIndices.push_back(Operands);
242 }
243 } else {
244 return false; // Not a load or a GEP.
245 }
Chris Lattner483ae012004-03-07 21:29:54 +0000246
Chris Lattner254f8f82004-05-23 21:21:17 +0000247 if (Loads.empty()) return true; // No users, this is a dead argument.
Chris Lattner483ae012004-03-07 21:29:54 +0000248
Chris Lattner244031d2004-11-13 23:31:34 +0000249 // If we decide that we want to promote this argument, the value is going to
250 // be unconditionally loaded in all callees. This is only safe to do if the
251 // pointer was going to be unconditionally loaded anyway (i.e. there is a load
252 // of the pointer in the entry block of the function) or if we can prove that
253 // all pointers passed in are always to legal locations (for example, no null
254 // pointers are passed in, no pointers to free'd memory, etc).
255 if (!HasLoadInEntryBlock && !AllCalleesPassInValidPointerForArgument(Arg))
256 return false; // Cannot prove that this is safe!!
257
258 // Okay, now we know that the argument is only used by load instructions and
259 // it is safe to unconditionally load the pointer. Use alias analysis to
260 // check to see if the pointer is guaranteed to not be modified from entry of
261 // the function to each of the load instructions.
Chris Lattner483ae012004-03-07 21:29:54 +0000262 Function &F = *Arg->getParent();
263
264 // Because there could be several/many load instructions, remember which
265 // blocks we know to be transparent to the load.
266 std::set<BasicBlock*> TranspBlocks;
267
268 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000269 TargetData &TD = getAnalysis<TargetData>();
Chris Lattner483ae012004-03-07 21:29:54 +0000270
271 for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
272 // Check to see if the load is invalidated from the start of the block to
273 // the load itself.
274 LoadInst *Load = Loads[i];
275 BasicBlock *BB = Load->getParent();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000276
277 const PointerType *LoadTy =
278 cast<PointerType>(Load->getOperand(0)->getType());
279 unsigned LoadSize = TD.getTypeSize(LoadTy->getElementType());
280
Chris Lattner483ae012004-03-07 21:29:54 +0000281 if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
282 return false; // Pointer is invalidated!
283
284 // Now check every path from the entry block to the load for transparency.
285 // To do this, we perform a depth first search on the inverse CFG from the
286 // loading block.
287 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
288 for (idf_ext_iterator<BasicBlock*> I = idf_ext_begin(*PI, TranspBlocks),
289 E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
290 if (AA.canBasicBlockModify(**I, Arg, LoadSize))
291 return false;
292 }
293
294 // If the path from the entry of the function to each load is free of
295 // instructions that potentially invalidate the load, we can make the
296 // transformation!
297 return true;
298}
299
Chris Lattner1c676f72004-06-21 00:07:58 +0000300namespace {
301 /// GEPIdxComparator - Provide a strong ordering for GEP indices. All Value*
302 /// elements are instances of ConstantInt.
303 ///
304 struct GEPIdxComparator {
305 bool operator()(const std::vector<Value*> &LHS,
306 const std::vector<Value*> &RHS) const {
307 unsigned idx = 0;
308 for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
309 if (LHS[idx] != RHS[idx]) {
310 return cast<ConstantInt>(LHS[idx])->getRawValue() <
311 cast<ConstantInt>(RHS[idx])->getRawValue();
312 }
313 }
314
315 // Return less than if we ran out of stuff in LHS and we didn't run out of
316 // stuff in RHS.
317 return idx == LHS.size() && idx != RHS.size();
318 }
319 };
320}
321
322
Chris Lattner254f8f82004-05-23 21:21:17 +0000323/// DoPromotion - This method actually performs the promotion of the specified
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000324/// arguments, and returns the new function. At this point, we know that it's
325/// safe to do so.
326Function *ArgPromotion::DoPromotion(Function *F,
327 std::vector<Argument*> &Args2Prom) {
Chris Lattner483ae012004-03-07 21:29:54 +0000328 std::set<Argument*> ArgsToPromote(Args2Prom.begin(), Args2Prom.end());
329
330 // Start by computing a new prototype for the function, which is the same as
331 // the old function, but has modified arguments.
332 const FunctionType *FTy = F->getFunctionType();
333 std::vector<const Type*> Params;
334
Chris Lattner1c676f72004-06-21 00:07:58 +0000335 typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
336
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000337 // ScalarizedElements - If we are promoting a pointer that has elements
338 // accessed out of it, keep track of which elements are accessed so that we
339 // can add one argument for each.
340 //
341 // Arguments that are directly loaded will have a zero element value here, to
342 // handle cases where there are both a direct load and GEP accesses.
343 //
Chris Lattner1c676f72004-06-21 00:07:58 +0000344 std::map<Argument*, ScalarizeTable> ScalarizedElements;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000345
Chris Lattner254f8f82004-05-23 21:21:17 +0000346 // OriginalLoads - Keep track of a representative load instruction from the
347 // original function so that we can tell the alias analysis implementation
348 // what the new GEP/Load instructions we are inserting look like.
349 std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
350
Chris Lattner483ae012004-03-07 21:29:54 +0000351 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I)
352 if (!ArgsToPromote.count(I)) {
353 Params.push_back(I->getType());
Chris Lattner254f8f82004-05-23 21:21:17 +0000354 } else if (I->use_empty()) {
355 ++NumArgumentsDead;
356 } else {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000357 // Okay, this is being promoted. Check to see if there are any GEP uses
358 // of the argument.
Chris Lattner1c676f72004-06-21 00:07:58 +0000359 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000360 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
361 ++UI) {
362 Instruction *User = cast<Instruction>(*UI);
363 assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
Chris Lattner254f8f82004-05-23 21:21:17 +0000364 std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
365 ArgIndices.insert(Indices);
366 LoadInst *OrigLoad;
367 if (LoadInst *L = dyn_cast<LoadInst>(User))
368 OrigLoad = L;
369 else
370 OrigLoad = cast<LoadInst>(User->use_back());
371 OriginalLoads[Indices] = OrigLoad;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000372 }
373
374 // Add a parameter to the function for each element passed in.
Chris Lattner1c676f72004-06-21 00:07:58 +0000375 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000376 E = ArgIndices.end(); SI != E; ++SI)
377 Params.push_back(GetElementPtrInst::getIndexedType(I->getType(), *SI));
378
379 if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
380 ++NumArgumentsPromoted;
381 else
382 ++NumAggregatesPromoted;
Chris Lattner483ae012004-03-07 21:29:54 +0000383 }
384
385 const Type *RetTy = FTy->getReturnType();
386
387 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
388 // have zero fixed arguments.
389 bool ExtraArgHack = false;
390 if (Params.empty() && FTy->isVarArg()) {
391 ExtraArgHack = true;
392 Params.push_back(Type::IntTy);
393 }
394 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
395
396 // Create the new function body and insert it into the module...
397 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
398 F->getParent()->getFunctionList().insert(F, NF);
Chris Lattner254f8f82004-05-23 21:21:17 +0000399
400 // Get the alias analysis information that we need to update to reflect our
401 // changes.
402 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
403
Chris Lattner483ae012004-03-07 21:29:54 +0000404 // Loop over all of the callers of the function, transforming the call sites
405 // to pass in the loaded pointers.
406 //
407 std::vector<Value*> Args;
408 while (!F->use_empty()) {
409 CallSite CS = CallSite::get(F->use_back());
410 Instruction *Call = CS.getInstruction();
411
Chris Lattner254f8f82004-05-23 21:21:17 +0000412 // Loop over the operands, inserting GEP and loads in the caller as
413 // appropriate.
Chris Lattner483ae012004-03-07 21:29:54 +0000414 CallSite::arg_iterator AI = CS.arg_begin();
415 for (Function::aiterator I = F->abegin(), E = F->aend(); I != E; ++I, ++AI)
416 if (!ArgsToPromote.count(I))
417 Args.push_back(*AI); // Unmodified argument
418 else if (!I->use_empty()) {
Chris Lattner254f8f82004-05-23 21:21:17 +0000419 // Non-dead argument: insert GEPs and loads as appropriate.
Chris Lattner1c676f72004-06-21 00:07:58 +0000420 ScalarizeTable &ArgIndices = ScalarizedElements[I];
421 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000422 E = ArgIndices.end(); SI != E; ++SI) {
423 Value *V = *AI;
Chris Lattner254f8f82004-05-23 21:21:17 +0000424 LoadInst *OrigLoad = OriginalLoads[*SI];
425 if (!SI->empty()) {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000426 V = new GetElementPtrInst(V, *SI, V->getName()+".idx", Call);
Chris Lattner254f8f82004-05-23 21:21:17 +0000427 AA.copyValue(OrigLoad->getOperand(0), V);
428 }
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000429 Args.push_back(new LoadInst(V, V->getName()+".val", Call));
Chris Lattner254f8f82004-05-23 21:21:17 +0000430 AA.copyValue(OrigLoad, Args.back());
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000431 }
Chris Lattner483ae012004-03-07 21:29:54 +0000432 }
433
434 if (ExtraArgHack)
435 Args.push_back(Constant::getNullValue(Type::IntTy));
436
437 // Push any varargs arguments on the list
438 for (; AI != CS.arg_end(); ++AI)
439 Args.push_back(*AI);
440
441 Instruction *New;
442 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
443 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
444 Args, "", Call);
445 } else {
446 New = new CallInst(NF, Args, "", Call);
447 }
448 Args.clear();
449
Chris Lattner254f8f82004-05-23 21:21:17 +0000450 // Update the alias analysis implementation to know that we are replacing
451 // the old call with a new one.
452 AA.replaceWithNewValue(Call, New);
453
Chris Lattner483ae012004-03-07 21:29:54 +0000454 if (!Call->use_empty()) {
455 Call->replaceAllUsesWith(New);
456 std::string Name = Call->getName();
457 Call->setName("");
458 New->setName(Name);
459 }
460
461 // Finally, remove the old call from the program, reducing the use-count of
462 // F.
463 Call->getParent()->getInstList().erase(Call);
464 }
465
466 // Since we have now created the new function, splice the body of the old
467 // function right into the new function, leaving the old rotting hulk of the
468 // function empty.
469 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
470
471 // Loop over the argument list, transfering uses of the old arguments over to
472 // the new arguments, also transfering over the names as well.
473 //
474 for (Function::aiterator I = F->abegin(), E = F->aend(), I2 = NF->abegin();
475 I != E; ++I)
476 if (!ArgsToPromote.count(I)) {
477 // If this is an unmodified argument, move the name and users over to the
478 // new version.
479 I->replaceAllUsesWith(I2);
480 I2->setName(I->getName());
Chris Lattner254f8f82004-05-23 21:21:17 +0000481 AA.replaceWithNewValue(I, I2);
Chris Lattner483ae012004-03-07 21:29:54 +0000482 ++I2;
Chris Lattner254f8f82004-05-23 21:21:17 +0000483 } else if (I->use_empty()) {
484 AA.deleteValue(I);
485 } else {
Chris Lattner483ae012004-03-07 21:29:54 +0000486 // Otherwise, if we promoted this argument, then all users are load
487 // instructions, and all loads should be using the new argument that we
488 // added.
Chris Lattner1c676f72004-06-21 00:07:58 +0000489 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000490
Chris Lattner483ae012004-03-07 21:29:54 +0000491 while (!I->use_empty()) {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000492 if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
493 assert(ArgIndices.begin()->empty() &&
494 "Load element should sort to front!");
495 I2->setName(I->getName()+".val");
496 LI->replaceAllUsesWith(I2);
Chris Lattner254f8f82004-05-23 21:21:17 +0000497 AA.replaceWithNewValue(LI, I2);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000498 LI->getParent()->getInstList().erase(LI);
Chris Lattner254f8f82004-05-23 21:21:17 +0000499 DEBUG(std::cerr << "*** Promoted load of argument '" << I->getName()
500 << "' in function '" << F->getName() << "'\n");
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000501 } else {
502 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
503 std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
504
505 unsigned ArgNo = 0;
506 Function::aiterator TheArg = I2;
Chris Lattner1c676f72004-06-21 00:07:58 +0000507 for (ScalarizeTable::iterator It = ArgIndices.begin();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000508 *It != Operands; ++It, ++TheArg) {
509 assert(It != ArgIndices.end() && "GEP not handled??");
510 }
511
512 std::string NewName = I->getName();
513 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
514 if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
515 NewName += "."+itostr((int64_t)CI->getRawValue());
516 else
517 NewName += ".x";
518 TheArg->setName(NewName+".val");
519
520 DEBUG(std::cerr << "*** Promoted agg argument '" << TheArg->getName()
521 << "' of function '" << F->getName() << "'\n");
522
523 // All of the uses must be load instructions. Replace them all with
524 // the argument specified by ArgNo.
525 while (!GEP->use_empty()) {
526 LoadInst *L = cast<LoadInst>(GEP->use_back());
527 L->replaceAllUsesWith(TheArg);
Chris Lattner254f8f82004-05-23 21:21:17 +0000528 AA.replaceWithNewValue(L, TheArg);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000529 L->getParent()->getInstList().erase(L);
530 }
Chris Lattner254f8f82004-05-23 21:21:17 +0000531 AA.deleteValue(GEP);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000532 GEP->getParent()->getInstList().erase(GEP);
533 }
Chris Lattner483ae012004-03-07 21:29:54 +0000534 }
Chris Lattnercc544e52004-03-07 22:52:53 +0000535
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000536 // Increment I2 past all of the arguments added for this promoted pointer.
537 for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i)
538 ++I2;
Chris Lattner483ae012004-03-07 21:29:54 +0000539 }
540
Chris Lattner254f8f82004-05-23 21:21:17 +0000541 // Notify the alias analysis implementation that we inserted a new argument.
542 if (ExtraArgHack)
543 AA.copyValue(Constant::getNullValue(Type::IntTy), NF->abegin());
544
545
546 // Tell the alias analysis that the old function is about to disappear.
547 AA.replaceWithNewValue(F, NF);
548
Chris Lattner483ae012004-03-07 21:29:54 +0000549 // Now that the old function is dead, delete it.
550 F->getParent()->getFunctionList().erase(F);
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000551 return NF;
Chris Lattner483ae012004-03-07 21:29:54 +0000552}