LLVM API Documentation

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