// If there is more than one pred of succ, and there are PHI nodes in
// the successor, then we need to add incoming edges for the PHI nodes
//
- const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
+ const SmallVector<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
// Loop over all of the PHI nodes in the successor of BB.
for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
PN->addIncoming(OldValPN->getIncomingValue(i),
OldValPN->getIncomingBlock(i));
} else {
- for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
- End = BBPreds.end(); PredI != End; ++PredI) {
- // Add an incoming value for each of the new incoming values...
- PN->addIncoming(OldVal, *PredI);
- }
+ // Add an incoming value for each of the new incoming values.
+ for (unsigned i = 0, e = BBPreds.size(); i != e; ++i)
+ PN->addIncoming(OldVal, BBPreds[i]);
}
}
}
if (isa<PHINode>(&BB->front())) {
- std::vector<BasicBlock*>
+ SmallVector<BasicBlock*, 16>
OldSuccPreds(pred_begin(Succ), pred_end(Succ));
// Move all PHI nodes in BB to Succ if they are alive, otherwise
// icmp_eq instructions that compare a value against a constant, return the
// value being compared, and stick the constant into the Values vector.
static Value *GatherConstantSetEQs(Value *V, std::vector<ConstantInt*> &Values){
- if (Instruction *Inst = dyn_cast<Instruction>(V))
+ if (Instruction *Inst = dyn_cast<Instruction>(V)) {
if (Inst->getOpcode() == Instruction::ICmp &&
cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_EQ) {
if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
if (LHS == RHS)
return LHS;
}
+ }
return 0;
}
// setne instructions that compare a value against a constant, return the value
// being compared, and stick the constant into the Values vector.
static Value *GatherConstantSetNEs(Value *V, std::vector<ConstantInt*> &Values){
- if (Instruction *Inst = dyn_cast<Instruction>(V))
+ if (Instruction *Inst = dyn_cast<Instruction>(V)) {
if (Inst->getOpcode() == Instruction::ICmp &&
cast<ICmpInst>(Inst)->getPredicate() == ICmpInst::ICMP_NE) {
if (ConstantInt *C = dyn_cast<ConstantInt>(Inst->getOperand(1))) {
if (LHS == RHS)
return LHS;
}
+ }
return 0;
}
static void ErasePossiblyDeadInstructionTree(Instruction *I) {
if (!isInstructionTriviallyDead(I)) return;
- std::vector<Instruction*> InstrsToInspect;
+ SmallVector<Instruction*, 16> InstrsToInspect;
InstrsToInspect.push_back(I);
while (!InstrsToInspect.empty()) {
assert(ThisCases.size() == 1 && "Branch can only have one case!");
Value *Cond = BTI->getCondition();
// Insert the new branch.
- Instruction *NI = new BranchInst(ThisDef, TI);
+ Instruction *NI = BranchInst::Create(ThisDef, TI);
// Remove PHI node entries for the dead edge.
ThisCases[0].second->removePredecessor(TI->getParent());
ConstantInt *TIV = 0;
BasicBlock *TIBB = TI->getParent();
for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
- if (PredCases[i].second == TIBB)
+ if (PredCases[i].second == TIBB) {
if (TIV == 0)
TIV = PredCases[i].first;
else
return false; // Cannot handle multiple values coming to this block.
+ }
assert(TIV && "No edge from pred to succ?");
// Okay, we found the one constant that our value can be if we get into TI's
CheckEdge = 0;
// Insert the new branch.
- Instruction *NI = new BranchInst(TheRealDest, TI);
+ Instruction *NI = BranchInst::Create(TheRealDest, TI);
DOUT << "Threading pred instr: " << *Pred->getTerminator()
<< "Through successor TI: " << *TI << "Leaving: " << *NI << "\n";
assert(CV && "Not a comparison?");
bool Changed = false;
- std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
+ SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
while (!Preds.empty()) {
BasicBlock *Pred = Preds.back();
Preds.pop_back();
// Based on whether the default edge from PTI goes to BB or not, fill in
// PredCases and PredDefault with the new switch cases we would like to
// build.
- std::vector<BasicBlock*> NewSuccessors;
+ SmallVector<BasicBlock*, 8> NewSuccessors;
if (PredDefault == BB) {
// If this is the default destination from PTI, only the edges in TI
AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
// Now that the successors are updated, create the new Switch instruction.
- SwitchInst *NewSI = new SwitchInst(CV, PredDefault, PredCases.size(),PTI);
+ SwitchInst *NewSI = SwitchInst::Create(CV, PredDefault, PredCases.size(), PTI);
for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
NewSI->addCase(PredCases[i].first, PredCases[i].second);
if (InfLoopBlock == 0) {
// Insert it at the end of the loop, because it's either code,
// or it won't matter if it's hot. :)
- InfLoopBlock = new BasicBlock("infloop", BB->getParent());
- new BranchInst(InfLoopBlock, InfLoopBlock);
+ InfLoopBlock = BasicBlock::Create("infloop", BB->getParent());
+ BranchInst::Create(InfLoopBlock, InfLoopBlock);
}
NewSI->setSuccessor(i, InfLoopBlock);
}
// that determines the right value.
SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
if (SI == 0)
- SI = new SelectInst(BI->getCondition(), BB1V, BB2V,
- BB1V->getName()+"."+BB2V->getName(), NT);
+ SI = SelectInst::Create(BI->getCondition(), BB1V, BB2V,
+ BB1V->getName()+"."+BB2V->getName(), NT);
// Make the PHI node use the select for all incoming values for BB1/BB2
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
// difficult cases. Instead of being smart about this, just insert a new
// block that jumps to the destination block, effectively splitting
// the edge we are about to create.
- BasicBlock *EdgeBB = new BasicBlock(RealDest->getName()+".critedge",
- RealDest->getParent(), RealDest);
- new BranchInst(RealDest, EdgeBB);
+ BasicBlock *EdgeBB = BasicBlock::Create(RealDest->getName()+".critedge",
+ RealDest->getParent(), RealDest);
+ BranchInst::Create(RealDest, EdgeBB);
PHINode *PN;
for (BasicBlock::iterator BBI = RealDest->begin();
(PN = dyn_cast<PHINode>(BBI)); ++BBI) {
Value *FalseVal =
PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
- Value *NV = new SelectInst(IfCond, TrueVal, FalseVal, "", AfterPHIIt);
+ Value *NV = SelectInst::Create(IfCond, TrueVal, FalseVal, "", AfterPHIIt);
PN->replaceAllUsesWith(NV);
NV->takeName(PN);
return true;
}
+/// SimplifyCondBranchToTwoReturns - If we found a conditional branch that goes
+/// to two returning blocks, try to merge them together into one return,
+/// introducing a select if the return values disagree.
+static bool SimplifyCondBranchToTwoReturns(BranchInst *BI) {
+ assert(BI->isConditional() && "Must be a conditional branch");
+ BasicBlock *TrueSucc = BI->getSuccessor(0);
+ BasicBlock *FalseSucc = BI->getSuccessor(1);
+ ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
+ ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
+
+ // Check to ensure both blocks are empty (just a return) or optionally empty
+ // with PHI nodes. If there are other instructions, merging would cause extra
+ // computation on one path or the other.
+ BasicBlock::iterator BBI = TrueRet;
+ if (BBI != TrueSucc->begin() && !isa<PHINode>(--BBI))
+ return false; // Not empty with optional phi nodes.
+ BBI = FalseRet;
+ if (BBI != FalseSucc->begin() && !isa<PHINode>(--BBI))
+ return false; // Not empty with optional phi nodes.
+
+ // Okay, we found a branch that is going to two return nodes. If
+ // there is no return value for this function, just change the
+ // branch into a return.
+ if (FalseRet->getNumOperands() == 0) {
+ TrueSucc->removePredecessor(BI->getParent());
+ FalseSucc->removePredecessor(BI->getParent());
+ ReturnInst::Create(0, BI);
+ BI->eraseFromParent();
+ return true;
+ }
+
+ // Otherwise, build up the result values for the new return.
+ SmallVector<Value*, 4> TrueResult;
+ SmallVector<Value*, 4> FalseResult;
+
+ for (unsigned i = 0, e = TrueRet->getNumOperands(); i != e; ++i) {
+ // Otherwise, figure out what the true and false return values are
+ // so we can insert a new select instruction.
+ Value *TrueValue = TrueRet->getOperand(i);
+ Value *FalseValue = FalseRet->getOperand(i);
+
+ // Unwrap any PHI nodes in the return blocks.
+ if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue))
+ if (TVPN->getParent() == TrueSucc)
+ TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
+ if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue))
+ if (FVPN->getParent() == FalseSucc)
+ FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
+
+ // In order for this transformation to be safe, we must be able to
+ // unconditionally execute both operands to the return. This is
+ // normally the case, but we could have a potentially-trapping
+ // constant expression that prevents this transformation from being
+ // safe.
+ if (ConstantExpr *TCV = dyn_cast<ConstantExpr>(TrueValue))
+ if (TCV->canTrap())
+ return false;
+ if (ConstantExpr *FCV = dyn_cast<ConstantExpr>(FalseValue))
+ if (FCV->canTrap())
+ return false;
+
+ TrueResult.push_back(TrueValue);
+ FalseResult.push_back(FalseValue);
+ }
+
+ // Okay, we collected all the mapped values and checked them for sanity, and
+ // defined to really do this transformation. First, update the CFG.
+ TrueSucc->removePredecessor(BI->getParent());
+ FalseSucc->removePredecessor(BI->getParent());
+
+ // Insert select instructions where needed.
+ Value *BrCond = BI->getCondition();
+ for (unsigned i = 0, e = TrueRet->getNumOperands(); i != e; ++i) {
+ // Insert a select if the results differ.
+ if (TrueResult[i] == FalseResult[i] || isa<UndefValue>(FalseResult[i]))
+ continue;
+ if (isa<UndefValue>(TrueResult[i])) {
+ TrueResult[i] = FalseResult[i];
+ continue;
+ }
+
+ TrueResult[i] = SelectInst::Create(BrCond, TrueResult[i],
+ FalseResult[i], "retval", BI);
+ }
+
+ Value *RI = ReturnInst::Create(&TrueResult[0], TrueResult.size(), BI);
+
+ DOUT << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
+ << "\n " << *BI << "NewRet = " << *RI
+ << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc;
+
+ BI->eraseFromParent();
+
+ if (Instruction *BrCondI = dyn_cast<Instruction>(BrCond))
+ ErasePossiblyDeadInstructionTree(BrCondI);
+ return true;
+}
+
+
namespace {
/// ConstantIntOrdering - This class implements a stable ordering of constant
/// integers that does not depend on their address. This is important for
"Can't Simplify entry block!");
// Remove basic blocks that have no predecessors... which are unreachable.
- if (pred_begin(BB) == pred_end(BB) ||
- *pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB)) {
+ if ((pred_begin(BB) == pred_end(BB)) ||
+ (*pred_begin(BB) == BB && ++pred_begin(BB) == pred_end(BB))) {
DOUT << "Removing BB: \n" << *BB;
// Loop through all of our successors and make sure they know that one
// away...
Changed |= ConstantFoldTerminator(BB);
+ // If there is a trivial two-entry PHI node in this basic block, and we can
+ // eliminate it, do so now.
+ if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
+ if (PN->getNumIncomingValues() == 2)
+ Changed |= FoldTwoEntryPHINode(PN);
+
// If this is a returning block with only PHI nodes in it, fold the return
// instruction into any unconditional branch predecessors.
//
BasicBlock::iterator BBI = BB->getTerminator();
if (BBI == BB->begin() || isa<PHINode>(--BBI)) {
// Find predecessors that end with branches.
- std::vector<BasicBlock*> UncondBranchPreds;
- std::vector<BranchInst*> CondBranchPreds;
+ SmallVector<BasicBlock*, 8> UncondBranchPreds;
+ SmallVector<BranchInst*, 8> CondBranchPreds;
for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
TerminatorInst *PTI = (*PI)->getTerminator();
- if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
+ if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
if (BI->isUnconditional())
UncondBranchPreds.push_back(*PI);
else
CondBranchPreds.push_back(BI);
+ }
}
// If we found some, do the transformation!
while (!CondBranchPreds.empty()) {
BranchInst *BI = CondBranchPreds.back();
CondBranchPreds.pop_back();
- BasicBlock *TrueSucc = BI->getSuccessor(0);
- BasicBlock *FalseSucc = BI->getSuccessor(1);
- BasicBlock *OtherSucc = TrueSucc == BB ? FalseSucc : TrueSucc;
// Check to see if the non-BB successor is also a return block.
- if (isa<ReturnInst>(OtherSucc->getTerminator())) {
- // Check to see if there are only PHI instructions in this block.
- BasicBlock::iterator OSI = OtherSucc->getTerminator();
- if (OSI == OtherSucc->begin() || isa<PHINode>(--OSI)) {
- // Okay, we found a branch that is going to two return nodes. If
- // there is no return value for this function, just change the
- // branch into a return.
- if (RI->getNumOperands() == 0) {
- TrueSucc->removePredecessor(BI->getParent());
- FalseSucc->removePredecessor(BI->getParent());
- new ReturnInst(0, BI);
- BI->getParent()->getInstList().erase(BI);
- return true;
- }
-
- // Otherwise, figure out what the true and false return values are
- // so we can insert a new select instruction.
- Value *TrueValue = TrueSucc->getTerminator()->getOperand(0);
- Value *FalseValue = FalseSucc->getTerminator()->getOperand(0);
-
- // Unwrap any PHI nodes in the return blocks.
- if (PHINode *TVPN = dyn_cast<PHINode>(TrueValue))
- if (TVPN->getParent() == TrueSucc)
- TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
- if (PHINode *FVPN = dyn_cast<PHINode>(FalseValue))
- if (FVPN->getParent() == FalseSucc)
- FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
-
- // In order for this transformation to be safe, we must be able to
- // unconditionally execute both operands to the return. This is
- // normally the case, but we could have a potentially-trapping
- // constant expression that prevents this transformation from being
- // safe.
- if ((!isa<ConstantExpr>(TrueValue) ||
- !cast<ConstantExpr>(TrueValue)->canTrap()) &&
- (!isa<ConstantExpr>(TrueValue) ||
- !cast<ConstantExpr>(TrueValue)->canTrap())) {
- TrueSucc->removePredecessor(BI->getParent());
- FalseSucc->removePredecessor(BI->getParent());
-
- // Insert a new select instruction.
- Value *NewRetVal;
- Value *BrCond = BI->getCondition();
- if (TrueValue != FalseValue)
- NewRetVal = new SelectInst(BrCond, TrueValue,
- FalseValue, "retval", BI);
- else
- NewRetVal = TrueValue;
-
- DOUT << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
- << "\n " << *BI << "Select = " << *NewRetVal
- << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc;
-
- new ReturnInst(NewRetVal, BI);
- BI->eraseFromParent();
- if (Instruction *BrCondI = dyn_cast<Instruction>(BrCond))
- if (isInstructionTriviallyDead(BrCondI))
- BrCondI->eraseFromParent();
- return true;
- }
- }
- }
+ if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
+ isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
+ SimplifyCondBranchToTwoReturns(BI))
+ return true;
}
}
} else if (isa<UnwindInst>(BB->begin())) {
// destination with call instructions, and any unconditional branch
// predecessor with an unwind.
//
- std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
+ SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
while (!Preds.empty()) {
BasicBlock *Pred = Preds.back();
if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator())) {
if (II->getUnwindDest() == BB) {
// Insert a new branch instruction before the invoke, because this
// is now a fall through...
- BranchInst *BI = new BranchInst(II->getNormalDest(), II);
+ BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
Pred->getInstList().remove(II); // Take out of symbol table
// Insert the call now...
SmallVector<Value*,8> Args(II->op_begin()+3, II->op_end());
- CallInst *CI = new CallInst(II->getCalledValue(),
- Args.begin(), Args.end(), II->getName(), BI);
+ CallInst *CI = CallInst::Create(II->getCalledValue(),
+ Args.begin(), Args.end(), II->getName(), BI);
CI->setCallingConv(II->getCallingConv());
CI->setParamAttrs(II->getParamAttrs());
// If the invoke produced a value, the Call now does instead
// Otherwise, if there are multiple predecessors, insert a PHI
// that merges in the constant and simplify the block result.
if (BlockIsSimpleEnoughToThreadThrough(BB)) {
- PHINode *NewPN = new PHINode(Type::Int1Ty,
- BI->getCondition()->getName()+".pr",
- BB->begin());
+ PHINode *NewPN = PHINode::Create(Type::Int1Ty,
+ BI->getCondition()->getName()+".pr",
+ BB->begin());
for (PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
if ((PBI = dyn_cast<BranchInst>((*PI)->getTerminator())) &&
PBI != BI && PBI->isConditional() &&
Value *PBIV = PN->getIncomingValue(PBBIdx);
if (BIV != PBIV) {
// Insert a select in PBI to pick the right value.
- Value *NV = new SelectInst(PBICond, PBIV, BIV,
- PBIV->getName()+".mux", PBI);
+ Value *NV = SelectInst::Create(PBICond, PBIV, BIV,
+ PBIV->getName()+".mux", PBI);
PN->setIncomingValue(PBBIdx, NV);
}
}
// If the unreachable instruction is the first in the block, take a gander
// at all of the predecessors of this instruction, and simplify them.
if (&BB->front() == Unreachable) {
- std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
+ SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
TerminatorInst *TI = Preds[i]->getTerminator();
}
} else {
if (BI->getSuccessor(0) == BB) {
- new BranchInst(BI->getSuccessor(1), BI);
+ BranchInst::Create(BI->getSuccessor(1), BI);
BI->eraseFromParent();
} else if (BI->getSuccessor(1) == BB) {
- new BranchInst(BI->getSuccessor(0), BI);
+ BranchInst::Create(BI->getSuccessor(0), BI);
BI->eraseFromParent();
Changed = true;
}
if (II->getUnwindDest() == BB) {
// Convert the invoke to a call instruction. This would be a good
// place to note that the call does not throw though.
- BranchInst *BI = new BranchInst(II->getNormalDest(), II);
+ BranchInst *BI = BranchInst::Create(II->getNormalDest(), II);
II->removeFromParent(); // Take out of symbol table
// Insert the call now...
SmallVector<Value*, 8> Args(II->op_begin()+3, II->op_end());
- CallInst *CI = new CallInst(II->getCalledValue(),
- Args.begin(), Args.end(),
- II->getName(), BI);
+ CallInst *CI = CallInst::Create(II->getCalledValue(),
+ Args.begin(), Args.end(),
+ II->getName(), BI);
CI->setCallingConv(II->getCallingConv());
CI->setParamAttrs(II->getParamAttrs());
// If the invoke produced a value, the Call does now instead.
if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
// Create the new switch instruction now.
- SwitchInst *New = new SwitchInst(CompVal, DefaultBB,Values.size(),BI);
+ SwitchInst *New = SwitchInst::Create(CompVal, DefaultBB,Values.size(),BI);
// Add all of the 'cases' to the switch instruction.
for (unsigned i = 0, e = Values.size(); i != e; ++i)
}
}
- // If there is a trivial two-entry PHI node in this basic block, and we can
- // eliminate it, do so now.
- if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
- if (PN->getNumIncomingValues() == 2)
- Changed |= FoldTwoEntryPHINode(PN);
-
return Changed;
}