Implement ExtractCodeRegion()
[oota-llvm.git] / lib / Transforms / Utils / CodeExtractor.cpp
1 //===- CodeExtractor.cpp - Pull code region into a new function -----------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the interface to tear out a code region, such as an
11 // individual loop or a parallel section, into a new function, replacing it with
12 // a call to the new function.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/BasicBlock.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
24 #include "llvm/Transforms/Utils/FunctionUtils.h"
25 #include "Support/Debug.h"
26 #include "Support/StringExtras.h"
27 #include <algorithm>
28 #include <map>
29 #include <vector>
30 using namespace llvm;
31
32 namespace {
33
34   inline bool contains(const std::vector<BasicBlock*> &V, const BasicBlock *BB){
35     return std::find(V.begin(), V.end(), BB) != V.end();
36   }
37
38   /// getFunctionArg - Return a pointer to F's ARGNOth argument.
39   ///
40   Argument *getFunctionArg(Function *F, unsigned argno) {
41     Function::aiterator ai = F->abegin();
42     while (argno) { ++ai; --argno; }
43     return &*ai;
44   }
45
46   struct CodeExtractor {
47     typedef std::vector<Value*> Values;
48     typedef std::vector<std::pair<unsigned, unsigned> > PhiValChangesTy;
49     typedef std::map<PHINode*, PhiValChangesTy> PhiVal2ArgTy;
50     PhiVal2ArgTy PhiVal2Arg;
51
52   public:
53     Function *ExtractCodeRegion(const std::vector<BasicBlock*> &code);
54
55   private:
56     void findInputsOutputs(const std::vector<BasicBlock*> &code,
57                            Values &inputs,
58                            Values &outputs,
59                            BasicBlock *newHeader,
60                            BasicBlock *newRootNode);
61
62     void processPhiNodeInputs(PHINode *Phi,
63                               const std::vector<BasicBlock*> &code,
64                               Values &inputs,
65                               BasicBlock *newHeader,
66                               BasicBlock *newRootNode);
67
68     void rewritePhiNodes(Function *F, BasicBlock *newFuncRoot);
69
70     Function *constructFunction(const Values &inputs,
71                                 const Values &outputs,
72                                 BasicBlock *newRootNode, BasicBlock *newHeader,
73                                 const std::vector<BasicBlock*> &code,
74                                 Function *oldFunction, Module *M);
75
76     void moveCodeToFunction(const std::vector<BasicBlock*> &code,
77                             Function *newFunction);
78
79     void emitCallAndSwitchStatement(Function *newFunction,
80                                     BasicBlock *newHeader,
81                                     const std::vector<BasicBlock*> &code,
82                                     Values &inputs,
83                                     Values &outputs);
84
85   };
86 }
87
88 void CodeExtractor::processPhiNodeInputs(PHINode *Phi,
89                                          const std::vector<BasicBlock*> &code,
90                                          Values &inputs,
91                                          BasicBlock *codeReplacer,
92                                          BasicBlock *newFuncRoot)
93 {
94   // Separate incoming values and BasicBlocks as internal/external. We ignore
95   // the case where both the value and BasicBlock are internal, because we don't
96   // need to do a thing.
97   std::vector<unsigned> EValEBB;
98   std::vector<unsigned> EValIBB;
99   std::vector<unsigned> IValEBB;
100
101   for (unsigned i = 0, e = Phi->getNumIncomingValues(); i != e; ++i) {
102     Value *phiVal = Phi->getIncomingValue(i);
103     if (Instruction *Inst = dyn_cast<Instruction>(phiVal)) {
104       if (contains(code, Inst->getParent())) {
105         if (!contains(code, Phi->getIncomingBlock(i)))
106           IValEBB.push_back(i);
107       } else {
108         if (contains(code, Phi->getIncomingBlock(i)))
109           EValIBB.push_back(i);
110         else
111           EValEBB.push_back(i);
112       }
113     } else if (Constant *Const = dyn_cast<Constant>(phiVal)) {
114       // Constants are internal, but considered `external' if they are coming
115       // from an external block.
116       if (!contains(code, Phi->getIncomingBlock(i)))
117         EValEBB.push_back(i);
118     } else if (Argument *Arg = dyn_cast<Argument>(phiVal)) {
119       // arguments are external
120       if (contains(code, Phi->getIncomingBlock(i)))
121         EValIBB.push_back(i);
122       else
123         EValEBB.push_back(i);
124     } else {
125       phiVal->dump();
126       assert(0 && "Unhandled input in a Phi node");
127     }
128   }
129
130   // Both value and block are external. Need to group all of
131   // these, have an external phi, pass the result as an
132   // argument, and have THIS phi use that result.
133   if (EValEBB.size() > 0) {
134     if (EValEBB.size() == 1) {
135       // Now if it's coming from the newFuncRoot, it's that funky input
136       unsigned phiIdx = EValEBB[0];
137       if (!dyn_cast<Constant>(Phi->getIncomingValue(phiIdx)))
138       {
139         PhiVal2Arg[Phi].push_back(std::make_pair(phiIdx, inputs.size()));
140         // We can just pass this value in as argument
141         inputs.push_back(Phi->getIncomingValue(phiIdx));
142       }
143       Phi->setIncomingBlock(phiIdx, newFuncRoot);
144     } else {
145       PHINode *externalPhi = new PHINode(Phi->getType(), "extPhi");
146       codeReplacer->getInstList().insert(codeReplacer->begin(), externalPhi);
147       for (std::vector<unsigned>::iterator i = EValEBB.begin(),
148              e = EValEBB.end(); i != e; ++i)
149       {
150         externalPhi->addIncoming(Phi->getIncomingValue(*i),
151                                  Phi->getIncomingBlock(*i));
152
153         // We make these values invalid instead of deleting them because that
154         // would shift the indices of other values... The fixPhiNodes should
155         // clean these phi nodes up later.
156         Phi->setIncomingValue(*i, 0);
157         Phi->setIncomingBlock(*i, 0);
158       }
159       PhiVal2Arg[Phi].push_back(std::make_pair(Phi->getNumIncomingValues(),
160                                                inputs.size()));
161       // We can just pass this value in as argument
162       inputs.push_back(externalPhi);
163     }
164   }
165
166   // When the value is external, but block internal...
167   // just pass it in as argument, no change to phi node
168   for (std::vector<unsigned>::iterator i = EValIBB.begin(),
169          e = EValIBB.end(); i != e; ++i)
170   {
171     // rewrite the phi input node to be an argument
172     PhiVal2Arg[Phi].push_back(std::make_pair(*i, inputs.size()));
173     inputs.push_back(Phi->getIncomingValue(*i));
174   }
175
176   // Value internal, block external
177   // this can happen if we are extracting a part of a loop
178   for (std::vector<unsigned>::iterator i = IValEBB.begin(),
179          e = IValEBB.end(); i != e; ++i)
180   {
181     assert(0 && "Cannot (YET) handle internal values via external blocks");
182   }
183 }
184
185
186 void CodeExtractor::findInputsOutputs(const std::vector<BasicBlock*> &code,
187                                       Values &inputs,
188                                       Values &outputs,
189                                       BasicBlock *newHeader,
190                                       BasicBlock *newRootNode)
191 {
192   for (std::vector<BasicBlock*>::const_iterator ci = code.begin(), 
193        ce = code.end(); ci != ce; ++ci) {
194     BasicBlock *BB = *ci;
195     for (BasicBlock::iterator BBi = BB->begin(), BBe = BB->end();
196          BBi != BBe; ++BBi) {
197       // If a use is defined outside the region, it's an input.
198       // If a def is used outside the region, it's an output.
199       if (Instruction *I = dyn_cast<Instruction>(&*BBi)) {
200         // If it's a phi node
201         if (PHINode *Phi = dyn_cast<PHINode>(I)) {
202           processPhiNodeInputs(Phi, code, inputs, newHeader, newRootNode);
203         } else {
204           // All other instructions go through the generic input finder
205           // Loop over the operands of each instruction (inputs)
206           for (User::op_iterator op = I->op_begin(), opE = I->op_end();
207                op != opE; ++op) {
208             if (Instruction *opI = dyn_cast<Instruction>(op->get())) {
209               // Check if definition of this operand is within the loop
210               if (!contains(code, opI->getParent())) {
211                 // add this operand to the inputs
212                 inputs.push_back(opI);
213               }
214             }
215           }
216         }
217
218         // Consider uses of this instruction (outputs)
219         for (Value::use_iterator use = I->use_begin(), useE = I->use_end();
220              use != useE; ++use) {
221           if (Instruction* inst = dyn_cast<Instruction>(*use)) {
222             if (!contains(code, inst->getParent())) {
223               // add this op to the outputs
224               outputs.push_back(I);
225             }
226           }
227         }
228       } /* if */
229     } /* for: insts */
230   } /* for: basic blocks */
231 }
232
233 void CodeExtractor::rewritePhiNodes(Function *F,
234                                     BasicBlock *newFuncRoot) {
235   // Write any changes that were saved before: use function arguments as inputs
236   for (PhiVal2ArgTy::iterator i = PhiVal2Arg.begin(), e = PhiVal2Arg.end();
237        i != e; ++i)
238   {
239     PHINode *phi = (*i).first;
240     PhiValChangesTy &values = (*i).second;
241     for (unsigned cIdx = 0, ce = values.size(); cIdx != ce; ++cIdx)
242     {
243       unsigned phiValueIdx = values[cIdx].first, argNum = values[cIdx].second;
244       if (phiValueIdx < phi->getNumIncomingValues())
245         phi->setIncomingValue(phiValueIdx, getFunctionArg(F, argNum));
246       else
247         phi->addIncoming(getFunctionArg(F, argNum), newFuncRoot);
248     }
249   }
250
251   // Delete any invalid Phi node inputs that were marked as NULL previously
252   for (PhiVal2ArgTy::iterator i = PhiVal2Arg.begin(), e = PhiVal2Arg.end();
253        i != e; ++i)
254   {
255     PHINode *phi = (*i).first;
256     for (unsigned idx = 0, end = phi->getNumIncomingValues(); idx != end; ++idx)
257     {
258       if (phi->getIncomingValue(idx) == 0 && phi->getIncomingBlock(idx) == 0) {
259         phi->removeIncomingValue(idx);
260         --idx;
261         --end;
262       }
263     }
264   }
265
266   // We are done with the saved values
267   PhiVal2Arg.clear();
268 }
269
270
271 /// constructFunction - make a function based on inputs and outputs, as follows:
272 /// f(in0, ..., inN, out0, ..., outN)
273 ///
274 Function *CodeExtractor::constructFunction(const Values &inputs,
275                                            const Values &outputs,
276                                            BasicBlock *newRootNode,
277                                            BasicBlock *newHeader,
278                                            const std::vector<BasicBlock*> &code,
279                                            Function *oldFunction, Module *M) {
280   DEBUG(std::cerr << "inputs: " << inputs.size() << "\n");
281   DEBUG(std::cerr << "outputs: " << outputs.size() << "\n");
282   BasicBlock *header = code[0];
283
284   // This function returns unsigned, outputs will go back by reference.
285   Type *retTy = Type::UShortTy;
286   std::vector<const Type*> paramTy;
287
288   // Add the types of the input values to the function's argument list
289   for (Values::const_iterator i = inputs.begin(),
290          e = inputs.end(); i != e; ++i) {
291     const Value *value = *i;
292     DEBUG(std::cerr << "value used in func: " << value << "\n");
293     paramTy.push_back(value->getType());
294   }
295
296   // Add the types of the output values to the function's argument list, but
297   // make them pointer types for scalars
298   for (Values::const_iterator i = outputs.begin(),
299          e = outputs.end(); i != e; ++i) {
300     const Value *value = *i;
301     DEBUG(std::cerr << "instr used in func: " << value << "\n");
302     const Type *valueType = value->getType();
303     // Convert scalar types into a pointer of that type
304     if (valueType->isPrimitiveType()) {
305       valueType = PointerType::get(valueType);
306     }
307     paramTy.push_back(valueType);
308   }
309
310   DEBUG(std::cerr << "Function type: " << retTy << " f(");
311   for (std::vector<const Type*>::iterator i = paramTy.begin(),
312          e = paramTy.end(); i != e; ++i)
313     DEBUG(std::cerr << (*i) << ", ");
314   DEBUG(std::cerr << ")\n");
315
316   const FunctionType *funcType = FunctionType::get(retTy, paramTy, false);
317
318   // Create the new function
319   Function *newFunction = new Function(funcType,
320                                        GlobalValue::InternalLinkage,
321                                        oldFunction->getName() + "_code", M);
322   newFunction->getBasicBlockList().push_back(newRootNode);
323
324   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
325     std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end());
326     for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
327          use != useE; ++use) {
328       if (Instruction* inst = dyn_cast<Instruction>(*use)) {
329         if (contains(code, inst->getParent())) {
330           inst->replaceUsesOfWith(inputs[i], getFunctionArg(newFunction, i));
331         }
332       }
333     }
334   }
335
336   // Rewrite branches to basic blocks outside of the loop to new dummy blocks
337   // within the new function. This must be done before we lose track of which
338   // blocks were originally in the code region.
339   std::vector<User*> Users(header->use_begin(), header->use_end());
340   for (std::vector<User*>::iterator i = Users.begin(), e = Users.end();
341        i != e; ++i) {
342     if (BranchInst *inst = dyn_cast<BranchInst>(*i)) {
343       BasicBlock *BB = inst->getParent();
344       if (!contains(code, BB) && BB->getParent() == oldFunction) {
345         // The BasicBlock which contains the branch is not in the region
346         // modify the branch target to a new block
347         inst->replaceUsesOfWith(header, newHeader);
348       }
349     }
350   }
351
352   return newFunction;
353 }
354
355 void CodeExtractor::moveCodeToFunction(const std::vector<BasicBlock*> &code,
356                                        Function *newFunction)
357 {
358   for (std::vector<BasicBlock*>::const_iterator i = code.begin(), e =code.end();
359        i != e; ++i) {
360     BasicBlock *BB = *i;
361     Function *oldFunc = BB->getParent();
362     Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
363
364     // Delete the basic block from the old function, and the list of blocks
365     oldBlocks.remove(BB);
366
367     // Insert this basic block into the new function
368     Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
369     newBlocks.push_back(BB);
370   }
371 }
372
373 void
374 CodeExtractor::emitCallAndSwitchStatement(Function *newFunction,
375                                           BasicBlock *codeReplacer,
376                                           const std::vector<BasicBlock*> &code,
377                                           Values &inputs,
378                                           Values &outputs)
379 {
380   // Emit a call to the new function, passing allocated memory for outputs and
381   // just plain inputs for non-scalars
382   std::vector<Value*> params;
383   BasicBlock *codeReplacerTail = new BasicBlock("codeReplTail",
384                                                 codeReplacer->getParent());
385   for (Values::const_iterator i = inputs.begin(),
386          e = inputs.end(); i != e; ++i)
387     params.push_back(*i);
388   for (Values::const_iterator i = outputs.begin(), 
389          e = outputs.end(); i != e; ++i) {
390     // Create allocas for scalar outputs
391     if ((*i)->getType()->isPrimitiveType()) {
392       Constant *one = ConstantUInt::get(Type::UIntTy, 1);
393       AllocaInst *alloca = new AllocaInst((*i)->getType(), one);
394       codeReplacer->getInstList().push_back(alloca);
395       params.push_back(alloca);
396
397       LoadInst *load = new LoadInst(alloca, "alloca");
398       codeReplacerTail->getInstList().push_back(load);
399       std::vector<User*> Users((*i)->use_begin(), (*i)->use_end());
400       for (std::vector<User*>::iterator use = Users.begin(), useE =Users.end();
401            use != useE; ++use) {
402         if (Instruction* inst = dyn_cast<Instruction>(*use)) {
403           if (!contains(code, inst->getParent())) {
404             inst->replaceUsesOfWith(*i, load);
405           }
406         }
407       }
408     } else {
409       params.push_back(*i);
410     }
411   }
412   CallInst *call = new CallInst(newFunction, params, "targetBlock");
413   codeReplacer->getInstList().push_back(call);
414   codeReplacer->getInstList().push_back(new BranchInst(codeReplacerTail));
415
416   // Now we can emit a switch statement using the call as a value.
417   // FIXME: perhaps instead of default being self BB, it should be a second
418   // dummy block which asserts that the value is not within the range...?
419   //BasicBlock *defaultBlock = new BasicBlock("defaultBlock", oldF);
420   //insert abort() ?
421   //defaultBlock->getInstList().push_back(new BranchInst(codeReplacer));
422
423   SwitchInst *switchInst = new SwitchInst(call, codeReplacerTail,
424                                           codeReplacerTail);
425
426   // Since there may be multiple exits from the original region, make the new
427   // function return an unsigned, switch on that number
428   unsigned switchVal = 0;
429   for (std::vector<BasicBlock*>::const_iterator i =code.begin(), e = code.end();
430        i != e; ++i) {
431     BasicBlock *BB = *i;
432
433     // rewrite the terminator of the original BasicBlock
434     Instruction *term = BB->getTerminator();
435     if (BranchInst *brInst = dyn_cast<BranchInst>(term)) {
436
437       // Restore values just before we exit
438       // FIXME: Use a GetElementPtr to bunch the outputs in a struct
439       for (unsigned outIdx = 0, outE = outputs.size(); outIdx != outE; ++outIdx)
440       {
441         new StoreInst(outputs[outIdx],
442                       getFunctionArg(newFunction, outIdx),
443                       brInst);
444       }
445
446       // Rewrite branches into exits which return a value based on which
447       // exit we take from this function
448       if (brInst->isUnconditional()) {
449         if (!contains(code, brInst->getSuccessor(0))) {
450           ConstantUInt *brVal = ConstantUInt::get(Type::UShortTy, switchVal);
451           ReturnInst *newRet = new ReturnInst(brVal);
452           // add a new target to the switch
453           switchInst->addCase(brVal, brInst->getSuccessor(0));
454           ++switchVal;
455           // rewrite the branch with a return
456           BasicBlock::iterator ii(brInst);
457           ReplaceInstWithInst(BB->getInstList(), ii, newRet);
458           delete brInst;
459         }
460       } else {
461         // Replace the conditional branch to branch
462         // to two new blocks, each of which returns a different code.
463         for (unsigned idx = 0; idx < 2; ++idx) {
464           BasicBlock *oldTarget = brInst->getSuccessor(idx);
465           if (!contains(code, oldTarget)) {
466             // add a new basic block which returns the appropriate value
467             BasicBlock *newTarget = new BasicBlock("newTarget", newFunction);
468             ConstantUInt *brVal = ConstantUInt::get(Type::UShortTy, switchVal);
469             ReturnInst *newRet = new ReturnInst(brVal);
470             newTarget->getInstList().push_back(newRet);
471             // rewrite the original branch instruction with this new target
472             brInst->setSuccessor(idx, newTarget);
473             // the switch statement knows what to do with this value
474             switchInst->addCase(brVal, oldTarget);
475             ++switchVal;
476           }
477         }
478       }
479     } else if (ReturnInst *retTerm = dyn_cast<ReturnInst>(term)) {
480       assert(0 && "Cannot handle return instructions just yet.");
481       // FIXME: what if the terminator is a return!??!
482       // Need to rewrite: add new basic block, move the return there
483       // treat the original as an unconditional branch to that basicblock
484     } else if (SwitchInst *swTerm = dyn_cast<SwitchInst>(term)) {
485       assert(0 && "Cannot handle switch instructions just yet.");
486     } else if (InvokeInst *invInst = dyn_cast<InvokeInst>(term)) {
487       assert(0 && "Cannot handle invoke instructions just yet.");
488     } else {
489       assert(0 && "Unrecognized terminator, or badly-formed BasicBlock.");
490     }
491   }
492 }
493
494
495 /// ExtractRegion - Removes a loop from a function, replaces it with a call to
496 /// new function. Returns pointer to the new function.
497 ///
498 /// algorithm:
499 ///
500 /// find inputs and outputs for the region
501 ///
502 /// for inputs: add to function as args, map input instr* to arg# 
503 /// for outputs: add allocas for scalars, 
504 ///             add to func as args, map output instr* to arg#
505 ///
506 /// rewrite func to use argument #s instead of instr*
507 ///
508 /// for each scalar output in the function: at every exit, store intermediate 
509 /// computed result back into memory.
510 ///
511 Function *CodeExtractor::ExtractCodeRegion(const std::vector<BasicBlock*> &code)
512 {
513   // 1) Find inputs, outputs
514   // 2) Construct new function
515   //  * Add allocas for defs, pass as args by reference
516   //  * Pass in uses as args
517   // 3) Move code region, add call instr to func
518   // 
519
520   Values inputs, outputs;
521
522   // Assumption: this is a single-entry code region, and the header is the first
523   // block in the region. FIXME: is this true for a list of blocks from a
524   // natural function?
525   BasicBlock *header = code[0];
526   Function *oldFunction = header->getParent();
527   Module *module = oldFunction->getParent();
528
529   // This takes place of the original loop
530   BasicBlock *codeReplacer = new BasicBlock("codeRepl", oldFunction);
531
532   // The new function needs a root node because other nodes can branch to the
533   // head of the loop, and the root cannot have predecessors
534   BasicBlock *newFuncRoot = new BasicBlock("newFuncRoot");
535   newFuncRoot->getInstList().push_back(new BranchInst(header));
536
537   // Find inputs to, outputs from the code region
538   //
539   // If one of the inputs is coming from a different basic block and it's in a
540   // phi node, we need to rewrite the phi node:
541   //
542   // * All the inputs which involve basic blocks OUTSIDE of this region go into
543   //   a NEW phi node that takes care of finding which value really came in.
544   //   The result of this phi is passed to the function as an argument. 
545   //
546   // * All the other phi values stay.
547   //
548   // FIXME: PHI nodes' incoming blocks aren't being rewritten to accomodate for
549   // blocks moving to a new function.
550   // SOLUTION: move Phi nodes out of the loop header into the codeReplacer, pass
551   // the values as parameters to the function
552   findInputsOutputs(code, inputs, outputs, codeReplacer, newFuncRoot);
553
554   // Step 2: Construct new function based on inputs/outputs,
555   // Add allocas for all defs
556   Function *newFunction = constructFunction(inputs, outputs, newFuncRoot, 
557                                             codeReplacer, code, 
558                                             oldFunction, module);
559
560   rewritePhiNodes(newFunction, newFuncRoot);
561
562   emitCallAndSwitchStatement(newFunction, codeReplacer, code, inputs, outputs);
563
564   moveCodeToFunction(code, newFunction);
565
566   return newFunction;
567 }
568
569 /// ExtractCodeRegion - slurp a sequence of basic blocks into a brand new
570 /// function
571 ///
572 Function* llvm::ExtractCodeRegion(const std::vector<BasicBlock*> &code) {
573   CodeExtractor CE;
574   return CE.ExtractCodeRegion(code);
575 }
576
577 /// ExtractBasicBlock - slurp a natural loop into a brand new function
578 ///
579 Function* llvm::ExtractLoop(Loop *L) {
580   CodeExtractor CE;
581   return CE.ExtractCodeRegion(L->getBlocks());
582 }
583
584 /// ExtractBasicBlock - slurp a basic block into a brand new function
585 ///
586 Function* llvm::ExtractBasicBlock(BasicBlock *BB) {
587   CodeExtractor CE;
588   std::vector<BasicBlock*> Blocks;
589   Blocks.push_back(BB);
590   return CE.ExtractCodeRegion(Blocks);  
591 }