blob: 467214dce666476f4060e8dc0e9c91dbe1db28c8 [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//
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 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
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
Chris Lattner1631bcb2006-12-19 22:09:18 +000050STATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted");
51STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
52STATISTIC(NumArgumentsDead , "Number of dead pointer args eliminated");
Chris Lattner483ae012004-03-07 21:29:54 +000053
Chris Lattner1631bcb2006-12-19 22:09:18 +000054namespace {
Chris Lattner483ae012004-03-07 21:29:54 +000055 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
56 ///
Chris Lattner37b6c4f2004-09-18 00:34:13 +000057 struct ArgPromotion : public CallGraphSCCPass {
Chris Lattner483ae012004-03-07 21:29:54 +000058 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
59 AU.addRequired<AliasAnalysis>();
60 AU.addRequired<TargetData>();
Chris Lattner37b6c4f2004-09-18 00:34:13 +000061 CallGraphSCCPass::getAnalysisUsage(AU);
Chris Lattner483ae012004-03-07 21:29:54 +000062 }
63
Chris Lattner37b6c4f2004-09-18 00:34:13 +000064 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
Chris Lattner483ae012004-03-07 21:29:54 +000065 private:
Chris Lattner37b6c4f2004-09-18 00:34:13 +000066 bool PromoteArguments(CallGraphNode *CGN);
Misha Brukmanb1c93172005-04-21 23:48:37 +000067 bool isSafeToPromoteArgument(Argument *Arg) const;
Chris Lattner37b6c4f2004-09-18 00:34:13 +000068 Function *DoPromotion(Function *F, std::vector<Argument*> &ArgsToPromote);
Chris Lattner483ae012004-03-07 21:29:54 +000069 };
70
Chris Lattnerc2d3d312006-08-27 22:42:52 +000071 RegisterPass<ArgPromotion> X("argpromotion",
72 "Promote 'by reference' arguments to scalars");
Chris Lattner483ae012004-03-07 21:29:54 +000073}
74
Chris Lattner4f2cf032004-09-20 04:48:05 +000075ModulePass *llvm::createArgumentPromotionPass() {
Chris Lattner483ae012004-03-07 21:29:54 +000076 return new ArgPromotion();
77}
78
Chris Lattner37b6c4f2004-09-18 00:34:13 +000079bool ArgPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
80 bool Changed = false, LocalChange;
Chris Lattner483ae012004-03-07 21:29:54 +000081
Chris Lattner9864df92004-09-19 01:05:16 +000082 do { // Iterate until we stop promoting from this SCC.
Chris Lattner37b6c4f2004-09-18 00:34:13 +000083 LocalChange = false;
84 // Attempt to promote arguments from all functions in this SCC.
85 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
86 LocalChange |= PromoteArguments(SCC[i]);
87 Changed |= LocalChange; // Remember that we changed something.
88 } while (LocalChange);
Misha Brukmanb1c93172005-04-21 23:48:37 +000089
Chris Lattner483ae012004-03-07 21:29:54 +000090 return Changed;
91}
92
Chris Lattner254f8f82004-05-23 21:21:17 +000093/// PromoteArguments - This method checks the specified function to see if there
94/// are any promotable arguments and if it is safe to promote the function (for
95/// example, all callers are direct). If safe to promote some arguments, it
96/// calls the DoPromotion method.
97///
Chris Lattner37b6c4f2004-09-18 00:34:13 +000098bool ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
99 Function *F = CGN->getFunction();
100
101 // Make sure that it is local to this module.
102 if (!F || !F->hasInternalLinkage()) return false;
Chris Lattner483ae012004-03-07 21:29:54 +0000103
104 // First check: see if there are any pointer arguments! If not, quick exit.
105 std::vector<Argument*> PointerArgs;
Chris Lattner531f9e92005-03-15 04:54:21 +0000106 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattner483ae012004-03-07 21:29:54 +0000107 if (isa<PointerType>(I->getType()))
108 PointerArgs.push_back(I);
109 if (PointerArgs.empty()) return false;
110
111 // Second check: make sure that all callers are direct callers. We can't
112 // transform functions that have indirect callers.
113 for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
Chris Lattner64b8d692004-03-07 22:43:27 +0000114 UI != E; ++UI) {
115 CallSite CS = CallSite::get(*UI);
Chris Lattner254f8f82004-05-23 21:21:17 +0000116 if (!CS.getInstruction()) // "Taking the address" of the function
117 return false;
118
119 // Ensure that this call site is CALLING the function, not passing it as
120 // an argument.
121 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
122 AI != E; ++AI)
123 if (*AI == F) return false; // Passing the function address in!
Chris Lattner64b8d692004-03-07 22:43:27 +0000124 }
Chris Lattner483ae012004-03-07 21:29:54 +0000125
126 // Check to see which arguments are promotable. If an argument is not
127 // promotable, remove it from the PointerArgs vector.
128 for (unsigned i = 0; i != PointerArgs.size(); ++i)
129 if (!isSafeToPromoteArgument(PointerArgs[i])) {
130 std::swap(PointerArgs[i--], PointerArgs.back());
131 PointerArgs.pop_back();
132 }
133
134 // No promotable pointer arguments.
135 if (PointerArgs.empty()) return false;
136
137 // Okay, promote all of the arguments are rewrite the callees!
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000138 Function *NewF = DoPromotion(F, PointerArgs);
139
140 // Update the call graph to know that the old function is gone.
141 getAnalysis<CallGraph>().changeFunction(F, NewF);
Chris Lattner483ae012004-03-07 21:29:54 +0000142 return true;
143}
144
Chris Lattner244031d2004-11-13 23:31:34 +0000145/// IsAlwaysValidPointer - Return true if the specified pointer is always legal
146/// to load.
147static bool IsAlwaysValidPointer(Value *V) {
148 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
149 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V))
150 return IsAlwaysValidPointer(GEP->getOperand(0));
151 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
152 if (CE->getOpcode() == Instruction::GetElementPtr)
153 return IsAlwaysValidPointer(CE->getOperand(0));
154
155 return false;
156}
157
158/// AllCalleesPassInValidPointerForArgument - Return true if we can prove that
159/// all callees pass in a valid pointer for the specified function argument.
160static bool AllCalleesPassInValidPointerForArgument(Argument *Arg) {
161 Function *Callee = Arg->getParent();
162
Chris Lattner531f9e92005-03-15 04:54:21 +0000163 unsigned ArgNo = std::distance(Callee->arg_begin(), Function::arg_iterator(Arg));
Chris Lattner244031d2004-11-13 23:31:34 +0000164
165 // Look at all call sites of the function. At this pointer we know we only
166 // have direct callees.
167 for (Value::use_iterator UI = Callee->use_begin(), E = Callee->use_end();
168 UI != E; ++UI) {
169 CallSite CS = CallSite::get(*UI);
170 assert(CS.getInstruction() && "Should only have direct calls!");
171
172 if (!IsAlwaysValidPointer(CS.getArgument(ArgNo)))
173 return false;
174 }
175 return true;
176}
177
Chris Lattner254f8f82004-05-23 21:21:17 +0000178
179/// isSafeToPromoteArgument - As you might guess from the name of this method,
180/// it checks to see if it is both safe and useful to promote the argument.
181/// This method limits promotion of aggregates to only promote up to three
182/// elements of the aggregate in order to avoid exploding the number of
183/// arguments passed in.
Chris Lattner483ae012004-03-07 21:29:54 +0000184bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg) const {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000185 // We can only promote this argument if all of the uses are loads, or are GEP
186 // instructions (with constant indices) that are subsequently loaded.
Chris Lattner244031d2004-11-13 23:31:34 +0000187 bool HasLoadInEntryBlock = false;
188 BasicBlock *EntryBlock = Arg->getParent()->begin();
Chris Lattner483ae012004-03-07 21:29:54 +0000189 std::vector<LoadInst*> Loads;
Chris Lattner1c676f72004-06-21 00:07:58 +0000190 std::vector<std::vector<ConstantInt*> > GEPIndices;
Chris Lattner483ae012004-03-07 21:29:54 +0000191 for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
192 UI != E; ++UI)
193 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
194 if (LI->isVolatile()) return false; // Don't hack volatile loads
195 Loads.push_back(LI);
Chris Lattner244031d2004-11-13 23:31:34 +0000196 HasLoadInEntryBlock |= LI->getParent() == EntryBlock;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000197 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
198 if (GEP->use_empty()) {
199 // Dead GEP's cause trouble later. Just remove them if we run into
200 // them.
Chris Lattner254f8f82004-05-23 21:21:17 +0000201 getAnalysis<AliasAnalysis>().deleteValue(GEP);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000202 GEP->getParent()->getInstList().erase(GEP);
203 return isSafeToPromoteArgument(Arg);
204 }
205 // Ensure that all of the indices are constants.
Chris Lattner1c676f72004-06-21 00:07:58 +0000206 std::vector<ConstantInt*> Operands;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000207 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
Chris Lattner1c676f72004-06-21 00:07:58 +0000208 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000209 Operands.push_back(C);
210 else
211 return false; // Not a constant operand GEP!
212
213 // Ensure that the only users of the GEP are load instructions.
214 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
215 UI != E; ++UI)
216 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
217 if (LI->isVolatile()) return false; // Don't hack volatile loads
218 Loads.push_back(LI);
Chris Lattner244031d2004-11-13 23:31:34 +0000219 HasLoadInEntryBlock |= LI->getParent() == EntryBlock;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000220 } else {
221 return false;
222 }
223
Chris Lattner254f8f82004-05-23 21:21:17 +0000224 // See if there is already a GEP with these indices. If not, check to
225 // make sure that we aren't promoting too many elements. If so, nothing
226 // to do.
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000227 if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
228 GEPIndices.end()) {
229 if (GEPIndices.size() == 3) {
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000230 DOUT << "argpromotion disable promoting argument '"
231 << Arg->getName() << "' because it would require adding more "
232 << "than 3 arguments to the function.\n";
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000233 // We limit aggregate promotion to only promoting up to three elements
234 // of the aggregate.
235 return false;
236 }
237 GEPIndices.push_back(Operands);
238 }
239 } else {
240 return false; // Not a load or a GEP.
241 }
Chris Lattner483ae012004-03-07 21:29:54 +0000242
Chris Lattner254f8f82004-05-23 21:21:17 +0000243 if (Loads.empty()) return true; // No users, this is a dead argument.
Chris Lattner483ae012004-03-07 21:29:54 +0000244
Chris Lattner244031d2004-11-13 23:31:34 +0000245 // If we decide that we want to promote this argument, the value is going to
246 // be unconditionally loaded in all callees. This is only safe to do if the
247 // pointer was going to be unconditionally loaded anyway (i.e. there is a load
248 // of the pointer in the entry block of the function) or if we can prove that
249 // all pointers passed in are always to legal locations (for example, no null
250 // pointers are passed in, no pointers to free'd memory, etc).
Evan Chengff510a52006-10-03 07:26:07 +0000251 if (!HasLoadInEntryBlock && !AllCalleesPassInValidPointerForArgument(Arg))
Chris Lattner244031d2004-11-13 23:31:34 +0000252 return false; // Cannot prove that this is safe!!
253
254 // Okay, now we know that the argument is only used by load instructions and
255 // it is safe to unconditionally load the pointer. Use alias analysis to
256 // check to see if the pointer is guaranteed to not be modified from entry of
257 // the function to each of the load instructions.
Chris Lattner483ae012004-03-07 21:29:54 +0000258
259 // Because there could be several/many load instructions, remember which
260 // blocks we know to be transparent to the load.
261 std::set<BasicBlock*> TranspBlocks;
Owen Andersonedadd3f2006-09-15 05:22:51 +0000262
263 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000264 TargetData &TD = getAnalysis<TargetData>();
Chris Lattner483ae012004-03-07 21:29:54 +0000265
266 for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
267 // Check to see if the load is invalidated from the start of the block to
268 // the load itself.
269 LoadInst *Load = Loads[i];
270 BasicBlock *BB = Load->getParent();
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000271
272 const PointerType *LoadTy =
273 cast<PointerType>(Load->getOperand(0)->getType());
Chris Lattner46fa04b2005-01-08 19:45:31 +0000274 unsigned LoadSize = (unsigned)TD.getTypeSize(LoadTy->getElementType());
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000275
Chris Lattner483ae012004-03-07 21:29:54 +0000276 if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
277 return false; // Pointer is invalidated!
278
279 // Now check every path from the entry block to the load for transparency.
280 // To do this, we perform a depth first search on the inverse CFG from the
281 // loading block.
282 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
283 for (idf_ext_iterator<BasicBlock*> I = idf_ext_begin(*PI, TranspBlocks),
284 E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
285 if (AA.canBasicBlockModify(**I, Arg, LoadSize))
286 return false;
287 }
288
289 // If the path from the entry of the function to each load is free of
290 // instructions that potentially invalidate the load, we can make the
291 // transformation!
292 return true;
293}
294
Chris Lattner1c676f72004-06-21 00:07:58 +0000295namespace {
296 /// GEPIdxComparator - Provide a strong ordering for GEP indices. All Value*
297 /// elements are instances of ConstantInt.
298 ///
299 struct GEPIdxComparator {
300 bool operator()(const std::vector<Value*> &LHS,
301 const std::vector<Value*> &RHS) const {
302 unsigned idx = 0;
303 for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
304 if (LHS[idx] != RHS[idx]) {
Reid Spencere0fc4df2006-10-20 07:07:24 +0000305 return cast<ConstantInt>(LHS[idx])->getZExtValue() <
306 cast<ConstantInt>(RHS[idx])->getZExtValue();
Chris Lattner1c676f72004-06-21 00:07:58 +0000307 }
308 }
309
310 // Return less than if we ran out of stuff in LHS and we didn't run out of
311 // stuff in RHS.
312 return idx == LHS.size() && idx != RHS.size();
313 }
314 };
315}
316
317
Chris Lattner254f8f82004-05-23 21:21:17 +0000318/// DoPromotion - This method actually performs the promotion of the specified
Chris Lattner37b6c4f2004-09-18 00:34:13 +0000319/// arguments, and returns the new function. At this point, we know that it's
320/// safe to do so.
321Function *ArgPromotion::DoPromotion(Function *F,
322 std::vector<Argument*> &Args2Prom) {
Chris Lattner483ae012004-03-07 21:29:54 +0000323 std::set<Argument*> ArgsToPromote(Args2Prom.begin(), Args2Prom.end());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000324
Chris Lattner483ae012004-03-07 21:29:54 +0000325 // Start by computing a new prototype for the function, which is the same as
326 // the old function, but has modified arguments.
327 const FunctionType *FTy = F->getFunctionType();
328 std::vector<const Type*> Params;
329
Chris Lattner1c676f72004-06-21 00:07:58 +0000330 typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
331
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000332 // ScalarizedElements - If we are promoting a pointer that has elements
333 // accessed out of it, keep track of which elements are accessed so that we
334 // can add one argument for each.
335 //
336 // Arguments that are directly loaded will have a zero element value here, to
337 // handle cases where there are both a direct load and GEP accesses.
338 //
Chris Lattner1c676f72004-06-21 00:07:58 +0000339 std::map<Argument*, ScalarizeTable> ScalarizedElements;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000340
Chris Lattner254f8f82004-05-23 21:21:17 +0000341 // OriginalLoads - Keep track of a representative load instruction from the
342 // original function so that we can tell the alias analysis implementation
343 // what the new GEP/Load instructions we are inserting look like.
344 std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
345
Chris Lattner531f9e92005-03-15 04:54:21 +0000346 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattner483ae012004-03-07 21:29:54 +0000347 if (!ArgsToPromote.count(I)) {
348 Params.push_back(I->getType());
Chris Lattner254f8f82004-05-23 21:21:17 +0000349 } else if (I->use_empty()) {
350 ++NumArgumentsDead;
351 } else {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000352 // Okay, this is being promoted. Check to see if there are any GEP uses
353 // of the argument.
Chris Lattner1c676f72004-06-21 00:07:58 +0000354 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000355 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
356 ++UI) {
357 Instruction *User = cast<Instruction>(*UI);
Owen Andersonedadd3f2006-09-15 05:22:51 +0000358 assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
359 std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
360 ArgIndices.insert(Indices);
361 LoadInst *OrigLoad;
362 if (LoadInst *L = dyn_cast<LoadInst>(User))
363 OrigLoad = L;
364 else
365 OrigLoad = cast<LoadInst>(User->use_back());
366 OriginalLoads[Indices] = OrigLoad;
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000367 }
368
369 // Add a parameter to the function for each element passed in.
Chris Lattner1c676f72004-06-21 00:07:58 +0000370 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000371 E = ArgIndices.end(); SI != E; ++SI)
372 Params.push_back(GetElementPtrInst::getIndexedType(I->getType(), *SI));
373
374 if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
375 ++NumArgumentsPromoted;
376 else
377 ++NumAggregatesPromoted;
Chris Lattner483ae012004-03-07 21:29:54 +0000378 }
379
380 const Type *RetTy = FTy->getReturnType();
381
382 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
383 // have zero fixed arguments.
384 bool ExtraArgHack = false;
385 if (Params.empty() && FTy->isVarArg()) {
386 ExtraArgHack = true;
Reid Spencerc635f472006-12-31 05:48:39 +0000387 Params.push_back(Type::Int32Ty);
Chris Lattner483ae012004-03-07 21:29:54 +0000388 }
389 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000390
Chris Lattner483ae012004-03-07 21:29:54 +0000391 // Create the new function body and insert it into the module...
392 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
Chris Lattnerd0525a22005-05-09 01:05:50 +0000393 NF->setCallingConv(F->getCallingConv());
Chris Lattner483ae012004-03-07 21:29:54 +0000394 F->getParent()->getFunctionList().insert(F, NF);
Chris Lattner254f8f82004-05-23 21:21:17 +0000395
396 // Get the alias analysis information that we need to update to reflect our
397 // changes.
398 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
399
Chris Lattner483ae012004-03-07 21:29:54 +0000400 // Loop over all of the callers of the function, transforming the call sites
401 // to pass in the loaded pointers.
402 //
403 std::vector<Value*> Args;
404 while (!F->use_empty()) {
405 CallSite CS = CallSite::get(F->use_back());
406 Instruction *Call = CS.getInstruction();
407
Chris Lattner254f8f82004-05-23 21:21:17 +0000408 // Loop over the operands, inserting GEP and loads in the caller as
409 // appropriate.
Chris Lattner483ae012004-03-07 21:29:54 +0000410 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattnerd0525a22005-05-09 01:05:50 +0000411 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
412 I != E; ++I, ++AI)
Chris Lattner483ae012004-03-07 21:29:54 +0000413 if (!ArgsToPromote.count(I))
414 Args.push_back(*AI); // Unmodified argument
415 else if (!I->use_empty()) {
Chris Lattner254f8f82004-05-23 21:21:17 +0000416 // Non-dead argument: insert GEPs and loads as appropriate.
Chris Lattner1c676f72004-06-21 00:07:58 +0000417 ScalarizeTable &ArgIndices = ScalarizedElements[I];
418 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000419 E = ArgIndices.end(); SI != E; ++SI) {
420 Value *V = *AI;
Chris Lattner254f8f82004-05-23 21:21:17 +0000421 LoadInst *OrigLoad = OriginalLoads[*SI];
422 if (!SI->empty()) {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000423 V = new GetElementPtrInst(V, *SI, V->getName()+".idx", Call);
Chris Lattner254f8f82004-05-23 21:21:17 +0000424 AA.copyValue(OrigLoad->getOperand(0), V);
425 }
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000426 Args.push_back(new LoadInst(V, V->getName()+".val", Call));
Chris Lattner254f8f82004-05-23 21:21:17 +0000427 AA.copyValue(OrigLoad, Args.back());
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000428 }
Chris Lattner483ae012004-03-07 21:29:54 +0000429 }
430
431 if (ExtraArgHack)
Reid Spencerc635f472006-12-31 05:48:39 +0000432 Args.push_back(Constant::getNullValue(Type::Int32Ty));
Chris Lattner483ae012004-03-07 21:29:54 +0000433
434 // Push any varargs arguments on the list
435 for (; AI != CS.arg_end(); ++AI)
436 Args.push_back(*AI);
437
438 Instruction *New;
439 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
440 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
441 Args, "", Call);
Chris Lattnerd0525a22005-05-09 01:05:50 +0000442 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner483ae012004-03-07 21:29:54 +0000443 } else {
444 New = new CallInst(NF, Args, "", Call);
Chris Lattnerd0525a22005-05-09 01:05:50 +0000445 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner324d2ee2005-05-06 06:46:58 +0000446 if (cast<CallInst>(Call)->isTailCall())
447 cast<CallInst>(New)->setTailCall();
Chris Lattner483ae012004-03-07 21:29:54 +0000448 }
449 Args.clear();
450
Chris Lattner254f8f82004-05-23 21:21:17 +0000451 // Update the alias analysis implementation to know that we are replacing
452 // the old call with a new one.
453 AA.replaceWithNewValue(Call, New);
454
Chris Lattner483ae012004-03-07 21:29:54 +0000455 if (!Call->use_empty()) {
456 Call->replaceAllUsesWith(New);
457 std::string Name = Call->getName();
458 Call->setName("");
459 New->setName(Name);
460 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000461
Chris Lattner483ae012004-03-07 21:29:54 +0000462 // Finally, remove the old call from the program, reducing the use-count of
463 // F.
464 Call->getParent()->getInstList().erase(Call);
465 }
466
467 // Since we have now created the new function, splice the body of the old
468 // function right into the new function, leaving the old rotting hulk of the
469 // function empty.
470 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
471
472 // Loop over the argument list, transfering uses of the old arguments over to
473 // the new arguments, also transfering over the names as well.
474 //
Chris Lattner531f9e92005-03-15 04:54:21 +0000475 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(), I2 = NF->arg_begin();
Chris Lattner483ae012004-03-07 21:29:54 +0000476 I != E; ++I)
477 if (!ArgsToPromote.count(I)) {
478 // If this is an unmodified argument, move the name and users over to the
479 // new version.
480 I->replaceAllUsesWith(I2);
481 I2->setName(I->getName());
Chris Lattner254f8f82004-05-23 21:21:17 +0000482 AA.replaceWithNewValue(I, I2);
Chris Lattner483ae012004-03-07 21:29:54 +0000483 ++I2;
Chris Lattner254f8f82004-05-23 21:21:17 +0000484 } else if (I->use_empty()) {
485 AA.deleteValue(I);
486 } else {
Chris Lattner483ae012004-03-07 21:29:54 +0000487 // Otherwise, if we promoted this argument, then all users are load
488 // instructions, and all loads should be using the new argument that we
489 // added.
Chris Lattner1c676f72004-06-21 00:07:58 +0000490 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000491
Chris Lattner483ae012004-03-07 21:29:54 +0000492 while (!I->use_empty()) {
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000493 if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
494 assert(ArgIndices.begin()->empty() &&
495 "Load element should sort to front!");
496 I2->setName(I->getName()+".val");
497 LI->replaceAllUsesWith(I2);
Chris Lattner254f8f82004-05-23 21:21:17 +0000498 AA.replaceWithNewValue(LI, I2);
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000499 LI->getParent()->getInstList().erase(LI);
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000500 DOUT << "*** Promoted load of argument '" << I->getName()
501 << "' in function '" << F->getName() << "'\n";
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000502 } else {
503 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
504 std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
505
Chris Lattner531f9e92005-03-15 04:54:21 +0000506 Function::arg_iterator 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]))
Reid Spencere0fc4df2006-10-20 07:07:24 +0000515 NewName += "."+itostr((int64_t)CI->getZExtValue());
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000516 else
517 NewName += ".x";
518 TheArg->setName(NewName+".val");
519
Bill Wendling8f13b5c2006-11-26 10:02:32 +0000520 DOUT << "*** Promoted agg argument '" << TheArg->getName()
521 << "' of function '" << F->getName() << "'\n";
Chris Lattnerfe6f2e32004-03-08 01:04:36 +0000522
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)
Reid Spencerc635f472006-12-31 05:48:39 +0000543 AA.copyValue(Constant::getNullValue(Type::Int32Ty), NF->arg_begin());
Chris Lattner254f8f82004-05-23 21:21:17 +0000544
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}