1 //===-- BasicBlockUtils.cpp - BasicBlock Utilities -------------------------==//
3 // This family of functions perform manipulations on basic blocks, and
4 // instructions contained within basic blocks.
6 //===----------------------------------------------------------------------===//
8 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
9 #include "llvm/Function.h"
10 #include "llvm/Instruction.h"
13 // ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
14 // with a value, then remove and delete the original instruction.
16 void ReplaceInstWithValue(BasicBlock::InstListType &BIL,
17 BasicBlock::iterator &BI, Value *V) {
19 // Replaces all of the uses of the instruction with uses of the value
20 I->replaceAllUsesWith(V);
22 // Remove the unneccesary instruction now...
25 // Make sure to propogate a name if there is one already...
26 if (I->hasName() && !V->hasName())
27 V->setName(I->getName(), BIL.getParent()->getSymbolTable());
29 // Remove the dead instruction now...
34 // ReplaceInstWithInst - Replace the instruction specified by BI with the
35 // instruction specified by I. The original instruction is deleted and BI is
36 // updated to point to the new instruction.
38 void ReplaceInstWithInst(BasicBlock::InstListType &BIL,
39 BasicBlock::iterator &BI, Instruction *I) {
40 assert(I->getParent() == 0 &&
41 "ReplaceInstWithInst: Instruction already inserted into basic block!");
43 // Insert the new instruction into the basic block...
44 BI = BIL.insert(BI, I)+1; // Increment BI to point to instruction to delete
46 // Replace all uses of the old instruction, and delete it.
47 ReplaceInstWithValue(BIL, BI, I);
49 // Move BI back to point to the newly inserted instruction
53 // ReplaceInstWithInst - Replace the instruction specified by From with the
54 // instruction specified by To. Note that this is slower than providing an
55 // iterator directly, because the basic block containing From must be searched
56 // for the instruction.
58 void ReplaceInstWithInst(Instruction *From, Instruction *To) {
59 BasicBlock *BB = From->getParent();
60 BasicBlock::InstListType &BIL = BB->getInstList();
61 BasicBlock::iterator BI = find(BIL.begin(), BIL.end(), From);
62 assert(BI != BIL.end() && "Inst not in it's parents BB!");
63 ReplaceInstWithInst(BIL, BI, To);
66 // InsertInstBeforeInst - Insert 'NewInst' into the basic block that 'Existing'
67 // is already in, and put it right before 'Existing'. This instruction should
68 // only be used when there is no iterator to Existing already around. The
69 // returned iterator points to the new instruction.
71 BasicBlock::iterator InsertInstBeforeInst(Instruction *NewInst,
72 Instruction *Existing) {
73 BasicBlock *BB = Existing->getParent();
74 BasicBlock::InstListType &BIL = BB->getInstList();
75 BasicBlock::iterator BI = find(BIL.begin(), BIL.end(), Existing);
76 assert(BI != BIL.end() && "Inst not in it's parents BB!");
77 return BIL.insert(BI, NewInst);