1 //===- CloneTrace.cpp - Clone a trace -------------------------------------===//
3 // This file implements the CloneTrace interface, which is used
4 // when writing runtime optimizations. It takes a vector of basic blocks
5 // clones the basic blocks, removes internal phi nodes, adds it to the
6 // same function as the original (although there is no jump to it) and
7 // returns the new vector of basic blocks.
9 //===----------------------------------------------------------------------===//
11 #include "llvm/Transforms/Utils/Cloning.h"
12 #include "llvm/iPHINode.h"
13 #include "llvm/Function.h"
16 //Clones the trace (a vector of basic blocks)
17 std::vector<BasicBlock *> CloneTrace(const std::vector<BasicBlock*> &origTrace) {
19 std::vector<BasicBlock *> clonedTrace;
20 std::map<const Value*, Value*> ValueMap;
22 //First, loop over all the Basic Blocks in the trace and copy
23 //them using CloneBasicBlock. Also fix the phi nodes during
24 //this loop. To fix the phi nodes, we delete incoming branches
25 //that are not in the trace.
26 for(std::vector<BasicBlock *>::const_iterator T = origTrace.begin(),
27 End = origTrace.end(); T != End; ++T) {
30 BasicBlock *clonedBlock = CloneBasicBlock(*T, ValueMap);
32 //Add it to our new trace
33 clonedTrace.push_back(clonedBlock);
35 //Add this new mapping to our Value Map
36 ValueMap[*T] = clonedBlock;
38 //Add this cloned BB to the old BB's function
39 (*T)->getParent()->getBasicBlockList().push_back(clonedBlock);
41 //Loop over the phi instructions and delete operands
42 //that are from blocks not in the trace
43 //only do this if we are NOT the first block
44 if(T != origTrace.begin()) {
45 for (BasicBlock::iterator I = clonedBlock->begin();
46 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
47 //get incoming value for the previous BB
48 Value *V = PN->getIncomingValueForBlock(*(T-1));
49 assert(V && "No incoming value from a BasicBlock in our trace!");
51 //remap our phi node to point to incoming value
55 clonedBlock->getInstList().erase(PN);
60 //Second loop to do the remapping
61 for(std::vector<BasicBlock *>::const_iterator BB = clonedTrace.begin(),
62 BE = clonedTrace.end(); BB != BE; ++BB) {
63 for(BasicBlock::iterator I = (*BB)->begin(); I != (*BB)->end(); ++I) {
65 //Loop over all the operands of the instruction
66 for(unsigned op=0, E = I->getNumOperands(); op != E; ++op) {
67 const Value *Op = I->getOperand(op);
69 //Get it out of the value map
70 Value *V = ValueMap[Op];
72 //If not in the value map, then its outside our trace so ignore
79 //return new vector of basic blocks