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 #define DEBUG_TYPE "misched"
00016 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
00017 #include "llvm/ADT/MapVector.h"
00018 #include "llvm/ADT/SmallPtrSet.h"
00019 #include "llvm/ADT/SmallSet.h"
00020 #include "llvm/Analysis/AliasAnalysis.h"
00021 #include "llvm/Analysis/ValueTracking.h"
00022 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
00023 #include "llvm/CodeGen/MachineFunctionPass.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/MC/MCInstrItineraries.h"
00032 #include "llvm/Support/CommandLine.h"
00033 #include "llvm/Support/Debug.h"
00034 #include "llvm/Support/Format.h"
00035 #include "llvm/Support/raw_ostream.h"
00036 #include "llvm/Target/TargetInstrInfo.h"
00037 #include "llvm/Target/TargetMachine.h"
00038 #include "llvm/Target/TargetRegisterInfo.h"
00039 #include "llvm/Target/TargetSubtargetInfo.h"
00040 #include <queue>
00041 
00042 using namespace llvm;
00043 
00044 static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
00045     cl::ZeroOrMore, cl::init(false),
00046     cl::desc("Enable use of AA during MI GAD construction"));
00047 
00048 static cl::opt<bool> UseTBAA("use-tbaa-in-sched-mi", cl::Hidden,
00049     cl::init(true), cl::desc("Enable use of TBAA during MI GAD construction"));
00050 
00051 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
00052                                      const MachineLoopInfo &mli,
00053                                      const MachineDominatorTree &mdt,
00054                                      bool IsPostRAFlag,
00055                                      bool RemoveKillFlags,
00056                                      LiveIntervals *lis)
00057   : ScheduleDAG(mf), MLI(mli), MDT(mdt), 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))
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   // Cover a trivial case - no edge is need to itself.
00515   if (MIa == MIb)
00516     return false;
00517 
00518   // FIXME: Need to handle multiple memory operands to support all targets.
00519   if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
00520     return true;
00521 
00522   if (isUnsafeMemoryObject(MIa, MFI) || isUnsafeMemoryObject(MIb, MFI))
00523     return true;
00524 
00525   // If we are dealing with two "normal" loads, we do not need an edge
00526   // between them - they could be reordered.
00527   if (!MIa->mayStore() && !MIb->mayStore())
00528     return false;
00529 
00530   // To this point analysis is generic. From here on we do need AA.
00531   if (!AA)
00532     return true;
00533 
00534   MachineMemOperand *MMOa = *MIa->memoperands_begin();
00535   MachineMemOperand *MMOb = *MIb->memoperands_begin();
00536 
00537   if (!MMOa->getValue() || !MMOb->getValue())
00538     return true;
00539 
00540   // The following interface to AA is fashioned after DAGCombiner::isAlias
00541   // and operates with MachineMemOperand offset with some important
00542   // assumptions:
00543   //   - LLVM fundamentally assumes flat address spaces.
00544   //   - MachineOperand offset can *only* result from legalization and
00545   //     cannot affect queries other than the trivial case of overlap
00546   //     checking.
00547   //   - These offsets never wrap and never step outside
00548   //     of allocated objects.
00549   //   - There should never be any negative offsets here.
00550   //
00551   // FIXME: Modify API to hide this math from "user"
00552   // FIXME: Even before we go to AA we can reason locally about some
00553   // memory objects. It can save compile time, and possibly catch some
00554   // corner cases not currently covered.
00555 
00556   assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
00557   assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
00558 
00559   int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
00560   int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
00561   int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
00562 
00563   AliasAnalysis::AliasResult AAResult = AA->alias(
00564       AliasAnalysis::Location(MMOa->getValue(), Overlapa,
00565                               UseTBAA ? MMOa->getTBAAInfo() : nullptr),
00566       AliasAnalysis::Location(MMOb->getValue(), Overlapb,
00567                               UseTBAA ? MMOb->getTBAAInfo() : nullptr));
00568 
00569   return (AAResult != AliasAnalysis::NoAlias);
00570 }
00571 
00572 /// This recursive function iterates over chain deps of SUb looking for
00573 /// "latest" node that needs a chain edge to SUa.
00574 static unsigned
00575 iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI,
00576                  SUnit *SUa, SUnit *SUb, SUnit *ExitSU, unsigned *Depth,
00577                  SmallPtrSet<const SUnit*, 16> &Visited) {
00578   if (!SUa || !SUb || SUb == ExitSU)
00579     return *Depth;
00580 
00581   // Remember visited nodes.
00582   if (!Visited.insert(SUb))
00583       return *Depth;
00584   // If there is _some_ dependency already in place, do not
00585   // descend any further.
00586   // TODO: Need to make sure that if that dependency got eliminated or ignored
00587   // for any reason in the future, we would not violate DAG topology.
00588   // Currently it does not happen, but makes an implicit assumption about
00589   // future implementation.
00590   //
00591   // Independently, if we encounter node that is some sort of global
00592   // object (like a call) we already have full set of dependencies to it
00593   // and we can stop descending.
00594   if (SUa->isSucc(SUb) ||
00595       isGlobalMemoryObject(AA, SUb->getInstr()))
00596     return *Depth;
00597 
00598   // If we do need an edge, or we have exceeded depth budget,
00599   // add that edge to the predecessors chain of SUb,
00600   // and stop descending.
00601   if (*Depth > 200 ||
00602       MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
00603     SUb->addPred(SDep(SUa, SDep::MayAliasMem));
00604     return *Depth;
00605   }
00606   // Track current depth.
00607   (*Depth)++;
00608   // Iterate over chain dependencies only.
00609   for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end();
00610        I != E; ++I)
00611     if (I->isCtrl())
00612       iterateChainSucc (AA, MFI, SUa, I->getSUnit(), ExitSU, Depth, Visited);
00613   return *Depth;
00614 }
00615 
00616 /// This function assumes that "downward" from SU there exist
00617 /// tail/leaf of already constructed DAG. It iterates downward and
00618 /// checks whether SU can be aliasing any node dominated
00619 /// by it.
00620 static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI,
00621                             SUnit *SU, SUnit *ExitSU, std::set<SUnit *> &CheckList,
00622                             unsigned LatencyToLoad) {
00623   if (!SU)
00624     return;
00625 
00626   SmallPtrSet<const SUnit*, 16> Visited;
00627   unsigned Depth = 0;
00628 
00629   for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end();
00630        I != IE; ++I) {
00631     if (SU == *I)
00632       continue;
00633     if (MIsNeedChainEdge(AA, MFI, SU->getInstr(), (*I)->getInstr())) {
00634       SDep Dep(SU, SDep::MayAliasMem);
00635       Dep.setLatency(((*I)->getInstr()->mayLoad()) ? LatencyToLoad : 0);
00636       (*I)->addPred(Dep);
00637     }
00638     // Now go through all the chain successors and iterate from them.
00639     // Keep track of visited nodes.
00640     for (SUnit::const_succ_iterator J = (*I)->Succs.begin(),
00641          JE = (*I)->Succs.end(); J != JE; ++J)
00642       if (J->isCtrl())
00643         iterateChainSucc (AA, MFI, SU, J->getSUnit(),
00644                           ExitSU, &Depth, Visited);
00645   }
00646 }
00647 
00648 /// Check whether two objects need a chain edge, if so, add it
00649 /// otherwise remember the rejected SU.
00650 static inline
00651 void addChainDependency (AliasAnalysis *AA, const MachineFrameInfo *MFI,
00652                          SUnit *SUa, SUnit *SUb,
00653                          std::set<SUnit *> &RejectList,
00654                          unsigned TrueMemOrderLatency = 0,
00655                          bool isNormalMemory = false) {
00656   // If this is a false dependency,
00657   // do not add the edge, but rememeber the rejected node.
00658   if (!AA || MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
00659     SDep Dep(SUa, isNormalMemory ? SDep::MayAliasMem : SDep::Barrier);
00660     Dep.setLatency(TrueMemOrderLatency);
00661     SUb->addPred(Dep);
00662   }
00663   else {
00664     // Duplicate entries should be ignored.
00665     RejectList.insert(SUb);
00666     DEBUG(dbgs() << "\tReject chain dep between SU("
00667           << SUa->NodeNum << ") and SU("
00668           << SUb->NodeNum << ")\n");
00669   }
00670 }
00671 
00672 /// Create an SUnit for each real instruction, numbered in top-down toplological
00673 /// order. The instruction order A < B, implies that no edge exists from B to A.
00674 ///
00675 /// Map each real instruction to its SUnit.
00676 ///
00677 /// After initSUnits, the SUnits vector cannot be resized and the scheduler may
00678 /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
00679 /// instead of pointers.
00680 ///
00681 /// MachineScheduler relies on initSUnits numbering the nodes by their order in
00682 /// the original instruction list.
00683 void ScheduleDAGInstrs::initSUnits() {
00684   // We'll be allocating one SUnit for each real instruction in the region,
00685   // which is contained within a basic block.
00686   SUnits.reserve(NumRegionInstrs);
00687 
00688   for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
00689     MachineInstr *MI = I;
00690     if (MI->isDebugValue())
00691       continue;
00692 
00693     SUnit *SU = newSUnit(MI);
00694     MISUnitMap[MI] = SU;
00695 
00696     SU->isCall = MI->isCall();
00697     SU->isCommutable = MI->isCommutable();
00698 
00699     // Assign the Latency field of SU using target-provided information.
00700     SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
00701 
00702     // If this SUnit uses a reserved or unbuffered resource, mark it as such.
00703     //
00704     // Reserved resources block an instruction from issueing and stall the
00705     // entire pipeline. These are identified by BufferSize=0.
00706     //
00707     // Unbuffered resources prevent execution of subsequeny instructions that
00708     // require the same resources. This is used for in-order execution pipelines
00709     // within an out-of-order core. These are identified by BufferSize=1.
00710     if (SchedModel.hasInstrSchedModel()) {
00711       const MCSchedClassDesc *SC = getSchedClass(SU);
00712       for (TargetSchedModel::ProcResIter
00713              PI = SchedModel.getWriteProcResBegin(SC),
00714              PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
00715         switch (SchedModel.getProcResource(PI->ProcResourceIdx)->BufferSize) {
00716         case 0:
00717           SU->hasReservedResource = true;
00718           break;
00719         case 1:
00720           SU->isUnbuffered = true;
00721           break;
00722         default:
00723           break;
00724         }
00725       }
00726     }
00727   }
00728 }
00729 
00730 /// If RegPressure is non-null, compute register pressure as a side effect. The
00731 /// DAG builder is an efficient place to do it because it already visits
00732 /// operands.
00733 void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
00734                                         RegPressureTracker *RPTracker,
00735                                         PressureDiffs *PDiffs) {
00736   const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
00737   bool UseAA = EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI
00738                                                        : ST.useAA();
00739   AliasAnalysis *AAForDep = UseAA ? AA : nullptr;
00740 
00741   MISUnitMap.clear();
00742   ScheduleDAG::clearDAG();
00743 
00744   // Create an SUnit for each real instruction.
00745   initSUnits();
00746 
00747   if (PDiffs)
00748     PDiffs->init(SUnits.size());
00749 
00750   // We build scheduling units by walking a block's instruction list from bottom
00751   // to top.
00752 
00753   // Remember where a generic side-effecting instruction is as we procede.
00754   SUnit *BarrierChain = nullptr, *AliasChain = nullptr;
00755 
00756   // Memory references to specific known memory locations are tracked
00757   // so that they can be given more precise dependencies. We track
00758   // separately the known memory locations that may alias and those
00759   // that are known not to alias
00760   MapVector<ValueType, std::vector<SUnit *> > AliasMemDefs, NonAliasMemDefs;
00761   MapVector<ValueType, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
00762   std::set<SUnit*> RejectMemNodes;
00763 
00764   // Remove any stale debug info; sometimes BuildSchedGraph is called again
00765   // without emitting the info from the previous call.
00766   DbgValues.clear();
00767   FirstDbgValue = nullptr;
00768 
00769   assert(Defs.empty() && Uses.empty() &&
00770          "Only BuildGraph should update Defs/Uses");
00771   Defs.setUniverse(TRI->getNumRegs());
00772   Uses.setUniverse(TRI->getNumRegs());
00773 
00774   assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
00775   VRegUses.clear();
00776   VRegDefs.setUniverse(MRI.getNumVirtRegs());
00777   VRegUses.setUniverse(MRI.getNumVirtRegs());
00778 
00779   // Model data dependencies between instructions being scheduled and the
00780   // ExitSU.
00781   addSchedBarrierDeps();
00782 
00783   // Walk the list of instructions, from bottom moving up.
00784   MachineInstr *DbgMI = nullptr;
00785   for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
00786        MII != MIE; --MII) {
00787     MachineInstr *MI = std::prev(MII);
00788     if (MI && DbgMI) {
00789       DbgValues.push_back(std::make_pair(DbgMI, MI));
00790       DbgMI = nullptr;
00791     }
00792 
00793     if (MI->isDebugValue()) {
00794       DbgMI = MI;
00795       continue;
00796     }
00797     SUnit *SU = MISUnitMap[MI];
00798     assert(SU && "No SUnit mapped to this MI");
00799 
00800     if (RPTracker) {
00801       PressureDiff *PDiff = PDiffs ? &(*PDiffs)[SU->NodeNum] : nullptr;
00802       RPTracker->recede(/*LiveUses=*/nullptr, PDiff);
00803       assert(RPTracker->getPos() == std::prev(MII) &&
00804              "RPTracker can't find MI");
00805     }
00806 
00807     assert(
00808         (CanHandleTerminators || (!MI->isTerminator() && !MI->isPosition())) &&
00809         "Cannot schedule terminators or labels!");
00810 
00811     // Add register-based dependencies (data, anti, and output).
00812     bool HasVRegDef = false;
00813     for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
00814       const MachineOperand &MO = MI->getOperand(j);
00815       if (!MO.isReg()) continue;
00816       unsigned Reg = MO.getReg();
00817       if (Reg == 0) continue;
00818 
00819       if (TRI->isPhysicalRegister(Reg))
00820         addPhysRegDeps(SU, j);
00821       else {
00822         assert(!IsPostRA && "Virtual register encountered!");
00823         if (MO.isDef()) {
00824           HasVRegDef = true;
00825           addVRegDefDeps(SU, j);
00826         }
00827         else if (MO.readsReg()) // ignore undef operands
00828           addVRegUseDeps(SU, j);
00829       }
00830     }
00831     // If we haven't seen any uses in this scheduling region, create a
00832     // dependence edge to ExitSU to model the live-out latency. This is required
00833     // for vreg defs with no in-region use, and prefetches with no vreg def.
00834     //
00835     // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
00836     // check currently relies on being called before adding chain deps.
00837     if (SU->NumSuccs == 0 && SU->Latency > 1
00838         && (HasVRegDef || MI->mayLoad())) {
00839       SDep Dep(SU, SDep::Artificial);
00840       Dep.setLatency(SU->Latency - 1);
00841       ExitSU.addPred(Dep);
00842     }
00843 
00844     // Add chain dependencies.
00845     // Chain dependencies used to enforce memory order should have
00846     // latency of 0 (except for true dependency of Store followed by
00847     // aliased Load... we estimate that with a single cycle of latency
00848     // assuming the hardware will bypass)
00849     // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
00850     // after stack slots are lowered to actual addresses.
00851     // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
00852     // produce more precise dependence information.
00853     unsigned TrueMemOrderLatency = MI->mayStore() ? 1 : 0;
00854     if (isGlobalMemoryObject(AA, MI)) {
00855       // Be conservative with these and add dependencies on all memory
00856       // references, even those that are known to not alias.
00857       for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
00858              NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
00859         for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
00860           I->second[i]->addPred(SDep(SU, SDep::Barrier));
00861         }
00862       }
00863       for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
00864              NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
00865         for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
00866           SDep Dep(SU, SDep::Barrier);
00867           Dep.setLatency(TrueMemOrderLatency);
00868           I->second[i]->addPred(Dep);
00869         }
00870       }
00871       // Add SU to the barrier chain.
00872       if (BarrierChain)
00873         BarrierChain->addPred(SDep(SU, SDep::Barrier));
00874       BarrierChain = SU;
00875       // This is a barrier event that acts as a pivotal node in the DAG,
00876       // so it is safe to clear list of exposed nodes.
00877       adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
00878                       TrueMemOrderLatency);
00879       RejectMemNodes.clear();
00880       NonAliasMemDefs.clear();
00881       NonAliasMemUses.clear();
00882 
00883       // fall-through
00884     new_alias_chain:
00885       // Chain all possibly aliasing memory references though SU.
00886       if (AliasChain) {
00887         unsigned ChainLatency = 0;
00888         if (AliasChain->getInstr()->mayLoad())
00889           ChainLatency = TrueMemOrderLatency;
00890         addChainDependency(AAForDep, MFI, SU, AliasChain, RejectMemNodes,
00891                            ChainLatency);
00892       }
00893       AliasChain = SU;
00894       for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
00895         addChainDependency(AAForDep, MFI, SU, PendingLoads[k], RejectMemNodes,
00896                            TrueMemOrderLatency);
00897       for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
00898            AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I) {
00899         for (unsigned i = 0, e = I->second.size(); i != e; ++i)
00900           addChainDependency(AAForDep, MFI, SU, I->second[i], RejectMemNodes);
00901       }
00902       for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
00903            AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
00904         for (unsigned i = 0, e = I->second.size(); i != e; ++i)
00905           addChainDependency(AAForDep, MFI, SU, I->second[i], RejectMemNodes,
00906                              TrueMemOrderLatency);
00907       }
00908       adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
00909                       TrueMemOrderLatency);
00910       PendingLoads.clear();
00911       AliasMemDefs.clear();
00912       AliasMemUses.clear();
00913     } else if (MI->mayStore()) {
00914       UnderlyingObjectsVector Objs;
00915       getUnderlyingObjectsForInstr(MI, MFI, Objs);
00916 
00917       if (Objs.empty()) {
00918         // Treat all other stores conservatively.
00919         goto new_alias_chain;
00920       }
00921 
00922       bool MayAlias = false;
00923       for (UnderlyingObjectsVector::iterator K = Objs.begin(), KE = Objs.end();
00924            K != KE; ++K) {
00925         ValueType V = K->getPointer();
00926         bool ThisMayAlias = K->getInt();
00927         if (ThisMayAlias)
00928           MayAlias = true;
00929 
00930         // A store to a specific PseudoSourceValue. Add precise dependencies.
00931         // Record the def in MemDefs, first adding a dep if there is
00932         // an existing def.
00933         MapVector<ValueType, std::vector<SUnit *> >::iterator I =
00934           ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
00935         MapVector<ValueType, std::vector<SUnit *> >::iterator IE =
00936           ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
00937         if (I != IE) {
00938           for (unsigned i = 0, e = I->second.size(); i != e; ++i)
00939             addChainDependency(AAForDep, MFI, SU, I->second[i], RejectMemNodes,
00940                                0, true);
00941 
00942           // If we're not using AA, then we only need one store per object.
00943           if (!AAForDep)
00944             I->second.clear();
00945           I->second.push_back(SU);
00946         } else {
00947           if (ThisMayAlias) {
00948             if (!AAForDep)
00949               AliasMemDefs[V].clear();
00950             AliasMemDefs[V].push_back(SU);
00951           } else {
00952             if (!AAForDep)
00953               NonAliasMemDefs[V].clear();
00954             NonAliasMemDefs[V].push_back(SU);
00955           }
00956         }
00957         // Handle the uses in MemUses, if there are any.
00958         MapVector<ValueType, std::vector<SUnit *> >::iterator J =
00959           ((ThisMayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
00960         MapVector<ValueType, std::vector<SUnit *> >::iterator JE =
00961           ((ThisMayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
00962         if (J != JE) {
00963           for (unsigned i = 0, e = J->second.size(); i != e; ++i)
00964             addChainDependency(AAForDep, MFI, SU, J->second[i], RejectMemNodes,
00965                                TrueMemOrderLatency, true);
00966           J->second.clear();
00967         }
00968       }
00969       if (MayAlias) {
00970         // Add dependencies from all the PendingLoads, i.e. loads
00971         // with no underlying object.
00972         for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
00973           addChainDependency(AAForDep, MFI, SU, PendingLoads[k], RejectMemNodes,
00974                              TrueMemOrderLatency);
00975         // Add dependence on alias chain, if needed.
00976         if (AliasChain)
00977           addChainDependency(AAForDep, MFI, SU, AliasChain, RejectMemNodes);
00978         // But we also should check dependent instructions for the
00979         // SU in question.
00980         adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
00981                         TrueMemOrderLatency);
00982       }
00983       // Add dependence on barrier chain, if needed.
00984       // There is no point to check aliasing on barrier event. Even if
00985       // SU and barrier _could_ be reordered, they should not. In addition,
00986       // we have lost all RejectMemNodes below barrier.
00987       if (BarrierChain)
00988         BarrierChain->addPred(SDep(SU, SDep::Barrier));
00989 
00990       if (!ExitSU.isPred(SU))
00991         // Push store's up a bit to avoid them getting in between cmp
00992         // and branches.
00993         ExitSU.addPred(SDep(SU, SDep::Artificial));
00994     } else if (MI->mayLoad()) {
00995       bool MayAlias = true;
00996       if (MI->isInvariantLoad(AA)) {
00997         // Invariant load, no chain dependencies needed!
00998       } else {
00999         UnderlyingObjectsVector Objs;
01000         getUnderlyingObjectsForInstr(MI, MFI, Objs);
01001 
01002         if (Objs.empty()) {
01003           // A load with no underlying object. Depend on all
01004           // potentially aliasing stores.
01005           for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
01006                  AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
01007             for (unsigned i = 0, e = I->second.size(); i != e; ++i)
01008               addChainDependency(AAForDep, MFI, SU, I->second[i],
01009                                  RejectMemNodes);
01010 
01011           PendingLoads.push_back(SU);
01012           MayAlias = true;
01013         } else {
01014           MayAlias = false;
01015         }
01016 
01017         for (UnderlyingObjectsVector::iterator
01018              J = Objs.begin(), JE = Objs.end(); J != JE; ++J) {
01019           ValueType V = J->getPointer();
01020           bool ThisMayAlias = J->getInt();
01021 
01022           if (ThisMayAlias)
01023             MayAlias = true;
01024 
01025           // A load from a specific PseudoSourceValue. Add precise dependencies.
01026           MapVector<ValueType, std::vector<SUnit *> >::iterator I =
01027             ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
01028           MapVector<ValueType, std::vector<SUnit *> >::iterator IE =
01029             ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
01030           if (I != IE)
01031             for (unsigned i = 0, e = I->second.size(); i != e; ++i)
01032               addChainDependency(AAForDep, MFI, SU, I->second[i],
01033                                  RejectMemNodes, 0, true);
01034           if (ThisMayAlias)
01035             AliasMemUses[V].push_back(SU);
01036           else
01037             NonAliasMemUses[V].push_back(SU);
01038         }
01039         if (MayAlias)
01040           adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, /*Latency=*/0);
01041         // Add dependencies on alias and barrier chains, if needed.
01042         if (MayAlias && AliasChain)
01043           addChainDependency(AAForDep, MFI, SU, AliasChain, RejectMemNodes);
01044         if (BarrierChain)
01045           BarrierChain->addPred(SDep(SU, SDep::Barrier));
01046       }
01047     }
01048   }
01049   if (DbgMI)
01050     FirstDbgValue = DbgMI;
01051 
01052   Defs.clear();
01053   Uses.clear();
01054   VRegDefs.clear();
01055   PendingLoads.clear();
01056 }
01057 
01058 /// \brief Initialize register live-range state for updating kills.
01059 void ScheduleDAGInstrs::startBlockForKills(MachineBasicBlock *BB) {
01060   // Start with no live registers.
01061   LiveRegs.reset();
01062 
01063   // Examine the live-in regs of all successors.
01064   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
01065        SE = BB->succ_end(); SI != SE; ++SI) {
01066     for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
01067          E = (*SI)->livein_end(); I != E; ++I) {
01068       unsigned Reg = *I;
01069       // Repeat, for reg and all subregs.
01070       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
01071            SubRegs.isValid(); ++SubRegs)
01072         LiveRegs.set(*SubRegs);
01073     }
01074   }
01075 }
01076 
01077 bool ScheduleDAGInstrs::toggleKillFlag(MachineInstr *MI, MachineOperand &MO) {
01078   // Setting kill flag...
01079   if (!MO.isKill()) {
01080     MO.setIsKill(true);
01081     return false;
01082   }
01083 
01084   // If MO itself is live, clear the kill flag...
01085   if (LiveRegs.test(MO.getReg())) {
01086     MO.setIsKill(false);
01087     return false;
01088   }
01089 
01090   // If any subreg of MO is live, then create an imp-def for that
01091   // subreg and keep MO marked as killed.
01092   MO.setIsKill(false);
01093   bool AllDead = true;
01094   const unsigned SuperReg = MO.getReg();
01095   MachineInstrBuilder MIB(MF, MI);
01096   for (MCSubRegIterator SubRegs(SuperReg, TRI); SubRegs.isValid(); ++SubRegs) {
01097     if (LiveRegs.test(*SubRegs)) {
01098       MIB.addReg(*SubRegs, RegState::ImplicitDefine);
01099       AllDead = false;
01100     }
01101   }
01102 
01103   if(AllDead)
01104     MO.setIsKill(true);
01105   return false;
01106 }
01107 
01108 // FIXME: Reuse the LivePhysRegs utility for this.
01109 void ScheduleDAGInstrs::fixupKills(MachineBasicBlock *MBB) {
01110   DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
01111 
01112   LiveRegs.resize(TRI->getNumRegs());
01113   BitVector killedRegs(TRI->getNumRegs());
01114 
01115   startBlockForKills(MBB);
01116 
01117   // Examine block from end to start...
01118   unsigned Count = MBB->size();
01119   for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
01120        I != E; --Count) {
01121     MachineInstr *MI = --I;
01122     if (MI->isDebugValue())
01123       continue;
01124 
01125     // Update liveness.  Registers that are defed but not used in this
01126     // instruction are now dead. Mark register and all subregs as they
01127     // are completely defined.
01128     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01129       MachineOperand &MO = MI->getOperand(i);
01130       if (MO.isRegMask())
01131         LiveRegs.clearBitsNotInMask(MO.getRegMask());
01132       if (!MO.isReg()) continue;
01133       unsigned Reg = MO.getReg();
01134       if (Reg == 0) continue;
01135       if (!MO.isDef()) continue;
01136       // Ignore two-addr defs.
01137       if (MI->isRegTiedToUseOperand(i)) continue;
01138 
01139       // Repeat for reg and all subregs.
01140       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
01141            SubRegs.isValid(); ++SubRegs)
01142         LiveRegs.reset(*SubRegs);
01143     }
01144 
01145     // Examine all used registers and set/clear kill flag. When a
01146     // register is used multiple times we only set the kill flag on
01147     // the first use. Don't set kill flags on undef operands.
01148     killedRegs.reset();
01149     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01150       MachineOperand &MO = MI->getOperand(i);
01151       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
01152       unsigned Reg = MO.getReg();
01153       if ((Reg == 0) || MRI.isReserved(Reg)) continue;
01154 
01155       bool kill = false;
01156       if (!killedRegs.test(Reg)) {
01157         kill = true;
01158         // A register is not killed if any subregs are live...
01159         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
01160           if (LiveRegs.test(*SubRegs)) {
01161             kill = false;
01162             break;
01163           }
01164         }
01165 
01166         // If subreg is not live, then register is killed if it became
01167         // live in this instruction
01168         if (kill)
01169           kill = !LiveRegs.test(Reg);
01170       }
01171 
01172       if (MO.isKill() != kill) {
01173         DEBUG(dbgs() << "Fixing " << MO << " in ");
01174         // Warning: toggleKillFlag may invalidate MO.
01175         toggleKillFlag(MI, MO);
01176         DEBUG(MI->dump());
01177       }
01178 
01179       killedRegs.set(Reg);
01180     }
01181 
01182     // Mark any used register (that is not using undef) and subregs as
01183     // now live...
01184     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01185       MachineOperand &MO = MI->getOperand(i);
01186       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
01187       unsigned Reg = MO.getReg();
01188       if ((Reg == 0) || MRI.isReserved(Reg)) continue;
01189 
01190       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
01191            SubRegs.isValid(); ++SubRegs)
01192         LiveRegs.set(*SubRegs);
01193     }
01194   }
01195 }
01196 
01197 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
01198 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01199   SU->getInstr()->dump();
01200 #endif
01201 }
01202 
01203 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
01204   std::string s;
01205   raw_string_ostream oss(s);
01206   if (SU == &EntrySU)
01207     oss << "<entry>";
01208   else if (SU == &ExitSU)
01209     oss << "<exit>";
01210   else
01211     SU->getInstr()->print(oss, &TM, /*SkipOpers=*/true);
01212   return oss.str();
01213 }
01214 
01215 /// Return the basic block label. It is not necessarilly unique because a block
01216 /// contains multiple scheduling regions. But it is fine for visualization.
01217 std::string ScheduleDAGInstrs::getDAGName() const {
01218   return "dag." + BB->getFullName();
01219 }
01220 
01221 //===----------------------------------------------------------------------===//
01222 // SchedDFSResult Implementation
01223 //===----------------------------------------------------------------------===//
01224 
01225 namespace llvm {
01226 /// \brief Internal state used to compute SchedDFSResult.
01227 class SchedDFSImpl {
01228   SchedDFSResult &R;
01229 
01230   /// Join DAG nodes into equivalence classes by their subtree.
01231   IntEqClasses SubtreeClasses;
01232   /// List PredSU, SuccSU pairs that represent data edges between subtrees.
01233   std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs;
01234 
01235   struct RootData {
01236     unsigned NodeID;
01237     unsigned ParentNodeID;  // Parent node (member of the parent subtree).
01238     unsigned SubInstrCount; // Instr count in this tree only, not children.
01239 
01240     RootData(unsigned id): NodeID(id),
01241                            ParentNodeID(SchedDFSResult::InvalidSubtreeID),
01242                            SubInstrCount(0) {}
01243 
01244     unsigned getSparseSetIndex() const { return NodeID; }
01245   };
01246 
01247   SparseSet<RootData> RootSet;
01248 
01249 public:
01250   SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
01251     RootSet.setUniverse(R.DFSNodeData.size());
01252   }
01253 
01254   /// Return true if this node been visited by the DFS traversal.
01255   ///
01256   /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
01257   /// ID. Later, SubtreeID is updated but remains valid.
01258   bool isVisited(const SUnit *SU) const {
01259     return R.DFSNodeData[SU->NodeNum].SubtreeID
01260       != SchedDFSResult::InvalidSubtreeID;
01261   }
01262 
01263   /// Initialize this node's instruction count. We don't need to flag the node
01264   /// visited until visitPostorder because the DAG cannot have cycles.
01265   void visitPreorder(const SUnit *SU) {
01266     R.DFSNodeData[SU->NodeNum].InstrCount =
01267       SU->getInstr()->isTransient() ? 0 : 1;
01268   }
01269 
01270   /// Called once for each node after all predecessors are visited. Revisit this
01271   /// node's predecessors and potentially join them now that we know the ILP of
01272   /// the other predecessors.
01273   void visitPostorderNode(const SUnit *SU) {
01274     // Mark this node as the root of a subtree. It may be joined with its
01275     // successors later.
01276     R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
01277     RootData RData(SU->NodeNum);
01278     RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
01279 
01280     // If any predecessors are still in their own subtree, they either cannot be
01281     // joined or are large enough to remain separate. If this parent node's
01282     // total instruction count is not greater than a child subtree by at least
01283     // the subtree limit, then try to join it now since splitting subtrees is
01284     // only useful if multiple high-pressure paths are possible.
01285     unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
01286     for (SUnit::const_pred_iterator
01287            PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
01288       if (PI->getKind() != SDep::Data)
01289         continue;
01290       unsigned PredNum = PI->getSUnit()->NodeNum;
01291       if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
01292         joinPredSubtree(*PI, SU, /*CheckLimit=*/false);
01293 
01294       // Either link or merge the TreeData entry from the child to the parent.
01295       if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
01296         // If the predecessor's parent is invalid, this is a tree edge and the
01297         // current node is the parent.
01298         if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
01299           RootSet[PredNum].ParentNodeID = SU->NodeNum;
01300       }
01301       else if (RootSet.count(PredNum)) {
01302         // The predecessor is not a root, but is still in the root set. This
01303         // must be the new parent that it was just joined to. Note that
01304         // RootSet[PredNum].ParentNodeID may either be invalid or may still be
01305         // set to the original parent.
01306         RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
01307         RootSet.erase(PredNum);
01308       }
01309     }
01310     RootSet[SU->NodeNum] = RData;
01311   }
01312 
01313   /// Called once for each tree edge after calling visitPostOrderNode on the
01314   /// predecessor. Increment the parent node's instruction count and
01315   /// preemptively join this subtree to its parent's if it is small enough.
01316   void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
01317     R.DFSNodeData[Succ->NodeNum].InstrCount
01318       += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
01319     joinPredSubtree(PredDep, Succ);
01320   }
01321 
01322   /// Add a connection for cross edges.
01323   void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
01324     ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
01325   }
01326 
01327   /// Set each node's subtree ID to the representative ID and record connections
01328   /// between trees.
01329   void finalize() {
01330     SubtreeClasses.compress();
01331     R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
01332     assert(SubtreeClasses.getNumClasses() == RootSet.size()
01333            && "number of roots should match trees");
01334     for (SparseSet<RootData>::const_iterator
01335            RI = RootSet.begin(), RE = RootSet.end(); RI != RE; ++RI) {
01336       unsigned TreeID = SubtreeClasses[RI->NodeID];
01337       if (RI->ParentNodeID != SchedDFSResult::InvalidSubtreeID)
01338         R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[RI->ParentNodeID];
01339       R.DFSTreeData[TreeID].SubInstrCount = RI->SubInstrCount;
01340       // Note that SubInstrCount may be greater than InstrCount if we joined
01341       // subtrees across a cross edge. InstrCount will be attributed to the
01342       // original parent, while SubInstrCount will be attributed to the joined
01343       // parent.
01344     }
01345     R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
01346     R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
01347     DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
01348     for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
01349       R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
01350       DEBUG(dbgs() << "  SU(" << Idx << ") in tree "
01351             << R.DFSNodeData[Idx].SubtreeID << '\n');
01352     }
01353     for (std::vector<std::pair<const SUnit*, const SUnit*> >::const_iterator
01354            I = ConnectionPairs.begin(), E = ConnectionPairs.end();
01355          I != E; ++I) {
01356       unsigned PredTree = SubtreeClasses[I->first->NodeNum];
01357       unsigned SuccTree = SubtreeClasses[I->second->NodeNum];
01358       if (PredTree == SuccTree)
01359         continue;
01360       unsigned Depth = I->first->getDepth();
01361       addConnection(PredTree, SuccTree, Depth);
01362       addConnection(SuccTree, PredTree, Depth);
01363     }
01364   }
01365 
01366 protected:
01367   /// Join the predecessor subtree with the successor that is its DFS
01368   /// parent. Apply some heuristics before joining.
01369   bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
01370                        bool CheckLimit = true) {
01371     assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
01372 
01373     // Check if the predecessor is already joined.
01374     const SUnit *PredSU = PredDep.getSUnit();
01375     unsigned PredNum = PredSU->NodeNum;
01376     if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
01377       return false;
01378 
01379     // Four is the magic number of successors before a node is considered a
01380     // pinch point.
01381     unsigned NumDataSucs = 0;
01382     for (SUnit::const_succ_iterator SI = PredSU->Succs.begin(),
01383            SE = PredSU->Succs.end(); SI != SE; ++SI) {
01384       if (SI->getKind() == SDep::Data) {
01385         if (++NumDataSucs >= 4)
01386           return false;
01387       }
01388     }
01389     if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
01390       return false;
01391     R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
01392     SubtreeClasses.join(Succ->NodeNum, PredNum);
01393     return true;
01394   }
01395 
01396   /// Called by finalize() to record a connection between trees.
01397   void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
01398     if (!Depth)
01399       return;
01400 
01401     do {
01402       SmallVectorImpl<SchedDFSResult::Connection> &Connections =
01403         R.SubtreeConnections[FromTree];
01404       for (SmallVectorImpl<SchedDFSResult::Connection>::iterator
01405              I = Connections.begin(), E = Connections.end(); I != E; ++I) {
01406         if (I->TreeID == ToTree) {
01407           I->Level = std::max(I->Level, Depth);
01408           return;
01409         }
01410       }
01411       Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
01412       FromTree = R.DFSTreeData[FromTree].ParentTreeID;
01413     } while (FromTree != SchedDFSResult::InvalidSubtreeID);
01414   }
01415 };
01416 } // namespace llvm
01417 
01418 namespace {
01419 /// \brief Manage the stack used by a reverse depth-first search over the DAG.
01420 class SchedDAGReverseDFS {
01421   std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
01422 public:
01423   bool isComplete() const { return DFSStack.empty(); }
01424 
01425   void follow(const SUnit *SU) {
01426     DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
01427   }
01428   void advance() { ++DFSStack.back().second; }
01429 
01430   const SDep *backtrack() {
01431     DFSStack.pop_back();
01432     return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
01433   }
01434 
01435   const SUnit *getCurr() const { return DFSStack.back().first; }
01436 
01437   SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
01438 
01439   SUnit::const_pred_iterator getPredEnd() const {
01440     return getCurr()->Preds.end();
01441   }
01442 };
01443 } // anonymous
01444 
01445 static bool hasDataSucc(const SUnit *SU) {
01446   for (SUnit::const_succ_iterator
01447          SI = SU->Succs.begin(), SE = SU->Succs.end(); SI != SE; ++SI) {
01448     if (SI->getKind() == SDep::Data && !SI->getSUnit()->isBoundaryNode())
01449       return true;
01450   }
01451   return false;
01452 }
01453 
01454 /// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
01455 /// search from this root.
01456 void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
01457   if (!IsBottomUp)
01458     llvm_unreachable("Top-down ILP metric is unimplemnted");
01459 
01460   SchedDFSImpl Impl(*this);
01461   for (ArrayRef<SUnit>::const_iterator
01462          SI = SUnits.begin(), SE = SUnits.end(); SI != SE; ++SI) {
01463     const SUnit *SU = &*SI;
01464     if (Impl.isVisited(SU) || hasDataSucc(SU))
01465       continue;
01466 
01467     SchedDAGReverseDFS DFS;
01468     Impl.visitPreorder(SU);
01469     DFS.follow(SU);
01470     for (;;) {
01471       // Traverse the leftmost path as far as possible.
01472       while (DFS.getPred() != DFS.getPredEnd()) {
01473         const SDep &PredDep = *DFS.getPred();
01474         DFS.advance();
01475         // Ignore non-data edges.
01476         if (PredDep.getKind() != SDep::Data
01477             || PredDep.getSUnit()->isBoundaryNode()) {
01478           continue;
01479         }
01480         // An already visited edge is a cross edge, assuming an acyclic DAG.
01481         if (Impl.isVisited(PredDep.getSUnit())) {
01482           Impl.visitCrossEdge(PredDep, DFS.getCurr());
01483           continue;
01484         }
01485         Impl.visitPreorder(PredDep.getSUnit());
01486         DFS.follow(PredDep.getSUnit());
01487       }
01488       // Visit the top of the stack in postorder and backtrack.
01489       const SUnit *Child = DFS.getCurr();
01490       const SDep *PredDep = DFS.backtrack();
01491       Impl.visitPostorderNode(Child);
01492       if (PredDep)
01493         Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
01494       if (DFS.isComplete())
01495         break;
01496     }
01497   }
01498   Impl.finalize();
01499 }
01500 
01501 /// The root of the given SubtreeID was just scheduled. For all subtrees
01502 /// connected to this tree, record the depth of the connection so that the
01503 /// nearest connected subtrees can be prioritized.
01504 void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
01505   for (SmallVectorImpl<Connection>::const_iterator
01506          I = SubtreeConnections[SubtreeID].begin(),
01507          E = SubtreeConnections[SubtreeID].end(); I != E; ++I) {
01508     SubtreeConnectLevels[I->TreeID] =
01509       std::max(SubtreeConnectLevels[I->TreeID], I->Level);
01510     DEBUG(dbgs() << "  Tree: " << I->TreeID
01511           << " @" << SubtreeConnectLevels[I->TreeID] << '\n');
01512   }
01513 }
01514 
01515 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01516 void ILPValue::print(raw_ostream &OS) const {
01517   OS << InstrCount << " / " << Length << " = ";
01518   if (!Length)
01519     OS << "BADILP";
01520   else
01521     OS << format("%g", ((double)InstrCount / Length));
01522 }
01523 
01524 void ILPValue::dump() const {
01525   dbgs() << *this << '\n';
01526 }
01527 
01528 namespace llvm {
01529 
01530 raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
01531   Val.print(OS);
01532   return OS;
01533 }
01534 
01535 } // namespace llvm
01536 #endif // !NDEBUG || LLVM_ENABLE_DUMP