- for (BBIt = BBs.begin(); BBIt != BBs.end(); BBIt++) {
- BasicBlock *BB = *BBIt;
-
- // Is there exactly one predecessor to this block?
- BasicBlock::pred_iterator PI(BB->pred_begin());
- if (PI != BB->pred_end() && ++PI == BB->pred_end() &&
- !BB->hasConstantPoolReferences()) {
- BasicBlock *Pred = *BB->pred_begin();
- TerminatorInst *Term = Pred->getTerminator();
- if (Term == 0) continue; // Err... malformed basic block!
-
- // Is it an unconditional branch?
- if (Term->getInstType() != Instruction::Br ||
- !((BranchInst*)Term)->isUnconditional())
- continue; // Nope, maybe next time...
-
- Changed = true;
-
- // Make all branches to the predecessor now point to the successor...
- Pred->replaceAllUsesWith(BB);
-
- // Move all definitions in the predecessor to the successor...
- BasicBlock::InstListType::iterator DI = Pred->getInstList().end();
- assert(Pred->getTerminator() &&
- "Degenerate basic block encountered!"); // Empty bb???
- delete Pred->getInstList().remove(--DI); // Remove terminator
-
- while (Pred->getInstList().begin() != (DI = Pred->getInstList().end())) {
- Instruction *Def = Pred->getInstList().remove(--DI); // Remove from end
- BB->getInstList().push_front(Def); // Add to front...
- }
-
- // Remove basic block from the method...
- BBs.remove(Pred);
-
- // Always inherit predecessors name if it exists...
- if (Pred->hasName()) BB->setName(Pred->getName());
-
- // So long you waste of a basic block you...
- delete Pred;
+ while (!WorkList.empty()) {
+ Instruction *I = WorkList.back();
+ WorkList.pop_back();
+
+ if (isInstructionTriviallyDead(I)) { // If the instruction is dead...
+ // Loop over all of the values that the instruction uses, if there are
+ // instructions being used, add them to the worklist, because they might
+ // go dead after this one is removed.
+ //
+ for (User::use_iterator UI = I->use_begin(), UE = I->use_end();
+ UI != UE; ++UI)
+ if (Instruction *Used = dyn_cast<Instruction>(*UI))
+ WorkList.push_back(Used);
+
+ // Tell the instruction to let go of all of the values it uses...
+ I->dropAllReferences();
+
+ // Keep track of this instruction, because we are going to delete it later
+ DeadInsts.insert(I);