blob: ef7e525e8165dde75fcceffaad7d5cc4569bbbed [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;
Richard Trieu7a083812016-02-18 22:09:30 +0000331 if (!Best || Depth < BestDepth) {
332 Best = Pred;
333 BestDepth = Depth;
334 }
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000335 }
336 return Best;
337}
338
339// Select the preferred successor for MBB.
340const MachineBasicBlock*
341MinInstrCountEnsemble::pickTraceSucc(const MachineBasicBlock *MBB) {
342 if (MBB->pred_empty())
Craig Topperc0196b12014-04-14 00:51:57 +0000343 return nullptr;
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000344 const MachineLoop *CurLoop = getLoopFor(MBB);
Craig Topperc0196b12014-04-14 00:51:57 +0000345 const MachineBasicBlock *Best = nullptr;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000346 unsigned BestHeight = 0;
Sanjay Patel99b3aa32015-05-21 17:22:45 +0000347 for (const MachineBasicBlock *Succ : MBB->successors()) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000348 // Don't consider back-edges.
349 if (CurLoop && Succ == CurLoop->getHeader())
350 continue;
Jakob Stoklund Olesenc14cf572012-07-30 23:15:10 +0000351 // Don't consider successors exiting CurLoop.
352 if (isExitingLoop(CurLoop, getLoopFor(Succ)))
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000353 continue;
Jakob Stoklund Olesenf308c122012-07-30 21:10:27 +0000354 const MachineTraceMetrics::TraceBlockInfo *SuccTBI =
355 getHeightResources(Succ);
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000356 // Ignore cycles that aren't natural loops.
357 if (!SuccTBI)
358 continue;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000359 // Pick the successor that would give this block the smallest InstrHeight.
360 unsigned Height = SuccTBI->InstrHeight;
Richard Trieu7a083812016-02-18 22:09:30 +0000361 if (!Best || Height < BestHeight) {
362 Best = Succ;
363 BestHeight = Height;
364 }
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000365 }
366 return Best;
367}
368
369// Get an Ensemble sub-class for the requested trace strategy.
370MachineTraceMetrics::Ensemble *
371MachineTraceMetrics::getEnsemble(MachineTraceMetrics::Strategy strategy) {
372 assert(strategy < TS_NumStrategies && "Invalid trace strategy enum");
373 Ensemble *&E = Ensembles[strategy];
374 if (E)
375 return E;
376
377 // Allocate new Ensemble on demand.
378 switch (strategy) {
379 case TS_MinInstrCount: return (E = new MinInstrCountEnsemble(this));
380 default: llvm_unreachable("Invalid trace strategy enum");
381 }
382}
383
384void MachineTraceMetrics::invalidate(const MachineBasicBlock *MBB) {
385 DEBUG(dbgs() << "Invalidate traces through BB#" << MBB->getNumber() << '\n');
386 BlockInfo[MBB->getNumber()].invalidate();
387 for (unsigned i = 0; i != TS_NumStrategies; ++i)
388 if (Ensembles[i])
389 Ensembles[i]->invalidate(MBB);
390}
391
Jakob Stoklund Olesena12a7d52012-07-30 20:57:50 +0000392void MachineTraceMetrics::verifyAnalysis() const {
Jakob Stoklund Olesen68c2cd02012-07-30 23:15:12 +0000393 if (!MF)
394 return;
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000395#ifndef NDEBUG
396 assert(BlockInfo.size() == MF->getNumBlockIDs() && "Outdated BlockInfo size");
397 for (unsigned i = 0; i != TS_NumStrategies; ++i)
398 if (Ensembles[i])
399 Ensembles[i]->verify();
400#endif
401}
402
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000403//===----------------------------------------------------------------------===//
404// Trace building
405//===----------------------------------------------------------------------===//
406//
407// Traces are built by two CFG traversals. To avoid recomputing too much, use a
408// set abstraction that confines the search to the current loop, and doesn't
409// revisit blocks.
410
411namespace {
412struct LoopBounds {
413 MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> Blocks;
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000414 SmallPtrSet<const MachineBasicBlock*, 8> Visited;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000415 const MachineLoopInfo *Loops;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000416 bool Downward;
417 LoopBounds(MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> blocks,
Jakob Stoklund Olesenc14cf572012-07-30 23:15:10 +0000418 const MachineLoopInfo *loops)
419 : Blocks(blocks), Loops(loops), Downward(false) {}
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000420};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000421}
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000422
423// Specialize po_iterator_storage in order to prune the post-order traversal so
424// it is limited to the current loop and doesn't traverse the loop back edges.
425namespace llvm {
426template<>
427class po_iterator_storage<LoopBounds, true> {
428 LoopBounds &LB;
429public:
430 po_iterator_storage(LoopBounds &lb) : LB(lb) {}
431 void finishPostorder(const MachineBasicBlock*) {}
432
Tim Shene0793db2016-08-15 21:52:54 +0000433 bool insertEdge(Optional<const MachineBasicBlock *> From,
434 const MachineBasicBlock *To) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000435 // Skip already visited To blocks.
436 MachineTraceMetrics::TraceBlockInfo &TBI = LB.Blocks[To->getNumber()];
437 if (LB.Downward ? TBI.hasValidHeight() : TBI.hasValidDepth())
438 return false;
Jakob Stoklund Olesenc14cf572012-07-30 23:15:10 +0000439 // From is null once when To is the trace center block.
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000440 if (From) {
Tim Shene0793db2016-08-15 21:52:54 +0000441 if (const MachineLoop *FromLoop = LB.Loops->getLoopFor(*From)) {
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000442 // Don't follow backedges, don't leave FromLoop when going upwards.
Tim Shene0793db2016-08-15 21:52:54 +0000443 if ((LB.Downward ? To : *From) == FromLoop->getHeader())
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000444 return false;
445 // Don't leave FromLoop.
446 if (isExitingLoop(FromLoop, LB.Loops->getLoopFor(To)))
447 return false;
448 }
449 }
450 // To is a new block. Mark the block as visited in case the CFG has cycles
451 // that MachineLoopInfo didn't recognize as a natural loop.
David Blaikie70573dc2014-11-19 07:49:26 +0000452 return LB.Visited.insert(To).second;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000453 }
454};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000455}
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000456
457/// Compute the trace through MBB.
458void MachineTraceMetrics::Ensemble::computeTrace(const MachineBasicBlock *MBB) {
459 DEBUG(dbgs() << "Computing " << getName() << " trace through BB#"
460 << MBB->getNumber() << '\n');
461 // Set up loop bounds for the backwards post-order traversal.
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000462 LoopBounds Bounds(BlockInfo, MTM.Loops);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000463
464 // Run an upwards post-order search for the trace start.
465 Bounds.Downward = false;
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000466 Bounds.Visited.clear();
Daniel Berlin25db4f42015-04-15 17:41:42 +0000467 for (auto I : inverse_post_order_ext(MBB, Bounds)) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000468 DEBUG(dbgs() << " pred for BB#" << I->getNumber() << ": ");
469 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
470 // All the predecessors have been visited, pick the preferred one.
Daniel Berlin25db4f42015-04-15 17:41:42 +0000471 TBI.Pred = pickTracePred(I);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000472 DEBUG({
473 if (TBI.Pred)
474 dbgs() << "BB#" << TBI.Pred->getNumber() << '\n';
475 else
476 dbgs() << "null\n";
477 });
478 // The trace leading to I is now known, compute the depth resources.
Daniel Berlin25db4f42015-04-15 17:41:42 +0000479 computeDepthResources(I);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000480 }
481
482 // Run a downwards post-order search for the trace end.
483 Bounds.Downward = true;
Jakob Stoklund Olesenbf1ac4b2012-08-08 22:12:01 +0000484 Bounds.Visited.clear();
Daniel Berlin25db4f42015-04-15 17:41:42 +0000485 for (auto I : post_order_ext(MBB, Bounds)) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000486 DEBUG(dbgs() << " succ for BB#" << I->getNumber() << ": ");
487 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
488 // All the successors have been visited, pick the preferred one.
Daniel Berlin25db4f42015-04-15 17:41:42 +0000489 TBI.Succ = pickTraceSucc(I);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000490 DEBUG({
Jakob Stoklund Olesenc14cf572012-07-30 23:15:10 +0000491 if (TBI.Succ)
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000492 dbgs() << "BB#" << TBI.Succ->getNumber() << '\n';
493 else
494 dbgs() << "null\n";
495 });
496 // The trace leaving I is now known, compute the height resources.
Daniel Berlin25db4f42015-04-15 17:41:42 +0000497 computeHeightResources(I);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000498 }
499}
500
501/// Invalidate traces through BadMBB.
502void
503MachineTraceMetrics::Ensemble::invalidate(const MachineBasicBlock *BadMBB) {
504 SmallVector<const MachineBasicBlock*, 16> WorkList;
505 TraceBlockInfo &BadTBI = BlockInfo[BadMBB->getNumber()];
506
507 // Invalidate height resources of blocks above MBB.
508 if (BadTBI.hasValidHeight()) {
509 BadTBI.invalidateHeight();
510 WorkList.push_back(BadMBB);
511 do {
512 const MachineBasicBlock *MBB = WorkList.pop_back_val();
513 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
514 << " height.\n");
515 // Find any MBB predecessors that have MBB as their preferred successor.
516 // They are the only ones that need to be invalidated.
Sanjay Pateld2b71442015-07-06 16:27:35 +0000517 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
518 TraceBlockInfo &TBI = BlockInfo[Pred->getNumber()];
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000519 if (!TBI.hasValidHeight())
520 continue;
521 if (TBI.Succ == MBB) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000522 TBI.invalidateHeight();
Sanjay Pateld2b71442015-07-06 16:27:35 +0000523 WorkList.push_back(Pred);
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000524 continue;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000525 }
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000526 // Verify that TBI.Succ is actually a *I successor.
Sanjay Pateld2b71442015-07-06 16:27:35 +0000527 assert((!TBI.Succ || Pred->isSuccessor(TBI.Succ)) && "CFG changed");
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000528 }
529 } while (!WorkList.empty());
530 }
531
532 // Invalidate depth resources of blocks below MBB.
533 if (BadTBI.hasValidDepth()) {
534 BadTBI.invalidateDepth();
535 WorkList.push_back(BadMBB);
536 do {
537 const MachineBasicBlock *MBB = WorkList.pop_back_val();
538 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
539 << " depth.\n");
540 // Find any MBB successors that have MBB as their preferred predecessor.
541 // They are the only ones that need to be invalidated.
Sanjay Pateld2b71442015-07-06 16:27:35 +0000542 for (const MachineBasicBlock *Succ : MBB->successors()) {
543 TraceBlockInfo &TBI = BlockInfo[Succ->getNumber()];
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000544 if (!TBI.hasValidDepth())
545 continue;
546 if (TBI.Pred == MBB) {
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000547 TBI.invalidateDepth();
Sanjay Pateld2b71442015-07-06 16:27:35 +0000548 WorkList.push_back(Succ);
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000549 continue;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000550 }
Jakob Stoklund Oleseneb488fe2012-07-30 17:36:49 +0000551 // Verify that TBI.Pred is actually a *I predecessor.
Sanjay Pateld2b71442015-07-06 16:27:35 +0000552 assert((!TBI.Pred || Succ->isPredecessor(TBI.Pred)) && "CFG changed");
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000553 }
554 } while (!WorkList.empty());
555 }
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000556
557 // Clear any per-instruction data. We only have to do this for BadMBB itself
558 // because the instructions in that block may change. Other blocks may be
559 // invalidated, but their instructions will stay the same, so there is no
560 // need to erase the Cycle entries. They will be overwritten when we
561 // recompute.
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000562 for (const auto &I : *BadMBB)
563 Cycles.erase(&I);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000564}
565
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000566void MachineTraceMetrics::Ensemble::verify() const {
567#ifndef NDEBUG
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000568 assert(BlockInfo.size() == MTM.MF->getNumBlockIDs() &&
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000569 "Outdated BlockInfo size");
570 for (unsigned Num = 0, e = BlockInfo.size(); Num != e; ++Num) {
571 const TraceBlockInfo &TBI = BlockInfo[Num];
572 if (TBI.hasValidDepth() && TBI.Pred) {
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000573 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000574 assert(MBB->isPredecessor(TBI.Pred) && "CFG doesn't match trace");
575 assert(BlockInfo[TBI.Pred->getNumber()].hasValidDepth() &&
576 "Trace is broken, depth should have been invalidated.");
577 const MachineLoop *Loop = getLoopFor(MBB);
578 assert(!(Loop && MBB == Loop->getHeader()) && "Trace contains backedge");
579 }
580 if (TBI.hasValidHeight() && TBI.Succ) {
Jakob Stoklund Olesen1dfb1012012-07-31 20:25:13 +0000581 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesen3df6c462012-07-30 18:34:11 +0000582 assert(MBB->isSuccessor(TBI.Succ) && "CFG doesn't match trace");
583 assert(BlockInfo[TBI.Succ->getNumber()].hasValidHeight() &&
584 "Trace is broken, height should have been invalidated.");
585 const MachineLoop *Loop = getLoopFor(MBB);
586 const MachineLoop *SuccLoop = getLoopFor(TBI.Succ);
587 assert(!(Loop && Loop == SuccLoop && TBI.Succ == Loop->getHeader()) &&
588 "Trace contains backedge");
589 }
590 }
591#endif
592}
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +0000593
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000594//===----------------------------------------------------------------------===//
595// Data Dependencies
596//===----------------------------------------------------------------------===//
597//
598// Compute the depth and height of each instruction based on data dependencies
599// and instruction latencies. These cycle numbers assume that the CPU can issue
600// an infinite number of instructions per cycle as long as their dependencies
601// are ready.
602
603// A data dependency is represented as a defining MI and operand numbers on the
604// defining and using MI.
605namespace {
606struct DataDep {
607 const MachineInstr *DefMI;
608 unsigned DefOp;
609 unsigned UseOp;
Jakob Stoklund Olesen5e19d352012-08-01 16:02:59 +0000610
611 DataDep(const MachineInstr *DefMI, unsigned DefOp, unsigned UseOp)
612 : DefMI(DefMI), DefOp(DefOp), UseOp(UseOp) {}
613
614 /// Create a DataDep from an SSA form virtual register.
615 DataDep(const MachineRegisterInfo *MRI, unsigned VirtReg, unsigned UseOp)
616 : UseOp(UseOp) {
617 assert(TargetRegisterInfo::isVirtualRegister(VirtReg));
618 MachineRegisterInfo::def_iterator DefI = MRI->def_begin(VirtReg);
619 assert(!DefI.atEnd() && "Register has no defs");
Owen Anderson16c6bf42014-03-13 23:12:04 +0000620 DefMI = DefI->getParent();
Jakob Stoklund Olesen5e19d352012-08-01 16:02:59 +0000621 DefOp = DefI.getOperandNo();
622 assert((++DefI).atEnd() && "Register has multiple defs");
623 }
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000624};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000625}
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000626
627// Get the input data dependencies that must be ready before UseMI can issue.
628// Return true if UseMI has any physreg operands.
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +0000629static bool getDataDeps(const MachineInstr &UseMI,
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000630 SmallVectorImpl<DataDep> &Deps,
631 const MachineRegisterInfo *MRI) {
Sanjay Patelf2fa58e2015-07-23 22:56:53 +0000632 // Debug values should not be included in any calculations.
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +0000633 if (UseMI.isDebugValue())
Sanjay Patelf2fa58e2015-07-23 22:56:53 +0000634 return false;
635
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000636 bool HasPhysRegs = false;
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +0000637 for (MachineInstr::const_mop_iterator I = UseMI.operands_begin(),
638 E = UseMI.operands_end(); I != E; ++I) {
Matthias Braune41e1462015-05-29 02:56:46 +0000639 const MachineOperand &MO = *I;
640 if (!MO.isReg())
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000641 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000642 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000643 if (!Reg)
644 continue;
645 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
646 HasPhysRegs = true;
647 continue;
648 }
649 // Collect virtual register reads.
Matthias Braune41e1462015-05-29 02:56:46 +0000650 if (MO.readsReg())
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +0000651 Deps.push_back(DataDep(MRI, Reg, UseMI.getOperandNo(I)));
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000652 }
653 return HasPhysRegs;
654}
655
656// Get the input data dependencies of a PHI instruction, using Pred as the
657// preferred predecessor.
658// This will add at most one dependency to Deps.
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000659static void getPHIDeps(const MachineInstr &UseMI,
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000660 SmallVectorImpl<DataDep> &Deps,
661 const MachineBasicBlock *Pred,
662 const MachineRegisterInfo *MRI) {
663 // No predecessor at the beginning of a trace. Ignore dependencies.
664 if (!Pred)
665 return;
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000666 assert(UseMI.isPHI() && UseMI.getNumOperands() % 2 && "Bad PHI");
667 for (unsigned i = 1; i != UseMI.getNumOperands(); i += 2) {
668 if (UseMI.getOperand(i + 1).getMBB() == Pred) {
669 unsigned Reg = UseMI.getOperand(i).getReg();
Jakob Stoklund Olesen5e19d352012-08-01 16:02:59 +0000670 Deps.push_back(DataDep(MRI, Reg, i));
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000671 return;
672 }
673 }
674}
675
676// Keep track of physreg data dependencies by recording each live register unit.
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000677// Associate each regunit with an instruction operand. Depending on the
678// direction instructions are scanned, it could be the operand that defined the
679// regunit, or the highest operand to read the regunit.
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000680namespace {
681struct LiveRegUnit {
682 unsigned RegUnit;
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000683 unsigned Cycle;
684 const MachineInstr *MI;
685 unsigned Op;
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000686
687 unsigned getSparseSetIndex() const { return RegUnit; }
688
Craig Topperc0196b12014-04-14 00:51:57 +0000689 LiveRegUnit(unsigned RU) : RegUnit(RU), Cycle(0), MI(nullptr), Op(0) {}
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000690};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000691}
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000692
693// Identify physreg dependencies for UseMI, and update the live regunit
694// tracking set when scanning instructions downwards.
695static void updatePhysDepsDownwards(const MachineInstr *UseMI,
696 SmallVectorImpl<DataDep> &Deps,
697 SparseSet<LiveRegUnit> &RegUnits,
698 const TargetRegisterInfo *TRI) {
699 SmallVector<unsigned, 8> Kills;
700 SmallVector<unsigned, 8> LiveDefOps;
701
Matthias Braune41e1462015-05-29 02:56:46 +0000702 for (MachineInstr::const_mop_iterator MI = UseMI->operands_begin(),
703 ME = UseMI->operands_end(); MI != ME; ++MI) {
704 const MachineOperand &MO = *MI;
705 if (!MO.isReg())
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000706 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000707 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000708 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
709 continue;
710 // Track live defs and kills for updating RegUnits.
Matthias Braune41e1462015-05-29 02:56:46 +0000711 if (MO.isDef()) {
712 if (MO.isDead())
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000713 Kills.push_back(Reg);
714 else
Matthias Braune41e1462015-05-29 02:56:46 +0000715 LiveDefOps.push_back(UseMI->getOperandNo(MI));
716 } else if (MO.isKill())
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000717 Kills.push_back(Reg);
718 // Identify dependencies.
Matthias Braune41e1462015-05-29 02:56:46 +0000719 if (!MO.readsReg())
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000720 continue;
721 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
722 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
723 if (I == RegUnits.end())
724 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000725 Deps.push_back(DataDep(I->MI, I->Op, UseMI->getOperandNo(MI)));
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000726 break;
727 }
728 }
729
730 // Update RegUnits to reflect live registers after UseMI.
731 // First kills.
Sanjay Patel87d2ae22015-12-09 22:45:45 +0000732 for (unsigned Kill : Kills)
733 for (MCRegUnitIterator Units(Kill, TRI); Units.isValid(); ++Units)
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000734 RegUnits.erase(*Units);
735
736 // Second, live defs.
Sanjay Patel87d2ae22015-12-09 22:45:45 +0000737 for (unsigned DefOp : LiveDefOps) {
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000738 for (MCRegUnitIterator Units(UseMI->getOperand(DefOp).getReg(), TRI);
739 Units.isValid(); ++Units) {
740 LiveRegUnit &LRU = RegUnits[*Units];
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000741 LRU.MI = UseMI;
742 LRU.Op = DefOp;
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000743 }
744 }
745}
746
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000747/// The length of the critical path through a trace is the maximum of two path
748/// lengths:
749///
750/// 1. The maximum height+depth over all instructions in the trace center block.
751///
752/// 2. The longest cross-block dependency chain. For small blocks, it is
753/// possible that the critical path through the trace doesn't include any
754/// instructions in the block.
755///
756/// This function computes the second number from the live-in list of the
757/// center block.
758unsigned MachineTraceMetrics::Ensemble::
759computeCrossBlockCriticalPath(const TraceBlockInfo &TBI) {
760 assert(TBI.HasValidInstrDepths && "Missing depth info");
761 assert(TBI.HasValidInstrHeights && "Missing height info");
762 unsigned MaxLen = 0;
Sanjay Patel87d2ae22015-12-09 22:45:45 +0000763 for (const LiveInReg &LIR : TBI.LiveIns) {
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000764 if (!TargetRegisterInfo::isVirtualRegister(LIR.Reg))
765 continue;
766 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
767 // Ignore dependencies outside the current trace.
768 const TraceBlockInfo &DefTBI = BlockInfo[DefMI->getParent()->getNumber()];
Jakob Stoklund Olesen299cedc2013-03-07 23:55:49 +0000769 if (!DefTBI.isUsefulDominator(TBI))
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000770 continue;
771 unsigned Len = LIR.Height + Cycles[DefMI].Depth;
772 MaxLen = std::max(MaxLen, Len);
773 }
774 return MaxLen;
775}
776
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000777/// Compute instruction depths for all instructions above or in MBB in its
778/// trace. This assumes that the trace through MBB has already been computed.
779void MachineTraceMetrics::Ensemble::
780computeInstrDepths(const MachineBasicBlock *MBB) {
781 // The top of the trace may already be computed, and HasValidInstrDepths
782 // implies Head->HasValidInstrDepths, so we only need to start from the first
783 // block in the trace that needs to be recomputed.
784 SmallVector<const MachineBasicBlock*, 8> Stack;
785 do {
786 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
787 assert(TBI.hasValidDepth() && "Incomplete trace");
788 if (TBI.HasValidInstrDepths)
789 break;
790 Stack.push_back(MBB);
791 MBB = TBI.Pred;
792 } while (MBB);
793
794 // FIXME: If MBB is non-null at this point, it is the last pre-computed block
795 // in the trace. We should track any live-out physregs that were defined in
796 // the trace. This is quite rare in SSA form, typically created by CSE
797 // hoisting a compare.
798 SparseSet<LiveRegUnit> RegUnits;
799 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
800
801 // Go through trace blocks in top-down order, stopping after the center block.
802 SmallVector<DataDep, 8> Deps;
803 while (!Stack.empty()) {
804 MBB = Stack.pop_back_val();
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000805 DEBUG(dbgs() << "\nDepths for BB#" << MBB->getNumber() << ":\n");
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000806 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
807 TBI.HasValidInstrDepths = true;
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000808 TBI.CriticalPath = 0;
809
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +0000810 // Print out resource depths here as well.
811 DEBUG({
812 dbgs() << format("%7u Instructions\n", TBI.InstrDepth);
813 ArrayRef<unsigned> PRDepths = getProcResourceDepths(MBB->getNumber());
814 for (unsigned K = 0; K != PRDepths.size(); ++K)
815 if (PRDepths[K]) {
816 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
817 dbgs() << format("%6uc @ ", MTM.getCycles(PRDepths[K]))
818 << MTM.SchedModel.getProcResource(K)->Name << " ("
819 << PRDepths[K]/Factor << " ops x" << Factor << ")\n";
820 }
821 });
822
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000823 // Also compute the critical path length through MBB when possible.
824 if (TBI.HasValidInstrHeights)
825 TBI.CriticalPath = computeCrossBlockCriticalPath(TBI);
826
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000827 for (const auto &UseMI : *MBB) {
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000828 // Collect all data dependencies.
829 Deps.clear();
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000830 if (UseMI.isPHI())
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +0000831 getPHIDeps(UseMI, Deps, TBI.Pred, MTM.MRI);
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +0000832 else if (getDataDeps(UseMI, Deps, MTM.MRI))
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000833 updatePhysDepsDownwards(&UseMI, Deps, RegUnits, MTM.TRI);
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000834
835 // Filter and process dependencies, computing the earliest issue cycle.
836 unsigned Cycle = 0;
Sanjay Patel0ca438c2015-06-30 16:30:22 +0000837 for (const DataDep &Dep : Deps) {
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000838 const TraceBlockInfo&DepTBI =
839 BlockInfo[Dep.DefMI->getParent()->getNumber()];
840 // Ignore dependencies from outside the current trace.
Jakob Stoklund Olesen299cedc2013-03-07 23:55:49 +0000841 if (!DepTBI.isUsefulDominator(TBI))
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000842 continue;
843 assert(DepTBI.HasValidInstrDepths && "Inconsistent dependency");
844 unsigned DepCycle = Cycles.lookup(Dep.DefMI).Depth;
845 // Add latency if DefMI is a real instruction. Transients get latency 0.
846 if (!Dep.DefMI->isTransient())
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +0000847 DepCycle += MTM.SchedModel
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000848 .computeOperandLatency(Dep.DefMI, Dep.DefOp, &UseMI, Dep.UseOp);
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000849 Cycle = std::max(Cycle, DepCycle);
850 }
851 // Remember the instruction depth.
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000852 InstrCycles &MICycles = Cycles[&UseMI];
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000853 MICycles.Depth = Cycle;
854
855 if (!TBI.HasValidInstrHeights) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000856 DEBUG(dbgs() << Cycle << '\t' << UseMI);
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +0000857 continue;
858 }
859 // Update critical path length.
860 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Height);
Alexey Samsonovf74bde62014-04-30 22:17:38 +0000861 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << UseMI);
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +0000862 }
863 }
864}
865
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000866// Identify physreg dependencies for MI when scanning instructions upwards.
867// Return the issue height of MI after considering any live regunits.
868// Height is the issue height computed from virtual register dependencies alone.
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000869static unsigned updatePhysDepsUpwards(const MachineInstr &MI, unsigned Height,
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000870 SparseSet<LiveRegUnit> &RegUnits,
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +0000871 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000872 const TargetInstrInfo *TII,
873 const TargetRegisterInfo *TRI) {
874 SmallVector<unsigned, 8> ReadOps;
Matthias Braune41e1462015-05-29 02:56:46 +0000875
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000876 for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(),
877 MOE = MI.operands_end();
878 MOI != MOE; ++MOI) {
Matthias Braune41e1462015-05-29 02:56:46 +0000879 const MachineOperand &MO = *MOI;
880 if (!MO.isReg())
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000881 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000882 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000883 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
884 continue;
Matthias Braune41e1462015-05-29 02:56:46 +0000885 if (MO.readsReg())
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000886 ReadOps.push_back(MI.getOperandNo(MOI));
Matthias Braune41e1462015-05-29 02:56:46 +0000887 if (!MO.isDef())
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000888 continue;
889 // This is a def of Reg. Remove corresponding entries from RegUnits, and
890 // update MI Height to consider the physreg dependencies.
891 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
892 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
893 if (I == RegUnits.end())
894 continue;
895 unsigned DepHeight = I->Cycle;
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000896 if (!MI.isTransient()) {
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000897 // We may not know the UseMI of this dependency, if it came from the
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +0000898 // live-in list. SchedModel can handle a NULL UseMI.
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000899 DepHeight += SchedModel.computeOperandLatency(&MI, MI.getOperandNo(MOI),
900 I->MI, I->Op);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000901 }
902 Height = std::max(Height, DepHeight);
903 // This regunit is dead above MI.
904 RegUnits.erase(I);
905 }
906 }
907
908 // Now we know the height of MI. Update any regunits read.
909 for (unsigned i = 0, e = ReadOps.size(); i != e; ++i) {
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000910 unsigned Reg = MI.getOperand(ReadOps[i]).getReg();
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000911 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
912 LiveRegUnit &LRU = RegUnits[*Units];
913 // Set the height to the highest reader of the unit.
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000914 if (LRU.Cycle <= Height && LRU.MI != &MI) {
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000915 LRU.Cycle = Height;
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000916 LRU.MI = &MI;
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000917 LRU.Op = ReadOps[i];
918 }
919 }
920 }
921
922 return Height;
923}
924
925
926typedef DenseMap<const MachineInstr *, unsigned> MIHeightMap;
927
928// Push the height of DefMI upwards if required to match UseMI.
929// Return true if this is the first time DefMI was seen.
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000930static bool pushDepHeight(const DataDep &Dep, const MachineInstr &UseMI,
931 unsigned UseHeight, MIHeightMap &Heights,
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +0000932 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000933 const TargetInstrInfo *TII) {
934 // Adjust height by Dep.DefMI latency.
935 if (!Dep.DefMI->isTransient())
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +0000936 UseHeight += SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp, &UseMI,
937 Dep.UseOp);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000938
939 // Update Heights[DefMI] to be the maximum height seen.
940 MIHeightMap::iterator I;
941 bool New;
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000942 std::tie(I, New) = Heights.insert(std::make_pair(Dep.DefMI, UseHeight));
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000943 if (New)
944 return true;
945
946 // DefMI has been pushed before. Give it the max height.
947 if (I->second < UseHeight)
948 I->second = UseHeight;
949 return false;
950}
951
Jakob Stoklund Olesend0d78602012-10-11 16:46:07 +0000952/// Assuming that the virtual register defined by DefMI:DefOp was used by
953/// Trace.back(), add it to the live-in lists of all the blocks in Trace. Stop
954/// when reaching the block that contains DefMI.
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000955void MachineTraceMetrics::Ensemble::
Jakob Stoklund Olesend0d78602012-10-11 16:46:07 +0000956addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000957 ArrayRef<const MachineBasicBlock*> Trace) {
958 assert(!Trace.empty() && "Trace should contain at least one block");
Jakob Stoklund Olesend0d78602012-10-11 16:46:07 +0000959 unsigned Reg = DefMI->getOperand(DefOp).getReg();
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +0000960 assert(TargetRegisterInfo::isVirtualRegister(Reg));
961 const MachineBasicBlock *DefMBB = DefMI->getParent();
962
963 // Reg is live-in to all blocks in Trace that follow DefMBB.
964 for (unsigned i = Trace.size(); i; --i) {
965 const MachineBasicBlock *MBB = Trace[i-1];
966 if (MBB == DefMBB)
967 return;
968 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
969 // Just add the register. The height will be updated later.
970 TBI.LiveIns.push_back(Reg);
971 }
972}
973
974/// Compute instruction heights in the trace through MBB. This updates MBB and
975/// the blocks below it in the trace. It is assumed that the trace has already
976/// been computed.
977void MachineTraceMetrics::Ensemble::
978computeInstrHeights(const MachineBasicBlock *MBB) {
979 // The bottom of the trace may already be computed.
980 // Find the blocks that need updating.
981 SmallVector<const MachineBasicBlock*, 8> Stack;
982 do {
983 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
984 assert(TBI.hasValidHeight() && "Incomplete trace");
985 if (TBI.HasValidInstrHeights)
986 break;
987 Stack.push_back(MBB);
988 TBI.LiveIns.clear();
989 MBB = TBI.Succ;
990 } while (MBB);
991
992 // As we move upwards in the trace, keep track of instructions that are
993 // required by deeper trace instructions. Map MI -> height required so far.
994 MIHeightMap Heights;
995
996 // For physregs, the def isn't known when we see the use.
997 // Instead, keep track of the highest use of each regunit.
998 SparseSet<LiveRegUnit> RegUnits;
999 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
1000
1001 // If the bottom of the trace was already precomputed, initialize heights
1002 // from its live-in list.
1003 // MBB is the highest precomputed block in the trace.
1004 if (MBB) {
1005 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
Sanjay Patel6d4c3e32015-07-06 16:19:14 +00001006 for (LiveInReg &LI : TBI.LiveIns) {
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001007 if (TargetRegisterInfo::isVirtualRegister(LI.Reg)) {
1008 // For virtual registers, the def latency is included.
1009 unsigned &Height = Heights[MTM.MRI->getVRegDef(LI.Reg)];
1010 if (Height < LI.Height)
1011 Height = LI.Height;
1012 } else {
1013 // For register units, the def latency is not included because we don't
1014 // know the def yet.
1015 RegUnits[LI.Reg].Cycle = LI.Height;
1016 }
1017 }
1018 }
1019
1020 // Go through the trace blocks in bottom-up order.
1021 SmallVector<DataDep, 8> Deps;
1022 for (;!Stack.empty(); Stack.pop_back()) {
1023 MBB = Stack.back();
1024 DEBUG(dbgs() << "Heights for BB#" << MBB->getNumber() << ":\n");
1025 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1026 TBI.HasValidInstrHeights = true;
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001027 TBI.CriticalPath = 0;
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001028
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001029 DEBUG({
1030 dbgs() << format("%7u Instructions\n", TBI.InstrHeight);
1031 ArrayRef<unsigned> PRHeights = getProcResourceHeights(MBB->getNumber());
1032 for (unsigned K = 0; K != PRHeights.size(); ++K)
1033 if (PRHeights[K]) {
1034 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
1035 dbgs() << format("%6uc @ ", MTM.getCycles(PRHeights[K]))
1036 << MTM.SchedModel.getProcResource(K)->Name << " ("
1037 << PRHeights[K]/Factor << " ops x" << Factor << ")\n";
1038 }
1039 });
1040
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001041 // Get dependencies from PHIs in the trace successor.
Jakob Stoklund Olesen0954d412012-08-10 20:11:38 +00001042 const MachineBasicBlock *Succ = TBI.Succ;
1043 // If MBB is the last block in the trace, and it has a back-edge to the
1044 // loop header, get loop-carried dependencies from PHIs in the header. For
1045 // that purpose, pretend that all the loop header PHIs have height 0.
1046 if (!Succ)
1047 if (const MachineLoop *Loop = getLoopFor(MBB))
1048 if (MBB->isSuccessor(Loop->getHeader()))
1049 Succ = Loop->getHeader();
1050
1051 if (Succ) {
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001052 for (const auto &PHI : *Succ) {
1053 if (!PHI.isPHI())
1054 break;
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001055 Deps.clear();
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001056 getPHIDeps(PHI, Deps, MBB, MTM.MRI);
Jakob Stoklund Olesen0954d412012-08-10 20:11:38 +00001057 if (!Deps.empty()) {
1058 // Loop header PHI heights are all 0.
Alexey Samsonovf74bde62014-04-30 22:17:38 +00001059 unsigned Height = TBI.Succ ? Cycles.lookup(&PHI).Height : 0;
1060 DEBUG(dbgs() << "pred\t" << Height << '\t' << PHI);
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +00001061 if (pushDepHeight(Deps.front(), PHI, Height, Heights, MTM.SchedModel,
1062 MTM.TII))
Jakob Stoklund Olesend0d78602012-10-11 16:46:07 +00001063 addLiveIns(Deps.front().DefMI, Deps.front().DefOp, Stack);
Jakob Stoklund Olesen0954d412012-08-10 20:11:38 +00001064 }
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001065 }
1066 }
1067
1068 // Go through the block backwards.
1069 for (MachineBasicBlock::const_iterator BI = MBB->end(), BB = MBB->begin();
1070 BI != BB;) {
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +00001071 const MachineInstr &MI = *--BI;
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001072
1073 // Find the MI height as determined by virtual register uses in the
1074 // trace below.
1075 unsigned Cycle = 0;
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +00001076 MIHeightMap::iterator HeightI = Heights.find(&MI);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001077 if (HeightI != Heights.end()) {
1078 Cycle = HeightI->second;
1079 // We won't be seeing any more MI uses.
1080 Heights.erase(HeightI);
1081 }
1082
1083 // Don't process PHI deps. They depend on the specific predecessor, and
1084 // we'll get them when visiting the predecessor.
1085 Deps.clear();
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +00001086 bool HasPhysRegs = !MI.isPHI() && getDataDeps(MI, Deps, MTM.MRI);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001087
1088 // There may also be regunit dependencies to include in the height.
1089 if (HasPhysRegs)
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +00001090 Cycle = updatePhysDepsUpwards(MI, Cycle, RegUnits, MTM.SchedModel,
1091 MTM.TII, MTM.TRI);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001092
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001093 // Update the required height of any virtual registers read by MI.
Sanjay Patel0ca438c2015-06-30 16:30:22 +00001094 for (const DataDep &Dep : Deps)
Duncan P. N. Exon Smith5a7538b2016-07-01 00:05:40 +00001095 if (pushDepHeight(Dep, MI, Cycle, Heights, MTM.SchedModel, MTM.TII))
Sanjay Patel0ca438c2015-06-30 16:30:22 +00001096 addLiveIns(Dep.DefMI, Dep.DefOp, Stack);
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001097
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +00001098 InstrCycles &MICycles = Cycles[&MI];
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001099 MICycles.Height = Cycle;
1100 if (!TBI.HasValidInstrDepths) {
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +00001101 DEBUG(dbgs() << Cycle << '\t' << MI);
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001102 continue;
1103 }
1104 // Update critical path length.
1105 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Depth);
Duncan P. N. Exon Smith5d2b9382016-06-30 23:53:20 +00001106 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << MI);
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001107 }
1108
1109 // Update virtual live-in heights. They were added by addLiveIns() with a 0
1110 // height because the final height isn't known until now.
1111 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " Live-ins:");
Sanjay Patel0ca438c2015-06-30 16:30:22 +00001112 for (LiveInReg &LIR : TBI.LiveIns) {
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001113 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
1114 LIR.Height = Heights.lookup(DefMI);
1115 DEBUG(dbgs() << ' ' << PrintReg(LIR.Reg) << '@' << LIR.Height);
1116 }
1117
1118 // Transfer the live regunits to the live-in list.
1119 for (SparseSet<LiveRegUnit>::const_iterator
1120 RI = RegUnits.begin(), RE = RegUnits.end(); RI != RE; ++RI) {
1121 TBI.LiveIns.push_back(LiveInReg(RI->RegUnit, RI->Cycle));
1122 DEBUG(dbgs() << ' ' << PrintRegUnit(RI->RegUnit, MTM.TRI)
1123 << '@' << RI->Cycle);
1124 }
1125 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001126
1127 if (!TBI.HasValidInstrDepths)
1128 continue;
1129 // Add live-ins to the critical path length.
1130 TBI.CriticalPath = std::max(TBI.CriticalPath,
1131 computeCrossBlockCriticalPath(TBI));
1132 DEBUG(dbgs() << "Critical path: " << TBI.CriticalPath << '\n');
Jakob Stoklund Olesen2db6b652012-08-01 22:36:00 +00001133 }
1134}
1135
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001136MachineTraceMetrics::Trace
1137MachineTraceMetrics::Ensemble::getTrace(const MachineBasicBlock *MBB) {
Sanjay Patel82db3b72015-07-04 15:00:28 +00001138 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1139
1140 if (!TBI.hasValidDepth() || !TBI.hasValidHeight())
1141 computeTrace(MBB);
1142 if (!TBI.HasValidInstrDepths)
1143 computeInstrDepths(MBB);
1144 if (!TBI.HasValidInstrHeights)
1145 computeInstrHeights(MBB);
1146
1147 return Trace(*this, TBI);
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001148}
1149
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001150unsigned
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001151MachineTraceMetrics::Trace::getInstrSlack(const MachineInstr &MI) const {
1152 assert(getBlockNum() == unsigned(MI.getParent()->getNumber()) &&
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001153 "MI must be in the trace center block");
1154 InstrCycles Cyc = getInstrCycles(MI);
1155 return getCriticalPath() - (Cyc.Depth + Cyc.Height);
1156}
1157
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001158unsigned
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001159MachineTraceMetrics::Trace::getPHIDepth(const MachineInstr &PHI) const {
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001160 const MachineBasicBlock *MBB = TE.MTM.MF->getBlockNumbered(getBlockNum());
1161 SmallVector<DataDep, 1> Deps;
1162 getPHIDeps(PHI, Deps, MBB, TE.MTM.MRI);
1163 assert(Deps.size() == 1 && "PHI doesn't have MBB as a predecessor");
1164 DataDep &Dep = Deps.front();
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001165 unsigned DepCycle = getInstrCycles(*Dep.DefMI).Depth;
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001166 // Add latency if DefMI is a real instruction. Transients get latency 0.
1167 if (!Dep.DefMI->isTransient())
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001168 DepCycle += TE.MTM.SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp,
1169 &PHI, Dep.UseOp);
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001170 return DepCycle;
1171}
1172
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001173/// When bottom is set include instructions in current block in estimate.
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001174unsigned MachineTraceMetrics::Trace::getResourceDepth(bool Bottom) const {
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001175 // Find the limiting processor resource.
1176 // Numbers have been pre-scaled to be comparable.
1177 unsigned PRMax = 0;
1178 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1179 if (Bottom) {
1180 ArrayRef<unsigned> PRCycles = TE.MTM.getProcResourceCycles(getBlockNum());
1181 for (unsigned K = 0; K != PRDepths.size(); ++K)
1182 PRMax = std::max(PRMax, PRDepths[K] + PRCycles[K]);
1183 } else {
1184 for (unsigned K = 0; K != PRDepths.size(); ++K)
1185 PRMax = std::max(PRMax, PRDepths[K]);
1186 }
1187 // Convert to cycle count.
1188 PRMax = TE.MTM.getCycles(PRMax);
1189
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001190 /// All instructions before current block
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001191 unsigned Instrs = TBI.InstrDepth;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001192 // plus instructions in current block
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001193 if (Bottom)
1194 Instrs += TE.MTM.BlockInfo[getBlockNum()].InstrCount;
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +00001195 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1196 Instrs /= IW;
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001197 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001198 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen75d9d512012-08-07 18:02:19 +00001199}
1200
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001201unsigned MachineTraceMetrics::Trace::getResourceLength(
1202 ArrayRef<const MachineBasicBlock *> Extrablocks,
1203 ArrayRef<const MCSchedClassDesc *> ExtraInstrs,
1204 ArrayRef<const MCSchedClassDesc *> RemoveInstrs) const {
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001205 // Add up resources above and below the center block.
1206 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1207 ArrayRef<unsigned> PRHeights = TE.getProcResourceHeights(getBlockNum());
1208 unsigned PRMax = 0;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001209
1210 // Capture computing cycles from extra instructions
1211 auto extraCycles = [this](ArrayRef<const MCSchedClassDesc *> Instrs,
1212 unsigned ResourceIdx)
1213 ->unsigned {
1214 unsigned Cycles = 0;
Sanjay Patel6d4c3e32015-07-06 16:19:14 +00001215 for (const MCSchedClassDesc *SC : Instrs) {
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001216 if (!SC->isValid())
1217 continue;
1218 for (TargetSchedModel::ProcResIter
1219 PI = TE.MTM.SchedModel.getWriteProcResBegin(SC),
1220 PE = TE.MTM.SchedModel.getWriteProcResEnd(SC);
1221 PI != PE; ++PI) {
1222 if (PI->ProcResourceIdx != ResourceIdx)
1223 continue;
1224 Cycles +=
1225 (PI->Cycles * TE.MTM.SchedModel.getResourceFactor(ResourceIdx));
1226 }
1227 }
1228 return Cycles;
1229 };
1230
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001231 for (unsigned K = 0; K != PRDepths.size(); ++K) {
1232 unsigned PRCycles = PRDepths[K] + PRHeights[K];
Sanjay Patel6d4c3e32015-07-06 16:19:14 +00001233 for (const MachineBasicBlock *MBB : Extrablocks)
1234 PRCycles += TE.MTM.getProcResourceCycles(MBB->getNumber())[K];
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001235 PRCycles += extraCycles(ExtraInstrs, K);
1236 PRCycles -= extraCycles(RemoveInstrs, K);
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001237 PRMax = std::max(PRMax, PRCycles);
1238 }
1239 // Convert to cycle count.
1240 PRMax = TE.MTM.getCycles(PRMax);
1241
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001242 // Instrs: #instructions in current trace outside current block.
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001243 unsigned Instrs = TBI.InstrDepth + TBI.InstrHeight;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001244 // Add instruction count from the extra blocks.
Sanjay Patel6d4c3e32015-07-06 16:19:14 +00001245 for (const MachineBasicBlock *MBB : Extrablocks)
1246 Instrs += TE.MTM.getResources(MBB)->InstrCount;
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001247 Instrs += ExtraInstrs.size();
1248 Instrs -= RemoveInstrs.size();
Jakob Stoklund Olesen89822222012-10-04 17:30:40 +00001249 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1250 Instrs /= IW;
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001251 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen3ca14772013-04-02 17:49:51 +00001252 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen34844202012-08-10 22:27:27 +00001253}
1254
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001255bool MachineTraceMetrics::Trace::isDepInTrace(const MachineInstr &DefMI,
1256 const MachineInstr &UseMI) const {
1257 if (DefMI.getParent() == UseMI.getParent())
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001258 return true;
1259
Duncan P. N. Exon Smithe59c8af2016-02-22 03:33:28 +00001260 const TraceBlockInfo &DepTBI = TE.BlockInfo[DefMI.getParent()->getNumber()];
1261 const TraceBlockInfo &TBI = TE.BlockInfo[UseMI.getParent()->getNumber()];
Gerolf Hoflehner5e1207e2014-08-03 21:35:39 +00001262
1263 return DepTBI.isUsefulDominator(TBI);
1264}
1265
Jakob Stoklund Olesen05633692012-07-27 23:58:38 +00001266void MachineTraceMetrics::Ensemble::print(raw_ostream &OS) const {
1267 OS << getName() << " ensemble:\n";
1268 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
1269 OS << " BB#" << i << '\t';
1270 BlockInfo[i].print(OS);
1271 OS << '\n';
1272 }
1273}
1274
1275void MachineTraceMetrics::TraceBlockInfo::print(raw_ostream &OS) const {
1276 if (hasValidDepth()) {
1277 OS << "depth=" << InstrDepth;
1278 if (Pred)
1279 OS << " pred=BB#" << Pred->getNumber();
1280 else
1281 OS << " pred=null";
1282 OS << " head=BB#" << Head;
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +00001283 if (HasValidInstrDepths)
1284 OS << " +instrs";
Jakob Stoklund Olesen05633692012-07-27 23:58:38 +00001285 } else
1286 OS << "depth invalid";
1287 OS << ", ";
1288 if (hasValidHeight()) {
1289 OS << "height=" << InstrHeight;
1290 if (Succ)
1291 OS << " succ=BB#" << Succ->getNumber();
1292 else
1293 OS << " succ=null";
1294 OS << " tail=BB#" << Tail;
Jakob Stoklund Olesen059e6472012-07-31 20:44:38 +00001295 if (HasValidInstrHeights)
1296 OS << " +instrs";
Jakob Stoklund Olesen05633692012-07-27 23:58:38 +00001297 } else
1298 OS << "height invalid";
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001299 if (HasValidInstrDepths && HasValidInstrHeights)
1300 OS << ", crit=" << CriticalPath;
Jakob Stoklund Olesen05633692012-07-27 23:58:38 +00001301}
1302
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001303void MachineTraceMetrics::Trace::print(raw_ostream &OS) const {
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +00001304 unsigned MBBNum = &TBI - &TE.BlockInfo[0];
1305
1306 OS << TE.getName() << " trace BB#" << TBI.Head << " --> BB#" << MBBNum
1307 << " --> BB#" << TBI.Tail << ':';
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001308 if (TBI.hasValidHeight() && TBI.hasValidDepth())
1309 OS << ' ' << getInstrCount() << " instrs.";
Jakob Stoklund Olesen5d306302012-08-02 18:45:54 +00001310 if (TBI.HasValidInstrDepths && TBI.HasValidInstrHeights)
1311 OS << ' ' << TBI.CriticalPath << " cycles.";
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001312
1313 const MachineTraceMetrics::TraceBlockInfo *Block = &TBI;
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +00001314 OS << "\nBB#" << MBBNum;
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001315 while (Block->hasValidDepth() && Block->Pred) {
1316 unsigned Num = Block->Pred->getNumber();
1317 OS << " <- BB#" << Num;
1318 Block = &TE.BlockInfo[Num];
1319 }
1320
1321 Block = &TBI;
Jakob Stoklund Olesen11522022012-07-27 23:58:36 +00001322 OS << "\n ";
Jakob Stoklund Olesenf9029fe2012-07-26 18:38:11 +00001323 while (Block->hasValidHeight() && Block->Succ) {
1324 unsigned Num = Block->Succ->getNumber();
1325 OS << " -> BB#" << Num;
1326 Block = &TE.BlockInfo[Num];
1327 }
1328 OS << '\n';
1329}