blob: 9f54388aa45e27a0a91662562cd7d8485f3e72b8 [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
Dan Gohmanae73dc12008-09-04 17:05:41 +000052 SRETPromotion() : CallGraphSCCPass(&ID) {}
Devang Patelca891ec2008-02-29 23:34:08 +000053
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
Rafael Espindolabb46f522009-01-15 20:18:42 +000085 if (!F || F->isDeclaration() || !F->hasLocalLinkage())
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
Matthijs Kooijman81ec2482008-08-07 15:14:04 +000092 DOUT << "SretPromotion: Looking at sret function " << F->getNameStart() << "\n";
93
Devang Patelca891ec2008-02-29 23:34:08 +000094 assert (F->getReturnType() == Type::VoidTy && "Invalid function return type");
95 Function::arg_iterator AI = F->arg_begin();
96 const llvm::PointerType *FArgType = dyn_cast<PointerType>(AI->getType());
Duncan Sands33af59d2008-05-09 12:20:10 +000097 assert (FArgType && "Invalid sret parameter type");
Devang Patelca891ec2008-02-29 23:34:08 +000098 const llvm::StructType *STy =
99 dyn_cast<StructType>(FArgType->getElementType());
100 assert (STy && "Invalid sret parameter element type");
101
102 // Check if it is ok to perform this promotion.
Devang Patel98a6e062008-03-04 17:44:37 +0000103 if (isSafeToUpdateAllCallers(F) == false) {
Matthijs Kooijman81ec2482008-08-07 15:14:04 +0000104 DOUT << "SretPromotion: Not all callers can be updated\n";
Devang Patel98a6e062008-03-04 17:44:37 +0000105 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
Matthijs Kooijman81ec2482008-08-07 15:14:04 +0000109 DOUT << "SretPromotion: sret argument will be promoted\n";
Devang Pateldf1d15c2008-03-04 17:48:11 +0000110 NumSRET++;
Devang Patelca891ec2008-02-29 23:34:08 +0000111 // [1] Replace use of sret parameter
Devang Patel98a6e062008-03-04 17:44:37 +0000112 AllocaInst *TheAlloca = new AllocaInst (STy, NULL, "mrv",
113 F->getEntryBlock().begin());
Devang Patelca891ec2008-02-29 23:34:08 +0000114 Value *NFirstArg = F->arg_begin();
115 NFirstArg->replaceAllUsesWith(TheAlloca);
116
Devang Patel98a6e062008-03-04 17:44:37 +0000117 // [2] Find and replace ret instructions
Devang Patelca891ec2008-02-29 23:34:08 +0000118 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)) {
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000123 Value *NV = new LoadInst(TheAlloca, "mrv.ld", I);
Matthijs Kooijmana7bab2c2008-08-07 15:58:09 +0000124 ReturnInst *NR = ReturnInst::Create(NV, I);
Devang Patelca891ec2008-02-29 23:34:08 +0000125 I->replaceAllUsesWith(NR);
126 I->eraseFromParent();
127 }
128 }
129
Devang Patel98a6e062008-03-04 17:44:37 +0000130 // [3] Create the new function body and insert it into the module.
Devang Patelca891ec2008-02-29 23:34:08 +0000131 Function *NF = cloneFunctionBody(F, STy);
132
Devang Patel98a6e062008-03-04 17:44:37 +0000133 // [4] Update all call sites to use new function
Devang Patelca891ec2008-02-29 23:34:08 +0000134 updateCallSites(F, NF);
135
136 F->eraseFromParent();
137 getAnalysis<CallGraph>().changeFunction(F, NF);
138 return true;
139}
140
Duncan Sands33af59d2008-05-09 12:20:10 +0000141// Check if it is ok to perform this promotion.
Devang Patelca891ec2008-02-29 23:34:08 +0000142bool SRETPromotion::isSafeToUpdateAllCallers(Function *F) {
143
144 if (F->use_empty())
145 // No users. OK to modify signature.
146 return true;
147
148 for (Value::use_iterator FnUseI = F->use_begin(), FnUseE = F->use_end();
149 FnUseI != FnUseE; ++FnUseI) {
Matthijs Kooijman257da0a2008-06-05 08:48:32 +0000150 // The function is passed in as an argument to (possibly) another function,
151 // we can't change it!
Devang Patelca891ec2008-02-29 23:34:08 +0000152 CallSite CS = CallSite::get(*FnUseI);
153 Instruction *Call = CS.getInstruction();
Matthijs Kooijman47c6fd72008-06-05 08:57:20 +0000154 // The function is used by something else than a call or invoke instruction,
155 // we can't change it!
Gabor Greifedc4d692009-01-22 21:35:57 +0000156 if (!Call || !CS.isCallee(FnUseI))
Matthijs Kooijman47c6fd72008-06-05 08:57:20 +0000157 return false;
Devang Patelca891ec2008-02-29 23:34:08 +0000158 CallSite::arg_iterator AI = CS.arg_begin();
159 Value *FirstArg = *AI;
160
161 if (!isa<AllocaInst>(FirstArg))
162 return false;
163
164 // Check FirstArg's users.
165 for (Value::use_iterator ArgI = FirstArg->use_begin(),
166 ArgE = FirstArg->use_end(); ArgI != ArgE; ++ArgI) {
167
168 // If FirstArg user is a CallInst that does not correspond to current
169 // call site then this function F is not suitable for sret promotion.
170 if (CallInst *CI = dyn_cast<CallInst>(ArgI)) {
171 if (CI != Call)
172 return false;
173 }
174 // If FirstArg user is a GEP whose all users are not LoadInst then
175 // this function F is not suitable for sret promotion.
176 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(ArgI)) {
Devang Patele0a6a3f2008-03-05 23:39:23 +0000177 // TODO : Use dom info and insert PHINodes to collect get results
178 // from multiple call sites for this GEP.
179 if (GEP->getParent() != Call->getParent())
180 return false;
Devang Patelca891ec2008-02-29 23:34:08 +0000181 for (Value::use_iterator GEPI = GEP->use_begin(), GEPE = GEP->use_end();
182 GEPI != GEPE; ++GEPI)
183 if (!isa<LoadInst>(GEPI))
184 return false;
185 }
186 // Any other FirstArg users make this function unsuitable for sret
187 // promotion.
188 else
189 return false;
190 }
191 }
192
193 return true;
194}
195
196/// cloneFunctionBody - Create a new function based on F and
197/// insert it into module. Remove first argument. Use STy as
198/// the return type for new function.
199Function *SRETPromotion::cloneFunctionBody(Function *F,
200 const StructType *STy) {
201
Devang Patelca891ec2008-02-29 23:34:08 +0000202 const FunctionType *FTy = F->getFunctionType();
203 std::vector<const Type*> Params;
204
Devang Patel05988662008-09-25 21:00:45 +0000205 // Attributes - Keep track of the parameter attributes for the arguments.
206 SmallVector<AttributeWithIndex, 8> AttributesVec;
207 const AttrListPtr &PAL = F->getAttributes();
Devang Patel2a4821b2008-03-03 18:36:03 +0000208
209 // Add any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000210 if (Attributes attrs = PAL.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +0000211 AttributesVec.push_back(AttributeWithIndex::get(0, attrs));
Devang Patel2a4821b2008-03-03 18:36:03 +0000212
Devang Patelca891ec2008-02-29 23:34:08 +0000213 // Skip first argument.
214 Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
215 ++I;
Devang Patel8f9b5512008-03-12 00:07:03 +0000216 // 0th parameter attribute is reserved for return type.
217 // 1th parameter attribute is for first 1st sret argument.
218 unsigned ParamIndex = 2;
Devang Patelca891ec2008-02-29 23:34:08 +0000219 while (I != E) {
220 Params.push_back(I->getType());
Devang Patel19c87462008-09-26 22:53:05 +0000221 if (Attributes Attrs = PAL.getParamAttributes(ParamIndex))
Devang Patel05988662008-09-25 21:00:45 +0000222 AttributesVec.push_back(AttributeWithIndex::get(ParamIndex - 1, Attrs));
Devang Patelca891ec2008-02-29 23:34:08 +0000223 ++I;
Devang Patel2a4821b2008-03-03 18:36:03 +0000224 ++ParamIndex;
Devang Patelca891ec2008-02-29 23:34:08 +0000225 }
226
Devang Patel19c87462008-09-26 22:53:05 +0000227 // Add any fn attributes.
228 if (Attributes attrs = PAL.getFnAttributes())
229 AttributesVec.push_back(AttributeWithIndex::get(~0, attrs));
230
231
Devang Patelca891ec2008-02-29 23:34:08 +0000232 FunctionType *NFTy = FunctionType::get(STy, Params, FTy->isVarArg());
Matthijs Kooijman7d942002008-08-07 16:01:23 +0000233 Function *NF = Function::Create(NFTy, F->getLinkage());
234 NF->takeName(F);
Duncan Sands28c3cff2008-05-26 19:58:59 +0000235 NF->copyAttributesFrom(F);
Devang Patel05988662008-09-25 21:00:45 +0000236 NF->setAttributes(AttrListPtr::get(AttributesVec.begin(), AttributesVec.end()));
Devang Patelca891ec2008-02-29 23:34:08 +0000237 F->getParent()->getFunctionList().insert(F, NF);
238 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
239
240 // Replace arguments
241 I = F->arg_begin();
242 E = F->arg_end();
243 Function::arg_iterator NI = NF->arg_begin();
244 ++I;
245 while (I != E) {
246 I->replaceAllUsesWith(NI);
247 NI->takeName(I);
248 ++I;
249 ++NI;
250 }
251
252 return NF;
253}
254
255/// updateCallSites - Update all sites that call F to use NF.
256void SRETPromotion::updateCallSites(Function *F, Function *NF) {
Duncan Sandsa9c32512008-09-08 11:08:09 +0000257 CallGraph &CG = getAnalysis<CallGraph>();
Devang Patelca891ec2008-02-29 23:34:08 +0000258 SmallVector<Value*, 16> Args;
259
Devang Patel05988662008-09-25 21:00:45 +0000260 // Attributes - Keep track of the parameter attributes for the arguments.
261 SmallVector<AttributeWithIndex, 8> ArgAttrsVec;
Devang Patel2a4821b2008-03-03 18:36:03 +0000262
Matthijs Kooijmanc1f1d462008-08-14 15:03:05 +0000263 while (!F->use_empty()) {
264 CallSite CS = CallSite::get(*F->use_begin());
Devang Patelca891ec2008-02-29 23:34:08 +0000265 Instruction *Call = CS.getInstruction();
266
Devang Patel05988662008-09-25 21:00:45 +0000267 const AttrListPtr &PAL = F->getAttributes();
Devang Patel2a4821b2008-03-03 18:36:03 +0000268 // Add any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000269 if (Attributes attrs = PAL.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +0000270 ArgAttrsVec.push_back(AttributeWithIndex::get(0, attrs));
Devang Patel2a4821b2008-03-03 18:36:03 +0000271
Devang Patelca891ec2008-02-29 23:34:08 +0000272 // Copy arguments, however skip first one.
273 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
274 Value *FirstCArg = *AI;
275 ++AI;
Devang Patel8f9b5512008-03-12 00:07:03 +0000276 // 0th parameter attribute is reserved for return type.
277 // 1th parameter attribute is for first 1st sret argument.
278 unsigned ParamIndex = 2;
Devang Patelca891ec2008-02-29 23:34:08 +0000279 while (AI != AE) {
280 Args.push_back(*AI);
Devang Patel19c87462008-09-26 22:53:05 +0000281 if (Attributes Attrs = PAL.getParamAttributes(ParamIndex))
Devang Patel05988662008-09-25 21:00:45 +0000282 ArgAttrsVec.push_back(AttributeWithIndex::get(ParamIndex - 1, Attrs));
Devang Patel2a4821b2008-03-03 18:36:03 +0000283 ++ParamIndex;
Devang Patelca891ec2008-02-29 23:34:08 +0000284 ++AI;
285 }
286
Devang Patel19c87462008-09-26 22:53:05 +0000287 // Add any function attributes.
288 if (Attributes attrs = PAL.getFnAttributes())
289 ArgAttrsVec.push_back(AttributeWithIndex::get(~0, attrs));
Chris Lattner58d74912008-03-12 17:45:29 +0000290
Devang Patel05988662008-09-25 21:00:45 +0000291 AttrListPtr NewPAL = AttrListPtr::get(ArgAttrsVec.begin(), ArgAttrsVec.end());
Chris Lattner58d74912008-03-12 17:45:29 +0000292
Devang Patelca891ec2008-02-29 23:34:08 +0000293 // Build new call instruction.
294 Instruction *New;
295 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Gabor Greif051a9502008-04-06 20:25:17 +0000296 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
297 Args.begin(), Args.end(), "", Call);
Devang Patelca891ec2008-02-29 23:34:08 +0000298 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000299 cast<InvokeInst>(New)->setAttributes(NewPAL);
Devang Patelca891ec2008-02-29 23:34:08 +0000300 } else {
Gabor Greif051a9502008-04-06 20:25:17 +0000301 New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
Devang Patelca891ec2008-02-29 23:34:08 +0000302 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000303 cast<CallInst>(New)->setAttributes(NewPAL);
Devang Patelca891ec2008-02-29 23:34:08 +0000304 if (cast<CallInst>(Call)->isTailCall())
305 cast<CallInst>(New)->setTailCall();
306 }
307 Args.clear();
Devang Patel544b92b2008-03-04 19:12:58 +0000308 ArgAttrsVec.clear();
Devang Patelca891ec2008-02-29 23:34:08 +0000309 New->takeName(Call);
310
Duncan Sandsa9c32512008-09-08 11:08:09 +0000311 // Update the callgraph to know that the callsite has been transformed.
312 CG[Call->getParent()->getParent()]->replaceCallSite(Call, New);
313
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000314 // Update all users of sret parameter to extract value using extractvalue.
Devang Patelca891ec2008-02-29 23:34:08 +0000315 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!");
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000324 Value *GR = ExtractValueInst::Create(New, Idx->getZExtValue(),
325 "evi", UGEP);
Matthijs Kooijmanc1f1d462008-08-14 15:03:05 +0000326 while(!UGEP->use_empty()) {
327 // isSafeToUpdateAllCallers has checked that all GEP uses are
328 // LoadInsts
329 LoadInst *L = cast<LoadInst>(*UGEP->use_begin());
330 L->replaceAllUsesWith(GR);
331 L->eraseFromParent();
Devang Patelca891ec2008-02-29 23:34:08 +0000332 }
333 UGEP->eraseFromParent();
334 }
335 else assert( 0 && "Unexpected sret parameter use");
336 }
337 Call->eraseFromParent();
338 }
339}
Devang Patela9fe8bb2008-03-04 21:32:09 +0000340
341/// nestedStructType - Return true if STy includes any
342/// other aggregate types
343bool SRETPromotion::nestedStructType(const StructType *STy) {
344 unsigned Num = STy->getNumElements();
345 for (unsigned i = 0; i < Num; i++) {
346 const Type *Ty = STy->getElementType(i);
Dan Gohman31e5bdc2008-05-23 00:12:03 +0000347 if (!Ty->isSingleValueType() && Ty != Type::VoidTy)
Devang Patela9fe8bb2008-03-04 21:32:09 +0000348 return true;
349 }
350 return false;
351}