1 //===-- StructRetPromotion.cpp - Promote sret arguments -000000------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // TODO : Describe this pass.
11 //===----------------------------------------------------------------------===//
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"
20 #include "llvm/ParamAttrsList.h"
21 #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"
27 #include "llvm/Support/Compiler.h"
31 /// SRETPromotion - This pass removes sret parameter and updates
32 /// function to use multiple return value.
34 struct VISIBILITY_HIDDEN SRETPromotion : public CallGraphSCCPass {
35 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
36 CallGraphSCCPass::getAnalysisUsage(AU);
39 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
40 static char ID; // Pass identification, replacement for typeid
41 SRETPromotion() : CallGraphSCCPass((intptr_t)&ID) {}
44 bool PromoteReturn(CallGraphNode *CGN);
45 bool isSafeToUpdateAllCallers(Function *F);
46 Function *cloneFunctionBody(Function *F, const StructType *STy);
47 void updateCallSites(Function *F, Function *NF);
50 char SRETPromotion::ID = 0;
51 RegisterPass<SRETPromotion> X("sretpromotion",
52 "Promote sret arguments to multiple ret values");
55 Pass *llvm::createStructRetPromotionPass() {
56 return new SRETPromotion();
59 bool SRETPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
62 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
63 Changed |= PromoteReturn(SCC[i]);
68 /// PromoteReturn - This method promotes function that uses StructRet paramater
69 /// into a function that uses mulitple return value.
70 bool SRETPromotion::PromoteReturn(CallGraphNode *CGN) {
71 Function *F = CGN->getFunction();
73 // Make sure that it is local to this module.
74 if (!F || !F->hasInternalLinkage())
77 // Make sure that function returns struct.
78 if (F->arg_size() == 0 || !F->isStructReturn() || F->doesNotReturn())
81 assert (F->getReturnType() == Type::VoidTy && "Invalid function return type");
82 Function::arg_iterator AI = F->arg_begin();
83 const llvm::PointerType *FArgType = dyn_cast<PointerType>(AI->getType());
84 assert (FArgType && "Invalid sret paramater type");
85 const llvm::StructType *STy =
86 dyn_cast<StructType>(FArgType->getElementType());
87 assert (STy && "Invalid sret parameter element type");
89 // Check if it is ok to perform this promotion.
90 if (isSafeToUpdateAllCallers(F) == false)
93 // [1] Replace use of sret parameter
94 AllocaInst *TheAlloca = new AllocaInst (STy, NULL, "mrv", F->getEntryBlock().begin());
95 Value *NFirstArg = F->arg_begin();
96 NFirstArg->replaceAllUsesWith(TheAlloca);
98 // Find and replace ret instructions
99 SmallVector<Value *,4> RetVals;
100 for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
101 for(BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
104 if (isa<ReturnInst>(I)) {
106 for (unsigned idx = 0; idx < STy->getNumElements(); ++idx) {
107 SmallVector<Value*, 2> GEPIdx;
108 GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, 0));
109 GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, idx));
110 Value *NGEPI = new GetElementPtrInst(TheAlloca, GEPIdx.begin(), GEPIdx.end(),
112 Value *NV = new LoadInst(NGEPI, "mrv.ld", I);
113 RetVals.push_back(NV);
116 ReturnInst *NR = new ReturnInst(&RetVals[0], RetVals.size(), I);
117 I->replaceAllUsesWith(NR);
118 I->eraseFromParent();
122 // Create the new function body and insert it into the module.
123 Function *NF = cloneFunctionBody(F, STy);
125 // Update all call sites to use new function
126 updateCallSites(F, NF);
128 F->eraseFromParent();
129 getAnalysis<CallGraph>().changeFunction(F, NF);
133 // Check if it is ok to perform this promotion.
134 bool SRETPromotion::isSafeToUpdateAllCallers(Function *F) {
137 // No users. OK to modify signature.
140 for (Value::use_iterator FnUseI = F->use_begin(), FnUseE = F->use_end();
141 FnUseI != FnUseE; ++FnUseI) {
143 CallSite CS = CallSite::get(*FnUseI);
144 Instruction *Call = CS.getInstruction();
145 CallSite::arg_iterator AI = CS.arg_begin();
146 Value *FirstArg = *AI;
148 if (!isa<AllocaInst>(FirstArg))
151 // Check FirstArg's users.
152 for (Value::use_iterator ArgI = FirstArg->use_begin(),
153 ArgE = FirstArg->use_end(); ArgI != ArgE; ++ArgI) {
155 // If FirstArg user is a CallInst that does not correspond to current
156 // call site then this function F is not suitable for sret promotion.
157 if (CallInst *CI = dyn_cast<CallInst>(ArgI)) {
161 // If FirstArg user is a GEP whose all users are not LoadInst then
162 // this function F is not suitable for sret promotion.
163 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(ArgI)) {
164 for (Value::use_iterator GEPI = GEP->use_begin(), GEPE = GEP->use_end();
165 GEPI != GEPE; ++GEPI)
166 if (!isa<LoadInst>(GEPI))
169 // Any other FirstArg users make this function unsuitable for sret
179 /// cloneFunctionBody - Create a new function based on F and
180 /// insert it into module. Remove first argument. Use STy as
181 /// the return type for new function.
182 Function *SRETPromotion::cloneFunctionBody(Function *F,
183 const StructType *STy) {
185 const FunctionType *FTy = F->getFunctionType();
186 std::vector<const Type*> Params;
188 // ParamAttrs - Keep track of the parameter attributes for the arguments.
189 ParamAttrsVector ParamAttrsVec;
190 const ParamAttrsList *PAL = F->getParamAttrs();
192 // Add any return attributes.
193 if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(0) : ParamAttr::None)
194 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
196 // Skip first argument.
197 Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
199 unsigned ParamIndex = 1; // 0th parameter attribute is reserved for return type.
201 Params.push_back(I->getType());
202 if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(ParamIndex) :
204 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Params.size(), attrs));
209 FunctionType *NFTy = FunctionType::get(STy, Params, FTy->isVarArg());
210 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
211 NF->setCallingConv(F->getCallingConv());
212 NF->setParamAttrs(ParamAttrsList::get(ParamAttrsVec));
213 F->getParent()->getFunctionList().insert(F, NF);
214 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
219 Function::arg_iterator NI = NF->arg_begin();
222 I->replaceAllUsesWith(NI);
231 /// updateCallSites - Update all sites that call F to use NF.
232 void SRETPromotion::updateCallSites(Function *F, Function *NF) {
234 SmallVector<Value*, 16> Args;
236 // ParamAttrs - Keep track of the parameter attributes for the arguments.
237 ParamAttrsVector ParamAttrsVec;
239 for (Value::use_iterator FUI = F->use_begin(), FUE = F->use_end(); FUI != FUE;) {
240 CallSite CS = CallSite::get(*FUI);
242 Instruction *Call = CS.getInstruction();
244 const ParamAttrsList *PAL = F->getParamAttrs();
245 // Add any return attributes.
246 if (ParameterAttributes attrs = PAL ? PAL->getParamAttrs(0) : ParamAttr::None)
247 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(0, attrs));
249 // Copy arguments, however skip first one.
250 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
251 Value *FirstCArg = *AI;
253 unsigned ParamIndex = 1; // 0th parameter attribute is reserved for return type.
256 if (ParameterAttributes Attrs = PAL ? PAL->getParamAttrs(ParamIndex) :
258 ParamAttrsVec.push_back(ParamAttrsWithIndex::get(Args.size(), Attrs));
263 // Build new call instruction.
265 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
266 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
267 Args.begin(), Args.end(), "", Call);
268 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
269 cast<InvokeInst>(New)->setParamAttrs(ParamAttrsList::get(ParamAttrsVec));
271 New = new CallInst(NF, Args.begin(), Args.end(), "", Call);
272 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
273 cast<CallInst>(New)->setParamAttrs(ParamAttrsList::get(ParamAttrsVec));
274 if (cast<CallInst>(Call)->isTailCall())
275 cast<CallInst>(New)->setTailCall();
278 ParamAttrsVec.clear();
281 // Update all users of sret parameter to extract value using getresult.
282 for (Value::use_iterator UI = FirstCArg->use_begin(),
283 UE = FirstCArg->use_end(); UI != UE; ) {
285 CallInst *C2 = dyn_cast<CallInst>(U2);
286 if (C2 && (C2 == Call))
288 else if (GetElementPtrInst *UGEP = dyn_cast<GetElementPtrInst>(U2)) {
289 Value *GR = new GetResultInst(New, 5, "xxx", UGEP);
290 for (Value::use_iterator GI = UGEP->use_begin(),
291 GE = UGEP->use_end(); GI != GE; ++GI) {
292 if (LoadInst *L = dyn_cast<LoadInst>(*GI)) {
293 L->replaceAllUsesWith(GR);
294 L->eraseFromParent();
297 UGEP->eraseFromParent();
299 else assert( 0 && "Unexpected sret parameter use");
301 Call->eraseFromParent();