MachineCombiner Pass for selecting faster instruction
[oota-llvm.git] / lib / CodeGen / MachineCombiner.cpp
1 //===---- MachineCombiner.cpp - Instcombining on SSA form machine code ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // The machine combiner pass uses machine trace metrics to ensure the combined
11 // instructions does not lengthen the critical path or the resource depth.
12 //===----------------------------------------------------------------------===//
13 #define DEBUG_TYPE "machine-combiner"
14
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/CodeGen/MachineDominators.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineLoopInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/MachineTraceMetrics.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/TargetSchedule.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Target/TargetSubtargetInfo.h"
32
33 using namespace llvm;
34
35 STATISTIC(NumInstCombined, "Number of machineinst combined");
36
37 namespace {
38 class MachineCombiner : public MachineFunctionPass {
39   const TargetInstrInfo *TII;
40   const TargetRegisterInfo *TRI;
41   const MCSchedModel *SchedModel;
42   MachineRegisterInfo *MRI;
43   MachineTraceMetrics *Traces;
44   MachineTraceMetrics::Ensemble *MinInstr;
45
46   TargetSchedModel TSchedModel;
47
48   /// OptSize - True if optimizing for code size.
49   bool OptSize;
50
51 public:
52   static char ID;
53   MachineCombiner() : MachineFunctionPass(ID) {
54     initializeMachineCombinerPass(*PassRegistry::getPassRegistry());
55   }
56   void getAnalysisUsage(AnalysisUsage &AU) const override;
57   bool runOnMachineFunction(MachineFunction &MF) override;
58   const char *getPassName() const override { return "Machine InstCombiner"; }
59
60 private:
61   bool doSubstitute(unsigned NewSize, unsigned OldSize);
62   bool combineInstructions(MachineBasicBlock *);
63   MachineInstr *getOperandDef(const MachineOperand &MO);
64   unsigned getDepth(SmallVectorImpl<MachineInstr *> &InsInstrs,
65                     DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
66                     MachineTraceMetrics::Trace BlockTrace);
67   unsigned getLatency(MachineInstr *Root, MachineInstr *NewRoot,
68                       MachineTraceMetrics::Trace BlockTrace);
69   bool
70   preservesCriticalPathLen(MachineBasicBlock *MBB, MachineInstr *Root,
71                            MachineTraceMetrics::Trace BlockTrace,
72                            SmallVectorImpl<MachineInstr *> &InsInstrs,
73                            DenseMap<unsigned, unsigned> &InstrIdxForVirtReg);
74   bool preservesResourceLen(MachineBasicBlock *MBB,
75                             MachineTraceMetrics::Trace BlockTrace,
76                             SmallVectorImpl<MachineInstr *> &InsInstrs,
77                             SmallVectorImpl<MachineInstr *> &DelInstrs);
78   void instr2instrSC(SmallVectorImpl<MachineInstr *> &Instrs,
79                      SmallVectorImpl<const MCSchedClassDesc *> &InstrsSC);
80 };
81 }
82
83 char MachineCombiner::ID = 0;
84 char &llvm::MachineCombinerID = MachineCombiner::ID;
85
86 INITIALIZE_PASS_BEGIN(MachineCombiner, "machine-combiner",
87                       "Machine InstCombiner", false, false)
88 INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics)
89 INITIALIZE_PASS_END(MachineCombiner, "machine-combiner", "Machine InstCombiner",
90                     false, false)
91
92 void MachineCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
93   AU.setPreservesCFG();
94   AU.addPreserved<MachineDominatorTree>();
95   AU.addPreserved<MachineLoopInfo>();
96   AU.addRequired<MachineTraceMetrics>();
97   AU.addPreserved<MachineTraceMetrics>();
98   MachineFunctionPass::getAnalysisUsage(AU);
99 }
100
101 MachineInstr *MachineCombiner::getOperandDef(const MachineOperand &MO) {
102   MachineInstr *DefInstr = nullptr;
103   // We need a virtual register definition.
104   if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
105     DefInstr = MRI->getUniqueVRegDef(MO.getReg());
106   // PHI's have no depth etc.
107   if (DefInstr && DefInstr->isPHI())
108     DefInstr = nullptr;
109   return DefInstr;
110 }
111
112 /// getDepth - Computes depth of instructions in vector \InsInstr.
113 ///
114 /// \param InsInstrs is a vector of machine instructions
115 /// \param InstrIdxForVirtReg is a dense map of virtual register to index
116 /// of defining machine instruction in \p InsInstrs
117 /// \param BlockTrace is a trace of machine instructions
118 ///
119 /// \returns Depth of last instruction in \InsInstrs ("NewRoot")
120 unsigned
121 MachineCombiner::getDepth(SmallVectorImpl<MachineInstr *> &InsInstrs,
122                           DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
123                           MachineTraceMetrics::Trace BlockTrace) {
124
125   SmallVector<unsigned, 16> InstrDepth;
126   assert(TSchedModel.hasInstrSchedModel() && "Missing machine model\n");
127
128   // Foreach instruction in in the new sequence compute the depth based on the
129   // operands. Use the trace information when possible. For new operands which
130   // are tracked in the InstrIdxForVirtReg map depth is looked up in InstrDepth
131   for (auto *InstrPtr : InsInstrs) { // for each Use
132     unsigned IDepth = 0;
133     DEBUG(dbgs() << "NEW INSTR "; InstrPtr->dump(); dbgs() << "\n";);
134     for (unsigned i = 0, e = InstrPtr->getNumOperands(); i != e; ++i) {
135       const MachineOperand &MO = InstrPtr->getOperand(i);
136       // Check for virtual register operand.
137       if (!(MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())))
138         continue;
139       if (!MO.isUse())
140         continue;
141       unsigned DepthOp = 0;
142       unsigned LatencyOp = 0;
143       DenseMap<unsigned, unsigned>::iterator II =
144           InstrIdxForVirtReg.find(MO.getReg());
145       if (II != InstrIdxForVirtReg.end()) {
146         // Operand is new virtual register not in trace
147         assert(II->second >= 0 && II->second < InstrDepth.size() &&
148                "Bad Index");
149         MachineInstr *DefInstr = InsInstrs[II->second];
150         assert(DefInstr &&
151                "There must be a definition for a new virtual register");
152         DepthOp = InstrDepth[II->second];
153         LatencyOp = TSchedModel.computeOperandLatency(
154             DefInstr, DefInstr->findRegisterDefOperandIdx(MO.getReg()),
155             InstrPtr, InstrPtr->findRegisterUseOperandIdx(MO.getReg()));
156       } else {
157         MachineInstr *DefInstr = getOperandDef(MO);
158         if (DefInstr) {
159           DepthOp = BlockTrace.getInstrCycles(DefInstr).Depth;
160           LatencyOp = TSchedModel.computeOperandLatency(
161               DefInstr, DefInstr->findRegisterDefOperandIdx(MO.getReg()),
162               InstrPtr, InstrPtr->findRegisterUseOperandIdx(MO.getReg()));
163         }
164       }
165       IDepth = std::max(IDepth, DepthOp + LatencyOp);
166     }
167     InstrDepth.push_back(IDepth);
168   }
169   unsigned NewRootIdx = InsInstrs.size() - 1;
170   return InstrDepth[NewRootIdx];
171 }
172
173 /// getLatency - Computes instruction latency as max of latency of defined
174 /// operands
175 ///
176 /// \param Root is a machine instruction that could be replaced by NewRoot.
177 /// It is used to compute a more accurate latency information for NewRoot in
178 /// case there is a dependent instruction in the same trace (\p BlockTrace)
179 /// \param NewRoot is the instruction for which the latency is computed
180 /// \param BlockTrace is a trace of machine instructions
181 ///
182 /// \returns Latency of \p NewRoot
183 unsigned MachineCombiner::getLatency(MachineInstr *Root, MachineInstr *NewRoot,
184                                      MachineTraceMetrics::Trace BlockTrace) {
185
186   assert(TSchedModel.hasInstrSchedModel() && "Missing machine model\n");
187
188   // Check each definition in NewRoot and compute the latency
189   unsigned NewRootLatency = 0;
190
191   for (unsigned i = 0, e = NewRoot->getNumOperands(); i != e; ++i) {
192     const MachineOperand &MO = NewRoot->getOperand(i);
193     // Check for virtual register operand.
194     if (!(MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())))
195       continue;
196     if (!MO.isDef())
197       continue;
198     // Get the first instruction that uses MO
199     MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(MO.getReg());
200     RI++;
201     MachineInstr *UseMO = RI->getParent();
202     unsigned LatencyOp = 0;
203     if (UseMO && BlockTrace.isDepInTrace(Root, UseMO)) {
204       LatencyOp = TSchedModel.computeOperandLatency(
205           NewRoot, NewRoot->findRegisterDefOperandIdx(MO.getReg()), UseMO,
206           UseMO->findRegisterUseOperandIdx(MO.getReg()));
207     } else {
208       LatencyOp = TSchedModel.computeInstrLatency(NewRoot->getOpcode());
209     }
210     NewRootLatency = std::max(NewRootLatency, LatencyOp);
211   }
212   return NewRootLatency;
213 }
214
215 /// preservesCriticalPathlen - True when the new instruction sequence does not
216 /// lengthen the critical path. The DAGCombine code sequence ends in MI
217 /// (Machine Instruction) Root. The new code sequence ends in MI NewRoot. A
218 /// necessary condition for the new sequence to replace the old sequence is that
219 /// is cannot lengthen the critical path. This is decided by the formula
220 /// (NewRootDepth + NewRootLatency) <=  (RootDepth + RootLatency + RootSlack)).
221 /// The slack is the number of cycles Root can be delayed before the critical
222 /// patch becomes longer.
223 bool MachineCombiner::preservesCriticalPathLen(
224     MachineBasicBlock *MBB, MachineInstr *Root,
225     MachineTraceMetrics::Trace BlockTrace,
226     SmallVectorImpl<MachineInstr *> &InsInstrs,
227     DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) {
228
229   assert(TSchedModel.hasInstrSchedModel() && "Missing machine model\n");
230   // NewRoot is the last instruction in the \p InsInstrs vector
231   // Get depth and latency of NewRoot
232   unsigned NewRootIdx = InsInstrs.size() - 1;
233   MachineInstr *NewRoot = InsInstrs[NewRootIdx];
234   unsigned NewRootDepth = getDepth(InsInstrs, InstrIdxForVirtReg, BlockTrace);
235   unsigned NewRootLatency = getLatency(Root, NewRoot, BlockTrace);
236
237   // Get depth, latency and slack of Root
238   unsigned RootDepth = BlockTrace.getInstrCycles(Root).Depth;
239   unsigned RootLatency = TSchedModel.computeInstrLatency(Root);
240   unsigned RootSlack = BlockTrace.getInstrSlack(Root);
241
242   DEBUG(dbgs() << "DEPENDENCE DATA FOR " << Root << "\n";
243         dbgs() << " NewRootDepth: " << NewRootDepth
244                << " NewRootLatency: " << NewRootLatency << "\n";
245         dbgs() << " RootDepth: " << RootDepth << " RootLatency: " << RootLatency
246                << " RootSlack: " << RootSlack << "\n";
247         dbgs() << " NewRootDepth + NewRootLatency "
248                << NewRootDepth + NewRootLatency << "\n";
249         dbgs() << " RootDepth + RootLatency + RootSlack "
250                << RootDepth + RootLatency + RootSlack << "\n";);
251
252   /// True when the new sequence does not lenghten the critical path.
253   return ((NewRootDepth + NewRootLatency) <=
254           (RootDepth + RootLatency + RootSlack));
255 }
256
257 /// helper routine to convert instructions into SC
258 void MachineCombiner::instr2instrSC(
259     SmallVectorImpl<MachineInstr *> &Instrs,
260     SmallVectorImpl<const MCSchedClassDesc *> &InstrsSC) {
261   for (auto *InstrPtr : Instrs) {
262     unsigned Opc = InstrPtr->getOpcode();
263     unsigned Idx = TII->get(Opc).getSchedClass();
264     const MCSchedClassDesc *SC = SchedModel->getSchedClassDesc(Idx);
265     InstrsSC.push_back(SC);
266   }
267 }
268 /// preservesResourceLen - True when the new instructions do not increase
269 /// resource length
270 bool MachineCombiner::preservesResourceLen(
271     MachineBasicBlock *MBB, MachineTraceMetrics::Trace BlockTrace,
272     SmallVectorImpl<MachineInstr *> &InsInstrs,
273     SmallVectorImpl<MachineInstr *> &DelInstrs) {
274
275   // Compute current resource length
276
277   ArrayRef<const MachineBasicBlock *> MBBarr(MBB);
278   unsigned ResLenBeforeCombine = BlockTrace.getResourceLength(MBBarr);
279
280   // Deal with SC rather than Instructions.
281   SmallVector<const MCSchedClassDesc *, 16> InsInstrsSC;
282   SmallVector<const MCSchedClassDesc *, 16> DelInstrsSC;
283
284   instr2instrSC(InsInstrs, InsInstrsSC);
285   instr2instrSC(DelInstrs, DelInstrsSC);
286
287   ArrayRef<const MCSchedClassDesc *> MSCInsArr = makeArrayRef(InsInstrsSC);
288   ArrayRef<const MCSchedClassDesc *> MSCDelArr = makeArrayRef(DelInstrsSC);
289
290   // Compute new resource length
291   unsigned ResLenAfterCombine =
292       BlockTrace.getResourceLength(MBBarr, MSCInsArr, MSCDelArr);
293
294   DEBUG(dbgs() << "RESOURCE DATA: \n";
295         dbgs() << " resource len before: " << ResLenBeforeCombine
296                << " after: " << ResLenAfterCombine << "\n";);
297
298   return ResLenAfterCombine <= ResLenBeforeCombine;
299 }
300
301 /// \returns true when new instruction sequence should be generated
302 /// independent if it lenghtens critical path or not
303 bool MachineCombiner::doSubstitute(unsigned NewSize, unsigned OldSize) {
304   if (OptSize && (NewSize < OldSize))
305     return true;
306   if (!TSchedModel.hasInstrSchedModel())
307     return true;
308   return false;
309 }
310
311 /// combineInstructions - substitute a slow code sequence with a faster one by
312 /// evaluating instruction combining pattern.
313 /// The prototype of such a pattern is MUl + ADD -> MADD. Performs instruction
314 /// combining based on machine trace metrics. Only combine a sequence of
315 /// instructions  when this neither lengthens the critical path nor increases
316 /// resource pressure. When optimizing for codesize always combine when the new
317 /// sequence is shorter.
318 bool MachineCombiner::combineInstructions(MachineBasicBlock *MBB) {
319   bool Changed = false;
320   DEBUG(dbgs() << "Combining MBB " << MBB->getName() << "\n");
321
322   auto BlockIter = MBB->begin();
323
324   while (BlockIter != MBB->end()) {
325     auto &MI = *BlockIter++;
326
327     DEBUG(dbgs() << "INSTR "; MI.dump(); dbgs() << "\n";);
328     SmallVector<MachineCombinerPattern::MC_PATTERN, 16> Pattern;
329     // The motivating example is:
330     //
331     //     MUL  Other        MUL_op1 MUL_op2  Other
332     //      \    /               \      |    /
333     //      ADD/SUB      =>        MADD/MSUB
334     //      (=Root)                (=NewRoot)
335
336     // The DAGCombine code always replaced MUL + ADD/SUB by MADD. While this is
337     // usually beneficial for code size it unfortunately can hurt performance
338     // when the ADD is on the critical path, but the MUL is not. With the
339     // substitution the MUL becomes part of the critical path (in form of the
340     // MADD) and can lengthen it on architectures where the MADD latency is
341     // longer than the ADD latency.
342     //
343     // For each instruction we check if it can be the root of a combiner
344     // pattern. Then for each pattern the new code sequence in form of MI is
345     // generated and evaluated. When the efficiency criteria (don't lengthen
346     // critical path, don't use more resources) is met the new sequence gets
347     // hooked up into the basic block before the old sequence is removed.
348     //
349     // The algorithm does not try to evaluate all patterns and pick the best.
350     // This is only an artificial restriction though. In practice there is
351     // mostly one pattern and hasPattern() can order patterns based on an
352     // internal cost heuristic.
353
354     if (TII->hasPattern(MI, Pattern)) {
355       for (auto P : Pattern) {
356         SmallVector<MachineInstr *, 16> InsInstrs;
357         SmallVector<MachineInstr *, 16> DelInstrs;
358         DenseMap<unsigned, unsigned> InstrIdxForVirtReg;
359         if (!MinInstr)
360           MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
361         MachineTraceMetrics::Trace BlockTrace = MinInstr->getTrace(MBB);
362         Traces->verifyAnalysis();
363         TII->genAlternativeCodeSequence(MI, P, InsInstrs, DelInstrs,
364                                         InstrIdxForVirtReg);
365         // Found pattern, but did not generate alternative sequence.
366         // This can happen e.g. when an immediate could not be materialized
367         // in a single instruction.
368         if (!InsInstrs.size())
369           continue;
370         // Substitute when we optimize for codesize and the new sequence has
371         // fewer instructions OR
372         // the new sequence neither lenghten the critical path nor increases
373         // resource pressure.
374         if (doSubstitute(InsInstrs.size(), DelInstrs.size()) ||
375             (preservesCriticalPathLen(MBB, &MI, BlockTrace, InsInstrs,
376                                       InstrIdxForVirtReg) &&
377              preservesResourceLen(MBB, BlockTrace, InsInstrs, DelInstrs))) {
378           for (auto *InstrPtr : InsInstrs)
379             MBB->insert((MachineBasicBlock::iterator) & MI,
380                         (MachineInstr *)InstrPtr);
381           for (auto *InstrPtr : DelInstrs)
382             InstrPtr->eraseFromParent();
383
384           Changed = true;
385           ++NumInstCombined;
386
387           Traces->invalidate(MBB);
388           Traces->verifyAnalysis();
389           // Eagerly stop after the first pattern fired
390           break;
391         } else {
392           // Cleanup instructions of the alternative code sequence. There is no
393           // use for them.
394           for (auto *InstrPtr : InsInstrs) {
395             MachineFunction *MF = MBB->getParent();
396             MF->DeleteMachineInstr((MachineInstr *)InstrPtr);
397           }
398         }
399         InstrIdxForVirtReg.clear();
400       }
401     }
402   }
403
404   return Changed;
405 }
406
407 bool MachineCombiner::runOnMachineFunction(MachineFunction &MF) {
408   TII = MF.getTarget().getInstrInfo();
409   TRI = MF.getTarget().getRegisterInfo();
410   const TargetSubtargetInfo &STI =
411       MF.getTarget().getSubtarget<TargetSubtargetInfo>();
412   SchedModel = STI.getSchedModel();
413   TSchedModel.init(*SchedModel, &STI, TII);
414   MRI = &MF.getRegInfo();
415   Traces = &getAnalysis<MachineTraceMetrics>();
416   MinInstr = 0;
417
418   OptSize = MF.getFunction()->getAttributes().hasAttribute(
419       AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
420
421   DEBUG(dbgs() << getPassName() << ": " << MF.getName() << '\n');
422   if (!TII->useMachineCombiner()) {
423     DEBUG(dbgs() << "  Skipping pass: Target does not support machine combiner\n");
424     return false;
425   }
426
427   bool Changed = false;
428
429   // Try to combine instructions.
430   for (auto &MBB : MF)
431     Changed |= combineInstructions(&MBB);
432
433   return Changed;
434 }