blob: feb5be64f813ad11e9233e87db09cfe74b9f67af [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
Devang Pateleaaffb52008-03-04 17:47:06 +000076 if (!F || F->isDeclaration())
Devang Patel72ef0c12008-02-29 23:34:08 +000077 return false;
78
79 // Make sure that function returns struct.
Devang Patel949a4b72008-03-03 21:46:28 +000080 if (F->arg_size() == 0 || !F->hasStructRetAttr() || F->doesNotReturn())
Devang Patel72ef0c12008-02-29 23:34:08 +000081 return false;
82
83 assert (F->getReturnType() == Type::VoidTy && "Invalid function return type");
84 Function::arg_iterator AI = F->arg_begin();
85 const llvm::PointerType *FArgType = dyn_cast<PointerType>(AI->getType());
86 assert (FArgType && "Invalid sret paramater type");
87 const llvm::StructType *STy =
88 dyn_cast<StructType>(FArgType->getElementType());
89 assert (STy && "Invalid sret parameter element type");
90
91 // Check if it is ok to perform this promotion.
Devang Patelfdf88812008-03-04 17:44:37 +000092 if (isSafeToUpdateAllCallers(F) == false) {
93 NumRejectedSRETUses++;
Devang Patel72ef0c12008-02-29 23:34:08 +000094 return false;
Devang Patelfdf88812008-03-04 17:44:37 +000095 }
Devang Patel72ef0c12008-02-29 23:34:08 +000096
97 // [1] Replace use of sret parameter
Devang Patelfdf88812008-03-04 17:44:37 +000098 AllocaInst *TheAlloca = new AllocaInst (STy, NULL, "mrv",
99 F->getEntryBlock().begin());
Devang Patel72ef0c12008-02-29 23:34:08 +0000100 Value *NFirstArg = F->arg_begin();
101 NFirstArg->replaceAllUsesWith(TheAlloca);
102
Devang Patelfdf88812008-03-04 17:44:37 +0000103 // [2] Find and replace ret instructions
Devang Patel72ef0c12008-02-29 23:34:08 +0000104 SmallVector<Value *,4> RetVals;
105 for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
106 for(BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
107 Instruction *I = BI;
108 ++BI;
109 if (isa<ReturnInst>(I)) {
110 RetVals.clear();
111 for (unsigned idx = 0; idx < STy->getNumElements(); ++idx) {
112 SmallVector<Value*, 2> GEPIdx;
113 GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, 0));
114 GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, idx));
115 Value *NGEPI = new GetElementPtrInst(TheAlloca, GEPIdx.begin(), GEPIdx.end(),
116 "mrv.gep", I);
117 Value *NV = new LoadInst(NGEPI, "mrv.ld", I);
118 RetVals.push_back(NV);
119 }
120
121 ReturnInst *NR = new ReturnInst(&RetVals[0], RetVals.size(), I);
122 I->replaceAllUsesWith(NR);
123 I->eraseFromParent();
124 }
125 }
126
Devang Patelfdf88812008-03-04 17:44:37 +0000127 // [3] Create the new function body and insert it into the module.
Devang Patel72ef0c12008-02-29 23:34:08 +0000128 Function *NF = cloneFunctionBody(F, STy);
129
Devang Patelfdf88812008-03-04 17:44:37 +0000130 // [4] Update all call sites to use new function
Devang Patel72ef0c12008-02-29 23:34:08 +0000131 updateCallSites(F, NF);
132
133 F->eraseFromParent();
134 getAnalysis<CallGraph>().changeFunction(F, NF);
135 return true;
136}
137
138 // Check if it is ok to perform this promotion.
139bool SRETPromotion::isSafeToUpdateAllCallers(Function *F) {
140
141 if (F->use_empty())
142 // No users. OK to modify signature.
143 return true;
144
145 for (Value::use_iterator FnUseI = F->use_begin(), FnUseE = F->use_end();
146 FnUseI != FnUseE; ++FnUseI) {
147
148 CallSite CS = CallSite::get(*FnUseI);
149 Instruction *Call = CS.getInstruction();
150 CallSite::arg_iterator AI = CS.arg_begin();
151 Value *FirstArg = *AI;
152
153 if (!isa<AllocaInst>(FirstArg))
154 return false;
155
156 // Check FirstArg's users.
157 for (Value::use_iterator ArgI = FirstArg->use_begin(),
158 ArgE = FirstArg->use_end(); ArgI != ArgE; ++ArgI) {
159
160 // If FirstArg user is a CallInst that does not correspond to current
161 // call site then this function F is not suitable for sret promotion.
162 if (CallInst *CI = dyn_cast<CallInst>(ArgI)) {
163 if (CI != Call)
164 return false;
165 }
166 // If FirstArg user is a GEP whose all users are not LoadInst then
167 // this function F is not suitable for sret promotion.
168 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(ArgI)) {
169 for (Value::use_iterator GEPI = GEP->use_begin(), GEPE = GEP->use_end();
170 GEPI != GEPE; ++GEPI)
171 if (!isa<LoadInst>(GEPI))
172 return false;
173 }
174 // Any other FirstArg users make this function unsuitable for sret
175 // promotion.
176 else
177 return false;
178 }
179 }
180
181 return true;
182}
183
184/// cloneFunctionBody - Create a new function based on F and
185/// insert it into module. Remove first argument. Use STy as
186/// the return type for new function.
187Function *SRETPromotion::cloneFunctionBody(Function *F,
188 const StructType *STy) {
189
Devang Patel72ef0c12008-02-29 23:34:08 +0000190 const FunctionType *FTy = F->getFunctionType();
191 std::vector<const Type*> Params;
192
Devang Patel0a42ac02008-03-03 18:36:03 +0000193 // ParamAttrs - Keep track of the parameter attributes for the arguments.
194 ParamAttrsVector ParamAttrsVec;
195 const ParamAttrsList *PAL = F->getParamAttrs();
196
197 // Add any return attributes.
198 if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(0) : ParamAttr::None)
199 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
200
Devang Patel72ef0c12008-02-29 23:34:08 +0000201 // Skip first argument.
202 Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
203 ++I;
Devang Patel0a42ac02008-03-03 18:36:03 +0000204 unsigned ParamIndex = 1; // 0th parameter attribute is reserved for return type.
Devang Patel72ef0c12008-02-29 23:34:08 +0000205 while (I != E) {
206 Params.push_back(I->getType());
Devang Patel0a42ac02008-03-03 18:36:03 +0000207 if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(ParamIndex) :
208 ParamAttr::None)
209 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(), attrs));
Devang Patel72ef0c12008-02-29 23:34:08 +0000210 ++I;
Devang Patel0a42ac02008-03-03 18:36:03 +0000211 ++ParamIndex;
Devang Patel72ef0c12008-02-29 23:34:08 +0000212 }
213
214 FunctionType *NFTy = FunctionType::get(STy, Params, FTy->isVarArg());
215 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
216 NF->setCallingConv(F->getCallingConv());
Devang Patel0a42ac02008-03-03 18:36:03 +0000217 NF->setParamAttrs(ParamAttrsList::get(ParamAttrsVec));
Devang Patel72ef0c12008-02-29 23:34:08 +0000218 F->getParent()->getFunctionList().insert(F, NF);
219 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
220
221 // Replace arguments
222 I = F->arg_begin();
223 E = F->arg_end();
224 Function::arg_iterator NI = NF->arg_begin();
225 ++I;
226 while (I != E) {
227 I->replaceAllUsesWith(NI);
228 NI->takeName(I);
229 ++I;
230 ++NI;
231 }
232
233 return NF;
234}
235
236/// updateCallSites - Update all sites that call F to use NF.
237void SRETPromotion::updateCallSites(Function *F, Function *NF) {
238
Devang Patel72ef0c12008-02-29 23:34:08 +0000239 SmallVector<Value*, 16> Args;
240
Devang Patel0a42ac02008-03-03 18:36:03 +0000241 // ParamAttrs - Keep track of the parameter attributes for the arguments.
242 ParamAttrsVector ParamAttrsVec;
243
Devang Patel72ef0c12008-02-29 23:34:08 +0000244 for (Value::use_iterator FUI = F->use_begin(), FUE = F->use_end(); FUI != FUE;) {
245 CallSite CS = CallSite::get(*FUI);
246 ++FUI;
247 Instruction *Call = CS.getInstruction();
248
Devang Patel0a42ac02008-03-03 18:36:03 +0000249 const ParamAttrsList *PAL = F->getParamAttrs();
250 // Add any return attributes.
251 if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(0) : ParamAttr::None)
252 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
253
Devang Patel72ef0c12008-02-29 23:34:08 +0000254 // Copy arguments, however skip first one.
255 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
256 Value *FirstCArg = *AI;
257 ++AI;
Devang Patel0a42ac02008-03-03 18:36:03 +0000258 unsigned ParamIndex = 1; // 0th parameter attribute is reserved for return type.
Devang Patel72ef0c12008-02-29 23:34:08 +0000259 while (AI != AE) {
260 Args.push_back(*AI);
Devang Patel0a42ac02008-03-03 18:36:03 +0000261 if (ParameterAttributes Attrs = PAL ? PAL->getParamAttrs(ParamIndex) :
262 ParamAttr::None)
263 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
264 ++ParamIndex;
Devang Patel72ef0c12008-02-29 23:34:08 +0000265 ++AI;
266 }
267
268 // Build new call instruction.
269 Instruction *New;
270 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
271 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
272 Args.begin(), Args.end(), "", Call);
273 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Devang Patel0a42ac02008-03-03 18:36:03 +0000274 cast<InvokeInst>(New)->setParamAttrs(ParamAttrsList::get(ParamAttrsVec));
Devang Patel72ef0c12008-02-29 23:34:08 +0000275 } else {
276 New = new CallInst(NF, Args.begin(), Args.end(), "", Call);
277 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Devang Patel0a42ac02008-03-03 18:36:03 +0000278 cast<CallInst>(New)->setParamAttrs(ParamAttrsList::get(ParamAttrsVec));
Devang Patel72ef0c12008-02-29 23:34:08 +0000279 if (cast<CallInst>(Call)->isTailCall())
280 cast<CallInst>(New)->setTailCall();
281 }
282 Args.clear();
Devang Patel0a42ac02008-03-03 18:36:03 +0000283 ParamAttrsVec.clear();
Devang Patel72ef0c12008-02-29 23:34:08 +0000284 New->takeName(Call);
285
286 // Update all users of sret parameter to extract value using getresult.
287 for (Value::use_iterator UI = FirstCArg->use_begin(),
288 UE = FirstCArg->use_end(); UI != UE; ) {
289 User *U2 = *UI++;
290 CallInst *C2 = dyn_cast<CallInst>(U2);
291 if (C2 && (C2 == Call))
292 continue;
293 else if (GetElementPtrInst *UGEP = dyn_cast<GetElementPtrInst>(U2)) {
294 Value *GR = new GetResultInst(New, 5, "xxx", UGEP);
295 for (Value::use_iterator GI = UGEP->use_begin(),
296 GE = UGEP->use_end(); GI != GE; ++GI) {
297 if (LoadInst *L = dyn_cast<LoadInst>(*GI)) {
298 L->replaceAllUsesWith(GR);
299 L->eraseFromParent();
300 }
301 }
302 UGEP->eraseFromParent();
303 }
304 else assert( 0 && "Unexpected sret parameter use");
305 }
306 Call->eraseFromParent();
307 }
308}