blob: d81c6f8a31e1f379722c90a1a0038ca257a17dce [file] [log] [blame]
Eugene Zelenko49e2fc42017-02-21 22:07:52 +00001//===- lib/CodeGen/MachineTraceMetrics.cpp --------------------------------===//
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00002//
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
Chandler Carruth6bda14b2017-06-06 11:49:48 +000010#include "llvm/CodeGen/MachineTraceMetrics.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000011#include "llvm/ADT/ArrayRef.h"
12#include "llvm/ADT/DenseMap.h"
13#include "llvm/ADT/Optional.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000014#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000015#include "llvm/ADT/SmallPtrSet.h"
16#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/SparseSet.h"
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000018#include "llvm/CodeGen/MachineBasicBlock.h"
19#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000020#include "llvm/CodeGen/MachineFunction.h"
21#include "llvm/CodeGen/MachineInstr.h"
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000022#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000023#include "llvm/CodeGen/MachineOperand.h"
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000025#include "llvm/CodeGen/TargetRegisterInfo.h"
Eugene Zelenko32a40562017-09-11 23:00:48 +000026#include "llvm/CodeGen/TargetSchedule.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000027#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000028#include "llvm/MC/MCRegisterInfo.h"
29#include "llvm/Pass.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/Support/Debug.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000031#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +000032#include "llvm/Support/Format.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Support/raw_ostream.h"
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000034#include <algorithm>
35#include <cassert>
36#include <iterator>
37#include <tuple>
38#include <utility>
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000039
40using namespace llvm;
41
Chandler Carruth1b9dde02014-04-22 02:02:50 +000042#define DEBUG_TYPE "machine-trace-metrics"
43
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000044char MachineTraceMetrics::ID = 0;
Eugene Zelenko32a40562017-09-11 23:00:48 +000045
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000046char &llvm::MachineTraceMetricsID = MachineTraceMetrics::ID;
47
Matthias Braun1527baa2017-05-25 21:26:32 +000048INITIALIZE_PASS_BEGIN(MachineTraceMetrics, DEBUG_TYPE,
49 "Machine Trace Metrics", false, true)
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000050INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
51INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Matthias Braun1527baa2017-05-25 21:26:32 +000052INITIALIZE_PASS_END(MachineTraceMetrics, DEBUG_TYPE,
53 "Machine Trace Metrics", false, true)
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000054
Eugene Zelenko49e2fc42017-02-21 22:07:52 +000055MachineTraceMetrics::MachineTraceMetrics() : MachineFunctionPass(ID) {
Benjamin Kramer502b9e12014-04-12 16:15:53 +000056 std::fill(std::begin(Ensembles), std::end(Ensembles), nullptr);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000057}
58
59void MachineTraceMetrics::getAnalysisUsage(AnalysisUsage &AU) const {
60 AU.setPreservesAll();
61 AU.addRequired<MachineBranchProbabilityInfo>();
62 AU.addRequired<MachineLoopInfo>();
63 MachineFunctionPass::getAnalysisUsage(AU);
64}
65
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +000066bool MachineTraceMetrics::runOnMachineFunction(MachineFunction &Func) {
67 MF = &Func;
Eric Christopher3d4276f2015-01-27 07:31:29 +000068 const TargetSubtargetInfo &ST = MF->getSubtarget();
69 TII = ST.getInstrInfo();
70 TRI = ST.getRegisterInfo();
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +000071 MRI = &MF->getRegInfo();
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000072 Loops = &getAnalysis<MachineLoopInfo>();
Pete Cooper11759452014-09-02 17:43:54 +000073 SchedModel.init(ST.getSchedModel(), &ST, TII);
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +000074 BlockInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +000075 ProcResourceCycles.resize(MF->getNumBlockIDs() *
76 SchedModel.getNumProcResourceKinds());
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000077 return false;
78}
79
80void MachineTraceMetrics::releaseMemory() {
Craig Topperc0196b12014-04-14 00:51:57 +000081 MF = nullptr;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000082 BlockInfo.clear();
83 for (unsigned i = 0; i != TS_NumStrategies; ++i) {
84 delete Ensembles[i];
Craig Topperc0196b12014-04-14 00:51:57 +000085 Ensembles[i] = nullptr;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000086 }
87}
88
89//===----------------------------------------------------------------------===//
90// Fixed block information
91//===----------------------------------------------------------------------===//
92//
93// The number of instructions in a basic block and the CPU resources used by
94// those instructions don't depend on any given trace strategy.
95
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000096/// Compute the resource usage in basic block MBB.
97const MachineTraceMetrics::FixedBlockInfo*
98MachineTraceMetrics::getResources(const MachineBasicBlock *MBB) {
99 assert(MBB && "No basic block");
100 FixedBlockInfo *FBI = &BlockInfo[MBB->getNumber()];
101 if (FBI->hasResources())
102 return FBI;
103
104 // Compute resource usage in the block.
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000105 FBI->HasCalls = false;
106 unsigned InstrCount = 0;
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000107
108 // Add up per-processor resource cycles as well.
109 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
110 SmallVector<unsigned, 32> PRCycles(PRKinds);
111
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000112 for (const auto &MI : *MBB) {
113 if (MI.isTransient())
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000114 continue;
115 ++InstrCount;
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000116 if (MI.isCall())
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000117 FBI->HasCalls = true;
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000118
119 // Count processor resources used.
Jakob Stoklund Olesenaeb69a52013-04-02 22:27:45 +0000120 if (!SchedModel.hasInstrSchedModel())
121 continue;
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000122 const MCSchedClassDesc *SC = SchedModel.resolveSchedClass(&MI);
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000123 if (!SC->isValid())
124 continue;
125
126 for (TargetSchedModel::ProcResIter
127 PI = SchedModel.getWriteProcResBegin(SC),
128 PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
129 assert(PI->ProcResourceIdx < PRKinds && "Bad processor resource kind");
130 PRCycles[PI->ProcResourceIdx] += PI->Cycles;
131 }
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000132 }
133 FBI->InstrCount = InstrCount;
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000134
135 // Scale the resource cycles so they are comparable.
136 unsigned PROffset = MBB->getNumber() * PRKinds;
137 for (unsigned K = 0; K != PRKinds; ++K)
138 ProcResourceCycles[PROffset + K] =
139 PRCycles[K] * SchedModel.getResourceFactor(K);
140
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000141 return FBI;
142}
143
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000144ArrayRef<unsigned>
145MachineTraceMetrics::getProcResourceCycles(unsigned MBBNum) const {
146 assert(BlockInfo[MBBNum].hasResources() &&
147 "getResources() must be called before getProcResourceCycles()");
148 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesenaeb69a52013-04-02 22:27:45 +0000149 assert((MBBNum+1) * PRKinds <= ProcResourceCycles.size());
Craig Toppere1d12942014-08-27 05:25:25 +0000150 return makeArrayRef(ProcResourceCycles.data() + MBBNum * PRKinds, PRKinds);
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000151}
152
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000153//===----------------------------------------------------------------------===//
154// Ensemble utility functions
155//===----------------------------------------------------------------------===//
156
157MachineTraceMetrics::Ensemble::Ensemble(MachineTraceMetrics *ct)
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000158 : MTM(*ct) {
159 BlockInfo.resize(MTM.BlockInfo.size());
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000160 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
161 ProcResourceDepths.resize(MTM.BlockInfo.size() * PRKinds);
162 ProcResourceHeights.resize(MTM.BlockInfo.size() * PRKinds);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000163}
164
165// Virtual destructor serves as an anchor.
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000166MachineTraceMetrics::Ensemble::~Ensemble() = default;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000167
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000168const MachineLoop*
169MachineTraceMetrics::Ensemble::getLoopFor(const MachineBasicBlock *MBB) const {
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000170 return MTM.Loops->getLoopFor(MBB);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000171}
172
173// Update resource-related information in the TraceBlockInfo for MBB.
174// Only update resources related to the trace above MBB.
175void MachineTraceMetrics::Ensemble::
176computeDepthResources(const MachineBasicBlock *MBB) {
177 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000178 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
179 unsigned PROffset = MBB->getNumber() * PRKinds;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000180
181 // Compute resources from trace above. The top block is simple.
182 if (!TBI->Pred) {
183 TBI->InstrDepth = 0;
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +0000184 TBI->Head = MBB->getNumber();
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000185 std::fill(ProcResourceDepths.begin() + PROffset,
186 ProcResourceDepths.begin() + PROffset + PRKinds, 0);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000187 return;
188 }
189
190 // Compute from the block above. A post-order traversal ensures the
191 // predecessor is always computed first.
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000192 unsigned PredNum = TBI->Pred->getNumber();
193 TraceBlockInfo *PredTBI = &BlockInfo[PredNum];
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000194 assert(PredTBI->hasValidDepth() && "Trace above has not been computed yet");
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000195 const FixedBlockInfo *PredFBI = MTM.getResources(TBI->Pred);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000196 TBI->InstrDepth = PredTBI->InstrDepth + PredFBI->InstrCount;
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +0000197 TBI->Head = PredTBI->Head;
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000198
199 // Compute per-resource depths.
200 ArrayRef<unsigned> PredPRDepths = getProcResourceDepths(PredNum);
201 ArrayRef<unsigned> PredPRCycles = MTM.getProcResourceCycles(PredNum);
202 for (unsigned K = 0; K != PRKinds; ++K)
203 ProcResourceDepths[PROffset + K] = PredPRDepths[K] + PredPRCycles[K];
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000204}
205
206// Update resource-related information in the TraceBlockInfo for MBB.
207// Only update resources related to the trace below MBB.
208void MachineTraceMetrics::Ensemble::
209computeHeightResources(const MachineBasicBlock *MBB) {
210 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000211 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
212 unsigned PROffset = MBB->getNumber() * PRKinds;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000213
214 // Compute resources for the current block.
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000215 TBI->InstrHeight = MTM.getResources(MBB)->InstrCount;
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000216 ArrayRef<unsigned> PRCycles = MTM.getProcResourceCycles(MBB->getNumber());
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000217
218 // The trace tail is done.
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +0000219 if (!TBI->Succ) {
220 TBI->Tail = MBB->getNumber();
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000221 std::copy(PRCycles.begin(), PRCycles.end(),
222 ProcResourceHeights.begin() + PROffset);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000223 return;
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +0000224 }
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000225
226 // Compute from the block below. A post-order traversal ensures the
227 // predecessor is always computed first.
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000228 unsigned SuccNum = TBI->Succ->getNumber();
229 TraceBlockInfo *SuccTBI = &BlockInfo[SuccNum];
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000230 assert(SuccTBI->hasValidHeight() && "Trace below has not been computed yet");
231 TBI->InstrHeight += SuccTBI->InstrHeight;
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +0000232 TBI->Tail = SuccTBI->Tail;
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000233
234 // Compute per-resource heights.
235 ArrayRef<unsigned> SuccPRHeights = getProcResourceHeights(SuccNum);
236 for (unsigned K = 0; K != PRKinds; ++K)
237 ProcResourceHeights[PROffset + K] = SuccPRHeights[K] + PRCycles[K];
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000238}
239
240// Check if depth resources for MBB are valid and return the TBI.
241// Return NULL if the resources have been invalidated.
242const MachineTraceMetrics::TraceBlockInfo*
243MachineTraceMetrics::Ensemble::
244getDepthResources(const MachineBasicBlock *MBB) const {
245 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Craig Topperc0196b12014-04-14 00:51:57 +0000246 return TBI->hasValidDepth() ? TBI : nullptr;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000247}
248
249// Check if height resources for MBB are valid and return the TBI.
250// Return NULL if the resources have been invalidated.
251const MachineTraceMetrics::TraceBlockInfo*
252MachineTraceMetrics::Ensemble::
253getHeightResources(const MachineBasicBlock *MBB) const {
254 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Craig Topperc0196b12014-04-14 00:51:57 +0000255 return TBI->hasValidHeight() ? TBI : nullptr;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000256}
257
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000258/// Get an array of processor resource depths for MBB. Indexed by processor
259/// resource kind, this array contains the scaled processor resources consumed
260/// by all blocks preceding MBB in its trace. It does not include instructions
261/// in MBB.
262///
263/// Compare TraceBlockInfo::InstrDepth.
264ArrayRef<unsigned>
265MachineTraceMetrics::Ensemble::
266getProcResourceDepths(unsigned MBBNum) const {
267 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesenaeb69a52013-04-02 22:27:45 +0000268 assert((MBBNum+1) * PRKinds <= ProcResourceDepths.size());
Craig Toppere1d12942014-08-27 05:25:25 +0000269 return makeArrayRef(ProcResourceDepths.data() + MBBNum * PRKinds, PRKinds);
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000270}
271
272/// Get an array of processor resource heights for MBB. Indexed by processor
273/// resource kind, this array contains the scaled processor resources consumed
274/// by this block and all blocks following it in its trace.
275///
276/// Compare TraceBlockInfo::InstrHeight.
277ArrayRef<unsigned>
278MachineTraceMetrics::Ensemble::
279getProcResourceHeights(unsigned MBBNum) const {
280 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesenaeb69a52013-04-02 22:27:45 +0000281 assert((MBBNum+1) * PRKinds <= ProcResourceHeights.size());
Craig Toppere1d12942014-08-27 05:25:25 +0000282 return makeArrayRef(ProcResourceHeights.data() + MBBNum * PRKinds, PRKinds);
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000283}
284
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000285//===----------------------------------------------------------------------===//
286// Trace Selection Strategies
287//===----------------------------------------------------------------------===//
288//
289// A trace selection strategy is implemented as a sub-class of Ensemble. The
290// trace through a block B is computed by two DFS traversals of the CFG
291// starting from B. One upwards, and one downwards. During the upwards DFS,
292// pickTracePred() is called on the post-ordered blocks. During the downwards
293// DFS, pickTraceSucc() is called in a post-order.
294//
295
Jakob Stoklund Olesenc14cf572012-07-30 23:15:10 +0000296// We never allow traces that leave loops, but we do allow traces to enter
297// nested loops. We also never allow traces to contain back-edges.
298//
299// This means that a loop header can never appear above the center block of a
300// trace, except as the trace head. Below the center block, loop exiting edges
301// are banned.
302//
303// Return true if an edge from the From loop to the To loop is leaving a loop.
304// Either of To and From can be null.
305static bool isExitingLoop(const MachineLoop *From, const MachineLoop *To) {
306 return From && !From->contains(To);
307}
308
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000309// MinInstrCountEnsemble - Pick the trace that executes the least number of
310// instructions.
311namespace {
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000312
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000313class MinInstrCountEnsemble : public MachineTraceMetrics::Ensemble {
Craig Topper4584cd52014-03-07 09:26:03 +0000314 const char *getName() const override { return "MinInstr"; }
315 const MachineBasicBlock *pickTracePred(const MachineBasicBlock*) override;
316 const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*) override;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000317
318public:
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000319 MinInstrCountEnsemble(MachineTraceMetrics *mtm)
320 : MachineTraceMetrics::Ensemble(mtm) {}
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000321};
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000322
323} // end anonymous namespace
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000324
325// Select the preferred predecessor for MBB.
326const MachineBasicBlock*
327MinInstrCountEnsemble::pickTracePred(const MachineBasicBlock *MBB) {
328 if (MBB->pred_empty())
Craig Topperc0196b12014-04-14 00:51:57 +0000329 return nullptr;
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000330 const MachineLoop *CurLoop = getLoopFor(MBB);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000331 // Don't leave loops, and never follow back-edges.
332 if (CurLoop && MBB == CurLoop->getHeader())
Craig Topperc0196b12014-04-14 00:51:57 +0000333 return nullptr;
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000334 unsigned CurCount = MTM.getResources(MBB)->InstrCount;
Craig Topperc0196b12014-04-14 00:51:57 +0000335 const MachineBasicBlock *Best = nullptr;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000336 unsigned BestDepth = 0;
Sanjay Patel99b3aa32015-05-21 17:22:45 +0000337 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
Jakob Stoklund Olesenf308c122012-07-30 21:10:27 +0000338 const MachineTraceMetrics::TraceBlockInfo *PredTBI =
339 getDepthResources(Pred);
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000340 // Ignore cycles that aren't natural loops.
341 if (!PredTBI)
342 continue;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000343 // Pick the predecessor that would give this block the smallest InstrDepth.
344 unsigned Depth = PredTBI->InstrDepth + CurCount;
Richard Trieu7a083812016-02-18 22:09:30 +0000345 if (!Best || Depth < BestDepth) {
346 Best = Pred;
347 BestDepth = Depth;
348 }
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000349 }
350 return Best;
351}
352
353// Select the preferred successor for MBB.
354const MachineBasicBlock*
355MinInstrCountEnsemble::pickTraceSucc(const MachineBasicBlock *MBB) {
356 if (MBB->pred_empty())
Craig Topperc0196b12014-04-14 00:51:57 +0000357 return nullptr;
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000358 const MachineLoop *CurLoop = getLoopFor(MBB);
Craig Topperc0196b12014-04-14 00:51:57 +0000359 const MachineBasicBlock *Best = nullptr;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000360 unsigned BestHeight = 0;
Sanjay Patel99b3aa32015-05-21 17:22:45 +0000361 for (const MachineBasicBlock *Succ : MBB->successors()) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000362 // Don't consider back-edges.
363 if (CurLoop && Succ == CurLoop->getHeader())
364 continue;
Jakob Stoklund Olesenc14cf572012-07-30 23:15:10 +0000365 // Don't consider successors exiting CurLoop.
366 if (isExitingLoop(CurLoop, getLoopFor(Succ)))
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000367 continue;
Jakob Stoklund Olesenf308c122012-07-30 21:10:27 +0000368 const MachineTraceMetrics::TraceBlockInfo *SuccTBI =
369 getHeightResources(Succ);
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000370 // Ignore cycles that aren't natural loops.
371 if (!SuccTBI)
372 continue;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000373 // Pick the successor that would give this block the smallest InstrHeight.
374 unsigned Height = SuccTBI->InstrHeight;
Richard Trieu7a083812016-02-18 22:09:30 +0000375 if (!Best || Height < BestHeight) {
376 Best = Succ;
377 BestHeight = Height;
378 }
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000379 }
380 return Best;
381}
382
383// Get an Ensemble sub-class for the requested trace strategy.
384MachineTraceMetrics::Ensemble *
385MachineTraceMetrics::getEnsemble(MachineTraceMetrics::Strategy strategy) {
386 assert(strategy < TS_NumStrategies && "Invalid trace strategy enum");
387 Ensemble *&E = Ensembles[strategy];
388 if (E)
389 return E;
390
391 // Allocate new Ensemble on demand.
392 switch (strategy) {
393 case TS_MinInstrCount: return (E = new MinInstrCountEnsemble(this));
394 default: llvm_unreachable("Invalid trace strategy enum");
395 }
396}
397
398void MachineTraceMetrics::invalidate(const MachineBasicBlock *MBB) {
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000399 DEBUG(dbgs() << "Invalidate traces through " << printMBBReference(*MBB)
400 << '\n');
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000401 BlockInfo[MBB->getNumber()].invalidate();
402 for (unsigned i = 0; i != TS_NumStrategies; ++i)
403 if (Ensembles[i])
404 Ensembles[i]->invalidate(MBB);
405}
406
Jakob Stoklund Olesena12a7d52012-07-30 20:57:50 +0000407void MachineTraceMetrics::verifyAnalysis() const {
Jakob Stoklund Olesen68c2cd02012-07-30 23:15:12 +0000408 if (!MF)
409 return;
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000410#ifndef NDEBUG
411 assert(BlockInfo.size() == MF->getNumBlockIDs() && "Outdated BlockInfo size");
412 for (unsigned i = 0; i != TS_NumStrategies; ++i)
413 if (Ensembles[i])
414 Ensembles[i]->verify();
415#endif
416}
417
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000418//===----------------------------------------------------------------------===//
419// Trace building
420//===----------------------------------------------------------------------===//
421//
422// Traces are built by two CFG traversals. To avoid recomputing too much, use a
423// set abstraction that confines the search to the current loop, and doesn't
424// revisit blocks.
425
426namespace {
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000427
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000428struct LoopBounds {
429 MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> Blocks;
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000430 SmallPtrSet<const MachineBasicBlock*, 8> Visited;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000431 const MachineLoopInfo *Loops;
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000432 bool Downward = false;
433
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000434 LoopBounds(MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> blocks,
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000435 const MachineLoopInfo *loops) : Blocks(blocks), Loops(loops) {}
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000436};
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000437
438} // end anonymous namespace
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000439
440// Specialize po_iterator_storage in order to prune the post-order traversal so
441// it is limited to the current loop and doesn't traverse the loop back edges.
442namespace llvm {
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000443
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000444template<>
445class po_iterator_storage<LoopBounds, true> {
446 LoopBounds &LB;
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000447
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000448public:
449 po_iterator_storage(LoopBounds &lb) : LB(lb) {}
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000450
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000451 void finishPostorder(const MachineBasicBlock*) {}
452
Tim Shene0793db2016-08-15 21:52:54 +0000453 bool insertEdge(Optional<const MachineBasicBlock *> From,
454 const MachineBasicBlock *To) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000455 // Skip already visited To blocks.
456 MachineTraceMetrics::TraceBlockInfo &TBI = LB.Blocks[To->getNumber()];
457 if (LB.Downward ? TBI.hasValidHeight() : TBI.hasValidDepth())
458 return false;
Jakob Stoklund Olesenc14cf572012-07-30 23:15:10 +0000459 // From is null once when To is the trace center block.
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000460 if (From) {
Tim Shene0793db2016-08-15 21:52:54 +0000461 if (const MachineLoop *FromLoop = LB.Loops->getLoopFor(*From)) {
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000462 // Don't follow backedges, don't leave FromLoop when going upwards.
Tim Shene0793db2016-08-15 21:52:54 +0000463 if ((LB.Downward ? To : *From) == FromLoop->getHeader())
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000464 return false;
465 // Don't leave FromLoop.
466 if (isExitingLoop(FromLoop, LB.Loops->getLoopFor(To)))
467 return false;
468 }
469 }
470 // To is a new block. Mark the block as visited in case the CFG has cycles
471 // that MachineLoopInfo didn't recognize as a natural loop.
David Blaikie70573dc2014-11-19 07:49:26 +0000472 return LB.Visited.insert(To).second;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000473 }
474};
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000475
476} // end namespace llvm
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000477
478/// Compute the trace through MBB.
479void MachineTraceMetrics::Ensemble::computeTrace(const MachineBasicBlock *MBB) {
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000480 DEBUG(dbgs() << "Computing " << getName() << " trace through "
481 << printMBBReference(*MBB) << '\n');
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000482 // Set up loop bounds for the backwards post-order traversal.
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000483 LoopBounds Bounds(BlockInfo, MTM.Loops);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000484
485 // Run an upwards post-order search for the trace start.
486 Bounds.Downward = false;
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000487 Bounds.Visited.clear();
Daniel Berlin25db4f42015-04-15 17:41:42 +0000488 for (auto I : inverse_post_order_ext(MBB, Bounds)) {
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000489 DEBUG(dbgs() << " pred for " << printMBBReference(*I) << ": ");
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000490 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
491 // All the predecessors have been visited, pick the preferred one.
Daniel Berlin25db4f42015-04-15 17:41:42 +0000492 TBI.Pred = pickTracePred(I);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000493 DEBUG({
494 if (TBI.Pred)
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000495 dbgs() << printMBBReference(*TBI.Pred) << '\n';
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000496 else
497 dbgs() << "null\n";
498 });
499 // The trace leading to I is now known, compute the depth resources.
Daniel Berlin25db4f42015-04-15 17:41:42 +0000500 computeDepthResources(I);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000501 }
502
503 // Run a downwards post-order search for the trace end.
504 Bounds.Downward = true;
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000505 Bounds.Visited.clear();
Daniel Berlin25db4f42015-04-15 17:41:42 +0000506 for (auto I : post_order_ext(MBB, Bounds)) {
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000507 DEBUG(dbgs() << " succ for " << printMBBReference(*I) << ": ");
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000508 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
509 // All the successors have been visited, pick the preferred one.
Daniel Berlin25db4f42015-04-15 17:41:42 +0000510 TBI.Succ = pickTraceSucc(I);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000511 DEBUG({
Jakob Stoklund Olesenc14cf572012-07-30 23:15:10 +0000512 if (TBI.Succ)
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000513 dbgs() << printMBBReference(*TBI.Succ) << '\n';
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000514 else
515 dbgs() << "null\n";
516 });
517 // The trace leaving I is now known, compute the height resources.
Daniel Berlin25db4f42015-04-15 17:41:42 +0000518 computeHeightResources(I);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000519 }
520}
521
522/// Invalidate traces through BadMBB.
523void
524MachineTraceMetrics::Ensemble::invalidate(const MachineBasicBlock *BadMBB) {
525 SmallVector<const MachineBasicBlock*, 16> WorkList;
526 TraceBlockInfo &BadTBI = BlockInfo[BadMBB->getNumber()];
527
528 // Invalidate height resources of blocks above MBB.
529 if (BadTBI.hasValidHeight()) {
530 BadTBI.invalidateHeight();
531 WorkList.push_back(BadMBB);
532 do {
533 const MachineBasicBlock *MBB = WorkList.pop_back_val();
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000534 DEBUG(dbgs() << "Invalidate " << printMBBReference(*MBB) << ' '
535 << getName() << " height.\n");
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000536 // Find any MBB predecessors that have MBB as their preferred successor.
537 // They are the only ones that need to be invalidated.
Sanjay Pateld2b71442015-07-06 16:27:35 +0000538 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
539 TraceBlockInfo &TBI = BlockInfo[Pred->getNumber()];
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000540 if (!TBI.hasValidHeight())
541 continue;
542 if (TBI.Succ == MBB) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000543 TBI.invalidateHeight();
Sanjay Pateld2b71442015-07-06 16:27:35 +0000544 WorkList.push_back(Pred);
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000545 continue;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000546 }
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000547 // Verify that TBI.Succ is actually a *I successor.
Sanjay Pateld2b71442015-07-06 16:27:35 +0000548 assert((!TBI.Succ || Pred->isSuccessor(TBI.Succ)) && "CFG changed");
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000549 }
550 } while (!WorkList.empty());
551 }
552
553 // Invalidate depth resources of blocks below MBB.
554 if (BadTBI.hasValidDepth()) {
555 BadTBI.invalidateDepth();
556 WorkList.push_back(BadMBB);
557 do {
558 const MachineBasicBlock *MBB = WorkList.pop_back_val();
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000559 DEBUG(dbgs() << "Invalidate " << printMBBReference(*MBB) << ' '
560 << getName() << " depth.\n");
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000561 // Find any MBB successors that have MBB as their preferred predecessor.
562 // They are the only ones that need to be invalidated.
Sanjay Pateld2b71442015-07-06 16:27:35 +0000563 for (const MachineBasicBlock *Succ : MBB->successors()) {
564 TraceBlockInfo &TBI = BlockInfo[Succ->getNumber()];
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000565 if (!TBI.hasValidDepth())
566 continue;
567 if (TBI.Pred == MBB) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000568 TBI.invalidateDepth();
Sanjay Pateld2b71442015-07-06 16:27:35 +0000569 WorkList.push_back(Succ);
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000570 continue;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000571 }
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000572 // Verify that TBI.Pred is actually a *I predecessor.
Sanjay Pateld2b71442015-07-06 16:27:35 +0000573 assert((!TBI.Pred || Succ->isPredecessor(TBI.Pred)) && "CFG changed");
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000574 }
575 } while (!WorkList.empty());
576 }
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000577
578 // Clear any per-instruction data. We only have to do this for BadMBB itself
579 // because the instructions in that block may change. Other blocks may be
580 // invalidated, but their instructions will stay the same, so there is no
581 // need to erase the Cycle entries. They will be overwritten when we
582 // recompute.
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000583 for (const auto &I : *BadMBB)
584 Cycles.erase(&I);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000585}
586
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000587void MachineTraceMetrics::Ensemble::verify() const {
588#ifndef NDEBUG
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000589 assert(BlockInfo.size() == MTM.MF->getNumBlockIDs() &&
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000590 "Outdated BlockInfo size");
591 for (unsigned Num = 0, e = BlockInfo.size(); Num != e; ++Num) {
592 const TraceBlockInfo &TBI = BlockInfo[Num];
593 if (TBI.hasValidDepth() && TBI.Pred) {
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000594 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000595 assert(MBB->isPredecessor(TBI.Pred) && "CFG doesn't match trace");
596 assert(BlockInfo[TBI.Pred->getNumber()].hasValidDepth() &&
597 "Trace is broken, depth should have been invalidated.");
598 const MachineLoop *Loop = getLoopFor(MBB);
599 assert(!(Loop && MBB == Loop->getHeader()) && "Trace contains backedge");
600 }
601 if (TBI.hasValidHeight() && TBI.Succ) {
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000602 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000603 assert(MBB->isSuccessor(TBI.Succ) && "CFG doesn't match trace");
604 assert(BlockInfo[TBI.Succ->getNumber()].hasValidHeight() &&
605 "Trace is broken, height should have been invalidated.");
606 const MachineLoop *Loop = getLoopFor(MBB);
607 const MachineLoop *SuccLoop = getLoopFor(TBI.Succ);
608 assert(!(Loop && Loop == SuccLoop && TBI.Succ == Loop->getHeader()) &&
609 "Trace contains backedge");
610 }
611 }
612#endif
613}
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000614
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000615//===----------------------------------------------------------------------===//
616// Data Dependencies
617//===----------------------------------------------------------------------===//
618//
619// Compute the depth and height of each instruction based on data dependencies
620// and instruction latencies. These cycle numbers assume that the CPU can issue
621// an infinite number of instructions per cycle as long as their dependencies
622// are ready.
623
624// A data dependency is represented as a defining MI and operand numbers on the
625// defining and using MI.
626namespace {
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000627
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000628struct DataDep {
629 const MachineInstr *DefMI;
630 unsigned DefOp;
631 unsigned UseOp;
Jakob Stoklund Olesen5e19d352012-08-01 16:02:59 +0000632
633 DataDep(const MachineInstr *DefMI, unsigned DefOp, unsigned UseOp)
634 : DefMI(DefMI), DefOp(DefOp), UseOp(UseOp) {}
635
636 /// Create a DataDep from an SSA form virtual register.
637 DataDep(const MachineRegisterInfo *MRI, unsigned VirtReg, unsigned UseOp)
638 : UseOp(UseOp) {
639 assert(TargetRegisterInfo::isVirtualRegister(VirtReg));
640 MachineRegisterInfo::def_iterator DefI = MRI->def_begin(VirtReg);
641 assert(!DefI.atEnd() && "Register has no defs");
Owen Anderson16c6bf42014-03-13 23:12:04 +0000642 DefMI = DefI->getParent();
Jakob Stoklund Olesen5e19d352012-08-01 16:02:59 +0000643 DefOp = DefI.getOperandNo();
644 assert((++DefI).atEnd() && "Register has multiple defs");
645 }
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000646};
Eugene Zelenko49e2fc42017-02-21 22:07:52 +0000647
648} // end anonymous namespace
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000649
650// Get the input data dependencies that must be ready before UseMI can issue.
651// Return true if UseMI has any physreg operands.
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +0000652static bool getDataDeps(const MachineInstr &UseMI,
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000653 SmallVectorImpl<DataDep> &Deps,
654 const MachineRegisterInfo *MRI) {
Sanjay Patelf2fa58e2015-07-23 22:56:53 +0000655 // Debug values should not be included in any calculations.
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +0000656 if (UseMI.isDebugValue())
Sanjay Patelf2fa58e2015-07-23 22:56:53 +0000657 return false;
658
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000659 bool HasPhysRegs = false;
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +0000660 for (MachineInstr::const_mop_iterator I = UseMI.operands_begin(),
661 E = UseMI.operands_end(); I != E; ++I) {
Matthias Braune41e1462015-05-29 02:56:46 +0000662 const MachineOperand &MO = *I;
663 if (!MO.isReg())
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000664 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000665 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000666 if (!Reg)
667 continue;
668 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
669 HasPhysRegs = true;
670 continue;
671 }
672 // Collect virtual register reads.
Matthias Braune41e1462015-05-29 02:56:46 +0000673 if (MO.readsReg())
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +0000674 Deps.push_back(DataDep(MRI, Reg, UseMI.getOperandNo(I)));
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000675 }
676 return HasPhysRegs;
677}
678
679// Get the input data dependencies of a PHI instruction, using Pred as the
680// preferred predecessor.
681// This will add at most one dependency to Deps.
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000682static void getPHIDeps(const MachineInstr &UseMI,
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000683 SmallVectorImpl<DataDep> &Deps,
684 const MachineBasicBlock *Pred,
685 const MachineRegisterInfo *MRI) {
686 // No predecessor at the beginning of a trace. Ignore dependencies.
687 if (!Pred)
688 return;
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000689 assert(UseMI.isPHI() && UseMI.getNumOperands() % 2 && "Bad PHI");
690 for (unsigned i = 1; i != UseMI.getNumOperands(); i += 2) {
691 if (UseMI.getOperand(i + 1).getMBB() == Pred) {
692 unsigned Reg = UseMI.getOperand(i).getReg();
Jakob Stoklund Olesen5e19d352012-08-01 16:02:59 +0000693 Deps.push_back(DataDep(MRI, Reg, i));
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000694 return;
695 }
696 }
697}
698
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000699// Identify physreg dependencies for UseMI, and update the live regunit
700// tracking set when scanning instructions downwards.
701static void updatePhysDepsDownwards(const MachineInstr *UseMI,
702 SmallVectorImpl<DataDep> &Deps,
703 SparseSet<LiveRegUnit> &RegUnits,
704 const TargetRegisterInfo *TRI) {
705 SmallVector<unsigned, 8> Kills;
706 SmallVector<unsigned, 8> LiveDefOps;
707
Matthias Braune41e1462015-05-29 02:56:46 +0000708 for (MachineInstr::const_mop_iterator MI = UseMI->operands_begin(),
709 ME = UseMI->operands_end(); MI != ME; ++MI) {
710 const MachineOperand &MO = *MI;
711 if (!MO.isReg())
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000712 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000713 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000714 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
715 continue;
716 // Track live defs and kills for updating RegUnits.
Matthias Braune41e1462015-05-29 02:56:46 +0000717 if (MO.isDef()) {
718 if (MO.isDead())
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000719 Kills.push_back(Reg);
720 else
Matthias Braune41e1462015-05-29 02:56:46 +0000721 LiveDefOps.push_back(UseMI->getOperandNo(MI));
722 } else if (MO.isKill())
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000723 Kills.push_back(Reg);
724 // Identify dependencies.
Matthias Braune41e1462015-05-29 02:56:46 +0000725 if (!MO.readsReg())
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000726 continue;
727 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
728 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
729 if (I == RegUnits.end())
730 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000731 Deps.push_back(DataDep(I->MI, I->Op, UseMI->getOperandNo(MI)));
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000732 break;
733 }
734 }
735
736 // Update RegUnits to reflect live registers after UseMI.
737 // First kills.
Sanjay Patel87d2ae22015-12-09 22:45:45 +0000738 for (unsigned Kill : Kills)
739 for (MCRegUnitIterator Units(Kill, TRI); Units.isValid(); ++Units)
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000740 RegUnits.erase(*Units);
741
742 // Second, live defs.
Sanjay Patel87d2ae22015-12-09 22:45:45 +0000743 for (unsigned DefOp : LiveDefOps) {
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000744 for (MCRegUnitIterator Units(UseMI->getOperand(DefOp).getReg(), TRI);
745 Units.isValid(); ++Units) {
746 LiveRegUnit &LRU = RegUnits[*Units];
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000747 LRU.MI = UseMI;
748 LRU.Op = DefOp;
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000749 }
750 }
751}
752
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000753/// The length of the critical path through a trace is the maximum of two path
754/// lengths:
755///
756/// 1. The maximum height+depth over all instructions in the trace center block.
757///
758/// 2. The longest cross-block dependency chain. For small blocks, it is
759/// possible that the critical path through the trace doesn't include any
760/// instructions in the block.
761///
762/// This function computes the second number from the live-in list of the
763/// center block.
764unsigned MachineTraceMetrics::Ensemble::
765computeCrossBlockCriticalPath(const TraceBlockInfo &TBI) {
766 assert(TBI.HasValidInstrDepths && "Missing depth info");
767 assert(TBI.HasValidInstrHeights && "Missing height info");
768 unsigned MaxLen = 0;
Sanjay Patel87d2ae22015-12-09 22:45:45 +0000769 for (const LiveInReg &LIR : TBI.LiveIns) {
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000770 if (!TargetRegisterInfo::isVirtualRegister(LIR.Reg))
771 continue;
772 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
773 // Ignore dependencies outside the current trace.
774 const TraceBlockInfo &DefTBI = BlockInfo[DefMI->getParent()->getNumber()];
Jakob Stoklund Olesen299cedc2013-03-07 23:55:49 +0000775 if (!DefTBI.isUsefulDominator(TBI))
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000776 continue;
777 unsigned Len = LIR.Height + Cycles[DefMI].Depth;
778 MaxLen = std::max(MaxLen, Len);
779 }
780 return MaxLen;
781}
782
Florian Hahncf0cdd42017-09-07 11:51:30 +0000783void MachineTraceMetrics::Ensemble::
784updateDepth(MachineTraceMetrics::TraceBlockInfo &TBI, const MachineInstr &UseMI,
785 SparseSet<LiveRegUnit> &RegUnits) {
786 SmallVector<DataDep, 8> Deps;
787 // Collect all data dependencies.
788 if (UseMI.isPHI())
789 getPHIDeps(UseMI, Deps, TBI.Pred, MTM.MRI);
790 else if (getDataDeps(UseMI, Deps, MTM.MRI))
791 updatePhysDepsDownwards(&UseMI, Deps, RegUnits, MTM.TRI);
792
793 // Filter and process dependencies, computing the earliest issue cycle.
794 unsigned Cycle = 0;
795 for (const DataDep &Dep : Deps) {
796 const TraceBlockInfo&DepTBI =
797 BlockInfo[Dep.DefMI->getParent()->getNumber()];
798 // Ignore dependencies from outside the current trace.
799 if (!DepTBI.isUsefulDominator(TBI))
800 continue;
801 assert(DepTBI.HasValidInstrDepths && "Inconsistent dependency");
802 unsigned DepCycle = Cycles.lookup(Dep.DefMI).Depth;
803 // Add latency if DefMI is a real instruction. Transients get latency 0.
804 if (!Dep.DefMI->isTransient())
805 DepCycle += MTM.SchedModel
806 .computeOperandLatency(Dep.DefMI, Dep.DefOp, &UseMI, Dep.UseOp);
807 Cycle = std::max(Cycle, DepCycle);
808 }
809 // Remember the instruction depth.
810 InstrCycles &MICycles = Cycles[&UseMI];
811 MICycles.Depth = Cycle;
812
813 if (TBI.HasValidInstrHeights) {
814 // Update critical path length.
815 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Height);
816 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << UseMI);
817 } else {
818 DEBUG(dbgs() << Cycle << '\t' << UseMI);
819 }
820}
821
822void MachineTraceMetrics::Ensemble::
823updateDepth(const MachineBasicBlock *MBB, const MachineInstr &UseMI,
824 SparseSet<LiveRegUnit> &RegUnits) {
825 updateDepth(BlockInfo[MBB->getNumber()], UseMI, RegUnits);
826}
827
Florian Hahnceb44942017-09-20 11:54:37 +0000828void MachineTraceMetrics::Ensemble::
829updateDepths(MachineBasicBlock::iterator Start,
830 MachineBasicBlock::iterator End,
831 SparseSet<LiveRegUnit> &RegUnits) {
832 for (; Start != End; Start++)
833 updateDepth(Start->getParent(), *Start, RegUnits);
834}
835
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000836/// Compute instruction depths for all instructions above or in MBB in its
837/// trace. This assumes that the trace through MBB has already been computed.
838void MachineTraceMetrics::Ensemble::
839computeInstrDepths(const MachineBasicBlock *MBB) {
840 // The top of the trace may already be computed, and HasValidInstrDepths
841 // implies Head->HasValidInstrDepths, so we only need to start from the first
842 // block in the trace that needs to be recomputed.
843 SmallVector<const MachineBasicBlock*, 8> Stack;
844 do {
845 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
846 assert(TBI.hasValidDepth() && "Incomplete trace");
847 if (TBI.HasValidInstrDepths)
848 break;
849 Stack.push_back(MBB);
850 MBB = TBI.Pred;
851 } while (MBB);
852
853 // FIXME: If MBB is non-null at this point, it is the last pre-computed block
854 // in the trace. We should track any live-out physregs that were defined in
855 // the trace. This is quite rare in SSA form, typically created by CSE
856 // hoisting a compare.
857 SparseSet<LiveRegUnit> RegUnits;
858 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
859
860 // Go through trace blocks in top-down order, stopping after the center block.
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000861 while (!Stack.empty()) {
862 MBB = Stack.pop_back_val();
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000863 DEBUG(dbgs() << "\nDepths for " << printMBBReference(*MBB) << ":\n");
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000864 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
865 TBI.HasValidInstrDepths = true;
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000866 TBI.CriticalPath = 0;
867
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000868 // Print out resource depths here as well.
869 DEBUG({
870 dbgs() << format("%7u Instructions\n", TBI.InstrDepth);
871 ArrayRef<unsigned> PRDepths = getProcResourceDepths(MBB->getNumber());
872 for (unsigned K = 0; K != PRDepths.size(); ++K)
873 if (PRDepths[K]) {
874 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
875 dbgs() << format("%6uc @ ", MTM.getCycles(PRDepths[K]))
876 << MTM.SchedModel.getProcResource(K)->Name << " ("
877 << PRDepths[K]/Factor << " ops x" << Factor << ")\n";
878 }
879 });
880
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000881 // Also compute the critical path length through MBB when possible.
882 if (TBI.HasValidInstrHeights)
883 TBI.CriticalPath = computeCrossBlockCriticalPath(TBI);
884
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000885 for (const auto &UseMI : *MBB) {
Florian Hahncf0cdd42017-09-07 11:51:30 +0000886 updateDepth(TBI, UseMI, RegUnits);
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000887 }
888 }
889}
890
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000891// Identify physreg dependencies for MI when scanning instructions upwards.
892// Return the issue height of MI after considering any live regunits.
893// Height is the issue height computed from virtual register dependencies alone.
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000894static unsigned updatePhysDepsUpwards(const MachineInstr &MI, unsigned Height,
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000895 SparseSet<LiveRegUnit> &RegUnits,
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +0000896 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000897 const TargetInstrInfo *TII,
898 const TargetRegisterInfo *TRI) {
899 SmallVector<unsigned, 8> ReadOps;
Matthias Braune41e1462015-05-29 02:56:46 +0000900
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000901 for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(),
902 MOE = MI.operands_end();
903 MOI != MOE; ++MOI) {
Matthias Braune41e1462015-05-29 02:56:46 +0000904 const MachineOperand &MO = *MOI;
905 if (!MO.isReg())
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000906 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000907 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000908 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
909 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000910 if (MO.readsReg())
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000911 ReadOps.push_back(MI.getOperandNo(MOI));
Matthias Braune41e1462015-05-29 02:56:46 +0000912 if (!MO.isDef())
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000913 continue;
914 // This is a def of Reg. Remove corresponding entries from RegUnits, and
915 // update MI Height to consider the physreg dependencies.
916 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
917 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
918 if (I == RegUnits.end())
919 continue;
920 unsigned DepHeight = I->Cycle;
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000921 if (!MI.isTransient()) {
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000922 // We may not know the UseMI of this dependency, if it came from the
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +0000923 // live-in list. SchedModel can handle a NULL UseMI.
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000924 DepHeight += SchedModel.computeOperandLatency(&MI, MI.getOperandNo(MOI),
925 I->MI, I->Op);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000926 }
927 Height = std::max(Height, DepHeight);
928 // This regunit is dead above MI.
929 RegUnits.erase(I);
930 }
931 }
932
933 // Now we know the height of MI. Update any regunits read.
934 for (unsigned i = 0, e = ReadOps.size(); i != e; ++i) {
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000935 unsigned Reg = MI.getOperand(ReadOps[i]).getReg();
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000936 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
937 LiveRegUnit &LRU = RegUnits[*Units];
938 // Set the height to the highest reader of the unit.
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000939 if (LRU.Cycle <= Height && LRU.MI != &MI) {
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000940 LRU.Cycle = Height;
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000941 LRU.MI = &MI;
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000942 LRU.Op = ReadOps[i];
943 }
944 }
945 }
946
947 return Height;
948}
949
Eugene Zelenko32a40562017-09-11 23:00:48 +0000950using MIHeightMap = DenseMap<const MachineInstr *, unsigned>;
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000951
952// Push the height of DefMI upwards if required to match UseMI.
953// Return true if this is the first time DefMI was seen.
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000954static bool pushDepHeight(const DataDep &Dep, const MachineInstr &UseMI,
955 unsigned UseHeight, MIHeightMap &Heights,
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +0000956 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000957 const TargetInstrInfo *TII) {
958 // Adjust height by Dep.DefMI latency.
959 if (!Dep.DefMI->isTransient())
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000960 UseHeight += SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp, &UseMI,
961 Dep.UseOp);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000962
963 // Update Heights[DefMI] to be the maximum height seen.
964 MIHeightMap::iterator I;
965 bool New;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000966 std::tie(I, New) = Heights.insert(std::make_pair(Dep.DefMI, UseHeight));
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000967 if (New)
968 return true;
969
970 // DefMI has been pushed before. Give it the max height.
971 if (I->second < UseHeight)
972 I->second = UseHeight;
973 return false;
974}
975
Jakob Stoklund Olesend0d78602012-10-11 16:46:07 +0000976/// Assuming that the virtual register defined by DefMI:DefOp was used by
977/// Trace.back(), add it to the live-in lists of all the blocks in Trace. Stop
978/// when reaching the block that contains DefMI.
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000979void MachineTraceMetrics::Ensemble::
Jakob Stoklund Olesend0d78602012-10-11 16:46:07 +0000980addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000981 ArrayRef<const MachineBasicBlock*> Trace) {
982 assert(!Trace.empty() && "Trace should contain at least one block");
Jakob Stoklund Olesend0d78602012-10-11 16:46:07 +0000983 unsigned Reg = DefMI->getOperand(DefOp).getReg();
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000984 assert(TargetRegisterInfo::isVirtualRegister(Reg));
985 const MachineBasicBlock *DefMBB = DefMI->getParent();
986
987 // Reg is live-in to all blocks in Trace that follow DefMBB.
988 for (unsigned i = Trace.size(); i; --i) {
989 const MachineBasicBlock *MBB = Trace[i-1];
990 if (MBB == DefMBB)
991 return;
992 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
993 // Just add the register. The height will be updated later.
994 TBI.LiveIns.push_back(Reg);
995 }
996}
997
998/// Compute instruction heights in the trace through MBB. This updates MBB and
999/// the blocks below it in the trace. It is assumed that the trace has already
1000/// been computed.
1001void MachineTraceMetrics::Ensemble::
1002computeInstrHeights(const MachineBasicBlock *MBB) {
1003 // The bottom of the trace may already be computed.
1004 // Find the blocks that need updating.
1005 SmallVector<const MachineBasicBlock*, 8> Stack;
1006 do {
1007 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1008 assert(TBI.hasValidHeight() && "Incomplete trace");
1009 if (TBI.HasValidInstrHeights)
1010 break;
1011 Stack.push_back(MBB);
1012 TBI.LiveIns.clear();
1013 MBB = TBI.Succ;
1014 } while (MBB);
1015
1016 // As we move upwards in the trace, keep track of instructions that are
1017 // required by deeper trace instructions. Map MI -> height required so far.
1018 MIHeightMap Heights;
1019
1020 // For physregs, the def isn't known when we see the use.
1021 // Instead, keep track of the highest use of each regunit.
1022 SparseSet<LiveRegUnit> RegUnits;
1023 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
1024
1025 // If the bottom of the trace was already precomputed, initialize heights
1026 // from its live-in list.
1027 // MBB is the highest precomputed block in the trace.
1028 if (MBB) {
1029 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
Sanjay Patel6d4c3e32015-07-06 16:19:14 +00001030 for (LiveInReg &LI : TBI.LiveIns) {
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001031 if (TargetRegisterInfo::isVirtualRegister(LI.Reg)) {
1032 // For virtual registers, the def latency is included.
1033 unsigned &Height = Heights[MTM.MRI->getVRegDef(LI.Reg)];
1034 if (Height < LI.Height)
1035 Height = LI.Height;
1036 } else {
1037 // For register units, the def latency is not included because we don't
1038 // know the def yet.
1039 RegUnits[LI.Reg].Cycle = LI.Height;
1040 }
1041 }
1042 }
1043
1044 // Go through the trace blocks in bottom-up order.
1045 SmallVector<DataDep, 8> Deps;
1046 for (;!Stack.empty(); Stack.pop_back()) {
1047 MBB = Stack.back();
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001048 DEBUG(dbgs() << "Heights for " << printMBBReference(*MBB) << ":\n");
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001049 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1050 TBI.HasValidInstrHeights = true;
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001051 TBI.CriticalPath = 0;
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001052
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001053 DEBUG({
1054 dbgs() << format("%7u Instructions\n", TBI.InstrHeight);
1055 ArrayRef<unsigned> PRHeights = getProcResourceHeights(MBB->getNumber());
1056 for (unsigned K = 0; K != PRHeights.size(); ++K)
1057 if (PRHeights[K]) {
1058 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
1059 dbgs() << format("%6uc @ ", MTM.getCycles(PRHeights[K]))
1060 << MTM.SchedModel.getProcResource(K)->Name << " ("
1061 << PRHeights[K]/Factor << " ops x" << Factor << ")\n";
1062 }
1063 });
1064
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001065 // Get dependencies from PHIs in the trace successor.
Jakob Stoklund Olesen0954d412012-08-10 20:11:38 +00001066 const MachineBasicBlock *Succ = TBI.Succ;
1067 // If MBB is the last block in the trace, and it has a back-edge to the
1068 // loop header, get loop-carried dependencies from PHIs in the header. For
1069 // that purpose, pretend that all the loop header PHIs have height 0.
1070 if (!Succ)
1071 if (const MachineLoop *Loop = getLoopFor(MBB))
1072 if (MBB->isSuccessor(Loop->getHeader()))
1073 Succ = Loop->getHeader();
1074
1075 if (Succ) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001076 for (const auto &PHI : *Succ) {
1077 if (!PHI.isPHI())
1078 break;
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001079 Deps.clear();
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001080 getPHIDeps(PHI, Deps, MBB, MTM.MRI);
Jakob Stoklund Olesen0954d412012-08-10 20:11:38 +00001081 if (!Deps.empty()) {
1082 // Loop header PHI heights are all 0.
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001083 unsigned Height = TBI.Succ ? Cycles.lookup(&PHI).Height : 0;
1084 DEBUG(dbgs() << "pred\t" << Height << '\t' << PHI);
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +00001085 if (pushDepHeight(Deps.front(), PHI, Height, Heights, MTM.SchedModel,
1086 MTM.TII))
Jakob Stoklund Olesend0d78602012-10-11 16:46:07 +00001087 addLiveIns(Deps.front().DefMI, Deps.front().DefOp, Stack);
Jakob Stoklund Olesen0954d412012-08-10 20:11:38 +00001088 }
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001089 }
1090 }
1091
1092 // Go through the block backwards.
1093 for (MachineBasicBlock::const_iterator BI = MBB->end(), BB = MBB->begin();
1094 BI != BB;) {
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +00001095 const MachineInstr &MI = *--BI;
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001096
1097 // Find the MI height as determined by virtual register uses in the
1098 // trace below.
1099 unsigned Cycle = 0;
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +00001100 MIHeightMap::iterator HeightI = Heights.find(&MI);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001101 if (HeightI != Heights.end()) {
1102 Cycle = HeightI->second;
1103 // We won't be seeing any more MI uses.
1104 Heights.erase(HeightI);
1105 }
1106
1107 // Don't process PHI deps. They depend on the specific predecessor, and
1108 // we'll get them when visiting the predecessor.
1109 Deps.clear();
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +00001110 bool HasPhysRegs = !MI.isPHI() && getDataDeps(MI, Deps, MTM.MRI);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001111
1112 // There may also be regunit dependencies to include in the height.
1113 if (HasPhysRegs)
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +00001114 Cycle = updatePhysDepsUpwards(MI, Cycle, RegUnits, MTM.SchedModel,
1115 MTM.TII, MTM.TRI);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001116
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001117 // Update the required height of any virtual registers read by MI.
Sanjay Patel0ca438c2015-06-30 16:30:22 +00001118 for (const DataDep &Dep : Deps)
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +00001119 if (pushDepHeight(Dep, MI, Cycle, Heights, MTM.SchedModel, MTM.TII))
Sanjay Patel0ca438c2015-06-30 16:30:22 +00001120 addLiveIns(Dep.DefMI, Dep.DefOp, Stack);
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001121
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +00001122 InstrCycles &MICycles = Cycles[&MI];
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001123 MICycles.Height = Cycle;
1124 if (!TBI.HasValidInstrDepths) {
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +00001125 DEBUG(dbgs() << Cycle << '\t' << MI);
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001126 continue;
1127 }
1128 // Update critical path length.
1129 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Depth);
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +00001130 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << MI);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001131 }
1132
1133 // Update virtual live-in heights. They were added by addLiveIns() with a 0
1134 // height because the final height isn't known until now.
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001135 DEBUG(dbgs() << printMBBReference(*MBB) << " Live-ins:");
Sanjay Patel0ca438c2015-06-30 16:30:22 +00001136 for (LiveInReg &LIR : TBI.LiveIns) {
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001137 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
1138 LIR.Height = Heights.lookup(DefMI);
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001139 DEBUG(dbgs() << ' ' << printReg(LIR.Reg) << '@' << LIR.Height);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001140 }
1141
1142 // Transfer the live regunits to the live-in list.
1143 for (SparseSet<LiveRegUnit>::const_iterator
1144 RI = RegUnits.begin(), RE = RegUnits.end(); RI != RE; ++RI) {
1145 TBI.LiveIns.push_back(LiveInReg(RI->RegUnit, RI->Cycle));
Francis Visoiu Mistrih9d419d32017-11-28 12:42:37 +00001146 DEBUG(dbgs() << ' ' << printRegUnit(RI->RegUnit, MTM.TRI)
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001147 << '@' << RI->Cycle);
1148 }
1149 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001150
1151 if (!TBI.HasValidInstrDepths)
1152 continue;
1153 // Add live-ins to the critical path length.
1154 TBI.CriticalPath = std::max(TBI.CriticalPath,
1155 computeCrossBlockCriticalPath(TBI));
1156 DEBUG(dbgs() << "Critical path: " << TBI.CriticalPath << '\n');
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001157 }
1158}
1159
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001160MachineTraceMetrics::Trace
1161MachineTraceMetrics::Ensemble::getTrace(const MachineBasicBlock *MBB) {
Sanjay Patel82db3b72015-07-04 15:00:28 +00001162 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1163
1164 if (!TBI.hasValidDepth() || !TBI.hasValidHeight())
1165 computeTrace(MBB);
1166 if (!TBI.HasValidInstrDepths)
1167 computeInstrDepths(MBB);
1168 if (!TBI.HasValidInstrHeights)
1169 computeInstrHeights(MBB);
1170
1171 return Trace(*this, TBI);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001172}
1173
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001174unsigned
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001175MachineTraceMetrics::Trace::getInstrSlack(const MachineInstr &MI) const {
1176 assert(getBlockNum() == unsigned(MI.getParent()->getNumber()) &&
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001177 "MI must be in the trace center block");
1178 InstrCycles Cyc = getInstrCycles(MI);
1179 return getCriticalPath() - (Cyc.Depth + Cyc.Height);
1180}
1181
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001182unsigned
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001183MachineTraceMetrics::Trace::getPHIDepth(const MachineInstr &PHI) const {
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001184 const MachineBasicBlock *MBB = TE.MTM.MF->getBlockNumbered(getBlockNum());
1185 SmallVector<DataDep, 1> Deps;
1186 getPHIDeps(PHI, Deps, MBB, TE.MTM.MRI);
1187 assert(Deps.size() == 1 && "PHI doesn't have MBB as a predecessor");
1188 DataDep &Dep = Deps.front();
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001189 unsigned DepCycle = getInstrCycles(*Dep.DefMI).Depth;
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001190 // Add latency if DefMI is a real instruction. Transients get latency 0.
1191 if (!Dep.DefMI->isTransient())
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001192 DepCycle += TE.MTM.SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp,
1193 &PHI, Dep.UseOp);
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001194 return DepCycle;
1195}
1196
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001197/// When bottom is set include instructions in current block in estimate.
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001198unsigned MachineTraceMetrics::Trace::getResourceDepth(bool Bottom) const {
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001199 // Find the limiting processor resource.
1200 // Numbers have been pre-scaled to be comparable.
1201 unsigned PRMax = 0;
1202 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1203 if (Bottom) {
1204 ArrayRef<unsigned> PRCycles = TE.MTM.getProcResourceCycles(getBlockNum());
1205 for (unsigned K = 0; K != PRDepths.size(); ++K)
1206 PRMax = std::max(PRMax, PRDepths[K] + PRCycles[K]);
1207 } else {
1208 for (unsigned K = 0; K != PRDepths.size(); ++K)
1209 PRMax = std::max(PRMax, PRDepths[K]);
1210 }
1211 // Convert to cycle count.
1212 PRMax = TE.MTM.getCycles(PRMax);
1213
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001214 /// All instructions before current block
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001215 unsigned Instrs = TBI.InstrDepth;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001216 // plus instructions in current block
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001217 if (Bottom)
1218 Instrs += TE.MTM.BlockInfo[getBlockNum()].InstrCount;
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +00001219 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1220 Instrs /= IW;
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001221 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001222 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001223}
1224
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001225unsigned MachineTraceMetrics::Trace::getResourceLength(
1226 ArrayRef<const MachineBasicBlock *> Extrablocks,
1227 ArrayRef<const MCSchedClassDesc *> ExtraInstrs,
1228 ArrayRef<const MCSchedClassDesc *> RemoveInstrs) const {
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001229 // Add up resources above and below the center block.
1230 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1231 ArrayRef<unsigned> PRHeights = TE.getProcResourceHeights(getBlockNum());
1232 unsigned PRMax = 0;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001233
1234 // Capture computing cycles from extra instructions
1235 auto extraCycles = [this](ArrayRef<const MCSchedClassDesc *> Instrs,
1236 unsigned ResourceIdx)
1237 ->unsigned {
1238 unsigned Cycles = 0;
Sanjay Patel6d4c3e32015-07-06 16:19:14 +00001239 for (const MCSchedClassDesc *SC : Instrs) {
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001240 if (!SC->isValid())
1241 continue;
1242 for (TargetSchedModel::ProcResIter
1243 PI = TE.MTM.SchedModel.getWriteProcResBegin(SC),
1244 PE = TE.MTM.SchedModel.getWriteProcResEnd(SC);
1245 PI != PE; ++PI) {
1246 if (PI->ProcResourceIdx != ResourceIdx)
1247 continue;
1248 Cycles +=
1249 (PI->Cycles * TE.MTM.SchedModel.getResourceFactor(ResourceIdx));
1250 }
1251 }
1252 return Cycles;
1253 };
1254
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001255 for (unsigned K = 0; K != PRDepths.size(); ++K) {
1256 unsigned PRCycles = PRDepths[K] + PRHeights[K];
Sanjay Patel6d4c3e32015-07-06 16:19:14 +00001257 for (const MachineBasicBlock *MBB : Extrablocks)
1258 PRCycles += TE.MTM.getProcResourceCycles(MBB->getNumber())[K];
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001259 PRCycles += extraCycles(ExtraInstrs, K);
1260 PRCycles -= extraCycles(RemoveInstrs, K);
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001261 PRMax = std::max(PRMax, PRCycles);
1262 }
1263 // Convert to cycle count.
1264 PRMax = TE.MTM.getCycles(PRMax);
1265
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001266 // Instrs: #instructions in current trace outside current block.
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001267 unsigned Instrs = TBI.InstrDepth + TBI.InstrHeight;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001268 // Add instruction count from the extra blocks.
Sanjay Patel6d4c3e32015-07-06 16:19:14 +00001269 for (const MachineBasicBlock *MBB : Extrablocks)
1270 Instrs += TE.MTM.getResources(MBB)->InstrCount;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001271 Instrs += ExtraInstrs.size();
1272 Instrs -= RemoveInstrs.size();
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +00001273 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1274 Instrs /= IW;
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001275 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001276 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001277}
1278
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001279bool MachineTraceMetrics::Trace::isDepInTrace(const MachineInstr &DefMI,
1280 const MachineInstr &UseMI) const {
1281 if (DefMI.getParent() == UseMI.getParent())
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001282 return true;
1283
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001284 const TraceBlockInfo &DepTBI = TE.BlockInfo[DefMI.getParent()->getNumber()];
1285 const TraceBlockInfo &TBI = TE.BlockInfo[UseMI.getParent()->getNumber()];
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001286
1287 return DepTBI.isUsefulDominator(TBI);
1288}
1289
Jakob Stoklund Olesen05633692012-07-27 23:58:38 +00001290void MachineTraceMetrics::Ensemble::print(raw_ostream &OS) const {
1291 OS << getName() << " ensemble:\n";
1292 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001293 OS << " %bb." << i << '\t';
Jakob Stoklund Olesen05633692012-07-27 23:58:38 +00001294 BlockInfo[i].print(OS);
1295 OS << '\n';
1296 }
1297}
1298
1299void MachineTraceMetrics::TraceBlockInfo::print(raw_ostream &OS) const {
1300 if (hasValidDepth()) {
1301 OS << "depth=" << InstrDepth;
1302 if (Pred)
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001303 OS << " pred=" << printMBBReference(*Pred);
Jakob Stoklund Olesen05633692012-07-27 23:58:38 +00001304 else
1305 OS << " pred=null";
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001306 OS << " head=%bb." << Head;
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +00001307 if (HasValidInstrDepths)
1308 OS << " +instrs";
Jakob Stoklund Olesen05633692012-07-27 23:58:38 +00001309 } else
1310 OS << "depth invalid";
1311 OS << ", ";
1312 if (hasValidHeight()) {
1313 OS << "height=" << InstrHeight;
1314 if (Succ)
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001315 OS << " succ=" << printMBBReference(*Succ);
Jakob Stoklund Olesen05633692012-07-27 23:58:38 +00001316 else
1317 OS << " succ=null";
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001318 OS << " tail=%bb." << Tail;
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +00001319 if (HasValidInstrHeights)
1320 OS << " +instrs";
Jakob Stoklund Olesen05633692012-07-27 23:58:38 +00001321 } else
1322 OS << "height invalid";
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001323 if (HasValidInstrDepths && HasValidInstrHeights)
1324 OS << ", crit=" << CriticalPath;
Jakob Stoklund Olesen05633692012-07-27 23:58:38 +00001325}
1326
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001327void MachineTraceMetrics::Trace::print(raw_ostream &OS) const {
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +00001328 unsigned MBBNum = &TBI - &TE.BlockInfo[0];
1329
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001330 OS << TE.getName() << " trace %bb." << TBI.Head << " --> %bb." << MBBNum
1331 << " --> %bb." << TBI.Tail << ':';
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001332 if (TBI.hasValidHeight() && TBI.hasValidDepth())
1333 OS << ' ' << getInstrCount() << " instrs.";
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001334 if (TBI.HasValidInstrDepths && TBI.HasValidInstrHeights)
1335 OS << ' ' << TBI.CriticalPath << " cycles.";
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001336
1337 const MachineTraceMetrics::TraceBlockInfo *Block = &TBI;
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001338 OS << "\n%bb." << MBBNum;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001339 while (Block->hasValidDepth() && Block->Pred) {
1340 unsigned Num = Block->Pred->getNumber();
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001341 OS << " <- " << printMBBReference(*Block->Pred);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001342 Block = &TE.BlockInfo[Num];
1343 }
1344
1345 Block = &TBI;
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +00001346 OS << "\n ";
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001347 while (Block->hasValidHeight() && Block->Succ) {
1348 unsigned Num = Block->Succ->getNumber();
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +00001349 OS << " -> " << printMBBReference(*Block->Succ);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001350 Block = &TE.BlockInfo[Num];
1351 }
1352 OS << '\n';
1353}