blob: 0c6efff7bb40ea8ada12b4944895c92235e23301 [file] [log] [blame]
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001//===---- 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
Eric Christopher17ce8a22017-03-15 21:50:46 +000011// instructions do not lengthen the critical path or the resource depth.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000012//===----------------------------------------------------------------------===//
Hans Wennborg083ca9b2015-10-06 23:24:35 +000013
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000014#include "llvm/ADT/DenseMap.h"
Mehdi Aminib550cb12016-04-18 09:17:29 +000015#include "llvm/ADT/Statistic.h"
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000016#include "llvm/CodeGen/MachineDominators.h"
17#include "llvm/CodeGen/MachineFunction.h"
18#include "llvm/CodeGen/MachineFunctionPass.h"
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000019#include "llvm/CodeGen/MachineLoopInfo.h"
20#include "llvm/CodeGen/MachineRegisterInfo.h"
21#include "llvm/CodeGen/MachineTraceMetrics.h"
22#include "llvm/CodeGen/Passes.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000023#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000024#include "llvm/CodeGen/TargetRegisterInfo.h"
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000025#include "llvm/CodeGen/TargetSchedule.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000026#include "llvm/CodeGen/TargetSubtargetInfo.h"
Florian Hahnceb44942017-09-20 11:54:37 +000027#include "llvm/Support/CommandLine.h"
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000028#include "llvm/Support/Debug.h"
29#include "llvm/Support/raw_ostream.h"
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000030
31using namespace llvm;
32
Jakub Kuderski1d2dc682017-07-13 19:30:52 +000033#define DEBUG_TYPE "machine-combiner"
34
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000035STATISTIC(NumInstCombined, "Number of machineinst combined");
36
Florian Hahnceb44942017-09-20 11:54:37 +000037static cl::opt<unsigned>
38inc_threshold("machine-combiner-inc-threshold", cl::Hidden,
39 cl::desc("Incremental depth computation will be used for basic "
40 "blocks with more instructions."), cl::init(500));
41
Andrew V. Tischenkob65b0782018-02-15 07:55:02 +000042static cl::opt<bool> dump_intrs("machine-combiner-dump-subst-intrs", cl::Hidden,
43 cl::desc("Dump all substituted intrs"),
44 cl::init(false));
45
Florian Hahnc68428b2018-01-31 13:54:30 +000046#ifdef EXPENSIVE_CHECKS
47static cl::opt<bool> VerifyPatternOrder(
48 "machine-combiner-verify-pattern-order", cl::Hidden,
49 cl::desc(
50 "Verify that the generated patterns are ordered by increasing latency"),
51 cl::init(true));
52#else
53static cl::opt<bool> VerifyPatternOrder(
54 "machine-combiner-verify-pattern-order", cl::Hidden,
55 cl::desc(
56 "Verify that the generated patterns are ordered by increasing latency"),
57 cl::init(false));
58#endif
59
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000060namespace {
61class MachineCombiner : public MachineFunctionPass {
Andrew V. Tischenkob65b0782018-02-15 07:55:02 +000062 const TargetSubtargetInfo *STI;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000063 const TargetInstrInfo *TII;
64 const TargetRegisterInfo *TRI;
Pete Cooper11759452014-09-02 17:43:54 +000065 MCSchedModel SchedModel;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000066 MachineRegisterInfo *MRI;
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +000067 MachineLoopInfo *MLI; // Current MachineLoopInfo
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000068 MachineTraceMetrics *Traces;
69 MachineTraceMetrics::Ensemble *MinInstr;
70
71 TargetSchedModel TSchedModel;
72
Sanjay Patelb1ca4e42015-01-27 22:26:56 +000073 /// True if optimizing for code size.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000074 bool OptSize;
75
76public:
77 static char ID;
78 MachineCombiner() : MachineFunctionPass(ID) {
79 initializeMachineCombinerPass(*PassRegistry::getPassRegistry());
80 }
81 void getAnalysisUsage(AnalysisUsage &AU) const override;
82 bool runOnMachineFunction(MachineFunction &MF) override;
Mehdi Amini117296c2016-10-01 02:56:57 +000083 StringRef getPassName() const override { return "Machine InstCombiner"; }
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +000084
85private:
86 bool doSubstitute(unsigned NewSize, unsigned OldSize);
87 bool combineInstructions(MachineBasicBlock *);
88 MachineInstr *getOperandDef(const MachineOperand &MO);
89 unsigned getDepth(SmallVectorImpl<MachineInstr *> &InsInstrs,
90 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
91 MachineTraceMetrics::Trace BlockTrace);
92 unsigned getLatency(MachineInstr *Root, MachineInstr *NewRoot,
93 MachineTraceMetrics::Trace BlockTrace);
94 bool
Sanjay Patele79b43a2015-06-23 00:39:40 +000095 improvesCriticalPathLen(MachineBasicBlock *MBB, MachineInstr *Root,
Sanjay Patel766589e2015-11-10 16:48:53 +000096 MachineTraceMetrics::Trace BlockTrace,
97 SmallVectorImpl<MachineInstr *> &InsInstrs,
Sebastian Pope08d9c72016-12-11 19:39:32 +000098 SmallVectorImpl<MachineInstr *> &DelInstrs,
Sanjay Patel766589e2015-11-10 16:48:53 +000099 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
Florian Hahnceb44942017-09-20 11:54:37 +0000100 MachineCombinerPattern Pattern, bool SlackIsAccurate);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000101 bool preservesResourceLen(MachineBasicBlock *MBB,
102 MachineTraceMetrics::Trace BlockTrace,
103 SmallVectorImpl<MachineInstr *> &InsInstrs,
104 SmallVectorImpl<MachineInstr *> &DelInstrs);
105 void instr2instrSC(SmallVectorImpl<MachineInstr *> &Instrs,
106 SmallVectorImpl<const MCSchedClassDesc *> &InstrsSC);
Florian Hahnc68428b2018-01-31 13:54:30 +0000107 std::pair<unsigned, unsigned>
108 getLatenciesForInstrSequences(MachineInstr &MI,
109 SmallVectorImpl<MachineInstr *> &InsInstrs,
110 SmallVectorImpl<MachineInstr *> &DelInstrs,
111 MachineTraceMetrics::Trace BlockTrace);
112
113 void verifyPatternOrder(MachineBasicBlock *MBB, MachineInstr &Root,
114 SmallVector<MachineCombinerPattern, 16> &Patterns);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000115};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000116}
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000117
118char MachineCombiner::ID = 0;
119char &llvm::MachineCombinerID = MachineCombiner::ID;
120
Matthias Braun1527baa2017-05-25 21:26:32 +0000121INITIALIZE_PASS_BEGIN(MachineCombiner, DEBUG_TYPE,
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000122 "Machine InstCombiner", false, false)
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +0000123INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000124INITIALIZE_PASS_DEPENDENCY(MachineTraceMetrics)
Matthias Braun1527baa2017-05-25 21:26:32 +0000125INITIALIZE_PASS_END(MachineCombiner, DEBUG_TYPE, "Machine InstCombiner",
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000126 false, false)
127
128void MachineCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
129 AU.setPreservesCFG();
130 AU.addPreserved<MachineDominatorTree>();
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +0000131 AU.addRequired<MachineLoopInfo>();
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000132 AU.addPreserved<MachineLoopInfo>();
133 AU.addRequired<MachineTraceMetrics>();
134 AU.addPreserved<MachineTraceMetrics>();
135 MachineFunctionPass::getAnalysisUsage(AU);
136}
137
138MachineInstr *MachineCombiner::getOperandDef(const MachineOperand &MO) {
139 MachineInstr *DefInstr = nullptr;
140 // We need a virtual register definition.
141 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
142 DefInstr = MRI->getUniqueVRegDef(MO.getReg());
143 // PHI's have no depth etc.
144 if (DefInstr && DefInstr->isPHI())
145 DefInstr = nullptr;
146 return DefInstr;
147}
148
Sanjay Patelb1ca4e42015-01-27 22:26:56 +0000149/// Computes depth of instructions in vector \InsInstr.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000150///
151/// \param InsInstrs is a vector of machine instructions
152/// \param InstrIdxForVirtReg is a dense map of virtual register to index
153/// of defining machine instruction in \p InsInstrs
154/// \param BlockTrace is a trace of machine instructions
155///
156/// \returns Depth of last instruction in \InsInstrs ("NewRoot")
157unsigned
158MachineCombiner::getDepth(SmallVectorImpl<MachineInstr *> &InsInstrs,
159 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
160 MachineTraceMetrics::Trace BlockTrace) {
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000161 SmallVector<unsigned, 16> InstrDepth;
Hal Finkele0fa8f22015-07-15 08:22:23 +0000162 assert(TSchedModel.hasInstrSchedModelOrItineraries() &&
163 "Missing machine model\n");
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000164
Sanjay Patel6b280772015-01-27 22:16:52 +0000165 // For each instruction in the new sequence compute the depth based on the
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000166 // operands. Use the trace information when possible. For new operands which
167 // are tracked in the InstrIdxForVirtReg map depth is looked up in InstrDepth
168 for (auto *InstrPtr : InsInstrs) { // for each Use
169 unsigned IDepth = 0;
Sanjay Patelf69f4e42015-05-21 17:43:26 +0000170 for (const MachineOperand &MO : InstrPtr->operands()) {
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000171 // Check for virtual register operand.
172 if (!(MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())))
173 continue;
174 if (!MO.isUse())
175 continue;
176 unsigned DepthOp = 0;
177 unsigned LatencyOp = 0;
178 DenseMap<unsigned, unsigned>::iterator II =
179 InstrIdxForVirtReg.find(MO.getReg());
180 if (II != InstrIdxForVirtReg.end()) {
181 // Operand is new virtual register not in trace
Saleem Abdulrasoolbefa2152014-08-03 23:00:38 +0000182 assert(II->second < InstrDepth.size() && "Bad Index");
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000183 MachineInstr *DefInstr = InsInstrs[II->second];
184 assert(DefInstr &&
185 "There must be a definition for a new virtual register");
186 DepthOp = InstrDepth[II->second];
Simon Pilgrim194693e2017-10-30 17:24:40 +0000187 int DefIdx = DefInstr->findRegisterDefOperandIdx(MO.getReg());
188 int UseIdx = InstrPtr->findRegisterUseOperandIdx(MO.getReg());
189 LatencyOp = TSchedModel.computeOperandLatency(DefInstr, DefIdx,
190 InstrPtr, UseIdx);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000191 } else {
192 MachineInstr *DefInstr = getOperandDef(MO);
193 if (DefInstr) {
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000194 DepthOp = BlockTrace.getInstrCycles(*DefInstr).Depth;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000195 LatencyOp = TSchedModel.computeOperandLatency(
196 DefInstr, DefInstr->findRegisterDefOperandIdx(MO.getReg()),
197 InstrPtr, InstrPtr->findRegisterUseOperandIdx(MO.getReg()));
198 }
199 }
200 IDepth = std::max(IDepth, DepthOp + LatencyOp);
201 }
202 InstrDepth.push_back(IDepth);
203 }
204 unsigned NewRootIdx = InsInstrs.size() - 1;
205 return InstrDepth[NewRootIdx];
206}
207
Sanjay Patelb1ca4e42015-01-27 22:26:56 +0000208/// Computes instruction latency as max of latency of defined operands.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000209///
210/// \param Root is a machine instruction that could be replaced by NewRoot.
211/// It is used to compute a more accurate latency information for NewRoot in
212/// case there is a dependent instruction in the same trace (\p BlockTrace)
213/// \param NewRoot is the instruction for which the latency is computed
214/// \param BlockTrace is a trace of machine instructions
215///
216/// \returns Latency of \p NewRoot
217unsigned MachineCombiner::getLatency(MachineInstr *Root, MachineInstr *NewRoot,
218 MachineTraceMetrics::Trace BlockTrace) {
Hal Finkele0fa8f22015-07-15 08:22:23 +0000219 assert(TSchedModel.hasInstrSchedModelOrItineraries() &&
220 "Missing machine model\n");
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000221
222 // Check each definition in NewRoot and compute the latency
223 unsigned NewRootLatency = 0;
224
Sanjay Patelf69f4e42015-05-21 17:43:26 +0000225 for (const MachineOperand &MO : NewRoot->operands()) {
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000226 // Check for virtual register operand.
227 if (!(MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())))
228 continue;
229 if (!MO.isDef())
230 continue;
231 // Get the first instruction that uses MO
232 MachineRegisterInfo::reg_iterator RI = MRI->reg_begin(MO.getReg());
233 RI++;
234 MachineInstr *UseMO = RI->getParent();
235 unsigned LatencyOp = 0;
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000236 if (UseMO && BlockTrace.isDepInTrace(*Root, *UseMO)) {
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000237 LatencyOp = TSchedModel.computeOperandLatency(
238 NewRoot, NewRoot->findRegisterDefOperandIdx(MO.getReg()), UseMO,
239 UseMO->findRegisterUseOperandIdx(MO.getReg()));
240 } else {
Hal Finkel17caf322015-08-05 07:45:28 +0000241 LatencyOp = TSchedModel.computeInstrLatency(NewRoot);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000242 }
243 NewRootLatency = std::max(NewRootLatency, LatencyOp);
244 }
245 return NewRootLatency;
246}
247
Sanjay Patel766589e2015-11-10 16:48:53 +0000248/// The combiner's goal may differ based on which pattern it is attempting
249/// to optimize.
250enum class CombinerObjective {
251 MustReduceDepth, // The data dependency chain must be improved.
252 Default // The critical path must not be lengthened.
253};
254
255static CombinerObjective getCombinerObjective(MachineCombinerPattern P) {
256 // TODO: If C++ ever gets a real enum class, make this part of the
257 // MachineCombinerPattern class.
258 switch (P) {
259 case MachineCombinerPattern::REASSOC_AX_BY:
260 case MachineCombinerPattern::REASSOC_AX_YB:
261 case MachineCombinerPattern::REASSOC_XA_BY:
262 case MachineCombinerPattern::REASSOC_XA_YB:
263 return CombinerObjective::MustReduceDepth;
264 default:
265 return CombinerObjective::Default;
266 }
267}
268
Florian Hahnc68428b2018-01-31 13:54:30 +0000269/// Estimate the latency of the new and original instruction sequence by summing
270/// up the latencies of the inserted and deleted instructions. This assumes
271/// that the inserted and deleted instructions are dependent instruction chains,
272/// which might not hold in all cases.
273std::pair<unsigned, unsigned> MachineCombiner::getLatenciesForInstrSequences(
274 MachineInstr &MI, SmallVectorImpl<MachineInstr *> &InsInstrs,
275 SmallVectorImpl<MachineInstr *> &DelInstrs,
276 MachineTraceMetrics::Trace BlockTrace) {
277 assert(!InsInstrs.empty() && "Only support sequences that insert instrs.");
278 unsigned NewRootLatency = 0;
279 // NewRoot is the last instruction in the \p InsInstrs vector.
280 MachineInstr *NewRoot = InsInstrs.back();
281 for (unsigned i = 0; i < InsInstrs.size() - 1; i++)
282 NewRootLatency += TSchedModel.computeInstrLatency(InsInstrs[i]);
283 NewRootLatency += getLatency(&MI, NewRoot, BlockTrace);
284
285 unsigned RootLatency = 0;
286 for (auto I : DelInstrs)
287 RootLatency += TSchedModel.computeInstrLatency(I);
288
289 return {NewRootLatency, RootLatency};
290}
291
Sanjay Patele79b43a2015-06-23 00:39:40 +0000292/// The DAGCombine code sequence ends in MI (Machine Instruction) Root.
293/// The new code sequence ends in MI NewRoot. A necessary condition for the new
294/// sequence to replace the old sequence is that it cannot lengthen the critical
Sanjay Patel766589e2015-11-10 16:48:53 +0000295/// path. The definition of "improve" may be restricted by specifying that the
296/// new path improves the data dependency chain (MustReduceDepth).
Sanjay Patele79b43a2015-06-23 00:39:40 +0000297bool MachineCombiner::improvesCriticalPathLen(
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000298 MachineBasicBlock *MBB, MachineInstr *Root,
299 MachineTraceMetrics::Trace BlockTrace,
300 SmallVectorImpl<MachineInstr *> &InsInstrs,
Sebastian Pope08d9c72016-12-11 19:39:32 +0000301 SmallVectorImpl<MachineInstr *> &DelInstrs,
Sanjay Patele79b43a2015-06-23 00:39:40 +0000302 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
Florian Hahnceb44942017-09-20 11:54:37 +0000303 MachineCombinerPattern Pattern,
304 bool SlackIsAccurate) {
Hal Finkele0fa8f22015-07-15 08:22:23 +0000305 assert(TSchedModel.hasInstrSchedModelOrItineraries() &&
306 "Missing machine model\n");
Sanjay Patel766589e2015-11-10 16:48:53 +0000307 // Get depth and latency of NewRoot and Root.
308 unsigned NewRootDepth = getDepth(InsInstrs, InstrIdxForVirtReg, BlockTrace);
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000309 unsigned RootDepth = BlockTrace.getInstrCycles(*Root).Depth;
Sanjay Patel766589e2015-11-10 16:48:53 +0000310
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000311 LLVM_DEBUG(dbgs() << " Dependence data for " << *Root << "\tNewRootDepth: "
312 << NewRootDepth << "\tRootDepth: " << RootDepth);
Sanjay Patel766589e2015-11-10 16:48:53 +0000313
314 // For a transform such as reassociation, the cost equation is
315 // conservatively calculated so that we must improve the depth (data
316 // dependency cycles) in the critical path to proceed with the transform.
317 // Being conservative also protects against inaccuracies in the underlying
318 // machine trace metrics and CPU models.
Andrew V. Tischenkob65b0782018-02-15 07:55:02 +0000319 if (getCombinerObjective(Pattern) == CombinerObjective::MustReduceDepth) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000320 LLVM_DEBUG(dbgs() << "\tIt MustReduceDepth ");
321 LLVM_DEBUG(NewRootDepth < RootDepth
322 ? dbgs() << "\t and it does it\n"
323 : dbgs() << "\t but it does NOT do it\n");
Sanjay Patel766589e2015-11-10 16:48:53 +0000324 return NewRootDepth < RootDepth;
Andrew V. Tischenkob65b0782018-02-15 07:55:02 +0000325 }
Sanjay Patel766589e2015-11-10 16:48:53 +0000326
327 // A more flexible cost calculation for the critical path includes the slack
328 // of the original code sequence. This may allow the transform to proceed
329 // even if the instruction depths (data dependency cycles) become worse.
Sebastian Pope08d9c72016-12-11 19:39:32 +0000330
Florian Hahn001c3dd2017-12-06 20:27:33 +0000331 // Account for the latency of the inserted and deleted instructions by
Florian Hahnc68428b2018-01-31 13:54:30 +0000332 unsigned NewRootLatency, RootLatency;
333 std::tie(NewRootLatency, RootLatency) =
334 getLatenciesForInstrSequences(*Root, InsInstrs, DelInstrs, BlockTrace);
Sebastian Pope08d9c72016-12-11 19:39:32 +0000335
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000336 unsigned RootSlack = BlockTrace.getInstrSlack(*Root);
Florian Hahnceb44942017-09-20 11:54:37 +0000337 unsigned NewCycleCount = NewRootDepth + NewRootLatency;
Andrew V. Tischenkob65b0782018-02-15 07:55:02 +0000338 unsigned OldCycleCount =
339 RootDepth + RootLatency + (SlackIsAccurate ? RootSlack : 0);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000340 LLVM_DEBUG(dbgs() << "\n\tNewRootLatency: " << NewRootLatency
341 << "\tRootLatency: " << RootLatency << "\n\tRootSlack: "
342 << RootSlack << " SlackIsAccurate=" << SlackIsAccurate
343 << "\n\tNewRootDepth + NewRootLatency = " << NewCycleCount
344 << "\n\tRootDepth + RootLatency + RootSlack = "
345 << OldCycleCount;);
346 LLVM_DEBUG(NewCycleCount <= OldCycleCount
347 ? dbgs() << "\n\t It IMPROVES PathLen because"
348 : dbgs() << "\n\t It DOES NOT improve PathLen because");
349 LLVM_DEBUG(dbgs() << "\n\t\tNewCycleCount = " << NewCycleCount
350 << ", OldCycleCount = " << OldCycleCount << "\n");
Junmo Park272a2bc2016-02-27 01:10:43 +0000351
Sanjay Patel766589e2015-11-10 16:48:53 +0000352 return NewCycleCount <= OldCycleCount;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000353}
354
355/// helper routine to convert instructions into SC
356void MachineCombiner::instr2instrSC(
357 SmallVectorImpl<MachineInstr *> &Instrs,
358 SmallVectorImpl<const MCSchedClassDesc *> &InstrsSC) {
359 for (auto *InstrPtr : Instrs) {
360 unsigned Opc = InstrPtr->getOpcode();
361 unsigned Idx = TII->get(Opc).getSchedClass();
Pete Cooper11759452014-09-02 17:43:54 +0000362 const MCSchedClassDesc *SC = SchedModel.getSchedClassDesc(Idx);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000363 InstrsSC.push_back(SC);
364 }
365}
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000366
Sanjay Patelb1ca4e42015-01-27 22:26:56 +0000367/// True when the new instructions do not increase resource length
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000368bool MachineCombiner::preservesResourceLen(
369 MachineBasicBlock *MBB, MachineTraceMetrics::Trace BlockTrace,
370 SmallVectorImpl<MachineInstr *> &InsInstrs,
371 SmallVectorImpl<MachineInstr *> &DelInstrs) {
Hal Finkele0fa8f22015-07-15 08:22:23 +0000372 if (!TSchedModel.hasInstrSchedModel())
373 return true;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000374
375 // Compute current resource length
376
Gerolf Hoflehner97c383b2014-08-07 21:40:58 +0000377 //ArrayRef<const MachineBasicBlock *> MBBarr(MBB);
378 SmallVector <const MachineBasicBlock *, 1> MBBarr;
379 MBBarr.push_back(MBB);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000380 unsigned ResLenBeforeCombine = BlockTrace.getResourceLength(MBBarr);
381
382 // Deal with SC rather than Instructions.
383 SmallVector<const MCSchedClassDesc *, 16> InsInstrsSC;
384 SmallVector<const MCSchedClassDesc *, 16> DelInstrsSC;
385
386 instr2instrSC(InsInstrs, InsInstrsSC);
387 instr2instrSC(DelInstrs, DelInstrsSC);
388
389 ArrayRef<const MCSchedClassDesc *> MSCInsArr = makeArrayRef(InsInstrsSC);
390 ArrayRef<const MCSchedClassDesc *> MSCDelArr = makeArrayRef(DelInstrsSC);
391
Sanjay Patelccb8d5c2015-06-10 19:52:58 +0000392 // Compute new resource length.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000393 unsigned ResLenAfterCombine =
394 BlockTrace.getResourceLength(MBBarr, MSCInsArr, MSCDelArr);
395
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000396 LLVM_DEBUG(dbgs() << "\t\tResource length before replacement: "
397 << ResLenBeforeCombine
398 << " and after: " << ResLenAfterCombine << "\n";);
399 LLVM_DEBUG(
Andrew V. Tischenkob65b0782018-02-15 07:55:02 +0000400 ResLenAfterCombine <= ResLenBeforeCombine
401 ? dbgs() << "\t\t As result it IMPROVES/PRESERVES Resource Length\n"
402 : dbgs() << "\t\t As result it DOES NOT improve/preserve Resource "
403 "Length\n");
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000404
405 return ResLenAfterCombine <= ResLenBeforeCombine;
406}
407
408/// \returns true when new instruction sequence should be generated
Sanjay Patel6b280772015-01-27 22:16:52 +0000409/// independent if it lengthens critical path or not
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000410bool MachineCombiner::doSubstitute(unsigned NewSize, unsigned OldSize) {
Reid Kleckner2aeb9302018-03-16 20:11:55 +0000411 if (OptSize && (NewSize < OldSize))
412 return true;
Hal Finkele0fa8f22015-07-15 08:22:23 +0000413 if (!TSchedModel.hasInstrSchedModelOrItineraries())
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000414 return true;
415 return false;
416}
417
Florian Hahnceb44942017-09-20 11:54:37 +0000418/// Inserts InsInstrs and deletes DelInstrs. Incrementally updates instruction
419/// depths if requested.
420///
421/// \param MBB basic block to insert instructions in
422/// \param MI current machine instruction
423/// \param InsInstrs new instructions to insert in \p MBB
424/// \param DelInstrs instruction to delete from \p MBB
425/// \param MinInstr is a pointer to the machine trace information
426/// \param RegUnits set of live registers, needed to compute instruction depths
427/// \param IncrementalUpdate if true, compute instruction depths incrementally,
428/// otherwise invalidate the trace
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000429static void insertDeleteInstructions(MachineBasicBlock *MBB, MachineInstr &MI,
430 SmallVector<MachineInstr *, 16> InsInstrs,
431 SmallVector<MachineInstr *, 16> DelInstrs,
Florian Hahnceb44942017-09-20 11:54:37 +0000432 MachineTraceMetrics::Ensemble *MinInstr,
433 SparseSet<LiveRegUnit> &RegUnits,
434 bool IncrementalUpdate) {
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000435 for (auto *InstrPtr : InsInstrs)
436 MBB->insert((MachineBasicBlock::iterator)&MI, InstrPtr);
Florian Hahnceb44942017-09-20 11:54:37 +0000437
438 for (auto *InstrPtr : DelInstrs) {
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000439 InstrPtr->eraseFromParentAndMarkDBGValuesForRemoval();
Florian Hahnceb44942017-09-20 11:54:37 +0000440 // Erase all LiveRegs defined by the removed instruction
441 for (auto I = RegUnits.begin(); I != RegUnits.end(); ) {
442 if (I->MI == InstrPtr)
443 I = RegUnits.erase(I);
444 else
445 I++;
446 }
447 }
448
449 if (IncrementalUpdate)
450 for (auto *InstrPtr : InsInstrs)
451 MinInstr->updateDepth(MBB, *InstrPtr, RegUnits);
452 else
453 MinInstr->invalidate(MBB);
454
455 NumInstCombined++;
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000456}
457
Florian Hahnc68428b2018-01-31 13:54:30 +0000458// Check that the difference between original and new latency is decreasing for
459// later patterns. This helps to discover sub-optimal pattern orderings.
460void MachineCombiner::verifyPatternOrder(
461 MachineBasicBlock *MBB, MachineInstr &Root,
462 SmallVector<MachineCombinerPattern, 16> &Patterns) {
463 long PrevLatencyDiff = std::numeric_limits<long>::max();
Alexander Ivchenko68050042018-02-06 09:53:02 +0000464 (void)PrevLatencyDiff; // Variable is used in assert only.
Florian Hahnc68428b2018-01-31 13:54:30 +0000465 for (auto P : Patterns) {
466 SmallVector<MachineInstr *, 16> InsInstrs;
467 SmallVector<MachineInstr *, 16> DelInstrs;
468 DenseMap<unsigned, unsigned> InstrIdxForVirtReg;
469 TII->genAlternativeCodeSequence(Root, P, InsInstrs, DelInstrs,
470 InstrIdxForVirtReg);
471 // Found pattern, but did not generate alternative sequence.
472 // This can happen e.g. when an immediate could not be materialized
473 // in a single instruction.
474 if (InsInstrs.empty() || !TSchedModel.hasInstrSchedModelOrItineraries())
475 continue;
476
477 unsigned NewRootLatency, RootLatency;
478 std::tie(NewRootLatency, RootLatency) = getLatenciesForInstrSequences(
479 Root, InsInstrs, DelInstrs, MinInstr->getTrace(MBB));
480 long CurrentLatencyDiff = ((long)RootLatency) - ((long)NewRootLatency);
481 assert(CurrentLatencyDiff <= PrevLatencyDiff &&
482 "Current pattern is better than previous pattern.");
483 PrevLatencyDiff = CurrentLatencyDiff;
484 }
485}
486
Sanjay Patelb1ca4e42015-01-27 22:26:56 +0000487/// Substitute a slow code sequence with a faster one by
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000488/// evaluating instruction combining pattern.
489/// The prototype of such a pattern is MUl + ADD -> MADD. Performs instruction
490/// combining based on machine trace metrics. Only combine a sequence of
491/// instructions when this neither lengthens the critical path nor increases
492/// resource pressure. When optimizing for codesize always combine when the new
493/// sequence is shorter.
494bool MachineCombiner::combineInstructions(MachineBasicBlock *MBB) {
495 bool Changed = false;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000496 LLVM_DEBUG(dbgs() << "Combining MBB " << MBB->getName() << "\n");
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000497
Florian Hahnceb44942017-09-20 11:54:37 +0000498 bool IncrementalUpdate = false;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000499 auto BlockIter = MBB->begin();
Florian Hahne52abba2017-10-11 20:25:58 +0000500 decltype(BlockIter) LastUpdate;
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +0000501 // Check if the block is in a loop.
502 const MachineLoop *ML = MLI->getLoopFor(MBB);
Florian Hahnceb44942017-09-20 11:54:37 +0000503 if (!MinInstr)
504 MinInstr = Traces->getEnsemble(MachineTraceMetrics::TS_MinInstrCount);
505
506 SparseSet<LiveRegUnit> RegUnits;
507 RegUnits.setUniverse(TRI->getNumRegUnits());
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000508
509 while (BlockIter != MBB->end()) {
510 auto &MI = *BlockIter++;
Sanjay Patel387e66e2015-11-05 19:34:57 +0000511 SmallVector<MachineCombinerPattern, 16> Patterns;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000512 // The motivating example is:
513 //
514 // MUL Other MUL_op1 MUL_op2 Other
515 // \ / \ | /
516 // ADD/SUB => MADD/MSUB
517 // (=Root) (=NewRoot)
518
519 // The DAGCombine code always replaced MUL + ADD/SUB by MADD. While this is
520 // usually beneficial for code size it unfortunately can hurt performance
521 // when the ADD is on the critical path, but the MUL is not. With the
522 // substitution the MUL becomes part of the critical path (in form of the
523 // MADD) and can lengthen it on architectures where the MADD latency is
524 // longer than the ADD latency.
525 //
526 // For each instruction we check if it can be the root of a combiner
527 // pattern. Then for each pattern the new code sequence in form of MI is
528 // generated and evaluated. When the efficiency criteria (don't lengthen
529 // critical path, don't use more resources) is met the new sequence gets
530 // hooked up into the basic block before the old sequence is removed.
531 //
532 // The algorithm does not try to evaluate all patterns and pick the best.
533 // This is only an artificial restriction though. In practice there is
Sanjay Patelcfe03932015-06-19 23:21:42 +0000534 // mostly one pattern, and getMachineCombinerPatterns() can order patterns
Florian Hahnc68428b2018-01-31 13:54:30 +0000535 // based on an internal cost heuristic. If
536 // machine-combiner-verify-pattern-order is enabled, all patterns are
537 // checked to ensure later patterns do not provide better latency savings.
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000538
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000539 if (!TII->getMachineCombinerPatterns(MI, Patterns))
540 continue;
541
Florian Hahnc68428b2018-01-31 13:54:30 +0000542 if (VerifyPatternOrder)
543 verifyPatternOrder(MBB, MI, Patterns);
544
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000545 for (auto P : Patterns) {
546 SmallVector<MachineInstr *, 16> InsInstrs;
547 SmallVector<MachineInstr *, 16> DelInstrs;
548 DenseMap<unsigned, unsigned> InstrIdxForVirtReg;
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000549 TII->genAlternativeCodeSequence(MI, P, InsInstrs, DelInstrs,
550 InstrIdxForVirtReg);
551 unsigned NewInstCount = InsInstrs.size();
552 unsigned OldInstCount = DelInstrs.size();
553 // Found pattern, but did not generate alternative sequence.
554 // This can happen e.g. when an immediate could not be materialized
555 // in a single instruction.
556 if (!NewInstCount)
557 continue;
558
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000559 LLVM_DEBUG(if (dump_intrs) {
Andrew V. Tischenkob65b0782018-02-15 07:55:02 +0000560 dbgs() << "\tFor the Pattern (" << (int)P << ") these instructions could be removed\n";
561 for (auto const *InstrPtr : DelInstrs) {
562 dbgs() << "\t\t" << STI->getSchedInfoStr(*InstrPtr) << ": ";
Andrew V. Tischenko08389192018-02-26 09:43:21 +0000563 InstrPtr->print(dbgs(), false, false, false, TII);
Andrew V. Tischenkob65b0782018-02-15 07:55:02 +0000564 }
565 dbgs() << "\tThese instructions could replace the removed ones\n";
566 for (auto const *InstrPtr : InsInstrs) {
567 dbgs() << "\t\t" << STI->getSchedInfoStr(*InstrPtr) << ": ";
Andrew V. Tischenko08389192018-02-26 09:43:21 +0000568 InstrPtr->print(dbgs(), false, false, false, TII);
Andrew V. Tischenkob65b0782018-02-15 07:55:02 +0000569 }
570 });
571
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +0000572 bool SubstituteAlways = false;
573 if (ML && TII->isThroughputPattern(P))
574 SubstituteAlways = true;
575
Florian Hahnceb44942017-09-20 11:54:37 +0000576 if (IncrementalUpdate) {
577 // Update depths since the last incremental update.
578 MinInstr->updateDepths(LastUpdate, BlockIter, RegUnits);
579 LastUpdate = BlockIter;
580 }
581
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000582 // Substitute when we optimize for codesize and the new sequence has
583 // fewer instructions OR
584 // the new sequence neither lengthens the critical path nor increases
585 // resource pressure.
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000586 if (SubstituteAlways || doSubstitute(NewInstCount, OldInstCount)) {
Florian Hahnceb44942017-09-20 11:54:37 +0000587 insertDeleteInstructions(MBB, MI, InsInstrs, DelInstrs, MinInstr,
588 RegUnits, IncrementalUpdate);
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000589 // Eagerly stop after the first pattern fires.
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000590 Changed = true;
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000591 break;
Reid Kleckner2aeb9302018-03-16 20:11:55 +0000592 } else {
Florian Hahnceb44942017-09-20 11:54:37 +0000593 // For big basic blocks, we only compute the full trace the first time
594 // we hit this. We do not invalidate the trace, but instead update the
595 // instruction depths incrementally.
596 // NOTE: Only the instruction depths up to MI are accurate. All other
597 // trace information is not updated.
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000598 MachineTraceMetrics::Trace BlockTrace = MinInstr->getTrace(MBB);
Florian Hahnceb44942017-09-20 11:54:37 +0000599 Traces->verifyAnalysis();
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000600 if (improvesCriticalPathLen(MBB, &MI, BlockTrace, InsInstrs, DelInstrs,
Florian Hahnceb44942017-09-20 11:54:37 +0000601 InstrIdxForVirtReg, P,
602 !IncrementalUpdate) &&
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000603 preservesResourceLen(MBB, BlockTrace, InsInstrs, DelInstrs)) {
Florian Hahne52abba2017-10-11 20:25:58 +0000604 if (MBB->size() > inc_threshold) {
Florian Hahnceb44942017-09-20 11:54:37 +0000605 // Use incremental depth updates for basic blocks above treshold
606 IncrementalUpdate = true;
Florian Hahne52abba2017-10-11 20:25:58 +0000607 LastUpdate = BlockIter;
608 }
Florian Hahnceb44942017-09-20 11:54:37 +0000609
610 insertDeleteInstructions(MBB, MI, InsInstrs, DelInstrs, MinInstr,
611 RegUnits, IncrementalUpdate);
612
Andrew V. Tischenko8da96912017-02-13 09:43:37 +0000613 // Eagerly stop after the first pattern fires.
614 Changed = true;
615 break;
616 }
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000617 // Cleanup instructions of the alternative code sequence. There is no
618 // use for them.
619 MachineFunction *MF = MBB->getParent();
620 for (auto *InstrPtr : InsInstrs)
621 MF->DeleteMachineInstr(InstrPtr);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000622 }
Sanjay Patel33ec5db2015-11-10 20:09:02 +0000623 InstrIdxForVirtReg.clear();
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000624 }
625 }
626
Florian Hahnceb44942017-09-20 11:54:37 +0000627 if (Changed && IncrementalUpdate)
628 Traces->invalidate(MBB);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000629 return Changed;
630}
631
632bool MachineCombiner::runOnMachineFunction(MachineFunction &MF) {
Andrew V. Tischenkob65b0782018-02-15 07:55:02 +0000633 STI = &MF.getSubtarget();
634 TII = STI->getInstrInfo();
635 TRI = STI->getRegisterInfo();
636 SchedModel = STI->getSchedModel();
Sanjay Patel0d7df362018-04-08 19:56:04 +0000637 TSchedModel.init(STI);
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000638 MRI = &MF.getRegInfo();
Gerolf Hoflehner01b3a6182016-04-24 05:14:01 +0000639 MLI = &getAnalysis<MachineLoopInfo>();
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000640 Traces = &getAnalysis<MachineTraceMetrics>();
Hans Wennborg083ca9b2015-10-06 23:24:35 +0000641 MinInstr = nullptr;
Matthias Braunf1caa282017-12-15 22:22:58 +0000642 OptSize = MF.getFunction().optForSize();
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000643
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000644 LLVM_DEBUG(dbgs() << getPassName() << ": " << MF.getName() << '\n');
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000645 if (!TII->useMachineCombiner()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000646 LLVM_DEBUG(
647 dbgs()
648 << " Skipping pass: Target does not support machine combiner\n");
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +0000649 return false;
650 }
651
652 bool Changed = false;
653
654 // Try to combine instructions.
655 for (auto &MBB : MF)
656 Changed |= combineInstructions(&MBB);
657
658 return Changed;
659}