xref: /llvm-project/llvm/lib/CodeGen/MachineCombiner.cpp (revision b5640369337e98e573c949080ed4a4061ec6ec9a)
1 //===---- MachineCombiner.cpp - Instcombining on SSA form machine code ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // The machine combiner pass uses machine trace metrics to ensure the combined
10 // instructions do not lengthen the critical path or the resource depth.
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/DenseMap.h"
14 #include "llvm/ADT/Statistic.h"
15 #include "llvm/Analysis/ProfileSummaryInfo.h"
16 #include "llvm/CodeGen/LazyMachineBlockFrequencyInfo.h"
17 #include "llvm/CodeGen/MachineCombinerPattern.h"
18 #include "llvm/CodeGen/MachineDominators.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineLoopInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/MachineSizeOpts.h"
24 #include "llvm/CodeGen/MachineTraceMetrics.h"
25 #include "llvm/CodeGen/RegisterClassInfo.h"
26 #include "llvm/CodeGen/TargetInstrInfo.h"
27 #include "llvm/CodeGen/TargetRegisterInfo.h"
28 #include "llvm/CodeGen/TargetSchedule.h"
29 #include "llvm/CodeGen/TargetSubtargetInfo.h"
30 #include "llvm/InitializePasses.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 
35 using namespace llvm;
36 
37 #define DEBUG_TYPE "machine-combiner"
38 
39 STATISTIC(NumInstCombined, "Number of machineinst combined");
40 
41 static cl::opt<unsigned>
42 inc_threshold("machine-combiner-inc-threshold", cl::Hidden,
43               cl::desc("Incremental depth computation will be used for basic "
44                        "blocks with more instructions."), cl::init(500));
45 
46 static cl::opt<bool> dump_intrs("machine-combiner-dump-subst-intrs", cl::Hidden,
47                                 cl::desc("Dump all substituted intrs"),
48                                 cl::init(false));
49 
50 #ifdef EXPENSIVE_CHECKS
51 static cl::opt<bool> VerifyPatternOrder(
52     "machine-combiner-verify-pattern-order", cl::Hidden,
53     cl::desc(
54         "Verify that the generated patterns are ordered by increasing latency"),
55     cl::init(true));
56 #else
57 static cl::opt<bool> VerifyPatternOrder(
58     "machine-combiner-verify-pattern-order", cl::Hidden,
59     cl::desc(
60         "Verify that the generated patterns are ordered by increasing latency"),
61     cl::init(false));
62 #endif
63 
64 namespace {
65 class MachineCombiner : public MachineFunctionPass {
66   const TargetSubtargetInfo *STI = nullptr;
67   const TargetInstrInfo *TII = nullptr;
68   const TargetRegisterInfo *TRI = nullptr;
69   MCSchedModel SchedModel;
70   MachineRegisterInfo *MRI = nullptr;
71   MachineLoopInfo *MLI = nullptr; // Current MachineLoopInfo
72   MachineTraceMetrics *Traces = nullptr;
73   MachineTraceMetrics::Ensemble *TraceEnsemble = nullptr;
74   MachineBlockFrequencyInfo *MBFI = nullptr;
75   ProfileSummaryInfo *PSI = nullptr;
76   RegisterClassInfo RegClassInfo;
77 
78   TargetSchedModel TSchedModel;
79 
80   /// True if optimizing for code size.
81   bool OptSize = false;
82 
83 public:
84   static char ID;
85   MachineCombiner() : MachineFunctionPass(ID) {
86     initializeMachineCombinerPass(*PassRegistry::getPassRegistry());
87   }
88   void getAnalysisUsage(AnalysisUsage &AU) const override;
89   bool runOnMachineFunction(MachineFunction &MF) override;
90   StringRef getPassName() const override { return "Machine InstCombiner"; }
91 
92 private:
93   bool combineInstructions(MachineBasicBlock *);
94   MachineInstr *getOperandDef(const MachineOperand &MO);
95   bool isTransientMI(const MachineInstr *MI);
96   unsigned getDepth(SmallVectorImpl<MachineInstr *> &InsInstrs,
97                     DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
98                     MachineTraceMetrics::Trace BlockTrace,
99                     const MachineBasicBlock &MBB);
100   unsigned getLatency(MachineInstr *Root, MachineInstr *NewRoot,
101                       MachineTraceMetrics::Trace BlockTrace);
102   bool improvesCriticalPathLen(MachineBasicBlock *MBB, MachineInstr *Root,
103                                MachineTraceMetrics::Trace BlockTrace,
104                                SmallVectorImpl<MachineInstr *> &InsInstrs,
105                                SmallVectorImpl<MachineInstr *> &DelInstrs,
106                                DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
107                                unsigned Pattern, bool SlackIsAccurate);
108   bool reduceRegisterPressure(MachineInstr &Root, MachineBasicBlock *MBB,
109                               SmallVectorImpl<MachineInstr *> &InsInstrs,
110                               SmallVectorImpl<MachineInstr *> &DelInstrs,
111                               unsigned Pattern);
112   bool preservesResourceLen(MachineBasicBlock *MBB,
113                             MachineTraceMetrics::Trace BlockTrace,
114                             SmallVectorImpl<MachineInstr *> &InsInstrs,
115                             SmallVectorImpl<MachineInstr *> &DelInstrs);
116   void instr2instrSC(SmallVectorImpl<MachineInstr *> &Instrs,
117                      SmallVectorImpl<const MCSchedClassDesc *> &InstrsSC);
118   std::pair<unsigned, unsigned>
119   getLatenciesForInstrSequences(MachineInstr &MI,
120                                 SmallVectorImpl<MachineInstr *> &InsInstrs,
121                                 SmallVectorImpl<MachineInstr *> &DelInstrs,
122                                 MachineTraceMetrics::Trace BlockTrace);
123 
124   void verifyPatternOrder(MachineBasicBlock *MBB, MachineInstr &Root,
125                           SmallVector<unsigned, 16> &Patterns);
126   CombinerObjective getCombinerObjective(unsigned Pattern);
127 };
128 }
129 
130 char MachineCombiner::ID = 0;
131 char &llvm::MachineCombinerID = MachineCombiner::ID;
132 
133 INITIALIZE_PASS_BEGIN(MachineCombiner, DEBUG_TYPE,
134                       "Machine InstCombiner", false, false)
135 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
136 INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics)
137 INITIALIZE_PASS_END(MachineCombiner, DEBUG_TYPE, "Machine InstCombiner",
138                     false, false)
139 
140 void MachineCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
141   AU.setPreservesCFG();
142   AU.addPreserved<MachineDominatorTree>();
143   AU.addRequired<MachineLoopInfo>();
144   AU.addPreserved<MachineLoopInfo>();
145   AU.addRequired<MachineTraceMetrics>();
146   AU.addPreserved<MachineTraceMetrics>();
147   AU.addRequired<LazyMachineBlockFrequencyInfoPass>();
148   AU.addRequired<ProfileSummaryInfoWrapperPass>();
149   MachineFunctionPass::getAnalysisUsage(AU);
150 }
151 
152 MachineInstr *
153 MachineCombiner::getOperandDef(const MachineOperand &MO) {
154   MachineInstr *DefInstr = nullptr;
155   // We need a virtual register definition.
156   if (MO.isReg() && MO.getReg().isVirtual())
157     DefInstr = MRI->getUniqueVRegDef(MO.getReg());
158   return DefInstr;
159 }
160 
161 /// Return true if MI is unlikely to generate an actual target instruction.
162 bool MachineCombiner::isTransientMI(const MachineInstr *MI) {
163   if (!MI->isCopy())
164     return MI->isTransient();
165 
166   // If MI is a COPY, check if its src and dst registers can be coalesced.
167   Register Dst = MI->getOperand(0).getReg();
168   Register Src = MI->getOperand(1).getReg();
169 
170   if (!MI->isFullCopy()) {
171     // If src RC contains super registers of dst RC, it can also be coalesced.
172     if (MI->getOperand(0).getSubReg() || Src.isPhysical() || Dst.isPhysical())
173       return false;
174 
175     auto SrcSub = MI->getOperand(1).getSubReg();
176     auto SrcRC = MRI->getRegClass(Src);
177     auto DstRC = MRI->getRegClass(Dst);
178     return TRI->getMatchingSuperRegClass(SrcRC, DstRC, SrcSub) != nullptr;
179   }
180 
181   if (Src.isPhysical() && Dst.isPhysical())
182     return Src == Dst;
183 
184   if (Src.isVirtual() && Dst.isVirtual()) {
185     auto SrcRC = MRI->getRegClass(Src);
186     auto DstRC = MRI->getRegClass(Dst);
187     return SrcRC->hasSuperClassEq(DstRC) || SrcRC->hasSubClassEq(DstRC);
188   }
189 
190   if (Src.isVirtual())
191     std::swap(Src, Dst);
192 
193   // Now Src is physical register, Dst is virtual register.
194   auto DstRC = MRI->getRegClass(Dst);
195   return DstRC->contains(Src);
196 }
197 
198 /// Computes depth of instructions in vector \InsInstr.
199 ///
200 /// \param InsInstrs is a vector of machine instructions
201 /// \param InstrIdxForVirtReg is a dense map of virtual register to index
202 /// of defining machine instruction in \p InsInstrs
203 /// \param BlockTrace is a trace of machine instructions
204 ///
205 /// \returns Depth of last instruction in \InsInstrs ("NewRoot")
206 unsigned
207 MachineCombiner::getDepth(SmallVectorImpl<MachineInstr *> &InsInstrs,
208                           DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
209                           MachineTraceMetrics::Trace BlockTrace,
210                           const MachineBasicBlock &MBB) {
211   SmallVector<unsigned, 16> InstrDepth;
212   // For each instruction in the new sequence compute the depth based on the
213   // operands. Use the trace information when possible. For new operands which
214   // are tracked in the InstrIdxForVirtReg map depth is looked up in InstrDepth
215   for (auto *InstrPtr : InsInstrs) { // for each Use
216     unsigned IDepth = 0;
217     for (const MachineOperand &MO : InstrPtr->all_uses()) {
218       // Check for virtual register operand.
219       if (!MO.getReg().isVirtual())
220         continue;
221       unsigned DepthOp = 0;
222       unsigned LatencyOp = 0;
223       DenseMap<unsigned, unsigned>::iterator II =
224           InstrIdxForVirtReg.find(MO.getReg());
225       if (II != InstrIdxForVirtReg.end()) {
226         // Operand is new virtual register not in trace
227         assert(II->second < InstrDepth.size() && "Bad Index");
228         MachineInstr *DefInstr = InsInstrs[II->second];
229         assert(DefInstr &&
230                "There must be a definition for a new virtual register");
231         DepthOp = InstrDepth[II->second];
232         int DefIdx = DefInstr->findRegisterDefOperandIdx(MO.getReg());
233         int UseIdx = InstrPtr->findRegisterUseOperandIdx(MO.getReg());
234         LatencyOp = TSchedModel.computeOperandLatency(DefInstr, DefIdx,
235                                                       InstrPtr, UseIdx);
236       } else {
237         MachineInstr *DefInstr = getOperandDef(MO);
238         if (DefInstr && (TII->getMachineCombinerTraceStrategy() !=
239                              MachineTraceStrategy::TS_Local ||
240                          DefInstr->getParent() == &MBB)) {
241           DepthOp = BlockTrace.getInstrCycles(*DefInstr).Depth;
242           if (!isTransientMI(DefInstr))
243             LatencyOp = TSchedModel.computeOperandLatency(
244                 DefInstr, DefInstr->findRegisterDefOperandIdx(MO.getReg()),
245                 InstrPtr, InstrPtr->findRegisterUseOperandIdx(MO.getReg()));
246         }
247       }
248       IDepth = std::max(IDepth, DepthOp + LatencyOp);
249     }
250     InstrDepth.push_back(IDepth);
251   }
252   unsigned NewRootIdx = InsInstrs.size() - 1;
253   return InstrDepth[NewRootIdx];
254 }
255 
256 /// Computes instruction latency as max of latency of defined operands.
257 ///
258 /// \param Root is a machine instruction that could be replaced by NewRoot.
259 /// It is used to compute a more accurate latency information for NewRoot in
260 /// case there is a dependent instruction in the same trace (\p BlockTrace)
261 /// \param NewRoot is the instruction for which the latency is computed
262 /// \param BlockTrace is a trace of machine instructions
263 ///
264 /// \returns Latency of \p NewRoot
265 unsigned MachineCombiner::getLatency(MachineInstr *Root, MachineInstr *NewRoot,
266                                      MachineTraceMetrics::Trace BlockTrace) {
267   // Check each definition in NewRoot and compute the latency
268   unsigned NewRootLatency = 0;
269 
270   for (const MachineOperand &MO : NewRoot->all_defs()) {
271     // Check for virtual register operand.
272     if (!MO.getReg().isVirtual())
273       continue;
274     // Get the first instruction that uses MO
275     MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(MO.getReg());
276     RI++;
277     if (RI == MRI->reg_end())
278       continue;
279     MachineInstr *UseMO = RI->getParent();
280     unsigned LatencyOp = 0;
281     if (UseMO && BlockTrace.isDepInTrace(*Root, *UseMO)) {
282       LatencyOp = TSchedModel.computeOperandLatency(
283           NewRoot, NewRoot->findRegisterDefOperandIdx(MO.getReg()), UseMO,
284           UseMO->findRegisterUseOperandIdx(MO.getReg()));
285     } else {
286       LatencyOp = TSchedModel.computeInstrLatency(NewRoot);
287     }
288     NewRootLatency = std::max(NewRootLatency, LatencyOp);
289   }
290   return NewRootLatency;
291 }
292 
293 CombinerObjective MachineCombiner::getCombinerObjective(unsigned Pattern) {
294   // TODO: If C++ ever gets a real enum class, make this part of the
295   // MachineCombinerPattern class.
296   switch (Pattern) {
297   case MachineCombinerPattern::REASSOC_AX_BY:
298   case MachineCombinerPattern::REASSOC_AX_YB:
299   case MachineCombinerPattern::REASSOC_XA_BY:
300   case MachineCombinerPattern::REASSOC_XA_YB:
301     return CombinerObjective::MustReduceDepth;
302   default:
303     return TII->getCombinerObjective(Pattern);
304   }
305 }
306 
307 /// Estimate the latency of the new and original instruction sequence by summing
308 /// up the latencies of the inserted and deleted instructions. This assumes
309 /// that the inserted and deleted instructions are dependent instruction chains,
310 /// which might not hold in all cases.
311 std::pair<unsigned, unsigned> MachineCombiner::getLatenciesForInstrSequences(
312     MachineInstr &MI, SmallVectorImpl<MachineInstr *> &InsInstrs,
313     SmallVectorImpl<MachineInstr *> &DelInstrs,
314     MachineTraceMetrics::Trace BlockTrace) {
315   assert(!InsInstrs.empty() && "Only support sequences that insert instrs.");
316   unsigned NewRootLatency = 0;
317   // NewRoot is the last instruction in the \p InsInstrs vector.
318   MachineInstr *NewRoot = InsInstrs.back();
319   for (unsigned i = 0; i < InsInstrs.size() - 1; i++)
320     NewRootLatency += TSchedModel.computeInstrLatency(InsInstrs[i]);
321   NewRootLatency += getLatency(&MI, NewRoot, BlockTrace);
322 
323   unsigned RootLatency = 0;
324   for (auto *I : DelInstrs)
325     RootLatency += TSchedModel.computeInstrLatency(I);
326 
327   return {NewRootLatency, RootLatency};
328 }
329 
330 bool MachineCombiner::reduceRegisterPressure(
331     MachineInstr &Root, MachineBasicBlock *MBB,
332     SmallVectorImpl<MachineInstr *> &InsInstrs,
333     SmallVectorImpl<MachineInstr *> &DelInstrs, unsigned Pattern) {
334   // FIXME: for now, we don't do any check for the register pressure patterns.
335   // We treat them as always profitable. But we can do better if we make
336   // RegPressureTracker class be aware of TIE attribute. Then we can get an
337   // accurate compare of register pressure with DelInstrs or InsInstrs.
338   return true;
339 }
340 
341 /// The DAGCombine code sequence ends in MI (Machine Instruction) Root.
342 /// The new code sequence ends in MI NewRoot. A necessary condition for the new
343 /// sequence to replace the old sequence is that it cannot lengthen the critical
344 /// path. The definition of "improve" may be restricted by specifying that the
345 /// new path improves the data dependency chain (MustReduceDepth).
346 bool MachineCombiner::improvesCriticalPathLen(
347     MachineBasicBlock *MBB, MachineInstr *Root,
348     MachineTraceMetrics::Trace BlockTrace,
349     SmallVectorImpl<MachineInstr *> &InsInstrs,
350     SmallVectorImpl<MachineInstr *> &DelInstrs,
351     DenseMap<unsigned, unsigned> &InstrIdxForVirtReg, unsigned Pattern,
352     bool SlackIsAccurate) {
353   // Get depth and latency of NewRoot and Root.
354   unsigned NewRootDepth =
355       getDepth(InsInstrs, InstrIdxForVirtReg, BlockTrace, *MBB);
356   unsigned RootDepth = BlockTrace.getInstrCycles(*Root).Depth;
357 
358   LLVM_DEBUG(dbgs() << "  Dependence data for " << *Root << "\tNewRootDepth: "
359                     << NewRootDepth << "\tRootDepth: " << RootDepth);
360 
361   // For a transform such as reassociation, the cost equation is
362   // conservatively calculated so that we must improve the depth (data
363   // dependency cycles) in the critical path to proceed with the transform.
364   // Being conservative also protects against inaccuracies in the underlying
365   // machine trace metrics and CPU models.
366   if (getCombinerObjective(Pattern) == CombinerObjective::MustReduceDepth) {
367     LLVM_DEBUG(dbgs() << "\tIt MustReduceDepth ");
368     LLVM_DEBUG(NewRootDepth < RootDepth
369                    ? dbgs() << "\t  and it does it\n"
370                    : dbgs() << "\t  but it does NOT do it\n");
371     return NewRootDepth < RootDepth;
372   }
373 
374   // A more flexible cost calculation for the critical path includes the slack
375   // of the original code sequence. This may allow the transform to proceed
376   // even if the instruction depths (data dependency cycles) become worse.
377 
378   // Account for the latency of the inserted and deleted instructions by
379   unsigned NewRootLatency, RootLatency;
380   if (TII->accumulateInstrSeqToRootLatency(*Root)) {
381     std::tie(NewRootLatency, RootLatency) =
382         getLatenciesForInstrSequences(*Root, InsInstrs, DelInstrs, BlockTrace);
383   } else {
384     NewRootLatency = TSchedModel.computeInstrLatency(InsInstrs.back());
385     RootLatency = TSchedModel.computeInstrLatency(Root);
386   }
387 
388   unsigned RootSlack = BlockTrace.getInstrSlack(*Root);
389   unsigned NewCycleCount = NewRootDepth + NewRootLatency;
390   unsigned OldCycleCount =
391       RootDepth + RootLatency + (SlackIsAccurate ? RootSlack : 0);
392   LLVM_DEBUG(dbgs() << "\n\tNewRootLatency: " << NewRootLatency
393                     << "\tRootLatency: " << RootLatency << "\n\tRootSlack: "
394                     << RootSlack << " SlackIsAccurate=" << SlackIsAccurate
395                     << "\n\tNewRootDepth + NewRootLatency = " << NewCycleCount
396                     << "\n\tRootDepth + RootLatency + RootSlack = "
397                     << OldCycleCount;);
398   LLVM_DEBUG(NewCycleCount <= OldCycleCount
399                  ? dbgs() << "\n\t  It IMPROVES PathLen because"
400                  : dbgs() << "\n\t  It DOES NOT improve PathLen because");
401   LLVM_DEBUG(dbgs() << "\n\t\tNewCycleCount = " << NewCycleCount
402                     << ", OldCycleCount = " << OldCycleCount << "\n");
403 
404   return NewCycleCount <= OldCycleCount;
405 }
406 
407 /// helper routine to convert instructions into SC
408 void MachineCombiner::instr2instrSC(
409     SmallVectorImpl<MachineInstr *> &Instrs,
410     SmallVectorImpl<const MCSchedClassDesc *> &InstrsSC) {
411   for (auto *InstrPtr : Instrs) {
412     unsigned Opc = InstrPtr->getOpcode();
413     unsigned Idx = TII->get(Opc).getSchedClass();
414     const MCSchedClassDesc *SC = SchedModel.getSchedClassDesc(Idx);
415     InstrsSC.push_back(SC);
416   }
417 }
418 
419 /// True when the new instructions do not increase resource length
420 bool MachineCombiner::preservesResourceLen(
421     MachineBasicBlock *MBB, MachineTraceMetrics::Trace BlockTrace,
422     SmallVectorImpl<MachineInstr *> &InsInstrs,
423     SmallVectorImpl<MachineInstr *> &DelInstrs) {
424   if (!TSchedModel.hasInstrSchedModel())
425     return true;
426 
427   // Compute current resource length
428 
429   //ArrayRef<const MachineBasicBlock *> MBBarr(MBB);
430   SmallVector <const MachineBasicBlock *, 1> MBBarr;
431   MBBarr.push_back(MBB);
432   unsigned ResLenBeforeCombine = BlockTrace.getResourceLength(MBBarr);
433 
434   // Deal with SC rather than Instructions.
435   SmallVector<const MCSchedClassDesc *, 16> InsInstrsSC;
436   SmallVector<const MCSchedClassDesc *, 16> DelInstrsSC;
437 
438   instr2instrSC(InsInstrs, InsInstrsSC);
439   instr2instrSC(DelInstrs, DelInstrsSC);
440 
441   ArrayRef<const MCSchedClassDesc *> MSCInsArr{InsInstrsSC};
442   ArrayRef<const MCSchedClassDesc *> MSCDelArr{DelInstrsSC};
443 
444   // Compute new resource length.
445   unsigned ResLenAfterCombine =
446       BlockTrace.getResourceLength(MBBarr, MSCInsArr, MSCDelArr);
447 
448   LLVM_DEBUG(dbgs() << "\t\tResource length before replacement: "
449                     << ResLenBeforeCombine
450                     << " and after: " << ResLenAfterCombine << "\n";);
451   LLVM_DEBUG(
452       ResLenAfterCombine <=
453       ResLenBeforeCombine + TII->getExtendResourceLenLimit()
454           ? dbgs() << "\t\t  As result it IMPROVES/PRESERVES Resource Length\n"
455           : dbgs() << "\t\t  As result it DOES NOT improve/preserve Resource "
456                       "Length\n");
457 
458   return ResLenAfterCombine <=
459          ResLenBeforeCombine + TII->getExtendResourceLenLimit();
460 }
461 
462 /// Inserts InsInstrs and deletes DelInstrs. Incrementally updates instruction
463 /// depths if requested.
464 ///
465 /// \param MBB basic block to insert instructions in
466 /// \param MI current machine instruction
467 /// \param InsInstrs new instructions to insert in \p MBB
468 /// \param DelInstrs instruction to delete from \p MBB
469 /// \param TraceEnsemble is a pointer to the machine trace information
470 /// \param RegUnits set of live registers, needed to compute instruction depths
471 /// \param TII is target instruction info, used to call target hook
472 /// \param Pattern is used to call target hook finalizeInsInstrs
473 /// \param IncrementalUpdate if true, compute instruction depths incrementally,
474 ///                          otherwise invalidate the trace
475 static void
476 insertDeleteInstructions(MachineBasicBlock *MBB, MachineInstr &MI,
477                          SmallVectorImpl<MachineInstr *> &InsInstrs,
478                          SmallVectorImpl<MachineInstr *> &DelInstrs,
479                          MachineTraceMetrics::Ensemble *TraceEnsemble,
480                          SparseSet<LiveRegUnit> &RegUnits,
481                          const TargetInstrInfo *TII, unsigned Pattern,
482                          bool IncrementalUpdate) {
483   // If we want to fix up some placeholder for some target, do it now.
484   // We need this because in genAlternativeCodeSequence, we have not decided the
485   // better pattern InsInstrs or DelInstrs, so we don't want generate some
486   // sideeffect to the function. For example we need to delay the constant pool
487   // entry creation here after InsInstrs is selected as better pattern.
488   // Otherwise the constant pool entry created for InsInstrs will not be deleted
489   // even if InsInstrs is not the better pattern.
490   TII->finalizeInsInstrs(MI, Pattern, InsInstrs);
491 
492   for (auto *InstrPtr : InsInstrs)
493     MBB->insert((MachineBasicBlock::iterator)&MI, InstrPtr);
494 
495   for (auto *InstrPtr : DelInstrs) {
496     InstrPtr->eraseFromParent();
497     // Erase all LiveRegs defined by the removed instruction
498     for (auto *I = RegUnits.begin(); I != RegUnits.end();) {
499       if (I->MI == InstrPtr)
500         I = RegUnits.erase(I);
501       else
502         I++;
503     }
504   }
505 
506   if (IncrementalUpdate)
507     for (auto *InstrPtr : InsInstrs)
508       TraceEnsemble->updateDepth(MBB, *InstrPtr, RegUnits);
509   else
510     TraceEnsemble->invalidate(MBB);
511 
512   NumInstCombined++;
513 }
514 
515 // Check that the difference between original and new latency is decreasing for
516 // later patterns. This helps to discover sub-optimal pattern orderings.
517 void MachineCombiner::verifyPatternOrder(MachineBasicBlock *MBB,
518                                          MachineInstr &Root,
519                                          SmallVector<unsigned, 16> &Patterns) {
520   long PrevLatencyDiff = std::numeric_limits<long>::max();
521   (void)PrevLatencyDiff; // Variable is used in assert only.
522   for (auto P : Patterns) {
523     SmallVector<MachineInstr *, 16> InsInstrs;
524     SmallVector<MachineInstr *, 16> DelInstrs;
525     DenseMap<unsigned, unsigned> InstrIdxForVirtReg;
526     TII->genAlternativeCodeSequence(Root, P, InsInstrs, DelInstrs,
527                                     InstrIdxForVirtReg);
528     // Found pattern, but did not generate alternative sequence.
529     // This can happen e.g. when an immediate could not be materialized
530     // in a single instruction.
531     if (InsInstrs.empty() || !TSchedModel.hasInstrSchedModelOrItineraries())
532       continue;
533 
534     unsigned NewRootLatency, RootLatency;
535     std::tie(NewRootLatency, RootLatency) = getLatenciesForInstrSequences(
536         Root, InsInstrs, DelInstrs, TraceEnsemble->getTrace(MBB));
537     long CurrentLatencyDiff = ((long)RootLatency) - ((long)NewRootLatency);
538     assert(CurrentLatencyDiff <= PrevLatencyDiff &&
539            "Current pattern is better than previous pattern.");
540     PrevLatencyDiff = CurrentLatencyDiff;
541   }
542 }
543 
544 /// Substitute a slow code sequence with a faster one by
545 /// evaluating instruction combining pattern.
546 /// The prototype of such a pattern is MUl + ADD -> MADD. Performs instruction
547 /// combining based on machine trace metrics. Only combine a sequence of
548 /// instructions  when this neither lengthens the critical path nor increases
549 /// resource pressure. When optimizing for codesize always combine when the new
550 /// sequence is shorter.
551 bool MachineCombiner::combineInstructions(MachineBasicBlock *MBB) {
552   bool Changed = false;
553   LLVM_DEBUG(dbgs() << "Combining MBB " << MBB->getName() << "\n");
554 
555   bool IncrementalUpdate = false;
556   auto BlockIter = MBB->begin();
557   decltype(BlockIter) LastUpdate;
558   // Check if the block is in a loop.
559   const MachineLoop *ML = MLI->getLoopFor(MBB);
560   if (!TraceEnsemble)
561     TraceEnsemble = Traces->getEnsemble(TII->getMachineCombinerTraceStrategy());
562 
563   SparseSet<LiveRegUnit> RegUnits;
564   RegUnits.setUniverse(TRI->getNumRegUnits());
565 
566   bool OptForSize = OptSize || llvm::shouldOptimizeForSize(MBB, PSI, MBFI);
567 
568   bool DoRegPressureReduce =
569       TII->shouldReduceRegisterPressure(MBB, &RegClassInfo);
570 
571   while (BlockIter != MBB->end()) {
572     auto &MI = *BlockIter++;
573     SmallVector<unsigned, 16> Patterns;
574     // The motivating example is:
575     //
576     //     MUL  Other        MUL_op1 MUL_op2  Other
577     //      \    /               \      |    /
578     //      ADD/SUB      =>        MADD/MSUB
579     //      (=Root)                (=NewRoot)
580 
581     // The DAGCombine code always replaced MUL + ADD/SUB by MADD. While this is
582     // usually beneficial for code size it unfortunately can hurt performance
583     // when the ADD is on the critical path, but the MUL is not. With the
584     // substitution the MUL becomes part of the critical path (in form of the
585     // MADD) and can lengthen it on architectures where the MADD latency is
586     // longer than the ADD latency.
587     //
588     // For each instruction we check if it can be the root of a combiner
589     // pattern. Then for each pattern the new code sequence in form of MI is
590     // generated and evaluated. When the efficiency criteria (don't lengthen
591     // critical path, don't use more resources) is met the new sequence gets
592     // hooked up into the basic block before the old sequence is removed.
593     //
594     // The algorithm does not try to evaluate all patterns and pick the best.
595     // This is only an artificial restriction though. In practice there is
596     // mostly one pattern, and getMachineCombinerPatterns() can order patterns
597     // based on an internal cost heuristic. If
598     // machine-combiner-verify-pattern-order is enabled, all patterns are
599     // checked to ensure later patterns do not provide better latency savings.
600 
601     if (!TII->getMachineCombinerPatterns(MI, Patterns, DoRegPressureReduce))
602       continue;
603 
604     if (VerifyPatternOrder)
605       verifyPatternOrder(MBB, MI, Patterns);
606 
607     for (const auto P : Patterns) {
608       SmallVector<MachineInstr *, 16> InsInstrs;
609       SmallVector<MachineInstr *, 16> DelInstrs;
610       DenseMap<unsigned, unsigned> InstrIdxForVirtReg;
611       TII->genAlternativeCodeSequence(MI, P, InsInstrs, DelInstrs,
612                                       InstrIdxForVirtReg);
613       // Found pattern, but did not generate alternative sequence.
614       // This can happen e.g. when an immediate could not be materialized
615       // in a single instruction.
616       if (InsInstrs.empty())
617         continue;
618 
619       LLVM_DEBUG(if (dump_intrs) {
620         dbgs() << "\tFor the Pattern (" << (int)P
621                << ") these instructions could be removed\n";
622         for (auto const *InstrPtr : DelInstrs)
623           InstrPtr->print(dbgs(), /*IsStandalone*/false, /*SkipOpers*/false,
624                           /*SkipDebugLoc*/false, /*AddNewLine*/true, TII);
625         dbgs() << "\tThese instructions could replace the removed ones\n";
626         for (auto const *InstrPtr : InsInstrs)
627           InstrPtr->print(dbgs(), /*IsStandalone*/false, /*SkipOpers*/false,
628                           /*SkipDebugLoc*/false, /*AddNewLine*/true, TII);
629       });
630 
631       if (IncrementalUpdate && LastUpdate != BlockIter) {
632         // Update depths since the last incremental update.
633         TraceEnsemble->updateDepths(LastUpdate, BlockIter, RegUnits);
634         LastUpdate = BlockIter;
635       }
636 
637       if (DoRegPressureReduce &&
638           getCombinerObjective(P) ==
639               CombinerObjective::MustReduceRegisterPressure) {
640         if (MBB->size() > inc_threshold) {
641           // Use incremental depth updates for basic blocks above threshold
642           IncrementalUpdate = true;
643           LastUpdate = BlockIter;
644         }
645         if (reduceRegisterPressure(MI, MBB, InsInstrs, DelInstrs, P)) {
646           // Replace DelInstrs with InsInstrs.
647           insertDeleteInstructions(MBB, MI, InsInstrs, DelInstrs, TraceEnsemble,
648                                    RegUnits, TII, P, IncrementalUpdate);
649           Changed |= true;
650 
651           // Go back to previous instruction as it may have ILP reassociation
652           // opportunity.
653           BlockIter--;
654           break;
655         }
656       }
657 
658       if (ML && TII->isThroughputPattern(P)) {
659         LLVM_DEBUG(dbgs() << "\t Replacing due to throughput pattern in loop\n");
660         insertDeleteInstructions(MBB, MI, InsInstrs, DelInstrs, TraceEnsemble,
661                                  RegUnits, TII, P, IncrementalUpdate);
662         // Eagerly stop after the first pattern fires.
663         Changed = true;
664         break;
665       } else if (OptForSize && InsInstrs.size() < DelInstrs.size()) {
666         LLVM_DEBUG(dbgs() << "\t Replacing due to OptForSize ("
667                           << InsInstrs.size() << " < "
668                           << DelInstrs.size() << ")\n");
669         insertDeleteInstructions(MBB, MI, InsInstrs, DelInstrs, TraceEnsemble,
670                                  RegUnits, TII, P, IncrementalUpdate);
671         // Eagerly stop after the first pattern fires.
672         Changed = true;
673         break;
674       } else {
675         // For big basic blocks, we only compute the full trace the first time
676         // we hit this. We do not invalidate the trace, but instead update the
677         // instruction depths incrementally.
678         // NOTE: Only the instruction depths up to MI are accurate. All other
679         // trace information is not updated.
680         MachineTraceMetrics::Trace BlockTrace = TraceEnsemble->getTrace(MBB);
681         Traces->verifyAnalysis();
682         if (improvesCriticalPathLen(MBB, &MI, BlockTrace, InsInstrs, DelInstrs,
683                                     InstrIdxForVirtReg, P,
684                                     !IncrementalUpdate) &&
685             preservesResourceLen(MBB, BlockTrace, InsInstrs, DelInstrs)) {
686           if (MBB->size() > inc_threshold) {
687             // Use incremental depth updates for basic blocks above treshold
688             IncrementalUpdate = true;
689             LastUpdate = BlockIter;
690           }
691 
692           insertDeleteInstructions(MBB, MI, InsInstrs, DelInstrs, TraceEnsemble,
693                                    RegUnits, TII, P, IncrementalUpdate);
694 
695           // Eagerly stop after the first pattern fires.
696           Changed = true;
697           break;
698         }
699         // Cleanup instructions of the alternative code sequence. There is no
700         // use for them.
701         MachineFunction *MF = MBB->getParent();
702         for (auto *InstrPtr : InsInstrs)
703           MF->deleteMachineInstr(InstrPtr);
704       }
705       InstrIdxForVirtReg.clear();
706     }
707   }
708 
709   if (Changed && IncrementalUpdate)
710     Traces->invalidate(MBB);
711   return Changed;
712 }
713 
714 bool MachineCombiner::runOnMachineFunction(MachineFunction &MF) {
715   STI = &MF.getSubtarget();
716   TII = STI->getInstrInfo();
717   TRI = STI->getRegisterInfo();
718   SchedModel = STI->getSchedModel();
719   TSchedModel.init(STI);
720   MRI = &MF.getRegInfo();
721   MLI = &getAnalysis<MachineLoopInfo>();
722   Traces = &getAnalysis<MachineTraceMetrics>();
723   PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
724   MBFI = (PSI && PSI->hasProfileSummary()) ?
725          &getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI() :
726          nullptr;
727   TraceEnsemble = nullptr;
728   OptSize = MF.getFunction().hasOptSize();
729   RegClassInfo.runOnMachineFunction(MF);
730 
731   LLVM_DEBUG(dbgs() << getPassName() << ": " << MF.getName() << '\n');
732   if (!TII->useMachineCombiner()) {
733     LLVM_DEBUG(
734         dbgs()
735         << "  Skipping pass: Target does not support machine combiner\n");
736     return false;
737   }
738 
739   bool Changed = false;
740 
741   // Try to combine instructions.
742   for (auto &MBB : MF)
743     Changed |= combineInstructions(&MBB);
744 
745   return Changed;
746 }
747