Handle a corner case when extracing code regions where one of the immediate successor
[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 is distributed under the University of Illinois Open Source
6 // 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/Transforms/Utils/FunctionUtils.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Analysis/Dominators.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Analysis/Verifier.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include <algorithm>
35 #include <set>
36 using namespace llvm;
37
38 // Provide a command-line option to aggregate function arguments into a struct
39 // for functions produced by the code extractor. This is useful when converting
40 // extracted functions to pthread-based code, as only one argument (void*) can
41 // be passed in to pthread_create().
42 static cl::opt<bool>
43 AggregateArgsOpt("aggregate-extracted-args", cl::Hidden,
44                  cl::desc("Aggregate arguments to code-extracted functions"));
45
46 namespace {
47   class VISIBILITY_HIDDEN CodeExtractor {
48     typedef std::vector<Value*> Values;
49     std::set<BasicBlock*> BlocksToExtract;
50     DominatorTree* DT;
51     bool AggregateArgs;
52     unsigned NumExitBlocks;
53     const Type *RetTy;
54   public:
55     CodeExtractor(DominatorTree* dt = 0, bool AggArgs = false)
56       : DT(dt), AggregateArgs(AggArgs||AggregateArgsOpt), NumExitBlocks(~0U) {}
57
58     Function *ExtractCodeRegion(const std::vector<BasicBlock*> &code);
59
60     bool isEligible(const std::vector<BasicBlock*> &code);
61
62   private:
63     /// definedInRegion - Return true if the specified value is defined in the
64     /// extracted region.
65     bool definedInRegion(Value *V) const {
66       if (Instruction *I = dyn_cast<Instruction>(V))
67         if (BlocksToExtract.count(I->getParent()))
68           return true;
69       return false;
70     }
71
72     /// definedInCaller - Return true if the specified value is defined in the
73     /// function being code extracted, but not in the region being extracted.
74     /// These values must be passed in as live-ins to the function.
75     bool definedInCaller(Value *V) const {
76       if (isa<Argument>(V)) return true;
77       if (Instruction *I = dyn_cast<Instruction>(V))
78         if (!BlocksToExtract.count(I->getParent()))
79           return true;
80       return false;
81     }
82
83     void severSplitPHINodes(BasicBlock *&Header);
84     void splitReturnBlocks();
85     void findInputsOutputs(Values &inputs, Values &outputs);
86
87     Function *constructFunction(const Values &inputs,
88                                 const Values &outputs,
89                                 BasicBlock *header,
90                                 BasicBlock *newRootNode, BasicBlock *newHeader,
91                                 Function *oldFunction, Module *M);
92
93     void moveCodeToFunction(Function *newFunction);
94
95     void emitCallAndSwitchStatement(Function *newFunction,
96                                     BasicBlock *newHeader,
97                                     Values &inputs,
98                                     Values &outputs);
99
100   };
101 }
102
103 /// severSplitPHINodes - If a PHI node has multiple inputs from outside of the
104 /// region, we need to split the entry block of the region so that the PHI node
105 /// is easier to deal with.
106 void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) {
107   bool HasPredsFromRegion = false;
108   unsigned NumPredsOutsideRegion = 0;
109
110   if (Header != &Header->getParent()->getEntryBlock()) {
111     PHINode *PN = dyn_cast<PHINode>(Header->begin());
112     if (!PN) return;  // No PHI nodes.
113
114     // If the header node contains any PHI nodes, check to see if there is more
115     // than one entry from outside the region.  If so, we need to sever the
116     // header block into two.
117     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
118       if (BlocksToExtract.count(PN->getIncomingBlock(i)))
119         HasPredsFromRegion = true;
120       else
121         ++NumPredsOutsideRegion;
122
123     // If there is one (or fewer) predecessor from outside the region, we don't
124     // need to do anything special.
125     if (NumPredsOutsideRegion <= 1) return;
126   }
127
128   // Otherwise, we need to split the header block into two pieces: one
129   // containing PHI nodes merging values from outside of the region, and a
130   // second that contains all of the code for the block and merges back any
131   // incoming values from inside of the region.
132   BasicBlock::iterator AfterPHIs = Header->getFirstNonPHI();
133   BasicBlock *NewBB = Header->splitBasicBlock(AfterPHIs,
134                                               Header->getName()+".ce");
135
136   // We only want to code extract the second block now, and it becomes the new
137   // header of the region.
138   BasicBlock *OldPred = Header;
139   BlocksToExtract.erase(OldPred);
140   BlocksToExtract.insert(NewBB);
141   Header = NewBB;
142
143   // Okay, update dominator sets. The blocks that dominate the new one are the
144   // blocks that dominate TIBB plus the new block itself.
145   if (DT)
146     DT->splitBlock(NewBB);
147
148   // Okay, now we need to adjust the PHI nodes and any branches from within the
149   // region to go to the new header block instead of the old header block.
150   if (HasPredsFromRegion) {
151     PHINode *PN = cast<PHINode>(OldPred->begin());
152     // Loop over all of the predecessors of OldPred that are in the region,
153     // changing them to branch to NewBB instead.
154     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
155       if (BlocksToExtract.count(PN->getIncomingBlock(i))) {
156         TerminatorInst *TI = PN->getIncomingBlock(i)->getTerminator();
157         TI->replaceUsesOfWith(OldPred, NewBB);
158       }
159
160     // Okay, everthing within the region is now branching to the right block, we
161     // just have to update the PHI nodes now, inserting PHI nodes into NewBB.
162     for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) {
163       PHINode *PN = cast<PHINode>(AfterPHIs);
164       // Create a new PHI node in the new region, which has an incoming value
165       // from OldPred of PN.
166       PHINode *NewPN = PHINode::Create(PN->getType(), PN->getName()+".ce",
167                                        NewBB->begin());
168       NewPN->addIncoming(PN, OldPred);
169
170       // Loop over all of the incoming value in PN, moving them to NewPN if they
171       // are from the extracted region.
172       for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
173         if (BlocksToExtract.count(PN->getIncomingBlock(i))) {
174           NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i));
175           PN->removeIncomingValue(i);
176           --i;
177         }
178       }
179     }
180   }
181 }
182
183 void CodeExtractor::splitReturnBlocks() {
184   for (std::set<BasicBlock*>::iterator I = BlocksToExtract.begin(),
185          E = BlocksToExtract.end(); I != E; ++I)
186     if (ReturnInst *RI = dyn_cast<ReturnInst>((*I)->getTerminator())) {
187       BasicBlock *New = (*I)->splitBasicBlock(RI, (*I)->getName()+".ret");
188       if (DT) {
189         // Old dominates New. New node domiantes all other nodes dominated
190         //by Old.
191         DomTreeNode *OldNode = DT->getNode(*I);
192         std::vector<DomTreeNode *> Children;
193         for (DomTreeNode::iterator DI = OldNode->begin(), DE = OldNode->end();
194              DI != DE; ++DI) 
195           Children.push_back(*DI);
196
197         DomTreeNode *NewNode = DT->addNewBlock(New, *I);
198
199         for (std::vector<DomTreeNode *>::iterator I = Children.begin(),
200                E = Children.end(); I != E; ++I) 
201           DT->changeImmediateDominator(*I, NewNode);
202       }
203     }
204 }
205
206 // findInputsOutputs - Find inputs to, outputs from the code region.
207 //
208 void CodeExtractor::findInputsOutputs(Values &inputs, Values &outputs) {
209   std::set<BasicBlock*> ExitBlocks;
210   for (std::set<BasicBlock*>::const_iterator ci = BlocksToExtract.begin(),
211        ce = BlocksToExtract.end(); ci != ce; ++ci) {
212     BasicBlock *BB = *ci;
213
214     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
215       // If a used value is defined outside the region, it's an input.  If an
216       // instruction is used outside the region, it's an output.
217       for (User::op_iterator O = I->op_begin(), E = I->op_end(); O != E; ++O)
218         if (definedInCaller(*O))
219           inputs.push_back(*O);
220
221       // Consider uses of this instruction (outputs).
222       for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
223            UI != E; ++UI)
224         if (!definedInRegion(*UI)) {
225           outputs.push_back(I);
226           break;
227         }
228     } // for: insts
229
230     // Keep track of the exit blocks from the region.
231     TerminatorInst *TI = BB->getTerminator();
232     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
233       if (!BlocksToExtract.count(TI->getSuccessor(i)))
234         ExitBlocks.insert(TI->getSuccessor(i));
235   } // for: basic blocks
236
237   NumExitBlocks = ExitBlocks.size();
238
239   // Eliminate duplicates.
240   std::sort(inputs.begin(), inputs.end());
241   inputs.erase(std::unique(inputs.begin(), inputs.end()), inputs.end());
242   std::sort(outputs.begin(), outputs.end());
243   outputs.erase(std::unique(outputs.begin(), outputs.end()), outputs.end());
244 }
245
246 /// constructFunction - make a function based on inputs and outputs, as follows:
247 /// f(in0, ..., inN, out0, ..., outN)
248 ///
249 Function *CodeExtractor::constructFunction(const Values &inputs,
250                                            const Values &outputs,
251                                            BasicBlock *header,
252                                            BasicBlock *newRootNode,
253                                            BasicBlock *newHeader,
254                                            Function *oldFunction,
255                                            Module *M) {
256   DEBUG(errs() << "inputs: " << inputs.size() << "\n");
257   DEBUG(errs() << "outputs: " << outputs.size() << "\n");
258
259   // This function returns unsigned, outputs will go back by reference.
260   switch (NumExitBlocks) {
261   case 0:
262   case 1: RetTy = Type::getVoidTy(header->getContext()); break;
263   case 2: RetTy = Type::getInt1Ty(header->getContext()); break;
264   default: RetTy = Type::getInt16Ty(header->getContext()); break;
265   }
266
267   std::vector<const Type*> paramTy;
268
269   // Add the types of the input values to the function's argument list
270   for (Values::const_iterator i = inputs.begin(),
271          e = inputs.end(); i != e; ++i) {
272     const Value *value = *i;
273     DEBUG(errs() << "value used in func: " << *value << "\n");
274     paramTy.push_back(value->getType());
275   }
276
277   // Add the types of the output values to the function's argument list.
278   for (Values::const_iterator I = outputs.begin(), E = outputs.end();
279        I != E; ++I) {
280     DEBUG(errs() << "instr used in func: " << **I << "\n");
281     if (AggregateArgs)
282       paramTy.push_back((*I)->getType());
283     else
284       paramTy.push_back(PointerType::getUnqual((*I)->getType()));
285   }
286
287   DEBUG(errs() << "Function type: " << *RetTy << " f(");
288   for (std::vector<const Type*>::iterator i = paramTy.begin(),
289          e = paramTy.end(); i != e; ++i)
290     DEBUG(errs() << **i << ", ");
291   DEBUG(errs() << ")\n");
292
293   if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
294     PointerType *StructPtr =
295            PointerType::getUnqual(StructType::get(M->getContext(), paramTy));
296     paramTy.clear();
297     paramTy.push_back(StructPtr);
298   }
299   const FunctionType *funcType =
300                   FunctionType::get(RetTy, paramTy, false);
301
302   // Create the new function
303   Function *newFunction = Function::Create(funcType,
304                                            GlobalValue::InternalLinkage,
305                                            oldFunction->getName() + "_" +
306                                            header->getName(), M);
307   // If the old function is no-throw, so is the new one.
308   if (oldFunction->doesNotThrow())
309     newFunction->setDoesNotThrow(true);
310   
311   newFunction->getBasicBlockList().push_back(newRootNode);
312
313   // Create an iterator to name all of the arguments we inserted.
314   Function::arg_iterator AI = newFunction->arg_begin();
315
316   // Rewrite all users of the inputs in the extracted region to use the
317   // arguments (or appropriate addressing into struct) instead.
318   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
319     Value *RewriteVal;
320     if (AggregateArgs) {
321       Value *Idx[2];
322       Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext()));
323       Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i);
324       TerminatorInst *TI = newFunction->begin()->getTerminator();
325       GetElementPtrInst *GEP = 
326         GetElementPtrInst::Create(AI, Idx, Idx+2, 
327                                   "gep_" + inputs[i]->getName(), TI);
328       RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI);
329     } else
330       RewriteVal = AI++;
331
332     std::vector<User*> Users(inputs[i]->use_begin(), inputs[i]->use_end());
333     for (std::vector<User*>::iterator use = Users.begin(), useE = Users.end();
334          use != useE; ++use)
335       if (Instruction* inst = dyn_cast<Instruction>(*use))
336         if (BlocksToExtract.count(inst->getParent()))
337           inst->replaceUsesOfWith(inputs[i], RewriteVal);
338   }
339
340   // Set names for input and output arguments.
341   if (!AggregateArgs) {
342     AI = newFunction->arg_begin();
343     for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI)
344       AI->setName(inputs[i]->getName());
345     for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI)
346       AI->setName(outputs[i]->getName()+".out");
347   }
348
349   // Rewrite branches to basic blocks outside of the loop to new dummy blocks
350   // within the new function. This must be done before we lose track of which
351   // blocks were originally in the code region.
352   std::vector<User*> Users(header->use_begin(), header->use_end());
353   for (unsigned i = 0, e = Users.size(); i != e; ++i)
354     // The BasicBlock which contains the branch is not in the region
355     // modify the branch target to a new block
356     if (TerminatorInst *TI = dyn_cast<TerminatorInst>(Users[i]))
357       if (!BlocksToExtract.count(TI->getParent()) &&
358           TI->getParent()->getParent() == oldFunction)
359         TI->replaceUsesOfWith(header, newHeader);
360
361   return newFunction;
362 }
363
364 /// emitCallAndSwitchStatement - This method sets up the caller side by adding
365 /// the call instruction, splitting any PHI nodes in the header block as
366 /// necessary.
367 void CodeExtractor::
368 emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer,
369                            Values &inputs, Values &outputs) {
370   // Emit a call to the new function, passing in: *pointer to struct (if
371   // aggregating parameters), or plan inputs and allocated memory for outputs
372   std::vector<Value*> params, StructValues, ReloadOutputs, Reloads;
373   
374   LLVMContext &Context = newFunction->getContext();
375
376   // Add inputs as params, or to be filled into the struct
377   for (Values::iterator i = inputs.begin(), e = inputs.end(); i != e; ++i)
378     if (AggregateArgs)
379       StructValues.push_back(*i);
380     else
381       params.push_back(*i);
382
383   // Create allocas for the outputs
384   for (Values::iterator i = outputs.begin(), e = outputs.end(); i != e; ++i) {
385     if (AggregateArgs) {
386       StructValues.push_back(*i);
387     } else {
388       AllocaInst *alloca =
389         new AllocaInst((*i)->getType(), 0, (*i)->getName()+".loc",
390                        codeReplacer->getParent()->begin()->begin());
391       ReloadOutputs.push_back(alloca);
392       params.push_back(alloca);
393     }
394   }
395
396   AllocaInst *Struct = 0;
397   if (AggregateArgs && (inputs.size() + outputs.size() > 0)) {
398     std::vector<const Type*> ArgTypes;
399     for (Values::iterator v = StructValues.begin(),
400            ve = StructValues.end(); v != ve; ++v)
401       ArgTypes.push_back((*v)->getType());
402
403     // Allocate a struct at the beginning of this function
404     Type *StructArgTy = StructType::get(newFunction->getContext(), ArgTypes);
405     Struct =
406       new AllocaInst(StructArgTy, 0, "structArg",
407                      codeReplacer->getParent()->begin()->begin());
408     params.push_back(Struct);
409
410     for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
411       Value *Idx[2];
412       Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
413       Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i);
414       GetElementPtrInst *GEP =
415         GetElementPtrInst::Create(Struct, Idx, Idx + 2,
416                                   "gep_" + StructValues[i]->getName());
417       codeReplacer->getInstList().push_back(GEP);
418       StoreInst *SI = new StoreInst(StructValues[i], GEP);
419       codeReplacer->getInstList().push_back(SI);
420     }
421   }
422
423   // Emit the call to the function
424   CallInst *call = CallInst::Create(newFunction, params.begin(), params.end(),
425                                     NumExitBlocks > 1 ? "targetBlock" : "");
426   codeReplacer->getInstList().push_back(call);
427
428   Function::arg_iterator OutputArgBegin = newFunction->arg_begin();
429   unsigned FirstOut = inputs.size();
430   if (!AggregateArgs)
431     std::advance(OutputArgBegin, inputs.size());
432
433   // Reload the outputs passed in by reference
434   for (unsigned i = 0, e = outputs.size(); i != e; ++i) {
435     Value *Output = 0;
436     if (AggregateArgs) {
437       Value *Idx[2];
438       Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
439       Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i);
440       GetElementPtrInst *GEP
441         = GetElementPtrInst::Create(Struct, Idx, Idx + 2,
442                                     "gep_reload_" + outputs[i]->getName());
443       codeReplacer->getInstList().push_back(GEP);
444       Output = GEP;
445     } else {
446       Output = ReloadOutputs[i];
447     }
448     LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload");
449     Reloads.push_back(load);
450     codeReplacer->getInstList().push_back(load);
451     std::vector<User*> Users(outputs[i]->use_begin(), outputs[i]->use_end());
452     for (unsigned u = 0, e = Users.size(); u != e; ++u) {
453       Instruction *inst = cast<Instruction>(Users[u]);
454       if (!BlocksToExtract.count(inst->getParent()))
455         inst->replaceUsesOfWith(outputs[i], load);
456     }
457   }
458
459   // Now we can emit a switch statement using the call as a value.
460   SwitchInst *TheSwitch =
461       SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)),
462                          codeReplacer, 0, codeReplacer);
463
464   // Since there may be multiple exits from the original region, make the new
465   // function return an unsigned, switch on that number.  This loop iterates
466   // over all of the blocks in the extracted region, updating any terminator
467   // instructions in the to-be-extracted region that branch to blocks that are
468   // not in the region to be extracted.
469   std::map<BasicBlock*, BasicBlock*> ExitBlockMap;
470
471   unsigned switchVal = 0;
472   for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
473          e = BlocksToExtract.end(); i != e; ++i) {
474     TerminatorInst *TI = (*i)->getTerminator();
475     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
476       if (!BlocksToExtract.count(TI->getSuccessor(i))) {
477         BasicBlock *OldTarget = TI->getSuccessor(i);
478         // add a new basic block which returns the appropriate value
479         BasicBlock *&NewTarget = ExitBlockMap[OldTarget];
480         if (!NewTarget) {
481           // If we don't already have an exit stub for this non-extracted
482           // destination, create one now!
483           NewTarget = BasicBlock::Create(Context,
484                                          OldTarget->getName() + ".exitStub",
485                                          newFunction);
486           unsigned SuccNum = switchVal++;
487
488           Value *brVal = 0;
489           switch (NumExitBlocks) {
490           case 0:
491           case 1: break;  // No value needed.
492           case 2:         // Conditional branch, return a bool
493             brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum);
494             break;
495           default:
496             brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum);
497             break;
498           }
499
500           ReturnInst *NTRet = ReturnInst::Create(Context, brVal, NewTarget);
501
502           // Update the switch instruction.
503           TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context),
504                                               SuccNum),
505                              OldTarget);
506
507           // Restore values just before we exit
508           Function::arg_iterator OAI = OutputArgBegin;
509           for (unsigned out = 0, e = outputs.size(); out != e; ++out) {
510             // For an invoke, the normal destination is the only one that is
511             // dominated by the result of the invocation
512             BasicBlock *DefBlock = cast<Instruction>(outputs[out])->getParent();
513
514             bool DominatesDef = true;
515
516             if (InvokeInst *Invoke = dyn_cast<InvokeInst>(outputs[out])) {
517               DefBlock = Invoke->getNormalDest();
518
519               // Make sure we are looking at the original successor block, not
520               // at a newly inserted exit block, which won't be in the dominator
521               // info.
522               for (std::map<BasicBlock*, BasicBlock*>::iterator I =
523                      ExitBlockMap.begin(), E = ExitBlockMap.end(); I != E; ++I)
524                 if (DefBlock == I->second) {
525                   DefBlock = I->first;
526                   break;
527                 }
528
529               // In the extract block case, if the block we are extracting ends
530               // with an invoke instruction, make sure that we don't emit a
531               // store of the invoke value for the unwind block.
532               if (!DT && DefBlock != OldTarget)
533                 DominatesDef = false;
534             }
535
536             if (DT) {
537               DominatesDef = DT->dominates(DefBlock, OldTarget);
538               
539               // If the output value is used by a phi in the target block,
540               // then we need to test for dominance of the phi's predecessor
541               // instead.  Unfortunately, this a little complicated since we
542               // have already rewritten uses of the value to uses of the reload.
543               for (Value::use_iterator UI = Reloads[out]->use_begin(),
544                    UE = Reloads[out]->use_end(); UI != UE; ++UI) {
545                  PHINode *P = dyn_cast<PHINode>(*UI);
546                  if (!P || P->getParent() != OldTarget) continue;
547                  
548                  BasicBlock* pred = P->getIncomingBlock(UI);
549                  if (DT->dominates(DefBlock, pred)) {
550                    DominatesDef = true;
551                    break;
552                  }
553               }
554             }
555
556             if (DominatesDef) {
557               if (AggregateArgs) {
558                 Value *Idx[2];
559                 Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context));
560                 Idx[1] = ConstantInt::get(Type::getInt32Ty(Context),
561                                           FirstOut+out);
562                 GetElementPtrInst *GEP =
563                   GetElementPtrInst::Create(OAI, Idx, Idx + 2,
564                                             "gep_" + outputs[out]->getName(),
565                                             NTRet);
566                 new StoreInst(outputs[out], GEP, NTRet);
567               } else {
568                 new StoreInst(outputs[out], OAI, NTRet);
569               }
570             }
571             // Advance output iterator even if we don't emit a store
572             if (!AggregateArgs) ++OAI;
573           }
574         }
575
576         // rewrite the original branch instruction with this new target
577         TI->setSuccessor(i, NewTarget);
578       }
579   }
580
581   // Now that we've done the deed, simplify the switch instruction.
582   const Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType();
583   switch (NumExitBlocks) {
584   case 0:
585     // There are no successors (the block containing the switch itself), which
586     // means that previously this was the last part of the function, and hence
587     // this should be rewritten as a `ret'
588
589     // Check if the function should return a value
590     if (OldFnRetTy == Type::getVoidTy(Context)) {
591       ReturnInst::Create(Context, 0, TheSwitch);  // Return void
592     } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) {
593       // return what we have
594       ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch);
595     } else {
596       // Otherwise we must have code extracted an unwind or something, just
597       // return whatever we want.
598       ReturnInst::Create(Context, 
599                          Constant::getNullValue(OldFnRetTy), TheSwitch);
600     }
601
602     TheSwitch->eraseFromParent();
603     break;
604   case 1:
605     // Only a single destination, change the switch into an unconditional
606     // branch.
607     BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch);
608     TheSwitch->eraseFromParent();
609     break;
610   case 2:
611     BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2),
612                        call, TheSwitch);
613     TheSwitch->eraseFromParent();
614     break;
615   default:
616     // Otherwise, make the default destination of the switch instruction be one
617     // of the other successors.
618     TheSwitch->setOperand(0, call);
619     TheSwitch->setSuccessor(0, TheSwitch->getSuccessor(NumExitBlocks));
620     TheSwitch->removeCase(NumExitBlocks);  // Remove redundant case
621     break;
622   }
623 }
624
625 void CodeExtractor::moveCodeToFunction(Function *newFunction) {
626   Function *oldFunc = (*BlocksToExtract.begin())->getParent();
627   Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList();
628   Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList();
629
630   for (std::set<BasicBlock*>::const_iterator i = BlocksToExtract.begin(),
631          e = BlocksToExtract.end(); i != e; ++i) {
632     // Delete the basic block from the old function, and the list of blocks
633     oldBlocks.remove(*i);
634
635     // Insert this basic block into the new function
636     newBlocks.push_back(*i);
637   }
638 }
639
640 /// ExtractRegion - Removes a loop from a function, replaces it with a call to
641 /// new function. Returns pointer to the new function.
642 ///
643 /// algorithm:
644 ///
645 /// find inputs and outputs for the region
646 ///
647 /// for inputs: add to function as args, map input instr* to arg#
648 /// for outputs: add allocas for scalars,
649 ///             add to func as args, map output instr* to arg#
650 ///
651 /// rewrite func to use argument #s instead of instr*
652 ///
653 /// for each scalar output in the function: at every exit, store intermediate
654 /// computed result back into memory.
655 ///
656 Function *CodeExtractor::
657 ExtractCodeRegion(const std::vector<BasicBlock*> &code) {
658   if (!isEligible(code))
659     return 0;
660
661   // 1) Find inputs, outputs
662   // 2) Construct new function
663   //  * Add allocas for defs, pass as args by reference
664   //  * Pass in uses as args
665   // 3) Move code region, add call instr to func
666   //
667   BlocksToExtract.insert(code.begin(), code.end());
668
669   Values inputs, outputs;
670
671   // Assumption: this is a single-entry code region, and the header is the first
672   // block in the region.
673   BasicBlock *header = code[0];
674
675   for (unsigned i = 1, e = code.size(); i != e; ++i)
676     for (pred_iterator PI = pred_begin(code[i]), E = pred_end(code[i]);
677          PI != E; ++PI)
678       assert(BlocksToExtract.count(*PI) &&
679              "No blocks in this region may have entries from outside the region"
680              " except for the first block!");
681
682   // If we have to split PHI nodes or the entry block, do so now.
683   severSplitPHINodes(header);
684
685   // If we have any return instructions in the region, split those blocks so
686   // that the return is not in the region.
687   splitReturnBlocks();
688
689   Function *oldFunction = header->getParent();
690
691   // This takes place of the original loop
692   BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(), 
693                                                 "codeRepl", oldFunction,
694                                                 header);
695
696   // The new function needs a root node because other nodes can branch to the
697   // head of the region, but the entry node of a function cannot have preds.
698   BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(), 
699                                                "newFuncRoot");
700   newFuncRoot->getInstList().push_back(BranchInst::Create(header));
701
702   // Find inputs to, outputs from the code region.
703   findInputsOutputs(inputs, outputs);
704
705   // Construct new function based on inputs/outputs & add allocas for all defs.
706   Function *newFunction = constructFunction(inputs, outputs, header,
707                                             newFuncRoot,
708                                             codeReplacer, oldFunction,
709                                             oldFunction->getParent());
710
711   emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs);
712
713   moveCodeToFunction(newFunction);
714
715   // Loop over all of the PHI nodes in the header block, and change any
716   // references to the old incoming edge to be the new incoming edge.
717   for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) {
718     PHINode *PN = cast<PHINode>(I);
719     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
720       if (!BlocksToExtract.count(PN->getIncomingBlock(i)))
721         PN->setIncomingBlock(i, newFuncRoot);
722   }
723
724   // Look at all successors of the codeReplacer block.  If any of these blocks
725   // had PHI nodes in them, we need to update the "from" block to be the code
726   // replacer, not the original block in the extracted region.
727   std::vector<BasicBlock*> Succs(succ_begin(codeReplacer),
728                                  succ_end(codeReplacer));
729   for (unsigned i = 0, e = Succs.size(); i != e; ++i)
730     for (BasicBlock::iterator I = Succs[i]->begin(); isa<PHINode>(I); ++I) {
731       PHINode *PN = cast<PHINode>(I);
732       std::set<BasicBlock*> ProcessedPreds;
733       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
734         if (BlocksToExtract.count(PN->getIncomingBlock(i))) {
735           if (ProcessedPreds.insert(PN->getIncomingBlock(i)).second)
736             PN->setIncomingBlock(i, codeReplacer);
737           else {
738             // There were multiple entries in the PHI for this block, now there
739             // is only one, so remove the duplicated entries.
740             PN->removeIncomingValue(i, false);
741             --i; --e;
742           }
743         }
744     }
745
746   //cerr << "NEW FUNCTION: " << *newFunction;
747   //  verifyFunction(*newFunction);
748
749   //  cerr << "OLD FUNCTION: " << *oldFunction;
750   //  verifyFunction(*oldFunction);
751
752   DEBUG(if (verifyFunction(*newFunction)) 
753         llvm_report_error("verifyFunction failed!"));
754   return newFunction;
755 }
756
757 bool CodeExtractor::isEligible(const std::vector<BasicBlock*> &code) {
758   // Deny code region if it contains allocas or vastarts.
759   for (std::vector<BasicBlock*>::const_iterator BB = code.begin(), e=code.end();
760        BB != e; ++BB)
761     for (BasicBlock::const_iterator I = (*BB)->begin(), Ie = (*BB)->end();
762          I != Ie; ++I)
763       if (isa<AllocaInst>(*I))
764         return false;
765       else if (const CallInst *CI = dyn_cast<CallInst>(I))
766         if (const Function *F = CI->getCalledFunction())
767           if (F->getIntrinsicID() == Intrinsic::vastart)
768             return false;
769   return true;
770 }
771
772
773 /// ExtractCodeRegion - slurp a sequence of basic blocks into a brand new
774 /// function
775 ///
776 Function* llvm::ExtractCodeRegion(DominatorTree &DT,
777                                   const std::vector<BasicBlock*> &code,
778                                   bool AggregateArgs) {
779   return CodeExtractor(&DT, AggregateArgs).ExtractCodeRegion(code);
780 }
781
782 /// ExtractBasicBlock - slurp a natural loop into a brand new function
783 ///
784 Function* llvm::ExtractLoop(DominatorTree &DT, Loop *L, bool AggregateArgs) {
785   return CodeExtractor(&DT, AggregateArgs).ExtractCodeRegion(L->getBlocks());
786 }
787
788 /// ExtractBasicBlock - slurp a basic block into a brand new function
789 ///
790 Function* llvm::ExtractBasicBlock(BasicBlock *BB, bool AggregateArgs) {
791   std::vector<BasicBlock*> Blocks;
792   Blocks.push_back(BB);
793   return CodeExtractor(0, AggregateArgs).ExtractCodeRegion(Blocks);
794 }