blob: 97a532b8b11d419a2d1ed9500d99cc74f052e362 [file] [log] [blame]
Gordon Henriksena8a118b2008-05-08 17:46:35 +00001//===-- StructRetPromotion.cpp - Promote sret arguments ------------------===//
Devang Patelca891ec2008-02-29 23:34:08 +00002//
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//
Gordon Henriksena8a118b2008-05-08 17:46:35 +000010// This pass finds functions that return a struct (using a pointer to the struct
11// as the first argument of the function, marked with the 'sret' attribute) and
12// replaces them with a new function that simply returns each of the elements of
13// that struct (using multiple return values).
14//
15// This pass works under a number of conditions:
16// 1. The returned struct must not contain other structs
17// 2. The returned struct must only be used to load values from
18// 3. The placeholder struct passed in is the result of an alloca
19//
Devang Patelca891ec2008-02-29 23:34:08 +000020//===----------------------------------------------------------------------===//
21
22#define DEBUG_TYPE "sretpromotion"
23#include "llvm/Transforms/IPO.h"
24#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
26#include "llvm/Module.h"
27#include "llvm/CallGraphSCCPass.h"
28#include "llvm/Instructions.h"
29#include "llvm/Analysis/CallGraph.h"
30#include "llvm/Support/CallSite.h"
31#include "llvm/Support/CFG.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/ADT/Statistic.h"
34#include "llvm/ADT/SmallVector.h"
Devang Patel98a6e062008-03-04 17:44:37 +000035#include "llvm/ADT/Statistic.h"
Devang Patelca891ec2008-02-29 23:34:08 +000036#include "llvm/Support/Compiler.h"
37using namespace llvm;
38
Devang Patel98a6e062008-03-04 17:44:37 +000039STATISTIC(NumRejectedSRETUses , "Number of sret rejected due to unexpected uses");
40STATISTIC(NumSRET , "Number of sret promoted");
Devang Patelca891ec2008-02-29 23:34:08 +000041namespace {
42 /// SRETPromotion - This pass removes sret parameter and updates
43 /// function to use multiple return value.
44 ///
45 struct VISIBILITY_HIDDEN SRETPromotion : public CallGraphSCCPass {
46 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47 CallGraphSCCPass::getAnalysisUsage(AU);
48 }
49
50 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
51 static char ID; // Pass identification, replacement for typeid
52 SRETPromotion() : CallGraphSCCPass((intptr_t)&ID) {}
53
54 private:
55 bool PromoteReturn(CallGraphNode *CGN);
56 bool isSafeToUpdateAllCallers(Function *F);
57 Function *cloneFunctionBody(Function *F, const StructType *STy);
58 void updateCallSites(Function *F, Function *NF);
Devang Patela9fe8bb2008-03-04 21:32:09 +000059 bool nestedStructType(const StructType *STy);
Devang Patelca891ec2008-02-29 23:34:08 +000060 };
Devang Patelca891ec2008-02-29 23:34:08 +000061}
62
Dan Gohman844731a2008-05-13 00:00:25 +000063char SRETPromotion::ID = 0;
64static RegisterPass<SRETPromotion>
65X("sretpromotion", "Promote sret arguments to multiple ret values");
66
Devang Patelca891ec2008-02-29 23:34:08 +000067Pass *llvm::createStructRetPromotionPass() {
68 return new SRETPromotion();
69}
70
71bool SRETPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
72 bool Changed = false;
73
74 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
75 Changed |= PromoteReturn(SCC[i]);
76
77 return Changed;
78}
79
80/// PromoteReturn - This method promotes function that uses StructRet paramater
81/// into a function that uses mulitple return value.
82bool SRETPromotion::PromoteReturn(CallGraphNode *CGN) {
83 Function *F = CGN->getFunction();
84
Devang Pateld7266d42008-05-08 15:08:39 +000085 if (!F || F->isDeclaration() || !F->hasInternalLinkage())
Devang Patelca891ec2008-02-29 23:34:08 +000086 return false;
87
88 // Make sure that function returns struct.
Devang Patel41e23972008-03-03 21:46:28 +000089 if (F->arg_size() == 0 || !F->hasStructRetAttr() || F->doesNotReturn())
Devang Patelca891ec2008-02-29 23:34:08 +000090 return false;
91
92 assert (F->getReturnType() == Type::VoidTy && "Invalid function return type");
93 Function::arg_iterator AI = F->arg_begin();
94 const llvm::PointerType *FArgType = dyn_cast<PointerType>(AI->getType());
Duncan Sands33af59d2008-05-09 12:20:10 +000095 assert (FArgType && "Invalid sret parameter type");
Devang Patelca891ec2008-02-29 23:34:08 +000096 const llvm::StructType *STy =
97 dyn_cast<StructType>(FArgType->getElementType());
98 assert (STy && "Invalid sret parameter element type");
99
Devang Patela9fe8bb2008-03-04 21:32:09 +0000100 if (nestedStructType(STy))
101 return false;
102
Devang Patelca891ec2008-02-29 23:34:08 +0000103 // Check if it is ok to perform this promotion.
Devang Patel98a6e062008-03-04 17:44:37 +0000104 if (isSafeToUpdateAllCallers(F) == false) {
105 NumRejectedSRETUses++;
Devang Patelca891ec2008-02-29 23:34:08 +0000106 return false;
Devang Patel98a6e062008-03-04 17:44:37 +0000107 }
Devang Patelca891ec2008-02-29 23:34:08 +0000108
Devang Pateldf1d15c2008-03-04 17:48:11 +0000109 NumSRET++;
Devang Patelca891ec2008-02-29 23:34:08 +0000110 // [1] Replace use of sret parameter
Devang Patel98a6e062008-03-04 17:44:37 +0000111 AllocaInst *TheAlloca = new AllocaInst (STy, NULL, "mrv",
112 F->getEntryBlock().begin());
Devang Patelca891ec2008-02-29 23:34:08 +0000113 Value *NFirstArg = F->arg_begin();
114 NFirstArg->replaceAllUsesWith(TheAlloca);
115
Devang Patel98a6e062008-03-04 17:44:37 +0000116 // [2] Find and replace ret instructions
Devang Patelca891ec2008-02-29 23:34:08 +0000117 SmallVector<Value *,4> RetVals;
118 for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
119 for(BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
120 Instruction *I = BI;
121 ++BI;
122 if (isa<ReturnInst>(I)) {
123 RetVals.clear();
124 for (unsigned idx = 0; idx < STy->getNumElements(); ++idx) {
125 SmallVector<Value*, 2> GEPIdx;
126 GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, 0));
127 GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, idx));
Gabor Greif051a9502008-04-06 20:25:17 +0000128 Value *NGEPI = GetElementPtrInst::Create(TheAlloca, GEPIdx.begin(),
129 GEPIdx.end(),
130 "mrv.gep", I);
Devang Patelca891ec2008-02-29 23:34:08 +0000131 Value *NV = new LoadInst(NGEPI, "mrv.ld", I);
132 RetVals.push_back(NV);
133 }
134
Gabor Greif051a9502008-04-06 20:25:17 +0000135 ReturnInst *NR = ReturnInst::Create(&RetVals[0], RetVals.size(), I);
Devang Patelca891ec2008-02-29 23:34:08 +0000136 I->replaceAllUsesWith(NR);
137 I->eraseFromParent();
138 }
139 }
140
Devang Patel98a6e062008-03-04 17:44:37 +0000141 // [3] Create the new function body and insert it into the module.
Devang Patelca891ec2008-02-29 23:34:08 +0000142 Function *NF = cloneFunctionBody(F, STy);
143
Devang Patel98a6e062008-03-04 17:44:37 +0000144 // [4] Update all call sites to use new function
Devang Patelca891ec2008-02-29 23:34:08 +0000145 updateCallSites(F, NF);
146
147 F->eraseFromParent();
148 getAnalysis<CallGraph>().changeFunction(F, NF);
149 return true;
150}
151
Duncan Sands33af59d2008-05-09 12:20:10 +0000152// Check if it is ok to perform this promotion.
Devang Patelca891ec2008-02-29 23:34:08 +0000153bool SRETPromotion::isSafeToUpdateAllCallers(Function *F) {
154
155 if (F->use_empty())
156 // No users. OK to modify signature.
157 return true;
158
159 for (Value::use_iterator FnUseI = F->use_begin(), FnUseE = F->use_end();
160 FnUseI != FnUseE; ++FnUseI) {
Matthijs Kooijman257da0a2008-06-05 08:48:32 +0000161 // The function is passed in as an argument to (possibly) another function,
162 // we can't change it!
163 if (FnUseI.getOperandNo() != 0)
164 return false;
Devang Patelca891ec2008-02-29 23:34:08 +0000165
166 CallSite CS = CallSite::get(*FnUseI);
167 Instruction *Call = CS.getInstruction();
168 CallSite::arg_iterator AI = CS.arg_begin();
169 Value *FirstArg = *AI;
170
171 if (!isa<AllocaInst>(FirstArg))
172 return false;
173
174 // Check FirstArg's users.
175 for (Value::use_iterator ArgI = FirstArg->use_begin(),
176 ArgE = FirstArg->use_end(); ArgI != ArgE; ++ArgI) {
177
178 // If FirstArg user is a CallInst that does not correspond to current
179 // call site then this function F is not suitable for sret promotion.
180 if (CallInst *CI = dyn_cast<CallInst>(ArgI)) {
181 if (CI != Call)
182 return false;
183 }
184 // If FirstArg user is a GEP whose all users are not LoadInst then
185 // this function F is not suitable for sret promotion.
186 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(ArgI)) {
Devang Patele0a6a3f2008-03-05 23:39:23 +0000187 // TODO : Use dom info and insert PHINodes to collect get results
188 // from multiple call sites for this GEP.
189 if (GEP->getParent() != Call->getParent())
190 return false;
Devang Patelca891ec2008-02-29 23:34:08 +0000191 for (Value::use_iterator GEPI = GEP->use_begin(), GEPE = GEP->use_end();
192 GEPI != GEPE; ++GEPI)
193 if (!isa<LoadInst>(GEPI))
194 return false;
195 }
196 // Any other FirstArg users make this function unsuitable for sret
197 // promotion.
198 else
199 return false;
200 }
201 }
202
203 return true;
204}
205
206/// cloneFunctionBody - Create a new function based on F and
207/// insert it into module. Remove first argument. Use STy as
208/// the return type for new function.
209Function *SRETPromotion::cloneFunctionBody(Function *F,
210 const StructType *STy) {
211
Devang Patelca891ec2008-02-29 23:34:08 +0000212 const FunctionType *FTy = F->getFunctionType();
213 std::vector<const Type*> Params;
214
Devang Patel2a4821b2008-03-03 18:36:03 +0000215 // ParamAttrs - Keep track of the parameter attributes for the arguments.
Chris Lattner58d74912008-03-12 17:45:29 +0000216 SmallVector<ParamAttrsWithIndex, 8> ParamAttrsVec;
217 const PAListPtr &PAL = F->getParamAttrs();
Devang Patel2a4821b2008-03-03 18:36:03 +0000218
219 // Add any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +0000220 if (ParameterAttributes attrs = PAL.getParamAttrs(0))
Devang Patel2a4821b2008-03-03 18:36:03 +0000221 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
222
Devang Patelca891ec2008-02-29 23:34:08 +0000223 // Skip first argument.
224 Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
225 ++I;
Devang Patel8f9b5512008-03-12 00:07:03 +0000226 // 0th parameter attribute is reserved for return type.
227 // 1th parameter attribute is for first 1st sret argument.
228 unsigned ParamIndex = 2;
Devang Patelca891ec2008-02-29 23:34:08 +0000229 while (I != E) {
230 Params.push_back(I->getType());
Chris Lattner58d74912008-03-12 17:45:29 +0000231 if (ParameterAttributes Attrs = PAL.getParamAttrs(ParamIndex))
232 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(ParamIndex - 1, Attrs));
Devang Patelca891ec2008-02-29 23:34:08 +0000233 ++I;
Devang Patel2a4821b2008-03-03 18:36:03 +0000234 ++ParamIndex;
Devang Patelca891ec2008-02-29 23:34:08 +0000235 }
236
237 FunctionType *NFTy = FunctionType::get(STy, Params, FTy->isVarArg());
Gabor Greif051a9502008-04-06 20:25:17 +0000238 Function *NF = Function::Create(NFTy, F->getLinkage(), F->getName());
Duncan Sands28c3cff2008-05-26 19:58:59 +0000239 NF->copyAttributesFrom(F);
Chris Lattner58d74912008-03-12 17:45:29 +0000240 NF->setParamAttrs(PAListPtr::get(ParamAttrsVec.begin(), ParamAttrsVec.end()));
Devang Patelca891ec2008-02-29 23:34:08 +0000241 F->getParent()->getFunctionList().insert(F, NF);
242 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
243
244 // Replace arguments
245 I = F->arg_begin();
246 E = F->arg_end();
247 Function::arg_iterator NI = NF->arg_begin();
248 ++I;
249 while (I != E) {
250 I->replaceAllUsesWith(NI);
251 NI->takeName(I);
252 ++I;
253 ++NI;
254 }
255
256 return NF;
257}
258
259/// updateCallSites - Update all sites that call F to use NF.
260void SRETPromotion::updateCallSites(Function *F, Function *NF) {
261
Devang Patelca891ec2008-02-29 23:34:08 +0000262 SmallVector<Value*, 16> Args;
263
Devang Patel2a4821b2008-03-03 18:36:03 +0000264 // ParamAttrs - Keep track of the parameter attributes for the arguments.
Chris Lattner58d74912008-03-12 17:45:29 +0000265 SmallVector<ParamAttrsWithIndex, 8> ArgAttrsVec;
Devang Patel2a4821b2008-03-03 18:36:03 +0000266
Chris Lattner58d74912008-03-12 17:45:29 +0000267 for (Value::use_iterator FUI = F->use_begin(), FUE = F->use_end();
268 FUI != FUE;) {
Devang Patelca891ec2008-02-29 23:34:08 +0000269 CallSite CS = CallSite::get(*FUI);
270 ++FUI;
271 Instruction *Call = CS.getInstruction();
272
Chris Lattner58d74912008-03-12 17:45:29 +0000273 const PAListPtr &PAL = F->getParamAttrs();
Devang Patel2a4821b2008-03-03 18:36:03 +0000274 // Add any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +0000275 if (ParameterAttributes attrs = PAL.getParamAttrs(0))
Devang Patel544b92b2008-03-04 19:12:58 +0000276 ArgAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
Devang Patel2a4821b2008-03-03 18:36:03 +0000277
Devang Patelca891ec2008-02-29 23:34:08 +0000278 // Copy arguments, however skip first one.
279 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
280 Value *FirstCArg = *AI;
281 ++AI;
Devang Patel8f9b5512008-03-12 00:07:03 +0000282 // 0th parameter attribute is reserved for return type.
283 // 1th parameter attribute is for first 1st sret argument.
284 unsigned ParamIndex = 2;
Devang Patelca891ec2008-02-29 23:34:08 +0000285 while (AI != AE) {
286 Args.push_back(*AI);
Chris Lattner58d74912008-03-12 17:45:29 +0000287 if (ParameterAttributes Attrs = PAL.getParamAttrs(ParamIndex))
288 ArgAttrsVec.push_back(ParamAttrsWithIndex::get(ParamIndex - 1, Attrs));
Devang Patel2a4821b2008-03-03 18:36:03 +0000289 ++ParamIndex;
Devang Patelca891ec2008-02-29 23:34:08 +0000290 ++AI;
291 }
292
Chris Lattner58d74912008-03-12 17:45:29 +0000293
294 PAListPtr NewPAL = PAListPtr::get(ArgAttrsVec.begin(), ArgAttrsVec.end());
295
Devang Patelca891ec2008-02-29 23:34:08 +0000296 // Build new call instruction.
297 Instruction *New;
298 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Gabor Greif051a9502008-04-06 20:25:17 +0000299 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
300 Args.begin(), Args.end(), "", Call);
Devang Patelca891ec2008-02-29 23:34:08 +0000301 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner58d74912008-03-12 17:45:29 +0000302 cast<InvokeInst>(New)->setParamAttrs(NewPAL);
Devang Patelca891ec2008-02-29 23:34:08 +0000303 } else {
Gabor Greif051a9502008-04-06 20:25:17 +0000304 New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
Devang Patelca891ec2008-02-29 23:34:08 +0000305 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Chris Lattner58d74912008-03-12 17:45:29 +0000306 cast<CallInst>(New)->setParamAttrs(NewPAL);
Devang Patelca891ec2008-02-29 23:34:08 +0000307 if (cast<CallInst>(Call)->isTailCall())
308 cast<CallInst>(New)->setTailCall();
309 }
310 Args.clear();
Devang Patel544b92b2008-03-04 19:12:58 +0000311 ArgAttrsVec.clear();
Devang Patelca891ec2008-02-29 23:34:08 +0000312 New->takeName(Call);
313
314 // Update all users of sret parameter to extract value using getresult.
315 for (Value::use_iterator UI = FirstCArg->use_begin(),
316 UE = FirstCArg->use_end(); UI != UE; ) {
317 User *U2 = *UI++;
318 CallInst *C2 = dyn_cast<CallInst>(U2);
319 if (C2 && (C2 == Call))
320 continue;
321 else if (GetElementPtrInst *UGEP = dyn_cast<GetElementPtrInst>(U2)) {
Devang Patel96f9cc02008-03-04 19:22:54 +0000322 ConstantInt *Idx = dyn_cast<ConstantInt>(UGEP->getOperand(2));
323 assert (Idx && "Unexpected getelementptr index!");
324 Value *GR = new GetResultInst(New, Idx->getZExtValue(), "gr", UGEP);
Devang Patelca891ec2008-02-29 23:34:08 +0000325 for (Value::use_iterator GI = UGEP->use_begin(),
326 GE = UGEP->use_end(); GI != GE; ++GI) {
327 if (LoadInst *L = dyn_cast<LoadInst>(*GI)) {
328 L->replaceAllUsesWith(GR);
329 L->eraseFromParent();
330 }
331 }
332 UGEP->eraseFromParent();
333 }
334 else assert( 0 && "Unexpected sret parameter use");
335 }
336 Call->eraseFromParent();
337 }
338}
Devang Patela9fe8bb2008-03-04 21:32:09 +0000339
340/// nestedStructType - Return true if STy includes any
341/// other aggregate types
342bool SRETPromotion::nestedStructType(const StructType *STy) {
343 unsigned Num = STy->getNumElements();
344 for (unsigned i = 0; i < Num; i++) {
345 const Type *Ty = STy->getElementType(i);
Dan Gohman31e5bdc2008-05-23 00:12:03 +0000346 if (!Ty->isSingleValueType() && Ty != Type::VoidTy)
Devang Patela9fe8bb2008-03-04 21:32:09 +0000347 return true;
348 }
349 return false;
350}