1 //===-- StructRetPromotion.cpp - Promote sret arguments -------------------===//
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 // 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).
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
20 //===----------------------------------------------------------------------===//
22 #define DEBUG_TYPE "sretpromotion"
23 #include "llvm/Transforms/IPO.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/LLVMContext.h"
27 #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"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/Support/raw_ostream.h"
40 STATISTIC(NumRejectedSRETUses , "Number of sret rejected due to unexpected uses");
41 STATISTIC(NumSRET , "Number of sret promoted");
43 /// SRETPromotion - This pass removes sret parameter and updates
44 /// function to use multiple return value.
46 struct SRETPromotion : public CallGraphSCCPass {
47 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
48 CallGraphSCCPass::getAnalysisUsage(AU);
51 virtual bool runOnSCC(CallGraphSCC &SCC);
52 static char ID; // Pass identification, replacement for typeid
53 SRETPromotion() : CallGraphSCCPass(ID) {}
56 CallGraphNode *PromoteReturn(CallGraphNode *CGN);
57 bool isSafeToUpdateAllCallers(Function *F);
58 Function *cloneFunctionBody(Function *F, const StructType *STy);
59 CallGraphNode *updateCallSites(Function *F, Function *NF);
63 char SRETPromotion::ID = 0;
64 INITIALIZE_PASS(SRETPromotion, "sretpromotion",
65 "Promote sret arguments to multiple ret values", false, false);
67 Pass *llvm::createStructRetPromotionPass() {
68 return new SRETPromotion();
71 bool SRETPromotion::runOnSCC(CallGraphSCC &SCC) {
74 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
75 if (CallGraphNode *NewNode = PromoteReturn(*I)) {
76 SCC.ReplaceNode(*I, NewNode);
83 /// PromoteReturn - This method promotes function that uses StructRet paramater
84 /// into a function that uses multiple return values.
85 CallGraphNode *SRETPromotion::PromoteReturn(CallGraphNode *CGN) {
86 Function *F = CGN->getFunction();
88 if (!F || F->isDeclaration() || !F->hasLocalLinkage())
91 // Make sure that function returns struct.
92 if (F->arg_size() == 0 || !F->hasStructRetAttr() || F->doesNotReturn())
95 DEBUG(dbgs() << "SretPromotion: Looking at sret function "
96 << F->getName() << "\n");
98 assert(F->getReturnType()->isVoidTy() && "Invalid function return type");
99 Function::arg_iterator AI = F->arg_begin();
100 const llvm::PointerType *FArgType = dyn_cast<PointerType>(AI->getType());
101 assert(FArgType && "Invalid sret parameter type");
102 const llvm::StructType *STy =
103 dyn_cast<StructType>(FArgType->getElementType());
104 assert(STy && "Invalid sret parameter element type");
106 // Check if it is ok to perform this promotion.
107 if (isSafeToUpdateAllCallers(F) == false) {
108 DEBUG(dbgs() << "SretPromotion: Not all callers can be updated\n");
109 ++NumRejectedSRETUses;
113 DEBUG(dbgs() << "SretPromotion: sret argument will be promoted\n");
115 // [1] Replace use of sret parameter
116 AllocaInst *TheAlloca = new AllocaInst(STy, NULL, "mrv",
117 F->getEntryBlock().begin());
118 Value *NFirstArg = F->arg_begin();
119 NFirstArg->replaceAllUsesWith(TheAlloca);
121 // [2] Find and replace ret instructions
122 for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
123 for(BasicBlock::iterator BI = FI->begin(), BE = FI->end(); BI != BE; ) {
126 if (isa<ReturnInst>(I)) {
127 Value *NV = new LoadInst(TheAlloca, "mrv.ld", I);
128 ReturnInst *NR = ReturnInst::Create(F->getContext(), NV, I);
129 I->replaceAllUsesWith(NR);
130 I->eraseFromParent();
134 // [3] Create the new function body and insert it into the module.
135 Function *NF = cloneFunctionBody(F, STy);
137 // [4] Update all call sites to use new function
138 CallGraphNode *NF_CFN = updateCallSites(F, NF);
140 CallGraph &CG = getAnalysis<CallGraph>();
141 NF_CFN->stealCalledFunctionsFrom(CG[F]);
143 delete CG.removeFunctionFromModule(F);
147 // Check if it is ok to perform this promotion.
148 bool SRETPromotion::isSafeToUpdateAllCallers(Function *F) {
151 // No users. OK to modify signature.
154 for (Value::use_iterator FnUseI = F->use_begin(), FnUseE = F->use_end();
155 FnUseI != FnUseE; ++FnUseI) {
156 // The function is passed in as an argument to (possibly) another function,
157 // we can't change it!
158 CallSite CS(*FnUseI);
159 Instruction *Call = CS.getInstruction();
160 // The function is used by something else than a call or invoke instruction,
161 // we can't change it!
162 if (!Call || !CS.isCallee(FnUseI))
164 CallSite::arg_iterator AI = CS.arg_begin();
165 Value *FirstArg = *AI;
167 if (!isa<AllocaInst>(FirstArg))
170 // Check FirstArg's users.
171 for (Value::use_iterator ArgI = FirstArg->use_begin(),
172 ArgE = FirstArg->use_end(); ArgI != ArgE; ++ArgI) {
174 // If FirstArg user is a CallInst that does not correspond to current
175 // call site then this function F is not suitable for sret promotion.
176 if (CallInst *CI = dyn_cast<CallInst>(U)) {
180 // If FirstArg user is a GEP whose all users are not LoadInst then
181 // this function F is not suitable for sret promotion.
182 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
183 // TODO : Use dom info and insert PHINodes to collect get results
184 // from multiple call sites for this GEP.
185 if (GEP->getParent() != Call->getParent())
187 for (Value::use_iterator GEPI = GEP->use_begin(), GEPE = GEP->use_end();
188 GEPI != GEPE; ++GEPI)
189 if (!isa<LoadInst>(*GEPI))
192 // Any other FirstArg users make this function unsuitable for sret
202 /// cloneFunctionBody - Create a new function based on F and
203 /// insert it into module. Remove first argument. Use STy as
204 /// the return type for new function.
205 Function *SRETPromotion::cloneFunctionBody(Function *F,
206 const StructType *STy) {
208 const FunctionType *FTy = F->getFunctionType();
209 std::vector<const Type*> Params;
211 // Attributes - Keep track of the parameter attributes for the arguments.
212 SmallVector<AttributeWithIndex, 8> AttributesVec;
213 const AttrListPtr &PAL = F->getAttributes();
215 // Add any return attributes.
216 if (Attributes attrs = PAL.getRetAttributes())
217 AttributesVec.push_back(AttributeWithIndex::get(0, attrs));
219 // Skip first argument.
220 Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
222 // 0th parameter attribute is reserved for return type.
223 // 1th parameter attribute is for first 1st sret argument.
224 unsigned ParamIndex = 2;
226 Params.push_back(I->getType());
227 if (Attributes Attrs = PAL.getParamAttributes(ParamIndex))
228 AttributesVec.push_back(AttributeWithIndex::get(ParamIndex - 1, Attrs));
233 // Add any fn attributes.
234 if (Attributes attrs = PAL.getFnAttributes())
235 AttributesVec.push_back(AttributeWithIndex::get(~0, attrs));
238 FunctionType *NFTy = FunctionType::get(STy, Params, FTy->isVarArg());
239 Function *NF = Function::Create(NFTy, F->getLinkage());
241 NF->copyAttributesFrom(F);
242 NF->setAttributes(AttrListPtr::get(AttributesVec.begin(), AttributesVec.end()));
243 F->getParent()->getFunctionList().insert(F, NF);
244 NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
249 Function::arg_iterator NI = NF->arg_begin();
252 I->replaceAllUsesWith(NI);
261 /// updateCallSites - Update all sites that call F to use NF.
262 CallGraphNode *SRETPromotion::updateCallSites(Function *F, Function *NF) {
263 CallGraph &CG = getAnalysis<CallGraph>();
264 SmallVector<Value*, 16> Args;
266 // Attributes - Keep track of the parameter attributes for the arguments.
267 SmallVector<AttributeWithIndex, 8> ArgAttrsVec;
269 // Get a new callgraph node for NF.
270 CallGraphNode *NF_CGN = CG.getOrInsertFunction(NF);
272 while (!F->use_empty()) {
273 CallSite CS(*F->use_begin());
274 Instruction *Call = CS.getInstruction();
276 const AttrListPtr &PAL = F->getAttributes();
277 // Add any return attributes.
278 if (Attributes attrs = PAL.getRetAttributes())
279 ArgAttrsVec.push_back(AttributeWithIndex::get(0, attrs));
281 // Copy arguments, however skip first one.
282 CallSite::arg_iterator AI = CS.arg_begin(), AE = CS.arg_end();
283 Value *FirstCArg = *AI;
285 // 0th parameter attribute is reserved for return type.
286 // 1th parameter attribute is for first 1st sret argument.
287 unsigned ParamIndex = 2;
290 if (Attributes Attrs = PAL.getParamAttributes(ParamIndex))
291 ArgAttrsVec.push_back(AttributeWithIndex::get(ParamIndex - 1, Attrs));
296 // Add any function attributes.
297 if (Attributes attrs = PAL.getFnAttributes())
298 ArgAttrsVec.push_back(AttributeWithIndex::get(~0, attrs));
300 AttrListPtr NewPAL = AttrListPtr::get(ArgAttrsVec.begin(), ArgAttrsVec.end());
302 // Build new call instruction.
304 if (InvokeInst *II = dyn_cast<InvokeInst>(Call)) {
305 New = InvokeInst::Create(NF, II->getNormalDest(), II->getUnwindDest(),
306 Args.begin(), Args.end(), "", Call);
307 cast<InvokeInst>(New)->setCallingConv(CS.getCallingConv());
308 cast<InvokeInst>(New)->setAttributes(NewPAL);
310 New = CallInst::Create(NF, Args.begin(), Args.end(), "", Call);
311 cast<CallInst>(New)->setCallingConv(CS.getCallingConv());
312 cast<CallInst>(New)->setAttributes(NewPAL);
313 if (cast<CallInst>(Call)->isTailCall())
314 cast<CallInst>(New)->setTailCall();
320 // Update the callgraph to know that the callsite has been transformed.
321 CallGraphNode *CalleeNode = CG[Call->getParent()->getParent()];
322 CalleeNode->removeCallEdgeFor(Call);
323 CalleeNode->addCalledFunction(New, NF_CGN);
325 // Update all users of sret parameter to extract value using extractvalue.
326 for (Value::use_iterator UI = FirstCArg->use_begin(),
327 UE = FirstCArg->use_end(); UI != UE; ) {
329 CallInst *C2 = dyn_cast<CallInst>(U2);
330 if (C2 && (C2 == Call))
333 GetElementPtrInst *UGEP = cast<GetElementPtrInst>(U2);
334 ConstantInt *Idx = cast<ConstantInt>(UGEP->getOperand(2));
335 Value *GR = ExtractValueInst::Create(New, Idx->getZExtValue(),
337 while(!UGEP->use_empty()) {
338 // isSafeToUpdateAllCallers has checked that all GEP uses are
340 LoadInst *L = cast<LoadInst>(*UGEP->use_begin());
341 L->replaceAllUsesWith(GR);
342 L->eraseFromParent();
344 UGEP->eraseFromParent();
347 Call->eraseFromParent();