blob: 54a34e8803f16d9b98ab522922f2b9f600f545b4 [file] [log] [blame]
Devang Patel72ef0c12008-02-29 23:34:08 +00001//===-- StructRetPromotion.cpp - Promote sret arguments -000000------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Devang Patel3b3596f2008-02-29 23:41:13 +000010// TODO : Describe this pass.
Devang Patel72ef0c12008-02-29 23:34:08 +000011//===----------------------------------------------------------------------===//
12
13#define DEBUG_TYPE "sretpromotion"
14#include "llvm/Transforms/IPO.h"
15#include "llvm/Constants.h"
16#include "llvm/DerivedTypes.h"
17#include "llvm/Module.h"
18#include "llvm/CallGraphSCCPass.h"
19#include "llvm/Instructions.h"
Devang Patel0a42ac02008-03-03 18:36:03 +000020#include "llvm/ParamAttrsList.h"
Devang Patel72ef0c12008-02-29 23:34:08 +000021#include "llvm/Analysis/CallGraph.h"
22#include "llvm/Support/CallSite.h"
23#include "llvm/Support/CFG.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/ADT/SmallVector.h"
Devang Patelfdf88812008-03-04 17:44:37 +000027#include "llvm/ADT/Statistic.h"
Devang Patel72ef0c12008-02-29 23:34:08 +000028#include "llvm/Support/Compiler.h"
29using namespace llvm;
30
Devang Patelfdf88812008-03-04 17:44:37 +000031STATISTIC(NumRejectedSRETUses , "Number of sret rejected due to unexpected uses");
32STATISTIC(NumSRET , "Number of sret promoted");
Devang Patel72ef0c12008-02-29 23:34:08 +000033namespace {
34 /// SRETPromotion - This pass removes sret parameter and updates
35 /// function to use multiple return value.
36 ///
37 struct VISIBILITY_HIDDEN SRETPromotion : public CallGraphSCCPass {
38 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
39 CallGraphSCCPass::getAnalysisUsage(AU);
40 }
41
42 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
43 static char ID; // Pass identification, replacement for typeid
44 SRETPromotion() : CallGraphSCCPass((intptr_t)&ID) {}
45
46 private:
47 bool PromoteReturn(CallGraphNode *CGN);
48 bool isSafeToUpdateAllCallers(Function *F);
49 Function *cloneFunctionBody(Function *F, const StructType *STy);
50 void updateCallSites(Function *F, Function *NF);
Devang Pateld81d65f2008-03-04 21:32:09 +000051 bool nestedStructType(const StructType *STy);
Devang Patel72ef0c12008-02-29 23:34:08 +000052 };
53
54 char SRETPromotion::ID = 0;
55 RegisterPass<SRETPromotion> X("sretpromotion",
56 "Promote sret arguments to multiple ret values");
57}
58
59Pass *llvm::createStructRetPromotionPass() {
60 return new SRETPromotion();
61}
62
63bool SRETPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
64 bool Changed = false;
65
66 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
67 Changed |= PromoteReturn(SCC[i]);
68
69 return Changed;
70}
71
72/// PromoteReturn - This method promotes function that uses StructRet paramater
73/// into a function that uses mulitple return value.
74bool SRETPromotion::PromoteReturn(CallGraphNode *CGN) {
75 Function *F = CGN->getFunction();
76
Devang Pateleaaffb52008-03-04 17:47:06 +000077 if (!F || F->isDeclaration())
Devang Patel72ef0c12008-02-29 23:34:08 +000078 return false;
79
80 // Make sure that function returns struct.
Devang Patel949a4b72008-03-03 21:46:28 +000081 if (F->arg_size() == 0 || !F->hasStructRetAttr() || F->doesNotReturn())
Devang Patel72ef0c12008-02-29 23:34:08 +000082 return false;
83
84 assert (F->getReturnType() == Type::VoidTy && "Invalid function return type");
85 Function::arg_iterator AI = F->arg_begin();
86 const llvm::PointerType *FArgType = dyn_cast<PointerType>(AI->getType());
87 assert (FArgType && "Invalid sret paramater type");
88 const llvm::StructType *STy =
89 dyn_cast<StructType>(FArgType->getElementType());
90 assert (STy && "Invalid sret parameter element type");
91
Devang Pateld81d65f2008-03-04 21:32:09 +000092 if (nestedStructType(STy))
93 return false;
94
Devang Patel72ef0c12008-02-29 23:34:08 +000095 // Check if it is ok to perform this promotion.
Devang Patelfdf88812008-03-04 17:44:37 +000096 if (isSafeToUpdateAllCallers(F) == false) {
97 NumRejectedSRETUses++;
Devang Patel72ef0c12008-02-29 23:34:08 +000098 return false;
Devang Patelfdf88812008-03-04 17:44:37 +000099 }
Devang Patel72ef0c12008-02-29 23:34:08 +0000100
Devang Patel09bfbff2008-03-04 17:48:11 +0000101 NumSRET++;
Devang Patel72ef0c12008-02-29 23:34:08 +0000102 // [1] Replace use of sret parameter
Devang Patelfdf88812008-03-04 17:44:37 +0000103 AllocaInst *TheAlloca = new AllocaInst (STy, NULL, "mrv",
104 F->getEntryBlock().begin());
Devang Patel72ef0c12008-02-29 23:34:08 +0000105 Value *NFirstArg = F->arg_begin();
106 NFirstArg->replaceAllUsesWith(TheAlloca);
107
Devang Patelfdf88812008-03-04 17:44:37 +0000108 // [2] Find and replace ret instructions
Devang Patel72ef0c12008-02-29 23:34:08 +0000109 SmallVector<Value *,4> RetVals;
110 for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
111 for(BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
112 Instruction *I = BI;
113 ++BI;
114 if (isa<ReturnInst>(I)) {
115 RetVals.clear();
116 for (unsigned idx = 0; idx < STy->getNumElements(); ++idx) {
117 SmallVector<Value*, 2> GEPIdx;
118 GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, 0));
119 GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, idx));
120 Value *NGEPI = new GetElementPtrInst(TheAlloca, GEPIdx.begin(), GEPIdx.end(),
121 "mrv.gep", I);
122 Value *NV = new LoadInst(NGEPI, "mrv.ld", I);
123 RetVals.push_back(NV);
124 }
125
126 ReturnInst *NR = new ReturnInst(&RetVals[0], RetVals.size(), I);
127 I->replaceAllUsesWith(NR);
128 I->eraseFromParent();
129 }
130 }
131
Devang Patelfdf88812008-03-04 17:44:37 +0000132 // [3] Create the new function body and insert it into the module.
Devang Patel72ef0c12008-02-29 23:34:08 +0000133 Function *NF = cloneFunctionBody(F, STy);
134
Devang Patelfdf88812008-03-04 17:44:37 +0000135 // [4] Update all call sites to use new function
Devang Patel72ef0c12008-02-29 23:34:08 +0000136 updateCallSites(F, NF);
137
138 F->eraseFromParent();
139 getAnalysis<CallGraph>().changeFunction(F, NF);
140 return true;
141}
142
143 // Check if it is ok to perform this promotion.
144bool SRETPromotion::isSafeToUpdateAllCallers(Function *F) {
145
146 if (F->use_empty())
147 // No users. OK to modify signature.
148 return true;
149
150 for (Value::use_iterator FnUseI = F->use_begin(), FnUseE = F->use_end();
151 FnUseI != FnUseE; ++FnUseI) {
152
153 CallSite CS = CallSite::get(*FnUseI);
154 Instruction *Call = CS.getInstruction();
155 CallSite::arg_iterator AI = CS.arg_begin();
156 Value *FirstArg = *AI;
157
158 if (!isa<AllocaInst>(FirstArg))
159 return false;
160
161 // Check FirstArg's users.
162 for (Value::use_iterator ArgI = FirstArg->use_begin(),
163 ArgE = FirstArg->use_end(); ArgI != ArgE; ++ArgI) {
164
165 // If FirstArg user is a CallInst that does not correspond to current
166 // call site then this function F is not suitable for sret promotion.
167 if (CallInst *CI = dyn_cast<CallInst>(ArgI)) {
168 if (CI != Call)
169 return false;
170 }
171 // If FirstArg user is a GEP whose all users are not LoadInst then
172 // this function F is not suitable for sret promotion.
173 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(ArgI)) {
174 for (Value::use_iterator GEPI = GEP->use_begin(), GEPE = GEP->use_end();
175 GEPI != GEPE; ++GEPI)
176 if (!isa<LoadInst>(GEPI))
177 return false;
178 }
179 // Any other FirstArg users make this function unsuitable for sret
180 // promotion.
181 else
182 return false;
183 }
184 }
185
186 return true;
187}
188
189/// cloneFunctionBody - Create a new function based on F and
190/// insert it into module. Remove first argument. Use STy as
191/// the return type for new function.
192Function *SRETPromotion::cloneFunctionBody(Function *F,
193 const StructType *STy) {
194
Devang Patel72ef0c12008-02-29 23:34:08 +0000195 const FunctionType *FTy = F->getFunctionType();
196 std::vector<const Type*> Params;
197
Devang Patel0a42ac02008-03-03 18:36:03 +0000198 // ParamAttrs - Keep track of the parameter attributes for the arguments.
199 ParamAttrsVector ParamAttrsVec;
200 const ParamAttrsList *PAL = F->getParamAttrs();
201
202 // Add any return attributes.
203 if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(0) : ParamAttr::None)
204 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
205
Devang Patel72ef0c12008-02-29 23:34:08 +0000206 // Skip first argument.
207 Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
208 ++I;
Devang Patel0a42ac02008-03-03 18:36:03 +0000209 unsigned ParamIndex = 1; // 0th parameter attribute is reserved for return type.
Devang Patel72ef0c12008-02-29 23:34:08 +0000210 while (I != E) {
211 Params.push_back(I->getType());
Devang Patel7d7e00a2008-03-04 19:12:58 +0000212 ParameterAttributes Attrs;
213 if (PAL) {
214 Attrs = PAL->getParamAttrs(ParamIndex);
215 if (ParamIndex == 1) // Skip sret attribute
216 Attrs = Attrs ^ ParamAttr::StructRet;
217 }
218 if (Attrs != ParamAttr::None)
219 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(ParamIndex, Attrs));
Devang Patel72ef0c12008-02-29 23:34:08 +0000220 ++I;
Devang Patel0a42ac02008-03-03 18:36:03 +0000221 ++ParamIndex;
Devang Patel72ef0c12008-02-29 23:34:08 +0000222 }
223
224 FunctionType *NFTy = FunctionType::get(STy, Params, FTy->isVarArg());
225 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
226 NF->setCallingConv(F->getCallingConv());
Devang Patel0a42ac02008-03-03 18:36:03 +0000227 NF->setParamAttrs(ParamAttrsList::get(ParamAttrsVec));
Devang Patel72ef0c12008-02-29 23:34:08 +0000228 F->getParent()->getFunctionList().insert(F, NF);
229 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
230
231 // Replace arguments
232 I = F->arg_begin();
233 E = F->arg_end();
234 Function::arg_iterator NI = NF->arg_begin();
235 ++I;
236 while (I != E) {
237 I->replaceAllUsesWith(NI);
238 NI->takeName(I);
239 ++I;
240 ++NI;
241 }
242
243 return NF;
244}
245
246/// updateCallSites - Update all sites that call F to use NF.
247void SRETPromotion::updateCallSites(Function *F, Function *NF) {
248
Devang Patel72ef0c12008-02-29 23:34:08 +0000249 SmallVector<Value*, 16> Args;
250
Devang Patel0a42ac02008-03-03 18:36:03 +0000251 // ParamAttrs - Keep track of the parameter attributes for the arguments.
Devang Patel7d7e00a2008-03-04 19:12:58 +0000252 ParamAttrsVector ArgAttrsVec;
Devang Patel0a42ac02008-03-03 18:36:03 +0000253
Devang Patel72ef0c12008-02-29 23:34:08 +0000254 for (Value::use_iterator FUI = F->use_begin(), FUE = F->use_end(); FUI != FUE;) {
255 CallSite CS = CallSite::get(*FUI);
256 ++FUI;
257 Instruction *Call = CS.getInstruction();
258
Devang Patel0a42ac02008-03-03 18:36:03 +0000259 const ParamAttrsList *PAL = F->getParamAttrs();
260 // Add any return attributes.
261 if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(0) : ParamAttr::None)
Devang Patel7d7e00a2008-03-04 19:12:58 +0000262 ArgAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
Devang Patel0a42ac02008-03-03 18:36:03 +0000263
Devang Patel72ef0c12008-02-29 23:34:08 +0000264 // Copy arguments, however skip first one.
265 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
266 Value *FirstCArg = *AI;
267 ++AI;
Devang Patel0a42ac02008-03-03 18:36:03 +0000268 unsigned ParamIndex = 1; // 0th parameter attribute is reserved for return type.
Devang Patel72ef0c12008-02-29 23:34:08 +0000269 while (AI != AE) {
270 Args.push_back(*AI);
Devang Patel7d7e00a2008-03-04 19:12:58 +0000271 ParameterAttributes Attrs;
272 if (PAL) {
273 Attrs = PAL->getParamAttrs(ParamIndex);
274 if (ParamIndex == 1) // Skip sret attribute
275 Attrs = Attrs ^ ParamAttr::StructRet;
276 }
277 if (Attrs != ParamAttr::None)
278 ArgAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
Devang Patel0a42ac02008-03-03 18:36:03 +0000279 ++ParamIndex;
Devang Patel72ef0c12008-02-29 23:34:08 +0000280 ++AI;
281 }
282
283 // Build new call instruction.
284 Instruction *New;
285 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
286 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
287 Args.begin(), Args.end(), "", Call);
288 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Devang Patel7d7e00a2008-03-04 19:12:58 +0000289 cast<InvokeInst>(New)->setParamAttrs(ParamAttrsList::get(ArgAttrsVec));
Devang Patel72ef0c12008-02-29 23:34:08 +0000290 } else {
291 New = new CallInst(NF, Args.begin(), Args.end(), "", Call);
292 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Devang Patel7d7e00a2008-03-04 19:12:58 +0000293 cast<CallInst>(New)->setParamAttrs(ParamAttrsList::get(ArgAttrsVec));
Devang Patel72ef0c12008-02-29 23:34:08 +0000294 if (cast<CallInst>(Call)->isTailCall())
295 cast<CallInst>(New)->setTailCall();
296 }
297 Args.clear();
Devang Patel7d7e00a2008-03-04 19:12:58 +0000298 ArgAttrsVec.clear();
Devang Patel72ef0c12008-02-29 23:34:08 +0000299 New->takeName(Call);
300
301 // Update all users of sret parameter to extract value using getresult.
302 for (Value::use_iterator UI = FirstCArg->use_begin(),
303 UE = FirstCArg->use_end(); UI != UE; ) {
304 User *U2 = *UI++;
305 CallInst *C2 = dyn_cast<CallInst>(U2);
306 if (C2 && (C2 == Call))
307 continue;
308 else if (GetElementPtrInst *UGEP = dyn_cast<GetElementPtrInst>(U2)) {
Devang Patel13eee892008-03-04 19:22:54 +0000309 ConstantInt *Idx = dyn_cast<ConstantInt>(UGEP->getOperand(2));
310 assert (Idx && "Unexpected getelementptr index!");
311 Value *GR = new GetResultInst(New, Idx->getZExtValue(), "gr", UGEP);
Devang Patel72ef0c12008-02-29 23:34:08 +0000312 for (Value::use_iterator GI = UGEP->use_begin(),
313 GE = UGEP->use_end(); GI != GE; ++GI) {
314 if (LoadInst *L = dyn_cast<LoadInst>(*GI)) {
315 L->replaceAllUsesWith(GR);
316 L->eraseFromParent();
317 }
318 }
319 UGEP->eraseFromParent();
320 }
321 else assert( 0 && "Unexpected sret parameter use");
322 }
323 Call->eraseFromParent();
324 }
325}
Devang Pateld81d65f2008-03-04 21:32:09 +0000326
327/// nestedStructType - Return true if STy includes any
328/// other aggregate types
329bool SRETPromotion::nestedStructType(const StructType *STy) {
330 unsigned Num = STy->getNumElements();
331 for (unsigned i = 0; i < Num; i++) {
332 const Type *Ty = STy->getElementType(i);
333 if (!Ty->isFirstClassType() && Ty != Type::VoidTy)
334 return true;
335 }
336 return false;
337}