LCOV - code coverage report
Current view: top level - lib/CodeGen - ScheduleDAGInstrs.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 503 539 93.3 %
Date: 2018-06-17 00:07:59 Functions: 36 41 87.8 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===---- ScheduleDAGInstrs.cpp - MachineInstr Rescheduling ---------------===//
       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             : /// \file This implements the ScheduleDAGInstrs class, which implements
      11             : /// re-scheduling of MachineInstrs.
      12             : //
      13             : //===----------------------------------------------------------------------===//
      14             : 
      15             : #include "llvm/CodeGen/ScheduleDAGInstrs.h"
      16             : #include "llvm/ADT/IntEqClasses.h"
      17             : #include "llvm/ADT/MapVector.h"
      18             : #include "llvm/ADT/SmallPtrSet.h"
      19             : #include "llvm/ADT/SmallVector.h"
      20             : #include "llvm/ADT/SparseSet.h"
      21             : #include "llvm/ADT/iterator_range.h"
      22             : #include "llvm/Analysis/AliasAnalysis.h"
      23             : #include "llvm/Analysis/ValueTracking.h"
      24             : #include "llvm/CodeGen/LiveIntervals.h"
      25             : #include "llvm/CodeGen/LivePhysRegs.h"
      26             : #include "llvm/CodeGen/MachineBasicBlock.h"
      27             : #include "llvm/CodeGen/MachineFrameInfo.h"
      28             : #include "llvm/CodeGen/MachineFunction.h"
      29             : #include "llvm/CodeGen/MachineInstr.h"
      30             : #include "llvm/CodeGen/MachineInstrBundle.h"
      31             : #include "llvm/CodeGen/MachineMemOperand.h"
      32             : #include "llvm/CodeGen/MachineOperand.h"
      33             : #include "llvm/CodeGen/MachineRegisterInfo.h"
      34             : #include "llvm/CodeGen/PseudoSourceValue.h"
      35             : #include "llvm/CodeGen/RegisterPressure.h"
      36             : #include "llvm/CodeGen/ScheduleDAG.h"
      37             : #include "llvm/CodeGen/ScheduleDFS.h"
      38             : #include "llvm/CodeGen/SlotIndexes.h"
      39             : #include "llvm/CodeGen/TargetRegisterInfo.h"
      40             : #include "llvm/CodeGen/TargetSubtargetInfo.h"
      41             : #include "llvm/Config/llvm-config.h"
      42             : #include "llvm/IR/Constants.h"
      43             : #include "llvm/IR/Function.h"
      44             : #include "llvm/IR/Instruction.h"
      45             : #include "llvm/IR/Instructions.h"
      46             : #include "llvm/IR/Operator.h"
      47             : #include "llvm/IR/Type.h"
      48             : #include "llvm/IR/Value.h"
      49             : #include "llvm/MC/LaneBitmask.h"
      50             : #include "llvm/MC/MCRegisterInfo.h"
      51             : #include "llvm/Support/Casting.h"
      52             : #include "llvm/Support/CommandLine.h"
      53             : #include "llvm/Support/Compiler.h"
      54             : #include "llvm/Support/Debug.h"
      55             : #include "llvm/Support/ErrorHandling.h"
      56             : #include "llvm/Support/Format.h"
      57             : #include "llvm/Support/raw_ostream.h"
      58             : #include <algorithm>
      59             : #include <cassert>
      60             : #include <iterator>
      61             : #include <string>
      62             : #include <utility>
      63             : #include <vector>
      64             : 
      65             : using namespace llvm;
      66             : 
      67             : #define DEBUG_TYPE "machine-scheduler"
      68             : 
      69      101169 : static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
      70      202338 :     cl::ZeroOrMore, cl::init(false),
      71      202338 :     cl::desc("Enable use of AA during MI DAG construction"));
      72             : 
      73      101169 : static cl::opt<bool> UseTBAA("use-tbaa-in-sched-mi", cl::Hidden,
      74      101169 :     cl::init(true), cl::desc("Enable use of TBAA during MI DAG construction"));
      75             : 
      76             : // Note: the two options below might be used in tuning compile time vs
      77             : // output quality. Setting HugeRegion so large that it will never be
      78             : // reached means best-effort, but may be slow.
      79             : 
      80             : // When Stores and Loads maps (or NonAliasStores and NonAliasLoads)
      81             : // together hold this many SUs, a reduction of maps will be done.
      82      101169 : static cl::opt<unsigned> HugeRegion("dag-maps-huge-region", cl::Hidden,
      83      202338 :     cl::init(1000), cl::desc("The limit to use while constructing the DAG "
      84             :                              "prior to scheduling, at which point a trade-off "
      85      101169 :                              "is made to avoid excessive compile time."));
      86             : 
      87      101169 : static cl::opt<unsigned> ReductionSize(
      88             :     "dag-maps-reduction-size", cl::Hidden,
      89      101169 :     cl::desc("A huge scheduling region will have maps reduced by this many "
      90      101169 :              "nodes at a time. Defaults to HugeRegion / 2."));
      91             : 
      92             : static unsigned getReductionSize() {
      93             :   // Always reduce a huge region with half of the elements, except
      94             :   // when user sets this number explicitly.
      95           7 :   if (ReductionSize.getNumOccurrences() == 0)
      96           7 :     return HugeRegion / 2;
      97             :   return ReductionSize;
      98             : }
      99             : 
     100             : static void dumpSUList(ScheduleDAGInstrs::SUList &L) {
     101             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
     102             :   dbgs() << "{ ";
     103             :   for (const SUnit *su : L) {
     104             :     dbgs() << "SU(" << su->NodeNum << ")";
     105             :     if (su != L.back())
     106             :       dbgs() << ", ";
     107             :   }
     108             :   dbgs() << "}\n";
     109             : #endif
     110             : }
     111             : 
     112      213390 : ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
     113             :                                      const MachineLoopInfo *mli,
     114      213390 :                                      bool RemoveKillFlags)
     115      213390 :     : ScheduleDAG(mf), MLI(mli), MFI(mf.getFrameInfo()),
     116             :       RemoveKillFlags(RemoveKillFlags),
     117      213390 :       UnknownValue(UndefValue::get(
     118     1280340 :                              Type::getVoidTy(mf.getFunction().getContext()))) {
     119             :   DbgValues.clear();
     120             : 
     121      213390 :   const TargetSubtargetInfo &ST = mf.getSubtarget();
     122      213390 :   SchedModel.init(&ST);
     123      213390 : }
     124             : 
     125             : /// If this machine instr has memory reference information and it can be
     126             : /// tracked to a normal reference to a known object, return the Value
     127             : /// for that object. This function returns false the memory location is
     128             : /// unknown or may alias anything.
     129             : static bool getUnderlyingObjectsForInstr(const MachineInstr *MI,
     130             :                                          const MachineFrameInfo &MFI,
     131             :                                          UnderlyingObjectsVector &Objects,
     132             :                                          const DataLayout &DL) {
     133     1111092 :   auto allMMOsOkay = [&]() {
     134     4634998 :     for (const MachineMemOperand *MMO : MI->memoperands()) {
     135     2831772 :       if (MMO->isVolatile())
     136             :         return false;
     137             : 
     138      172333 :       if (const PseudoSourceValue *PSV = MMO->getPseudoValue()) {
     139             :         // Function that contain tail calls don't have unique PseudoSourceValue
     140             :         // objects. Two PseudoSourceValues might refer to the same or
     141             :         // overlapping locations. The client code calling this function assumes
     142             :         // this is not the case. So return a conservative answer of no known
     143             :         // object.
     144      316678 :         if (MFI.hasTailCall())
     145             :           return false;
     146             : 
     147             :         // For now, ignore PseudoSourceValues which may alias LLVM IR values
     148             :         // because the code that uses this function has no way to cope with
     149             :         // such aliases.
     150      171321 :         if (PSV->isAliased(&MFI))
     151             :           return false;
     152             : 
     153      288690 :         bool MayAlias = PSV->mayAlias(&MFI);
     154     1351085 :         Objects.push_back(UnderlyingObjectsVector::value_type(PSV, MayAlias));
     155     1243553 :       } else if (const Value *V = MMO->getValue()) {
     156             :         SmallVector<Value *, 4> Objs;
     157     1232763 :         if (!getUnderlyingObjectsForCodeGen(V, Objs, DL))
     158             :           return false;
     159             : 
     160     3186852 :         for (Value *V : Objs) {
     161             :           assert(isIdentifiedObject(V));
     162     2124790 :           Objects.push_back(UnderlyingObjectsVector::value_type(V, true));
     163             :         }
     164             :       } else
     165             :         return false;
     166             :     }
     167             :     return true;
     168     1111092 :   };
     169             : 
     170     1111092 :   if (!allMMOsOkay()) {
     171             :     Objects.clear();
     172             :     return false;
     173             :   }
     174             : 
     175             :   return true;
     176             : }
     177             : 
     178      456425 : void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
     179      456425 :   BB = bb;
     180      456425 : }
     181             : 
     182      457118 : void ScheduleDAGInstrs::finishBlock() {
     183             :   // Subclasses should no longer refer to the old block.
     184      457118 :   BB = nullptr;
     185      457118 : }
     186             : 
     187     1331933 : void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
     188             :                                     MachineBasicBlock::iterator begin,
     189             :                                     MachineBasicBlock::iterator end,
     190             :                                     unsigned regioninstrs) {
     191             :   assert(bb == BB && "startBlock should set BB");
     192     1331933 :   RegionBegin = begin;
     193     1331933 :   RegionEnd = end;
     194     1331933 :   NumRegionInstrs = regioninstrs;
     195     1331933 : }
     196             : 
     197     1331933 : void ScheduleDAGInstrs::exitRegion() {
     198             :   // Nothing to do.
     199     1331933 : }
     200             : 
     201      819566 : void ScheduleDAGInstrs::addSchedBarrierDeps() {
     202     1639132 :   MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : nullptr;
     203             :   ExitSU.setInstr(ExitMI);
     204             :   // Add dependencies on the defs and uses of the instruction.
     205      687174 :   if (ExitMI) {
     206     5916996 :     for (const MachineOperand &MO : ExitMI->operands()) {
     207     5840247 :       if (!MO.isReg() || MO.isDef()) continue;
     208     1168108 :       unsigned Reg = MO.getReg();
     209     1168108 :       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
     210     2275328 :         Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
     211       30444 :       } else if (TargetRegisterInfo::isVirtualRegister(Reg) && MO.readsReg()) {
     212        5431 :         addVRegUseDeps(&ExitSU, ExitMI->getOperandNo(&MO));
     213             :       }
     214             :     }
     215             :   }
     216     2004937 :   if (!ExitMI || (!ExitMI->isCall() && !ExitMI->isBarrier())) {
     217             :     // For others, e.g. fallthrough, conditional branch, assume the exit
     218             :     // uses all the registers that are livein to the successor blocks.
     219     1326212 :     for (const MachineBasicBlock *Succ : BB->successors()) {
     220     1545160 :       for (const auto &LI : Succ->liveins()) {
     221     1050374 :         if (!Uses.contains(LI.PhysReg))
     222     1554456 :           Uses.insert(PhysRegSUOper(&ExitSU, -1, LI.PhysReg));
     223             :       }
     224             :     }
     225             :   }
     226      819566 : }
     227             : 
     228             : /// MO is an operand of SU's instruction that defines a physical register. Adds
     229             : /// data dependencies from SU to any uses of the physical register.
     230     1786176 : void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
     231     1786176 :   const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
     232             :   assert(MO.isDef() && "expect physreg def");
     233             : 
     234             :   // Ask the target if address-backscheduling is desirable, and if so how much.
     235     1786176 :   const TargetSubtargetInfo &ST = MF.getSubtarget();
     236             : 
     237    12954087 :   for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
     238    24121998 :        Alias.isValid(); ++Alias) {
     239    20121936 :     if (!Uses.contains(*Alias))
     240     8954025 :       continue;
     241             :     for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
     242     2720542 :       SUnit *UseSU = I->SU;
     243     2720542 :       if (UseSU == SU)
     244           0 :         continue;
     245             : 
     246             :       // Adjust the dependence latency using operand def/use information,
     247             :       // then allow the target to perform its own adjustments.
     248     2720542 :       int UseOp = I->OpIdx;
     249             :       MachineInstr *RegUse = nullptr;
     250             :       SDep Dep;
     251     2720542 :       if (UseOp < 0)
     252     1120237 :         Dep = SDep(SU, SDep::Artificial);
     253             :       else {
     254             :         // Set the hasPhysRegDefs only for physreg defs that have a use within
     255             :         // the scheduling region.
     256     1600305 :         SU->hasPhysRegDefs = true;
     257     1600305 :         Dep = SDep(SU, SDep::Data, *Alias);
     258     1600305 :         RegUse = UseSU->getInstr();
     259             :       }
     260     5441084 :       Dep.setLatency(
     261     2720542 :         SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, RegUse,
     262             :                                          UseOp));
     263             : 
     264     2720542 :       ST.adjustSchedDependency(SU, UseSU, Dep);
     265     2720542 :       UseSU->addPred(Dep);
     266             :     }
     267             :   }
     268     1786176 : }
     269             : 
     270             : /// Adds register dependencies (data, anti, and output) from this SUnit
     271             : /// to following instructions in the same scheduling region that depend the
     272             : /// physical register referenced at OperIdx.
     273     4670864 : void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
     274     4670864 :   MachineInstr *MI = SU->getInstr();
     275     4670864 :   MachineOperand &MO = MI->getOperand(OperIdx);
     276     4670864 :   unsigned Reg = MO.getReg();
     277             :   // We do not need to track any dependencies for constant registers.
     278     4670864 :   if (MRI.isConstantPhysReg(Reg))
     279             :     return;
     280             : 
     281             :   // Optionally add output and anti dependencies. For anti
     282             :   // dependencies we use a latency of 0 because for a multi-issue
     283             :   // target we want to allow the defining instruction to issue
     284             :   // in the same cycle as the using instruction.
     285             :   // TODO: Using a latency of 1 here for output dependencies assumes
     286             :   //       there's no cost for reusing registers.
     287     3919687 :   SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
     288    63987230 :   for (MCRegAliasIterator Alias(Reg, TRI, true); Alias.isValid(); ++Alias) {
     289    54237402 :     if (!Defs.contains(*Alias))
     290    26163474 :       continue;
     291             :     for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
     292     3168322 :       SUnit *DefSU = I->SU;
     293     3168322 :       if (DefSU == &ExitSU)
     294           0 :         continue;
     295     3168322 :       if (DefSU != SU &&
     296     3249257 :           (Kind != SDep::Output || !MO.isDead() ||
     297     1262775 :            !DefSU->getInstr()->registerDefIsDead(*Alias))) {
     298     1430657 :         if (Kind == SDep::Anti)
     299      540842 :           DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
     300             :         else {
     301             :           SDep Dep(SU, Kind, /*Reg=*/*Alias);
     302     1779630 :           Dep.setLatency(
     303      889815 :             SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
     304      889815 :           DefSU->addPred(Dep);
     305             :         }
     306             :       }
     307             :     }
     308             :   }
     309             : 
     310     3919687 :   if (!MO.isDef()) {
     311     2133511 :     SU->hasPhysRegUses = true;
     312             :     // Either insert a new Reg2SUnits entry with an empty SUnits list, or
     313             :     // retrieve the existing SUnits list for this register's uses.
     314             :     // Push this SUnit on the use list.
     315     4267022 :     Uses.insert(PhysRegSUOper(SU, OperIdx, Reg));
     316     2133511 :     if (RemoveKillFlags)
     317             :       MO.setIsKill(false);
     318             :   } else {
     319     1786176 :     addPhysRegDataDeps(SU, OperIdx);
     320             : 
     321             :     // Clear previous uses and defs of this register and its subergisters.
     322     7570978 :     for (MCSubRegIterator SubReg(Reg, TRI, true); SubReg.isValid(); ++SubReg) {
     323     3998626 :       if (Uses.contains(*SubReg))
     324     1283168 :         Uses.eraseAll(*SubReg);
     325     3998626 :       if (!MO.isDead())
     326     3509935 :         Defs.eraseAll(*SubReg);
     327             :     }
     328     1786176 :     if (MO.isDead() && SU->isCall) {
     329             :       // Calls will not be reordered because of chain dependencies (see
     330             :       // below). Since call operands are dead, calls may continue to be added
     331             :       // to the DefList making dependence checking quadratic in the size of
     332             :       // the block. Instead, we leave only one call at the back of the
     333             :       // DefList.
     334        1382 :       Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
     335             :       Reg2SUnitsMap::iterator B = P.first;
     336        1382 :       Reg2SUnitsMap::iterator I = P.second;
     337        2654 :       for (bool isBegin = I == B; !isBegin; /* empty */) {
     338        1100 :         isBegin = (--I) == B;
     339        1100 :         if (!I->SU->isCall)
     340             :           break;
     341         636 :         I = Defs.erase(I);
     342             :       }
     343             :     }
     344             : 
     345             :     // Defs are pushed in the order they are visited and never reordered.
     346     3572352 :     Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
     347             :   }
     348             : }
     349             : 
     350      590137 : LaneBitmask ScheduleDAGInstrs::getLaneMaskForMO(const MachineOperand &MO) const
     351             : {
     352      590137 :   unsigned Reg = MO.getReg();
     353             :   // No point in tracking lanemasks if we don't have interesting subregisters.
     354      590137 :   const TargetRegisterClass &RC = *MRI.getRegClass(Reg);
     355      590137 :   if (!RC.HasDisjunctSubRegs)
     356      238888 :     return LaneBitmask::getAll();
     357             : 
     358             :   unsigned SubReg = MO.getSubReg();
     359      351249 :   if (SubReg == 0)
     360             :     return RC.getLaneMask();
     361      175218 :   return TRI->getSubRegIndexLaneMask(SubReg);
     362             : }
     363             : 
     364             : /// Adds register output and data dependencies from this SUnit to instructions
     365             : /// that occur later in the same scheduling region if they read from or write to
     366             : /// the virtual register defined at OperIdx.
     367             : ///
     368             : /// TODO: Hoist loop induction variable increments. This has to be
     369             : /// reevaluated. Generally, IV scheduling should be done before coalescing.
     370     1430216 : void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
     371     1430216 :   MachineInstr *MI = SU->getInstr();
     372     1430216 :   MachineOperand &MO = MI->getOperand(OperIdx);
     373     1430216 :   unsigned Reg = MO.getReg();
     374             : 
     375             :   LaneBitmask DefLaneMask;
     376             :   LaneBitmask KillLaneMask;
     377     1430216 :   if (TrackLaneMasks) {
     378      371171 :     bool IsKill = MO.getSubReg() == 0 || MO.isUndef();
     379      268420 :     DefLaneMask = getLaneMaskForMO(MO);
     380             :     // If we have a <read-undef> flag, none of the lane values comes from an
     381             :     // earlier instruction.
     382      268420 :     KillLaneMask = IsKill ? LaneBitmask::getAll() : DefLaneMask;
     383             : 
     384             :     // Clear undef flag, we'll re-add it later once we know which subregister
     385             :     // Def is first.
     386             :     MO.setIsUndef(false);
     387             :   } else {
     388             :     DefLaneMask = LaneBitmask::getAll();
     389             :     KillLaneMask = LaneBitmask::getAll();
     390             :   }
     391             : 
     392     1430216 :   if (MO.isDead()) {
     393             :     assert(CurrentVRegUses.find(Reg) == CurrentVRegUses.end() &&
     394             :            "Dead defs should have no uses");
     395             :   } else {
     396             :     // Add data dependence to all uses we found so far.
     397     1420797 :     const TargetSubtargetInfo &ST = MF.getSubtarget();
     398     1420797 :     for (VReg2SUnitOperIdxMultiMap::iterator I = CurrentVRegUses.find(Reg),
     399             :          E = CurrentVRegUses.end(); I != E; /*empty*/) {
     400     1723379 :       LaneBitmask LaneMask = I->LaneMask;
     401             :       // Ignore uses of other lanes.
     402     1762093 :       if ((LaneMask & KillLaneMask).none()) {
     403             :         ++I;
     404             :         continue;
     405             :       }
     406             : 
     407     1684665 :       if ((LaneMask & DefLaneMask).any()) {
     408     1684664 :         SUnit *UseSU = I->SU;
     409     1684664 :         MachineInstr *Use = UseSU->getInstr();
     410             :         SDep Dep(SU, SDep::Data, Reg);
     411     1684664 :         Dep.setLatency(SchedModel.computeOperandLatency(MI, OperIdx, Use,
     412             :                                                         I->OperandIndex));
     413     1684664 :         ST.adjustSchedDependency(SU, UseSU, Dep);
     414     1684664 :         UseSU->addPred(Dep);
     415             :       }
     416             : 
     417             :       LaneMask &= ~KillLaneMask;
     418             :       // If we found a Def for all lanes of this use, remove it from the list.
     419     1684665 :       if (LaneMask.any()) {
     420       84851 :         I->LaneMask = LaneMask;
     421             :         ++I;
     422             :       } else
     423     1599814 :         I = CurrentVRegUses.erase(I);
     424             :     }
     425             :   }
     426             : 
     427             :   // Shortcut: Singly defined vregs do not have output/anti dependencies.
     428     1430216 :   if (MRI.hasOneDef(Reg))
     429             :     return;
     430             : 
     431             :   // Add output dependence to the next nearest defs of this vreg.
     432             :   //
     433             :   // Unless this definition is dead, the output dependence should be
     434             :   // transitively redundant with antidependencies from this definition's
     435             :   // uses. We're conservative for now until we have a way to guarantee the uses
     436             :   // are not eliminated sometime during scheduling. The output dependence edge
     437             :   // is also useful if output latency exceeds def-use latency.
     438             :   LaneBitmask LaneMask = DefLaneMask;
     439             :   for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
     440      559385 :                                      CurrentVRegDefs.end())) {
     441             :     // Ignore defs for other lanes.
     442      602112 :     if ((V2SU.LaneMask & LaneMask).none())
     443      271668 :       continue;
     444             :     // Add an output dependence.
     445      330444 :     SUnit *DefSU = V2SU.SU;
     446             :     // Ignore additional defs of the same lanes in one instruction. This can
     447             :     // happen because lanemasks are shared for targets with too many
     448             :     // subregisters. We also use some representration tricks/hacks where we
     449             :     // add super-register defs/uses, to imply that although we only access parts
     450             :     // of the reg we care about the full one.
     451      330444 :     if (DefSU == SU)
     452           0 :       continue;
     453             :     SDep Dep(SU, SDep::Output, Reg);
     454      660888 :     Dep.setLatency(
     455      330444 :       SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
     456      330444 :     DefSU->addPred(Dep);
     457             : 
     458             :     // Update current definition. This can get tricky if the def was about a
     459             :     // bigger lanemask before. We then have to shrink it and create a new
     460             :     // VReg2SUnit for the non-overlapping part.
     461             :     LaneBitmask OverlapMask = V2SU.LaneMask & LaneMask;
     462             :     LaneBitmask NonOverlapMask = V2SU.LaneMask & ~LaneMask;
     463      330444 :     V2SU.SU = SU;
     464      330444 :     V2SU.LaneMask = OverlapMask;
     465      330444 :     if (NonOverlapMask.any())
     466         127 :       CurrentVRegDefs.insert(VReg2SUnit(Reg, NonOverlapMask, DefSU));
     467             :   }
     468             :   // If there was no CurrentVRegDefs entry for some lanes yet, create one.
     469      559385 :   if (LaneMask.any())
     470      559385 :     CurrentVRegDefs.insert(VReg2SUnit(Reg, LaneMask, SU));
     471             : }
     472             : 
     473             : /// Adds a register data dependency if the instruction that defines the
     474             : /// virtual register used at OperIdx is mapped to an SUnit. Add a register
     475             : /// antidependency from this SUnit to instructions that occur later in the same
     476             : /// scheduling region if they write the virtual register.
     477             : ///
     478             : /// TODO: Handle ExitSU "uses" properly.
     479     2221784 : void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
     480     2221784 :   const MachineInstr *MI = SU->getInstr();
     481     2221784 :   const MachineOperand &MO = MI->getOperand(OperIdx);
     482     2221784 :   unsigned Reg = MO.getReg();
     483             : 
     484             :   // Remember the use. Data dependencies will be added when we find the def.
     485     2221784 :   LaneBitmask LaneMask = TrackLaneMasks ? getLaneMaskForMO(MO)
     486     2221784 :                                         : LaneBitmask::getAll();
     487     4443568 :   CurrentVRegUses.insert(VReg2SUnitOperIdx(Reg, LaneMask, OperIdx, SU));
     488             : 
     489             :   // Add antidependences to the following defs of the vreg.
     490             :   for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
     491     2221784 :                                      CurrentVRegDefs.end())) {
     492             :     // Ignore defs for unrelated lanes.
     493      394963 :     LaneBitmask PrevDefLaneMask = V2SU.LaneMask;
     494      394963 :     if ((PrevDefLaneMask & LaneMask).none())
     495       25278 :       continue;
     496      369685 :     if (V2SU.SU == SU)
     497      302308 :       continue;
     498             : 
     499       67377 :     V2SU.SU->addPred(SDep(SU, SDep::Anti, Reg));
     500             :   }
     501     2221784 : }
     502             : 
     503             : /// Returns true if MI is an instruction we are unable to reason about
     504             : /// (like a call or something with unmodeled side effects).
     505     3465780 : static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
     506     6900145 :   return MI->isCall() || MI->hasUnmodeledSideEffects() ||
     507     3494195 :          (MI->hasOrderedMemoryRef() && !MI->isDereferenceableInvariantLoad(AA));
     508             : }
     509             : 
     510     3289135 : void ScheduleDAGInstrs::addChainDependency (SUnit *SUa, SUnit *SUb,
     511             :                                             unsigned Latency) {
     512     6578270 :   if (SUa->getInstr()->mayAlias(AAForDep, *SUb->getInstr(), UseTBAA)) {
     513             :     SDep Dep(SUa, SDep::MayAliasMem);
     514             :     Dep.setLatency(Latency);
     515     1855124 :     SUb->addPred(Dep);
     516             :   }
     517     3289135 : }
     518             : 
     519             : /// Creates an SUnit for each real instruction, numbered in top-down
     520             : /// topological order. The instruction order A < B, implies that no edge exists
     521             : /// from B to A.
     522             : ///
     523             : /// Map each real instruction to its SUnit.
     524             : ///
     525             : /// After initSUnits, the SUnits vector cannot be resized and the scheduler may
     526             : /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
     527             : /// instead of pointers.
     528             : ///
     529             : /// MachineScheduler relies on initSUnits numbering the nodes by their order in
     530             : /// the original instruction list.
     531      819566 : void ScheduleDAGInstrs::initSUnits() {
     532             :   // We'll be allocating one SUnit for each real instruction in the region,
     533             :   // which is contained within a basic block.
     534      819566 :   SUnits.reserve(NumRegionInstrs);
     535             : 
     536     5138653 :   for (MachineInstr &MI : make_range(RegionBegin, RegionEnd)) {
     537       33741 :     if (MI.isDebugInstr())
     538       33741 :       continue;
     539             : 
     540             :     SUnit *SU = newSUnit(&MI);
     541     6931560 :     MISUnitMap[&MI] = SU;
     542             : 
     543     3465780 :     SU->isCall = MI.isCall();
     544     3465780 :     SU->isCommutable = MI.isCommutable();
     545             : 
     546             :     // Assign the Latency field of SU using target-provided information.
     547     3465780 :     SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
     548             : 
     549             :     // If this SUnit uses a reserved or unbuffered resource, mark it as such.
     550             :     //
     551             :     // Reserved resources block an instruction from issuing and stall the
     552             :     // entire pipeline. These are identified by BufferSize=0.
     553             :     //
     554             :     // Unbuffered resources prevent execution of subsequent instructions that
     555             :     // require the same resources. This is used for in-order execution pipelines
     556             :     // within an out-of-order core. These are identified by BufferSize=1.
     557     3465780 :     if (SchedModel.hasInstrSchedModel()) {
     558     1139476 :       const MCSchedClassDesc *SC = getSchedClass(SU);
     559     1877094 :       for (const MCWriteProcResEntry &PRE :
     560             :            make_range(SchedModel.getWriteProcResBegin(SC),
     561     4156046 :                       SchedModel.getWriteProcResEnd(SC))) {
     562     3754188 :         switch (SchedModel.getProcResource(PRE.ProcResourceIdx)->BufferSize) {
     563        1111 :         case 0:
     564        1111 :           SU->hasReservedResource = true;
     565        1111 :           break;
     566      321964 :         case 1:
     567      321964 :           SU->isUnbuffered = true;
     568      321964 :           break;
     569             :         default:
     570             :           break;
     571             :         }
     572             :       }
     573             :     }
     574             :   }
     575      819566 : }
     576             : 
     577     2458698 : class ScheduleDAGInstrs::Value2SUsMap : public MapVector<ValueType, SUList> {
     578             :   /// Current total number of SUs in map.
     579             :   unsigned NumNodes = 0;
     580             : 
     581             :   /// 1 for loads, 0 for stores. (see comment in SUList)
     582             :   unsigned TrueMemOrderLatency;
     583             : 
     584             : public:
     585     4097830 :   Value2SUsMap(unsigned lat = 0) : TrueMemOrderLatency(lat) {}
     586             : 
     587             :   /// To keep NumNodes up to date, insert() is used instead of
     588             :   /// this operator w/ push_back().
     589             :   ValueType &operator[](const SUList &Key) {
     590             :     llvm_unreachable("Don't use. Use insert() instead."); };
     591             : 
     592             :   /// Adds SU to the SUList of V. If Map grows huge, reduce its size by calling
     593             :   /// reduce().
     594     1416219 :   void inline insert(SUnit *SU, ValueType V) {
     595     1416219 :     MapVector::operator[](V).push_back(SU);
     596     1416219 :     NumNodes++;
     597     1416219 :   }
     598             : 
     599             :   /// Clears the list of SUs mapped to V.
     600             :   void inline clearList(ValueType V) {
     601             :     iterator Itr = find(V);
     602             :     if (Itr != end()) {
     603             :       assert(NumNodes >= Itr->second.size());
     604             :       NumNodes -= Itr->second.size();
     605             : 
     606             :       Itr->second.clear();
     607             :     }
     608             :   }
     609             : 
     610             :   /// Clears map from all contents.
     611             :   void clear() {
     612             :     MapVector<ValueType, SUList>::clear();
     613      364980 :     NumNodes = 0;
     614             :   }
     615             : 
     616             :   unsigned inline size() const { return NumNodes; }
     617             : 
     618             :   /// Counts the number of SUs in this map after a reduction.
     619             :   void reComputeSize() {
     620          14 :     NumNodes = 0;
     621        1474 :     for (auto &I : *this)
     622        1460 :       NumNodes += I.second.size();
     623             :   }
     624             : 
     625             :   unsigned inline getTrueMemOrderLatency() const {
     626             :     return TrueMemOrderLatency;
     627             :   }
     628             : 
     629             :   void dump();
     630             : };
     631             : 
     632      613788 : void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
     633             :                                              Value2SUsMap &Val2SUsMap) {
     634      778037 :   for (auto &I : Val2SUsMap)
     635      164249 :     addChainDependencies(SU, I.second,
     636             :                          Val2SUsMap.getTrueMemOrderLatency());
     637      613788 : }
     638             : 
     639     3838919 : void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
     640             :                                              Value2SUsMap &Val2SUsMap,
     641             :                                              ValueType V) {
     642     3838919 :   Value2SUsMap::iterator Itr = Val2SUsMap.find(V);
     643     3838919 :   if (Itr != Val2SUsMap.end())
     644      627974 :     addChainDependencies(SU, Itr->second,
     645             :                          Val2SUsMap.getTrueMemOrderLatency());
     646     3838919 : }
     647             : 
     648      364980 : void ScheduleDAGInstrs::addBarrierChain(Value2SUsMap &map) {
     649             :   assert(BarrierChain != nullptr);
     650             : 
     651      383929 :   for (auto &I : map) {
     652             :     SUList &sus = I.second;
     653       70961 :     for (auto *SU : sus)
     654       33063 :       SU->addPredBarrier(BarrierChain);
     655             :   }
     656             :   map.clear();
     657      364980 : }
     658             : 
     659          14 : void ScheduleDAGInstrs::insertBarrierChain(Value2SUsMap &map) {
     660             :   assert(BarrierChain != nullptr);
     661             : 
     662             :   // Go through all lists of SUs.
     663        2958 :   for (Value2SUsMap::iterator I = map.begin(), EE = map.end(); I != EE;) {
     664             :     Value2SUsMap::iterator CurrItr = I++;
     665        2944 :     SUList &sus = CurrItr->second;
     666        2944 :     SUList::iterator SUItr = sus.begin(), SUEE = sus.end();
     667        6437 :     for (; SUItr != SUEE; ++SUItr) {
     668             :       // Stop on BarrierChain or any instruction above it.
     669        4955 :       if ((*SUItr)->NodeNum <= BarrierChain->NodeNum)
     670             :         break;
     671             : 
     672        3493 :       (*SUItr)->addPredBarrier(BarrierChain);
     673             :     }
     674             : 
     675             :     // Remove also the BarrierChain from list if present.
     676        2944 :     if (SUItr != SUEE && *SUItr == BarrierChain)
     677             :       SUItr++;
     678             : 
     679             :     // Remove all SUs that are now successors of BarrierChain.
     680        2944 :     if (SUItr != sus.begin())
     681        1492 :       sus.erase(sus.begin(), SUItr);
     682             :   }
     683             : 
     684             :   // Remove all entries with empty su lists.
     685          14 :   map.remove_if([&](std::pair<ValueType, SUList> &mapEntry) {
     686             :       return (mapEntry.second.empty()); });
     687             : 
     688             :   // Recompute the size of the map (NumNodes).
     689             :   map.reComputeSize();
     690          14 : }
     691             : 
     692      819566 : void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
     693             :                                         RegPressureTracker *RPTracker,
     694             :                                         PressureDiffs *PDiffs,
     695             :                                         LiveIntervals *LIS,
     696             :                                         bool TrackLaneMasks) {
     697      819566 :   const TargetSubtargetInfo &ST = MF.getSubtarget();
     698     1639011 :   bool UseAA = EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI
     699      819445 :                                                        : ST.useAA();
     700      819566 :   AAForDep = UseAA ? AA : nullptr;
     701             : 
     702      819566 :   BarrierChain = nullptr;
     703             : 
     704      819566 :   this->TrackLaneMasks = TrackLaneMasks;
     705      819566 :   MISUnitMap.clear();
     706      819566 :   ScheduleDAG::clearDAG();
     707             : 
     708             :   // Create an SUnit for each real instruction.
     709      819566 :   initSUnits();
     710             : 
     711      819566 :   if (PDiffs)
     712      225000 :     PDiffs->init(SUnits.size());
     713             : 
     714             :   // We build scheduling units by walking a block's instruction list
     715             :   // from bottom to top.
     716             : 
     717             :   // Each MIs' memory operand(s) is analyzed to a list of underlying
     718             :   // objects. The SU is then inserted in the SUList(s) mapped from the
     719             :   // Value(s). Each Value thus gets mapped to lists of SUs depending
     720             :   // on it, stores and loads kept separately. Two SUs are trivially
     721             :   // non-aliasing if they both depend on only identified Values and do
     722             :   // not share any common Value.
     723             :   Value2SUsMap Stores, Loads(1 /*TrueMemOrderLatency*/);
     724             : 
     725             :   // Certain memory accesses are known to not alias any SU in Stores
     726             :   // or Loads, and have therefore their own 'NonAlias'
     727             :   // domain. E.g. spill / reload instructions never alias LLVM I/R
     728             :   // Values. It would be nice to assume that this type of memory
     729             :   // accesses always have a proper memory operand modelling, and are
     730             :   // therefore never unanalyzable, but this is conservatively not
     731             :   // done.
     732             :   Value2SUsMap NonAliasStores, NonAliasLoads(1 /*TrueMemOrderLatency*/);
     733             : 
     734             :   // Remove any stale debug info; sometimes BuildSchedGraph is called again
     735             :   // without emitting the info from the previous call.
     736      819566 :   DbgValues.clear();
     737      819566 :   FirstDbgValue = nullptr;
     738             : 
     739             :   assert(Defs.empty() && Uses.empty() &&
     740             :          "Only BuildGraph should update Defs/Uses");
     741      819566 :   Defs.setUniverse(TRI->getNumRegs());
     742      819566 :   Uses.setUniverse(TRI->getNumRegs());
     743             : 
     744             :   assert(CurrentVRegDefs.empty() && "nobody else should use CurrentVRegDefs");
     745             :   assert(CurrentVRegUses.empty() && "nobody else should use CurrentVRegUses");
     746      819566 :   unsigned NumVirtRegs = MRI.getNumVirtRegs();
     747             :   CurrentVRegDefs.setUniverse(NumVirtRegs);
     748      819566 :   CurrentVRegUses.setUniverse(NumVirtRegs);
     749             : 
     750             :   // Model data dependencies between instructions being scheduled and the
     751             :   // ExitSU.
     752      819566 :   addSchedBarrierDeps();
     753             : 
     754             :   // Walk the list of instructions, from bottom moving up.
     755             :   MachineInstr *DbgMI = nullptr;
     756      819566 :   for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
     757     4319087 :        MII != MIE; --MII) {
     758             :     MachineInstr &MI = *std::prev(MII);
     759     3499521 :     if (DbgMI) {
     760       61962 :       DbgValues.push_back(std::make_pair(DbgMI, &MI));
     761             :       DbgMI = nullptr;
     762             :     }
     763             : 
     764     3499521 :     if (MI.isDebugValue()) {
     765             :       DbgMI = &MI;
     766     2422170 :       continue;
     767             :     }
     768     3465780 :     if (MI.isDebugLabel())
     769           0 :       continue;
     770             : 
     771     6931560 :     SUnit *SU = MISUnitMap[&MI];
     772             :     assert(SU && "No SUnit mapped to this MI");
     773             : 
     774     3465780 :     if (RPTracker) {
     775     1411928 :       RegisterOperands RegOpers;
     776     1411928 :       RegOpers.collect(MI, *TRI, MRI, TrackLaneMasks, false);
     777     1411928 :       if (TrackLaneMasks) {
     778      603766 :         SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
     779      301883 :         RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx);
     780             :       }
     781     1411928 :       if (PDiffs != nullptr)
     782     1411928 :         PDiffs->addInstruction(SU->NodeNum, RegOpers, MRI);
     783             : 
     784     1411928 :       if (RPTracker->getPos() == RegionEnd || &*RPTracker->getPos() != &MI)
     785     1411928 :         RPTracker->recedeSkipDebugValues();
     786             :       assert(&*RPTracker->getPos() == &MI && "RPTracker in sync");
     787     1411928 :       RPTracker->recede(RegOpers);
     788             :     }
     789             : 
     790             :     assert(
     791             :         (CanHandleTerminators || (!MI.isTerminator() && !MI.isPosition())) &&
     792             :         "Cannot schedule terminators or labels!");
     793             : 
     794             :     // Add register-based dependencies (data, anti, and output).
     795             :     // For some instructions (calls, returns, inline-asm, etc.) there can
     796             :     // be explicit uses and implicit defs, in which case the use will appear
     797             :     // on the operand list before the def. Do two passes over the operand
     798             :     // list to make sure that defs are processed before any uses.
     799             :     bool HasVRegDef = false;
     800    19901201 :     for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
     801    16435421 :       const MachineOperand &MO = MI.getOperand(j);
     802    40439794 :       if (!MO.isReg() || !MO.isDef())
     803    13217648 :         continue;
     804     3217773 :       unsigned Reg = MO.getReg();
     805     3217773 :       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
     806     1787557 :         addPhysRegDeps(SU, j);
     807     1430216 :       } else if (TargetRegisterInfo::isVirtualRegister(Reg)) {
     808             :         HasVRegDef = true;
     809     1430216 :         addVRegDefDeps(SU, j);
     810             :       }
     811             :     }
     812             :     // Now process all uses.
     813    19901201 :     for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
     814    16435421 :       const MachineOperand &MO = MI.getOperand(j);
     815             :       // Only look at use operands.
     816             :       // We do not need to check for MO.readsReg() here because subsequent
     817             :       // subregister defs will get output dependence edges and need no
     818             :       // additional use dependencies.
     819    36088615 :       if (!MO.isReg() || !MO.isUse())
     820     8866469 :         continue;
     821     7568952 :       unsigned Reg = MO.getReg();
     822     7568952 :       if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
     823     2883307 :         addPhysRegDeps(SU, j);
     824     4685645 :       } else if (TargetRegisterInfo::isVirtualRegister(Reg) && MO.readsReg()) {
     825     2216353 :         addVRegUseDeps(SU, j);
     826             :       }
     827             :     }
     828             : 
     829             :     // If we haven't seen any uses in this scheduling region, create a
     830             :     // dependence edge to ExitSU to model the live-out latency. This is required
     831             :     // for vreg defs with no in-region use, and prefetches with no vreg def.
     832             :     //
     833             :     // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
     834             :     // check currently relies on being called before adding chain deps.
     835     3465780 :     if (SU->NumSuccs == 0 && SU->Latency > 1 && (HasVRegDef || MI.mayLoad())) {
     836             :       SDep Dep(SU, SDep::Artificial);
     837      231572 :       Dep.setLatency(SU->Latency - 1);
     838      231572 :       ExitSU.addPred(Dep);
     839             :     }
     840             : 
     841             :     // Add memory dependencies (Note: isStoreToStackSlot and
     842             :     // isLoadFromStackSLot are not usable after stack slots are lowered to
     843             :     // actual addresses).
     844             : 
     845             :     // This is a barrier event that acts as a pivotal node in the DAG.
     846     3557025 :     if (isGlobalMemoryObject(AA, &MI)) {
     847             : 
     848             :       // Become the barrier chain.
     849       91245 :       if (BarrierChain)
     850       46275 :         BarrierChain->addPredBarrier(SU);
     851       91245 :       BarrierChain = SU;
     852             : 
     853             :       LLVM_DEBUG(dbgs() << "Global memory object and new barrier chain: SU("
     854             :                         << BarrierChain->NodeNum << ").\n";);
     855             : 
     856             :       // Add dependencies against everything below it and clear maps.
     857       91245 :       addBarrierChain(Stores);
     858       91245 :       addBarrierChain(Loads);
     859       91245 :       addBarrierChain(NonAliasStores);
     860       91245 :       addBarrierChain(NonAliasLoads);
     861             : 
     862       91245 :       continue;
     863             :     }
     864             : 
     865             :     // If it's not a store or a variant load, we're done.
     866     8201802 :     if (!MI.mayStore() &&
     867     2992420 :         !(MI.mayLoad() && !MI.isDereferenceableInvariantLoad(AA)))
     868     2263443 :       continue;
     869             : 
     870             :     // Always add dependecy edge to BarrierChain if present.
     871     1111092 :     if (BarrierChain)
     872       30304 :       BarrierChain->addPredBarrier(SU);
     873             : 
     874             :     // Find the underlying objects for MI. The Objs vector is either
     875             :     // empty, or filled with the Values of memory locations which this
     876             :     // SU depends on.
     877             :     UnderlyingObjectsVector Objs;
     878     1111092 :     bool ObjsFound = getUnderlyingObjectsForInstr(&MI, MFI, Objs,
     879     1111092 :                                                   MF.getDataLayout());
     880             : 
     881     1111092 :     if (MI.mayStore()) {
     882      810711 :       if (!ObjsFound) {
     883             :         // An unknown store depends on all stores and loads.
     884       97415 :         addChainDependencies(SU, Stores);
     885       97415 :         addChainDependencies(SU, NonAliasStores);
     886       97415 :         addChainDependencies(SU, Loads);
     887       97415 :         addChainDependencies(SU, NonAliasLoads);
     888             : 
     889             :         // Map this store to 'UnknownValue'.
     890      194830 :         Stores.insert(SU, UnknownValue);
     891             :       } else {
     892             :         // Add precise dependencies against all previously seen memory
     893             :         // accesses mapped to the same Value(s).
     894     2747836 :         for (const UnderlyingObject &UnderlObj : Objs) {
     895     1017270 :           ValueType V = UnderlObj.getValue();
     896             :           bool ThisMayAlias = UnderlObj.mayAlias();
     897             : 
     898             :           // Add dependencies to previous stores and loads mapped to V.
     899     1017270 :           addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
     900     1017270 :           addChainDependencies(SU, (ThisMayAlias ? Loads : NonAliasLoads), V);
     901             :         }
     902             :         // Update the store map after all chains have been added to avoid adding
     903             :         // self-loop edge if multiple underlying objects are present.
     904     2747836 :         for (const UnderlyingObject &UnderlObj : Objs) {
     905     1017270 :           ValueType V = UnderlObj.getValue();
     906             :           bool ThisMayAlias = UnderlObj.mayAlias();
     907             : 
     908             :           // Map this store to V.
     909     1017270 :           (ThisMayAlias ? Stores : NonAliasStores).insert(SU, V);
     910             :         }
     911             :         // The store may have dependencies to unanalyzable loads and
     912             :         // stores.
     913     1426592 :         addChainDependencies(SU, Loads, UnknownValue);
     914     1426592 :         addChainDependencies(SU, Stores, UnknownValue);
     915             :       }
     916             :     } else { // SU is a load.
     917      300381 :       if (!ObjsFound) {
     918             :         // An unknown load depends on all stores.
     919      112064 :         addChainDependencies(SU, Stores);
     920      112064 :         addChainDependencies(SU, NonAliasStores);
     921             : 
     922      224128 :         Loads.insert(SU, UnknownValue);
     923             :       } else {
     924      567257 :         for (const UnderlyingObject &UnderlObj : Objs) {
     925      189470 :           ValueType V = UnderlObj.getValue();
     926             :           bool ThisMayAlias = UnderlObj.mayAlias();
     927             : 
     928             :           // Add precise dependencies against all previously seen stores
     929             :           // mapping to the same Value(s).
     930      189470 :           addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
     931             : 
     932             :           // Map this load to V.
     933      189470 :           (ThisMayAlias ? Loads : NonAliasLoads).insert(SU, V);
     934             :         }
     935             :         // The load may have dependencies to unanalyzable stores.
     936      376634 :         addChainDependencies(SU, Stores, UnknownValue);
     937             :       }
     938             :     }
     939             : 
     940             :     // Reduce maps if they grow huge.
     941     2222184 :     if (Stores.size() + Loads.size() >= HugeRegion) {
     942             :       LLVM_DEBUG(dbgs() << "Reducing Stores and Loads maps.\n";);
     943           7 :       reduceHugeMemNodeMaps(Stores, Loads, getReductionSize());
     944             :     }
     945     2222184 :     if (NonAliasStores.size() + NonAliasLoads.size() >= HugeRegion) {
     946             :       LLVM_DEBUG(
     947             :           dbgs() << "Reducing NonAliasStores and NonAliasLoads maps.\n";);
     948           0 :       reduceHugeMemNodeMaps(NonAliasStores, NonAliasLoads, getReductionSize());
     949             :     }
     950             :   }
     951             : 
     952      819566 :   if (DbgMI)
     953        2760 :     FirstDbgValue = DbgMI;
     954             : 
     955             :   Defs.clear();
     956             :   Uses.clear();
     957             :   CurrentVRegDefs.clear();
     958             :   CurrentVRegUses.clear();
     959      819566 : }
     960             : 
     961           0 : raw_ostream &llvm::operator<<(raw_ostream &OS, const PseudoSourceValue* PSV) {
     962           0 :   PSV->printCustom(OS);
     963           0 :   return OS;
     964             : }
     965             : 
     966           0 : void ScheduleDAGInstrs::Value2SUsMap::dump() {
     967           0 :   for (auto &Itr : *this) {
     968           0 :     if (Itr.first.is<const Value*>()) {
     969             :       const Value *V = Itr.first.get<const Value*>();
     970           0 :       if (isa<UndefValue>(V))
     971           0 :         dbgs() << "Unknown";
     972             :       else
     973           0 :         V->printAsOperand(dbgs());
     974             :     }
     975             :     else if (Itr.first.is<const PseudoSourceValue*>())
     976           0 :       dbgs() <<  Itr.first.get<const PseudoSourceValue*>();
     977             :     else
     978             :       llvm_unreachable("Unknown Value type.");
     979             : 
     980           0 :     dbgs() << " : ";
     981             :     dumpSUList(Itr.second);
     982             :   }
     983           0 : }
     984             : 
     985           7 : void ScheduleDAGInstrs::reduceHugeMemNodeMaps(Value2SUsMap &stores,
     986             :                                               Value2SUsMap &loads, unsigned N) {
     987             :   LLVM_DEBUG(dbgs() << "Before reduction:\nStoring SUnits:\n"; stores.dump();
     988             :              dbgs() << "Loading SUnits:\n"; loads.dump());
     989             : 
     990             :   // Insert all SU's NodeNums into a vector and sort it.
     991             :   std::vector<unsigned> NodeNums;
     992           7 :   NodeNums.reserve(stores.size() + loads.size());
     993        2951 :   for (auto &I : stores)
     994       12888 :     for (auto *SU : I.second)
     995        7000 :       NodeNums.push_back(SU->NodeNum);
     996           7 :   for (auto &I : loads)
     997           0 :     for (auto *SU : I.second)
     998           0 :       NodeNums.push_back(SU->NodeNum);
     999             :   llvm::sort(NodeNums.begin(), NodeNums.end());
    1000             : 
    1001             :   // The N last elements in NodeNums will be removed, and the SU with
    1002             :   // the lowest NodeNum of them will become the new BarrierChain to
    1003             :   // let the not yet seen SUs have a dependency to the removed SUs.
    1004             :   assert(N <= NodeNums.size());
    1005           7 :   SUnit *newBarrierChain = &SUnits[*(NodeNums.end() - N)];
    1006           7 :   if (BarrierChain) {
    1007             :     // The aliasing and non-aliasing maps reduce independently of each
    1008             :     // other, but share a common BarrierChain. Check if the
    1009             :     // newBarrierChain is above the former one. If it is not, it may
    1010             :     // introduce a loop to use newBarrierChain, so keep the old one.
    1011           2 :     if (newBarrierChain->NodeNum < BarrierChain->NodeNum) {
    1012           2 :       BarrierChain->addPredBarrier(newBarrierChain);
    1013           2 :       BarrierChain = newBarrierChain;
    1014             :       LLVM_DEBUG(dbgs() << "Inserting new barrier chain: SU("
    1015             :                         << BarrierChain->NodeNum << ").\n";);
    1016             :     }
    1017             :     else
    1018             :       LLVM_DEBUG(dbgs() << "Keeping old barrier chain: SU("
    1019             :                         << BarrierChain->NodeNum << ").\n";);
    1020             :   }
    1021             :   else
    1022           5 :     BarrierChain = newBarrierChain;
    1023             : 
    1024           7 :   insertBarrierChain(stores);
    1025           7 :   insertBarrierChain(loads);
    1026             : 
    1027             :   LLVM_DEBUG(dbgs() << "After reduction:\nStoring SUnits:\n"; stores.dump();
    1028             :              dbgs() << "Loading SUnits:\n"; loads.dump());
    1029           7 : }
    1030             : 
    1031     1268756 : static void toggleKills(const MachineRegisterInfo &MRI, LivePhysRegs &LiveRegs,
    1032             :                         MachineInstr &MI, bool addToLiveRegs) {
    1033    12775554 :   for (MachineOperand &MO : MI.operands()) {
    1034     8728707 :     if (!MO.isReg() || !MO.readsReg())
    1035     2975308 :       continue;
    1036     2778091 :     unsigned Reg = MO.getReg();
    1037     3636893 :     if (!Reg)
    1038      858802 :       continue;
    1039             : 
    1040             :     // Things that are available after the instruction are killed by it.
    1041     1919289 :     bool IsKill = LiveRegs.available(MRI, Reg);
    1042             :     MO.setIsKill(IsKill);
    1043     1919289 :     if (addToLiveRegs)
    1044     1917665 :       LiveRegs.addReg(Reg);
    1045             :   }
    1046     1268756 : }
    1047             : 
    1048      127100 : void ScheduleDAGInstrs::fixupKills(MachineBasicBlock &MBB) {
    1049             :   LLVM_DEBUG(dbgs() << "Fixup kills for " << printMBBReference(MBB) << '\n');
    1050             : 
    1051      127100 :   LiveRegs.init(*TRI);
    1052      127100 :   LiveRegs.addLiveOuts(MBB);
    1053             : 
    1054             :   // Examine block from end to start...
    1055     1521352 :   for (MachineInstr &MI : make_range(MBB.rbegin(), MBB.rend())) {
    1056         231 :     if (MI.isDebugInstr())
    1057         231 :       continue;
    1058             : 
    1059             :     // Update liveness.  Registers that are defed but not used in this
    1060             :     // instruction are now dead. Mark register and all subregs as they
    1061             :     // are completely defined.
    1062     7023143 :     for (ConstMIBundleOperands O(MI); O.isValid(); ++O) {
    1063             :       const MachineOperand &MO = *O;
    1064     5756222 :       if (MO.isReg()) {
    1065     3950316 :         if (!MO.isDef())
    1066     2854407 :           continue;
    1067     1095909 :         unsigned Reg = MO.getReg();
    1068     1095909 :         if (!Reg)
    1069           0 :           continue;
    1070     1095909 :         LiveRegs.removeReg(Reg);
    1071     1805906 :       } else if (MO.isRegMask()) {
    1072       65800 :         LiveRegs.removeRegsInMask(MO);
    1073             :       }
    1074             :     }
    1075             : 
    1076             :     // If there is a bundle header fix it up first.
    1077             :     if (!MI.isBundled()) {
    1078     1265692 :       toggleKills(MRI, LiveRegs, MI, true);
    1079             :     } else {
    1080        1229 :       MachineBasicBlock::instr_iterator First = MI.getIterator();
    1081        1229 :       if (MI.isBundle()) {
    1082        1229 :         toggleKills(MRI, LiveRegs, MI, false);
    1083             :         ++First;
    1084             :       }
    1085             :       // Some targets make the (questionable) assumtion that the instructions
    1086             :       // inside the bundle are ordered and consequently only the last use of
    1087             :       // a register inside the bundle can kill it.
    1088             :       MachineBasicBlock::instr_iterator I = std::next(First);
    1089        1836 :       while (I->isBundledWithSucc())
    1090             :         ++I;
    1091             :       do {
    1092             :         if (!I->isDebugInstr())
    1093        1835 :           toggleKills(MRI, LiveRegs, *I, true);
    1094             :         --I;
    1095        1836 :       } while(I != First);
    1096             :     }
    1097             :   }
    1098      127100 : }
    1099             : 
    1100           0 : void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
    1101             :   // Cannot completely remove virtual function even in release mode.
    1102             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
    1103             :   SU->getInstr()->dump();
    1104             : #endif
    1105           0 : }
    1106             : 
    1107           0 : std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
    1108             :   std::string s;
    1109           0 :   raw_string_ostream oss(s);
    1110           0 :   if (SU == &EntrySU)
    1111           0 :     oss << "<entry>";
    1112           0 :   else if (SU == &ExitSU)
    1113           0 :     oss << "<exit>";
    1114             :   else
    1115           0 :     SU->getInstr()->print(oss, /*SkipOpers=*/true);
    1116           0 :   return oss.str();
    1117             : }
    1118             : 
    1119             : /// Return the basic block label. It is not necessarilly unique because a block
    1120             : /// contains multiple scheduling regions. But it is fine for visualization.
    1121           0 : std::string ScheduleDAGInstrs::getDAGName() const {
    1122           0 :   return "dag." + BB->getFullName();
    1123             : }
    1124             : 
    1125             : //===----------------------------------------------------------------------===//
    1126             : // SchedDFSResult Implementation
    1127             : //===----------------------------------------------------------------------===//
    1128             : 
    1129             : namespace llvm {
    1130             : 
    1131             : /// Internal state used to compute SchedDFSResult.
    1132          20 : class SchedDFSImpl {
    1133             :   SchedDFSResult &R;
    1134             : 
    1135             :   /// Join DAG nodes into equivalence classes by their subtree.
    1136             :   IntEqClasses SubtreeClasses;
    1137             :   /// List PredSU, SuccSU pairs that represent data edges between subtrees.
    1138             :   std::vector<std::pair<const SUnit *, const SUnit*>> ConnectionPairs;
    1139             : 
    1140             :   struct RootData {
    1141             :     unsigned NodeID;
    1142             :     unsigned ParentNodeID;  ///< Parent node (member of the parent subtree).
    1143             :     unsigned SubInstrCount = 0; ///< Instr count in this tree only, not
    1144             :                                 /// children.
    1145             : 
    1146         354 :     RootData(unsigned id): NodeID(id),
    1147         354 :                            ParentNodeID(SchedDFSResult::InvalidSubtreeID) {}
    1148             : 
    1149             :     unsigned getSparseSetIndex() const { return NodeID; }
    1150             :   };
    1151             : 
    1152             :   SparseSet<RootData> RootSet;
    1153             : 
    1154             : public:
    1155          20 :   SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
    1156          20 :     RootSet.setUniverse(R.DFSNodeData.size());
    1157          10 :   }
    1158             : 
    1159             :   /// Returns true if this node been visited by the DFS traversal.
    1160             :   ///
    1161             :   /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
    1162             :   /// ID. Later, SubtreeID is updated but remains valid.
    1163             :   bool isVisited(const SUnit *SU) const {
    1164         708 :     return R.DFSNodeData[SU->NodeNum].SubtreeID
    1165             :       != SchedDFSResult::InvalidSubtreeID;
    1166             :   }
    1167             : 
    1168             :   /// Initializes this node's instruction count. We don't need to flag the node
    1169             :   /// visited until visitPostorder because the DAG cannot have cycles.
    1170         176 :   void visitPreorder(const SUnit *SU) {
    1171         352 :     R.DFSNodeData[SU->NodeNum].InstrCount =
    1172         176 :       SU->getInstr()->isTransient() ? 0 : 1;
    1173         176 :   }
    1174             : 
    1175             :   /// Called once for each node after all predecessors are visited. Revisit this
    1176             :   /// node's predecessors and potentially join them now that we know the ILP of
    1177             :   /// the other predecessors.
    1178         176 :   void visitPostorderNode(const SUnit *SU) {
    1179             :     // Mark this node as the root of a subtree. It may be joined with its
    1180             :     // successors later.
    1181         352 :     R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
    1182         176 :     RootData RData(SU->NodeNum);
    1183         176 :     RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
    1184             : 
    1185             :     // If any predecessors are still in their own subtree, they either cannot be
    1186             :     // joined or are large enough to remain separate. If this parent node's
    1187             :     // total instruction count is not greater than a child subtree by at least
    1188             :     // the subtree limit, then try to join it now since splitting subtrees is
    1189             :     // only useful if multiple high-pressure paths are possible.
    1190         352 :     unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
    1191         920 :     for (const SDep &PredDep : SU->Preds) {
    1192         372 :       if (PredDep.getKind() != SDep::Data)
    1193             :         continue;
    1194         178 :       unsigned PredNum = PredDep.getSUnit()->NodeNum;
    1195         356 :       if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
    1196         170 :         joinPredSubtree(PredDep, SU, /*CheckLimit=*/false);
    1197             : 
    1198             :       // Either link or merge the TreeData entry from the child to the parent.
    1199         356 :       if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
    1200             :         // If the predecessor's parent is invalid, this is a tree edge and the
    1201             :         // current node is the parent.
    1202          64 :         if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
    1203           8 :           RootSet[PredNum].ParentNodeID = SU->NodeNum;
    1204             :       }
    1205         146 :       else if (RootSet.count(PredNum)) {
    1206             :         // The predecessor is not a root, but is still in the root set. This
    1207             :         // must be the new parent that it was just joined to. Note that
    1208             :         // RootSet[PredNum].ParentNodeID may either be invalid or may still be
    1209             :         // set to the original parent.
    1210         276 :         RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
    1211         138 :         RootSet.erase(PredNum);
    1212             :       }
    1213             :     }
    1214         352 :     RootSet[SU->NodeNum] = RData;
    1215         176 :   }
    1216             : 
    1217             :   /// Called once for each tree edge after calling visitPostOrderNode on
    1218             :   /// the predecessor. Increment the parent node's instruction count and
    1219             :   /// preemptively join this subtree to its parent's if it is small enough.
    1220         146 :   void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
    1221         146 :     R.DFSNodeData[Succ->NodeNum].InstrCount
    1222         438 :       += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
    1223         146 :     joinPredSubtree(PredDep, Succ);
    1224         146 :   }
    1225             : 
    1226             :   /// Adds a connection for cross edges.
    1227             :   void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
    1228          32 :     ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
    1229             :   }
    1230             : 
    1231             :   /// Sets each node's subtree ID to the representative ID and record
    1232             :   /// connections between trees.
    1233          10 :   void finalize() {
    1234          10 :     SubtreeClasses.compress();
    1235          10 :     R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
    1236             :     assert(SubtreeClasses.getNumClasses() == RootSet.size()
    1237             :            && "number of roots should match trees");
    1238          86 :     for (const RootData &Root : RootSet) {
    1239          38 :       unsigned TreeID = SubtreeClasses[Root.NodeID];
    1240          38 :       if (Root.ParentNodeID != SchedDFSResult::InvalidSubtreeID)
    1241          16 :         R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[Root.ParentNodeID];
    1242          76 :       R.DFSTreeData[TreeID].SubInstrCount = Root.SubInstrCount;
    1243             :       // Note that SubInstrCount may be greater than InstrCount if we joined
    1244             :       // subtrees across a cross edge. InstrCount will be attributed to the
    1245             :       // original parent, while SubInstrCount will be attributed to the joined
    1246             :       // parent.
    1247             :     }
    1248          10 :     R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
    1249          10 :     R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
    1250             :     LLVM_DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
    1251         196 :     for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
    1252         352 :       R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
    1253             :       LLVM_DEBUG(dbgs() << "  SU(" << Idx << ") in tree "
    1254             :                         << R.DFSNodeData[Idx].SubtreeID << '\n');
    1255             :     }
    1256          42 :     for (const std::pair<const SUnit*, const SUnit*> &P : ConnectionPairs) {
    1257          32 :       unsigned PredTree = SubtreeClasses[P.first->NodeNum];
    1258          32 :       unsigned SuccTree = SubtreeClasses[P.second->NodeNum];
    1259          32 :       if (PredTree == SuccTree)
    1260           0 :         continue;
    1261             :       unsigned Depth = P.first->getDepth();
    1262          32 :       addConnection(PredTree, SuccTree, Depth);
    1263          32 :       addConnection(SuccTree, PredTree, Depth);
    1264             :     }
    1265          10 :   }
    1266             : 
    1267             : protected:
    1268             :   /// Joins the predecessor subtree with the successor that is its DFS parent.
    1269             :   /// Applies some heuristics before joining.
    1270         316 :   bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
    1271             :                        bool CheckLimit = true) {
    1272             :     assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
    1273             : 
    1274             :     // Check if the predecessor is already joined.
    1275             :     const SUnit *PredSU = PredDep.getSUnit();
    1276         316 :     unsigned PredNum = PredSU->NodeNum;
    1277         632 :     if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
    1278             :       return false;
    1279             : 
    1280             :     // Four is the magic number of successors before a node is considered a
    1281             :     // pinch point.
    1282             :     unsigned NumDataSucs = 0;
    1283        1050 :     for (const SDep &SuccDep : PredSU->Succs) {
    1284         472 :       if (SuccDep.getKind() == SDep::Data) {
    1285         314 :         if (++NumDataSucs >= 4)
    1286             :           return false;
    1287             :       }
    1288             :     }
    1289         146 :     if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
    1290             :       return false;
    1291         138 :     R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
    1292         138 :     SubtreeClasses.join(Succ->NodeNum, PredNum);
    1293         138 :     return true;
    1294             :   }
    1295             : 
    1296             :   /// Called by finalize() to record a connection between trees.
    1297          64 :   void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
    1298          64 :     if (!Depth)
    1299             :       return;
    1300             : 
    1301             :     do {
    1302             :       SmallVectorImpl<SchedDFSResult::Connection> &Connections =
    1303           2 :         R.SubtreeConnections[FromTree];
    1304           2 :       for (SchedDFSResult::Connection &C : Connections) {
    1305           0 :         if (C.TreeID == ToTree) {
    1306           0 :           C.Level = std::max(C.Level, Depth);
    1307             :           return;
    1308             :         }
    1309             :       }
    1310           4 :       Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
    1311           4 :       FromTree = R.DFSTreeData[FromTree].ParentTreeID;
    1312           2 :     } while (FromTree != SchedDFSResult::InvalidSubtreeID);
    1313             :   }
    1314             : };
    1315             : 
    1316             : } // end namespace llvm
    1317             : 
    1318             : namespace {
    1319             : 
    1320             : /// Manage the stack used by a reverse depth-first search over the DAG.
    1321             : class SchedDAGReverseDFS {
    1322             :   std::vector<std::pair<const SUnit *, SUnit::const_pred_iterator>> DFSStack;
    1323             : 
    1324             : public:
    1325             :   bool isComplete() const { return DFSStack.empty(); }
    1326             : 
    1327             :   void follow(const SUnit *SU) {
    1328         352 :     DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
    1329             :   }
    1330         372 :   void advance() { ++DFSStack.back().second; }
    1331             : 
    1332             :   const SDep *backtrack() {
    1333             :     DFSStack.pop_back();
    1334         176 :     return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
    1335             :   }
    1336             : 
    1337         694 :   const SUnit *getCurr() const { return DFSStack.back().first; }
    1338             : 
    1339         548 :   SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
    1340             : 
    1341             :   SUnit::const_pred_iterator getPredEnd() const {
    1342             :     return getCurr()->Preds.end();
    1343             :   }
    1344             : };
    1345             : 
    1346             : } // end anonymous namespace
    1347             : 
    1348             : static bool hasDataSucc(const SUnit *SU) {
    1349         250 :   for (const SDep &SuccDep : SU->Succs) {
    1350         329 :     if (SuccDep.getKind() == SDep::Data &&
    1351         146 :         !SuccDep.getSUnit()->isBoundaryNode())
    1352             :       return true;
    1353             :   }
    1354             :   return false;
    1355             : }
    1356             : 
    1357             : /// Computes an ILP metric for all nodes in the subDAG reachable via depth-first
    1358             : /// search from this root.
    1359          10 : void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
    1360          10 :   if (!IsBottomUp)
    1361           0 :     llvm_unreachable("Top-down ILP metric is unimplemented");
    1362             : 
    1363          20 :   SchedDFSImpl Impl(*this);
    1364         362 :   for (const SUnit &SU : SUnits) {
    1365         528 :     if (Impl.isVisited(&SU) || hasDataSucc(&SU))
    1366         146 :       continue;
    1367             : 
    1368             :     SchedDAGReverseDFS DFS;
    1369          30 :     Impl.visitPreorder(&SU);
    1370             :     DFS.follow(&SU);
    1371             :     while (true) {
    1372             :       // Traverse the leftmost path as far as possible.
    1373         548 :       while (DFS.getPred() != DFS.getPredEnd()) {
    1374             :         const SDep &PredDep = *DFS.getPred();
    1375             :         DFS.advance();
    1376             :         // Ignore non-data edges.
    1377         194 :         if (PredDep.getKind() != SDep::Data
    1378         550 :             || PredDep.getSUnit()->isBoundaryNode()) {
    1379         194 :           continue;
    1380             :         }
    1381             :         // An already visited edge is a cross edge, assuming an acyclic DAG.
    1382         388 :         if (Impl.isVisited(PredDep.getSUnit())) {
    1383             :           Impl.visitCrossEdge(PredDep, DFS.getCurr());
    1384          32 :           continue;
    1385             :         }
    1386         146 :         Impl.visitPreorder(PredDep.getSUnit());
    1387             :         DFS.follow(PredDep.getSUnit());
    1388             :       }
    1389             :       // Visit the top of the stack in postorder and backtrack.
    1390             :       const SUnit *Child = DFS.getCurr();
    1391             :       const SDep *PredDep = DFS.backtrack();
    1392         176 :       Impl.visitPostorderNode(Child);
    1393         176 :       if (PredDep)
    1394         146 :         Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
    1395         176 :       if (DFS.isComplete())
    1396             :         break;
    1397             :     }
    1398             :   }
    1399          10 :   Impl.finalize();
    1400          10 : }
    1401             : 
    1402             : /// The root of the given SubtreeID was just scheduled. For all subtrees
    1403             : /// connected to this tree, record the depth of the connection so that the
    1404             : /// nearest connected subtrees can be prioritized.
    1405          38 : void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
    1406          80 :   for (const Connection &C : SubtreeConnections[SubtreeID]) {
    1407           2 :     SubtreeConnectLevels[C.TreeID] =
    1408           4 :       std::max(SubtreeConnectLevels[C.TreeID], C.Level);
    1409             :     LLVM_DEBUG(dbgs() << "  Tree: " << C.TreeID << " @"
    1410             :                       << SubtreeConnectLevels[C.TreeID] << '\n');
    1411             :   }
    1412      303545 : }
    1413             : 
    1414             : #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
    1415             : LLVM_DUMP_METHOD void ILPValue::print(raw_ostream &OS) const {
    1416             :   OS << InstrCount << " / " << Length << " = ";
    1417             :   if (!Length)
    1418             :     OS << "BADILP";
    1419             :   else
    1420             :     OS << format("%g", ((double)InstrCount / Length));
    1421             : }
    1422             : 
    1423             : LLVM_DUMP_METHOD void ILPValue::dump() const {
    1424             :   dbgs() << *this << '\n';
    1425             : }
    1426             : 
    1427             : namespace llvm {
    1428             : 
    1429             : LLVM_DUMP_METHOD
    1430             : raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
    1431             :   Val.print(OS);
    1432             :   return OS;
    1433             : }
    1434             : 
    1435             : } // end namespace llvm
    1436             : 
    1437             : #endif

Generated by: LCOV version 1.13