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 // This implements the ScheduleDAGInstrs class, which implements re-scheduling 11 // of MachineInstrs. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/CodeGen/ScheduleDAGInstrs.h" 16 #include "llvm/ADT/IntEqClasses.h" 17 #include "llvm/ADT/SmallPtrSet.h" 18 #include "llvm/ADT/SmallSet.h" 19 #include "llvm/Analysis/AliasAnalysis.h" 20 #include "llvm/Analysis/ValueTracking.h" 21 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 22 #include "llvm/CodeGen/MachineFunctionPass.h" 23 #include "llvm/CodeGen/MachineFrameInfo.h" 24 #include "llvm/CodeGen/MachineInstrBuilder.h" 25 #include "llvm/CodeGen/MachineMemOperand.h" 26 #include "llvm/CodeGen/MachineRegisterInfo.h" 27 #include "llvm/CodeGen/PseudoSourceValue.h" 28 #include "llvm/CodeGen/RegisterPressure.h" 29 #include "llvm/CodeGen/ScheduleDFS.h" 30 #include "llvm/IR/Function.h" 31 #include "llvm/IR/Type.h" 32 #include "llvm/IR/Operator.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/Format.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include "llvm/Target/TargetInstrInfo.h" 38 #include "llvm/Target/TargetMachine.h" 39 #include "llvm/Target/TargetRegisterInfo.h" 40 #include "llvm/Target/TargetSubtargetInfo.h" 41 #include <queue> 42 43 using namespace llvm; 44 45 #define DEBUG_TYPE "misched" 46 47 static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden, 48 cl::ZeroOrMore, cl::init(false), 49 cl::desc("Enable use of AA during MI DAG construction")); 50 51 static cl::opt<bool> UseTBAA("use-tbaa-in-sched-mi", cl::Hidden, 52 cl::init(true), cl::desc("Enable use of TBAA during MI DAG construction")); 53 54 // Note: the two options below might be used in tuning compile time vs 55 // output quality. Setting HugeRegion so large that it will never be 56 // reached means best-effort, but may be slow. 57 58 // When Stores and Loads maps (or NonAliasStores and NonAliasLoads) 59 // together hold this many SUs, a reduction of maps will be done. 60 static cl::opt<unsigned> HugeRegion("dag-maps-huge-region", cl::Hidden, 61 cl::init(1000), cl::desc("The limit to use while constructing the DAG " 62 "prior to scheduling, at which point a trade-off " 63 "is made to avoid excessive compile time.")); 64 65 static cl::opt<unsigned> ReductionSize("dag-maps-reduction-size", cl::Hidden, 66 cl::desc("A huge scheduling region will have maps reduced by this many " 67 "nodes at a time. Defaults to HugeRegion / 2.")); 68 69 static void dumpSUList(ScheduleDAGInstrs::SUList &L) { 70 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 71 dbgs() << "{ "; 72 for (auto *su : L) { 73 dbgs() << "SU(" << su->NodeNum << ")"; 74 if (su != L.back()) 75 dbgs() << ", "; 76 } 77 dbgs() << "}\n"; 78 #endif 79 } 80 81 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf, 82 const MachineLoopInfo *mli, 83 bool RemoveKillFlags) 84 : ScheduleDAG(mf), MLI(mli), MFI(mf.getFrameInfo()), 85 RemoveKillFlags(RemoveKillFlags), CanHandleTerminators(false), 86 TrackLaneMasks(false), AAForDep(nullptr), BarrierChain(nullptr), 87 UnknownValue(UndefValue::get( 88 Type::getVoidTy(mf.getFunction()->getContext()))), 89 FirstDbgValue(nullptr) { 90 DbgValues.clear(); 91 92 const TargetSubtargetInfo &ST = mf.getSubtarget(); 93 SchedModel.init(ST.getSchedModel(), &ST, TII); 94 } 95 96 /// getUnderlyingObjectFromInt - This is the function that does the work of 97 /// looking through basic ptrtoint+arithmetic+inttoptr sequences. 98 static const Value *getUnderlyingObjectFromInt(const Value *V) { 99 do { 100 if (const Operator *U = dyn_cast<Operator>(V)) { 101 // If we find a ptrtoint, we can transfer control back to the 102 // regular getUnderlyingObjectFromInt. 103 if (U->getOpcode() == Instruction::PtrToInt) 104 return U->getOperand(0); 105 // If we find an add of a constant, a multiplied value, or a phi, it's 106 // likely that the other operand will lead us to the base 107 // object. We don't have to worry about the case where the 108 // object address is somehow being computed by the multiply, 109 // because our callers only care when the result is an 110 // identifiable object. 111 if (U->getOpcode() != Instruction::Add || 112 (!isa<ConstantInt>(U->getOperand(1)) && 113 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul && 114 !isa<PHINode>(U->getOperand(1)))) 115 return V; 116 V = U->getOperand(0); 117 } else { 118 return V; 119 } 120 assert(V->getType()->isIntegerTy() && "Unexpected operand type!"); 121 } while (1); 122 } 123 124 /// getUnderlyingObjects - This is a wrapper around GetUnderlyingObjects 125 /// and adds support for basic ptrtoint+arithmetic+inttoptr sequences. 126 static void getUnderlyingObjects(const Value *V, 127 SmallVectorImpl<Value *> &Objects, 128 const DataLayout &DL) { 129 SmallPtrSet<const Value *, 16> Visited; 130 SmallVector<const Value *, 4> Working(1, V); 131 do { 132 V = Working.pop_back_val(); 133 134 SmallVector<Value *, 4> Objs; 135 GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL); 136 137 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), IE = Objs.end(); 138 I != IE; ++I) { 139 V = *I; 140 if (!Visited.insert(V).second) 141 continue; 142 if (Operator::getOpcode(V) == Instruction::IntToPtr) { 143 const Value *O = 144 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0)); 145 if (O->getType()->isPointerTy()) { 146 Working.push_back(O); 147 continue; 148 } 149 } 150 Objects.push_back(const_cast<Value *>(V)); 151 } 152 } while (!Working.empty()); 153 } 154 155 /// getUnderlyingObjectsForInstr - If this machine instr has memory reference 156 /// information and it can be tracked to a normal reference to a known 157 /// object, return the Value for that object. 158 static void getUnderlyingObjectsForInstr(const MachineInstr *MI, 159 const MachineFrameInfo *MFI, 160 UnderlyingObjectsVector &Objects, 161 const DataLayout &DL) { 162 if (!MI->hasOneMemOperand() || 163 (!(*MI->memoperands_begin())->getValue() && 164 !(*MI->memoperands_begin())->getPseudoValue()) || 165 (*MI->memoperands_begin())->isVolatile()) 166 return; 167 168 if (const PseudoSourceValue *PSV = 169 (*MI->memoperands_begin())->getPseudoValue()) { 170 // Function that contain tail calls don't have unique PseudoSourceValue 171 // objects. Two PseudoSourceValues might refer to the same or overlapping 172 // locations. The client code calling this function assumes this is not the 173 // case. So return a conservative answer of no known object. 174 if (MFI->hasTailCall()) 175 return; 176 177 // For now, ignore PseudoSourceValues which may alias LLVM IR values 178 // because the code that uses this function has no way to cope with 179 // such aliases. 180 if (!PSV->isAliased(MFI)) { 181 bool MayAlias = PSV->mayAlias(MFI); 182 Objects.push_back(UnderlyingObjectsVector::value_type(PSV, MayAlias)); 183 } 184 return; 185 } 186 187 const Value *V = (*MI->memoperands_begin())->getValue(); 188 if (!V) 189 return; 190 191 SmallVector<Value *, 4> Objs; 192 getUnderlyingObjects(V, Objs, DL); 193 194 for (Value *V : Objs) { 195 if (!isIdentifiedObject(V)) { 196 Objects.clear(); 197 return; 198 } 199 200 Objects.push_back(UnderlyingObjectsVector::value_type(V, true)); 201 } 202 } 203 204 void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) { 205 BB = bb; 206 } 207 208 void ScheduleDAGInstrs::finishBlock() { 209 // Subclasses should no longer refer to the old block. 210 BB = nullptr; 211 } 212 213 /// Initialize the DAG and common scheduler state for the current scheduling 214 /// region. This does not actually create the DAG, only clears it. The 215 /// scheduling driver may call BuildSchedGraph multiple times per scheduling 216 /// region. 217 void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb, 218 MachineBasicBlock::iterator begin, 219 MachineBasicBlock::iterator end, 220 unsigned regioninstrs) { 221 assert(bb == BB && "startBlock should set BB"); 222 RegionBegin = begin; 223 RegionEnd = end; 224 NumRegionInstrs = regioninstrs; 225 } 226 227 /// Close the current scheduling region. Don't clear any state in case the 228 /// driver wants to refer to the previous scheduling region. 229 void ScheduleDAGInstrs::exitRegion() { 230 // Nothing to do. 231 } 232 233 /// addSchedBarrierDeps - Add dependencies from instructions in the current 234 /// list of instructions being scheduled to scheduling barrier by adding 235 /// the exit SU to the register defs and use list. This is because we want to 236 /// make sure instructions which define registers that are either used by 237 /// the terminator or are live-out are properly scheduled. This is 238 /// especially important when the definition latency of the return value(s) 239 /// are too high to be hidden by the branch or when the liveout registers 240 /// used by instructions in the fallthrough block. 241 void ScheduleDAGInstrs::addSchedBarrierDeps() { 242 MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : nullptr; 243 ExitSU.setInstr(ExitMI); 244 bool AllDepKnown = ExitMI && 245 (ExitMI->isCall() || ExitMI->isBarrier()); 246 if (ExitMI && AllDepKnown) { 247 // If it's a call or a barrier, add dependencies on the defs and uses of 248 // instruction. 249 for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) { 250 const MachineOperand &MO = ExitMI->getOperand(i); 251 if (!MO.isReg() || MO.isDef()) continue; 252 unsigned Reg = MO.getReg(); 253 if (Reg == 0) continue; 254 255 if (TRI->isPhysicalRegister(Reg)) 256 Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg)); 257 else if (MO.readsReg()) // ignore undef operands 258 addVRegUseDeps(&ExitSU, i); 259 } 260 } else { 261 // For others, e.g. fallthrough, conditional branch, assume the exit 262 // uses all the registers that are livein to the successor blocks. 263 assert(Uses.empty() && "Uses in set before adding deps?"); 264 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(), 265 SE = BB->succ_end(); SI != SE; ++SI) 266 for (const auto &LI : (*SI)->liveins()) { 267 if (!Uses.contains(LI.PhysReg)) 268 Uses.insert(PhysRegSUOper(&ExitSU, -1, LI.PhysReg)); 269 } 270 } 271 } 272 273 /// MO is an operand of SU's instruction that defines a physical register. Add 274 /// data dependencies from SU to any uses of the physical register. 275 void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) { 276 const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx); 277 assert(MO.isDef() && "expect physreg def"); 278 279 // Ask the target if address-backscheduling is desirable, and if so how much. 280 const TargetSubtargetInfo &ST = MF.getSubtarget(); 281 282 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true); 283 Alias.isValid(); ++Alias) { 284 if (!Uses.contains(*Alias)) 285 continue; 286 for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) { 287 SUnit *UseSU = I->SU; 288 if (UseSU == SU) 289 continue; 290 291 // Adjust the dependence latency using operand def/use information, 292 // then allow the target to perform its own adjustments. 293 int UseOp = I->OpIdx; 294 MachineInstr *RegUse = nullptr; 295 SDep Dep; 296 if (UseOp < 0) 297 Dep = SDep(SU, SDep::Artificial); 298 else { 299 // Set the hasPhysRegDefs only for physreg defs that have a use within 300 // the scheduling region. 301 SU->hasPhysRegDefs = true; 302 Dep = SDep(SU, SDep::Data, *Alias); 303 RegUse = UseSU->getInstr(); 304 } 305 Dep.setLatency( 306 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, RegUse, 307 UseOp)); 308 309 ST.adjustSchedDependency(SU, UseSU, Dep); 310 UseSU->addPred(Dep); 311 } 312 } 313 } 314 315 /// addPhysRegDeps - Add register dependencies (data, anti, and output) from 316 /// this SUnit to following instructions in the same scheduling region that 317 /// depend the physical register referenced at OperIdx. 318 void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) { 319 MachineInstr *MI = SU->getInstr(); 320 MachineOperand &MO = MI->getOperand(OperIdx); 321 322 // Optionally add output and anti dependencies. For anti 323 // dependencies we use a latency of 0 because for a multi-issue 324 // target we want to allow the defining instruction to issue 325 // in the same cycle as the using instruction. 326 // TODO: Using a latency of 1 here for output dependencies assumes 327 // there's no cost for reusing registers. 328 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output; 329 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true); 330 Alias.isValid(); ++Alias) { 331 if (!Defs.contains(*Alias)) 332 continue; 333 for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) { 334 SUnit *DefSU = I->SU; 335 if (DefSU == &ExitSU) 336 continue; 337 if (DefSU != SU && 338 (Kind != SDep::Output || !MO.isDead() || 339 !DefSU->getInstr()->registerDefIsDead(*Alias))) { 340 if (Kind == SDep::Anti) 341 DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias)); 342 else { 343 SDep Dep(SU, Kind, /*Reg=*/*Alias); 344 Dep.setLatency( 345 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr())); 346 DefSU->addPred(Dep); 347 } 348 } 349 } 350 } 351 352 if (!MO.isDef()) { 353 SU->hasPhysRegUses = true; 354 // Either insert a new Reg2SUnits entry with an empty SUnits list, or 355 // retrieve the existing SUnits list for this register's uses. 356 // Push this SUnit on the use list. 357 Uses.insert(PhysRegSUOper(SU, OperIdx, MO.getReg())); 358 if (RemoveKillFlags) 359 MO.setIsKill(false); 360 } 361 else { 362 addPhysRegDataDeps(SU, OperIdx); 363 unsigned Reg = MO.getReg(); 364 365 // clear this register's use list 366 if (Uses.contains(Reg)) 367 Uses.eraseAll(Reg); 368 369 if (!MO.isDead()) { 370 Defs.eraseAll(Reg); 371 } else if (SU->isCall) { 372 // Calls will not be reordered because of chain dependencies (see 373 // below). Since call operands are dead, calls may continue to be added 374 // to the DefList making dependence checking quadratic in the size of 375 // the block. Instead, we leave only one call at the back of the 376 // DefList. 377 Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg); 378 Reg2SUnitsMap::iterator B = P.first; 379 Reg2SUnitsMap::iterator I = P.second; 380 for (bool isBegin = I == B; !isBegin; /* empty */) { 381 isBegin = (--I) == B; 382 if (!I->SU->isCall) 383 break; 384 I = Defs.erase(I); 385 } 386 } 387 388 // Defs are pushed in the order they are visited and never reordered. 389 Defs.insert(PhysRegSUOper(SU, OperIdx, Reg)); 390 } 391 } 392 393 LaneBitmask ScheduleDAGInstrs::getLaneMaskForMO(const MachineOperand &MO) const 394 { 395 unsigned Reg = MO.getReg(); 396 // No point in tracking lanemasks if we don't have interesting subregisters. 397 const TargetRegisterClass &RC = *MRI.getRegClass(Reg); 398 if (!RC.HasDisjunctSubRegs) 399 return ~0u; 400 401 unsigned SubReg = MO.getSubReg(); 402 if (SubReg == 0) 403 return RC.getLaneMask(); 404 return TRI->getSubRegIndexLaneMask(SubReg); 405 } 406 407 /// addVRegDefDeps - Add register output and data dependencies from this SUnit 408 /// to instructions that occur later in the same scheduling region if they read 409 /// from or write to the virtual register defined at OperIdx. 410 /// 411 /// TODO: Hoist loop induction variable increments. This has to be 412 /// reevaluated. Generally, IV scheduling should be done before coalescing. 413 void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) { 414 MachineInstr *MI = SU->getInstr(); 415 MachineOperand &MO = MI->getOperand(OperIdx); 416 unsigned Reg = MO.getReg(); 417 418 LaneBitmask DefLaneMask; 419 LaneBitmask KillLaneMask; 420 if (TrackLaneMasks) { 421 bool IsKill = MO.getSubReg() == 0 || MO.isUndef(); 422 DefLaneMask = getLaneMaskForMO(MO); 423 // If we have a <read-undef> flag, none of the lane values comes from an 424 // earlier instruction. 425 KillLaneMask = IsKill ? ~0u : DefLaneMask; 426 427 // Clear undef flag, we'll re-add it later once we know which subregister 428 // Def is first. 429 MO.setIsUndef(false); 430 } else { 431 DefLaneMask = ~0u; 432 KillLaneMask = ~0u; 433 } 434 435 if (MO.isDead()) { 436 assert(CurrentVRegUses.find(Reg) == CurrentVRegUses.end() && 437 "Dead defs should have no uses"); 438 } else { 439 // Add data dependence to all uses we found so far. 440 const TargetSubtargetInfo &ST = MF.getSubtarget(); 441 for (VReg2SUnitOperIdxMultiMap::iterator I = CurrentVRegUses.find(Reg), 442 E = CurrentVRegUses.end(); I != E; /*empty*/) { 443 LaneBitmask LaneMask = I->LaneMask; 444 // Ignore uses of other lanes. 445 if ((LaneMask & KillLaneMask) == 0) { 446 ++I; 447 continue; 448 } 449 450 if ((LaneMask & DefLaneMask) != 0) { 451 SUnit *UseSU = I->SU; 452 MachineInstr *Use = UseSU->getInstr(); 453 SDep Dep(SU, SDep::Data, Reg); 454 Dep.setLatency(SchedModel.computeOperandLatency(MI, OperIdx, Use, 455 I->OperandIndex)); 456 ST.adjustSchedDependency(SU, UseSU, Dep); 457 UseSU->addPred(Dep); 458 } 459 460 LaneMask &= ~KillLaneMask; 461 // If we found a Def for all lanes of this use, remove it from the list. 462 if (LaneMask != 0) { 463 I->LaneMask = LaneMask; 464 ++I; 465 } else 466 I = CurrentVRegUses.erase(I); 467 } 468 } 469 470 // Shortcut: Singly defined vregs do not have output/anti dependencies. 471 if (MRI.hasOneDef(Reg)) 472 return; 473 474 // Add output dependence to the next nearest defs of this vreg. 475 // 476 // Unless this definition is dead, the output dependence should be 477 // transitively redundant with antidependencies from this definition's 478 // uses. We're conservative for now until we have a way to guarantee the uses 479 // are not eliminated sometime during scheduling. The output dependence edge 480 // is also useful if output latency exceeds def-use latency. 481 LaneBitmask LaneMask = DefLaneMask; 482 for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg), 483 CurrentVRegDefs.end())) { 484 // Ignore defs for other lanes. 485 if ((V2SU.LaneMask & LaneMask) == 0) 486 continue; 487 // Add an output dependence. 488 SUnit *DefSU = V2SU.SU; 489 // Ignore additional defs of the same lanes in one instruction. This can 490 // happen because lanemasks are shared for targets with too many 491 // subregisters. We also use some representration tricks/hacks where we 492 // add super-register defs/uses, to imply that although we only access parts 493 // of the reg we care about the full one. 494 if (DefSU == SU) 495 continue; 496 SDep Dep(SU, SDep::Output, Reg); 497 Dep.setLatency( 498 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr())); 499 DefSU->addPred(Dep); 500 501 // Update current definition. This can get tricky if the def was about a 502 // bigger lanemask before. We then have to shrink it and create a new 503 // VReg2SUnit for the non-overlapping part. 504 LaneBitmask OverlapMask = V2SU.LaneMask & LaneMask; 505 LaneBitmask NonOverlapMask = V2SU.LaneMask & ~LaneMask; 506 if (NonOverlapMask != 0) 507 CurrentVRegDefs.insert(VReg2SUnit(Reg, NonOverlapMask, V2SU.SU)); 508 V2SU.SU = SU; 509 V2SU.LaneMask = OverlapMask; 510 } 511 // If there was no CurrentVRegDefs entry for some lanes yet, create one. 512 if (LaneMask != 0) 513 CurrentVRegDefs.insert(VReg2SUnit(Reg, LaneMask, SU)); 514 } 515 516 /// addVRegUseDeps - Add a register data dependency if the instruction that 517 /// defines the virtual register used at OperIdx is mapped to an SUnit. Add a 518 /// register antidependency from this SUnit to instructions that occur later in 519 /// the same scheduling region if they write the virtual register. 520 /// 521 /// TODO: Handle ExitSU "uses" properly. 522 void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) { 523 const MachineInstr *MI = SU->getInstr(); 524 const MachineOperand &MO = MI->getOperand(OperIdx); 525 unsigned Reg = MO.getReg(); 526 527 // Remember the use. Data dependencies will be added when we find the def. 528 LaneBitmask LaneMask = TrackLaneMasks ? getLaneMaskForMO(MO) : ~0u; 529 CurrentVRegUses.insert(VReg2SUnitOperIdx(Reg, LaneMask, OperIdx, SU)); 530 531 // Add antidependences to the following defs of the vreg. 532 for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg), 533 CurrentVRegDefs.end())) { 534 // Ignore defs for unrelated lanes. 535 LaneBitmask PrevDefLaneMask = V2SU.LaneMask; 536 if ((PrevDefLaneMask & LaneMask) == 0) 537 continue; 538 if (V2SU.SU == SU) 539 continue; 540 541 V2SU.SU->addPred(SDep(SU, SDep::Anti, Reg)); 542 } 543 } 544 545 /// Return true if MI is an instruction we are unable to reason about 546 /// (like a call or something with unmodeled side effects). 547 static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) { 548 return MI->isCall() || MI->hasUnmodeledSideEffects() || 549 (MI->hasOrderedMemoryRef() && !MI->isInvariantLoad(AA)); 550 } 551 552 // This MI might have either incomplete info, or known to be unsafe 553 // to deal with (i.e. volatile object). 554 static inline bool isUnsafeMemoryObject(MachineInstr *MI, 555 const MachineFrameInfo *MFI, 556 const DataLayout &DL) { 557 if (!MI || MI->memoperands_empty()) 558 return true; 559 // We purposefully do no check for hasOneMemOperand() here 560 // in hope to trigger an assert downstream in order to 561 // finish implementation. 562 if ((*MI->memoperands_begin())->isVolatile() || 563 MI->hasUnmodeledSideEffects()) 564 return true; 565 566 if ((*MI->memoperands_begin())->getPseudoValue()) { 567 // Similarly to getUnderlyingObjectForInstr: 568 // For now, ignore PseudoSourceValues which may alias LLVM IR values 569 // because the code that uses this function has no way to cope with 570 // such aliases. 571 return true; 572 } 573 574 if ((*MI->memoperands_begin())->getValue() == nullptr) 575 return true; 576 577 return false; 578 } 579 580 /// This returns true if the two MIs need a chain edge between them. 581 /// This is called on normal stores and loads. 582 static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI, 583 const DataLayout &DL, MachineInstr *MIa, 584 MachineInstr *MIb) { 585 const MachineFunction *MF = MIa->getParent()->getParent(); 586 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 587 588 assert ((MIa->mayStore() || MIb->mayStore()) && 589 "Dependency checked between two loads"); 590 591 // Let the target decide if memory accesses cannot possibly overlap. 592 if (TII->areMemAccessesTriviallyDisjoint(MIa, MIb, AA)) 593 return false; 594 595 // FIXME: Need to handle multiple memory operands to support all targets. 596 if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand()) 597 return true; 598 599 if (isUnsafeMemoryObject(MIa, MFI, DL) || isUnsafeMemoryObject(MIb, MFI, DL)) 600 return true; 601 602 // To this point analysis is generic. From here on we do need AA. 603 if (!AA) 604 return true; 605 606 MachineMemOperand *MMOa = *MIa->memoperands_begin(); 607 MachineMemOperand *MMOb = *MIb->memoperands_begin(); 608 609 if (!MMOa->getValue() || !MMOb->getValue()) 610 return true; 611 612 // The following interface to AA is fashioned after DAGCombiner::isAlias 613 // and operates with MachineMemOperand offset with some important 614 // assumptions: 615 // - LLVM fundamentally assumes flat address spaces. 616 // - MachineOperand offset can *only* result from legalization and 617 // cannot affect queries other than the trivial case of overlap 618 // checking. 619 // - These offsets never wrap and never step outside 620 // of allocated objects. 621 // - There should never be any negative offsets here. 622 // 623 // FIXME: Modify API to hide this math from "user" 624 // FIXME: Even before we go to AA we can reason locally about some 625 // memory objects. It can save compile time, and possibly catch some 626 // corner cases not currently covered. 627 628 assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset"); 629 assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset"); 630 631 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset()); 632 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset; 633 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset; 634 635 AliasResult AAResult = 636 AA->alias(MemoryLocation(MMOa->getValue(), Overlapa, 637 UseTBAA ? MMOa->getAAInfo() : AAMDNodes()), 638 MemoryLocation(MMOb->getValue(), Overlapb, 639 UseTBAA ? MMOb->getAAInfo() : AAMDNodes())); 640 641 return (AAResult != NoAlias); 642 } 643 644 /// Check whether two objects need a chain edge and add it if needed. 645 void ScheduleDAGInstrs::addChainDependency (SUnit *SUa, SUnit *SUb, 646 unsigned Latency) { 647 if (MIsNeedChainEdge(AAForDep, MFI, MF.getDataLayout(), SUa->getInstr(), 648 SUb->getInstr())) { 649 SDep Dep(SUa, SDep::MayAliasMem); 650 Dep.setLatency(Latency); 651 SUb->addPred(Dep); 652 } 653 } 654 655 /// Create an SUnit for each real instruction, numbered in top-down topological 656 /// order. The instruction order A < B, implies that no edge exists from B to A. 657 /// 658 /// Map each real instruction to its SUnit. 659 /// 660 /// After initSUnits, the SUnits vector cannot be resized and the scheduler may 661 /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs 662 /// instead of pointers. 663 /// 664 /// MachineScheduler relies on initSUnits numbering the nodes by their order in 665 /// the original instruction list. 666 void ScheduleDAGInstrs::initSUnits() { 667 // We'll be allocating one SUnit for each real instruction in the region, 668 // which is contained within a basic block. 669 SUnits.reserve(NumRegionInstrs); 670 671 for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) { 672 MachineInstr *MI = I; 673 if (MI->isDebugValue()) 674 continue; 675 676 SUnit *SU = newSUnit(MI); 677 MISUnitMap[MI] = SU; 678 679 SU->isCall = MI->isCall(); 680 SU->isCommutable = MI->isCommutable(); 681 682 // Assign the Latency field of SU using target-provided information. 683 SU->Latency = SchedModel.computeInstrLatency(SU->getInstr()); 684 685 // If this SUnit uses a reserved or unbuffered resource, mark it as such. 686 // 687 // Reserved resources block an instruction from issuing and stall the 688 // entire pipeline. These are identified by BufferSize=0. 689 // 690 // Unbuffered resources prevent execution of subsequent instructions that 691 // require the same resources. This is used for in-order execution pipelines 692 // within an out-of-order core. These are identified by BufferSize=1. 693 if (SchedModel.hasInstrSchedModel()) { 694 const MCSchedClassDesc *SC = getSchedClass(SU); 695 for (TargetSchedModel::ProcResIter 696 PI = SchedModel.getWriteProcResBegin(SC), 697 PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) { 698 switch (SchedModel.getProcResource(PI->ProcResourceIdx)->BufferSize) { 699 case 0: 700 SU->hasReservedResource = true; 701 break; 702 case 1: 703 SU->isUnbuffered = true; 704 break; 705 default: 706 break; 707 } 708 } 709 } 710 } 711 } 712 713 void ScheduleDAGInstrs::collectVRegUses(SUnit *SU) { 714 const MachineInstr *MI = SU->getInstr(); 715 for (const MachineOperand &MO : MI->operands()) { 716 if (!MO.isReg()) 717 continue; 718 if (!MO.readsReg()) 719 continue; 720 if (TrackLaneMasks && !MO.isUse()) 721 continue; 722 723 unsigned Reg = MO.getReg(); 724 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 725 continue; 726 727 // Ignore re-defs. 728 if (TrackLaneMasks) { 729 bool FoundDef = false; 730 for (const MachineOperand &MO2 : MI->operands()) { 731 if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) { 732 FoundDef = true; 733 break; 734 } 735 } 736 if (FoundDef) 737 continue; 738 } 739 740 // Record this local VReg use. 741 VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg); 742 for (; UI != VRegUses.end(); ++UI) { 743 if (UI->SU == SU) 744 break; 745 } 746 if (UI == VRegUses.end()) 747 VRegUses.insert(VReg2SUnit(Reg, 0, SU)); 748 } 749 } 750 751 class ScheduleDAGInstrs::Value2SUsMap : public MapVector<ValueType, SUList> { 752 753 /// Current total number of SUs in map. 754 unsigned NumNodes; 755 756 /// 1 for loads, 0 for stores. (see comment in SUList) 757 unsigned TrueMemOrderLatency; 758 public: 759 760 Value2SUsMap(unsigned lat = 0) : NumNodes(0), TrueMemOrderLatency(lat) {} 761 762 /// To keep NumNodes up to date, insert() is used instead of 763 /// this operator w/ push_back(). 764 ValueType &operator[](const SUList &Key) { 765 llvm_unreachable("Don't use. Use insert() instead."); }; 766 767 /// Add SU to the SUList of V. If Map grows huge, reduce its size 768 /// by calling reduce(). 769 void inline insert(SUnit *SU, ValueType V) { 770 MapVector::operator[](V).push_back(SU); 771 NumNodes++; 772 } 773 774 /// Clears the list of SUs mapped to V. 775 void inline clearList(ValueType V) { 776 iterator Itr = find(V); 777 if (Itr != end()) { 778 assert (NumNodes >= Itr->second.size()); 779 NumNodes -= Itr->second.size(); 780 781 Itr->second.clear(); 782 } 783 } 784 785 /// Clears map from all contents. 786 void clear() { 787 MapVector<ValueType, SUList>::clear(); 788 NumNodes = 0; 789 } 790 791 unsigned inline size() const { return NumNodes; } 792 793 /// Count the number of SUs in this map after a reduction. 794 void reComputeSize(void) { 795 NumNodes = 0; 796 for (auto &I : *this) 797 NumNodes += I.second.size(); 798 } 799 800 unsigned inline getTrueMemOrderLatency() const { 801 return TrueMemOrderLatency; 802 } 803 804 void dump(); 805 }; 806 807 void ScheduleDAGInstrs::addChainDependencies(SUnit *SU, 808 Value2SUsMap &Val2SUsMap) { 809 for (auto &I : Val2SUsMap) 810 addChainDependencies(SU, I.second, 811 Val2SUsMap.getTrueMemOrderLatency()); 812 } 813 814 void ScheduleDAGInstrs::addChainDependencies(SUnit *SU, 815 Value2SUsMap &Val2SUsMap, 816 ValueType V) { 817 Value2SUsMap::iterator Itr = Val2SUsMap.find(V); 818 if (Itr != Val2SUsMap.end()) 819 addChainDependencies(SU, Itr->second, 820 Val2SUsMap.getTrueMemOrderLatency()); 821 } 822 823 void ScheduleDAGInstrs::addBarrierChain(Value2SUsMap &map) { 824 assert (BarrierChain != nullptr); 825 826 for (auto &I : map) { 827 SUList &sus = I.second; 828 for (auto *SU : sus) 829 SU->addPredBarrier(BarrierChain); 830 } 831 map.clear(); 832 } 833 834 void ScheduleDAGInstrs::insertBarrierChain(Value2SUsMap &map) { 835 assert (BarrierChain != nullptr); 836 837 // Go through all lists of SUs. 838 for (Value2SUsMap::iterator I = map.begin(), EE = map.end(); I != EE;) { 839 Value2SUsMap::iterator CurrItr = I++; 840 SUList &sus = CurrItr->second; 841 SUList::iterator SUItr = sus.begin(), SUEE = sus.end(); 842 for (; SUItr != SUEE; ++SUItr) { 843 // Stop on BarrierChain or any instruction above it. 844 if ((*SUItr)->NodeNum <= BarrierChain->NodeNum) 845 break; 846 847 (*SUItr)->addPredBarrier(BarrierChain); 848 } 849 850 // Remove also the BarrierChain from list if present. 851 if (*SUItr == BarrierChain) 852 SUItr++; 853 854 // Remove all SUs that are now successors of BarrierChain. 855 if (SUItr != sus.begin()) 856 sus.erase(sus.begin(), SUItr); 857 } 858 859 // Remove all entries with empty su lists. 860 map.remove_if([&](std::pair<ValueType, SUList> &mapEntry) { 861 return (mapEntry.second.empty()); }); 862 863 // Recompute the size of the map (NumNodes). 864 map.reComputeSize(); 865 } 866 867 /// If RegPressure is non-null, compute register pressure as a side effect. The 868 /// DAG builder is an efficient place to do it because it already visits 869 /// operands. 870 void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA, 871 RegPressureTracker *RPTracker, 872 PressureDiffs *PDiffs, 873 LiveIntervals *LIS, 874 bool TrackLaneMasks) { 875 const TargetSubtargetInfo &ST = MF.getSubtarget(); 876 bool UseAA = EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI 877 : ST.useAA(); 878 AAForDep = UseAA ? AA : nullptr; 879 880 BarrierChain = nullptr; 881 882 this->TrackLaneMasks = TrackLaneMasks; 883 MISUnitMap.clear(); 884 ScheduleDAG::clearDAG(); 885 886 // Create an SUnit for each real instruction. 887 initSUnits(); 888 889 if (PDiffs) 890 PDiffs->init(SUnits.size()); 891 892 // We build scheduling units by walking a block's instruction list 893 // from bottom to top. 894 895 // Each MIs' memory operand(s) is analyzed to a list of underlying 896 // objects. The SU is then inserted in the SUList(s) mapped from the 897 // Value(s). Each Value thus gets mapped to lists of SUs depending 898 // on it, stores and loads kept separately. Two SUs are trivially 899 // non-aliasing if they both depend on only identified Values and do 900 // not share any common Value. 901 Value2SUsMap Stores, Loads(1 /*TrueMemOrderLatency*/); 902 903 // Certain memory accesses are known to not alias any SU in Stores 904 // or Loads, and have therefore their own 'NonAlias' 905 // domain. E.g. spill / reload instructions never alias LLVM I/R 906 // Values. It would be nice to assume that this type of memory 907 // accesses always have a proper memory operand modelling, and are 908 // therefore never unanalyzable, but this is conservatively not 909 // done. 910 Value2SUsMap NonAliasStores, NonAliasLoads(1 /*TrueMemOrderLatency*/); 911 912 // Always reduce a huge region with half of the elements, except 913 // when user sets this number explicitly. 914 if (ReductionSize.getNumOccurrences() == 0) 915 ReductionSize = (HugeRegion / 2); 916 917 // Remove any stale debug info; sometimes BuildSchedGraph is called again 918 // without emitting the info from the previous call. 919 DbgValues.clear(); 920 FirstDbgValue = nullptr; 921 922 assert(Defs.empty() && Uses.empty() && 923 "Only BuildGraph should update Defs/Uses"); 924 Defs.setUniverse(TRI->getNumRegs()); 925 Uses.setUniverse(TRI->getNumRegs()); 926 927 assert(CurrentVRegDefs.empty() && "nobody else should use CurrentVRegDefs"); 928 assert(CurrentVRegUses.empty() && "nobody else should use CurrentVRegUses"); 929 unsigned NumVirtRegs = MRI.getNumVirtRegs(); 930 CurrentVRegDefs.setUniverse(NumVirtRegs); 931 CurrentVRegUses.setUniverse(NumVirtRegs); 932 933 VRegUses.clear(); 934 VRegUses.setUniverse(NumVirtRegs); 935 936 // Model data dependencies between instructions being scheduled and the 937 // ExitSU. 938 addSchedBarrierDeps(); 939 940 // Walk the list of instructions, from bottom moving up. 941 MachineInstr *DbgMI = nullptr; 942 for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin; 943 MII != MIE; --MII) { 944 MachineInstr *MI = std::prev(MII); 945 if (MI && DbgMI) { 946 DbgValues.push_back(std::make_pair(DbgMI, MI)); 947 DbgMI = nullptr; 948 } 949 950 if (MI->isDebugValue()) { 951 DbgMI = MI; 952 continue; 953 } 954 SUnit *SU = MISUnitMap[MI]; 955 assert(SU && "No SUnit mapped to this MI"); 956 957 if (RPTracker) { 958 collectVRegUses(SU); 959 960 RegisterOperands RegOpers; 961 RegOpers.collect(*MI, *TRI, MRI, TrackLaneMasks, false); 962 if (TrackLaneMasks) { 963 SlotIndex SlotIdx = LIS->getInstructionIndex(MI); 964 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx); 965 } 966 if (PDiffs != nullptr) 967 PDiffs->addInstruction(SU->NodeNum, RegOpers, MRI); 968 969 RPTracker->recedeSkipDebugValues(); 970 assert(&*RPTracker->getPos() == MI && "RPTracker in sync"); 971 RPTracker->recede(RegOpers); 972 } 973 974 assert( 975 (CanHandleTerminators || (!MI->isTerminator() && !MI->isPosition())) && 976 "Cannot schedule terminators or labels!"); 977 978 // Add register-based dependencies (data, anti, and output). 979 bool HasVRegDef = false; 980 for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) { 981 const MachineOperand &MO = MI->getOperand(j); 982 if (!MO.isReg()) continue; 983 unsigned Reg = MO.getReg(); 984 if (Reg == 0) continue; 985 986 if (TRI->isPhysicalRegister(Reg)) 987 addPhysRegDeps(SU, j); 988 else { 989 if (MO.isDef()) { 990 HasVRegDef = true; 991 addVRegDefDeps(SU, j); 992 } 993 else if (MO.readsReg()) // ignore undef operands 994 addVRegUseDeps(SU, j); 995 } 996 } 997 // If we haven't seen any uses in this scheduling region, create a 998 // dependence edge to ExitSU to model the live-out latency. This is required 999 // for vreg defs with no in-region use, and prefetches with no vreg def. 1000 // 1001 // FIXME: NumDataSuccs would be more precise than NumSuccs here. This 1002 // check currently relies on being called before adding chain deps. 1003 if (SU->NumSuccs == 0 && SU->Latency > 1 1004 && (HasVRegDef || MI->mayLoad())) { 1005 SDep Dep(SU, SDep::Artificial); 1006 Dep.setLatency(SU->Latency - 1); 1007 ExitSU.addPred(Dep); 1008 } 1009 1010 // Add memory dependencies (Note: isStoreToStackSlot and 1011 // isLoadFromStackSLot are not usable after stack slots are lowered to 1012 // actual addresses). 1013 1014 // This is a barrier event that acts as a pivotal node in the DAG. 1015 if (isGlobalMemoryObject(AA, MI)) { 1016 1017 // Become the barrier chain. 1018 if (BarrierChain) 1019 BarrierChain->addPredBarrier(SU); 1020 BarrierChain = SU; 1021 1022 DEBUG(dbgs() << "Global memory object and new barrier chain: SU(" 1023 << BarrierChain->NodeNum << ").\n";); 1024 1025 // Add dependencies against everything below it and clear maps. 1026 addBarrierChain(Stores); 1027 addBarrierChain(Loads); 1028 addBarrierChain(NonAliasStores); 1029 addBarrierChain(NonAliasLoads); 1030 1031 continue; 1032 } 1033 1034 // If it's not a store or a variant load, we're done. 1035 if (!MI->mayStore() && !(MI->mayLoad() && !MI->isInvariantLoad(AA))) 1036 continue; 1037 1038 // Always add dependecy edge to BarrierChain if present. 1039 if (BarrierChain) 1040 BarrierChain->addPredBarrier(SU); 1041 1042 // Find the underlying objects for MI. The Objs vector is either 1043 // empty, or filled with the Values of memory locations which this 1044 // SU depends on. An empty vector means the memory location is 1045 // unknown, and may alias anything except NonAlias nodes. 1046 UnderlyingObjectsVector Objs; 1047 getUnderlyingObjectsForInstr(MI, MFI, Objs, MF.getDataLayout()); 1048 1049 if (MI->mayStore()) { 1050 if (Objs.empty()) { 1051 // An unknown store depends on all stores and loads. 1052 addChainDependencies(SU, Stores); 1053 addChainDependencies(SU, NonAliasStores); 1054 addChainDependencies(SU, Loads); 1055 addChainDependencies(SU, NonAliasLoads); 1056 1057 // Map this store to 'UnknownValue'. 1058 Stores.insert(SU, UnknownValue); 1059 continue; 1060 } 1061 1062 // Add precise dependencies against all previously seen memory 1063 // accesses mapped to the same Value(s). 1064 for (auto &underlObj : Objs) { 1065 ValueType V = underlObj.getPointer(); 1066 bool ThisMayAlias = underlObj.getInt(); 1067 1068 Value2SUsMap &stores_ = (ThisMayAlias ? Stores : NonAliasStores); 1069 1070 // Add dependencies to previous stores and loads mapped to V. 1071 addChainDependencies(SU, stores_, V); 1072 addChainDependencies(SU, (ThisMayAlias ? Loads : NonAliasLoads), V); 1073 1074 // Map this store to V. 1075 stores_.insert(SU, V); 1076 } 1077 // The store may have dependencies to unanalyzable loads and 1078 // stores. 1079 addChainDependencies(SU, Loads, UnknownValue); 1080 addChainDependencies(SU, Stores, UnknownValue); 1081 } 1082 else { // SU is a load. 1083 if (Objs.empty()) { 1084 // An unknown load depends on all stores. 1085 addChainDependencies(SU, Stores); 1086 addChainDependencies(SU, NonAliasStores); 1087 1088 Loads.insert(SU, UnknownValue); 1089 continue; 1090 } 1091 1092 for (auto &underlObj : Objs) { 1093 ValueType V = underlObj.getPointer(); 1094 bool ThisMayAlias = underlObj.getInt(); 1095 1096 // Add precise dependencies against all previously seen stores 1097 // mapping to the same Value(s). 1098 addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V); 1099 1100 // Map this load to V. 1101 (ThisMayAlias ? Loads : NonAliasLoads).insert(SU, V); 1102 } 1103 // The load may have dependencies to unanalyzable stores. 1104 addChainDependencies(SU, Stores, UnknownValue); 1105 } 1106 1107 // Reduce maps if they grow huge. 1108 if (Stores.size() + Loads.size() >= HugeRegion) { 1109 DEBUG(dbgs() << "Reducing Stores and Loads maps.\n";); 1110 reduceHugeMemNodeMaps(Stores, Loads, ReductionSize); 1111 } 1112 if (NonAliasStores.size() + NonAliasLoads.size() >= HugeRegion) { 1113 DEBUG(dbgs() << "Reducing NonAliasStores and NonAliasLoads maps.\n";); 1114 reduceHugeMemNodeMaps(NonAliasStores, NonAliasLoads, ReductionSize); 1115 } 1116 } 1117 1118 if (DbgMI) 1119 FirstDbgValue = DbgMI; 1120 1121 Defs.clear(); 1122 Uses.clear(); 1123 CurrentVRegDefs.clear(); 1124 CurrentVRegUses.clear(); 1125 } 1126 1127 raw_ostream &llvm::operator<<(raw_ostream &OS, const PseudoSourceValue* PSV) { 1128 PSV->printCustom(OS); 1129 return OS; 1130 } 1131 1132 void ScheduleDAGInstrs::Value2SUsMap::dump() { 1133 for (auto &Itr : *this) { 1134 if (Itr.first.is<const Value*>()) { 1135 const Value *V = Itr.first.get<const Value*>(); 1136 if (isa<UndefValue>(V)) 1137 dbgs() << "Unknown"; 1138 else 1139 V->printAsOperand(dbgs()); 1140 } 1141 else if (Itr.first.is<const PseudoSourceValue*>()) 1142 dbgs() << Itr.first.get<const PseudoSourceValue*>(); 1143 else 1144 llvm_unreachable("Unknown Value type."); 1145 1146 dbgs() << " : "; 1147 dumpSUList(Itr.second); 1148 } 1149 } 1150 1151 /// Reduce maps in FIFO order, by N SUs. This is better than turning 1152 /// every Nth memory SU into BarrierChain in buildSchedGraph(), since 1153 /// it avoids unnecessary edges between seen SUs above the new 1154 /// BarrierChain, and those below it. 1155 void ScheduleDAGInstrs::reduceHugeMemNodeMaps(Value2SUsMap &stores, 1156 Value2SUsMap &loads, unsigned N) { 1157 DEBUG(dbgs() << "Before reduction:\nStoring SUnits:\n"; 1158 stores.dump(); 1159 dbgs() << "Loading SUnits:\n"; 1160 loads.dump()); 1161 1162 // Insert all SU's NodeNums into a vector and sort it. 1163 std::vector<unsigned> NodeNums; 1164 NodeNums.reserve(stores.size() + loads.size()); 1165 for (auto &I : stores) 1166 for (auto *SU : I.second) 1167 NodeNums.push_back(SU->NodeNum); 1168 for (auto &I : loads) 1169 for (auto *SU : I.second) 1170 NodeNums.push_back(SU->NodeNum); 1171 std::sort(NodeNums.begin(), NodeNums.end()); 1172 1173 // The N last elements in NodeNums will be removed, and the SU with 1174 // the lowest NodeNum of them will become the new BarrierChain to 1175 // let the not yet seen SUs have a dependency to the removed SUs. 1176 assert (N <= NodeNums.size()); 1177 SUnit *newBarrierChain = &SUnits[*(NodeNums.end() - N)]; 1178 if (BarrierChain) { 1179 // The aliasing and non-aliasing maps reduce independently of each 1180 // other, but share a common BarrierChain. Check if the 1181 // newBarrierChain is above the former one. If it is not, it may 1182 // introduce a loop to use newBarrierChain, so keep the old one. 1183 if (newBarrierChain->NodeNum < BarrierChain->NodeNum) { 1184 BarrierChain->addPredBarrier(newBarrierChain); 1185 BarrierChain = newBarrierChain; 1186 DEBUG(dbgs() << "Inserting new barrier chain: SU(" 1187 << BarrierChain->NodeNum << ").\n";); 1188 } 1189 else 1190 DEBUG(dbgs() << "Keeping old barrier chain: SU(" 1191 << BarrierChain->NodeNum << ").\n";); 1192 } 1193 else 1194 BarrierChain = newBarrierChain; 1195 1196 insertBarrierChain(stores); 1197 insertBarrierChain(loads); 1198 1199 DEBUG(dbgs() << "After reduction:\nStoring SUnits:\n"; 1200 stores.dump(); 1201 dbgs() << "Loading SUnits:\n"; 1202 loads.dump()); 1203 } 1204 1205 /// \brief Initialize register live-range state for updating kills. 1206 void ScheduleDAGInstrs::startBlockForKills(MachineBasicBlock *BB) { 1207 // Start with no live registers. 1208 LiveRegs.reset(); 1209 1210 // Examine the live-in regs of all successors. 1211 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(), 1212 SE = BB->succ_end(); SI != SE; ++SI) { 1213 for (const auto &LI : (*SI)->liveins()) { 1214 // Repeat, for reg and all subregs. 1215 for (MCSubRegIterator SubRegs(LI.PhysReg, TRI, /*IncludeSelf=*/true); 1216 SubRegs.isValid(); ++SubRegs) 1217 LiveRegs.set(*SubRegs); 1218 } 1219 } 1220 } 1221 1222 /// \brief If we change a kill flag on the bundle instruction implicit register 1223 /// operands, then we also need to propagate that to any instructions inside 1224 /// the bundle which had the same kill state. 1225 static void toggleBundleKillFlag(MachineInstr *MI, unsigned Reg, 1226 bool NewKillState) { 1227 if (MI->getOpcode() != TargetOpcode::BUNDLE) 1228 return; 1229 1230 // Walk backwards from the last instruction in the bundle to the first. 1231 // Once we set a kill flag on an instruction, we bail out, as otherwise we 1232 // might set it on too many operands. We will clear as many flags as we 1233 // can though. 1234 MachineBasicBlock::instr_iterator Begin = MI->getIterator(); 1235 MachineBasicBlock::instr_iterator End = getBundleEnd(MI); 1236 while (Begin != End) { 1237 for (MachineOperand &MO : (--End)->operands()) { 1238 if (!MO.isReg() || MO.isDef() || Reg != MO.getReg()) 1239 continue; 1240 1241 // DEBUG_VALUE nodes do not contribute to code generation and should 1242 // always be ignored. Failure to do so may result in trying to modify 1243 // KILL flags on DEBUG_VALUE nodes, which is distressing. 1244 if (MO.isDebug()) 1245 continue; 1246 1247 // If the register has the internal flag then it could be killing an 1248 // internal def of the register. In this case, just skip. We only want 1249 // to toggle the flag on operands visible outside the bundle. 1250 if (MO.isInternalRead()) 1251 continue; 1252 1253 if (MO.isKill() == NewKillState) 1254 continue; 1255 MO.setIsKill(NewKillState); 1256 if (NewKillState) 1257 return; 1258 } 1259 } 1260 } 1261 1262 bool ScheduleDAGInstrs::toggleKillFlag(MachineInstr *MI, MachineOperand &MO) { 1263 // Setting kill flag... 1264 if (!MO.isKill()) { 1265 MO.setIsKill(true); 1266 toggleBundleKillFlag(MI, MO.getReg(), true); 1267 return false; 1268 } 1269 1270 // If MO itself is live, clear the kill flag... 1271 if (LiveRegs.test(MO.getReg())) { 1272 MO.setIsKill(false); 1273 toggleBundleKillFlag(MI, MO.getReg(), false); 1274 return false; 1275 } 1276 1277 // If any subreg of MO is live, then create an imp-def for that 1278 // subreg and keep MO marked as killed. 1279 MO.setIsKill(false); 1280 toggleBundleKillFlag(MI, MO.getReg(), false); 1281 bool AllDead = true; 1282 const unsigned SuperReg = MO.getReg(); 1283 MachineInstrBuilder MIB(MF, MI); 1284 for (MCSubRegIterator SubRegs(SuperReg, TRI); SubRegs.isValid(); ++SubRegs) { 1285 if (LiveRegs.test(*SubRegs)) { 1286 MIB.addReg(*SubRegs, RegState::ImplicitDefine); 1287 AllDead = false; 1288 } 1289 } 1290 1291 if(AllDead) { 1292 MO.setIsKill(true); 1293 toggleBundleKillFlag(MI, MO.getReg(), true); 1294 } 1295 return false; 1296 } 1297 1298 // FIXME: Reuse the LivePhysRegs utility for this. 1299 void ScheduleDAGInstrs::fixupKills(MachineBasicBlock *MBB) { 1300 DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n'); 1301 1302 LiveRegs.resize(TRI->getNumRegs()); 1303 BitVector killedRegs(TRI->getNumRegs()); 1304 1305 startBlockForKills(MBB); 1306 1307 // Examine block from end to start... 1308 unsigned Count = MBB->size(); 1309 for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin(); 1310 I != E; --Count) { 1311 MachineInstr *MI = --I; 1312 if (MI->isDebugValue()) 1313 continue; 1314 1315 // Update liveness. Registers that are defed but not used in this 1316 // instruction are now dead. Mark register and all subregs as they 1317 // are completely defined. 1318 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 1319 MachineOperand &MO = MI->getOperand(i); 1320 if (MO.isRegMask()) 1321 LiveRegs.clearBitsNotInMask(MO.getRegMask()); 1322 if (!MO.isReg()) continue; 1323 unsigned Reg = MO.getReg(); 1324 if (Reg == 0) continue; 1325 if (!MO.isDef()) continue; 1326 // Ignore two-addr defs. 1327 if (MI->isRegTiedToUseOperand(i)) continue; 1328 1329 // Repeat for reg and all subregs. 1330 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true); 1331 SubRegs.isValid(); ++SubRegs) 1332 LiveRegs.reset(*SubRegs); 1333 } 1334 1335 // Examine all used registers and set/clear kill flag. When a 1336 // register is used multiple times we only set the kill flag on 1337 // the first use. Don't set kill flags on undef operands. 1338 killedRegs.reset(); 1339 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 1340 MachineOperand &MO = MI->getOperand(i); 1341 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue; 1342 unsigned Reg = MO.getReg(); 1343 if ((Reg == 0) || MRI.isReserved(Reg)) continue; 1344 1345 bool kill = false; 1346 if (!killedRegs.test(Reg)) { 1347 kill = true; 1348 // A register is not killed if any subregs are live... 1349 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) { 1350 if (LiveRegs.test(*SubRegs)) { 1351 kill = false; 1352 break; 1353 } 1354 } 1355 1356 // If subreg is not live, then register is killed if it became 1357 // live in this instruction 1358 if (kill) 1359 kill = !LiveRegs.test(Reg); 1360 } 1361 1362 if (MO.isKill() != kill) { 1363 DEBUG(dbgs() << "Fixing " << MO << " in "); 1364 // Warning: toggleKillFlag may invalidate MO. 1365 toggleKillFlag(MI, MO); 1366 DEBUG(MI->dump()); 1367 DEBUG(if (MI->getOpcode() == TargetOpcode::BUNDLE) { 1368 MachineBasicBlock::instr_iterator Begin = MI->getIterator(); 1369 MachineBasicBlock::instr_iterator End = getBundleEnd(MI); 1370 while (++Begin != End) 1371 DEBUG(Begin->dump()); 1372 }); 1373 } 1374 1375 killedRegs.set(Reg); 1376 } 1377 1378 // Mark any used register (that is not using undef) and subregs as 1379 // now live... 1380 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 1381 MachineOperand &MO = MI->getOperand(i); 1382 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue; 1383 unsigned Reg = MO.getReg(); 1384 if ((Reg == 0) || MRI.isReserved(Reg)) continue; 1385 1386 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true); 1387 SubRegs.isValid(); ++SubRegs) 1388 LiveRegs.set(*SubRegs); 1389 } 1390 } 1391 } 1392 1393 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const { 1394 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1395 SU->getInstr()->dump(); 1396 #endif 1397 } 1398 1399 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const { 1400 std::string s; 1401 raw_string_ostream oss(s); 1402 if (SU == &EntrySU) 1403 oss << "<entry>"; 1404 else if (SU == &ExitSU) 1405 oss << "<exit>"; 1406 else 1407 SU->getInstr()->print(oss, /*SkipOpers=*/true); 1408 return oss.str(); 1409 } 1410 1411 /// Return the basic block label. It is not necessarilly unique because a block 1412 /// contains multiple scheduling regions. But it is fine for visualization. 1413 std::string ScheduleDAGInstrs::getDAGName() const { 1414 return "dag." + BB->getFullName(); 1415 } 1416 1417 //===----------------------------------------------------------------------===// 1418 // SchedDFSResult Implementation 1419 //===----------------------------------------------------------------------===// 1420 1421 namespace llvm { 1422 /// \brief Internal state used to compute SchedDFSResult. 1423 class SchedDFSImpl { 1424 SchedDFSResult &R; 1425 1426 /// Join DAG nodes into equivalence classes by their subtree. 1427 IntEqClasses SubtreeClasses; 1428 /// List PredSU, SuccSU pairs that represent data edges between subtrees. 1429 std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs; 1430 1431 struct RootData { 1432 unsigned NodeID; 1433 unsigned ParentNodeID; // Parent node (member of the parent subtree). 1434 unsigned SubInstrCount; // Instr count in this tree only, not children. 1435 1436 RootData(unsigned id): NodeID(id), 1437 ParentNodeID(SchedDFSResult::InvalidSubtreeID), 1438 SubInstrCount(0) {} 1439 1440 unsigned getSparseSetIndex() const { return NodeID; } 1441 }; 1442 1443 SparseSet<RootData> RootSet; 1444 1445 public: 1446 SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) { 1447 RootSet.setUniverse(R.DFSNodeData.size()); 1448 } 1449 1450 /// Return true if this node been visited by the DFS traversal. 1451 /// 1452 /// During visitPostorderNode the Node's SubtreeID is assigned to the Node 1453 /// ID. Later, SubtreeID is updated but remains valid. 1454 bool isVisited(const SUnit *SU) const { 1455 return R.DFSNodeData[SU->NodeNum].SubtreeID 1456 != SchedDFSResult::InvalidSubtreeID; 1457 } 1458 1459 /// Initialize this node's instruction count. We don't need to flag the node 1460 /// visited until visitPostorder because the DAG cannot have cycles. 1461 void visitPreorder(const SUnit *SU) { 1462 R.DFSNodeData[SU->NodeNum].InstrCount = 1463 SU->getInstr()->isTransient() ? 0 : 1; 1464 } 1465 1466 /// Called once for each node after all predecessors are visited. Revisit this 1467 /// node's predecessors and potentially join them now that we know the ILP of 1468 /// the other predecessors. 1469 void visitPostorderNode(const SUnit *SU) { 1470 // Mark this node as the root of a subtree. It may be joined with its 1471 // successors later. 1472 R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum; 1473 RootData RData(SU->NodeNum); 1474 RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1; 1475 1476 // If any predecessors are still in their own subtree, they either cannot be 1477 // joined or are large enough to remain separate. If this parent node's 1478 // total instruction count is not greater than a child subtree by at least 1479 // the subtree limit, then try to join it now since splitting subtrees is 1480 // only useful if multiple high-pressure paths are possible. 1481 unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount; 1482 for (SUnit::const_pred_iterator 1483 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) { 1484 if (PI->getKind() != SDep::Data) 1485 continue; 1486 unsigned PredNum = PI->getSUnit()->NodeNum; 1487 if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit) 1488 joinPredSubtree(*PI, SU, /*CheckLimit=*/false); 1489 1490 // Either link or merge the TreeData entry from the child to the parent. 1491 if (R.DFSNodeData[PredNum].SubtreeID == PredNum) { 1492 // If the predecessor's parent is invalid, this is a tree edge and the 1493 // current node is the parent. 1494 if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID) 1495 RootSet[PredNum].ParentNodeID = SU->NodeNum; 1496 } 1497 else if (RootSet.count(PredNum)) { 1498 // The predecessor is not a root, but is still in the root set. This 1499 // must be the new parent that it was just joined to. Note that 1500 // RootSet[PredNum].ParentNodeID may either be invalid or may still be 1501 // set to the original parent. 1502 RData.SubInstrCount += RootSet[PredNum].SubInstrCount; 1503 RootSet.erase(PredNum); 1504 } 1505 } 1506 RootSet[SU->NodeNum] = RData; 1507 } 1508 1509 /// Called once for each tree edge after calling visitPostOrderNode on the 1510 /// predecessor. Increment the parent node's instruction count and 1511 /// preemptively join this subtree to its parent's if it is small enough. 1512 void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) { 1513 R.DFSNodeData[Succ->NodeNum].InstrCount 1514 += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount; 1515 joinPredSubtree(PredDep, Succ); 1516 } 1517 1518 /// Add a connection for cross edges. 1519 void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) { 1520 ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ)); 1521 } 1522 1523 /// Set each node's subtree ID to the representative ID and record connections 1524 /// between trees. 1525 void finalize() { 1526 SubtreeClasses.compress(); 1527 R.DFSTreeData.resize(SubtreeClasses.getNumClasses()); 1528 assert(SubtreeClasses.getNumClasses() == RootSet.size() 1529 && "number of roots should match trees"); 1530 for (SparseSet<RootData>::const_iterator 1531 RI = RootSet.begin(), RE = RootSet.end(); RI != RE; ++RI) { 1532 unsigned TreeID = SubtreeClasses[RI->NodeID]; 1533 if (RI->ParentNodeID != SchedDFSResult::InvalidSubtreeID) 1534 R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[RI->ParentNodeID]; 1535 R.DFSTreeData[TreeID].SubInstrCount = RI->SubInstrCount; 1536 // Note that SubInstrCount may be greater than InstrCount if we joined 1537 // subtrees across a cross edge. InstrCount will be attributed to the 1538 // original parent, while SubInstrCount will be attributed to the joined 1539 // parent. 1540 } 1541 R.SubtreeConnections.resize(SubtreeClasses.getNumClasses()); 1542 R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses()); 1543 DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n"); 1544 for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) { 1545 R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx]; 1546 DEBUG(dbgs() << " SU(" << Idx << ") in tree " 1547 << R.DFSNodeData[Idx].SubtreeID << '\n'); 1548 } 1549 for (std::vector<std::pair<const SUnit*, const SUnit*> >::const_iterator 1550 I = ConnectionPairs.begin(), E = ConnectionPairs.end(); 1551 I != E; ++I) { 1552 unsigned PredTree = SubtreeClasses[I->first->NodeNum]; 1553 unsigned SuccTree = SubtreeClasses[I->second->NodeNum]; 1554 if (PredTree == SuccTree) 1555 continue; 1556 unsigned Depth = I->first->getDepth(); 1557 addConnection(PredTree, SuccTree, Depth); 1558 addConnection(SuccTree, PredTree, Depth); 1559 } 1560 } 1561 1562 protected: 1563 /// Join the predecessor subtree with the successor that is its DFS 1564 /// parent. Apply some heuristics before joining. 1565 bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ, 1566 bool CheckLimit = true) { 1567 assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges"); 1568 1569 // Check if the predecessor is already joined. 1570 const SUnit *PredSU = PredDep.getSUnit(); 1571 unsigned PredNum = PredSU->NodeNum; 1572 if (R.DFSNodeData[PredNum].SubtreeID != PredNum) 1573 return false; 1574 1575 // Four is the magic number of successors before a node is considered a 1576 // pinch point. 1577 unsigned NumDataSucs = 0; 1578 for (SUnit::const_succ_iterator SI = PredSU->Succs.begin(), 1579 SE = PredSU->Succs.end(); SI != SE; ++SI) { 1580 if (SI->getKind() == SDep::Data) { 1581 if (++NumDataSucs >= 4) 1582 return false; 1583 } 1584 } 1585 if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit) 1586 return false; 1587 R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum; 1588 SubtreeClasses.join(Succ->NodeNum, PredNum); 1589 return true; 1590 } 1591 1592 /// Called by finalize() to record a connection between trees. 1593 void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) { 1594 if (!Depth) 1595 return; 1596 1597 do { 1598 SmallVectorImpl<SchedDFSResult::Connection> &Connections = 1599 R.SubtreeConnections[FromTree]; 1600 for (SmallVectorImpl<SchedDFSResult::Connection>::iterator 1601 I = Connections.begin(), E = Connections.end(); I != E; ++I) { 1602 if (I->TreeID == ToTree) { 1603 I->Level = std::max(I->Level, Depth); 1604 return; 1605 } 1606 } 1607 Connections.push_back(SchedDFSResult::Connection(ToTree, Depth)); 1608 FromTree = R.DFSTreeData[FromTree].ParentTreeID; 1609 } while (FromTree != SchedDFSResult::InvalidSubtreeID); 1610 } 1611 }; 1612 } // namespace llvm 1613 1614 namespace { 1615 /// \brief Manage the stack used by a reverse depth-first search over the DAG. 1616 class SchedDAGReverseDFS { 1617 std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack; 1618 public: 1619 bool isComplete() const { return DFSStack.empty(); } 1620 1621 void follow(const SUnit *SU) { 1622 DFSStack.push_back(std::make_pair(SU, SU->Preds.begin())); 1623 } 1624 void advance() { ++DFSStack.back().second; } 1625 1626 const SDep *backtrack() { 1627 DFSStack.pop_back(); 1628 return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second); 1629 } 1630 1631 const SUnit *getCurr() const { return DFSStack.back().first; } 1632 1633 SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; } 1634 1635 SUnit::const_pred_iterator getPredEnd() const { 1636 return getCurr()->Preds.end(); 1637 } 1638 }; 1639 } // anonymous 1640 1641 static bool hasDataSucc(const SUnit *SU) { 1642 for (SUnit::const_succ_iterator 1643 SI = SU->Succs.begin(), SE = SU->Succs.end(); SI != SE; ++SI) { 1644 if (SI->getKind() == SDep::Data && !SI->getSUnit()->isBoundaryNode()) 1645 return true; 1646 } 1647 return false; 1648 } 1649 1650 /// Compute an ILP metric for all nodes in the subDAG reachable via depth-first 1651 /// search from this root. 1652 void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) { 1653 if (!IsBottomUp) 1654 llvm_unreachable("Top-down ILP metric is unimplemnted"); 1655 1656 SchedDFSImpl Impl(*this); 1657 for (ArrayRef<SUnit>::const_iterator 1658 SI = SUnits.begin(), SE = SUnits.end(); SI != SE; ++SI) { 1659 const SUnit *SU = &*SI; 1660 if (Impl.isVisited(SU) || hasDataSucc(SU)) 1661 continue; 1662 1663 SchedDAGReverseDFS DFS; 1664 Impl.visitPreorder(SU); 1665 DFS.follow(SU); 1666 for (;;) { 1667 // Traverse the leftmost path as far as possible. 1668 while (DFS.getPred() != DFS.getPredEnd()) { 1669 const SDep &PredDep = *DFS.getPred(); 1670 DFS.advance(); 1671 // Ignore non-data edges. 1672 if (PredDep.getKind() != SDep::Data 1673 || PredDep.getSUnit()->isBoundaryNode()) { 1674 continue; 1675 } 1676 // An already visited edge is a cross edge, assuming an acyclic DAG. 1677 if (Impl.isVisited(PredDep.getSUnit())) { 1678 Impl.visitCrossEdge(PredDep, DFS.getCurr()); 1679 continue; 1680 } 1681 Impl.visitPreorder(PredDep.getSUnit()); 1682 DFS.follow(PredDep.getSUnit()); 1683 } 1684 // Visit the top of the stack in postorder and backtrack. 1685 const SUnit *Child = DFS.getCurr(); 1686 const SDep *PredDep = DFS.backtrack(); 1687 Impl.visitPostorderNode(Child); 1688 if (PredDep) 1689 Impl.visitPostorderEdge(*PredDep, DFS.getCurr()); 1690 if (DFS.isComplete()) 1691 break; 1692 } 1693 } 1694 Impl.finalize(); 1695 } 1696 1697 /// The root of the given SubtreeID was just scheduled. For all subtrees 1698 /// connected to this tree, record the depth of the connection so that the 1699 /// nearest connected subtrees can be prioritized. 1700 void SchedDFSResult::scheduleTree(unsigned SubtreeID) { 1701 for (SmallVectorImpl<Connection>::const_iterator 1702 I = SubtreeConnections[SubtreeID].begin(), 1703 E = SubtreeConnections[SubtreeID].end(); I != E; ++I) { 1704 SubtreeConnectLevels[I->TreeID] = 1705 std::max(SubtreeConnectLevels[I->TreeID], I->Level); 1706 DEBUG(dbgs() << " Tree: " << I->TreeID 1707 << " @" << SubtreeConnectLevels[I->TreeID] << '\n'); 1708 } 1709 } 1710 1711 LLVM_DUMP_METHOD 1712 void ILPValue::print(raw_ostream &OS) const { 1713 OS << InstrCount << " / " << Length << " = "; 1714 if (!Length) 1715 OS << "BADILP"; 1716 else 1717 OS << format("%g", ((double)InstrCount / Length)); 1718 } 1719 1720 LLVM_DUMP_METHOD 1721 void ILPValue::dump() const { 1722 dbgs() << *this << '\n'; 1723 } 1724 1725 namespace llvm { 1726 1727 LLVM_DUMP_METHOD 1728 raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) { 1729 Val.print(OS); 1730 return OS; 1731 } 1732 1733 } // namespace llvm 1734