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