blob: 9404c687d4101a693974c61e6d88115309c10699 [file] [log] [blame]
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001//===- lib/CodeGen/MachineTraceMetrics.cpp ----------------------*- C++ -*-===//
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
Jakob Stoklund Olesen965665b2013-01-17 01:06:04 +000010#include "llvm/CodeGen/MachineTraceMetrics.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000011#include "llvm/ADT/PostOrderIterator.h"
12#include "llvm/ADT/SparseSet.h"
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000013#include "llvm/CodeGen/MachineBasicBlock.h"
14#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
15#include "llvm/CodeGen/MachineLoopInfo.h"
16#include "llvm/CodeGen/MachineRegisterInfo.h"
17#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +000018#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/Support/Debug.h"
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +000020#include "llvm/Support/Format.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000022#include "llvm/Target/TargetInstrInfo.h"
23#include "llvm/Target/TargetRegisterInfo.h"
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +000024#include "llvm/Target/TargetSubtargetInfo.h"
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000025
26using namespace llvm;
27
Chandler Carruth1b9dde02014-04-22 02:02:50 +000028#define DEBUG_TYPE "machine-trace-metrics"
29
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000030char MachineTraceMetrics::ID = 0;
31char &llvm::MachineTraceMetricsID = MachineTraceMetrics::ID;
32
33INITIALIZE_PASS_BEGIN(MachineTraceMetrics,
34 "machine-trace-metrics", "Machine Trace Metrics", false, true)
35INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
36INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
37INITIALIZE_PASS_END(MachineTraceMetrics,
38 "machine-trace-metrics", "Machine Trace Metrics", false, true)
39
40MachineTraceMetrics::MachineTraceMetrics()
Craig Topperc0196b12014-04-14 00:51:57 +000041 : MachineFunctionPass(ID), MF(nullptr), TII(nullptr), TRI(nullptr),
42 MRI(nullptr), Loops(nullptr) {
Benjamin Kramer502b9e12014-04-12 16:15:53 +000043 std::fill(std::begin(Ensembles), std::end(Ensembles), nullptr);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000044}
45
46void MachineTraceMetrics::getAnalysisUsage(AnalysisUsage &AU) const {
47 AU.setPreservesAll();
48 AU.addRequired<MachineBranchProbabilityInfo>();
49 AU.addRequired<MachineLoopInfo>();
50 MachineFunctionPass::getAnalysisUsage(AU);
51}
52
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +000053bool MachineTraceMetrics::runOnMachineFunction(MachineFunction &Func) {
54 MF = &Func;
Eric Christopher3d4276f2015-01-27 07:31:29 +000055 const TargetSubtargetInfo &ST = MF->getSubtarget();
56 TII = ST.getInstrInfo();
57 TRI = ST.getRegisterInfo();
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +000058 MRI = &MF->getRegInfo();
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000059 Loops = &getAnalysis<MachineLoopInfo>();
Pete Cooper11759452014-09-02 17:43:54 +000060 SchedModel.init(ST.getSchedModel(), &ST, TII);
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +000061 BlockInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +000062 ProcResourceCycles.resize(MF->getNumBlockIDs() *
63 SchedModel.getNumProcResourceKinds());
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000064 return false;
65}
66
67void MachineTraceMetrics::releaseMemory() {
Craig Topperc0196b12014-04-14 00:51:57 +000068 MF = nullptr;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000069 BlockInfo.clear();
70 for (unsigned i = 0; i != TS_NumStrategies; ++i) {
71 delete Ensembles[i];
Craig Topperc0196b12014-04-14 00:51:57 +000072 Ensembles[i] = nullptr;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000073 }
74}
75
76//===----------------------------------------------------------------------===//
77// Fixed block information
78//===----------------------------------------------------------------------===//
79//
80// The number of instructions in a basic block and the CPU resources used by
81// those instructions don't depend on any given trace strategy.
82
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000083/// Compute the resource usage in basic block MBB.
84const MachineTraceMetrics::FixedBlockInfo*
85MachineTraceMetrics::getResources(const MachineBasicBlock *MBB) {
86 assert(MBB && "No basic block");
87 FixedBlockInfo *FBI = &BlockInfo[MBB->getNumber()];
88 if (FBI->hasResources())
89 return FBI;
90
91 // Compute resource usage in the block.
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +000092 FBI->HasCalls = false;
93 unsigned InstrCount = 0;
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +000094
95 // Add up per-processor resource cycles as well.
96 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
97 SmallVector<unsigned, 32> PRCycles(PRKinds);
98
Alexey Samsonovf74bde62014-04-30 22:17:38 +000099 for (const auto &MI : *MBB) {
100 if (MI.isTransient())
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000101 continue;
102 ++InstrCount;
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000103 if (MI.isCall())
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000104 FBI->HasCalls = true;
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000105
106 // Count processor resources used.
Jakob Stoklund Olesenaeb69a52013-04-02 22:27:45 +0000107 if (!SchedModel.hasInstrSchedModel())
108 continue;
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000109 const MCSchedClassDesc *SC = SchedModel.resolveSchedClass(&MI);
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000110 if (!SC->isValid())
111 continue;
112
113 for (TargetSchedModel::ProcResIter
114 PI = SchedModel.getWriteProcResBegin(SC),
115 PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
116 assert(PI->ProcResourceIdx < PRKinds && "Bad processor resource kind");
117 PRCycles[PI->ProcResourceIdx] += PI->Cycles;
118 }
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000119 }
120 FBI->InstrCount = InstrCount;
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000121
122 // Scale the resource cycles so they are comparable.
123 unsigned PROffset = MBB->getNumber() * PRKinds;
124 for (unsigned K = 0; K != PRKinds; ++K)
125 ProcResourceCycles[PROffset + K] =
126 PRCycles[K] * SchedModel.getResourceFactor(K);
127
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000128 return FBI;
129}
130
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000131ArrayRef<unsigned>
132MachineTraceMetrics::getProcResourceCycles(unsigned MBBNum) const {
133 assert(BlockInfo[MBBNum].hasResources() &&
134 "getResources() must be called before getProcResourceCycles()");
135 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesenaeb69a52013-04-02 22:27:45 +0000136 assert((MBBNum+1) * PRKinds <= ProcResourceCycles.size());
Craig Toppere1d12942014-08-27 05:25:25 +0000137 return makeArrayRef(ProcResourceCycles.data() + MBBNum * PRKinds, PRKinds);
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000138}
139
140
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000141//===----------------------------------------------------------------------===//
142// Ensemble utility functions
143//===----------------------------------------------------------------------===//
144
145MachineTraceMetrics::Ensemble::Ensemble(MachineTraceMetrics *ct)
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000146 : MTM(*ct) {
147 BlockInfo.resize(MTM.BlockInfo.size());
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000148 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
149 ProcResourceDepths.resize(MTM.BlockInfo.size() * PRKinds);
150 ProcResourceHeights.resize(MTM.BlockInfo.size() * PRKinds);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000151}
152
153// Virtual destructor serves as an anchor.
154MachineTraceMetrics::Ensemble::~Ensemble() {}
155
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000156const MachineLoop*
157MachineTraceMetrics::Ensemble::getLoopFor(const MachineBasicBlock *MBB) const {
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000158 return MTM.Loops->getLoopFor(MBB);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000159}
160
161// Update resource-related information in the TraceBlockInfo for MBB.
162// Only update resources related to the trace above MBB.
163void MachineTraceMetrics::Ensemble::
164computeDepthResources(const MachineBasicBlock *MBB) {
165 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000166 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
167 unsigned PROffset = MBB->getNumber() * PRKinds;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000168
169 // Compute resources from trace above. The top block is simple.
170 if (!TBI->Pred) {
171 TBI->InstrDepth = 0;
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +0000172 TBI->Head = MBB->getNumber();
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000173 std::fill(ProcResourceDepths.begin() + PROffset,
174 ProcResourceDepths.begin() + PROffset + PRKinds, 0);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000175 return;
176 }
177
178 // Compute from the block above. A post-order traversal ensures the
179 // predecessor is always computed first.
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000180 unsigned PredNum = TBI->Pred->getNumber();
181 TraceBlockInfo *PredTBI = &BlockInfo[PredNum];
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000182 assert(PredTBI->hasValidDepth() && "Trace above has not been computed yet");
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000183 const FixedBlockInfo *PredFBI = MTM.getResources(TBI->Pred);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000184 TBI->InstrDepth = PredTBI->InstrDepth + PredFBI->InstrCount;
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +0000185 TBI->Head = PredTBI->Head;
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000186
187 // Compute per-resource depths.
188 ArrayRef<unsigned> PredPRDepths = getProcResourceDepths(PredNum);
189 ArrayRef<unsigned> PredPRCycles = MTM.getProcResourceCycles(PredNum);
190 for (unsigned K = 0; K != PRKinds; ++K)
191 ProcResourceDepths[PROffset + K] = PredPRDepths[K] + PredPRCycles[K];
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000192}
193
194// Update resource-related information in the TraceBlockInfo for MBB.
195// Only update resources related to the trace below MBB.
196void MachineTraceMetrics::Ensemble::
197computeHeightResources(const MachineBasicBlock *MBB) {
198 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000199 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
200 unsigned PROffset = MBB->getNumber() * PRKinds;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000201
202 // Compute resources for the current block.
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000203 TBI->InstrHeight = MTM.getResources(MBB)->InstrCount;
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000204 ArrayRef<unsigned> PRCycles = MTM.getProcResourceCycles(MBB->getNumber());
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000205
206 // The trace tail is done.
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +0000207 if (!TBI->Succ) {
208 TBI->Tail = MBB->getNumber();
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000209 std::copy(PRCycles.begin(), PRCycles.end(),
210 ProcResourceHeights.begin() + PROffset);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000211 return;
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +0000212 }
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000213
214 // Compute from the block below. A post-order traversal ensures the
215 // predecessor is always computed first.
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000216 unsigned SuccNum = TBI->Succ->getNumber();
217 TraceBlockInfo *SuccTBI = &BlockInfo[SuccNum];
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000218 assert(SuccTBI->hasValidHeight() && "Trace below has not been computed yet");
219 TBI->InstrHeight += SuccTBI->InstrHeight;
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +0000220 TBI->Tail = SuccTBI->Tail;
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000221
222 // Compute per-resource heights.
223 ArrayRef<unsigned> SuccPRHeights = getProcResourceHeights(SuccNum);
224 for (unsigned K = 0; K != PRKinds; ++K)
225 ProcResourceHeights[PROffset + K] = SuccPRHeights[K] + PRCycles[K];
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000226}
227
228// Check if depth resources for MBB are valid and return the TBI.
229// Return NULL if the resources have been invalidated.
230const MachineTraceMetrics::TraceBlockInfo*
231MachineTraceMetrics::Ensemble::
232getDepthResources(const MachineBasicBlock *MBB) const {
233 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Craig Topperc0196b12014-04-14 00:51:57 +0000234 return TBI->hasValidDepth() ? TBI : nullptr;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000235}
236
237// Check if height resources for MBB are valid and return the TBI.
238// Return NULL if the resources have been invalidated.
239const MachineTraceMetrics::TraceBlockInfo*
240MachineTraceMetrics::Ensemble::
241getHeightResources(const MachineBasicBlock *MBB) const {
242 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Craig Topperc0196b12014-04-14 00:51:57 +0000243 return TBI->hasValidHeight() ? TBI : nullptr;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000244}
245
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000246/// Get an array of processor resource depths for MBB. Indexed by processor
247/// resource kind, this array contains the scaled processor resources consumed
248/// by all blocks preceding MBB in its trace. It does not include instructions
249/// in MBB.
250///
251/// Compare TraceBlockInfo::InstrDepth.
252ArrayRef<unsigned>
253MachineTraceMetrics::Ensemble::
254getProcResourceDepths(unsigned MBBNum) const {
255 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesenaeb69a52013-04-02 22:27:45 +0000256 assert((MBBNum+1) * PRKinds <= ProcResourceDepths.size());
Craig Toppere1d12942014-08-27 05:25:25 +0000257 return makeArrayRef(ProcResourceDepths.data() + MBBNum * PRKinds, PRKinds);
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000258}
259
260/// Get an array of processor resource heights for MBB. Indexed by processor
261/// resource kind, this array contains the scaled processor resources consumed
262/// by this block and all blocks following it in its trace.
263///
264/// Compare TraceBlockInfo::InstrHeight.
265ArrayRef<unsigned>
266MachineTraceMetrics::Ensemble::
267getProcResourceHeights(unsigned MBBNum) const {
268 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesenaeb69a52013-04-02 22:27:45 +0000269 assert((MBBNum+1) * PRKinds <= ProcResourceHeights.size());
Craig Toppere1d12942014-08-27 05:25:25 +0000270 return makeArrayRef(ProcResourceHeights.data() + MBBNum * PRKinds, PRKinds);
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000271}
272
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000273//===----------------------------------------------------------------------===//
274// Trace Selection Strategies
275//===----------------------------------------------------------------------===//
276//
277// A trace selection strategy is implemented as a sub-class of Ensemble. The
278// trace through a block B is computed by two DFS traversals of the CFG
279// starting from B. One upwards, and one downwards. During the upwards DFS,
280// pickTracePred() is called on the post-ordered blocks. During the downwards
281// DFS, pickTraceSucc() is called in a post-order.
282//
283
Jakob Stoklund Olesenc14cf572012-07-30 23:15:10 +0000284// We never allow traces that leave loops, but we do allow traces to enter
285// nested loops. We also never allow traces to contain back-edges.
286//
287// This means that a loop header can never appear above the center block of a
288// trace, except as the trace head. Below the center block, loop exiting edges
289// are banned.
290//
291// Return true if an edge from the From loop to the To loop is leaving a loop.
292// Either of To and From can be null.
293static bool isExitingLoop(const MachineLoop *From, const MachineLoop *To) {
294 return From && !From->contains(To);
295}
296
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000297// MinInstrCountEnsemble - Pick the trace that executes the least number of
298// instructions.
299namespace {
300class MinInstrCountEnsemble : public MachineTraceMetrics::Ensemble {
Craig Topper4584cd52014-03-07 09:26:03 +0000301 const char *getName() const override { return "MinInstr"; }
302 const MachineBasicBlock *pickTracePred(const MachineBasicBlock*) override;
303 const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*) override;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000304
305public:
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000306 MinInstrCountEnsemble(MachineTraceMetrics *mtm)
307 : MachineTraceMetrics::Ensemble(mtm) {}
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000308};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000309}
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000310
311// Select the preferred predecessor for MBB.
312const MachineBasicBlock*
313MinInstrCountEnsemble::pickTracePred(const MachineBasicBlock *MBB) {
314 if (MBB->pred_empty())
Craig Topperc0196b12014-04-14 00:51:57 +0000315 return nullptr;
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000316 const MachineLoop *CurLoop = getLoopFor(MBB);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000317 // Don't leave loops, and never follow back-edges.
318 if (CurLoop && MBB == CurLoop->getHeader())
Craig Topperc0196b12014-04-14 00:51:57 +0000319 return nullptr;
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000320 unsigned CurCount = MTM.getResources(MBB)->InstrCount;
Craig Topperc0196b12014-04-14 00:51:57 +0000321 const MachineBasicBlock *Best = nullptr;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000322 unsigned BestDepth = 0;
Sanjay Patel99b3aa32015-05-21 17:22:45 +0000323 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
Jakob Stoklund Olesenf308c122012-07-30 21:10:27 +0000324 const MachineTraceMetrics::TraceBlockInfo *PredTBI =
325 getDepthResources(Pred);
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000326 // Ignore cycles that aren't natural loops.
327 if (!PredTBI)
328 continue;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000329 // Pick the predecessor that would give this block the smallest InstrDepth.
330 unsigned Depth = PredTBI->InstrDepth + CurCount;
331 if (!Best || Depth < BestDepth)
332 Best = Pred, BestDepth = Depth;
333 }
334 return Best;
335}
336
337// Select the preferred successor for MBB.
338const MachineBasicBlock*
339MinInstrCountEnsemble::pickTraceSucc(const MachineBasicBlock *MBB) {
340 if (MBB->pred_empty())
Craig Topperc0196b12014-04-14 00:51:57 +0000341 return nullptr;
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000342 const MachineLoop *CurLoop = getLoopFor(MBB);
Craig Topperc0196b12014-04-14 00:51:57 +0000343 const MachineBasicBlock *Best = nullptr;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000344 unsigned BestHeight = 0;
Sanjay Patel99b3aa32015-05-21 17:22:45 +0000345 for (const MachineBasicBlock *Succ : MBB->successors()) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000346 // Don't consider back-edges.
347 if (CurLoop && Succ == CurLoop->getHeader())
348 continue;
Jakob Stoklund Olesenc14cf572012-07-30 23:15:10 +0000349 // Don't consider successors exiting CurLoop.
350 if (isExitingLoop(CurLoop, getLoopFor(Succ)))
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000351 continue;
Jakob Stoklund Olesenf308c122012-07-30 21:10:27 +0000352 const MachineTraceMetrics::TraceBlockInfo *SuccTBI =
353 getHeightResources(Succ);
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000354 // Ignore cycles that aren't natural loops.
355 if (!SuccTBI)
356 continue;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000357 // Pick the successor that would give this block the smallest InstrHeight.
358 unsigned Height = SuccTBI->InstrHeight;
359 if (!Best || Height < BestHeight)
360 Best = Succ, BestHeight = Height;
361 }
362 return Best;
363}
364
365// Get an Ensemble sub-class for the requested trace strategy.
366MachineTraceMetrics::Ensemble *
367MachineTraceMetrics::getEnsemble(MachineTraceMetrics::Strategy strategy) {
368 assert(strategy < TS_NumStrategies && "Invalid trace strategy enum");
369 Ensemble *&E = Ensembles[strategy];
370 if (E)
371 return E;
372
373 // Allocate new Ensemble on demand.
374 switch (strategy) {
375 case TS_MinInstrCount: return (E = new MinInstrCountEnsemble(this));
376 default: llvm_unreachable("Invalid trace strategy enum");
377 }
378}
379
380void MachineTraceMetrics::invalidate(const MachineBasicBlock *MBB) {
381 DEBUG(dbgs() << "Invalidate traces through BB#" << MBB->getNumber() << '\n');
382 BlockInfo[MBB->getNumber()].invalidate();
383 for (unsigned i = 0; i != TS_NumStrategies; ++i)
384 if (Ensembles[i])
385 Ensembles[i]->invalidate(MBB);
386}
387
Jakob Stoklund Olesena12a7d52012-07-30 20:57:50 +0000388void MachineTraceMetrics::verifyAnalysis() const {
Jakob Stoklund Olesen68c2cd02012-07-30 23:15:12 +0000389 if (!MF)
390 return;
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000391#ifndef NDEBUG
392 assert(BlockInfo.size() == MF->getNumBlockIDs() && "Outdated BlockInfo size");
393 for (unsigned i = 0; i != TS_NumStrategies; ++i)
394 if (Ensembles[i])
395 Ensembles[i]->verify();
396#endif
397}
398
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000399//===----------------------------------------------------------------------===//
400// Trace building
401//===----------------------------------------------------------------------===//
402//
403// Traces are built by two CFG traversals. To avoid recomputing too much, use a
404// set abstraction that confines the search to the current loop, and doesn't
405// revisit blocks.
406
407namespace {
408struct LoopBounds {
409 MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> Blocks;
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000410 SmallPtrSet<const MachineBasicBlock*, 8> Visited;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000411 const MachineLoopInfo *Loops;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000412 bool Downward;
413 LoopBounds(MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> blocks,
Jakob Stoklund Olesenc14cf572012-07-30 23:15:10 +0000414 const MachineLoopInfo *loops)
415 : Blocks(blocks), Loops(loops), Downward(false) {}
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000416};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000417}
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000418
419// Specialize po_iterator_storage in order to prune the post-order traversal so
420// it is limited to the current loop and doesn't traverse the loop back edges.
421namespace llvm {
422template<>
423class po_iterator_storage<LoopBounds, true> {
424 LoopBounds &LB;
425public:
426 po_iterator_storage(LoopBounds &lb) : LB(lb) {}
427 void finishPostorder(const MachineBasicBlock*) {}
428
429 bool insertEdge(const MachineBasicBlock *From, const MachineBasicBlock *To) {
430 // Skip already visited To blocks.
431 MachineTraceMetrics::TraceBlockInfo &TBI = LB.Blocks[To->getNumber()];
432 if (LB.Downward ? TBI.hasValidHeight() : TBI.hasValidDepth())
433 return false;
Jakob Stoklund Olesenc14cf572012-07-30 23:15:10 +0000434 // From is null once when To is the trace center block.
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000435 if (From) {
436 if (const MachineLoop *FromLoop = LB.Loops->getLoopFor(From)) {
437 // Don't follow backedges, don't leave FromLoop when going upwards.
438 if ((LB.Downward ? To : From) == FromLoop->getHeader())
439 return false;
440 // Don't leave FromLoop.
441 if (isExitingLoop(FromLoop, LB.Loops->getLoopFor(To)))
442 return false;
443 }
444 }
445 // To is a new block. Mark the block as visited in case the CFG has cycles
446 // that MachineLoopInfo didn't recognize as a natural loop.
David Blaikie70573dc2014-11-19 07:49:26 +0000447 return LB.Visited.insert(To).second;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000448 }
449};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000450}
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000451
452/// Compute the trace through MBB.
453void MachineTraceMetrics::Ensemble::computeTrace(const MachineBasicBlock *MBB) {
454 DEBUG(dbgs() << "Computing " << getName() << " trace through BB#"
455 << MBB->getNumber() << '\n');
456 // Set up loop bounds for the backwards post-order traversal.
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000457 LoopBounds Bounds(BlockInfo, MTM.Loops);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000458
459 // Run an upwards post-order search for the trace start.
460 Bounds.Downward = false;
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000461 Bounds.Visited.clear();
Daniel Berlin25db4f42015-04-15 17:41:42 +0000462 for (auto I : inverse_post_order_ext(MBB, Bounds)) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000463 DEBUG(dbgs() << " pred for BB#" << I->getNumber() << ": ");
464 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
465 // All the predecessors have been visited, pick the preferred one.
Daniel Berlin25db4f42015-04-15 17:41:42 +0000466 TBI.Pred = pickTracePred(I);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000467 DEBUG({
468 if (TBI.Pred)
469 dbgs() << "BB#" << TBI.Pred->getNumber() << '\n';
470 else
471 dbgs() << "null\n";
472 });
473 // The trace leading to I is now known, compute the depth resources.
Daniel Berlin25db4f42015-04-15 17:41:42 +0000474 computeDepthResources(I);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000475 }
476
477 // Run a downwards post-order search for the trace end.
478 Bounds.Downward = true;
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000479 Bounds.Visited.clear();
Daniel Berlin25db4f42015-04-15 17:41:42 +0000480 for (auto I : post_order_ext(MBB, Bounds)) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000481 DEBUG(dbgs() << " succ for BB#" << I->getNumber() << ": ");
482 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
483 // All the successors have been visited, pick the preferred one.
Daniel Berlin25db4f42015-04-15 17:41:42 +0000484 TBI.Succ = pickTraceSucc(I);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000485 DEBUG({
Jakob Stoklund Olesenc14cf572012-07-30 23:15:10 +0000486 if (TBI.Succ)
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000487 dbgs() << "BB#" << TBI.Succ->getNumber() << '\n';
488 else
489 dbgs() << "null\n";
490 });
491 // The trace leaving I is now known, compute the height resources.
Daniel Berlin25db4f42015-04-15 17:41:42 +0000492 computeHeightResources(I);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000493 }
494}
495
496/// Invalidate traces through BadMBB.
497void
498MachineTraceMetrics::Ensemble::invalidate(const MachineBasicBlock *BadMBB) {
499 SmallVector<const MachineBasicBlock*, 16> WorkList;
500 TraceBlockInfo &BadTBI = BlockInfo[BadMBB->getNumber()];
501
502 // Invalidate height resources of blocks above MBB.
503 if (BadTBI.hasValidHeight()) {
504 BadTBI.invalidateHeight();
505 WorkList.push_back(BadMBB);
506 do {
507 const MachineBasicBlock *MBB = WorkList.pop_back_val();
508 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
509 << " height.\n");
510 // Find any MBB predecessors that have MBB as their preferred successor.
511 // They are the only ones that need to be invalidated.
Sanjay Pateld2b71442015-07-06 16:27:35 +0000512 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
513 TraceBlockInfo &TBI = BlockInfo[Pred->getNumber()];
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000514 if (!TBI.hasValidHeight())
515 continue;
516 if (TBI.Succ == MBB) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000517 TBI.invalidateHeight();
Sanjay Pateld2b71442015-07-06 16:27:35 +0000518 WorkList.push_back(Pred);
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000519 continue;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000520 }
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000521 // Verify that TBI.Succ is actually a *I successor.
Sanjay Pateld2b71442015-07-06 16:27:35 +0000522 assert((!TBI.Succ || Pred->isSuccessor(TBI.Succ)) && "CFG changed");
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000523 }
524 } while (!WorkList.empty());
525 }
526
527 // Invalidate depth resources of blocks below MBB.
528 if (BadTBI.hasValidDepth()) {
529 BadTBI.invalidateDepth();
530 WorkList.push_back(BadMBB);
531 do {
532 const MachineBasicBlock *MBB = WorkList.pop_back_val();
533 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
534 << " depth.\n");
535 // Find any MBB successors that have MBB as their preferred predecessor.
536 // They are the only ones that need to be invalidated.
Sanjay Pateld2b71442015-07-06 16:27:35 +0000537 for (const MachineBasicBlock *Succ : MBB->successors()) {
538 TraceBlockInfo &TBI = BlockInfo[Succ->getNumber()];
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000539 if (!TBI.hasValidDepth())
540 continue;
541 if (TBI.Pred == MBB) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000542 TBI.invalidateDepth();
Sanjay Pateld2b71442015-07-06 16:27:35 +0000543 WorkList.push_back(Succ);
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000544 continue;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000545 }
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000546 // Verify that TBI.Pred is actually a *I predecessor.
Sanjay Pateld2b71442015-07-06 16:27:35 +0000547 assert((!TBI.Pred || Succ->isPredecessor(TBI.Pred)) && "CFG changed");
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000548 }
549 } while (!WorkList.empty());
550 }
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000551
552 // Clear any per-instruction data. We only have to do this for BadMBB itself
553 // because the instructions in that block may change. Other blocks may be
554 // invalidated, but their instructions will stay the same, so there is no
555 // need to erase the Cycle entries. They will be overwritten when we
556 // recompute.
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000557 for (const auto &I : *BadMBB)
558 Cycles.erase(&I);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000559}
560
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000561void MachineTraceMetrics::Ensemble::verify() const {
562#ifndef NDEBUG
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000563 assert(BlockInfo.size() == MTM.MF->getNumBlockIDs() &&
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000564 "Outdated BlockInfo size");
565 for (unsigned Num = 0, e = BlockInfo.size(); Num != e; ++Num) {
566 const TraceBlockInfo &TBI = BlockInfo[Num];
567 if (TBI.hasValidDepth() && TBI.Pred) {
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000568 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000569 assert(MBB->isPredecessor(TBI.Pred) && "CFG doesn't match trace");
570 assert(BlockInfo[TBI.Pred->getNumber()].hasValidDepth() &&
571 "Trace is broken, depth should have been invalidated.");
572 const MachineLoop *Loop = getLoopFor(MBB);
573 assert(!(Loop && MBB == Loop->getHeader()) && "Trace contains backedge");
574 }
575 if (TBI.hasValidHeight() && TBI.Succ) {
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000576 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000577 assert(MBB->isSuccessor(TBI.Succ) && "CFG doesn't match trace");
578 assert(BlockInfo[TBI.Succ->getNumber()].hasValidHeight() &&
579 "Trace is broken, height should have been invalidated.");
580 const MachineLoop *Loop = getLoopFor(MBB);
581 const MachineLoop *SuccLoop = getLoopFor(TBI.Succ);
582 assert(!(Loop && Loop == SuccLoop && TBI.Succ == Loop->getHeader()) &&
583 "Trace contains backedge");
584 }
585 }
586#endif
587}
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000588
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000589//===----------------------------------------------------------------------===//
590// Data Dependencies
591//===----------------------------------------------------------------------===//
592//
593// Compute the depth and height of each instruction based on data dependencies
594// and instruction latencies. These cycle numbers assume that the CPU can issue
595// an infinite number of instructions per cycle as long as their dependencies
596// are ready.
597
598// A data dependency is represented as a defining MI and operand numbers on the
599// defining and using MI.
600namespace {
601struct DataDep {
602 const MachineInstr *DefMI;
603 unsigned DefOp;
604 unsigned UseOp;
Jakob Stoklund Olesen5e19d352012-08-01 16:02:59 +0000605
606 DataDep(const MachineInstr *DefMI, unsigned DefOp, unsigned UseOp)
607 : DefMI(DefMI), DefOp(DefOp), UseOp(UseOp) {}
608
609 /// Create a DataDep from an SSA form virtual register.
610 DataDep(const MachineRegisterInfo *MRI, unsigned VirtReg, unsigned UseOp)
611 : UseOp(UseOp) {
612 assert(TargetRegisterInfo::isVirtualRegister(VirtReg));
613 MachineRegisterInfo::def_iterator DefI = MRI->def_begin(VirtReg);
614 assert(!DefI.atEnd() && "Register has no defs");
Owen Anderson16c6bf42014-03-13 23:12:04 +0000615 DefMI = DefI->getParent();
Jakob Stoklund Olesen5e19d352012-08-01 16:02:59 +0000616 DefOp = DefI.getOperandNo();
617 assert((++DefI).atEnd() && "Register has multiple defs");
618 }
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000619};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000620}
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000621
622// Get the input data dependencies that must be ready before UseMI can issue.
623// Return true if UseMI has any physreg operands.
624static bool getDataDeps(const MachineInstr *UseMI,
625 SmallVectorImpl<DataDep> &Deps,
626 const MachineRegisterInfo *MRI) {
627 bool HasPhysRegs = false;
Matthias Braune41e1462015-05-29 02:56:46 +0000628 for (MachineInstr::const_mop_iterator I = UseMI->operands_begin(),
629 E = UseMI->operands_end(); I != E; ++I) {
630 const MachineOperand &MO = *I;
631 if (!MO.isReg())
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000632 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000633 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000634 if (!Reg)
635 continue;
636 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
637 HasPhysRegs = true;
638 continue;
639 }
640 // Collect virtual register reads.
Matthias Braune41e1462015-05-29 02:56:46 +0000641 if (MO.readsReg())
642 Deps.push_back(DataDep(MRI, Reg, UseMI->getOperandNo(I)));
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000643 }
644 return HasPhysRegs;
645}
646
647// Get the input data dependencies of a PHI instruction, using Pred as the
648// preferred predecessor.
649// This will add at most one dependency to Deps.
650static void getPHIDeps(const MachineInstr *UseMI,
651 SmallVectorImpl<DataDep> &Deps,
652 const MachineBasicBlock *Pred,
653 const MachineRegisterInfo *MRI) {
654 // No predecessor at the beginning of a trace. Ignore dependencies.
655 if (!Pred)
656 return;
657 assert(UseMI->isPHI() && UseMI->getNumOperands() % 2 && "Bad PHI");
658 for (unsigned i = 1; i != UseMI->getNumOperands(); i += 2) {
659 if (UseMI->getOperand(i + 1).getMBB() == Pred) {
660 unsigned Reg = UseMI->getOperand(i).getReg();
Jakob Stoklund Olesen5e19d352012-08-01 16:02:59 +0000661 Deps.push_back(DataDep(MRI, Reg, i));
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000662 return;
663 }
664 }
665}
666
667// Keep track of physreg data dependencies by recording each live register unit.
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000668// Associate each regunit with an instruction operand. Depending on the
669// direction instructions are scanned, it could be the operand that defined the
670// regunit, or the highest operand to read the regunit.
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000671namespace {
672struct LiveRegUnit {
673 unsigned RegUnit;
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000674 unsigned Cycle;
675 const MachineInstr *MI;
676 unsigned Op;
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000677
678 unsigned getSparseSetIndex() const { return RegUnit; }
679
Craig Topperc0196b12014-04-14 00:51:57 +0000680 LiveRegUnit(unsigned RU) : RegUnit(RU), Cycle(0), MI(nullptr), Op(0) {}
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000681};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000682}
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000683
684// Identify physreg dependencies for UseMI, and update the live regunit
685// tracking set when scanning instructions downwards.
686static void updatePhysDepsDownwards(const MachineInstr *UseMI,
687 SmallVectorImpl<DataDep> &Deps,
688 SparseSet<LiveRegUnit> &RegUnits,
689 const TargetRegisterInfo *TRI) {
690 SmallVector<unsigned, 8> Kills;
691 SmallVector<unsigned, 8> LiveDefOps;
692
Matthias Braune41e1462015-05-29 02:56:46 +0000693 for (MachineInstr::const_mop_iterator MI = UseMI->operands_begin(),
694 ME = UseMI->operands_end(); MI != ME; ++MI) {
695 const MachineOperand &MO = *MI;
696 if (!MO.isReg())
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000697 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000698 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000699 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
700 continue;
701 // Track live defs and kills for updating RegUnits.
Matthias Braune41e1462015-05-29 02:56:46 +0000702 if (MO.isDef()) {
703 if (MO.isDead())
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000704 Kills.push_back(Reg);
705 else
Matthias Braune41e1462015-05-29 02:56:46 +0000706 LiveDefOps.push_back(UseMI->getOperandNo(MI));
707 } else if (MO.isKill())
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000708 Kills.push_back(Reg);
709 // Identify dependencies.
Matthias Braune41e1462015-05-29 02:56:46 +0000710 if (!MO.readsReg())
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000711 continue;
712 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
713 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
714 if (I == RegUnits.end())
715 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000716 Deps.push_back(DataDep(I->MI, I->Op, UseMI->getOperandNo(MI)));
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000717 break;
718 }
719 }
720
721 // Update RegUnits to reflect live registers after UseMI.
722 // First kills.
723 for (unsigned i = 0, e = Kills.size(); i != e; ++i)
724 for (MCRegUnitIterator Units(Kills[i], TRI); Units.isValid(); ++Units)
725 RegUnits.erase(*Units);
726
727 // Second, live defs.
728 for (unsigned i = 0, e = LiveDefOps.size(); i != e; ++i) {
729 unsigned DefOp = LiveDefOps[i];
730 for (MCRegUnitIterator Units(UseMI->getOperand(DefOp).getReg(), TRI);
731 Units.isValid(); ++Units) {
732 LiveRegUnit &LRU = RegUnits[*Units];
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000733 LRU.MI = UseMI;
734 LRU.Op = DefOp;
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000735 }
736 }
737}
738
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000739/// The length of the critical path through a trace is the maximum of two path
740/// lengths:
741///
742/// 1. The maximum height+depth over all instructions in the trace center block.
743///
744/// 2. The longest cross-block dependency chain. For small blocks, it is
745/// possible that the critical path through the trace doesn't include any
746/// instructions in the block.
747///
748/// This function computes the second number from the live-in list of the
749/// center block.
750unsigned MachineTraceMetrics::Ensemble::
751computeCrossBlockCriticalPath(const TraceBlockInfo &TBI) {
752 assert(TBI.HasValidInstrDepths && "Missing depth info");
753 assert(TBI.HasValidInstrHeights && "Missing height info");
754 unsigned MaxLen = 0;
755 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
756 const LiveInReg &LIR = TBI.LiveIns[i];
757 if (!TargetRegisterInfo::isVirtualRegister(LIR.Reg))
758 continue;
759 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
760 // Ignore dependencies outside the current trace.
761 const TraceBlockInfo &DefTBI = BlockInfo[DefMI->getParent()->getNumber()];
Jakob Stoklund Olesen299cedc2013-03-07 23:55:49 +0000762 if (!DefTBI.isUsefulDominator(TBI))
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000763 continue;
764 unsigned Len = LIR.Height + Cycles[DefMI].Depth;
765 MaxLen = std::max(MaxLen, Len);
766 }
767 return MaxLen;
768}
769
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000770/// Compute instruction depths for all instructions above or in MBB in its
771/// trace. This assumes that the trace through MBB has already been computed.
772void MachineTraceMetrics::Ensemble::
773computeInstrDepths(const MachineBasicBlock *MBB) {
774 // The top of the trace may already be computed, and HasValidInstrDepths
775 // implies Head->HasValidInstrDepths, so we only need to start from the first
776 // block in the trace that needs to be recomputed.
777 SmallVector<const MachineBasicBlock*, 8> Stack;
778 do {
779 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
780 assert(TBI.hasValidDepth() && "Incomplete trace");
781 if (TBI.HasValidInstrDepths)
782 break;
783 Stack.push_back(MBB);
784 MBB = TBI.Pred;
785 } while (MBB);
786
787 // FIXME: If MBB is non-null at this point, it is the last pre-computed block
788 // in the trace. We should track any live-out physregs that were defined in
789 // the trace. This is quite rare in SSA form, typically created by CSE
790 // hoisting a compare.
791 SparseSet<LiveRegUnit> RegUnits;
792 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
793
794 // Go through trace blocks in top-down order, stopping after the center block.
795 SmallVector<DataDep, 8> Deps;
796 while (!Stack.empty()) {
797 MBB = Stack.pop_back_val();
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000798 DEBUG(dbgs() << "\nDepths for BB#" << MBB->getNumber() << ":\n");
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000799 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
800 TBI.HasValidInstrDepths = true;
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000801 TBI.CriticalPath = 0;
802
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000803 // Print out resource depths here as well.
804 DEBUG({
805 dbgs() << format("%7u Instructions\n", TBI.InstrDepth);
806 ArrayRef<unsigned> PRDepths = getProcResourceDepths(MBB->getNumber());
807 for (unsigned K = 0; K != PRDepths.size(); ++K)
808 if (PRDepths[K]) {
809 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
810 dbgs() << format("%6uc @ ", MTM.getCycles(PRDepths[K]))
811 << MTM.SchedModel.getProcResource(K)->Name << " ("
812 << PRDepths[K]/Factor << " ops x" << Factor << ")\n";
813 }
814 });
815
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000816 // Also compute the critical path length through MBB when possible.
817 if (TBI.HasValidInstrHeights)
818 TBI.CriticalPath = computeCrossBlockCriticalPath(TBI);
819
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000820 for (const auto &UseMI : *MBB) {
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000821 // Collect all data dependencies.
822 Deps.clear();
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000823 if (UseMI.isPHI())
824 getPHIDeps(&UseMI, Deps, TBI.Pred, MTM.MRI);
825 else if (getDataDeps(&UseMI, Deps, MTM.MRI))
826 updatePhysDepsDownwards(&UseMI, Deps, RegUnits, MTM.TRI);
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000827
828 // Filter and process dependencies, computing the earliest issue cycle.
829 unsigned Cycle = 0;
Sanjay Patel0ca438c2015-06-30 16:30:22 +0000830 for (const DataDep &Dep : Deps) {
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000831 const TraceBlockInfo&DepTBI =
832 BlockInfo[Dep.DefMI->getParent()->getNumber()];
833 // Ignore dependencies from outside the current trace.
Jakob Stoklund Olesen299cedc2013-03-07 23:55:49 +0000834 if (!DepTBI.isUsefulDominator(TBI))
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000835 continue;
836 assert(DepTBI.HasValidInstrDepths && "Inconsistent dependency");
837 unsigned DepCycle = Cycles.lookup(Dep.DefMI).Depth;
838 // Add latency if DefMI is a real instruction. Transients get latency 0.
839 if (!Dep.DefMI->isTransient())
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +0000840 DepCycle += MTM.SchedModel
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000841 .computeOperandLatency(Dep.DefMI, Dep.DefOp, &UseMI, Dep.UseOp);
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000842 Cycle = std::max(Cycle, DepCycle);
843 }
844 // Remember the instruction depth.
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000845 InstrCycles &MICycles = Cycles[&UseMI];
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000846 MICycles.Depth = Cycle;
847
848 if (!TBI.HasValidInstrHeights) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000849 DEBUG(dbgs() << Cycle << '\t' << UseMI);
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000850 continue;
851 }
852 // Update critical path length.
853 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Height);
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000854 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << UseMI);
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000855 }
856 }
857}
858
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000859// Identify physreg dependencies for MI when scanning instructions upwards.
860// Return the issue height of MI after considering any live regunits.
861// Height is the issue height computed from virtual register dependencies alone.
862static unsigned updatePhysDepsUpwards(const MachineInstr *MI, unsigned Height,
863 SparseSet<LiveRegUnit> &RegUnits,
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +0000864 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000865 const TargetInstrInfo *TII,
866 const TargetRegisterInfo *TRI) {
867 SmallVector<unsigned, 8> ReadOps;
Matthias Braune41e1462015-05-29 02:56:46 +0000868
869 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
870 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
871 const MachineOperand &MO = *MOI;
872 if (!MO.isReg())
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000873 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000874 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000875 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
876 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000877 if (MO.readsReg())
878 ReadOps.push_back(MI->getOperandNo(MOI));
879 if (!MO.isDef())
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000880 continue;
881 // This is a def of Reg. Remove corresponding entries from RegUnits, and
882 // update MI Height to consider the physreg dependencies.
883 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
884 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
885 if (I == RegUnits.end())
886 continue;
887 unsigned DepHeight = I->Cycle;
888 if (!MI->isTransient()) {
889 // We may not know the UseMI of this dependency, if it came from the
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +0000890 // live-in list. SchedModel can handle a NULL UseMI.
891 DepHeight += SchedModel
Matthias Braune41e1462015-05-29 02:56:46 +0000892 .computeOperandLatency(MI, MI->getOperandNo(MOI), I->MI, I->Op);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000893 }
894 Height = std::max(Height, DepHeight);
895 // This regunit is dead above MI.
896 RegUnits.erase(I);
897 }
898 }
899
900 // Now we know the height of MI. Update any regunits read.
901 for (unsigned i = 0, e = ReadOps.size(); i != e; ++i) {
902 unsigned Reg = MI->getOperand(ReadOps[i]).getReg();
903 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
904 LiveRegUnit &LRU = RegUnits[*Units];
905 // Set the height to the highest reader of the unit.
906 if (LRU.Cycle <= Height && LRU.MI != MI) {
907 LRU.Cycle = Height;
908 LRU.MI = MI;
909 LRU.Op = ReadOps[i];
910 }
911 }
912 }
913
914 return Height;
915}
916
917
918typedef DenseMap<const MachineInstr *, unsigned> MIHeightMap;
919
920// Push the height of DefMI upwards if required to match UseMI.
921// Return true if this is the first time DefMI was seen.
922static bool pushDepHeight(const DataDep &Dep,
923 const MachineInstr *UseMI, unsigned UseHeight,
924 MIHeightMap &Heights,
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +0000925 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000926 const TargetInstrInfo *TII) {
927 // Adjust height by Dep.DefMI latency.
928 if (!Dep.DefMI->isTransient())
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +0000929 UseHeight += SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp,
Andrew Trickde2109e2013-06-15 04:49:57 +0000930 UseMI, Dep.UseOp);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000931
932 // Update Heights[DefMI] to be the maximum height seen.
933 MIHeightMap::iterator I;
934 bool New;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000935 std::tie(I, New) = Heights.insert(std::make_pair(Dep.DefMI, UseHeight));
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000936 if (New)
937 return true;
938
939 // DefMI has been pushed before. Give it the max height.
940 if (I->second < UseHeight)
941 I->second = UseHeight;
942 return false;
943}
944
Jakob Stoklund Olesend0d78602012-10-11 16:46:07 +0000945/// Assuming that the virtual register defined by DefMI:DefOp was used by
946/// Trace.back(), add it to the live-in lists of all the blocks in Trace. Stop
947/// when reaching the block that contains DefMI.
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000948void MachineTraceMetrics::Ensemble::
Jakob Stoklund Olesend0d78602012-10-11 16:46:07 +0000949addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000950 ArrayRef<const MachineBasicBlock*> Trace) {
951 assert(!Trace.empty() && "Trace should contain at least one block");
Jakob Stoklund Olesend0d78602012-10-11 16:46:07 +0000952 unsigned Reg = DefMI->getOperand(DefOp).getReg();
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000953 assert(TargetRegisterInfo::isVirtualRegister(Reg));
954 const MachineBasicBlock *DefMBB = DefMI->getParent();
955
956 // Reg is live-in to all blocks in Trace that follow DefMBB.
957 for (unsigned i = Trace.size(); i; --i) {
958 const MachineBasicBlock *MBB = Trace[i-1];
959 if (MBB == DefMBB)
960 return;
961 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
962 // Just add the register. The height will be updated later.
963 TBI.LiveIns.push_back(Reg);
964 }
965}
966
967/// Compute instruction heights in the trace through MBB. This updates MBB and
968/// the blocks below it in the trace. It is assumed that the trace has already
969/// been computed.
970void MachineTraceMetrics::Ensemble::
971computeInstrHeights(const MachineBasicBlock *MBB) {
972 // The bottom of the trace may already be computed.
973 // Find the blocks that need updating.
974 SmallVector<const MachineBasicBlock*, 8> Stack;
975 do {
976 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
977 assert(TBI.hasValidHeight() && "Incomplete trace");
978 if (TBI.HasValidInstrHeights)
979 break;
980 Stack.push_back(MBB);
981 TBI.LiveIns.clear();
982 MBB = TBI.Succ;
983 } while (MBB);
984
985 // As we move upwards in the trace, keep track of instructions that are
986 // required by deeper trace instructions. Map MI -> height required so far.
987 MIHeightMap Heights;
988
989 // For physregs, the def isn't known when we see the use.
990 // Instead, keep track of the highest use of each regunit.
991 SparseSet<LiveRegUnit> RegUnits;
992 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
993
994 // If the bottom of the trace was already precomputed, initialize heights
995 // from its live-in list.
996 // MBB is the highest precomputed block in the trace.
997 if (MBB) {
998 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
Sanjay Patel6d4c3e32015-07-06 16:19:14 +0000999 for (LiveInReg &LI : TBI.LiveIns) {
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001000 if (TargetRegisterInfo::isVirtualRegister(LI.Reg)) {
1001 // For virtual registers, the def latency is included.
1002 unsigned &Height = Heights[MTM.MRI->getVRegDef(LI.Reg)];
1003 if (Height < LI.Height)
1004 Height = LI.Height;
1005 } else {
1006 // For register units, the def latency is not included because we don't
1007 // know the def yet.
1008 RegUnits[LI.Reg].Cycle = LI.Height;
1009 }
1010 }
1011 }
1012
1013 // Go through the trace blocks in bottom-up order.
1014 SmallVector<DataDep, 8> Deps;
1015 for (;!Stack.empty(); Stack.pop_back()) {
1016 MBB = Stack.back();
1017 DEBUG(dbgs() << "Heights for BB#" << MBB->getNumber() << ":\n");
1018 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1019 TBI.HasValidInstrHeights = true;
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001020 TBI.CriticalPath = 0;
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001021
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001022 DEBUG({
1023 dbgs() << format("%7u Instructions\n", TBI.InstrHeight);
1024 ArrayRef<unsigned> PRHeights = getProcResourceHeights(MBB->getNumber());
1025 for (unsigned K = 0; K != PRHeights.size(); ++K)
1026 if (PRHeights[K]) {
1027 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
1028 dbgs() << format("%6uc @ ", MTM.getCycles(PRHeights[K]))
1029 << MTM.SchedModel.getProcResource(K)->Name << " ("
1030 << PRHeights[K]/Factor << " ops x" << Factor << ")\n";
1031 }
1032 });
1033
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001034 // Get dependencies from PHIs in the trace successor.
Jakob Stoklund Olesen0954d412012-08-10 20:11:38 +00001035 const MachineBasicBlock *Succ = TBI.Succ;
1036 // If MBB is the last block in the trace, and it has a back-edge to the
1037 // loop header, get loop-carried dependencies from PHIs in the header. For
1038 // that purpose, pretend that all the loop header PHIs have height 0.
1039 if (!Succ)
1040 if (const MachineLoop *Loop = getLoopFor(MBB))
1041 if (MBB->isSuccessor(Loop->getHeader()))
1042 Succ = Loop->getHeader();
1043
1044 if (Succ) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001045 for (const auto &PHI : *Succ) {
1046 if (!PHI.isPHI())
1047 break;
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001048 Deps.clear();
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001049 getPHIDeps(&PHI, Deps, MBB, MTM.MRI);
Jakob Stoklund Olesen0954d412012-08-10 20:11:38 +00001050 if (!Deps.empty()) {
1051 // Loop header PHI heights are all 0.
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001052 unsigned Height = TBI.Succ ? Cycles.lookup(&PHI).Height : 0;
1053 DEBUG(dbgs() << "pred\t" << Height << '\t' << PHI);
1054 if (pushDepHeight(Deps.front(), &PHI, Height,
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +00001055 Heights, MTM.SchedModel, MTM.TII))
Jakob Stoklund Olesend0d78602012-10-11 16:46:07 +00001056 addLiveIns(Deps.front().DefMI, Deps.front().DefOp, Stack);
Jakob Stoklund Olesen0954d412012-08-10 20:11:38 +00001057 }
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001058 }
1059 }
1060
1061 // Go through the block backwards.
1062 for (MachineBasicBlock::const_iterator BI = MBB->end(), BB = MBB->begin();
1063 BI != BB;) {
1064 const MachineInstr *MI = --BI;
1065
1066 // Find the MI height as determined by virtual register uses in the
1067 // trace below.
1068 unsigned Cycle = 0;
1069 MIHeightMap::iterator HeightI = Heights.find(MI);
1070 if (HeightI != Heights.end()) {
1071 Cycle = HeightI->second;
1072 // We won't be seeing any more MI uses.
1073 Heights.erase(HeightI);
1074 }
1075
1076 // Don't process PHI deps. They depend on the specific predecessor, and
1077 // we'll get them when visiting the predecessor.
1078 Deps.clear();
1079 bool HasPhysRegs = !MI->isPHI() && getDataDeps(MI, Deps, MTM.MRI);
1080
1081 // There may also be regunit dependencies to include in the height.
1082 if (HasPhysRegs)
1083 Cycle = updatePhysDepsUpwards(MI, Cycle, RegUnits,
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +00001084 MTM.SchedModel, MTM.TII, MTM.TRI);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001085
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001086 // Update the required height of any virtual registers read by MI.
Sanjay Patel0ca438c2015-06-30 16:30:22 +00001087 for (const DataDep &Dep : Deps)
1088 if (pushDepHeight(Dep, MI, Cycle, Heights, MTM.SchedModel, MTM.TII))
1089 addLiveIns(Dep.DefMI, Dep.DefOp, Stack);
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001090
1091 InstrCycles &MICycles = Cycles[MI];
1092 MICycles.Height = Cycle;
1093 if (!TBI.HasValidInstrDepths) {
1094 DEBUG(dbgs() << Cycle << '\t' << *MI);
1095 continue;
1096 }
1097 // Update critical path length.
1098 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Depth);
1099 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << *MI);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001100 }
1101
1102 // Update virtual live-in heights. They were added by addLiveIns() with a 0
1103 // height because the final height isn't known until now.
1104 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " Live-ins:");
Sanjay Patel0ca438c2015-06-30 16:30:22 +00001105 for (LiveInReg &LIR : TBI.LiveIns) {
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001106 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
1107 LIR.Height = Heights.lookup(DefMI);
1108 DEBUG(dbgs() << ' ' << PrintReg(LIR.Reg) << '@' << LIR.Height);
1109 }
1110
1111 // Transfer the live regunits to the live-in list.
1112 for (SparseSet<LiveRegUnit>::const_iterator
1113 RI = RegUnits.begin(), RE = RegUnits.end(); RI != RE; ++RI) {
1114 TBI.LiveIns.push_back(LiveInReg(RI->RegUnit, RI->Cycle));
1115 DEBUG(dbgs() << ' ' << PrintRegUnit(RI->RegUnit, MTM.TRI)
1116 << '@' << RI->Cycle);
1117 }
1118 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001119
1120 if (!TBI.HasValidInstrDepths)
1121 continue;
1122 // Add live-ins to the critical path length.
1123 TBI.CriticalPath = std::max(TBI.CriticalPath,
1124 computeCrossBlockCriticalPath(TBI));
1125 DEBUG(dbgs() << "Critical path: " << TBI.CriticalPath << '\n');
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001126 }
1127}
1128
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001129MachineTraceMetrics::Trace
1130MachineTraceMetrics::Ensemble::getTrace(const MachineBasicBlock *MBB) {
Sanjay Patel82db3b72015-07-04 15:00:28 +00001131 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1132
1133 if (!TBI.hasValidDepth() || !TBI.hasValidHeight())
1134 computeTrace(MBB);
1135 if (!TBI.HasValidInstrDepths)
1136 computeInstrDepths(MBB);
1137 if (!TBI.HasValidInstrHeights)
1138 computeInstrHeights(MBB);
1139
1140 return Trace(*this, TBI);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001141}
1142
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001143unsigned
1144MachineTraceMetrics::Trace::getInstrSlack(const MachineInstr *MI) const {
1145 assert(MI && "Not an instruction.");
1146 assert(getBlockNum() == unsigned(MI->getParent()->getNumber()) &&
1147 "MI must be in the trace center block");
1148 InstrCycles Cyc = getInstrCycles(MI);
1149 return getCriticalPath() - (Cyc.Depth + Cyc.Height);
1150}
1151
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001152unsigned
1153MachineTraceMetrics::Trace::getPHIDepth(const MachineInstr *PHI) const {
1154 const MachineBasicBlock *MBB = TE.MTM.MF->getBlockNumbered(getBlockNum());
1155 SmallVector<DataDep, 1> Deps;
1156 getPHIDeps(PHI, Deps, MBB, TE.MTM.MRI);
1157 assert(Deps.size() == 1 && "PHI doesn't have MBB as a predecessor");
1158 DataDep &Dep = Deps.front();
1159 unsigned DepCycle = getInstrCycles(Dep.DefMI).Depth;
1160 // Add latency if DefMI is a real instruction. Transients get latency 0.
1161 if (!Dep.DefMI->isTransient())
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +00001162 DepCycle += TE.MTM.SchedModel
Andrew Trickde2109e2013-06-15 04:49:57 +00001163 .computeOperandLatency(Dep.DefMI, Dep.DefOp, PHI, Dep.UseOp);
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001164 return DepCycle;
1165}
1166
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001167/// When bottom is set include instructions in current block in estimate.
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001168unsigned MachineTraceMetrics::Trace::getResourceDepth(bool Bottom) const {
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001169 // Find the limiting processor resource.
1170 // Numbers have been pre-scaled to be comparable.
1171 unsigned PRMax = 0;
1172 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1173 if (Bottom) {
1174 ArrayRef<unsigned> PRCycles = TE.MTM.getProcResourceCycles(getBlockNum());
1175 for (unsigned K = 0; K != PRDepths.size(); ++K)
1176 PRMax = std::max(PRMax, PRDepths[K] + PRCycles[K]);
1177 } else {
1178 for (unsigned K = 0; K != PRDepths.size(); ++K)
1179 PRMax = std::max(PRMax, PRDepths[K]);
1180 }
1181 // Convert to cycle count.
1182 PRMax = TE.MTM.getCycles(PRMax);
1183
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001184 /// All instructions before current block
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001185 unsigned Instrs = TBI.InstrDepth;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001186 // plus instructions in current block
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001187 if (Bottom)
1188 Instrs += TE.MTM.BlockInfo[getBlockNum()].InstrCount;
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +00001189 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1190 Instrs /= IW;
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001191 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001192 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001193}
1194
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001195unsigned MachineTraceMetrics::Trace::getResourceLength(
1196 ArrayRef<const MachineBasicBlock *> Extrablocks,
1197 ArrayRef<const MCSchedClassDesc *> ExtraInstrs,
1198 ArrayRef<const MCSchedClassDesc *> RemoveInstrs) const {
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001199 // Add up resources above and below the center block.
1200 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1201 ArrayRef<unsigned> PRHeights = TE.getProcResourceHeights(getBlockNum());
1202 unsigned PRMax = 0;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001203
1204 // Capture computing cycles from extra instructions
1205 auto extraCycles = [this](ArrayRef<const MCSchedClassDesc *> Instrs,
1206 unsigned ResourceIdx)
1207 ->unsigned {
1208 unsigned Cycles = 0;
Sanjay Patel6d4c3e32015-07-06 16:19:14 +00001209 for (const MCSchedClassDesc *SC : Instrs) {
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001210 if (!SC->isValid())
1211 continue;
1212 for (TargetSchedModel::ProcResIter
1213 PI = TE.MTM.SchedModel.getWriteProcResBegin(SC),
1214 PE = TE.MTM.SchedModel.getWriteProcResEnd(SC);
1215 PI != PE; ++PI) {
1216 if (PI->ProcResourceIdx != ResourceIdx)
1217 continue;
1218 Cycles +=
1219 (PI->Cycles * TE.MTM.SchedModel.getResourceFactor(ResourceIdx));
1220 }
1221 }
1222 return Cycles;
1223 };
1224
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001225 for (unsigned K = 0; K != PRDepths.size(); ++K) {
1226 unsigned PRCycles = PRDepths[K] + PRHeights[K];
Sanjay Patel6d4c3e32015-07-06 16:19:14 +00001227 for (const MachineBasicBlock *MBB : Extrablocks)
1228 PRCycles += TE.MTM.getProcResourceCycles(MBB->getNumber())[K];
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001229 PRCycles += extraCycles(ExtraInstrs, K);
1230 PRCycles -= extraCycles(RemoveInstrs, K);
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001231 PRMax = std::max(PRMax, PRCycles);
1232 }
1233 // Convert to cycle count.
1234 PRMax = TE.MTM.getCycles(PRMax);
1235
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001236 // Instrs: #instructions in current trace outside current block.
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001237 unsigned Instrs = TBI.InstrDepth + TBI.InstrHeight;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001238 // Add instruction count from the extra blocks.
Sanjay Patel6d4c3e32015-07-06 16:19:14 +00001239 for (const MachineBasicBlock *MBB : Extrablocks)
1240 Instrs += TE.MTM.getResources(MBB)->InstrCount;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001241 Instrs += ExtraInstrs.size();
1242 Instrs -= RemoveInstrs.size();
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +00001243 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1244 Instrs /= IW;
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001245 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001246 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001247}
1248
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001249bool MachineTraceMetrics::Trace::isDepInTrace(const MachineInstr *DefMI,
1250 const MachineInstr *UseMI) const {
1251 if (DefMI->getParent() == UseMI->getParent())
1252 return true;
1253
1254 const TraceBlockInfo &DepTBI = TE.BlockInfo[DefMI->getParent()->getNumber()];
1255 const TraceBlockInfo &TBI = TE.BlockInfo[UseMI->getParent()->getNumber()];
1256
1257 return DepTBI.isUsefulDominator(TBI);
1258}
1259
Jakob Stoklund Olesen05633692012-07-27 23:58:38 +00001260void MachineTraceMetrics::Ensemble::print(raw_ostream &OS) const {
1261 OS << getName() << " ensemble:\n";
1262 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
1263 OS << " BB#" << i << '\t';
1264 BlockInfo[i].print(OS);
1265 OS << '\n';
1266 }
1267}
1268
1269void MachineTraceMetrics::TraceBlockInfo::print(raw_ostream &OS) const {
1270 if (hasValidDepth()) {
1271 OS << "depth=" << InstrDepth;
1272 if (Pred)
1273 OS << " pred=BB#" << Pred->getNumber();
1274 else
1275 OS << " pred=null";
1276 OS << " head=BB#" << Head;
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +00001277 if (HasValidInstrDepths)
1278 OS << " +instrs";
Jakob Stoklund Olesen05633692012-07-27 23:58:38 +00001279 } else
1280 OS << "depth invalid";
1281 OS << ", ";
1282 if (hasValidHeight()) {
1283 OS << "height=" << InstrHeight;
1284 if (Succ)
1285 OS << " succ=BB#" << Succ->getNumber();
1286 else
1287 OS << " succ=null";
1288 OS << " tail=BB#" << Tail;
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +00001289 if (HasValidInstrHeights)
1290 OS << " +instrs";
Jakob Stoklund Olesen05633692012-07-27 23:58:38 +00001291 } else
1292 OS << "height invalid";
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001293 if (HasValidInstrDepths && HasValidInstrHeights)
1294 OS << ", crit=" << CriticalPath;
Jakob Stoklund Olesen05633692012-07-27 23:58:38 +00001295}
1296
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001297void MachineTraceMetrics::Trace::print(raw_ostream &OS) const {
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +00001298 unsigned MBBNum = &TBI - &TE.BlockInfo[0];
1299
1300 OS << TE.getName() << " trace BB#" << TBI.Head << " --> BB#" << MBBNum
1301 << " --> BB#" << TBI.Tail << ':';
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001302 if (TBI.hasValidHeight() && TBI.hasValidDepth())
1303 OS << ' ' << getInstrCount() << " instrs.";
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001304 if (TBI.HasValidInstrDepths && TBI.HasValidInstrHeights)
1305 OS << ' ' << TBI.CriticalPath << " cycles.";
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001306
1307 const MachineTraceMetrics::TraceBlockInfo *Block = &TBI;
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +00001308 OS << "\nBB#" << MBBNum;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001309 while (Block->hasValidDepth() && Block->Pred) {
1310 unsigned Num = Block->Pred->getNumber();
1311 OS << " <- BB#" << Num;
1312 Block = &TE.BlockInfo[Num];
1313 }
1314
1315 Block = &TBI;
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +00001316 OS << "\n ";
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001317 while (Block->hasValidHeight() && Block->Succ) {
1318 unsigned Num = Block->Succ->getNumber();
1319 OS << " -> BB#" << Num;
1320 Block = &TE.BlockInfo[Num];
1321 }
1322 OS << '\n';
1323}