blob: 3ea9a04adb59430cbf6a69e9b9edaa010fb10012 [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);
51 };
52
53 char SRETPromotion::ID = 0;
54 RegisterPass<SRETPromotion> X("sretpromotion",
55 "Promote sret arguments to multiple ret values");
56}
57
58Pass *llvm::createStructRetPromotionPass() {
59 return new SRETPromotion();
60}
61
62bool SRETPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
63 bool Changed = false;
64
65 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
66 Changed |= PromoteReturn(SCC[i]);
67
68 return Changed;
69}
70
71/// PromoteReturn - This method promotes function that uses StructRet paramater
72/// into a function that uses mulitple return value.
73bool SRETPromotion::PromoteReturn(CallGraphNode *CGN) {
74 Function *F = CGN->getFunction();
75
76 // Make sure that it is local to this module.
77 if (!F || !F->hasInternalLinkage())
78 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
92 // Check if it is ok to perform this promotion.
Devang Patelfdf88812008-03-04 17:44:37 +000093 if (isSafeToUpdateAllCallers(F) == false) {
94 NumRejectedSRETUses++;
Devang Patel72ef0c12008-02-29 23:34:08 +000095 return false;
Devang Patelfdf88812008-03-04 17:44:37 +000096 }
Devang Patel72ef0c12008-02-29 23:34:08 +000097
98 // [1] Replace use of sret parameter
Devang Patelfdf88812008-03-04 17:44:37 +000099 AllocaInst *TheAlloca = new AllocaInst (STy, NULL, "mrv",
100 F->getEntryBlock().begin());
Devang Patel72ef0c12008-02-29 23:34:08 +0000101 Value *NFirstArg = F->arg_begin();
102 NFirstArg->replaceAllUsesWith(TheAlloca);
103
Devang Patelfdf88812008-03-04 17:44:37 +0000104 // [2] Find and replace ret instructions
Devang Patel72ef0c12008-02-29 23:34:08 +0000105 SmallVector<Value *,4> RetVals;
106 for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
107 for(BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
108 Instruction *I = BI;
109 ++BI;
110 if (isa<ReturnInst>(I)) {
111 RetVals.clear();
112 for (unsigned idx = 0; idx < STy->getNumElements(); ++idx) {
113 SmallVector<Value*, 2> GEPIdx;
114 GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, 0));
115 GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, idx));
116 Value *NGEPI = new GetElementPtrInst(TheAlloca, GEPIdx.begin(), GEPIdx.end(),
117 "mrv.gep", I);
118 Value *NV = new LoadInst(NGEPI, "mrv.ld", I);
119 RetVals.push_back(NV);
120 }
121
122 ReturnInst *NR = new ReturnInst(&RetVals[0], RetVals.size(), I);
123 I->replaceAllUsesWith(NR);
124 I->eraseFromParent();
125 }
126 }
127
Devang Patelfdf88812008-03-04 17:44:37 +0000128 // [3] Create the new function body and insert it into the module.
Devang Patel72ef0c12008-02-29 23:34:08 +0000129 Function *NF = cloneFunctionBody(F, STy);
130
Devang Patelfdf88812008-03-04 17:44:37 +0000131 // [4] Update all call sites to use new function
Devang Patel72ef0c12008-02-29 23:34:08 +0000132 updateCallSites(F, NF);
133
134 F->eraseFromParent();
135 getAnalysis<CallGraph>().changeFunction(F, NF);
136 return true;
137}
138
139 // Check if it is ok to perform this promotion.
140bool SRETPromotion::isSafeToUpdateAllCallers(Function *F) {
141
142 if (F->use_empty())
143 // No users. OK to modify signature.
144 return true;
145
146 for (Value::use_iterator FnUseI = F->use_begin(), FnUseE = F->use_end();
147 FnUseI != FnUseE; ++FnUseI) {
148
149 CallSite CS = CallSite::get(*FnUseI);
150 Instruction *Call = CS.getInstruction();
151 CallSite::arg_iterator AI = CS.arg_begin();
152 Value *FirstArg = *AI;
153
154 if (!isa<AllocaInst>(FirstArg))
155 return false;
156
157 // Check FirstArg's users.
158 for (Value::use_iterator ArgI = FirstArg->use_begin(),
159 ArgE = FirstArg->use_end(); ArgI != ArgE; ++ArgI) {
160
161 // If FirstArg user is a CallInst that does not correspond to current
162 // call site then this function F is not suitable for sret promotion.
163 if (CallInst *CI = dyn_cast<CallInst>(ArgI)) {
164 if (CI != Call)
165 return false;
166 }
167 // If FirstArg user is a GEP whose all users are not LoadInst then
168 // this function F is not suitable for sret promotion.
169 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(ArgI)) {
170 for (Value::use_iterator GEPI = GEP->use_begin(), GEPE = GEP->use_end();
171 GEPI != GEPE; ++GEPI)
172 if (!isa<LoadInst>(GEPI))
173 return false;
174 }
175 // Any other FirstArg users make this function unsuitable for sret
176 // promotion.
177 else
178 return false;
179 }
180 }
181
182 return true;
183}
184
185/// cloneFunctionBody - Create a new function based on F and
186/// insert it into module. Remove first argument. Use STy as
187/// the return type for new function.
188Function *SRETPromotion::cloneFunctionBody(Function *F,
189 const StructType *STy) {
190
Devang Patel72ef0c12008-02-29 23:34:08 +0000191 const FunctionType *FTy = F->getFunctionType();
192 std::vector<const Type*> Params;
193
Devang Patel0a42ac02008-03-03 18:36:03 +0000194 // ParamAttrs - Keep track of the parameter attributes for the arguments.
195 ParamAttrsVector ParamAttrsVec;
196 const ParamAttrsList *PAL = F->getParamAttrs();
197
198 // Add any return attributes.
199 if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(0) : ParamAttr::None)
200 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
201
Devang Patel72ef0c12008-02-29 23:34:08 +0000202 // Skip first argument.
203 Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
204 ++I;
Devang Patel0a42ac02008-03-03 18:36:03 +0000205 unsigned ParamIndex = 1; // 0th parameter attribute is reserved for return type.
Devang Patel72ef0c12008-02-29 23:34:08 +0000206 while (I != E) {
207 Params.push_back(I->getType());
Devang Patel0a42ac02008-03-03 18:36:03 +0000208 if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(ParamIndex) :
209 ParamAttr::None)
210 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(), attrs));
Devang Patel72ef0c12008-02-29 23:34:08 +0000211 ++I;
Devang Patel0a42ac02008-03-03 18:36:03 +0000212 ++ParamIndex;
Devang Patel72ef0c12008-02-29 23:34:08 +0000213 }
214
215 FunctionType *NFTy = FunctionType::get(STy, Params, FTy->isVarArg());
216 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
217 NF->setCallingConv(F->getCallingConv());
Devang Patel0a42ac02008-03-03 18:36:03 +0000218 NF->setParamAttrs(ParamAttrsList::get(ParamAttrsVec));
Devang Patel72ef0c12008-02-29 23:34:08 +0000219 F->getParent()->getFunctionList().insert(F, NF);
220 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
221
222 // Replace arguments
223 I = F->arg_begin();
224 E = F->arg_end();
225 Function::arg_iterator NI = NF->arg_begin();
226 ++I;
227 while (I != E) {
228 I->replaceAllUsesWith(NI);
229 NI->takeName(I);
230 ++I;
231 ++NI;
232 }
233
234 return NF;
235}
236
237/// updateCallSites - Update all sites that call F to use NF.
238void SRETPromotion::updateCallSites(Function *F, Function *NF) {
239
Devang Patel72ef0c12008-02-29 23:34:08 +0000240 SmallVector<Value*, 16> Args;
241
Devang Patel0a42ac02008-03-03 18:36:03 +0000242 // ParamAttrs - Keep track of the parameter attributes for the arguments.
243 ParamAttrsVector ParamAttrsVec;
244
Devang Patel72ef0c12008-02-29 23:34:08 +0000245 for (Value::use_iterator FUI = F->use_begin(), FUE = F->use_end(); FUI != FUE;) {
246 CallSite CS = CallSite::get(*FUI);
247 ++FUI;
248 Instruction *Call = CS.getInstruction();
249
Devang Patel0a42ac02008-03-03 18:36:03 +0000250 const ParamAttrsList *PAL = F->getParamAttrs();
251 // Add any return attributes.
252 if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(0) : ParamAttr::None)
253 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
254
Devang Patel72ef0c12008-02-29 23:34:08 +0000255 // Copy arguments, however skip first one.
256 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
257 Value *FirstCArg = *AI;
258 ++AI;
Devang Patel0a42ac02008-03-03 18:36:03 +0000259 unsigned ParamIndex = 1; // 0th parameter attribute is reserved for return type.
Devang Patel72ef0c12008-02-29 23:34:08 +0000260 while (AI != AE) {
261 Args.push_back(*AI);
Devang Patel0a42ac02008-03-03 18:36:03 +0000262 if (ParameterAttributes Attrs = PAL ? PAL->getParamAttrs(ParamIndex) :
263 ParamAttr::None)
264 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
265 ++ParamIndex;
Devang Patel72ef0c12008-02-29 23:34:08 +0000266 ++AI;
267 }
268
269 // Build new call instruction.
270 Instruction *New;
271 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
272 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
273 Args.begin(), Args.end(), "", Call);
274 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Devang Patel0a42ac02008-03-03 18:36:03 +0000275 cast<InvokeInst>(New)->setParamAttrs(ParamAttrsList::get(ParamAttrsVec));
Devang Patel72ef0c12008-02-29 23:34:08 +0000276 } else {
277 New = new CallInst(NF, Args.begin(), Args.end(), "", Call);
278 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Devang Patel0a42ac02008-03-03 18:36:03 +0000279 cast<CallInst>(New)->setParamAttrs(ParamAttrsList::get(ParamAttrsVec));
Devang Patel72ef0c12008-02-29 23:34:08 +0000280 if (cast<CallInst>(Call)->isTailCall())
281 cast<CallInst>(New)->setTailCall();
282 }
283 Args.clear();
Devang Patel0a42ac02008-03-03 18:36:03 +0000284 ParamAttrsVec.clear();
Devang Patel72ef0c12008-02-29 23:34:08 +0000285 New->takeName(Call);
286
287 // Update all users of sret parameter to extract value using getresult.
288 for (Value::use_iterator UI = FirstCArg->use_begin(),
289 UE = FirstCArg->use_end(); UI != UE; ) {
290 User *U2 = *UI++;
291 CallInst *C2 = dyn_cast<CallInst>(U2);
292 if (C2 && (C2 == Call))
293 continue;
294 else if (GetElementPtrInst *UGEP = dyn_cast<GetElementPtrInst>(U2)) {
295 Value *GR = new GetResultInst(New, 5, "xxx", UGEP);
296 for (Value::use_iterator GI = UGEP->use_begin(),
297 GE = UGEP->use_end(); GI != GE; ++GI) {
298 if (LoadInst *L = dyn_cast<LoadInst>(*GI)) {
299 L->replaceAllUsesWith(GR);
300 L->eraseFromParent();
301 }
302 }
303 UGEP->eraseFromParent();
304 }
305 else assert( 0 && "Unexpected sret parameter use");
306 }
307 Call->eraseFromParent();
308 }
309}