blob: 5a6b466d9e9fd0db351deab1cd28cb086552f638 [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"
Reid Spencer9133fe22007-02-05 23:32:05 +000047#include "llvm/Support/Compiler.h"
Chris Lattnered570a72004-03-07 21:29:54 +000048#include <set>
49using namespace llvm;
50
Chris Lattner86453c52006-12-19 22:09:18 +000051STATISTIC(NumArgumentsPromoted , "Number of pointer arguments promoted");
52STATISTIC(NumAggregatesPromoted, "Number of aggregate arguments promoted");
53STATISTIC(NumArgumentsDead , "Number of dead pointer args eliminated");
Chris Lattnered570a72004-03-07 21:29:54 +000054
Chris Lattner86453c52006-12-19 22:09:18 +000055namespace {
Chris Lattnered570a72004-03-07 21:29:54 +000056 /// ArgPromotion - The 'by reference' to 'by value' argument promotion pass.
57 ///
Reid Spencer9133fe22007-02-05 23:32:05 +000058 struct VISIBILITY_HIDDEN ArgPromotion : public CallGraphSCCPass {
Chris Lattnered570a72004-03-07 21:29:54 +000059 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
60 AU.addRequired<AliasAnalysis>();
61 AU.addRequired<TargetData>();
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000062 CallGraphSCCPass::getAnalysisUsage(AU);
Chris Lattnered570a72004-03-07 21:29:54 +000063 }
64
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000065 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
Devang Patel19974732007-05-03 01:11:54 +000066 static char ID; // Pass identifcation, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000067 ArgPromotion() : CallGraphSCCPass((intptr_t)&ID) {}
68
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
Devang Patel19974732007-05-03 01:11:54 +000075 char ArgPromotion::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +000076 RegisterPass<ArgPromotion> X("argpromotion",
77 "Promote 'by reference' arguments to scalars");
Chris Lattnered570a72004-03-07 21:29:54 +000078}
79
Devang Patelc71ca3c2007-01-26 00:47:38 +000080Pass *llvm::createArgumentPromotionPass() {
Chris Lattnered570a72004-03-07 21:29:54 +000081 return new ArgPromotion();
82}
83
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000084bool ArgPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
85 bool Changed = false, LocalChange;
Chris Lattnered570a72004-03-07 21:29:54 +000086
Chris Lattnerf5afcab2004-09-19 01:05:16 +000087 do { // Iterate until we stop promoting from this SCC.
Chris Lattner5eb6f6c2004-09-18 00:34:13 +000088 LocalChange = false;
89 // Attempt to promote arguments from all functions in this SCC.
90 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
91 LocalChange |= PromoteArguments(SCC[i]);
92 Changed |= LocalChange; // Remember that we changed something.
93 } while (LocalChange);
Misha Brukmanfd939082005-04-21 23:48:37 +000094
Chris Lattnered570a72004-03-07 21:29:54 +000095 return Changed;
96}
97
Chris Lattner9e7cc2f2004-05-23 21:21:17 +000098/// PromoteArguments - This method checks the specified function to see if there
99/// are any promotable arguments and if it is safe to promote the function (for
100/// example, all callers are direct). If safe to promote some arguments, it
101/// calls the DoPromotion method.
102///
Chris Lattner5eb6f6c2004-09-18 00:34:13 +0000103bool ArgPromotion::PromoteArguments(CallGraphNode *CGN) {
104 Function *F = CGN->getFunction();
105
106 // Make sure that it is local to this module.
107 if (!F || !F->hasInternalLinkage()) return false;
Chris Lattnered570a72004-03-07 21:29:54 +0000108
109 // First check: see if there are any pointer arguments! If not, quick exit.
110 std::vector<Argument*> PointerArgs;
Chris Lattnere4d5c442005-03-15 04:54:21 +0000111 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnered570a72004-03-07 21:29:54 +0000112 if (isa<PointerType>(I->getType()))
113 PointerArgs.push_back(I);
114 if (PointerArgs.empty()) return false;
115
116 // Second check: make sure that all callers are direct callers. We can't
117 // transform functions that have indirect callers.
118 for (Value::use_iterator UI = F->use_begin(), E = F->use_end();
Chris Lattner7db5a6d2004-03-07 22:43:27 +0000119 UI != E; ++UI) {
120 CallSite CS = CallSite::get(*UI);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000121 if (!CS.getInstruction()) // "Taking the address" of the function
122 return false;
123
124 // Ensure that this call site is CALLING the function, not passing it as
125 // an argument.
126 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
127 AI != E; ++AI)
128 if (*AI == F) return false; // Passing the function address in!
Chris Lattner7db5a6d2004-03-07 22:43:27 +0000129 }
Chris Lattnered570a72004-03-07 21:29:54 +0000130
131 // Check to see which arguments are promotable. If an argument is not
132 // promotable, remove it from the PointerArgs vector.
133 for (unsigned i = 0; i != PointerArgs.size(); ++i)
134 if (!isSafeToPromoteArgument(PointerArgs[i])) {
135 std::swap(PointerArgs[i--], PointerArgs.back());
136 PointerArgs.pop_back();
137 }
138
139 // No promotable pointer arguments.
140 if (PointerArgs.empty()) return false;
141
142 // Okay, promote all of the arguments are rewrite the callees!
Chris Lattner5eb6f6c2004-09-18 00:34:13 +0000143 Function *NewF = DoPromotion(F, PointerArgs);
144
145 // Update the call graph to know that the old function is gone.
146 getAnalysis<CallGraph>().changeFunction(F, NewF);
Chris Lattnered570a72004-03-07 21:29:54 +0000147 return true;
148}
149
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000150/// IsAlwaysValidPointer - Return true if the specified pointer is always legal
151/// to load.
152static bool IsAlwaysValidPointer(Value *V) {
153 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
154 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V))
155 return IsAlwaysValidPointer(GEP->getOperand(0));
156 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
157 if (CE->getOpcode() == Instruction::GetElementPtr)
158 return IsAlwaysValidPointer(CE->getOperand(0));
159
160 return false;
161}
162
163/// AllCalleesPassInValidPointerForArgument - Return true if we can prove that
164/// all callees pass in a valid pointer for the specified function argument.
165static bool AllCalleesPassInValidPointerForArgument(Argument *Arg) {
166 Function *Callee = Arg->getParent();
167
Chris Lattner93e985f2007-02-13 02:10:56 +0000168 unsigned ArgNo = std::distance(Callee->arg_begin(),
169 Function::arg_iterator(Arg));
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000170
171 // Look at all call sites of the function. At this pointer we know we only
172 // have direct callees.
173 for (Value::use_iterator UI = Callee->use_begin(), E = Callee->use_end();
174 UI != E; ++UI) {
175 CallSite CS = CallSite::get(*UI);
176 assert(CS.getInstruction() && "Should only have direct calls!");
177
178 if (!IsAlwaysValidPointer(CS.getArgument(ArgNo)))
179 return false;
180 }
181 return true;
182}
183
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000184
185/// isSafeToPromoteArgument - As you might guess from the name of this method,
186/// it checks to see if it is both safe and useful to promote the argument.
187/// This method limits promotion of aggregates to only promote up to three
188/// elements of the aggregate in order to avoid exploding the number of
189/// arguments passed in.
Chris Lattnered570a72004-03-07 21:29:54 +0000190bool ArgPromotion::isSafeToPromoteArgument(Argument *Arg) const {
Chris Lattner9440db82004-03-08 01:04:36 +0000191 // We can only promote this argument if all of the uses are loads, or are GEP
192 // instructions (with constant indices) that are subsequently loaded.
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000193 bool HasLoadInEntryBlock = false;
194 BasicBlock *EntryBlock = Arg->getParent()->begin();
Chris Lattnered570a72004-03-07 21:29:54 +0000195 std::vector<LoadInst*> Loads;
Chris Lattnerbeabf452004-06-21 00:07:58 +0000196 std::vector<std::vector<ConstantInt*> > GEPIndices;
Chris Lattnered570a72004-03-07 21:29:54 +0000197 for (Value::use_iterator UI = Arg->use_begin(), E = Arg->use_end();
198 UI != E; ++UI)
199 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
200 if (LI->isVolatile()) return false; // Don't hack volatile loads
201 Loads.push_back(LI);
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000202 HasLoadInEntryBlock |= LI->getParent() == EntryBlock;
Chris Lattner9440db82004-03-08 01:04:36 +0000203 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
204 if (GEP->use_empty()) {
205 // Dead GEP's cause trouble later. Just remove them if we run into
206 // them.
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000207 getAnalysis<AliasAnalysis>().deleteValue(GEP);
Chris Lattner9440db82004-03-08 01:04:36 +0000208 GEP->getParent()->getInstList().erase(GEP);
209 return isSafeToPromoteArgument(Arg);
210 }
211 // Ensure that all of the indices are constants.
Chris Lattnerbeabf452004-06-21 00:07:58 +0000212 std::vector<ConstantInt*> Operands;
Chris Lattner9440db82004-03-08 01:04:36 +0000213 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
Chris Lattnerbeabf452004-06-21 00:07:58 +0000214 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP->getOperand(i)))
Chris Lattner9440db82004-03-08 01:04:36 +0000215 Operands.push_back(C);
216 else
217 return false; // Not a constant operand GEP!
218
219 // Ensure that the only users of the GEP are load instructions.
220 for (Value::use_iterator UI = GEP->use_begin(), E = GEP->use_end();
221 UI != E; ++UI)
222 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
223 if (LI->isVolatile()) return false; // Don't hack volatile loads
224 Loads.push_back(LI);
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000225 HasLoadInEntryBlock |= LI->getParent() == EntryBlock;
Chris Lattner9440db82004-03-08 01:04:36 +0000226 } else {
227 return false;
228 }
229
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000230 // See if there is already a GEP with these indices. If not, check to
231 // make sure that we aren't promoting too many elements. If so, nothing
232 // to do.
Chris Lattner9440db82004-03-08 01:04:36 +0000233 if (std::find(GEPIndices.begin(), GEPIndices.end(), Operands) ==
234 GEPIndices.end()) {
235 if (GEPIndices.size() == 3) {
Bill Wendling0a81aac2006-11-26 10:02:32 +0000236 DOUT << "argpromotion disable promoting argument '"
237 << Arg->getName() << "' because it would require adding more "
238 << "than 3 arguments to the function.\n";
Chris Lattner9440db82004-03-08 01:04:36 +0000239 // We limit aggregate promotion to only promoting up to three elements
240 // of the aggregate.
241 return false;
242 }
243 GEPIndices.push_back(Operands);
244 }
245 } else {
246 return false; // Not a load or a GEP.
247 }
Chris Lattnered570a72004-03-07 21:29:54 +0000248
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000249 if (Loads.empty()) return true; // No users, this is a dead argument.
Chris Lattnered570a72004-03-07 21:29:54 +0000250
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000251 // If we decide that we want to promote this argument, the value is going to
252 // be unconditionally loaded in all callees. This is only safe to do if the
253 // pointer was going to be unconditionally loaded anyway (i.e. there is a load
254 // of the pointer in the entry block of the function) or if we can prove that
255 // all pointers passed in are always to legal locations (for example, no null
256 // pointers are passed in, no pointers to free'd memory, etc).
Evan Cheng99435d32006-10-03 07:26:07 +0000257 if (!HasLoadInEntryBlock && !AllCalleesPassInValidPointerForArgument(Arg))
Chris Lattner11a3d7b2004-11-13 23:31:34 +0000258 return false; // Cannot prove that this is safe!!
259
260 // Okay, now we know that the argument is only used by load instructions and
261 // it is safe to unconditionally load the pointer. Use alias analysis to
262 // check to see if the pointer is guaranteed to not be modified from entry of
263 // the function to each of the load instructions.
Chris Lattnered570a72004-03-07 21:29:54 +0000264
265 // Because there could be several/many load instructions, remember which
266 // blocks we know to be transparent to the load.
267 std::set<BasicBlock*> TranspBlocks;
Owen Anderson46f022a2006-09-15 05:22:51 +0000268
269 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
Chris Lattner9440db82004-03-08 01:04:36 +0000270 TargetData &TD = getAnalysis<TargetData>();
Chris Lattnered570a72004-03-07 21:29:54 +0000271
272 for (unsigned i = 0, e = Loads.size(); i != e; ++i) {
273 // Check to see if the load is invalidated from the start of the block to
274 // the load itself.
275 LoadInst *Load = Loads[i];
276 BasicBlock *BB = Load->getParent();
Chris Lattner9440db82004-03-08 01:04:36 +0000277
278 const PointerType *LoadTy =
279 cast<PointerType>(Load->getOperand(0)->getType());
Chris Lattner4d0801b2005-01-08 19:45:31 +0000280 unsigned LoadSize = (unsigned)TD.getTypeSize(LoadTy->getElementType());
Chris Lattner9440db82004-03-08 01:04:36 +0000281
Chris Lattnered570a72004-03-07 21:29:54 +0000282 if (AA.canInstructionRangeModify(BB->front(), *Load, Arg, LoadSize))
283 return false; // Pointer is invalidated!
284
285 // Now check every path from the entry block to the load for transparency.
286 // To do this, we perform a depth first search on the inverse CFG from the
287 // loading block.
288 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
289 for (idf_ext_iterator<BasicBlock*> I = idf_ext_begin(*PI, TranspBlocks),
290 E = idf_ext_end(*PI, TranspBlocks); I != E; ++I)
291 if (AA.canBasicBlockModify(**I, Arg, LoadSize))
292 return false;
293 }
294
295 // If the path from the entry of the function to each load is free of
296 // instructions that potentially invalidate the load, we can make the
297 // transformation!
298 return true;
299}
300
Chris Lattnerbeabf452004-06-21 00:07:58 +0000301namespace {
302 /// GEPIdxComparator - Provide a strong ordering for GEP indices. All Value*
303 /// elements are instances of ConstantInt.
304 ///
305 struct GEPIdxComparator {
306 bool operator()(const std::vector<Value*> &LHS,
307 const std::vector<Value*> &RHS) const {
308 unsigned idx = 0;
309 for (; idx < LHS.size() && idx < RHS.size(); ++idx) {
310 if (LHS[idx] != RHS[idx]) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000311 return cast<ConstantInt>(LHS[idx])->getZExtValue() <
312 cast<ConstantInt>(RHS[idx])->getZExtValue();
Chris Lattnerbeabf452004-06-21 00:07:58 +0000313 }
314 }
315
316 // Return less than if we ran out of stuff in LHS and we didn't run out of
317 // stuff in RHS.
318 return idx == LHS.size() && idx != RHS.size();
319 }
320 };
321}
322
323
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000324/// DoPromotion - This method actually performs the promotion of the specified
Chris Lattner5eb6f6c2004-09-18 00:34:13 +0000325/// arguments, and returns the new function. At this point, we know that it's
326/// safe to do so.
327Function *ArgPromotion::DoPromotion(Function *F,
328 std::vector<Argument*> &Args2Prom) {
Chris Lattnered570a72004-03-07 21:29:54 +0000329 std::set<Argument*> ArgsToPromote(Args2Prom.begin(), Args2Prom.end());
Misha Brukmanfd939082005-04-21 23:48:37 +0000330
Chris Lattnered570a72004-03-07 21:29:54 +0000331 // Start by computing a new prototype for the function, which is the same as
332 // the old function, but has modified arguments.
333 const FunctionType *FTy = F->getFunctionType();
334 std::vector<const Type*> Params;
335
Chris Lattnerbeabf452004-06-21 00:07:58 +0000336 typedef std::set<std::vector<Value*>, GEPIdxComparator> ScalarizeTable;
337
Chris Lattner9440db82004-03-08 01:04:36 +0000338 // ScalarizedElements - If we are promoting a pointer that has elements
339 // accessed out of it, keep track of which elements are accessed so that we
340 // can add one argument for each.
341 //
342 // Arguments that are directly loaded will have a zero element value here, to
343 // handle cases where there are both a direct load and GEP accesses.
344 //
Chris Lattnerbeabf452004-06-21 00:07:58 +0000345 std::map<Argument*, ScalarizeTable> ScalarizedElements;
Chris Lattner9440db82004-03-08 01:04:36 +0000346
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000347 // OriginalLoads - Keep track of a representative load instruction from the
348 // original function so that we can tell the alias analysis implementation
349 // what the new GEP/Load instructions we are inserting look like.
350 std::map<std::vector<Value*>, LoadInst*> OriginalLoads;
351
Chris Lattnere4d5c442005-03-15 04:54:21 +0000352 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
Chris Lattnered570a72004-03-07 21:29:54 +0000353 if (!ArgsToPromote.count(I)) {
354 Params.push_back(I->getType());
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000355 } else if (I->use_empty()) {
356 ++NumArgumentsDead;
357 } else {
Chris Lattner9440db82004-03-08 01:04:36 +0000358 // Okay, this is being promoted. Check to see if there are any GEP uses
359 // of the argument.
Chris Lattnerbeabf452004-06-21 00:07:58 +0000360 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattner9440db82004-03-08 01:04:36 +0000361 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
362 ++UI) {
363 Instruction *User = cast<Instruction>(*UI);
Owen Anderson46f022a2006-09-15 05:22:51 +0000364 assert(isa<LoadInst>(User) || isa<GetElementPtrInst>(User));
365 std::vector<Value*> Indices(User->op_begin()+1, User->op_end());
366 ArgIndices.insert(Indices);
367 LoadInst *OrigLoad;
368 if (LoadInst *L = dyn_cast<LoadInst>(User))
369 OrigLoad = L;
370 else
371 OrigLoad = cast<LoadInst>(User->use_back());
372 OriginalLoads[Indices] = OrigLoad;
Chris Lattner9440db82004-03-08 01:04:36 +0000373 }
374
375 // Add a parameter to the function for each element passed in.
Chris Lattnerbeabf452004-06-21 00:07:58 +0000376 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattner9440db82004-03-08 01:04:36 +0000377 E = ArgIndices.end(); SI != E; ++SI)
Chris Lattner1ccd1852007-02-12 22:56:41 +0000378 Params.push_back(GetElementPtrInst::getIndexedType(I->getType(),
379 &(*SI)[0],
380 SI->size()));
Chris Lattner9440db82004-03-08 01:04:36 +0000381
382 if (ArgIndices.size() == 1 && ArgIndices.begin()->empty())
383 ++NumArgumentsPromoted;
384 else
385 ++NumAggregatesPromoted;
Chris Lattnered570a72004-03-07 21:29:54 +0000386 }
387
388 const Type *RetTy = FTy->getReturnType();
389
390 // Work around LLVM bug PR56: the CWriter cannot emit varargs functions which
391 // have zero fixed arguments.
392 bool ExtraArgHack = false;
393 if (Params.empty() && FTy->isVarArg()) {
394 ExtraArgHack = true;
Reid Spencerc5b206b2006-12-31 05:48:39 +0000395 Params.push_back(Type::Int32Ty);
Chris Lattnered570a72004-03-07 21:29:54 +0000396 }
397 FunctionType *NFTy = FunctionType::get(RetTy, Params, FTy->isVarArg());
Misha Brukmanfd939082005-04-21 23:48:37 +0000398
Chris Lattnered570a72004-03-07 21:29:54 +0000399 // Create the new function body and insert it into the module...
400 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000401 NF->setCallingConv(F->getCallingConv());
Chris Lattnered570a72004-03-07 21:29:54 +0000402 F->getParent()->getFunctionList().insert(F, NF);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000403
404 // Get the alias analysis information that we need to update to reflect our
405 // changes.
406 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
407
Chris Lattnered570a72004-03-07 21:29:54 +0000408 // Loop over all of the callers of the function, transforming the call sites
409 // to pass in the loaded pointers.
410 //
411 std::vector<Value*> Args;
412 while (!F->use_empty()) {
413 CallSite CS = CallSite::get(F->use_back());
414 Instruction *Call = CS.getInstruction();
415
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000416 // Loop over the operands, inserting GEP and loads in the caller as
417 // appropriate.
Chris Lattnered570a72004-03-07 21:29:54 +0000418 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000419 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
420 I != E; ++I, ++AI)
Chris Lattnered570a72004-03-07 21:29:54 +0000421 if (!ArgsToPromote.count(I))
422 Args.push_back(*AI); // Unmodified argument
423 else if (!I->use_empty()) {
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000424 // Non-dead argument: insert GEPs and loads as appropriate.
Chris Lattnerbeabf452004-06-21 00:07:58 +0000425 ScalarizeTable &ArgIndices = ScalarizedElements[I];
426 for (ScalarizeTable::iterator SI = ArgIndices.begin(),
Chris Lattner9440db82004-03-08 01:04:36 +0000427 E = ArgIndices.end(); SI != E; ++SI) {
428 Value *V = *AI;
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000429 LoadInst *OrigLoad = OriginalLoads[*SI];
430 if (!SI->empty()) {
Chris Lattner1ccd1852007-02-12 22:56:41 +0000431 V = new GetElementPtrInst(V, &(*SI)[0], SI->size(),
432 V->getName()+".idx", Call);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000433 AA.copyValue(OrigLoad->getOperand(0), V);
434 }
Chris Lattner9440db82004-03-08 01:04:36 +0000435 Args.push_back(new LoadInst(V, V->getName()+".val", Call));
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000436 AA.copyValue(OrigLoad, Args.back());
Chris Lattner9440db82004-03-08 01:04:36 +0000437 }
Chris Lattnered570a72004-03-07 21:29:54 +0000438 }
439
440 if (ExtraArgHack)
Reid Spencerc5b206b2006-12-31 05:48:39 +0000441 Args.push_back(Constant::getNullValue(Type::Int32Ty));
Chris Lattnered570a72004-03-07 21:29:54 +0000442
443 // Push any varargs arguments on the list
444 for (; AI != CS.arg_end(); ++AI)
445 Args.push_back(*AI);
446
447 Instruction *New;
448 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
449 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner93e985f2007-02-13 02:10:56 +0000450 &Args[0], Args.size(), "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000451 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattnered570a72004-03-07 21:29:54 +0000452 } else {
Chris Lattner93e985f2007-02-13 02:10:56 +0000453 New = new CallInst(NF, &Args[0], Args.size(), "", Call);
Chris Lattnerf201dbc2005-05-09 01:05:50 +0000454 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner1430ef12005-05-06 06:46:58 +0000455 if (cast<CallInst>(Call)->isTailCall())
456 cast<CallInst>(New)->setTailCall();
Chris Lattnered570a72004-03-07 21:29:54 +0000457 }
458 Args.clear();
459
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000460 // Update the alias analysis implementation to know that we are replacing
461 // the old call with a new one.
462 AA.replaceWithNewValue(Call, New);
463
Chris Lattnered570a72004-03-07 21:29:54 +0000464 if (!Call->use_empty()) {
465 Call->replaceAllUsesWith(New);
Chris Lattner046800a2007-02-11 01:08:35 +0000466 New->takeName(Call);
Chris Lattnered570a72004-03-07 21:29:54 +0000467 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000468
Chris Lattnered570a72004-03-07 21:29:54 +0000469 // Finally, remove the old call from the program, reducing the use-count of
470 // F.
471 Call->getParent()->getInstList().erase(Call);
472 }
473
474 // Since we have now created the new function, splice the body of the old
475 // function right into the new function, leaving the old rotting hulk of the
476 // function empty.
477 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
478
479 // Loop over the argument list, transfering uses of the old arguments over to
480 // the new arguments, also transfering over the names as well.
481 //
Chris Lattner93e985f2007-02-13 02:10:56 +0000482 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(),
483 I2 = NF->arg_begin(); I != E; ++I)
Chris Lattnered570a72004-03-07 21:29:54 +0000484 if (!ArgsToPromote.count(I)) {
485 // If this is an unmodified argument, move the name and users over to the
486 // new version.
487 I->replaceAllUsesWith(I2);
Chris Lattner046800a2007-02-11 01:08:35 +0000488 I2->takeName(I);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000489 AA.replaceWithNewValue(I, I2);
Chris Lattnered570a72004-03-07 21:29:54 +0000490 ++I2;
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000491 } else if (I->use_empty()) {
492 AA.deleteValue(I);
493 } else {
Chris Lattnered570a72004-03-07 21:29:54 +0000494 // Otherwise, if we promoted this argument, then all users are load
495 // instructions, and all loads should be using the new argument that we
496 // added.
Chris Lattnerbeabf452004-06-21 00:07:58 +0000497 ScalarizeTable &ArgIndices = ScalarizedElements[I];
Chris Lattner9440db82004-03-08 01:04:36 +0000498
Chris Lattnered570a72004-03-07 21:29:54 +0000499 while (!I->use_empty()) {
Chris Lattner9440db82004-03-08 01:04:36 +0000500 if (LoadInst *LI = dyn_cast<LoadInst>(I->use_back())) {
501 assert(ArgIndices.begin()->empty() &&
502 "Load element should sort to front!");
503 I2->setName(I->getName()+".val");
504 LI->replaceAllUsesWith(I2);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000505 AA.replaceWithNewValue(LI, I2);
Chris Lattner9440db82004-03-08 01:04:36 +0000506 LI->getParent()->getInstList().erase(LI);
Bill Wendling0a81aac2006-11-26 10:02:32 +0000507 DOUT << "*** Promoted load of argument '" << I->getName()
508 << "' in function '" << F->getName() << "'\n";
Chris Lattner9440db82004-03-08 01:04:36 +0000509 } else {
510 GetElementPtrInst *GEP = cast<GetElementPtrInst>(I->use_back());
511 std::vector<Value*> Operands(GEP->op_begin()+1, GEP->op_end());
512
Chris Lattnere4d5c442005-03-15 04:54:21 +0000513 Function::arg_iterator TheArg = I2;
Chris Lattnerbeabf452004-06-21 00:07:58 +0000514 for (ScalarizeTable::iterator It = ArgIndices.begin();
Chris Lattner9440db82004-03-08 01:04:36 +0000515 *It != Operands; ++It, ++TheArg) {
516 assert(It != ArgIndices.end() && "GEP not handled??");
517 }
518
519 std::string NewName = I->getName();
520 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
521 if (ConstantInt *CI = dyn_cast<ConstantInt>(Operands[i]))
Reid Spencera0e01292007-03-01 21:00:32 +0000522 NewName += "." + CI->getValue().toString(10);
Chris Lattner9440db82004-03-08 01:04:36 +0000523 else
524 NewName += ".x";
525 TheArg->setName(NewName+".val");
526
Bill Wendling0a81aac2006-11-26 10:02:32 +0000527 DOUT << "*** Promoted agg argument '" << TheArg->getName()
528 << "' of function '" << F->getName() << "'\n";
Chris Lattner9440db82004-03-08 01:04:36 +0000529
530 // All of the uses must be load instructions. Replace them all with
531 // the argument specified by ArgNo.
532 while (!GEP->use_empty()) {
533 LoadInst *L = cast<LoadInst>(GEP->use_back());
534 L->replaceAllUsesWith(TheArg);
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000535 AA.replaceWithNewValue(L, TheArg);
Chris Lattner9440db82004-03-08 01:04:36 +0000536 L->getParent()->getInstList().erase(L);
537 }
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000538 AA.deleteValue(GEP);
Chris Lattner9440db82004-03-08 01:04:36 +0000539 GEP->getParent()->getInstList().erase(GEP);
540 }
Chris Lattnered570a72004-03-07 21:29:54 +0000541 }
Chris Lattner86a734b2004-03-07 22:52:53 +0000542
Chris Lattner5eb6f6c2004-09-18 00:34:13 +0000543 // Increment I2 past all of the arguments added for this promoted pointer.
544 for (unsigned i = 0, e = ArgIndices.size(); i != e; ++i)
545 ++I2;
Chris Lattnered570a72004-03-07 21:29:54 +0000546 }
547
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000548 // Notify the alias analysis implementation that we inserted a new argument.
549 if (ExtraArgHack)
Reid Spencerc5b206b2006-12-31 05:48:39 +0000550 AA.copyValue(Constant::getNullValue(Type::Int32Ty), NF->arg_begin());
Chris Lattner9e7cc2f2004-05-23 21:21:17 +0000551
552
553 // Tell the alias analysis that the old function is about to disappear.
554 AA.replaceWithNewValue(F, NF);
555
Chris Lattnered570a72004-03-07 21:29:54 +0000556 // Now that the old function is dead, delete it.
557 F->getParent()->getFunctionList().erase(F);
Chris Lattner5eb6f6c2004-09-18 00:34:13 +0000558 return NF;
Chris Lattnered570a72004-03-07 21:29:54 +0000559}