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/Analysis/CallGraph.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Support/CFG.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/Support/Compiler.h"
30 /// SRETPromotion - This pass removes sret parameter and updates
31 /// function to use multiple return value.
33 struct VISIBILITY_HIDDEN SRETPromotion : public CallGraphSCCPass {
34 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
35 CallGraphSCCPass::getAnalysisUsage(AU);
38 virtual bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
39 static char ID; // Pass identification, replacement for typeid
40 SRETPromotion() : CallGraphSCCPass((intptr_t)&ID) {}
43 bool PromoteReturn(CallGraphNode *CGN);
44 bool isSafeToUpdateAllCallers(Function *F);
45 Function *cloneFunctionBody(Function *F, const StructType *STy);
46 void updateCallSites(Function *F, Function *NF);
49 char SRETPromotion::ID = 0;
50 RegisterPass<SRETPromotion> X("sretpromotion",
51 "Promote sret arguments to multiple ret values");
54 Pass *llvm::createStructRetPromotionPass() {
55 return new SRETPromotion();
58 bool SRETPromotion::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
61 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
62 Changed |= PromoteReturn(SCC[i]);
67 /// PromoteReturn - This method promotes function that uses StructRet paramater
68 /// into a function that uses mulitple return value.
69 bool SRETPromotion::PromoteReturn(CallGraphNode *CGN) {
70 Function *F = CGN->getFunction();
72 // Make sure that it is local to this module.
73 if (!F || !F->hasInternalLinkage())
76 // Make sure that function returns struct.
77 if (F->arg_size() == 0 || !F->isStructReturn() || F->doesNotReturn())
80 assert (F->getReturnType() == Type::VoidTy && "Invalid function return type");
81 Function::arg_iterator AI = F->arg_begin();
82 const llvm::PointerType *FArgType = dyn_cast<PointerType>(AI->getType());
83 assert (FArgType && "Invalid sret paramater type");
84 const llvm::StructType *STy =
85 dyn_cast<StructType>(FArgType->getElementType());
86 assert (STy && "Invalid sret parameter element type");
88 // Check if it is ok to perform this promotion.
89 if (isSafeToUpdateAllCallers(F) == false)
92 // [1] Replace use of sret parameter
93 AllocaInst *TheAlloca = new AllocaInst (STy, NULL, "mrv", F->getEntryBlock().begin());
94 Value *NFirstArg = F->arg_begin();
95 NFirstArg->replaceAllUsesWith(TheAlloca);
97 // Find and replace ret instructions
98 SmallVector<Value *,4> RetVals;
99 for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
100 for(BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
103 if (isa<ReturnInst>(I)) {
105 for (unsigned idx = 0; idx < STy->getNumElements(); ++idx) {
106 SmallVector<Value*, 2> GEPIdx;
107 GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, 0));
108 GEPIdx.push_back(ConstantInt::get(Type::Int32Ty, idx));
109 Value *NGEPI = new GetElementPtrInst(TheAlloca, GEPIdx.begin(), GEPIdx.end(),
111 Value *NV = new LoadInst(NGEPI, "mrv.ld", I);
112 RetVals.push_back(NV);
115 ReturnInst *NR = new ReturnInst(&RetVals[0], RetVals.size(), I);
116 I->replaceAllUsesWith(NR);
117 I->eraseFromParent();
121 // Create the new function body and insert it into the module.
122 Function *NF = cloneFunctionBody(F, STy);
124 // Update all call sites to use new function
125 updateCallSites(F, NF);
127 F->eraseFromParent();
128 getAnalysis<CallGraph>().changeFunction(F, NF);
132 // Check if it is ok to perform this promotion.
133 bool SRETPromotion::isSafeToUpdateAllCallers(Function *F) {
136 // No users. OK to modify signature.
139 for (Value::use_iterator FnUseI = F->use_begin(), FnUseE = F->use_end();
140 FnUseI != FnUseE; ++FnUseI) {
142 CallSite CS = CallSite::get(*FnUseI);
143 Instruction *Call = CS.getInstruction();
144 CallSite::arg_iterator AI = CS.arg_begin();
145 Value *FirstArg = *AI;
147 if (!isa<AllocaInst>(FirstArg))
150 // Check FirstArg's users.
151 for (Value::use_iterator ArgI = FirstArg->use_begin(),
152 ArgE = FirstArg->use_end(); ArgI != ArgE; ++ArgI) {
154 // If FirstArg user is a CallInst that does not correspond to current
155 // call site then this function F is not suitable for sret promotion.
156 if (CallInst *CI = dyn_cast<CallInst>(ArgI)) {
160 // If FirstArg user is a GEP whose all users are not LoadInst then
161 // this function F is not suitable for sret promotion.
162 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(ArgI)) {
163 for (Value::use_iterator GEPI = GEP->use_begin(), GEPE = GEP->use_end();
164 GEPI != GEPE; ++GEPI)
165 if (!isa<LoadInst>(GEPI))
168 // Any other FirstArg users make this function unsuitable for sret
178 /// cloneFunctionBody - Create a new function based on F and
179 /// insert it into module. Remove first argument. Use STy as
180 /// the return type for new function.
181 Function *SRETPromotion::cloneFunctionBody(Function *F,
182 const StructType *STy) {
184 // FIXME : Do not drop param attributes on the floor.
185 const FunctionType *FTy = F->getFunctionType();
186 std::vector<const Type*> Params;
188 // Skip first argument.
189 Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
192 Params.push_back(I->getType());
196 FunctionType *NFTy = FunctionType::get(STy, Params, FTy->isVarArg());
197 Function *NF = new Function(NFTy, F->getLinkage(), F->getName());
198 NF->setCallingConv(F->getCallingConv());
199 F->getParent()->getFunctionList().insert(F, NF);
200 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
205 Function::arg_iterator NI = NF->arg_begin();
208 I->replaceAllUsesWith(NI);
217 /// updateCallSites - Update all sites that call F to use NF.
218 void SRETPromotion::updateCallSites(Function *F, Function *NF) {
220 // FIXME : Handle parameter attributes
221 SmallVector<Value*, 16> Args;
223 for (Value::use_iterator FUI = F->use_begin(), FUE = F->use_end(); FUI != FUE;) {
224 CallSite CS = CallSite::get(*FUI);
226 Instruction *Call = CS.getInstruction();
228 // Copy arguments, however skip first one.
229 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
230 Value *FirstCArg = *AI;
237 // Build new call instruction.
239 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
240 New = new InvokeInst(NF, II->getNormalDest(), II->getUnwindDest(),
241 Args.begin(), Args.end(), "", Call);
242 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
244 New = new CallInst(NF, Args.begin(), Args.end(), "", Call);
245 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
246 if (cast<CallInst>(Call)->isTailCall())
247 cast<CallInst>(New)->setTailCall();
252 // Update all users of sret parameter to extract value using getresult.
253 for (Value::use_iterator UI = FirstCArg->use_begin(),
254 UE = FirstCArg->use_end(); UI != UE; ) {
256 CallInst *C2 = dyn_cast<CallInst>(U2);
257 if (C2 && (C2 == Call))
259 else if (GetElementPtrInst *UGEP = dyn_cast<GetElementPtrInst>(U2)) {
260 Value *GR = new GetResultInst(New, 5, "xxx", UGEP);
261 for (Value::use_iterator GI = UGEP->use_begin(),
262 GE = UGEP->use_end(); GI != GE; ++GI) {
263 if (LoadInst *L = dyn_cast<LoadInst>(*GI)) {
264 L->replaceAllUsesWith(GR);
265 L->eraseFromParent();
268 UGEP->eraseFromParent();
270 else assert( 0 && "Unexpected sret parameter use");
272 Call->eraseFromParent();