blob: 94b37a219114a501d8cde8cb965fc6ba4724c6f7 [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"
Owen Anderson14ce9ef2009-07-06 01:34:54 +000026#include "llvm/LLVMContext.h"
Devang Patelca891ec2008-02-29 23:34:08 +000027#include "llvm/Module.h"
28#include "llvm/CallGraphSCCPass.h"
29#include "llvm/Instructions.h"
30#include "llvm/Analysis/CallGraph.h"
31#include "llvm/Support/CallSite.h"
32#include "llvm/Support/CFG.h"
33#include "llvm/Support/Debug.h"
34#include "llvm/ADT/Statistic.h"
35#include "llvm/ADT/SmallVector.h"
Devang Patel98a6e062008-03-04 17:44:37 +000036#include "llvm/ADT/Statistic.h"
Devang Patelca891ec2008-02-29 23:34:08 +000037#include "llvm/Support/Compiler.h"
38using namespace llvm;
39
Devang Patel98a6e062008-03-04 17:44:37 +000040STATISTIC(NumRejectedSRETUses , "Number of sret rejected due to unexpected uses");
41STATISTIC(NumSRET , "Number of sret promoted");
Devang Patelca891ec2008-02-29 23:34:08 +000042namespace {
43 /// SRETPromotion - This pass removes sret parameter and updates
44 /// function to use multiple return value.
45 ///
46 struct VISIBILITY_HIDDEN SRETPromotion : public CallGraphSCCPass {
47 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
48 CallGraphSCCPass::getAnalysisUsage(AU);
49 }
50
51 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
52 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000053 SRETPromotion() : CallGraphSCCPass(&ID) {}
Devang Patelca891ec2008-02-29 23:34:08 +000054
55 private:
56 bool PromoteReturn(CallGraphNode *CGN);
57 bool isSafeToUpdateAllCallers(Function *F);
58 Function *cloneFunctionBody(Function *F, const StructType *STy);
59 void updateCallSites(Function *F, Function *NF);
Devang Patela9fe8bb2008-03-04 21:32:09 +000060 bool nestedStructType(const StructType *STy);
Devang Patelca891ec2008-02-29 23:34:08 +000061 };
Devang Patelca891ec2008-02-29 23:34:08 +000062}
63
Dan Gohman844731a2008-05-13 00:00:25 +000064char SRETPromotion::ID = 0;
65static RegisterPass<SRETPromotion>
66X("sretpromotion", "Promote sret arguments to multiple ret values");
67
Devang Patelca891ec2008-02-29 23:34:08 +000068Pass *llvm::createStructRetPromotionPass() {
69 return new SRETPromotion();
70}
71
72bool SRETPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
73 bool Changed = false;
74
75 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
76 Changed |= PromoteReturn(SCC[i]);
77
78 return Changed;
79}
80
81/// PromoteReturn - This method promotes function that uses StructRet paramater
82/// into a function that uses mulitple return value.
83bool SRETPromotion::PromoteReturn(CallGraphNode *CGN) {
84 Function *F = CGN->getFunction();
85
Rafael Espindolabb46f522009-01-15 20:18:42 +000086 if (!F || F->isDeclaration() || !F->hasLocalLinkage())
Devang Patelca891ec2008-02-29 23:34:08 +000087 return false;
88
89 // Make sure that function returns struct.
Devang Patel41e23972008-03-03 21:46:28 +000090 if (F->arg_size() == 0 || !F->hasStructRetAttr() || F->doesNotReturn())
Devang Patelca891ec2008-02-29 23:34:08 +000091 return false;
92
Matthijs Kooijman81ec2482008-08-07 15:14:04 +000093 DOUT << "SretPromotion: Looking at sret function " << F->getNameStart() << "\n";
94
Devang Patelca891ec2008-02-29 23:34:08 +000095 assert (F->getReturnType() == Type::VoidTy && "Invalid function return type");
96 Function::arg_iterator AI = F->arg_begin();
97 const llvm::PointerType *FArgType = dyn_cast<PointerType>(AI->getType());
Duncan Sands33af59d2008-05-09 12:20:10 +000098 assert (FArgType && "Invalid sret parameter type");
Devang Patelca891ec2008-02-29 23:34:08 +000099 const llvm::StructType *STy =
100 dyn_cast<StructType>(FArgType->getElementType());
101 assert (STy && "Invalid sret parameter element type");
102
103 // Check if it is ok to perform this promotion.
Devang Patel98a6e062008-03-04 17:44:37 +0000104 if (isSafeToUpdateAllCallers(F) == false) {
Matthijs Kooijman81ec2482008-08-07 15:14:04 +0000105 DOUT << "SretPromotion: Not all callers can be updated\n";
Devang Patel98a6e062008-03-04 17:44:37 +0000106 NumRejectedSRETUses++;
Devang Patelca891ec2008-02-29 23:34:08 +0000107 return false;
Devang Patel98a6e062008-03-04 17:44:37 +0000108 }
Devang Patelca891ec2008-02-29 23:34:08 +0000109
Matthijs Kooijman81ec2482008-08-07 15:14:04 +0000110 DOUT << "SretPromotion: sret argument will be promoted\n";
Devang Pateldf1d15c2008-03-04 17:48:11 +0000111 NumSRET++;
Devang Patelca891ec2008-02-29 23:34:08 +0000112 // [1] Replace use of sret parameter
Devang Patel98a6e062008-03-04 17:44:37 +0000113 AllocaInst *TheAlloca = new AllocaInst (STy, NULL, "mrv",
114 F->getEntryBlock().begin());
Devang Patelca891ec2008-02-29 23:34:08 +0000115 Value *NFirstArg = F->arg_begin();
116 NFirstArg->replaceAllUsesWith(TheAlloca);
117
Devang Patel98a6e062008-03-04 17:44:37 +0000118 // [2] Find and replace ret instructions
Devang Patelca891ec2008-02-29 23:34:08 +0000119 for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
120 for(BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
121 Instruction *I = BI;
122 ++BI;
123 if (isa<ReturnInst>(I)) {
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000124 Value *NV = new LoadInst(TheAlloca, "mrv.ld", I);
Matthijs Kooijmana7bab2c2008-08-07 15:58:09 +0000125 ReturnInst *NR = ReturnInst::Create(NV, I);
Devang Patelca891ec2008-02-29 23:34:08 +0000126 I->replaceAllUsesWith(NR);
127 I->eraseFromParent();
128 }
129 }
130
Devang Patel98a6e062008-03-04 17:44:37 +0000131 // [3] Create the new function body and insert it into the module.
Devang Patelca891ec2008-02-29 23:34:08 +0000132 Function *NF = cloneFunctionBody(F, STy);
133
Devang Patel98a6e062008-03-04 17:44:37 +0000134 // [4] Update all call sites to use new function
Devang Patelca891ec2008-02-29 23:34:08 +0000135 updateCallSites(F, NF);
136
137 F->eraseFromParent();
138 getAnalysis<CallGraph>().changeFunction(F, NF);
139 return true;
140}
141
Duncan Sands33af59d2008-05-09 12:20:10 +0000142// Check if it is ok to perform this promotion.
Devang Patelca891ec2008-02-29 23:34:08 +0000143bool SRETPromotion::isSafeToUpdateAllCallers(Function *F) {
144
145 if (F->use_empty())
146 // No users. OK to modify signature.
147 return true;
148
149 for (Value::use_iterator FnUseI = F->use_begin(), FnUseE = F->use_end();
150 FnUseI != FnUseE; ++FnUseI) {
Matthijs Kooijman257da0a2008-06-05 08:48:32 +0000151 // The function is passed in as an argument to (possibly) another function,
152 // we can't change it!
Devang Patelca891ec2008-02-29 23:34:08 +0000153 CallSite CS = CallSite::get(*FnUseI);
154 Instruction *Call = CS.getInstruction();
Matthijs Kooijman47c6fd72008-06-05 08:57:20 +0000155 // The function is used by something else than a call or invoke instruction,
156 // we can't change it!
Gabor Greifedc4d692009-01-22 21:35:57 +0000157 if (!Call || !CS.isCallee(FnUseI))
Matthijs Kooijman47c6fd72008-06-05 08:57:20 +0000158 return false;
Devang Patelca891ec2008-02-29 23:34:08 +0000159 CallSite::arg_iterator AI = CS.arg_begin();
160 Value *FirstArg = *AI;
161
162 if (!isa<AllocaInst>(FirstArg))
163 return false;
164
165 // Check FirstArg's users.
166 for (Value::use_iterator ArgI = FirstArg->use_begin(),
167 ArgE = FirstArg->use_end(); ArgI != ArgE; ++ArgI) {
168
169 // If FirstArg user is a CallInst that does not correspond to current
170 // call site then this function F is not suitable for sret promotion.
171 if (CallInst *CI = dyn_cast<CallInst>(ArgI)) {
172 if (CI != Call)
173 return false;
174 }
175 // If FirstArg user is a GEP whose all users are not LoadInst then
176 // this function F is not suitable for sret promotion.
177 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(ArgI)) {
Devang Patele0a6a3f2008-03-05 23:39:23 +0000178 // TODO : Use dom info and insert PHINodes to collect get results
179 // from multiple call sites for this GEP.
180 if (GEP->getParent() != Call->getParent())
181 return false;
Devang Patelca891ec2008-02-29 23:34:08 +0000182 for (Value::use_iterator GEPI = GEP->use_begin(), GEPE = GEP->use_end();
183 GEPI != GEPE; ++GEPI)
184 if (!isa<LoadInst>(GEPI))
185 return false;
186 }
187 // Any other FirstArg users make this function unsuitable for sret
188 // promotion.
189 else
190 return false;
191 }
192 }
193
194 return true;
195}
196
197/// cloneFunctionBody - Create a new function based on F and
198/// insert it into module. Remove first argument. Use STy as
199/// the return type for new function.
200Function *SRETPromotion::cloneFunctionBody(Function *F,
201 const StructType *STy) {
202
Devang Patelca891ec2008-02-29 23:34:08 +0000203 const FunctionType *FTy = F->getFunctionType();
204 std::vector<const Type*> Params;
205
Devang Patel05988662008-09-25 21:00:45 +0000206 // Attributes - Keep track of the parameter attributes for the arguments.
207 SmallVector<AttributeWithIndex, 8> AttributesVec;
208 const AttrListPtr &PAL = F->getAttributes();
Devang Patel2a4821b2008-03-03 18:36:03 +0000209
210 // Add any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000211 if (Attributes attrs = PAL.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +0000212 AttributesVec.push_back(AttributeWithIndex::get(0, attrs));
Devang Patel2a4821b2008-03-03 18:36:03 +0000213
Devang Patelca891ec2008-02-29 23:34:08 +0000214 // Skip first argument.
215 Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
216 ++I;
Devang Patel8f9b5512008-03-12 00:07:03 +0000217 // 0th parameter attribute is reserved for return type.
218 // 1th parameter attribute is for first 1st sret argument.
219 unsigned ParamIndex = 2;
Devang Patelca891ec2008-02-29 23:34:08 +0000220 while (I != E) {
221 Params.push_back(I->getType());
Devang Patel19c87462008-09-26 22:53:05 +0000222 if (Attributes Attrs = PAL.getParamAttributes(ParamIndex))
Devang Patel05988662008-09-25 21:00:45 +0000223 AttributesVec.push_back(AttributeWithIndex::get(ParamIndex - 1, Attrs));
Devang Patelca891ec2008-02-29 23:34:08 +0000224 ++I;
Devang Patel2a4821b2008-03-03 18:36:03 +0000225 ++ParamIndex;
Devang Patelca891ec2008-02-29 23:34:08 +0000226 }
227
Devang Patel19c87462008-09-26 22:53:05 +0000228 // Add any fn attributes.
229 if (Attributes attrs = PAL.getFnAttributes())
230 AttributesVec.push_back(AttributeWithIndex::get(~0, attrs));
231
232
Owen Anderson14ce9ef2009-07-06 01:34:54 +0000233 FunctionType *NFTy = Context->getFunctionType(STy, Params, FTy->isVarArg());
Matthijs Kooijman7d942002008-08-07 16:01:23 +0000234 Function *NF = Function::Create(NFTy, F->getLinkage());
235 NF->takeName(F);
Duncan Sands28c3cff2008-05-26 19:58:59 +0000236 NF->copyAttributesFrom(F);
Devang Patel05988662008-09-25 21:00:45 +0000237 NF->setAttributes(AttrListPtr::get(AttributesVec.begin(), AttributesVec.end()));
Devang Patelca891ec2008-02-29 23:34:08 +0000238 F->getParent()->getFunctionList().insert(F, NF);
239 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
240
241 // Replace arguments
242 I = F->arg_begin();
243 E = F->arg_end();
244 Function::arg_iterator NI = NF->arg_begin();
245 ++I;
246 while (I != E) {
247 I->replaceAllUsesWith(NI);
248 NI->takeName(I);
249 ++I;
250 ++NI;
251 }
252
253 return NF;
254}
255
256/// updateCallSites - Update all sites that call F to use NF.
257void SRETPromotion::updateCallSites(Function *F, Function *NF) {
Duncan Sandsa9c32512008-09-08 11:08:09 +0000258 CallGraph &CG = getAnalysis<CallGraph>();
Devang Patelca891ec2008-02-29 23:34:08 +0000259 SmallVector<Value*, 16> Args;
260
Devang Patel05988662008-09-25 21:00:45 +0000261 // Attributes - Keep track of the parameter attributes for the arguments.
262 SmallVector<AttributeWithIndex, 8> ArgAttrsVec;
Devang Patel2a4821b2008-03-03 18:36:03 +0000263
Matthijs Kooijmanc1f1d462008-08-14 15:03:05 +0000264 while (!F->use_empty()) {
265 CallSite CS = CallSite::get(*F->use_begin());
Devang Patelca891ec2008-02-29 23:34:08 +0000266 Instruction *Call = CS.getInstruction();
267
Devang Patel05988662008-09-25 21:00:45 +0000268 const AttrListPtr &PAL = F->getAttributes();
Devang Patel2a4821b2008-03-03 18:36:03 +0000269 // Add any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +0000270 if (Attributes attrs = PAL.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +0000271 ArgAttrsVec.push_back(AttributeWithIndex::get(0, attrs));
Devang Patel2a4821b2008-03-03 18:36:03 +0000272
Devang Patelca891ec2008-02-29 23:34:08 +0000273 // Copy arguments, however skip first one.
274 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
275 Value *FirstCArg = *AI;
276 ++AI;
Devang Patel8f9b5512008-03-12 00:07:03 +0000277 // 0th parameter attribute is reserved for return type.
278 // 1th parameter attribute is for first 1st sret argument.
279 unsigned ParamIndex = 2;
Devang Patelca891ec2008-02-29 23:34:08 +0000280 while (AI != AE) {
281 Args.push_back(*AI);
Devang Patel19c87462008-09-26 22:53:05 +0000282 if (Attributes Attrs = PAL.getParamAttributes(ParamIndex))
Devang Patel05988662008-09-25 21:00:45 +0000283 ArgAttrsVec.push_back(AttributeWithIndex::get(ParamIndex - 1, Attrs));
Devang Patel2a4821b2008-03-03 18:36:03 +0000284 ++ParamIndex;
Devang Patelca891ec2008-02-29 23:34:08 +0000285 ++AI;
286 }
287
Devang Patel19c87462008-09-26 22:53:05 +0000288 // Add any function attributes.
289 if (Attributes attrs = PAL.getFnAttributes())
290 ArgAttrsVec.push_back(AttributeWithIndex::get(~0, attrs));
Chris Lattner58d74912008-03-12 17:45:29 +0000291
Devang Patel05988662008-09-25 21:00:45 +0000292 AttrListPtr NewPAL = AttrListPtr::get(ArgAttrsVec.begin(), ArgAttrsVec.end());
Chris Lattner58d74912008-03-12 17:45:29 +0000293
Devang Patelca891ec2008-02-29 23:34:08 +0000294 // Build new call instruction.
295 Instruction *New;
296 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
Gabor Greif051a9502008-04-06 20:25:17 +0000297 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
298 Args.begin(), Args.end(), "", Call);
Devang Patelca891ec2008-02-29 23:34:08 +0000299 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000300 cast<InvokeInst>(New)->setAttributes(NewPAL);
Devang Patelca891ec2008-02-29 23:34:08 +0000301 } else {
Gabor Greif051a9502008-04-06 20:25:17 +0000302 New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
Devang Patelca891ec2008-02-29 23:34:08 +0000303 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +0000304 cast<CallInst>(New)->setAttributes(NewPAL);
Devang Patelca891ec2008-02-29 23:34:08 +0000305 if (cast<CallInst>(Call)->isTailCall())
306 cast<CallInst>(New)->setTailCall();
307 }
308 Args.clear();
Devang Patel544b92b2008-03-04 19:12:58 +0000309 ArgAttrsVec.clear();
Devang Patelca891ec2008-02-29 23:34:08 +0000310 New->takeName(Call);
311
Duncan Sandsa9c32512008-09-08 11:08:09 +0000312 // Update the callgraph to know that the callsite has been transformed.
313 CG[Call->getParent()->getParent()]->replaceCallSite(Call, New);
314
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000315 // Update all users of sret parameter to extract value using extractvalue.
Devang Patelca891ec2008-02-29 23:34:08 +0000316 for (Value::use_iterator UI = FirstCArg->use_begin(),
317 UE = FirstCArg->use_end(); UI != UE; ) {
318 User *U2 = *UI++;
319 CallInst *C2 = dyn_cast<CallInst>(U2);
320 if (C2 && (C2 == Call))
321 continue;
322 else if (GetElementPtrInst *UGEP = dyn_cast<GetElementPtrInst>(U2)) {
Devang Patel96f9cc02008-03-04 19:22:54 +0000323 ConstantInt *Idx = dyn_cast<ConstantInt>(UGEP->getOperand(2));
324 assert (Idx && "Unexpected getelementptr index!");
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000325 Value *GR = ExtractValueInst::Create(New, Idx->getZExtValue(),
326 "evi", UGEP);
Matthijs Kooijmanc1f1d462008-08-14 15:03:05 +0000327 while(!UGEP->use_empty()) {
328 // isSafeToUpdateAllCallers has checked that all GEP uses are
329 // LoadInsts
330 LoadInst *L = cast<LoadInst>(*UGEP->use_begin());
331 L->replaceAllUsesWith(GR);
332 L->eraseFromParent();
Devang Patelca891ec2008-02-29 23:34:08 +0000333 }
334 UGEP->eraseFromParent();
335 }
336 else assert( 0 && "Unexpected sret parameter use");
337 }
338 Call->eraseFromParent();
339 }
340}
Devang Patela9fe8bb2008-03-04 21:32:09 +0000341
342/// nestedStructType - Return true if STy includes any
343/// other aggregate types
344bool SRETPromotion::nestedStructType(const StructType *STy) {
345 unsigned Num = STy->getNumElements();
346 for (unsigned i = 0; i < Num; i++) {
347 const Type *Ty = STy->getElementType(i);
Dan Gohman31e5bdc2008-05-23 00:12:03 +0000348 if (!Ty->isSingleValueType() && Ty != Type::VoidTy)
Devang Patela9fe8bb2008-03-04 21:32:09 +0000349 return true;
350 }
351 return false;
352}