@@ -7806,23 +7806,41 @@ bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) {
78067806 DenseMap<Instruction *, Instruction *> NewInstructions;
78077807 for (Use *U : ToReplace) {
78087808 auto *UI = cast<Instruction>(U->get ());
7809- Instruction *NI = UI->clone ();
7810-
7811- if (IsHugeFunc) {
7812- // Now we clone an instruction, its operands' defs may sink to this BB
7813- // now. So we put the operands defs' BBs into FreshBBs to do optimization.
7814- for (Value *Op : NI->operands ())
7815- if (auto *OpDef = dyn_cast<Instruction>(Op))
7816- FreshBBs.insert (OpDef->getParent ());
7809+ // Before we clone the instruction, check if we already created an
7810+ // equivalent instruction in the BB and use that instead.
7811+ bool foundEquiv = false ;
7812+ Instruction *NI = nullptr ;
7813+ for (auto &IToCheck : *TargetBB) {
7814+ if (&IToCheck == I)
7815+ break ;
7816+ if (UI->isIdenticalTo (&IToCheck)) {
7817+ // We found an equivalent instruction in this BB that dominates I, let's
7818+ // use it instead!
7819+ NI = &IToCheck;
7820+ LLVM_DEBUG (dbgs () << " Found an equivalent instruction for " << *UI << " in BB: " << *NI << " \n " );
7821+ foundEquiv = true ;
7822+ break ;
7823+ }
78177824 }
7825+ if (!foundEquiv) {
7826+ NI = UI->clone ();
78187827
7828+ if (IsHugeFunc) {
7829+ // Now we clone an instruction, its operands' defs may sink to this BB
7830+ // now. So we put the operands defs' BBs into FreshBBs to do optimization.
7831+ for (Value *Op : NI->operands ())
7832+ if (auto *OpDef = dyn_cast<Instruction>(Op))
7833+ FreshBBs.insert (OpDef->getParent ());
7834+ }
7835+
7836+ LLVM_DEBUG (dbgs () << " Sinking " << *UI << " to user " << *I << " \n " );
7837+ NI->insertBefore (InsertPoint->getIterator ());
7838+ InsertPoint = NI;
7839+ InsertedInsts.insert (NI);
7840+ }
7841+ assert (NI && " Didn't find/create a valid sunk instruction!" );
78197842 NewInstructions[UI] = NI;
78207843 MaybeDead.insert (UI);
7821- LLVM_DEBUG (dbgs () << " Sinking " << *UI << " to user " << *I << " \n " );
7822- NI->insertBefore (InsertPoint->getIterator ());
7823- InsertPoint = NI;
7824- InsertedInsts.insert (NI);
7825-
78267844 // Update the use for the new instruction, making sure that we update the
78277845 // sunk instruction uses, if it is part of a chain that has already been
78287846 // sunk.
0 commit comments