blob: 960e36ba54c5c096ce420fdb2625ee97a8bbeedb [file] [log] [blame]
Chris Lattner9e7cc2f2004-05-23 21:21:17 +00001//===-- ArgumentPromotion.cpp - Promote by-reference arguments ------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
Chris Lattnered570a72004-03-07 21:29:54 +00003// 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.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
Chris Lattnered570a72004-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
Chris Lattnerebeb0cb2004-09-17 03:58:39 +000012// arguments. If we can prove, through the use of alias analysis, that an
Chris Lattnered570a72004-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 Lattner9e7cc2f2004-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 Lattnered570a72004-03-07 21:29:54 +000017//
Chris Lattner9440db82004-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 Lattner9e7cc2f2004-05-23 21:21:17 +000022// operands for a large array or structure!
Chris Lattner9440db82004-03-08 01:04:36 +000023//
Chris Lattnered570a72004-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 Lattner9440db82004-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 Lattnered570a72004-03-07 21:29:54 +000028//
29//===----------------------------------------------------------------------===//
30
Chris Lattner9e7cc2f2004-05-23 21:21:17 +000031#define DEBUG_TYPE "argpromotion"
Chris Lattnered570a72004-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 Lattner5eb6f6c2004-09-18 00:34:13 +000036#include "llvm/CallGraphSCCPass.h"
Chris Lattnered570a72004-03-07 21:29:54 +000037#include "llvm/Instructions.h"
38#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000039#include "llvm/Analysis/CallGraph.h"
Chris Lattnered570a72004-03-07 21:29:54 +000040#include "llvm/Target/TargetData.h"
41#include "llvm/Support/CallSite.h"
42#include "llvm/Support/CFG.h"
Reid Spencer551ccae2004-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 Lattnerdac58ad2006-01-22 23:32:06 +000047#include <iostream>
Chris Lattnered570a72004-03-07 21:29:54 +000048#include <set>
49using namespace llvm;
50
51namespace {
52 Statistic<> NumArgumentsPromoted("argpromotion",
53 "Number of pointer arguments promoted");
Chris Lattner9440db82004-03-08 01:04:36 +000054 Statistic<> NumAggregatesPromoted("argpromotion",
55 "Number of aggregate arguments promoted");
Chris Lattnered570a72004-03-07 21:29:54 +000056 Statistic<> NumArgumentsDead("argpromotion",
57 "Number of dead pointer args eliminated");
58
59 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
60 ///
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000061 struct ArgPromotion : public CallGraphSCCPass {
Chris Lattnered570a72004-03-07 21:29:54 +000062 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
63 AU.addRequired<AliasAnalysis>();
64 AU.addRequired<TargetData>();
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000065 CallGraphSCCPass::getAnalysisUsage(AU);
Chris Lattnered570a72004-03-07 21:29:54 +000066 }
67
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000068 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
Chris Lattnered570a72004-03-07 21:29:54 +000069 private:
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000070 bool PromoteArguments(CallGraphNode *CGN);
Misha Brukmanfd939082005-04-21 23:48:37 +000071 bool isSafeToPromoteArgument(Argument *Arg) const;
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000072 Function *DoPromotion(Function *F, std::vector<Argument*> &ArgsToPromote);
Chris Lattnered570a72004-03-07 21:29:54 +000073 };
74
75 RegisterOpt<ArgPromotion> X("argpromotion",
76 "Promote 'by reference' arguments to scalars");
77}
78
Chris Lattnerb12914b2004-09-20 04:48:05 +000079ModulePass *llvm::createArgumentPromotionPass() {
Chris Lattnered570a72004-03-07 21:29:54 +000080 return new ArgPromotion();
81}
82
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000083bool ArgPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
84 bool Changed = false, LocalChange;
Chris Lattnered570a72004-03-07 21:29:54 +000085
Chris Lattnerf5afcab2004-09-19 01:05:16 +000086 do { // Iterate until we stop promoting from this SCC.
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000087 LocalChange = false;
88 // Attempt to promote arguments from all functions in this SCC.
89 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
90 LocalChange |= PromoteArguments(SCC[i]);
91 Changed |= LocalChange; // Remember that we changed something.
92 } while (LocalChange);
Misha Brukmanfd939082005-04-21 23:48:37 +000093
Chris Lattnered570a72004-03-07 21:29:54 +000094 return Changed;
95}
96
Chris Lattner9e7cc2f2004-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 Lattner5eb6f6c2004-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 Lattnered570a72004-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;
Chris Lattnere4d5c442005-03-15 04:54:21 +0000110 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnered570a72004-03-07 21:29:54 +0000111 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 Lattner7db5a6d2004-03-07 22:43:27 +0000118 UI != E; ++UI) {
119 CallSite CS = CallSite::get(*UI);
Chris Lattner9e7cc2f2004-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 Lattner7db5a6d2004-03-07 22:43:27 +0000128 }
Chris Lattnered570a72004-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 Lattner5eb6f6c2004-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 Lattnered570a72004-03-07 21:29:54 +0000146 return true;
147}
148
Chris Lattner11a3d7b2004-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
Chris Lattnere4d5c442005-03-15 04:54:21 +0000167 unsigned ArgNo = std::distance(Callee->arg_begin(), Function::arg_iterator(Arg));
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000168
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 Lattner9e7cc2f2004-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 Lattnered570a72004-03-07 21:29:54 +0000188bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg) const {
Chris Lattner9440db82004-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 Lattner11a3d7b2004-11-13 23:31:34 +0000191 bool HasLoadInEntryBlock = false;
192 BasicBlock *EntryBlock = Arg->getParent()->begin();
Chris Lattnered570a72004-03-07 21:29:54 +0000193 std::vector<LoadInst*> Loads;
Chris Lattnerbeabf452004-06-21 00:07:58 +0000194 std::vector<std::vector<ConstantInt*> > GEPIndices;
Chris Lattnered570a72004-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 Lattner11a3d7b2004-11-13 23:31:34 +0000200 HasLoadInEntryBlock |= LI->getParent() == EntryBlock;
Chris Lattner9440db82004-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 Lattner9e7cc2f2004-05-23 21:21:17 +0000205 getAnalysis<AliasAnalysis>().deleteValue(GEP);
Chris Lattner9440db82004-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 Lattnerbeabf452004-06-21 00:07:58 +0000210 std::vector<ConstantInt*> Operands;
Chris Lattner9440db82004-03-08 01:04:36 +0000211 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
Chris Lattnerbeabf452004-06-21 00:07:58 +0000212 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
Chris Lattner9440db82004-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 Lattner11a3d7b2004-11-13 23:31:34 +0000223 HasLoadInEntryBlock |= LI->getParent() == EntryBlock;
Chris Lattner9440db82004-03-08 01:04:36 +0000224 } else {
225 return false;
226 }
227
Chris Lattner9e7cc2f2004-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 Lattner9440db82004-03-08 01:04:36 +0000231 if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
232 GEPIndices.end()) {
233 if (GEPIndices.size() == 3) {
Chris Lattner9e7cc2f2004-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 Lattner9440db82004-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 Lattnered570a72004-03-07 21:29:54 +0000246
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000247 if (Loads.empty()) return true; // No users, this is a dead argument.
Chris Lattnered570a72004-03-07 21:29:54 +0000248
Chris Lattner11a3d7b2004-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 Lattnered570a72004-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 Lattner9440db82004-03-08 01:04:36 +0000269 TargetData &TD = getAnalysis<TargetData>();
Chris Lattnered570a72004-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 Lattner9440db82004-03-08 01:04:36 +0000276
277 const PointerType *LoadTy =
278 cast<PointerType>(Load->getOperand(0)->getType());
Chris Lattner4d0801b2005-01-08 19:45:31 +0000279 unsigned LoadSize = (unsigned)TD.getTypeSize(LoadTy->getElementType());
Chris Lattner9440db82004-03-08 01:04:36 +0000280
Chris Lattnered570a72004-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 Lattnerbeabf452004-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]) {
Misha Brukmanfd939082005-04-21 23:48:37 +0000310 return cast<ConstantInt>(LHS[idx])->getRawValue() <
Chris Lattnerbeabf452004-06-21 00:07:58 +0000311 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 Lattner9e7cc2f2004-05-23 21:21:17 +0000323/// DoPromotion - This method actually performs the promotion of the specified
Chris Lattner5eb6f6c2004-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 Lattnered570a72004-03-07 21:29:54 +0000328 std::set<Argument*> ArgsToPromote(Args2Prom.begin(), Args2Prom.end());
Misha Brukmanfd939082005-04-21 23:48:37 +0000329
Chris Lattnered570a72004-03-07 21:29:54 +0000330 // 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 Lattnerbeabf452004-06-21 00:07:58 +0000335 typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
336
Chris Lattner9440db82004-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 Lattnerbeabf452004-06-21 00:07:58 +0000344 std::map<Argument*, ScalarizeTable> ScalarizedElements;
Chris Lattner9440db82004-03-08 01:04:36 +0000345
Chris Lattner9e7cc2f2004-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 Lattnere4d5c442005-03-15 04:54:21 +0000351 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnered570a72004-03-07 21:29:54 +0000352 if (!ArgsToPromote.count(I)) {
353 Params.push_back(I->getType());
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000354 } else if (I->use_empty()) {
355 ++NumArgumentsDead;
356 } else {
Chris Lattner9440db82004-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 Lattnerbeabf452004-06-21 00:07:58 +0000359 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattner9440db82004-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 Lattner9e7cc2f2004-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 Lattner9440db82004-03-08 01:04:36 +0000372 }
373
374 // Add a parameter to the function for each element passed in.
Chris Lattnerbeabf452004-06-21 00:07:58 +0000375 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattner9440db82004-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 Lattnered570a72004-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());
Misha Brukmanfd939082005-04-21 23:48:37 +0000395
Chris Lattnered570a72004-03-07 21:29:54 +0000396 // Create the new function body and insert it into the module...
397 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000398 NF->setCallingConv(F->getCallingConv());
Chris Lattnered570a72004-03-07 21:29:54 +0000399 F->getParent()->getFunctionList().insert(F, NF);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000400
401 // Get the alias analysis information that we need to update to reflect our
402 // changes.
403 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
404
Chris Lattnered570a72004-03-07 21:29:54 +0000405 // Loop over all of the callers of the function, transforming the call sites
406 // to pass in the loaded pointers.
407 //
408 std::vector<Value*> Args;
409 while (!F->use_empty()) {
410 CallSite CS = CallSite::get(F->use_back());
411 Instruction *Call = CS.getInstruction();
412
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000413 // Loop over the operands, inserting GEP and loads in the caller as
414 // appropriate.
Chris Lattnered570a72004-03-07 21:29:54 +0000415 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000416 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
417 I != E; ++I, ++AI)
Chris Lattnered570a72004-03-07 21:29:54 +0000418 if (!ArgsToPromote.count(I))
419 Args.push_back(*AI); // Unmodified argument
420 else if (!I->use_empty()) {
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000421 // Non-dead argument: insert GEPs and loads as appropriate.
Chris Lattnerbeabf452004-06-21 00:07:58 +0000422 ScalarizeTable &ArgIndices = ScalarizedElements[I];
423 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattner9440db82004-03-08 01:04:36 +0000424 E = ArgIndices.end(); SI != E; ++SI) {
425 Value *V = *AI;
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000426 LoadInst *OrigLoad = OriginalLoads[*SI];
427 if (!SI->empty()) {
Chris Lattner9440db82004-03-08 01:04:36 +0000428 V = new GetElementPtrInst(V, *SI, V->getName()+".idx", Call);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000429 AA.copyValue(OrigLoad->getOperand(0), V);
430 }
Chris Lattner9440db82004-03-08 01:04:36 +0000431 Args.push_back(new LoadInst(V, V->getName()+".val", Call));
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000432 AA.copyValue(OrigLoad, Args.back());
Chris Lattner9440db82004-03-08 01:04:36 +0000433 }
Chris Lattnered570a72004-03-07 21:29:54 +0000434 }
435
436 if (ExtraArgHack)
437 Args.push_back(Constant::getNullValue(Type::IntTy));
438
439 // Push any varargs arguments on the list
440 for (; AI != CS.arg_end(); ++AI)
441 Args.push_back(*AI);
442
443 Instruction *New;
444 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
445 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
446 Args, "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000447 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattnered570a72004-03-07 21:29:54 +0000448 } else {
449 New = new CallInst(NF, Args, "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000450 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner1430ef12005-05-06 06:46:58 +0000451 if (cast<CallInst>(Call)->isTailCall())
452 cast<CallInst>(New)->setTailCall();
Chris Lattnered570a72004-03-07 21:29:54 +0000453 }
454 Args.clear();
455
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000456 // Update the alias analysis implementation to know that we are replacing
457 // the old call with a new one.
458 AA.replaceWithNewValue(Call, New);
459
Chris Lattnered570a72004-03-07 21:29:54 +0000460 if (!Call->use_empty()) {
461 Call->replaceAllUsesWith(New);
462 std::string Name = Call->getName();
463 Call->setName("");
464 New->setName(Name);
465 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000466
Chris Lattnered570a72004-03-07 21:29:54 +0000467 // Finally, remove the old call from the program, reducing the use-count of
468 // F.
469 Call->getParent()->getInstList().erase(Call);
470 }
471
472 // Since we have now created the new function, splice the body of the old
473 // function right into the new function, leaving the old rotting hulk of the
474 // function empty.
475 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
476
477 // Loop over the argument list, transfering uses of the old arguments over to
478 // the new arguments, also transfering over the names as well.
479 //
Chris Lattnere4d5c442005-03-15 04:54:21 +0000480 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(), I2 = NF->arg_begin();
Chris Lattnered570a72004-03-07 21:29:54 +0000481 I != E; ++I)
482 if (!ArgsToPromote.count(I)) {
483 // If this is an unmodified argument, move the name and users over to the
484 // new version.
485 I->replaceAllUsesWith(I2);
486 I2->setName(I->getName());
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000487 AA.replaceWithNewValue(I, I2);
Chris Lattnered570a72004-03-07 21:29:54 +0000488 ++I2;
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000489 } else if (I->use_empty()) {
490 AA.deleteValue(I);
491 } else {
Chris Lattnered570a72004-03-07 21:29:54 +0000492 // Otherwise, if we promoted this argument, then all users are load
493 // instructions, and all loads should be using the new argument that we
494 // added.
Chris Lattnerbeabf452004-06-21 00:07:58 +0000495 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattner9440db82004-03-08 01:04:36 +0000496
Chris Lattnered570a72004-03-07 21:29:54 +0000497 while (!I->use_empty()) {
Chris Lattner9440db82004-03-08 01:04:36 +0000498 if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
499 assert(ArgIndices.begin()->empty() &&
500 "Load element should sort to front!");
501 I2->setName(I->getName()+".val");
502 LI->replaceAllUsesWith(I2);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000503 AA.replaceWithNewValue(LI, I2);
Chris Lattner9440db82004-03-08 01:04:36 +0000504 LI->getParent()->getInstList().erase(LI);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000505 DEBUG(std::cerr << "*** Promoted load of argument '" << I->getName()
506 << "' in function '" << F->getName() << "'\n");
Chris Lattner9440db82004-03-08 01:04:36 +0000507 } else {
508 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
509 std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
510
511 unsigned ArgNo = 0;
Chris Lattnere4d5c442005-03-15 04:54:21 +0000512 Function::arg_iterator TheArg = I2;
Chris Lattnerbeabf452004-06-21 00:07:58 +0000513 for (ScalarizeTable::iterator It = ArgIndices.begin();
Chris Lattner9440db82004-03-08 01:04:36 +0000514 *It != Operands; ++It, ++TheArg) {
515 assert(It != ArgIndices.end() && "GEP not handled??");
516 }
517
518 std::string NewName = I->getName();
519 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
520 if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
521 NewName += "."+itostr((int64_t)CI->getRawValue());
522 else
523 NewName += ".x";
524 TheArg->setName(NewName+".val");
525
526 DEBUG(std::cerr << "*** Promoted agg argument '" << TheArg->getName()
527 << "' of function '" << F->getName() << "'\n");
528
529 // All of the uses must be load instructions. Replace them all with
530 // the argument specified by ArgNo.
531 while (!GEP->use_empty()) {
532 LoadInst *L = cast<LoadInst>(GEP->use_back());
533 L->replaceAllUsesWith(TheArg);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000534 AA.replaceWithNewValue(L, TheArg);
Chris Lattner9440db82004-03-08 01:04:36 +0000535 L->getParent()->getInstList().erase(L);
536 }
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000537 AA.deleteValue(GEP);
Chris Lattner9440db82004-03-08 01:04:36 +0000538 GEP->getParent()->getInstList().erase(GEP);
539 }
Chris Lattnered570a72004-03-07 21:29:54 +0000540 }
Chris Lattner86a734b2004-03-07 22:52:53 +0000541
Chris Lattner5eb6f6c2004-09-18 00:34:13 +0000542 // Increment I2 past all of the arguments added for this promoted pointer.
543 for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i)
544 ++I2;
Chris Lattnered570a72004-03-07 21:29:54 +0000545 }
546
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000547 // Notify the alias analysis implementation that we inserted a new argument.
548 if (ExtraArgHack)
Chris Lattnere4d5c442005-03-15 04:54:21 +0000549 AA.copyValue(Constant::getNullValue(Type::IntTy), NF->arg_begin());
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000550
551
552 // Tell the alias analysis that the old function is about to disappear.
553 AA.replaceWithNewValue(F, NF);
554
Chris Lattnered570a72004-03-07 21:29:54 +0000555 // Now that the old function is dead, delete it.
556 F->getParent()->getFunctionList().erase(F);
Chris Lattner5eb6f6c2004-09-18 00:34:13 +0000557 return NF;
Chris Lattnered570a72004-03-07 21:29:54 +0000558}