1 //===- 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 10 #include "llvm/CodeGen/MachineTraceMetrics.h" 11 #include "llvm/ADT/PostOrderIterator.h" 12 #include "llvm/ADT/SparseSet.h" 13 #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" 18 #include "llvm/MC/MCSubtargetInfo.h" 19 #include "llvm/Support/Debug.h" 20 #include "llvm/Support/Format.h" 21 #include "llvm/Support/raw_ostream.h" 22 #include "llvm/Target/TargetInstrInfo.h" 23 #include "llvm/Target/TargetRegisterInfo.h" 24 #include "llvm/Target/TargetSubtargetInfo.h" 25 26 using namespace llvm; 27 28 #define DEBUG_TYPE "machine-trace-metrics" 29 30 char MachineTraceMetrics::ID = 0; 31 char &llvm::MachineTraceMetricsID = MachineTraceMetrics::ID; 32 33 INITIALIZE_PASS_BEGIN(MachineTraceMetrics, 34 "machine-trace-metrics", "Machine Trace Metrics", false, true) 35 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo) 36 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 37 INITIALIZE_PASS_END(MachineTraceMetrics, 38 "machine-trace-metrics", "Machine Trace Metrics", false, true) 39 40 MachineTraceMetrics::MachineTraceMetrics() 41 : MachineFunctionPass(ID), MF(nullptr), TII(nullptr), TRI(nullptr), 42 MRI(nullptr), Loops(nullptr) { 43 std::fill(std::begin(Ensembles), std::end(Ensembles), nullptr); 44 } 45 46 void MachineTraceMetrics::getAnalysisUsage(AnalysisUsage &AU) const { 47 AU.setPreservesAll(); 48 AU.addRequired<MachineBranchProbabilityInfo>(); 49 AU.addRequired<MachineLoopInfo>(); 50 MachineFunctionPass::getAnalysisUsage(AU); 51 } 52 53 bool MachineTraceMetrics::runOnMachineFunction(MachineFunction &Func) { 54 MF = &Func; 55 const TargetSubtargetInfo &ST = MF->getSubtarget(); 56 TII = ST.getInstrInfo(); 57 TRI = ST.getRegisterInfo(); 58 MRI = &MF->getRegInfo(); 59 Loops = &getAnalysis<MachineLoopInfo>(); 60 SchedModel.init(ST.getSchedModel(), &ST, TII); 61 BlockInfo.resize(MF->getNumBlockIDs()); 62 ProcResourceCycles.resize(MF->getNumBlockIDs() * 63 SchedModel.getNumProcResourceKinds()); 64 return false; 65 } 66 67 void MachineTraceMetrics::releaseMemory() { 68 MF = nullptr; 69 BlockInfo.clear(); 70 for (unsigned i = 0; i != TS_NumStrategies; ++i) { 71 delete Ensembles[i]; 72 Ensembles[i] = nullptr; 73 } 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 83 /// Compute the resource usage in basic block MBB. 84 const MachineTraceMetrics::FixedBlockInfo* 85 MachineTraceMetrics::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. 92 FBI->HasCalls = false; 93 unsigned InstrCount = 0; 94 95 // Add up per-processor resource cycles as well. 96 unsigned PRKinds = SchedModel.getNumProcResourceKinds(); 97 SmallVector<unsigned, 32> PRCycles(PRKinds); 98 99 for (const auto &MI : *MBB) { 100 if (MI.isTransient()) 101 continue; 102 ++InstrCount; 103 if (MI.isCall()) 104 FBI->HasCalls = true; 105 106 // Count processor resources used. 107 if (!SchedModel.hasInstrSchedModel()) 108 continue; 109 const MCSchedClassDesc *SC = SchedModel.resolveSchedClass(&MI); 110 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 } 119 } 120 FBI->InstrCount = InstrCount; 121 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 128 return FBI; 129 } 130 131 ArrayRef<unsigned> 132 MachineTraceMetrics::getProcResourceCycles(unsigned MBBNum) const { 133 assert(BlockInfo[MBBNum].hasResources() && 134 "getResources() must be called before getProcResourceCycles()"); 135 unsigned PRKinds = SchedModel.getNumProcResourceKinds(); 136 assert((MBBNum+1) * PRKinds <= ProcResourceCycles.size()); 137 return makeArrayRef(ProcResourceCycles.data() + MBBNum * PRKinds, PRKinds); 138 } 139 140 141 //===----------------------------------------------------------------------===// 142 // Ensemble utility functions 143 //===----------------------------------------------------------------------===// 144 145 MachineTraceMetrics::Ensemble::Ensemble(MachineTraceMetrics *ct) 146 : MTM(*ct) { 147 BlockInfo.resize(MTM.BlockInfo.size()); 148 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds(); 149 ProcResourceDepths.resize(MTM.BlockInfo.size() * PRKinds); 150 ProcResourceHeights.resize(MTM.BlockInfo.size() * PRKinds); 151 } 152 153 // Virtual destructor serves as an anchor. 154 MachineTraceMetrics::Ensemble::~Ensemble() {} 155 156 const MachineLoop* 157 MachineTraceMetrics::Ensemble::getLoopFor(const MachineBasicBlock *MBB) const { 158 return MTM.Loops->getLoopFor(MBB); 159 } 160 161 // Update resource-related information in the TraceBlockInfo for MBB. 162 // Only update resources related to the trace above MBB. 163 void MachineTraceMetrics::Ensemble:: 164 computeDepthResources(const MachineBasicBlock *MBB) { 165 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()]; 166 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds(); 167 unsigned PROffset = MBB->getNumber() * PRKinds; 168 169 // Compute resources from trace above. The top block is simple. 170 if (!TBI->Pred) { 171 TBI->InstrDepth = 0; 172 TBI->Head = MBB->getNumber(); 173 std::fill(ProcResourceDepths.begin() + PROffset, 174 ProcResourceDepths.begin() + PROffset + PRKinds, 0); 175 return; 176 } 177 178 // Compute from the block above. A post-order traversal ensures the 179 // predecessor is always computed first. 180 unsigned PredNum = TBI->Pred->getNumber(); 181 TraceBlockInfo *PredTBI = &BlockInfo[PredNum]; 182 assert(PredTBI->hasValidDepth() && "Trace above has not been computed yet"); 183 const FixedBlockInfo *PredFBI = MTM.getResources(TBI->Pred); 184 TBI->InstrDepth = PredTBI->InstrDepth + PredFBI->InstrCount; 185 TBI->Head = PredTBI->Head; 186 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]; 192 } 193 194 // Update resource-related information in the TraceBlockInfo for MBB. 195 // Only update resources related to the trace below MBB. 196 void MachineTraceMetrics::Ensemble:: 197 computeHeightResources(const MachineBasicBlock *MBB) { 198 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()]; 199 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds(); 200 unsigned PROffset = MBB->getNumber() * PRKinds; 201 202 // Compute resources for the current block. 203 TBI->InstrHeight = MTM.getResources(MBB)->InstrCount; 204 ArrayRef<unsigned> PRCycles = MTM.getProcResourceCycles(MBB->getNumber()); 205 206 // The trace tail is done. 207 if (!TBI->Succ) { 208 TBI->Tail = MBB->getNumber(); 209 std::copy(PRCycles.begin(), PRCycles.end(), 210 ProcResourceHeights.begin() + PROffset); 211 return; 212 } 213 214 // Compute from the block below. A post-order traversal ensures the 215 // predecessor is always computed first. 216 unsigned SuccNum = TBI->Succ->getNumber(); 217 TraceBlockInfo *SuccTBI = &BlockInfo[SuccNum]; 218 assert(SuccTBI->hasValidHeight() && "Trace below has not been computed yet"); 219 TBI->InstrHeight += SuccTBI->InstrHeight; 220 TBI->Tail = SuccTBI->Tail; 221 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]; 226 } 227 228 // Check if depth resources for MBB are valid and return the TBI. 229 // Return NULL if the resources have been invalidated. 230 const MachineTraceMetrics::TraceBlockInfo* 231 MachineTraceMetrics::Ensemble:: 232 getDepthResources(const MachineBasicBlock *MBB) const { 233 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()]; 234 return TBI->hasValidDepth() ? TBI : nullptr; 235 } 236 237 // Check if height resources for MBB are valid and return the TBI. 238 // Return NULL if the resources have been invalidated. 239 const MachineTraceMetrics::TraceBlockInfo* 240 MachineTraceMetrics::Ensemble:: 241 getHeightResources(const MachineBasicBlock *MBB) const { 242 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()]; 243 return TBI->hasValidHeight() ? TBI : nullptr; 244 } 245 246 /// 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. 252 ArrayRef<unsigned> 253 MachineTraceMetrics::Ensemble:: 254 getProcResourceDepths(unsigned MBBNum) const { 255 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds(); 256 assert((MBBNum+1) * PRKinds <= ProcResourceDepths.size()); 257 return makeArrayRef(ProcResourceDepths.data() + MBBNum * PRKinds, PRKinds); 258 } 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. 265 ArrayRef<unsigned> 266 MachineTraceMetrics::Ensemble:: 267 getProcResourceHeights(unsigned MBBNum) const { 268 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds(); 269 assert((MBBNum+1) * PRKinds <= ProcResourceHeights.size()); 270 return makeArrayRef(ProcResourceHeights.data() + MBBNum * PRKinds, PRKinds); 271 } 272 273 //===----------------------------------------------------------------------===// 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 284 // 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. 293 static bool isExitingLoop(const MachineLoop *From, const MachineLoop *To) { 294 return From && !From->contains(To); 295 } 296 297 // MinInstrCountEnsemble - Pick the trace that executes the least number of 298 // instructions. 299 namespace { 300 class MinInstrCountEnsemble : public MachineTraceMetrics::Ensemble { 301 const char *getName() const override { return "MinInstr"; } 302 const MachineBasicBlock *pickTracePred(const MachineBasicBlock*) override; 303 const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*) override; 304 305 public: 306 MinInstrCountEnsemble(MachineTraceMetrics *mtm) 307 : MachineTraceMetrics::Ensemble(mtm) {} 308 }; 309 } 310 311 // Select the preferred predecessor for MBB. 312 const MachineBasicBlock* 313 MinInstrCountEnsemble::pickTracePred(const MachineBasicBlock *MBB) { 314 if (MBB->pred_empty()) 315 return nullptr; 316 const MachineLoop *CurLoop = getLoopFor(MBB); 317 // Don't leave loops, and never follow back-edges. 318 if (CurLoop && MBB == CurLoop->getHeader()) 319 return nullptr; 320 unsigned CurCount = MTM.getResources(MBB)->InstrCount; 321 const MachineBasicBlock *Best = nullptr; 322 unsigned BestDepth = 0; 323 for (const MachineBasicBlock *Pred : MBB->predecessors()) { 324 const MachineTraceMetrics::TraceBlockInfo *PredTBI = 325 getDepthResources(Pred); 326 // Ignore cycles that aren't natural loops. 327 if (!PredTBI) 328 continue; 329 // 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. 338 const MachineBasicBlock* 339 MinInstrCountEnsemble::pickTraceSucc(const MachineBasicBlock *MBB) { 340 if (MBB->pred_empty()) 341 return nullptr; 342 const MachineLoop *CurLoop = getLoopFor(MBB); 343 const MachineBasicBlock *Best = nullptr; 344 unsigned BestHeight = 0; 345 for (const MachineBasicBlock *Succ : MBB->successors()) { 346 // Don't consider back-edges. 347 if (CurLoop && Succ == CurLoop->getHeader()) 348 continue; 349 // Don't consider successors exiting CurLoop. 350 if (isExitingLoop(CurLoop, getLoopFor(Succ))) 351 continue; 352 const MachineTraceMetrics::TraceBlockInfo *SuccTBI = 353 getHeightResources(Succ); 354 // Ignore cycles that aren't natural loops. 355 if (!SuccTBI) 356 continue; 357 // 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. 366 MachineTraceMetrics::Ensemble * 367 MachineTraceMetrics::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 380 void 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 388 void MachineTraceMetrics::verifyAnalysis() const { 389 if (!MF) 390 return; 391 #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 399 //===----------------------------------------------------------------------===// 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 407 namespace { 408 struct LoopBounds { 409 MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> Blocks; 410 SmallPtrSet<const MachineBasicBlock*, 8> Visited; 411 const MachineLoopInfo *Loops; 412 bool Downward; 413 LoopBounds(MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> blocks, 414 const MachineLoopInfo *loops) 415 : Blocks(blocks), Loops(loops), Downward(false) {} 416 }; 417 } 418 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. 421 namespace llvm { 422 template<> 423 class po_iterator_storage<LoopBounds, true> { 424 LoopBounds &LB; 425 public: 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; 434 // From is null once when To is the trace center block. 435 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. 447 return LB.Visited.insert(To).second; 448 } 449 }; 450 } 451 452 /// Compute the trace through MBB. 453 void 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. 457 LoopBounds Bounds(BlockInfo, MTM.Loops); 458 459 // Run an upwards post-order search for the trace start. 460 Bounds.Downward = false; 461 Bounds.Visited.clear(); 462 for (auto I : inverse_post_order_ext(MBB, Bounds)) { 463 DEBUG(dbgs() << " pred for BB#" << I->getNumber() << ": "); 464 TraceBlockInfo &TBI = BlockInfo[I->getNumber()]; 465 // All the predecessors have been visited, pick the preferred one. 466 TBI.Pred = pickTracePred(I); 467 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. 474 computeDepthResources(I); 475 } 476 477 // Run a downwards post-order search for the trace end. 478 Bounds.Downward = true; 479 Bounds.Visited.clear(); 480 for (auto I : post_order_ext(MBB, Bounds)) { 481 DEBUG(dbgs() << " succ for BB#" << I->getNumber() << ": "); 482 TraceBlockInfo &TBI = BlockInfo[I->getNumber()]; 483 // All the successors have been visited, pick the preferred one. 484 TBI.Succ = pickTraceSucc(I); 485 DEBUG({ 486 if (TBI.Succ) 487 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. 492 computeHeightResources(I); 493 } 494 } 495 496 /// Invalidate traces through BadMBB. 497 void 498 MachineTraceMetrics::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. 512 for (MachineBasicBlock::const_pred_iterator 513 I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) { 514 TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()]; 515 if (!TBI.hasValidHeight()) 516 continue; 517 if (TBI.Succ == MBB) { 518 TBI.invalidateHeight(); 519 WorkList.push_back(*I); 520 continue; 521 } 522 // Verify that TBI.Succ is actually a *I successor. 523 assert((!TBI.Succ || (*I)->isSuccessor(TBI.Succ)) && "CFG changed"); 524 } 525 } while (!WorkList.empty()); 526 } 527 528 // Invalidate depth resources of blocks below MBB. 529 if (BadTBI.hasValidDepth()) { 530 BadTBI.invalidateDepth(); 531 WorkList.push_back(BadMBB); 532 do { 533 const MachineBasicBlock *MBB = WorkList.pop_back_val(); 534 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName() 535 << " depth.\n"); 536 // Find any MBB successors that have MBB as their preferred predecessor. 537 // They are the only ones that need to be invalidated. 538 for (MachineBasicBlock::const_succ_iterator 539 I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) { 540 TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()]; 541 if (!TBI.hasValidDepth()) 542 continue; 543 if (TBI.Pred == MBB) { 544 TBI.invalidateDepth(); 545 WorkList.push_back(*I); 546 continue; 547 } 548 // Verify that TBI.Pred is actually a *I predecessor. 549 assert((!TBI.Pred || (*I)->isPredecessor(TBI.Pred)) && "CFG changed"); 550 } 551 } while (!WorkList.empty()); 552 } 553 554 // Clear any per-instruction data. We only have to do this for BadMBB itself 555 // because the instructions in that block may change. Other blocks may be 556 // invalidated, but their instructions will stay the same, so there is no 557 // need to erase the Cycle entries. They will be overwritten when we 558 // recompute. 559 for (const auto &I : *BadMBB) 560 Cycles.erase(&I); 561 } 562 563 void MachineTraceMetrics::Ensemble::verify() const { 564 #ifndef NDEBUG 565 assert(BlockInfo.size() == MTM.MF->getNumBlockIDs() && 566 "Outdated BlockInfo size"); 567 for (unsigned Num = 0, e = BlockInfo.size(); Num != e; ++Num) { 568 const TraceBlockInfo &TBI = BlockInfo[Num]; 569 if (TBI.hasValidDepth() && TBI.Pred) { 570 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num); 571 assert(MBB->isPredecessor(TBI.Pred) && "CFG doesn't match trace"); 572 assert(BlockInfo[TBI.Pred->getNumber()].hasValidDepth() && 573 "Trace is broken, depth should have been invalidated."); 574 const MachineLoop *Loop = getLoopFor(MBB); 575 assert(!(Loop && MBB == Loop->getHeader()) && "Trace contains backedge"); 576 } 577 if (TBI.hasValidHeight() && TBI.Succ) { 578 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num); 579 assert(MBB->isSuccessor(TBI.Succ) && "CFG doesn't match trace"); 580 assert(BlockInfo[TBI.Succ->getNumber()].hasValidHeight() && 581 "Trace is broken, height should have been invalidated."); 582 const MachineLoop *Loop = getLoopFor(MBB); 583 const MachineLoop *SuccLoop = getLoopFor(TBI.Succ); 584 assert(!(Loop && Loop == SuccLoop && TBI.Succ == Loop->getHeader()) && 585 "Trace contains backedge"); 586 } 587 } 588 #endif 589 } 590 591 //===----------------------------------------------------------------------===// 592 // Data Dependencies 593 //===----------------------------------------------------------------------===// 594 // 595 // Compute the depth and height of each instruction based on data dependencies 596 // and instruction latencies. These cycle numbers assume that the CPU can issue 597 // an infinite number of instructions per cycle as long as their dependencies 598 // are ready. 599 600 // A data dependency is represented as a defining MI and operand numbers on the 601 // defining and using MI. 602 namespace { 603 struct DataDep { 604 const MachineInstr *DefMI; 605 unsigned DefOp; 606 unsigned UseOp; 607 608 DataDep(const MachineInstr *DefMI, unsigned DefOp, unsigned UseOp) 609 : DefMI(DefMI), DefOp(DefOp), UseOp(UseOp) {} 610 611 /// Create a DataDep from an SSA form virtual register. 612 DataDep(const MachineRegisterInfo *MRI, unsigned VirtReg, unsigned UseOp) 613 : UseOp(UseOp) { 614 assert(TargetRegisterInfo::isVirtualRegister(VirtReg)); 615 MachineRegisterInfo::def_iterator DefI = MRI->def_begin(VirtReg); 616 assert(!DefI.atEnd() && "Register has no defs"); 617 DefMI = DefI->getParent(); 618 DefOp = DefI.getOperandNo(); 619 assert((++DefI).atEnd() && "Register has multiple defs"); 620 } 621 }; 622 } 623 624 // Get the input data dependencies that must be ready before UseMI can issue. 625 // Return true if UseMI has any physreg operands. 626 static bool getDataDeps(const MachineInstr *UseMI, 627 SmallVectorImpl<DataDep> &Deps, 628 const MachineRegisterInfo *MRI) { 629 bool HasPhysRegs = false; 630 for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) { 631 if (!MO->isReg()) 632 continue; 633 unsigned Reg = MO->getReg(); 634 if (!Reg) 635 continue; 636 if (TargetRegisterInfo::isPhysicalRegister(Reg)) { 637 HasPhysRegs = true; 638 continue; 639 } 640 // Collect virtual register reads. 641 if (MO->readsReg()) 642 Deps.push_back(DataDep(MRI, Reg, MO.getOperandNo())); 643 } 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. 650 static 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(); 661 Deps.push_back(DataDep(MRI, Reg, i)); 662 return; 663 } 664 } 665 } 666 667 // Keep track of physreg data dependencies by recording each live register unit. 668 // 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. 671 namespace { 672 struct LiveRegUnit { 673 unsigned RegUnit; 674 unsigned Cycle; 675 const MachineInstr *MI; 676 unsigned Op; 677 678 unsigned getSparseSetIndex() const { return RegUnit; } 679 680 LiveRegUnit(unsigned RU) : RegUnit(RU), Cycle(0), MI(nullptr), Op(0) {} 681 }; 682 } 683 684 // Identify physreg dependencies for UseMI, and update the live regunit 685 // tracking set when scanning instructions downwards. 686 static 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 693 for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) { 694 if (!MO->isReg()) 695 continue; 696 unsigned Reg = MO->getReg(); 697 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) 698 continue; 699 // Track live defs and kills for updating RegUnits. 700 if (MO->isDef()) { 701 if (MO->isDead()) 702 Kills.push_back(Reg); 703 else 704 LiveDefOps.push_back(MO.getOperandNo()); 705 } else if (MO->isKill()) 706 Kills.push_back(Reg); 707 // Identify dependencies. 708 if (!MO->readsReg()) 709 continue; 710 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) { 711 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units); 712 if (I == RegUnits.end()) 713 continue; 714 Deps.push_back(DataDep(I->MI, I->Op, MO.getOperandNo())); 715 break; 716 } 717 } 718 719 // Update RegUnits to reflect live registers after UseMI. 720 // First kills. 721 for (unsigned i = 0, e = Kills.size(); i != e; ++i) 722 for (MCRegUnitIterator Units(Kills[i], TRI); Units.isValid(); ++Units) 723 RegUnits.erase(*Units); 724 725 // Second, live defs. 726 for (unsigned i = 0, e = LiveDefOps.size(); i != e; ++i) { 727 unsigned DefOp = LiveDefOps[i]; 728 for (MCRegUnitIterator Units(UseMI->getOperand(DefOp).getReg(), TRI); 729 Units.isValid(); ++Units) { 730 LiveRegUnit &LRU = RegUnits[*Units]; 731 LRU.MI = UseMI; 732 LRU.Op = DefOp; 733 } 734 } 735 } 736 737 /// The length of the critical path through a trace is the maximum of two path 738 /// lengths: 739 /// 740 /// 1. The maximum height+depth over all instructions in the trace center block. 741 /// 742 /// 2. The longest cross-block dependency chain. For small blocks, it is 743 /// possible that the critical path through the trace doesn't include any 744 /// instructions in the block. 745 /// 746 /// This function computes the second number from the live-in list of the 747 /// center block. 748 unsigned MachineTraceMetrics::Ensemble:: 749 computeCrossBlockCriticalPath(const TraceBlockInfo &TBI) { 750 assert(TBI.HasValidInstrDepths && "Missing depth info"); 751 assert(TBI.HasValidInstrHeights && "Missing height info"); 752 unsigned MaxLen = 0; 753 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) { 754 const LiveInReg &LIR = TBI.LiveIns[i]; 755 if (!TargetRegisterInfo::isVirtualRegister(LIR.Reg)) 756 continue; 757 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg); 758 // Ignore dependencies outside the current trace. 759 const TraceBlockInfo &DefTBI = BlockInfo[DefMI->getParent()->getNumber()]; 760 if (!DefTBI.isUsefulDominator(TBI)) 761 continue; 762 unsigned Len = LIR.Height + Cycles[DefMI].Depth; 763 MaxLen = std::max(MaxLen, Len); 764 } 765 return MaxLen; 766 } 767 768 /// Compute instruction depths for all instructions above or in MBB in its 769 /// trace. This assumes that the trace through MBB has already been computed. 770 void MachineTraceMetrics::Ensemble:: 771 computeInstrDepths(const MachineBasicBlock *MBB) { 772 // The top of the trace may already be computed, and HasValidInstrDepths 773 // implies Head->HasValidInstrDepths, so we only need to start from the first 774 // block in the trace that needs to be recomputed. 775 SmallVector<const MachineBasicBlock*, 8> Stack; 776 do { 777 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()]; 778 assert(TBI.hasValidDepth() && "Incomplete trace"); 779 if (TBI.HasValidInstrDepths) 780 break; 781 Stack.push_back(MBB); 782 MBB = TBI.Pred; 783 } while (MBB); 784 785 // FIXME: If MBB is non-null at this point, it is the last pre-computed block 786 // in the trace. We should track any live-out physregs that were defined in 787 // the trace. This is quite rare in SSA form, typically created by CSE 788 // hoisting a compare. 789 SparseSet<LiveRegUnit> RegUnits; 790 RegUnits.setUniverse(MTM.TRI->getNumRegUnits()); 791 792 // Go through trace blocks in top-down order, stopping after the center block. 793 SmallVector<DataDep, 8> Deps; 794 while (!Stack.empty()) { 795 MBB = Stack.pop_back_val(); 796 DEBUG(dbgs() << "\nDepths for BB#" << MBB->getNumber() << ":\n"); 797 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()]; 798 TBI.HasValidInstrDepths = true; 799 TBI.CriticalPath = 0; 800 801 // Print out resource depths here as well. 802 DEBUG({ 803 dbgs() << format("%7u Instructions\n", TBI.InstrDepth); 804 ArrayRef<unsigned> PRDepths = getProcResourceDepths(MBB->getNumber()); 805 for (unsigned K = 0; K != PRDepths.size(); ++K) 806 if (PRDepths[K]) { 807 unsigned Factor = MTM.SchedModel.getResourceFactor(K); 808 dbgs() << format("%6uc @ ", MTM.getCycles(PRDepths[K])) 809 << MTM.SchedModel.getProcResource(K)->Name << " (" 810 << PRDepths[K]/Factor << " ops x" << Factor << ")\n"; 811 } 812 }); 813 814 // Also compute the critical path length through MBB when possible. 815 if (TBI.HasValidInstrHeights) 816 TBI.CriticalPath = computeCrossBlockCriticalPath(TBI); 817 818 for (const auto &UseMI : *MBB) { 819 // Collect all data dependencies. 820 Deps.clear(); 821 if (UseMI.isPHI()) 822 getPHIDeps(&UseMI, Deps, TBI.Pred, MTM.MRI); 823 else if (getDataDeps(&UseMI, Deps, MTM.MRI)) 824 updatePhysDepsDownwards(&UseMI, Deps, RegUnits, MTM.TRI); 825 826 // Filter and process dependencies, computing the earliest issue cycle. 827 unsigned Cycle = 0; 828 for (unsigned i = 0, e = Deps.size(); i != e; ++i) { 829 const DataDep &Dep = Deps[i]; 830 const TraceBlockInfo&DepTBI = 831 BlockInfo[Dep.DefMI->getParent()->getNumber()]; 832 // Ignore dependencies from outside the current trace. 833 if (!DepTBI.isUsefulDominator(TBI)) 834 continue; 835 assert(DepTBI.HasValidInstrDepths && "Inconsistent dependency"); 836 unsigned DepCycle = Cycles.lookup(Dep.DefMI).Depth; 837 // Add latency if DefMI is a real instruction. Transients get latency 0. 838 if (!Dep.DefMI->isTransient()) 839 DepCycle += MTM.SchedModel 840 .computeOperandLatency(Dep.DefMI, Dep.DefOp, &UseMI, Dep.UseOp); 841 Cycle = std::max(Cycle, DepCycle); 842 } 843 // Remember the instruction depth. 844 InstrCycles &MICycles = Cycles[&UseMI]; 845 MICycles.Depth = Cycle; 846 847 if (!TBI.HasValidInstrHeights) { 848 DEBUG(dbgs() << Cycle << '\t' << UseMI); 849 continue; 850 } 851 // Update critical path length. 852 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Height); 853 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << UseMI); 854 } 855 } 856 } 857 858 // Identify physreg dependencies for MI when scanning instructions upwards. 859 // Return the issue height of MI after considering any live regunits. 860 // Height is the issue height computed from virtual register dependencies alone. 861 static unsigned updatePhysDepsUpwards(const MachineInstr *MI, unsigned Height, 862 SparseSet<LiveRegUnit> &RegUnits, 863 const TargetSchedModel &SchedModel, 864 const TargetInstrInfo *TII, 865 const TargetRegisterInfo *TRI) { 866 SmallVector<unsigned, 8> ReadOps; 867 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) { 868 if (!MO->isReg()) 869 continue; 870 unsigned Reg = MO->getReg(); 871 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) 872 continue; 873 if (MO->readsReg()) 874 ReadOps.push_back(MO.getOperandNo()); 875 if (!MO->isDef()) 876 continue; 877 // This is a def of Reg. Remove corresponding entries from RegUnits, and 878 // update MI Height to consider the physreg dependencies. 879 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) { 880 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units); 881 if (I == RegUnits.end()) 882 continue; 883 unsigned DepHeight = I->Cycle; 884 if (!MI->isTransient()) { 885 // We may not know the UseMI of this dependency, if it came from the 886 // live-in list. SchedModel can handle a NULL UseMI. 887 DepHeight += SchedModel 888 .computeOperandLatency(MI, MO.getOperandNo(), I->MI, I->Op); 889 } 890 Height = std::max(Height, DepHeight); 891 // This regunit is dead above MI. 892 RegUnits.erase(I); 893 } 894 } 895 896 // Now we know the height of MI. Update any regunits read. 897 for (unsigned i = 0, e = ReadOps.size(); i != e; ++i) { 898 unsigned Reg = MI->getOperand(ReadOps[i]).getReg(); 899 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) { 900 LiveRegUnit &LRU = RegUnits[*Units]; 901 // Set the height to the highest reader of the unit. 902 if (LRU.Cycle <= Height && LRU.MI != MI) { 903 LRU.Cycle = Height; 904 LRU.MI = MI; 905 LRU.Op = ReadOps[i]; 906 } 907 } 908 } 909 910 return Height; 911 } 912 913 914 typedef DenseMap<const MachineInstr *, unsigned> MIHeightMap; 915 916 // Push the height of DefMI upwards if required to match UseMI. 917 // Return true if this is the first time DefMI was seen. 918 static bool pushDepHeight(const DataDep &Dep, 919 const MachineInstr *UseMI, unsigned UseHeight, 920 MIHeightMap &Heights, 921 const TargetSchedModel &SchedModel, 922 const TargetInstrInfo *TII) { 923 // Adjust height by Dep.DefMI latency. 924 if (!Dep.DefMI->isTransient()) 925 UseHeight += SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp, 926 UseMI, Dep.UseOp); 927 928 // Update Heights[DefMI] to be the maximum height seen. 929 MIHeightMap::iterator I; 930 bool New; 931 std::tie(I, New) = Heights.insert(std::make_pair(Dep.DefMI, UseHeight)); 932 if (New) 933 return true; 934 935 // DefMI has been pushed before. Give it the max height. 936 if (I->second < UseHeight) 937 I->second = UseHeight; 938 return false; 939 } 940 941 /// Assuming that the virtual register defined by DefMI:DefOp was used by 942 /// Trace.back(), add it to the live-in lists of all the blocks in Trace. Stop 943 /// when reaching the block that contains DefMI. 944 void MachineTraceMetrics::Ensemble:: 945 addLiveIns(const MachineInstr *DefMI, unsigned DefOp, 946 ArrayRef<const MachineBasicBlock*> Trace) { 947 assert(!Trace.empty() && "Trace should contain at least one block"); 948 unsigned Reg = DefMI->getOperand(DefOp).getReg(); 949 assert(TargetRegisterInfo::isVirtualRegister(Reg)); 950 const MachineBasicBlock *DefMBB = DefMI->getParent(); 951 952 // Reg is live-in to all blocks in Trace that follow DefMBB. 953 for (unsigned i = Trace.size(); i; --i) { 954 const MachineBasicBlock *MBB = Trace[i-1]; 955 if (MBB == DefMBB) 956 return; 957 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()]; 958 // Just add the register. The height will be updated later. 959 TBI.LiveIns.push_back(Reg); 960 } 961 } 962 963 /// Compute instruction heights in the trace through MBB. This updates MBB and 964 /// the blocks below it in the trace. It is assumed that the trace has already 965 /// been computed. 966 void MachineTraceMetrics::Ensemble:: 967 computeInstrHeights(const MachineBasicBlock *MBB) { 968 // The bottom of the trace may already be computed. 969 // Find the blocks that need updating. 970 SmallVector<const MachineBasicBlock*, 8> Stack; 971 do { 972 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()]; 973 assert(TBI.hasValidHeight() && "Incomplete trace"); 974 if (TBI.HasValidInstrHeights) 975 break; 976 Stack.push_back(MBB); 977 TBI.LiveIns.clear(); 978 MBB = TBI.Succ; 979 } while (MBB); 980 981 // As we move upwards in the trace, keep track of instructions that are 982 // required by deeper trace instructions. Map MI -> height required so far. 983 MIHeightMap Heights; 984 985 // For physregs, the def isn't known when we see the use. 986 // Instead, keep track of the highest use of each regunit. 987 SparseSet<LiveRegUnit> RegUnits; 988 RegUnits.setUniverse(MTM.TRI->getNumRegUnits()); 989 990 // If the bottom of the trace was already precomputed, initialize heights 991 // from its live-in list. 992 // MBB is the highest precomputed block in the trace. 993 if (MBB) { 994 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()]; 995 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) { 996 LiveInReg LI = TBI.LiveIns[i]; 997 if (TargetRegisterInfo::isVirtualRegister(LI.Reg)) { 998 // For virtual registers, the def latency is included. 999 unsigned &Height = Heights[MTM.MRI->getVRegDef(LI.Reg)]; 1000 if (Height < LI.Height) 1001 Height = LI.Height; 1002 } else { 1003 // For register units, the def latency is not included because we don't 1004 // know the def yet. 1005 RegUnits[LI.Reg].Cycle = LI.Height; 1006 } 1007 } 1008 } 1009 1010 // Go through the trace blocks in bottom-up order. 1011 SmallVector<DataDep, 8> Deps; 1012 for (;!Stack.empty(); Stack.pop_back()) { 1013 MBB = Stack.back(); 1014 DEBUG(dbgs() << "Heights for BB#" << MBB->getNumber() << ":\n"); 1015 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()]; 1016 TBI.HasValidInstrHeights = true; 1017 TBI.CriticalPath = 0; 1018 1019 DEBUG({ 1020 dbgs() << format("%7u Instructions\n", TBI.InstrHeight); 1021 ArrayRef<unsigned> PRHeights = getProcResourceHeights(MBB->getNumber()); 1022 for (unsigned K = 0; K != PRHeights.size(); ++K) 1023 if (PRHeights[K]) { 1024 unsigned Factor = MTM.SchedModel.getResourceFactor(K); 1025 dbgs() << format("%6uc @ ", MTM.getCycles(PRHeights[K])) 1026 << MTM.SchedModel.getProcResource(K)->Name << " (" 1027 << PRHeights[K]/Factor << " ops x" << Factor << ")\n"; 1028 } 1029 }); 1030 1031 // Get dependencies from PHIs in the trace successor. 1032 const MachineBasicBlock *Succ = TBI.Succ; 1033 // If MBB is the last block in the trace, and it has a back-edge to the 1034 // loop header, get loop-carried dependencies from PHIs in the header. For 1035 // that purpose, pretend that all the loop header PHIs have height 0. 1036 if (!Succ) 1037 if (const MachineLoop *Loop = getLoopFor(MBB)) 1038 if (MBB->isSuccessor(Loop->getHeader())) 1039 Succ = Loop->getHeader(); 1040 1041 if (Succ) { 1042 for (const auto &PHI : *Succ) { 1043 if (!PHI.isPHI()) 1044 break; 1045 Deps.clear(); 1046 getPHIDeps(&PHI, Deps, MBB, MTM.MRI); 1047 if (!Deps.empty()) { 1048 // Loop header PHI heights are all 0. 1049 unsigned Height = TBI.Succ ? Cycles.lookup(&PHI).Height : 0; 1050 DEBUG(dbgs() << "pred\t" << Height << '\t' << PHI); 1051 if (pushDepHeight(Deps.front(), &PHI, Height, 1052 Heights, MTM.SchedModel, MTM.TII)) 1053 addLiveIns(Deps.front().DefMI, Deps.front().DefOp, Stack); 1054 } 1055 } 1056 } 1057 1058 // Go through the block backwards. 1059 for (MachineBasicBlock::const_iterator BI = MBB->end(), BB = MBB->begin(); 1060 BI != BB;) { 1061 const MachineInstr *MI = --BI; 1062 1063 // Find the MI height as determined by virtual register uses in the 1064 // trace below. 1065 unsigned Cycle = 0; 1066 MIHeightMap::iterator HeightI = Heights.find(MI); 1067 if (HeightI != Heights.end()) { 1068 Cycle = HeightI->second; 1069 // We won't be seeing any more MI uses. 1070 Heights.erase(HeightI); 1071 } 1072 1073 // Don't process PHI deps. They depend on the specific predecessor, and 1074 // we'll get them when visiting the predecessor. 1075 Deps.clear(); 1076 bool HasPhysRegs = !MI->isPHI() && getDataDeps(MI, Deps, MTM.MRI); 1077 1078 // There may also be regunit dependencies to include in the height. 1079 if (HasPhysRegs) 1080 Cycle = updatePhysDepsUpwards(MI, Cycle, RegUnits, 1081 MTM.SchedModel, MTM.TII, MTM.TRI); 1082 1083 // Update the required height of any virtual registers read by MI. 1084 for (unsigned i = 0, e = Deps.size(); i != e; ++i) 1085 if (pushDepHeight(Deps[i], MI, Cycle, Heights, MTM.SchedModel, MTM.TII)) 1086 addLiveIns(Deps[i].DefMI, Deps[i].DefOp, Stack); 1087 1088 InstrCycles &MICycles = Cycles[MI]; 1089 MICycles.Height = Cycle; 1090 if (!TBI.HasValidInstrDepths) { 1091 DEBUG(dbgs() << Cycle << '\t' << *MI); 1092 continue; 1093 } 1094 // Update critical path length. 1095 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Depth); 1096 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << *MI); 1097 } 1098 1099 // Update virtual live-in heights. They were added by addLiveIns() with a 0 1100 // height because the final height isn't known until now. 1101 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " Live-ins:"); 1102 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) { 1103 LiveInReg &LIR = TBI.LiveIns[i]; 1104 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg); 1105 LIR.Height = Heights.lookup(DefMI); 1106 DEBUG(dbgs() << ' ' << PrintReg(LIR.Reg) << '@' << LIR.Height); 1107 } 1108 1109 // Transfer the live regunits to the live-in list. 1110 for (SparseSet<LiveRegUnit>::const_iterator 1111 RI = RegUnits.begin(), RE = RegUnits.end(); RI != RE; ++RI) { 1112 TBI.LiveIns.push_back(LiveInReg(RI->RegUnit, RI->Cycle)); 1113 DEBUG(dbgs() << ' ' << PrintRegUnit(RI->RegUnit, MTM.TRI) 1114 << '@' << RI->Cycle); 1115 } 1116 DEBUG(dbgs() << '\n'); 1117 1118 if (!TBI.HasValidInstrDepths) 1119 continue; 1120 // Add live-ins to the critical path length. 1121 TBI.CriticalPath = std::max(TBI.CriticalPath, 1122 computeCrossBlockCriticalPath(TBI)); 1123 DEBUG(dbgs() << "Critical path: " << TBI.CriticalPath << '\n'); 1124 } 1125 } 1126 1127 MachineTraceMetrics::Trace 1128 MachineTraceMetrics::Ensemble::getTrace(const MachineBasicBlock *MBB) { 1129 // FIXME: Check cache tags, recompute as needed. 1130 computeTrace(MBB); 1131 computeInstrDepths(MBB); 1132 computeInstrHeights(MBB); 1133 return Trace(*this, BlockInfo[MBB->getNumber()]); 1134 } 1135 1136 unsigned 1137 MachineTraceMetrics::Trace::getInstrSlack(const MachineInstr *MI) const { 1138 assert(MI && "Not an instruction."); 1139 assert(getBlockNum() == unsigned(MI->getParent()->getNumber()) && 1140 "MI must be in the trace center block"); 1141 InstrCycles Cyc = getInstrCycles(MI); 1142 return getCriticalPath() - (Cyc.Depth + Cyc.Height); 1143 } 1144 1145 unsigned 1146 MachineTraceMetrics::Trace::getPHIDepth(const MachineInstr *PHI) const { 1147 const MachineBasicBlock *MBB = TE.MTM.MF->getBlockNumbered(getBlockNum()); 1148 SmallVector<DataDep, 1> Deps; 1149 getPHIDeps(PHI, Deps, MBB, TE.MTM.MRI); 1150 assert(Deps.size() == 1 && "PHI doesn't have MBB as a predecessor"); 1151 DataDep &Dep = Deps.front(); 1152 unsigned DepCycle = getInstrCycles(Dep.DefMI).Depth; 1153 // Add latency if DefMI is a real instruction. Transients get latency 0. 1154 if (!Dep.DefMI->isTransient()) 1155 DepCycle += TE.MTM.SchedModel 1156 .computeOperandLatency(Dep.DefMI, Dep.DefOp, PHI, Dep.UseOp); 1157 return DepCycle; 1158 } 1159 1160 /// When bottom is set include instructions in current block in estimate. 1161 unsigned MachineTraceMetrics::Trace::getResourceDepth(bool Bottom) const { 1162 // Find the limiting processor resource. 1163 // Numbers have been pre-scaled to be comparable. 1164 unsigned PRMax = 0; 1165 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum()); 1166 if (Bottom) { 1167 ArrayRef<unsigned> PRCycles = TE.MTM.getProcResourceCycles(getBlockNum()); 1168 for (unsigned K = 0; K != PRDepths.size(); ++K) 1169 PRMax = std::max(PRMax, PRDepths[K] + PRCycles[K]); 1170 } else { 1171 for (unsigned K = 0; K != PRDepths.size(); ++K) 1172 PRMax = std::max(PRMax, PRDepths[K]); 1173 } 1174 // Convert to cycle count. 1175 PRMax = TE.MTM.getCycles(PRMax); 1176 1177 /// All instructions before current block 1178 unsigned Instrs = TBI.InstrDepth; 1179 // plus instructions in current block 1180 if (Bottom) 1181 Instrs += TE.MTM.BlockInfo[getBlockNum()].InstrCount; 1182 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth()) 1183 Instrs /= IW; 1184 // Assume issue width 1 without a schedule model. 1185 return std::max(Instrs, PRMax); 1186 } 1187 1188 unsigned MachineTraceMetrics::Trace::getResourceLength( 1189 ArrayRef<const MachineBasicBlock *> Extrablocks, 1190 ArrayRef<const MCSchedClassDesc *> ExtraInstrs, 1191 ArrayRef<const MCSchedClassDesc *> RemoveInstrs) const { 1192 // Add up resources above and below the center block. 1193 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum()); 1194 ArrayRef<unsigned> PRHeights = TE.getProcResourceHeights(getBlockNum()); 1195 unsigned PRMax = 0; 1196 1197 // Capture computing cycles from extra instructions 1198 auto extraCycles = [this](ArrayRef<const MCSchedClassDesc *> Instrs, 1199 unsigned ResourceIdx) 1200 ->unsigned { 1201 unsigned Cycles = 0; 1202 for (unsigned I = 0; I != Instrs.size(); ++I) { 1203 const MCSchedClassDesc *SC = Instrs[I]; 1204 if (!SC->isValid()) 1205 continue; 1206 for (TargetSchedModel::ProcResIter 1207 PI = TE.MTM.SchedModel.getWriteProcResBegin(SC), 1208 PE = TE.MTM.SchedModel.getWriteProcResEnd(SC); 1209 PI != PE; ++PI) { 1210 if (PI->ProcResourceIdx != ResourceIdx) 1211 continue; 1212 Cycles += 1213 (PI->Cycles * TE.MTM.SchedModel.getResourceFactor(ResourceIdx)); 1214 } 1215 } 1216 return Cycles; 1217 }; 1218 1219 for (unsigned K = 0; K != PRDepths.size(); ++K) { 1220 unsigned PRCycles = PRDepths[K] + PRHeights[K]; 1221 for (unsigned I = 0; I != Extrablocks.size(); ++I) 1222 PRCycles += TE.MTM.getProcResourceCycles(Extrablocks[I]->getNumber())[K]; 1223 PRCycles += extraCycles(ExtraInstrs, K); 1224 PRCycles -= extraCycles(RemoveInstrs, K); 1225 PRMax = std::max(PRMax, PRCycles); 1226 } 1227 // Convert to cycle count. 1228 PRMax = TE.MTM.getCycles(PRMax); 1229 1230 // Instrs: #instructions in current trace outside current block. 1231 unsigned Instrs = TBI.InstrDepth + TBI.InstrHeight; 1232 // Add instruction count from the extra blocks. 1233 for (unsigned i = 0, e = Extrablocks.size(); i != e; ++i) 1234 Instrs += TE.MTM.getResources(Extrablocks[i])->InstrCount; 1235 Instrs += ExtraInstrs.size(); 1236 Instrs -= RemoveInstrs.size(); 1237 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth()) 1238 Instrs /= IW; 1239 // Assume issue width 1 without a schedule model. 1240 return std::max(Instrs, PRMax); 1241 } 1242 1243 bool MachineTraceMetrics::Trace::isDepInTrace(const MachineInstr *DefMI, 1244 const MachineInstr *UseMI) const { 1245 if (DefMI->getParent() == UseMI->getParent()) 1246 return true; 1247 1248 const TraceBlockInfo &DepTBI = TE.BlockInfo[DefMI->getParent()->getNumber()]; 1249 const TraceBlockInfo &TBI = TE.BlockInfo[UseMI->getParent()->getNumber()]; 1250 1251 return DepTBI.isUsefulDominator(TBI); 1252 } 1253 1254 void MachineTraceMetrics::Ensemble::print(raw_ostream &OS) const { 1255 OS << getName() << " ensemble:\n"; 1256 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) { 1257 OS << " BB#" << i << '\t'; 1258 BlockInfo[i].print(OS); 1259 OS << '\n'; 1260 } 1261 } 1262 1263 void MachineTraceMetrics::TraceBlockInfo::print(raw_ostream &OS) const { 1264 if (hasValidDepth()) { 1265 OS << "depth=" << InstrDepth; 1266 if (Pred) 1267 OS << " pred=BB#" << Pred->getNumber(); 1268 else 1269 OS << " pred=null"; 1270 OS << " head=BB#" << Head; 1271 if (HasValidInstrDepths) 1272 OS << " +instrs"; 1273 } else 1274 OS << "depth invalid"; 1275 OS << ", "; 1276 if (hasValidHeight()) { 1277 OS << "height=" << InstrHeight; 1278 if (Succ) 1279 OS << " succ=BB#" << Succ->getNumber(); 1280 else 1281 OS << " succ=null"; 1282 OS << " tail=BB#" << Tail; 1283 if (HasValidInstrHeights) 1284 OS << " +instrs"; 1285 } else 1286 OS << "height invalid"; 1287 if (HasValidInstrDepths && HasValidInstrHeights) 1288 OS << ", crit=" << CriticalPath; 1289 } 1290 1291 void MachineTraceMetrics::Trace::print(raw_ostream &OS) const { 1292 unsigned MBBNum = &TBI - &TE.BlockInfo[0]; 1293 1294 OS << TE.getName() << " trace BB#" << TBI.Head << " --> BB#" << MBBNum 1295 << " --> BB#" << TBI.Tail << ':'; 1296 if (TBI.hasValidHeight() && TBI.hasValidDepth()) 1297 OS << ' ' << getInstrCount() << " instrs."; 1298 if (TBI.HasValidInstrDepths && TBI.HasValidInstrHeights) 1299 OS << ' ' << TBI.CriticalPath << " cycles."; 1300 1301 const MachineTraceMetrics::TraceBlockInfo *Block = &TBI; 1302 OS << "\nBB#" << MBBNum; 1303 while (Block->hasValidDepth() && Block->Pred) { 1304 unsigned Num = Block->Pred->getNumber(); 1305 OS << " <- BB#" << Num; 1306 Block = &TE.BlockInfo[Num]; 1307 } 1308 1309 Block = &TBI; 1310 OS << "\n "; 1311 while (Block->hasValidHeight() && Block->Succ) { 1312 unsigned Num = Block->Succ->getNumber(); 1313 OS << " -> BB#" << Num; 1314 Block = &TE.BlockInfo[Num]; 1315 } 1316 OS << '\n'; 1317 } 1318