LLVM  mainline
ScheduleDAGInstrs.cpp
Go to the documentation of this file.
00001 //===---- ScheduleDAGInstrs.cpp - MachineInstr Rescheduling ---------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This implements the ScheduleDAGInstrs class, which implements re-scheduling
00011 // of MachineInstrs.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
00016 #include "llvm/ADT/MapVector.h"
00017 #include "llvm/ADT/SmallPtrSet.h"
00018 #include "llvm/ADT/SmallSet.h"
00019 #include "llvm/Analysis/AliasAnalysis.h"
00020 #include "llvm/Analysis/ValueTracking.h"
00021 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00022 #include "llvm/CodeGen/MachineFunctionPass.h"
00023 #include "llvm/CodeGen/MachineFrameInfo.h"
00024 #include "llvm/CodeGen/MachineInstrBuilder.h"
00025 #include "llvm/CodeGen/MachineMemOperand.h"
00026 #include "llvm/CodeGen/MachineRegisterInfo.h"
00027 #include "llvm/CodeGen/PseudoSourceValue.h"
00028 #include "llvm/CodeGen/RegisterPressure.h"
00029 #include "llvm/CodeGen/ScheduleDFS.h"
00030 #include "llvm/IR/Operator.h"
00031 #include "llvm/Support/CommandLine.h"
00032 #include "llvm/Support/Debug.h"
00033 #include "llvm/Support/Format.h"
00034 #include "llvm/Support/raw_ostream.h"
00035 #include "llvm/Target/TargetInstrInfo.h"
00036 #include "llvm/Target/TargetMachine.h"
00037 #include "llvm/Target/TargetRegisterInfo.h"
00038 #include "llvm/Target/TargetSubtargetInfo.h"
00039 #include <queue>
00040 
00041 using namespace llvm;
00042 
00043 #define DEBUG_TYPE "misched"
00044 
00045 static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
00046     cl::ZeroOrMore, cl::init(false),
00047     cl::desc("Enable use of AA during MI DAG construction"));
00048 
00049 static cl::opt<bool> UseTBAA("use-tbaa-in-sched-mi", cl::Hidden,
00050     cl::init(true), cl::desc("Enable use of TBAA during MI DAG construction"));
00051 
00052 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
00053                                      const MachineLoopInfo *mli,
00054                                      bool IsPostRAFlag, bool RemoveKillFlags,
00055                                      LiveIntervals *lis)
00056     : ScheduleDAG(mf), MLI(mli), MFI(mf.getFrameInfo()), LIS(lis),
00057       IsPostRA(IsPostRAFlag), RemoveKillFlags(RemoveKillFlags),
00058       CanHandleTerminators(false), FirstDbgValue(nullptr) {
00059   assert((IsPostRA || LIS) && "PreRA scheduling requires LiveIntervals");
00060   DbgValues.clear();
00061   assert(!(IsPostRA && MRI.getNumVirtRegs()) &&
00062          "Virtual registers must be removed prior to PostRA scheduling");
00063 
00064   const TargetSubtargetInfo &ST = mf.getSubtarget();
00065   SchedModel.init(ST.getSchedModel(), &ST, TII);
00066 }
00067 
00068 /// getUnderlyingObjectFromInt - This is the function that does the work of
00069 /// looking through basic ptrtoint+arithmetic+inttoptr sequences.
00070 static const Value *getUnderlyingObjectFromInt(const Value *V) {
00071   do {
00072     if (const Operator *U = dyn_cast<Operator>(V)) {
00073       // If we find a ptrtoint, we can transfer control back to the
00074       // regular getUnderlyingObjectFromInt.
00075       if (U->getOpcode() == Instruction::PtrToInt)
00076         return U->getOperand(0);
00077       // If we find an add of a constant, a multiplied value, or a phi, it's
00078       // likely that the other operand will lead us to the base
00079       // object. We don't have to worry about the case where the
00080       // object address is somehow being computed by the multiply,
00081       // because our callers only care when the result is an
00082       // identifiable object.
00083       if (U->getOpcode() != Instruction::Add ||
00084           (!isa<ConstantInt>(U->getOperand(1)) &&
00085            Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
00086            !isa<PHINode>(U->getOperand(1))))
00087         return V;
00088       V = U->getOperand(0);
00089     } else {
00090       return V;
00091     }
00092     assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
00093   } while (1);
00094 }
00095 
00096 /// getUnderlyingObjects - This is a wrapper around GetUnderlyingObjects
00097 /// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
00098 static void getUnderlyingObjects(const Value *V,
00099                                  SmallVectorImpl<Value *> &Objects,
00100                                  const DataLayout &DL) {
00101   SmallPtrSet<const Value *, 16> Visited;
00102   SmallVector<const Value *, 4> Working(1, V);
00103   do {
00104     V = Working.pop_back_val();
00105 
00106     SmallVector<Value *, 4> Objs;
00107     GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
00108 
00109     for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), IE = Objs.end();
00110          I != IE; ++I) {
00111       V = *I;
00112       if (!Visited.insert(V).second)
00113         continue;
00114       if (Operator::getOpcode(V) == Instruction::IntToPtr) {
00115         const Value *O =
00116           getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
00117         if (O->getType()->isPointerTy()) {
00118           Working.push_back(O);
00119           continue;
00120         }
00121       }
00122       Objects.push_back(const_cast<Value *>(V));
00123     }
00124   } while (!Working.empty());
00125 }
00126 
00127 typedef PointerUnion<const Value *, const PseudoSourceValue *> ValueType;
00128 typedef SmallVector<PointerIntPair<ValueType, 1, bool>, 4>
00129 UnderlyingObjectsVector;
00130 
00131 /// getUnderlyingObjectsForInstr - If this machine instr has memory reference
00132 /// information and it can be tracked to a normal reference to a known
00133 /// object, return the Value for that object.
00134 static void getUnderlyingObjectsForInstr(const MachineInstr *MI,
00135                                          const MachineFrameInfo *MFI,
00136                                          UnderlyingObjectsVector &Objects,
00137                                          const DataLayout &DL) {
00138   if (!MI->hasOneMemOperand() ||
00139       (!(*MI->memoperands_begin())->getValue() &&
00140        !(*MI->memoperands_begin())->getPseudoValue()) ||
00141       (*MI->memoperands_begin())->isVolatile())
00142     return;
00143 
00144   if (const PseudoSourceValue *PSV =
00145       (*MI->memoperands_begin())->getPseudoValue()) {
00146     // Function that contain tail calls don't have unique PseudoSourceValue
00147     // objects. Two PseudoSourceValues might refer to the same or overlapping
00148     // locations. The client code calling this function assumes this is not the
00149     // case. So return a conservative answer of no known object.
00150     if (MFI->hasTailCall())
00151       return;
00152 
00153     // For now, ignore PseudoSourceValues which may alias LLVM IR values
00154     // because the code that uses this function has no way to cope with
00155     // such aliases.
00156     if (!PSV->isAliased(MFI)) {
00157       bool MayAlias = PSV->mayAlias(MFI);
00158       Objects.push_back(UnderlyingObjectsVector::value_type(PSV, MayAlias));
00159     }
00160     return;
00161   }
00162 
00163   const Value *V = (*MI->memoperands_begin())->getValue();
00164   if (!V)
00165     return;
00166 
00167   SmallVector<Value *, 4> Objs;
00168   getUnderlyingObjects(V, Objs, DL);
00169 
00170   for (Value *V : Objs) {
00171     if (!isIdentifiedObject(V)) {
00172       Objects.clear();
00173       return;
00174     }
00175 
00176     Objects.push_back(UnderlyingObjectsVector::value_type(V, true));
00177   }
00178 }
00179 
00180 void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
00181   BB = bb;
00182 }
00183 
00184 void ScheduleDAGInstrs::finishBlock() {
00185   // Subclasses should no longer refer to the old block.
00186   BB = nullptr;
00187 }
00188 
00189 /// Initialize the DAG and common scheduler state for the current scheduling
00190 /// region. This does not actually create the DAG, only clears it. The
00191 /// scheduling driver may call BuildSchedGraph multiple times per scheduling
00192 /// region.
00193 void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
00194                                     MachineBasicBlock::iterator begin,
00195                                     MachineBasicBlock::iterator end,
00196                                     unsigned regioninstrs) {
00197   assert(bb == BB && "startBlock should set BB");
00198   RegionBegin = begin;
00199   RegionEnd = end;
00200   NumRegionInstrs = regioninstrs;
00201 }
00202 
00203 /// Close the current scheduling region. Don't clear any state in case the
00204 /// driver wants to refer to the previous scheduling region.
00205 void ScheduleDAGInstrs::exitRegion() {
00206   // Nothing to do.
00207 }
00208 
00209 /// addSchedBarrierDeps - Add dependencies from instructions in the current
00210 /// list of instructions being scheduled to scheduling barrier by adding
00211 /// the exit SU to the register defs and use list. This is because we want to
00212 /// make sure instructions which define registers that are either used by
00213 /// the terminator or are live-out are properly scheduled. This is
00214 /// especially important when the definition latency of the return value(s)
00215 /// are too high to be hidden by the branch or when the liveout registers
00216 /// used by instructions in the fallthrough block.
00217 void ScheduleDAGInstrs::addSchedBarrierDeps() {
00218   MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : nullptr;
00219   ExitSU.setInstr(ExitMI);
00220   bool AllDepKnown = ExitMI &&
00221     (ExitMI->isCall() || ExitMI->isBarrier());
00222   if (ExitMI && AllDepKnown) {
00223     // If it's a call or a barrier, add dependencies on the defs and uses of
00224     // instruction.
00225     for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
00226       const MachineOperand &MO = ExitMI->getOperand(i);
00227       if (!MO.isReg() || MO.isDef()) continue;
00228       unsigned Reg = MO.getReg();
00229       if (Reg == 0) continue;
00230 
00231       if (TRI->isPhysicalRegister(Reg))
00232         Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
00233       else {
00234         assert(!IsPostRA && "Virtual register encountered after regalloc.");
00235         if (MO.readsReg()) // ignore undef operands
00236           addVRegUseDeps(&ExitSU, i);
00237       }
00238     }
00239   } else {
00240     // For others, e.g. fallthrough, conditional branch, assume the exit
00241     // uses all the registers that are livein to the successor blocks.
00242     assert(Uses.empty() && "Uses in set before adding deps?");
00243     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
00244            SE = BB->succ_end(); SI != SE; ++SI)
00245       for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
00246              E = (*SI)->livein_end(); I != E; ++I) {
00247         unsigned Reg = *I;
00248         if (!Uses.contains(Reg))
00249           Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
00250       }
00251   }
00252 }
00253 
00254 /// MO is an operand of SU's instruction that defines a physical register. Add
00255 /// data dependencies from SU to any uses of the physical register.
00256 void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
00257   const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
00258   assert(MO.isDef() && "expect physreg def");
00259 
00260   // Ask the target if address-backscheduling is desirable, and if so how much.
00261   const TargetSubtargetInfo &ST = MF.getSubtarget();
00262 
00263   for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
00264        Alias.isValid(); ++Alias) {
00265     if (!Uses.contains(*Alias))
00266       continue;
00267     for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
00268       SUnit *UseSU = I->SU;
00269       if (UseSU == SU)
00270         continue;
00271 
00272       // Adjust the dependence latency using operand def/use information,
00273       // then allow the target to perform its own adjustments.
00274       int UseOp = I->OpIdx;
00275       MachineInstr *RegUse = nullptr;
00276       SDep Dep;
00277       if (UseOp < 0)
00278         Dep = SDep(SU, SDep::Artificial);
00279       else {
00280         // Set the hasPhysRegDefs only for physreg defs that have a use within
00281         // the scheduling region.
00282         SU->hasPhysRegDefs = true;
00283         Dep = SDep(SU, SDep::Data, *Alias);
00284         RegUse = UseSU->getInstr();
00285       }
00286       Dep.setLatency(
00287         SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, RegUse,
00288                                          UseOp));
00289 
00290       ST.adjustSchedDependency(SU, UseSU, Dep);
00291       UseSU->addPred(Dep);
00292     }
00293   }
00294 }
00295 
00296 /// addPhysRegDeps - Add register dependencies (data, anti, and output) from
00297 /// this SUnit to following instructions in the same scheduling region that
00298 /// depend the physical register referenced at OperIdx.
00299 void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
00300   MachineInstr *MI = SU->getInstr();
00301   MachineOperand &MO = MI->getOperand(OperIdx);
00302 
00303   // Optionally add output and anti dependencies. For anti
00304   // dependencies we use a latency of 0 because for a multi-issue
00305   // target we want to allow the defining instruction to issue
00306   // in the same cycle as the using instruction.
00307   // TODO: Using a latency of 1 here for output dependencies assumes
00308   //       there's no cost for reusing registers.
00309   SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
00310   for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
00311        Alias.isValid(); ++Alias) {
00312     if (!Defs.contains(*Alias))
00313       continue;
00314     for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
00315       SUnit *DefSU = I->SU;
00316       if (DefSU == &ExitSU)
00317         continue;
00318       if (DefSU != SU &&
00319           (Kind != SDep::Output || !MO.isDead() ||
00320            !DefSU->getInstr()->registerDefIsDead(*Alias))) {
00321         if (Kind == SDep::Anti)
00322           DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
00323         else {
00324           SDep Dep(SU, Kind, /*Reg=*/*Alias);
00325           Dep.setLatency(
00326             SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
00327           DefSU->addPred(Dep);
00328         }
00329       }
00330     }
00331   }
00332 
00333   if (!MO.isDef()) {
00334     SU->hasPhysRegUses = true;
00335     // Either insert a new Reg2SUnits entry with an empty SUnits list, or
00336     // retrieve the existing SUnits list for this register's uses.
00337     // Push this SUnit on the use list.
00338     Uses.insert(PhysRegSUOper(SU, OperIdx, MO.getReg()));
00339     if (RemoveKillFlags)
00340       MO.setIsKill(false);
00341   }
00342   else {
00343     addPhysRegDataDeps(SU, OperIdx);
00344     unsigned Reg = MO.getReg();
00345 
00346     // clear this register's use list
00347     if (Uses.contains(Reg))
00348       Uses.eraseAll(Reg);
00349 
00350     if (!MO.isDead()) {
00351       Defs.eraseAll(Reg);
00352     } else if (SU->isCall) {
00353       // Calls will not be reordered because of chain dependencies (see
00354       // below). Since call operands are dead, calls may continue to be added
00355       // to the DefList making dependence checking quadratic in the size of
00356       // the block. Instead, we leave only one call at the back of the
00357       // DefList.
00358       Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
00359       Reg2SUnitsMap::iterator B = P.first;
00360       Reg2SUnitsMap::iterator I = P.second;
00361       for (bool isBegin = I == B; !isBegin; /* empty */) {
00362         isBegin = (--I) == B;
00363         if (!I->SU->isCall)
00364           break;
00365         I = Defs.erase(I);
00366       }
00367     }
00368 
00369     // Defs are pushed in the order they are visited and never reordered.
00370     Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
00371   }
00372 }
00373 
00374 /// addVRegDefDeps - Add register output and data dependencies from this SUnit
00375 /// to instructions that occur later in the same scheduling region if they read
00376 /// from or write to the virtual register defined at OperIdx.
00377 ///
00378 /// TODO: Hoist loop induction variable increments. This has to be
00379 /// reevaluated. Generally, IV scheduling should be done before coalescing.
00380 void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
00381   const MachineInstr *MI = SU->getInstr();
00382   unsigned Reg = MI->getOperand(OperIdx).getReg();
00383 
00384   // Singly defined vregs do not have output/anti dependencies.
00385   // The current operand is a def, so we have at least one.
00386   // Check here if there are any others...
00387   if (MRI.hasOneDef(Reg))
00388     return;
00389 
00390   // Add output dependence to the next nearest def of this vreg.
00391   //
00392   // Unless this definition is dead, the output dependence should be
00393   // transitively redundant with antidependencies from this definition's
00394   // uses. We're conservative for now until we have a way to guarantee the uses
00395   // are not eliminated sometime during scheduling. The output dependence edge
00396   // is also useful if output latency exceeds def-use latency.
00397   VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
00398   if (DefI == VRegDefs.end())
00399     VRegDefs.insert(VReg2SUnit(Reg, SU));
00400   else {
00401     SUnit *DefSU = DefI->SU;
00402     if (DefSU != SU && DefSU != &ExitSU) {
00403       SDep Dep(SU, SDep::Output, Reg);
00404       Dep.setLatency(
00405         SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
00406       DefSU->addPred(Dep);
00407     }
00408     DefI->SU = SU;
00409   }
00410 }
00411 
00412 /// addVRegUseDeps - Add a register data dependency if the instruction that
00413 /// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
00414 /// register antidependency from this SUnit to instructions that occur later in
00415 /// the same scheduling region if they write the virtual register.
00416 ///
00417 /// TODO: Handle ExitSU "uses" properly.
00418 void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
00419   MachineInstr *MI = SU->getInstr();
00420   unsigned Reg = MI->getOperand(OperIdx).getReg();
00421 
00422   // Record this local VReg use.
00423   VReg2UseMap::iterator UI = VRegUses.find(Reg);
00424   for (; UI != VRegUses.end(); ++UI) {
00425     if (UI->SU == SU)
00426       break;
00427   }
00428   if (UI == VRegUses.end())
00429     VRegUses.insert(VReg2SUnit(Reg, SU));
00430 
00431   // Lookup this operand's reaching definition.
00432   assert(LIS && "vreg dependencies requires LiveIntervals");
00433   LiveQueryResult LRQ
00434     = LIS->getInterval(Reg).Query(LIS->getInstructionIndex(MI));
00435   VNInfo *VNI = LRQ.valueIn();
00436 
00437   // VNI will be valid because MachineOperand::readsReg() is checked by caller.
00438   assert(VNI && "No value to read by operand");
00439   MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def);
00440   // Phis and other noninstructions (after coalescing) have a NULL Def.
00441   if (Def) {
00442     SUnit *DefSU = getSUnit(Def);
00443     if (DefSU) {
00444       // The reaching Def lives within this scheduling region.
00445       // Create a data dependence.
00446       SDep dep(DefSU, SDep::Data, Reg);
00447       // Adjust the dependence latency using operand def/use information, then
00448       // allow the target to perform its own adjustments.
00449       int DefOp = Def->findRegisterDefOperandIdx(Reg);
00450       dep.setLatency(SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx));
00451 
00452       const TargetSubtargetInfo &ST = MF.getSubtarget();
00453       ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
00454       SU->addPred(dep);
00455     }
00456   }
00457 
00458   // Add antidependence to the following def of the vreg it uses.
00459   VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
00460   if (DefI != VRegDefs.end() && DefI->SU != SU)
00461     DefI->SU->addPred(SDep(SU, SDep::Anti, Reg));
00462 }
00463 
00464 /// Return true if MI is an instruction we are unable to reason about
00465 /// (like a call or something with unmodeled side effects).
00466 static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
00467   if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
00468       (MI->hasOrderedMemoryRef() &&
00469        (!MI->mayLoad() || !MI->isInvariantLoad(AA))))
00470     return true;
00471   return false;
00472 }
00473 
00474 // This MI might have either incomplete info, or known to be unsafe
00475 // to deal with (i.e. volatile object).
00476 static inline bool isUnsafeMemoryObject(MachineInstr *MI,
00477                                         const MachineFrameInfo *MFI,
00478                                         const DataLayout &DL) {
00479   if (!MI || MI->memoperands_empty())
00480     return true;
00481   // We purposefully do no check for hasOneMemOperand() here
00482   // in hope to trigger an assert downstream in order to
00483   // finish implementation.
00484   if ((*MI->memoperands_begin())->isVolatile() ||
00485        MI->hasUnmodeledSideEffects())
00486     return true;
00487 
00488   if ((*MI->memoperands_begin())->getPseudoValue()) {
00489     // Similarly to getUnderlyingObjectForInstr:
00490     // For now, ignore PseudoSourceValues which may alias LLVM IR values
00491     // because the code that uses this function has no way to cope with
00492     // such aliases.
00493     return true;
00494   }
00495 
00496   const Value *V = (*MI->memoperands_begin())->getValue();
00497   if (!V)
00498     return true;
00499 
00500   SmallVector<Value *, 4> Objs;
00501   getUnderlyingObjects(V, Objs, DL);
00502   for (Value *V : Objs) {
00503     // Does this pointer refer to a distinct and identifiable object?
00504     if (!isIdentifiedObject(V))
00505       return true;
00506   }
00507 
00508   return false;
00509 }
00510 
00511 /// This returns true if the two MIs need a chain edge betwee them.
00512 /// If these are not even memory operations, we still may need
00513 /// chain deps between them. The question really is - could
00514 /// these two MIs be reordered during scheduling from memory dependency
00515 /// point of view.
00516 static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
00517                              const DataLayout &DL, MachineInstr *MIa,
00518                              MachineInstr *MIb) {
00519   const MachineFunction *MF = MIa->getParent()->getParent();
00520   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
00521 
00522   // Cover a trivial case - no edge is need to itself.
00523   if (MIa == MIb)
00524     return false;
00525  
00526   // Let the target decide if memory accesses cannot possibly overlap.
00527   if ((MIa->mayLoad() || MIa->mayStore()) &&
00528       (MIb->mayLoad() || MIb->mayStore()))
00529     if (TII->areMemAccessesTriviallyDisjoint(MIa, MIb, AA))
00530       return false;
00531 
00532   // FIXME: Need to handle multiple memory operands to support all targets.
00533   if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
00534     return true;
00535 
00536   if (isUnsafeMemoryObject(MIa, MFI, DL) || isUnsafeMemoryObject(MIb, MFI, DL))
00537     return true;
00538 
00539   // If we are dealing with two "normal" loads, we do not need an edge
00540   // between them - they could be reordered.
00541   if (!MIa->mayStore() && !MIb->mayStore())
00542     return false;
00543 
00544   // To this point analysis is generic. From here on we do need AA.
00545   if (!AA)
00546     return true;
00547 
00548   MachineMemOperand *MMOa = *MIa->memoperands_begin();
00549   MachineMemOperand *MMOb = *MIb->memoperands_begin();
00550 
00551   if (!MMOa->getValue() || !MMOb->getValue())
00552     return true;
00553 
00554   // The following interface to AA is fashioned after DAGCombiner::isAlias
00555   // and operates with MachineMemOperand offset with some important
00556   // assumptions:
00557   //   - LLVM fundamentally assumes flat address spaces.
00558   //   - MachineOperand offset can *only* result from legalization and
00559   //     cannot affect queries other than the trivial case of overlap
00560   //     checking.
00561   //   - These offsets never wrap and never step outside
00562   //     of allocated objects.
00563   //   - There should never be any negative offsets here.
00564   //
00565   // FIXME: Modify API to hide this math from "user"
00566   // FIXME: Even before we go to AA we can reason locally about some
00567   // memory objects. It can save compile time, and possibly catch some
00568   // corner cases not currently covered.
00569 
00570   assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
00571   assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
00572 
00573   int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
00574   int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
00575   int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
00576 
00577   AliasResult AAResult =
00578       AA->alias(MemoryLocation(MMOa->getValue(), Overlapa,
00579                                UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
00580                 MemoryLocation(MMOb->getValue(), Overlapb,
00581                                UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
00582 
00583   return (AAResult != NoAlias);
00584 }
00585 
00586 /// This recursive function iterates over chain deps of SUb looking for
00587 /// "latest" node that needs a chain edge to SUa.
00588 static unsigned iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI,
00589                                  const DataLayout &DL, SUnit *SUa, SUnit *SUb,
00590                                  SUnit *ExitSU, unsigned *Depth,
00591                                  SmallPtrSetImpl<const SUnit *> &Visited) {
00592   if (!SUa || !SUb || SUb == ExitSU)
00593     return *Depth;
00594 
00595   // Remember visited nodes.
00596   if (!Visited.insert(SUb).second)
00597       return *Depth;
00598   // If there is _some_ dependency already in place, do not
00599   // descend any further.
00600   // TODO: Need to make sure that if that dependency got eliminated or ignored
00601   // for any reason in the future, we would not violate DAG topology.
00602   // Currently it does not happen, but makes an implicit assumption about
00603   // future implementation.
00604   //
00605   // Independently, if we encounter node that is some sort of global
00606   // object (like a call) we already have full set of dependencies to it
00607   // and we can stop descending.
00608   if (SUa->isSucc(SUb) ||
00609       isGlobalMemoryObject(AA, SUb->getInstr()))
00610     return *Depth;
00611 
00612   // If we do need an edge, or we have exceeded depth budget,
00613   // add that edge to the predecessors chain of SUb,
00614   // and stop descending.
00615   if (*Depth > 200 ||
00616       MIsNeedChainEdge(AA, MFI, DL, SUa->getInstr(), SUb->getInstr())) {
00617     SUb->addPred(SDep(SUa, SDep::MayAliasMem));
00618     return *Depth;
00619   }
00620   // Track current depth.
00621   (*Depth)++;
00622   // Iterate over memory dependencies only.
00623   for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end();
00624        I != E; ++I)
00625     if (I->isNormalMemoryOrBarrier())
00626       iterateChainSucc(AA, MFI, DL, SUa, I->getSUnit(), ExitSU, Depth, Visited);
00627   return *Depth;
00628 }
00629 
00630 /// This function assumes that "downward" from SU there exist
00631 /// tail/leaf of already constructed DAG. It iterates downward and
00632 /// checks whether SU can be aliasing any node dominated
00633 /// by it.
00634 static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI,
00635                             const DataLayout &DL, SUnit *SU, SUnit *ExitSU,
00636                             std::set<SUnit *> &CheckList,
00637                             unsigned LatencyToLoad) {
00638   if (!SU)
00639     return;
00640 
00641   SmallPtrSet<const SUnit*, 16> Visited;
00642   unsigned Depth = 0;
00643 
00644   for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end();
00645        I != IE; ++I) {
00646     if (SU == *I)
00647       continue;
00648     if (MIsNeedChainEdge(AA, MFI, DL, SU->getInstr(), (*I)->getInstr())) {
00649       SDep Dep(SU, SDep::MayAliasMem);
00650       Dep.setLatency(((*I)->getInstr()->mayLoad()) ? LatencyToLoad : 0);
00651       (*I)->addPred(Dep);
00652     }
00653 
00654     // Iterate recursively over all previously added memory chain
00655     // successors. Keep track of visited nodes.
00656     for (SUnit::const_succ_iterator J = (*I)->Succs.begin(),
00657          JE = (*I)->Succs.end(); J != JE; ++J)
00658       if (J->isNormalMemoryOrBarrier())
00659         iterateChainSucc(AA, MFI, DL, SU, J->getSUnit(), ExitSU, &Depth,
00660                          Visited);
00661   }
00662 }
00663 
00664 /// Check whether two objects need a chain edge, if so, add it
00665 /// otherwise remember the rejected SU.
00666 static inline void addChainDependency(AliasAnalysis *AA,
00667                                       const MachineFrameInfo *MFI,
00668                                       const DataLayout &DL, SUnit *SUa,
00669                                       SUnit *SUb, std::set<SUnit *> &RejectList,
00670                                       unsigned TrueMemOrderLatency = 0,
00671                                       bool isNormalMemory = false) {
00672   // If this is a false dependency,
00673   // do not add the edge, but rememeber the rejected node.
00674   if (MIsNeedChainEdge(AA, MFI, DL, SUa->getInstr(), SUb->getInstr())) {
00675     SDep Dep(SUa, isNormalMemory ? SDep::MayAliasMem : SDep::Barrier);
00676     Dep.setLatency(TrueMemOrderLatency);
00677     SUb->addPred(Dep);
00678   }
00679   else {
00680     // Duplicate entries should be ignored.
00681     RejectList.insert(SUb);
00682     DEBUG(dbgs() << "\tReject chain dep between SU("
00683           << SUa->NodeNum << ") and SU("
00684           << SUb->NodeNum << ")\n");
00685   }
00686 }
00687 
00688 /// Create an SUnit for each real instruction, numbered in top-down toplological
00689 /// order. The instruction order A < B, implies that no edge exists from B to A.
00690 ///
00691 /// Map each real instruction to its SUnit.
00692 ///
00693 /// After initSUnits, the SUnits vector cannot be resized and the scheduler may
00694 /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
00695 /// instead of pointers.
00696 ///
00697 /// MachineScheduler relies on initSUnits numbering the nodes by their order in
00698 /// the original instruction list.
00699 void ScheduleDAGInstrs::initSUnits() {
00700   // We'll be allocating one SUnit for each real instruction in the region,
00701   // which is contained within a basic block.
00702   SUnits.reserve(NumRegionInstrs);
00703 
00704   for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
00705     MachineInstr *MI = I;
00706     if (MI->isDebugValue())
00707       continue;
00708 
00709     SUnit *SU = newSUnit(MI);
00710     MISUnitMap[MI] = SU;
00711 
00712     SU->isCall = MI->isCall();
00713     SU->isCommutable = MI->isCommutable();
00714 
00715     // Assign the Latency field of SU using target-provided information.
00716     SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
00717 
00718     // If this SUnit uses a reserved or unbuffered resource, mark it as such.
00719     //
00720     // Reserved resources block an instruction from issuing and stall the
00721     // entire pipeline. These are identified by BufferSize=0.
00722     //
00723     // Unbuffered resources prevent execution of subsequent instructions that
00724     // require the same resources. This is used for in-order execution pipelines
00725     // within an out-of-order core. These are identified by BufferSize=1.
00726     if (SchedModel.hasInstrSchedModel()) {
00727       const MCSchedClassDesc *SC = getSchedClass(SU);
00728       for (TargetSchedModel::ProcResIter
00729              PI = SchedModel.getWriteProcResBegin(SC),
00730              PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
00731         switch (SchedModel.getProcResource(PI->ProcResourceIdx)->BufferSize) {
00732         case 0:
00733           SU->hasReservedResource = true;
00734           break;
00735         case 1:
00736           SU->isUnbuffered = true;
00737           break;
00738         default:
00739           break;
00740         }
00741       }
00742     }
00743   }
00744 }
00745 
00746 /// If RegPressure is non-null, compute register pressure as a side effect. The
00747 /// DAG builder is an efficient place to do it because it already visits
00748 /// operands.
00749 void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
00750                                         RegPressureTracker *RPTracker,
00751                                         PressureDiffs *PDiffs) {
00752   const TargetSubtargetInfo &ST = MF.getSubtarget();
00753   bool UseAA = EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI
00754                                                        : ST.useAA();
00755   AliasAnalysis *AAForDep = UseAA ? AA : nullptr;
00756 
00757   MISUnitMap.clear();
00758   ScheduleDAG::clearDAG();
00759 
00760   // Create an SUnit for each real instruction.
00761   initSUnits();
00762 
00763   if (PDiffs)
00764     PDiffs->init(SUnits.size());
00765 
00766   // We build scheduling units by walking a block's instruction list from bottom
00767   // to top.
00768 
00769   // Remember where a generic side-effecting instruction is as we procede.
00770   SUnit *BarrierChain = nullptr, *AliasChain = nullptr;
00771 
00772   // Memory references to specific known memory locations are tracked
00773   // so that they can be given more precise dependencies. We track
00774   // separately the known memory locations that may alias and those
00775   // that are known not to alias
00776   MapVector<ValueType, std::vector<SUnit *> > AliasMemDefs, NonAliasMemDefs;
00777   MapVector<ValueType, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
00778   std::set<SUnit*> RejectMemNodes;
00779 
00780   // Remove any stale debug info; sometimes BuildSchedGraph is called again
00781   // without emitting the info from the previous call.
00782   DbgValues.clear();
00783   FirstDbgValue = nullptr;
00784 
00785   assert(Defs.empty() && Uses.empty() &&
00786          "Only BuildGraph should update Defs/Uses");
00787   Defs.setUniverse(TRI->getNumRegs());
00788   Uses.setUniverse(TRI->getNumRegs());
00789 
00790   assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
00791   VRegUses.clear();
00792   VRegDefs.setUniverse(MRI.getNumVirtRegs());
00793   VRegUses.setUniverse(MRI.getNumVirtRegs());
00794 
00795   // Model data dependencies between instructions being scheduled and the
00796   // ExitSU.
00797   addSchedBarrierDeps();
00798 
00799   // Walk the list of instructions, from bottom moving up.
00800   MachineInstr *DbgMI = nullptr;
00801   for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
00802        MII != MIE; --MII) {
00803     MachineInstr *MI = std::prev(MII);
00804     if (MI && DbgMI) {
00805       DbgValues.push_back(std::make_pair(DbgMI, MI));
00806       DbgMI = nullptr;
00807     }
00808 
00809     if (MI->isDebugValue()) {
00810       DbgMI = MI;
00811       continue;
00812     }
00813     SUnit *SU = MISUnitMap[MI];
00814     assert(SU && "No SUnit mapped to this MI");
00815 
00816     if (RPTracker) {
00817       PressureDiff *PDiff = PDiffs ? &(*PDiffs)[SU->NodeNum] : nullptr;
00818       RPTracker->recede(/*LiveUses=*/nullptr, PDiff);
00819       assert(RPTracker->getPos() == std::prev(MII) &&
00820              "RPTracker can't find MI");
00821     }
00822 
00823     assert(
00824         (CanHandleTerminators || (!MI->isTerminator() && !MI->isPosition())) &&
00825         "Cannot schedule terminators or labels!");
00826 
00827     // Add register-based dependencies (data, anti, and output).
00828     bool HasVRegDef = false;
00829     for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
00830       const MachineOperand &MO = MI->getOperand(j);
00831       if (!MO.isReg()) continue;
00832       unsigned Reg = MO.getReg();
00833       if (Reg == 0) continue;
00834 
00835       if (TRI->isPhysicalRegister(Reg))
00836         addPhysRegDeps(SU, j);
00837       else {
00838         assert(!IsPostRA && "Virtual register encountered!");
00839         if (MO.isDef()) {
00840           HasVRegDef = true;
00841           addVRegDefDeps(SU, j);
00842         }
00843         else if (MO.readsReg()) // ignore undef operands
00844           addVRegUseDeps(SU, j);
00845       }
00846     }
00847     // If we haven't seen any uses in this scheduling region, create a
00848     // dependence edge to ExitSU to model the live-out latency. This is required
00849     // for vreg defs with no in-region use, and prefetches with no vreg def.
00850     //
00851     // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
00852     // check currently relies on being called before adding chain deps.
00853     if (SU->NumSuccs == 0 && SU->Latency > 1
00854         && (HasVRegDef || MI->mayLoad())) {
00855       SDep Dep(SU, SDep::Artificial);
00856       Dep.setLatency(SU->Latency - 1);
00857       ExitSU.addPred(Dep);
00858     }
00859 
00860     // Add chain dependencies.
00861     // Chain dependencies used to enforce memory order should have
00862     // latency of 0 (except for true dependency of Store followed by
00863     // aliased Load... we estimate that with a single cycle of latency
00864     // assuming the hardware will bypass)
00865     // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
00866     // after stack slots are lowered to actual addresses.
00867     // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
00868     // produce more precise dependence information.
00869     unsigned TrueMemOrderLatency = MI->mayStore() ? 1 : 0;
00870     if (isGlobalMemoryObject(AA, MI)) {
00871       // Be conservative with these and add dependencies on all memory
00872       // references, even those that are known to not alias.
00873       for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
00874              NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
00875         for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
00876           I->second[i]->addPred(SDep(SU, SDep::Barrier));
00877         }
00878       }
00879       for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
00880              NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
00881         for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
00882           SDep Dep(SU, SDep::Barrier);
00883           Dep.setLatency(TrueMemOrderLatency);
00884           I->second[i]->addPred(Dep);
00885         }
00886       }
00887       // Add SU to the barrier chain.
00888       if (BarrierChain)
00889         BarrierChain->addPred(SDep(SU, SDep::Barrier));
00890       BarrierChain = SU;
00891       // This is a barrier event that acts as a pivotal node in the DAG,
00892       // so it is safe to clear list of exposed nodes.
00893       adjustChainDeps(AA, MFI, *TM.getDataLayout(), SU, &ExitSU, RejectMemNodes,
00894                       TrueMemOrderLatency);
00895       RejectMemNodes.clear();
00896       NonAliasMemDefs.clear();
00897       NonAliasMemUses.clear();
00898 
00899       // fall-through
00900     new_alias_chain:
00901       // Chain all possibly aliasing memory references through SU.
00902       if (AliasChain) {
00903         unsigned ChainLatency = 0;
00904         if (AliasChain->getInstr()->mayLoad())
00905           ChainLatency = TrueMemOrderLatency;
00906         addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU, AliasChain,
00907                            RejectMemNodes, ChainLatency);
00908       }
00909       AliasChain = SU;
00910       for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
00911         addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU,
00912                            PendingLoads[k], RejectMemNodes,
00913                            TrueMemOrderLatency);
00914       for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
00915            AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I) {
00916         for (unsigned i = 0, e = I->second.size(); i != e; ++i)
00917           addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU,
00918                              I->second[i], RejectMemNodes);
00919       }
00920       for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
00921            AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
00922         for (unsigned i = 0, e = I->second.size(); i != e; ++i)
00923           addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU,
00924                              I->second[i], RejectMemNodes, TrueMemOrderLatency);
00925       }
00926       adjustChainDeps(AA, MFI, *TM.getDataLayout(), SU, &ExitSU, RejectMemNodes,
00927                       TrueMemOrderLatency);
00928       PendingLoads.clear();
00929       AliasMemDefs.clear();
00930       AliasMemUses.clear();
00931     } else if (MI->mayStore()) {
00932       // Add dependence on barrier chain, if needed.
00933       // There is no point to check aliasing on barrier event. Even if
00934       // SU and barrier _could_ be reordered, they should not. In addition,
00935       // we have lost all RejectMemNodes below barrier.
00936       if (BarrierChain)
00937         BarrierChain->addPred(SDep(SU, SDep::Barrier));
00938 
00939       UnderlyingObjectsVector Objs;
00940       getUnderlyingObjectsForInstr(MI, MFI, Objs, *TM.getDataLayout());
00941 
00942       if (Objs.empty()) {
00943         // Treat all other stores conservatively.
00944         goto new_alias_chain;
00945       }
00946 
00947       bool MayAlias = false;
00948       for (UnderlyingObjectsVector::iterator K = Objs.begin(), KE = Objs.end();
00949            K != KE; ++K) {
00950         ValueType V = K->getPointer();
00951         bool ThisMayAlias = K->getInt();
00952         if (ThisMayAlias)
00953           MayAlias = true;
00954 
00955         // A store to a specific PseudoSourceValue. Add precise dependencies.
00956         // Record the def in MemDefs, first adding a dep if there is
00957         // an existing def.
00958         MapVector<ValueType, std::vector<SUnit *> >::iterator I =
00959           ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
00960         MapVector<ValueType, std::vector<SUnit *> >::iterator IE =
00961           ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
00962         if (I != IE) {
00963           for (unsigned i = 0, e = I->second.size(); i != e; ++i)
00964             addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU,
00965                                I->second[i], RejectMemNodes, 0, true);
00966 
00967           // If we're not using AA, then we only need one store per object.
00968           if (!AAForDep)
00969             I->second.clear();
00970           I->second.push_back(SU);
00971         } else {
00972           if (ThisMayAlias) {
00973             if (!AAForDep)
00974               AliasMemDefs[V].clear();
00975             AliasMemDefs[V].push_back(SU);
00976           } else {
00977             if (!AAForDep)
00978               NonAliasMemDefs[V].clear();
00979             NonAliasMemDefs[V].push_back(SU);
00980           }
00981         }
00982         // Handle the uses in MemUses, if there are any.
00983         MapVector<ValueType, std::vector<SUnit *> >::iterator J =
00984           ((ThisMayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
00985         MapVector<ValueType, std::vector<SUnit *> >::iterator JE =
00986           ((ThisMayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
00987         if (J != JE) {
00988           for (unsigned i = 0, e = J->second.size(); i != e; ++i)
00989             addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU,
00990                                J->second[i], RejectMemNodes,
00991                                TrueMemOrderLatency, true);
00992           J->second.clear();
00993         }
00994       }
00995       if (MayAlias) {
00996         // Add dependencies from all the PendingLoads, i.e. loads
00997         // with no underlying object.
00998         for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
00999           addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU,
01000                              PendingLoads[k], RejectMemNodes,
01001                              TrueMemOrderLatency);
01002         // Add dependence on alias chain, if needed.
01003         if (AliasChain)
01004           addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU, AliasChain,
01005                              RejectMemNodes);
01006       }
01007       adjustChainDeps(AA, MFI, *TM.getDataLayout(), SU, &ExitSU, RejectMemNodes,
01008                       TrueMemOrderLatency);
01009     } else if (MI->mayLoad()) {
01010       bool MayAlias = true;
01011       if (MI->isInvariantLoad(AA)) {
01012         // Invariant load, no chain dependencies needed!
01013       } else {
01014         UnderlyingObjectsVector Objs;
01015         getUnderlyingObjectsForInstr(MI, MFI, Objs, *TM.getDataLayout());
01016 
01017         if (Objs.empty()) {
01018           // A load with no underlying object. Depend on all
01019           // potentially aliasing stores.
01020           for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
01021                  AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
01022             for (unsigned i = 0, e = I->second.size(); i != e; ++i)
01023               addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU,
01024                                  I->second[i], RejectMemNodes);
01025 
01026           PendingLoads.push_back(SU);
01027           MayAlias = true;
01028         } else {
01029           MayAlias = false;
01030         }
01031 
01032         for (UnderlyingObjectsVector::iterator
01033              J = Objs.begin(), JE = Objs.end(); J != JE; ++J) {
01034           ValueType V = J->getPointer();
01035           bool ThisMayAlias = J->getInt();
01036 
01037           if (ThisMayAlias)
01038             MayAlias = true;
01039 
01040           // A load from a specific PseudoSourceValue. Add precise dependencies.
01041           MapVector<ValueType, std::vector<SUnit *> >::iterator I =
01042             ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
01043           MapVector<ValueType, std::vector<SUnit *> >::iterator IE =
01044             ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
01045           if (I != IE)
01046             for (unsigned i = 0, e = I->second.size(); i != e; ++i)
01047               addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU,
01048                                  I->second[i], RejectMemNodes, 0, true);
01049           if (ThisMayAlias)
01050             AliasMemUses[V].push_back(SU);
01051           else
01052             NonAliasMemUses[V].push_back(SU);
01053         }
01054         if (MayAlias)
01055           adjustChainDeps(AA, MFI, *TM.getDataLayout(), SU, &ExitSU,
01056                           RejectMemNodes, /*Latency=*/0);
01057         // Add dependencies on alias and barrier chains, if needed.
01058         if (MayAlias && AliasChain)
01059           addChainDependency(AAForDep, MFI, *TM.getDataLayout(), SU, AliasChain,
01060                              RejectMemNodes);
01061         if (BarrierChain)
01062           BarrierChain->addPred(SDep(SU, SDep::Barrier));
01063       }
01064     }
01065   }
01066   if (DbgMI)
01067     FirstDbgValue = DbgMI;
01068 
01069   Defs.clear();
01070   Uses.clear();
01071   VRegDefs.clear();
01072   PendingLoads.clear();
01073 }
01074 
01075 /// \brief Initialize register live-range state for updating kills.
01076 void ScheduleDAGInstrs::startBlockForKills(MachineBasicBlock *BB) {
01077   // Start with no live registers.
01078   LiveRegs.reset();
01079 
01080   // Examine the live-in regs of all successors.
01081   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
01082        SE = BB->succ_end(); SI != SE; ++SI) {
01083     for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
01084          E = (*SI)->livein_end(); I != E; ++I) {
01085       unsigned Reg = *I;
01086       // Repeat, for reg and all subregs.
01087       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
01088            SubRegs.isValid(); ++SubRegs)
01089         LiveRegs.set(*SubRegs);
01090     }
01091   }
01092 }
01093 
01094 /// \brief If we change a kill flag on the bundle instruction implicit register
01095 /// operands, then we also need to propagate that to any instructions inside
01096 /// the bundle which had the same kill state.
01097 static void toggleBundleKillFlag(MachineInstr *MI, unsigned Reg,
01098                                  bool NewKillState) {
01099   if (MI->getOpcode() != TargetOpcode::BUNDLE)
01100     return;
01101 
01102   // Walk backwards from the last instruction in the bundle to the first.
01103   // Once we set a kill flag on an instruction, we bail out, as otherwise we
01104   // might set it on too many operands.  We will clear as many flags as we
01105   // can though.
01106   MachineBasicBlock::instr_iterator Begin = MI;
01107   MachineBasicBlock::instr_iterator End = getBundleEnd(MI);
01108   while (Begin != End) {
01109     for (MachineOperand &MO : (--End)->operands()) {
01110       if (!MO.isReg() || MO.isDef() || Reg != MO.getReg())
01111         continue;
01112 
01113       // DEBUG_VALUE nodes do not contribute to code generation and should
01114       // always be ignored.  Failure to do so may result in trying to modify
01115       // KILL flags on DEBUG_VALUE nodes, which is distressing.
01116       if (MO.isDebug())
01117         continue;
01118 
01119       // If the register has the internal flag then it could be killing an
01120       // internal def of the register.  In this case, just skip.  We only want
01121       // to toggle the flag on operands visible outside the bundle.
01122       if (MO.isInternalRead())
01123         continue;
01124 
01125       if (MO.isKill() == NewKillState)
01126         continue;
01127       MO.setIsKill(NewKillState);
01128       if (NewKillState)
01129         return;
01130     }
01131   }
01132 }
01133 
01134 bool ScheduleDAGInstrs::toggleKillFlag(MachineInstr *MI, MachineOperand &MO) {
01135   // Setting kill flag...
01136   if (!MO.isKill()) {
01137     MO.setIsKill(true);
01138     toggleBundleKillFlag(MI, MO.getReg(), true);
01139     return false;
01140   }
01141 
01142   // If MO itself is live, clear the kill flag...
01143   if (LiveRegs.test(MO.getReg())) {
01144     MO.setIsKill(false);
01145     toggleBundleKillFlag(MI, MO.getReg(), false);
01146     return false;
01147   }
01148 
01149   // If any subreg of MO is live, then create an imp-def for that
01150   // subreg and keep MO marked as killed.
01151   MO.setIsKill(false);
01152   toggleBundleKillFlag(MI, MO.getReg(), false);
01153   bool AllDead = true;
01154   const unsigned SuperReg = MO.getReg();
01155   MachineInstrBuilder MIB(MF, MI);
01156   for (MCSubRegIterator SubRegs(SuperReg, TRI); SubRegs.isValid(); ++SubRegs) {
01157     if (LiveRegs.test(*SubRegs)) {
01158       MIB.addReg(*SubRegs, RegState::ImplicitDefine);
01159       AllDead = false;
01160     }
01161   }
01162 
01163   if(AllDead) {
01164     MO.setIsKill(true);
01165     toggleBundleKillFlag(MI, MO.getReg(), true);
01166   }
01167   return false;
01168 }
01169 
01170 // FIXME: Reuse the LivePhysRegs utility for this.
01171 void ScheduleDAGInstrs::fixupKills(MachineBasicBlock *MBB) {
01172   DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
01173 
01174   LiveRegs.resize(TRI->getNumRegs());
01175   BitVector killedRegs(TRI->getNumRegs());
01176 
01177   startBlockForKills(MBB);
01178 
01179   // Examine block from end to start...
01180   unsigned Count = MBB->size();
01181   for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
01182        I != E; --Count) {
01183     MachineInstr *MI = --I;
01184     if (MI->isDebugValue())
01185       continue;
01186 
01187     // Update liveness.  Registers that are defed but not used in this
01188     // instruction are now dead. Mark register and all subregs as they
01189     // are completely defined.
01190     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01191       MachineOperand &MO = MI->getOperand(i);
01192       if (MO.isRegMask())
01193         LiveRegs.clearBitsNotInMask(MO.getRegMask());
01194       if (!MO.isReg()) continue;
01195       unsigned Reg = MO.getReg();
01196       if (Reg == 0) continue;
01197       if (!MO.isDef()) continue;
01198       // Ignore two-addr defs.
01199       if (MI->isRegTiedToUseOperand(i)) continue;
01200 
01201       // Repeat for reg and all subregs.
01202       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
01203            SubRegs.isValid(); ++SubRegs)
01204         LiveRegs.reset(*SubRegs);
01205     }
01206 
01207     // Examine all used registers and set/clear kill flag. When a
01208     // register is used multiple times we only set the kill flag on
01209     // the first use. Don't set kill flags on undef operands.
01210     killedRegs.reset();
01211     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01212       MachineOperand &MO = MI->getOperand(i);
01213       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
01214       unsigned Reg = MO.getReg();
01215       if ((Reg == 0) || MRI.isReserved(Reg)) continue;
01216 
01217       bool kill = false;
01218       if (!killedRegs.test(Reg)) {
01219         kill = true;
01220         // A register is not killed if any subregs are live...
01221         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
01222           if (LiveRegs.test(*SubRegs)) {
01223             kill = false;
01224             break;
01225           }
01226         }
01227 
01228         // If subreg is not live, then register is killed if it became
01229         // live in this instruction
01230         if (kill)
01231           kill = !LiveRegs.test(Reg);
01232       }
01233 
01234       if (MO.isKill() != kill) {
01235         DEBUG(dbgs() << "Fixing " << MO << " in ");
01236         // Warning: toggleKillFlag may invalidate MO.
01237         toggleKillFlag(MI, MO);
01238         DEBUG(MI->dump());
01239         DEBUG(if (MI->getOpcode() == TargetOpcode::BUNDLE) {
01240           MachineBasicBlock::instr_iterator Begin = MI;
01241           MachineBasicBlock::instr_iterator End = getBundleEnd(MI);
01242           while (++Begin != End)
01243             DEBUG(Begin->dump());
01244         });
01245       }
01246 
01247       killedRegs.set(Reg);
01248     }
01249 
01250     // Mark any used register (that is not using undef) and subregs as
01251     // now live...
01252     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01253       MachineOperand &MO = MI->getOperand(i);
01254       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
01255       unsigned Reg = MO.getReg();
01256       if ((Reg == 0) || MRI.isReserved(Reg)) continue;
01257 
01258       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
01259            SubRegs.isValid(); ++SubRegs)
01260         LiveRegs.set(*SubRegs);
01261     }
01262   }
01263 }
01264 
01265 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
01266 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01267   SU->getInstr()->dump();
01268 #endif
01269 }
01270 
01271 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
01272   std::string s;
01273   raw_string_ostream oss(s);
01274   if (SU == &EntrySU)
01275     oss << "<entry>";
01276   else if (SU == &ExitSU)
01277     oss << "<exit>";
01278   else
01279     SU->getInstr()->print(oss, /*SkipOpers=*/true);
01280   return oss.str();
01281 }
01282 
01283 /// Return the basic block label. It is not necessarilly unique because a block
01284 /// contains multiple scheduling regions. But it is fine for visualization.
01285 std::string ScheduleDAGInstrs::getDAGName() const {
01286   return "dag." + BB->getFullName();
01287 }
01288 
01289 //===----------------------------------------------------------------------===//
01290 // SchedDFSResult Implementation
01291 //===----------------------------------------------------------------------===//
01292 
01293 namespace llvm {
01294 /// \brief Internal state used to compute SchedDFSResult.
01295 class SchedDFSImpl {
01296   SchedDFSResult &R;
01297 
01298   /// Join DAG nodes into equivalence classes by their subtree.
01299   IntEqClasses SubtreeClasses;
01300   /// List PredSU, SuccSU pairs that represent data edges between subtrees.
01301   std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs;
01302 
01303   struct RootData {
01304     unsigned NodeID;
01305     unsigned ParentNodeID;  // Parent node (member of the parent subtree).
01306     unsigned SubInstrCount; // Instr count in this tree only, not children.
01307 
01308     RootData(unsigned id): NodeID(id),
01309                            ParentNodeID(SchedDFSResult::InvalidSubtreeID),
01310                            SubInstrCount(0) {}
01311 
01312     unsigned getSparseSetIndex() const { return NodeID; }
01313   };
01314 
01315   SparseSet<RootData> RootSet;
01316 
01317 public:
01318   SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
01319     RootSet.setUniverse(R.DFSNodeData.size());
01320   }
01321 
01322   /// Return true if this node been visited by the DFS traversal.
01323   ///
01324   /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
01325   /// ID. Later, SubtreeID is updated but remains valid.
01326   bool isVisited(const SUnit *SU) const {
01327     return R.DFSNodeData[SU->NodeNum].SubtreeID
01328       != SchedDFSResult::InvalidSubtreeID;
01329   }
01330 
01331   /// Initialize this node's instruction count. We don't need to flag the node
01332   /// visited until visitPostorder because the DAG cannot have cycles.
01333   void visitPreorder(const SUnit *SU) {
01334     R.DFSNodeData[SU->NodeNum].InstrCount =
01335       SU->getInstr()->isTransient() ? 0 : 1;
01336   }
01337 
01338   /// Called once for each node after all predecessors are visited. Revisit this
01339   /// node's predecessors and potentially join them now that we know the ILP of
01340   /// the other predecessors.
01341   void visitPostorderNode(const SUnit *SU) {
01342     // Mark this node as the root of a subtree. It may be joined with its
01343     // successors later.
01344     R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
01345     RootData RData(SU->NodeNum);
01346     RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
01347 
01348     // If any predecessors are still in their own subtree, they either cannot be
01349     // joined or are large enough to remain separate. If this parent node's
01350     // total instruction count is not greater than a child subtree by at least
01351     // the subtree limit, then try to join it now since splitting subtrees is
01352     // only useful if multiple high-pressure paths are possible.
01353     unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
01354     for (SUnit::const_pred_iterator
01355            PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
01356       if (PI->getKind() != SDep::Data)
01357         continue;
01358       unsigned PredNum = PI->getSUnit()->NodeNum;
01359       if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
01360         joinPredSubtree(*PI, SU, /*CheckLimit=*/false);
01361 
01362       // Either link or merge the TreeData entry from the child to the parent.
01363       if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
01364         // If the predecessor's parent is invalid, this is a tree edge and the
01365         // current node is the parent.
01366         if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
01367           RootSet[PredNum].ParentNodeID = SU->NodeNum;
01368       }
01369       else if (RootSet.count(PredNum)) {
01370         // The predecessor is not a root, but is still in the root set. This
01371         // must be the new parent that it was just joined to. Note that
01372         // RootSet[PredNum].ParentNodeID may either be invalid or may still be
01373         // set to the original parent.
01374         RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
01375         RootSet.erase(PredNum);
01376       }
01377     }
01378     RootSet[SU->NodeNum] = RData;
01379   }
01380 
01381   /// Called once for each tree edge after calling visitPostOrderNode on the
01382   /// predecessor. Increment the parent node's instruction count and
01383   /// preemptively join this subtree to its parent's if it is small enough.
01384   void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
01385     R.DFSNodeData[Succ->NodeNum].InstrCount
01386       += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
01387     joinPredSubtree(PredDep, Succ);
01388   }
01389 
01390   /// Add a connection for cross edges.
01391   void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
01392     ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
01393   }
01394 
01395   /// Set each node's subtree ID to the representative ID and record connections
01396   /// between trees.
01397   void finalize() {
01398     SubtreeClasses.compress();
01399     R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
01400     assert(SubtreeClasses.getNumClasses() == RootSet.size()
01401            && "number of roots should match trees");
01402     for (SparseSet<RootData>::const_iterator
01403            RI = RootSet.begin(), RE = RootSet.end(); RI != RE; ++RI) {
01404       unsigned TreeID = SubtreeClasses[RI->NodeID];
01405       if (RI->ParentNodeID != SchedDFSResult::InvalidSubtreeID)
01406         R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[RI->ParentNodeID];
01407       R.DFSTreeData[TreeID].SubInstrCount = RI->SubInstrCount;
01408       // Note that SubInstrCount may be greater than InstrCount if we joined
01409       // subtrees across a cross edge. InstrCount will be attributed to the
01410       // original parent, while SubInstrCount will be attributed to the joined
01411       // parent.
01412     }
01413     R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
01414     R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
01415     DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
01416     for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
01417       R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
01418       DEBUG(dbgs() << "  SU(" << Idx << ") in tree "
01419             << R.DFSNodeData[Idx].SubtreeID << '\n');
01420     }
01421     for (std::vector<std::pair<const SUnit*, const SUnit*> >::const_iterator
01422            I = ConnectionPairs.begin(), E = ConnectionPairs.end();
01423          I != E; ++I) {
01424       unsigned PredTree = SubtreeClasses[I->first->NodeNum];
01425       unsigned SuccTree = SubtreeClasses[I->second->NodeNum];
01426       if (PredTree == SuccTree)
01427         continue;
01428       unsigned Depth = I->first->getDepth();
01429       addConnection(PredTree, SuccTree, Depth);
01430       addConnection(SuccTree, PredTree, Depth);
01431     }
01432   }
01433 
01434 protected:
01435   /// Join the predecessor subtree with the successor that is its DFS
01436   /// parent. Apply some heuristics before joining.
01437   bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
01438                        bool CheckLimit = true) {
01439     assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
01440 
01441     // Check if the predecessor is already joined.
01442     const SUnit *PredSU = PredDep.getSUnit();
01443     unsigned PredNum = PredSU->NodeNum;
01444     if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
01445       return false;
01446 
01447     // Four is the magic number of successors before a node is considered a
01448     // pinch point.
01449     unsigned NumDataSucs = 0;
01450     for (SUnit::const_succ_iterator SI = PredSU->Succs.begin(),
01451            SE = PredSU->Succs.end(); SI != SE; ++SI) {
01452       if (SI->getKind() == SDep::Data) {
01453         if (++NumDataSucs >= 4)
01454           return false;
01455       }
01456     }
01457     if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
01458       return false;
01459     R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
01460     SubtreeClasses.join(Succ->NodeNum, PredNum);
01461     return true;
01462   }
01463 
01464   /// Called by finalize() to record a connection between trees.
01465   void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
01466     if (!Depth)
01467       return;
01468 
01469     do {
01470       SmallVectorImpl<SchedDFSResult::Connection> &Connections =
01471         R.SubtreeConnections[FromTree];
01472       for (SmallVectorImpl<SchedDFSResult::Connection>::iterator
01473              I = Connections.begin(), E = Connections.end(); I != E; ++I) {
01474         if (I->TreeID == ToTree) {
01475           I->Level = std::max(I->Level, Depth);
01476           return;
01477         }
01478       }
01479       Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
01480       FromTree = R.DFSTreeData[FromTree].ParentTreeID;
01481     } while (FromTree != SchedDFSResult::InvalidSubtreeID);
01482   }
01483 };
01484 } // namespace llvm
01485 
01486 namespace {
01487 /// \brief Manage the stack used by a reverse depth-first search over the DAG.
01488 class SchedDAGReverseDFS {
01489   std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
01490 public:
01491   bool isComplete() const { return DFSStack.empty(); }
01492 
01493   void follow(const SUnit *SU) {
01494     DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
01495   }
01496   void advance() { ++DFSStack.back().second; }
01497 
01498   const SDep *backtrack() {
01499     DFSStack.pop_back();
01500     return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
01501   }
01502 
01503   const SUnit *getCurr() const { return DFSStack.back().first; }
01504 
01505   SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
01506 
01507   SUnit::const_pred_iterator getPredEnd() const {
01508     return getCurr()->Preds.end();
01509   }
01510 };
01511 } // anonymous
01512 
01513 static bool hasDataSucc(const SUnit *SU) {
01514   for (SUnit::const_succ_iterator
01515          SI = SU->Succs.begin(), SE = SU->Succs.end(); SI != SE; ++SI) {
01516     if (SI->getKind() == SDep::Data && !SI->getSUnit()->isBoundaryNode())
01517       return true;
01518   }
01519   return false;
01520 }
01521 
01522 /// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
01523 /// search from this root.
01524 void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
01525   if (!IsBottomUp)
01526     llvm_unreachable("Top-down ILP metric is unimplemnted");
01527 
01528   SchedDFSImpl Impl(*this);
01529   for (ArrayRef<SUnit>::const_iterator
01530          SI = SUnits.begin(), SE = SUnits.end(); SI != SE; ++SI) {
01531     const SUnit *SU = &*SI;
01532     if (Impl.isVisited(SU) || hasDataSucc(SU))
01533       continue;
01534 
01535     SchedDAGReverseDFS DFS;
01536     Impl.visitPreorder(SU);
01537     DFS.follow(SU);
01538     for (;;) {
01539       // Traverse the leftmost path as far as possible.
01540       while (DFS.getPred() != DFS.getPredEnd()) {
01541         const SDep &PredDep = *DFS.getPred();
01542         DFS.advance();
01543         // Ignore non-data edges.
01544         if (PredDep.getKind() != SDep::Data
01545             || PredDep.getSUnit()->isBoundaryNode()) {
01546           continue;
01547         }
01548         // An already visited edge is a cross edge, assuming an acyclic DAG.
01549         if (Impl.isVisited(PredDep.getSUnit())) {
01550           Impl.visitCrossEdge(PredDep, DFS.getCurr());
01551           continue;
01552         }
01553         Impl.visitPreorder(PredDep.getSUnit());
01554         DFS.follow(PredDep.getSUnit());
01555       }
01556       // Visit the top of the stack in postorder and backtrack.
01557       const SUnit *Child = DFS.getCurr();
01558       const SDep *PredDep = DFS.backtrack();
01559       Impl.visitPostorderNode(Child);
01560       if (PredDep)
01561         Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
01562       if (DFS.isComplete())
01563         break;
01564     }
01565   }
01566   Impl.finalize();
01567 }
01568 
01569 /// The root of the given SubtreeID was just scheduled. For all subtrees
01570 /// connected to this tree, record the depth of the connection so that the
01571 /// nearest connected subtrees can be prioritized.
01572 void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
01573   for (SmallVectorImpl<Connection>::const_iterator
01574          I = SubtreeConnections[SubtreeID].begin(),
01575          E = SubtreeConnections[SubtreeID].end(); I != E; ++I) {
01576     SubtreeConnectLevels[I->TreeID] =
01577       std::max(SubtreeConnectLevels[I->TreeID], I->Level);
01578     DEBUG(dbgs() << "  Tree: " << I->TreeID
01579           << " @" << SubtreeConnectLevels[I->TreeID] << '\n');
01580   }
01581 }
01582 
01583 LLVM_DUMP_METHOD
01584 void ILPValue::print(raw_ostream &OS) const {
01585   OS << InstrCount << " / " << Length << " = ";
01586   if (!Length)
01587     OS << "BADILP";
01588   else
01589     OS << format("%g", ((double)InstrCount / Length));
01590 }
01591 
01592 LLVM_DUMP_METHOD
01593 void ILPValue::dump() const {
01594   dbgs() << *this << '\n';
01595 }
01596 
01597 namespace llvm {
01598 
01599 LLVM_DUMP_METHOD
01600 raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
01601   Val.print(OS);
01602   return OS;
01603 }
01604 
01605 } // namespace llvm