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       // Add dependence on barrier chain, if needed.
00924       // There is no point to check aliasing on barrier event. Even if
00925       // SU and barrier _could_ be reordered, they should not. In addition,
00926       // we have lost all RejectMemNodes below barrier.
00927       if (BarrierChain)
00928         BarrierChain->addPred(SDep(SU, SDep::Barrier));
00929 
00930       UnderlyingObjectsVector Objs;
00931       getUnderlyingObjectsForInstr(MI, MFI, Objs);
00932 
00933       if (Objs.empty()) {
00934         // Treat all other stores conservatively.
00935         goto new_alias_chain;
00936       }
00937 
00938       bool MayAlias = false;
00939       for (UnderlyingObjectsVector::iterator K = Objs.begin(), KE = Objs.end();
00940            K != KE; ++K) {
00941         ValueType V = K->getPointer();
00942         bool ThisMayAlias = K->getInt();
00943         if (ThisMayAlias)
00944           MayAlias = true;
00945 
00946         // A store to a specific PseudoSourceValue. Add precise dependencies.
00947         // Record the def in MemDefs, first adding a dep if there is
00948         // an existing def.
00949         MapVector<ValueType, std::vector<SUnit *> >::iterator I =
00950           ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
00951         MapVector<ValueType, std::vector<SUnit *> >::iterator IE =
00952           ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
00953         if (I != IE) {
00954           for (unsigned i = 0, e = I->second.size(); i != e; ++i)
00955             addChainDependency(AAForDep, MFI, SU, I->second[i], RejectMemNodes,
00956                                0, true);
00957 
00958           // If we're not using AA, then we only need one store per object.
00959           if (!AAForDep)
00960             I->second.clear();
00961           I->second.push_back(SU);
00962         } else {
00963           if (ThisMayAlias) {
00964             if (!AAForDep)
00965               AliasMemDefs[V].clear();
00966             AliasMemDefs[V].push_back(SU);
00967           } else {
00968             if (!AAForDep)
00969               NonAliasMemDefs[V].clear();
00970             NonAliasMemDefs[V].push_back(SU);
00971           }
00972         }
00973         // Handle the uses in MemUses, if there are any.
00974         MapVector<ValueType, std::vector<SUnit *> >::iterator J =
00975           ((ThisMayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
00976         MapVector<ValueType, std::vector<SUnit *> >::iterator JE =
00977           ((ThisMayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
00978         if (J != JE) {
00979           for (unsigned i = 0, e = J->second.size(); i != e; ++i)
00980             addChainDependency(AAForDep, MFI, SU, J->second[i], RejectMemNodes,
00981                                TrueMemOrderLatency, true);
00982           J->second.clear();
00983         }
00984       }
00985       if (MayAlias) {
00986         // Add dependencies from all the PendingLoads, i.e. loads
00987         // with no underlying object.
00988         for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
00989           addChainDependency(AAForDep, MFI, SU, PendingLoads[k], RejectMemNodes,
00990                              TrueMemOrderLatency);
00991         // Add dependence on alias chain, if needed.
00992         if (AliasChain)
00993           addChainDependency(AAForDep, MFI, SU, AliasChain, RejectMemNodes);
00994         // But we also should check dependent instructions for the
00995         // SU in question.
00996         adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
00997                         TrueMemOrderLatency);
00998       }
00999     } else if (MI->mayLoad()) {
01000       bool MayAlias = true;
01001       if (MI->isInvariantLoad(AA)) {
01002         // Invariant load, no chain dependencies needed!
01003       } else {
01004         UnderlyingObjectsVector Objs;
01005         getUnderlyingObjectsForInstr(MI, MFI, Objs);
01006 
01007         if (Objs.empty()) {
01008           // A load with no underlying object. Depend on all
01009           // potentially aliasing stores.
01010           for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
01011                  AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
01012             for (unsigned i = 0, e = I->second.size(); i != e; ++i)
01013               addChainDependency(AAForDep, MFI, SU, I->second[i],
01014                                  RejectMemNodes);
01015 
01016           PendingLoads.push_back(SU);
01017           MayAlias = true;
01018         } else {
01019           MayAlias = false;
01020         }
01021 
01022         for (UnderlyingObjectsVector::iterator
01023              J = Objs.begin(), JE = Objs.end(); J != JE; ++J) {
01024           ValueType V = J->getPointer();
01025           bool ThisMayAlias = J->getInt();
01026 
01027           if (ThisMayAlias)
01028             MayAlias = true;
01029 
01030           // A load from a specific PseudoSourceValue. Add precise dependencies.
01031           MapVector<ValueType, std::vector<SUnit *> >::iterator I =
01032             ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
01033           MapVector<ValueType, std::vector<SUnit *> >::iterator IE =
01034             ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
01035           if (I != IE)
01036             for (unsigned i = 0, e = I->second.size(); i != e; ++i)
01037               addChainDependency(AAForDep, MFI, SU, I->second[i],
01038                                  RejectMemNodes, 0, true);
01039           if (ThisMayAlias)
01040             AliasMemUses[V].push_back(SU);
01041           else
01042             NonAliasMemUses[V].push_back(SU);
01043         }
01044         if (MayAlias)
01045           adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, /*Latency=*/0);
01046         // Add dependencies on alias and barrier chains, if needed.
01047         if (MayAlias && AliasChain)
01048           addChainDependency(AAForDep, MFI, SU, AliasChain, RejectMemNodes);
01049         if (BarrierChain)
01050           BarrierChain->addPred(SDep(SU, SDep::Barrier));
01051       }
01052     }
01053   }
01054   if (DbgMI)
01055     FirstDbgValue = DbgMI;
01056 
01057   Defs.clear();
01058   Uses.clear();
01059   VRegDefs.clear();
01060   PendingLoads.clear();
01061 }
01062 
01063 /// \brief Initialize register live-range state for updating kills.
01064 void ScheduleDAGInstrs::startBlockForKills(MachineBasicBlock *BB) {
01065   // Start with no live registers.
01066   LiveRegs.reset();
01067 
01068   // Examine the live-in regs of all successors.
01069   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
01070        SE = BB->succ_end(); SI != SE; ++SI) {
01071     for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
01072          E = (*SI)->livein_end(); I != E; ++I) {
01073       unsigned Reg = *I;
01074       // Repeat, for reg and all subregs.
01075       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
01076            SubRegs.isValid(); ++SubRegs)
01077         LiveRegs.set(*SubRegs);
01078     }
01079   }
01080 }
01081 
01082 bool ScheduleDAGInstrs::toggleKillFlag(MachineInstr *MI, MachineOperand &MO) {
01083   // Setting kill flag...
01084   if (!MO.isKill()) {
01085     MO.setIsKill(true);
01086     return false;
01087   }
01088 
01089   // If MO itself is live, clear the kill flag...
01090   if (LiveRegs.test(MO.getReg())) {
01091     MO.setIsKill(false);
01092     return false;
01093   }
01094 
01095   // If any subreg of MO is live, then create an imp-def for that
01096   // subreg and keep MO marked as killed.
01097   MO.setIsKill(false);
01098   bool AllDead = true;
01099   const unsigned SuperReg = MO.getReg();
01100   MachineInstrBuilder MIB(MF, MI);
01101   for (MCSubRegIterator SubRegs(SuperReg, TRI); SubRegs.isValid(); ++SubRegs) {
01102     if (LiveRegs.test(*SubRegs)) {
01103       MIB.addReg(*SubRegs, RegState::ImplicitDefine);
01104       AllDead = false;
01105     }
01106   }
01107 
01108   if(AllDead)
01109     MO.setIsKill(true);
01110   return false;
01111 }
01112 
01113 // FIXME: Reuse the LivePhysRegs utility for this.
01114 void ScheduleDAGInstrs::fixupKills(MachineBasicBlock *MBB) {
01115   DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
01116 
01117   LiveRegs.resize(TRI->getNumRegs());
01118   BitVector killedRegs(TRI->getNumRegs());
01119 
01120   startBlockForKills(MBB);
01121 
01122   // Examine block from end to start...
01123   unsigned Count = MBB->size();
01124   for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
01125        I != E; --Count) {
01126     MachineInstr *MI = --I;
01127     if (MI->isDebugValue())
01128       continue;
01129 
01130     // Update liveness.  Registers that are defed but not used in this
01131     // instruction are now dead. Mark register and all subregs as they
01132     // are completely defined.
01133     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01134       MachineOperand &MO = MI->getOperand(i);
01135       if (MO.isRegMask())
01136         LiveRegs.clearBitsNotInMask(MO.getRegMask());
01137       if (!MO.isReg()) continue;
01138       unsigned Reg = MO.getReg();
01139       if (Reg == 0) continue;
01140       if (!MO.isDef()) continue;
01141       // Ignore two-addr defs.
01142       if (MI->isRegTiedToUseOperand(i)) continue;
01143 
01144       // Repeat for reg and all subregs.
01145       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
01146            SubRegs.isValid(); ++SubRegs)
01147         LiveRegs.reset(*SubRegs);
01148     }
01149 
01150     // Examine all used registers and set/clear kill flag. When a
01151     // register is used multiple times we only set the kill flag on
01152     // the first use. Don't set kill flags on undef operands.
01153     killedRegs.reset();
01154     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01155       MachineOperand &MO = MI->getOperand(i);
01156       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
01157       unsigned Reg = MO.getReg();
01158       if ((Reg == 0) || MRI.isReserved(Reg)) continue;
01159 
01160       bool kill = false;
01161       if (!killedRegs.test(Reg)) {
01162         kill = true;
01163         // A register is not killed if any subregs are live...
01164         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
01165           if (LiveRegs.test(*SubRegs)) {
01166             kill = false;
01167             break;
01168           }
01169         }
01170 
01171         // If subreg is not live, then register is killed if it became
01172         // live in this instruction
01173         if (kill)
01174           kill = !LiveRegs.test(Reg);
01175       }
01176 
01177       if (MO.isKill() != kill) {
01178         DEBUG(dbgs() << "Fixing " << MO << " in ");
01179         // Warning: toggleKillFlag may invalidate MO.
01180         toggleKillFlag(MI, MO);
01181         DEBUG(MI->dump());
01182       }
01183 
01184       killedRegs.set(Reg);
01185     }
01186 
01187     // Mark any used register (that is not using undef) and subregs as
01188     // now live...
01189     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01190       MachineOperand &MO = MI->getOperand(i);
01191       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
01192       unsigned Reg = MO.getReg();
01193       if ((Reg == 0) || MRI.isReserved(Reg)) continue;
01194 
01195       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
01196            SubRegs.isValid(); ++SubRegs)
01197         LiveRegs.set(*SubRegs);
01198     }
01199   }
01200 }
01201 
01202 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
01203 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01204   SU->getInstr()->dump();
01205 #endif
01206 }
01207 
01208 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
01209   std::string s;
01210   raw_string_ostream oss(s);
01211   if (SU == &EntrySU)
01212     oss << "<entry>";
01213   else if (SU == &ExitSU)
01214     oss << "<exit>";
01215   else
01216     SU->getInstr()->print(oss, &TM, /*SkipOpers=*/true);
01217   return oss.str();
01218 }
01219 
01220 /// Return the basic block label. It is not necessarilly unique because a block
01221 /// contains multiple scheduling regions. But it is fine for visualization.
01222 std::string ScheduleDAGInstrs::getDAGName() const {
01223   return "dag." + BB->getFullName();
01224 }
01225 
01226 //===----------------------------------------------------------------------===//
01227 // SchedDFSResult Implementation
01228 //===----------------------------------------------------------------------===//
01229 
01230 namespace llvm {
01231 /// \brief Internal state used to compute SchedDFSResult.
01232 class SchedDFSImpl {
01233   SchedDFSResult &R;
01234 
01235   /// Join DAG nodes into equivalence classes by their subtree.
01236   IntEqClasses SubtreeClasses;
01237   /// List PredSU, SuccSU pairs that represent data edges between subtrees.
01238   std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs;
01239 
01240   struct RootData {
01241     unsigned NodeID;
01242     unsigned ParentNodeID;  // Parent node (member of the parent subtree).
01243     unsigned SubInstrCount; // Instr count in this tree only, not children.
01244 
01245     RootData(unsigned id): NodeID(id),
01246                            ParentNodeID(SchedDFSResult::InvalidSubtreeID),
01247                            SubInstrCount(0) {}
01248 
01249     unsigned getSparseSetIndex() const { return NodeID; }
01250   };
01251 
01252   SparseSet<RootData> RootSet;
01253 
01254 public:
01255   SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
01256     RootSet.setUniverse(R.DFSNodeData.size());
01257   }
01258 
01259   /// Return true if this node been visited by the DFS traversal.
01260   ///
01261   /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
01262   /// ID. Later, SubtreeID is updated but remains valid.
01263   bool isVisited(const SUnit *SU) const {
01264     return R.DFSNodeData[SU->NodeNum].SubtreeID
01265       != SchedDFSResult::InvalidSubtreeID;
01266   }
01267 
01268   /// Initialize this node's instruction count. We don't need to flag the node
01269   /// visited until visitPostorder because the DAG cannot have cycles.
01270   void visitPreorder(const SUnit *SU) {
01271     R.DFSNodeData[SU->NodeNum].InstrCount =
01272       SU->getInstr()->isTransient() ? 0 : 1;
01273   }
01274 
01275   /// Called once for each node after all predecessors are visited. Revisit this
01276   /// node's predecessors and potentially join them now that we know the ILP of
01277   /// the other predecessors.
01278   void visitPostorderNode(const SUnit *SU) {
01279     // Mark this node as the root of a subtree. It may be joined with its
01280     // successors later.
01281     R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
01282     RootData RData(SU->NodeNum);
01283     RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
01284 
01285     // If any predecessors are still in their own subtree, they either cannot be
01286     // joined or are large enough to remain separate. If this parent node's
01287     // total instruction count is not greater than a child subtree by at least
01288     // the subtree limit, then try to join it now since splitting subtrees is
01289     // only useful if multiple high-pressure paths are possible.
01290     unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
01291     for (SUnit::const_pred_iterator
01292            PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
01293       if (PI->getKind() != SDep::Data)
01294         continue;
01295       unsigned PredNum = PI->getSUnit()->NodeNum;
01296       if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
01297         joinPredSubtree(*PI, SU, /*CheckLimit=*/false);
01298 
01299       // Either link or merge the TreeData entry from the child to the parent.
01300       if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
01301         // If the predecessor's parent is invalid, this is a tree edge and the
01302         // current node is the parent.
01303         if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
01304           RootSet[PredNum].ParentNodeID = SU->NodeNum;
01305       }
01306       else if (RootSet.count(PredNum)) {
01307         // The predecessor is not a root, but is still in the root set. This
01308         // must be the new parent that it was just joined to. Note that
01309         // RootSet[PredNum].ParentNodeID may either be invalid or may still be
01310         // set to the original parent.
01311         RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
01312         RootSet.erase(PredNum);
01313       }
01314     }
01315     RootSet[SU->NodeNum] = RData;
01316   }
01317 
01318   /// Called once for each tree edge after calling visitPostOrderNode on the
01319   /// predecessor. Increment the parent node's instruction count and
01320   /// preemptively join this subtree to its parent's if it is small enough.
01321   void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
01322     R.DFSNodeData[Succ->NodeNum].InstrCount
01323       += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
01324     joinPredSubtree(PredDep, Succ);
01325   }
01326 
01327   /// Add a connection for cross edges.
01328   void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
01329     ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
01330   }
01331 
01332   /// Set each node's subtree ID to the representative ID and record connections
01333   /// between trees.
01334   void finalize() {
01335     SubtreeClasses.compress();
01336     R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
01337     assert(SubtreeClasses.getNumClasses() == RootSet.size()
01338            && "number of roots should match trees");
01339     for (SparseSet<RootData>::const_iterator
01340            RI = RootSet.begin(), RE = RootSet.end(); RI != RE; ++RI) {
01341       unsigned TreeID = SubtreeClasses[RI->NodeID];
01342       if (RI->ParentNodeID != SchedDFSResult::InvalidSubtreeID)
01343         R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[RI->ParentNodeID];
01344       R.DFSTreeData[TreeID].SubInstrCount = RI->SubInstrCount;
01345       // Note that SubInstrCount may be greater than InstrCount if we joined
01346       // subtrees across a cross edge. InstrCount will be attributed to the
01347       // original parent, while SubInstrCount will be attributed to the joined
01348       // parent.
01349     }
01350     R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
01351     R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
01352     DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
01353     for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
01354       R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
01355       DEBUG(dbgs() << "  SU(" << Idx << ") in tree "
01356             << R.DFSNodeData[Idx].SubtreeID << '\n');
01357     }
01358     for (std::vector<std::pair<const SUnit*, const SUnit*> >::const_iterator
01359            I = ConnectionPairs.begin(), E = ConnectionPairs.end();
01360          I != E; ++I) {
01361       unsigned PredTree = SubtreeClasses[I->first->NodeNum];
01362       unsigned SuccTree = SubtreeClasses[I->second->NodeNum];
01363       if (PredTree == SuccTree)
01364         continue;
01365       unsigned Depth = I->first->getDepth();
01366       addConnection(PredTree, SuccTree, Depth);
01367       addConnection(SuccTree, PredTree, Depth);
01368     }
01369   }
01370 
01371 protected:
01372   /// Join the predecessor subtree with the successor that is its DFS
01373   /// parent. Apply some heuristics before joining.
01374   bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
01375                        bool CheckLimit = true) {
01376     assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
01377 
01378     // Check if the predecessor is already joined.
01379     const SUnit *PredSU = PredDep.getSUnit();
01380     unsigned PredNum = PredSU->NodeNum;
01381     if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
01382       return false;
01383 
01384     // Four is the magic number of successors before a node is considered a
01385     // pinch point.
01386     unsigned NumDataSucs = 0;
01387     for (SUnit::const_succ_iterator SI = PredSU->Succs.begin(),
01388            SE = PredSU->Succs.end(); SI != SE; ++SI) {
01389       if (SI->getKind() == SDep::Data) {
01390         if (++NumDataSucs >= 4)
01391           return false;
01392       }
01393     }
01394     if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
01395       return false;
01396     R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
01397     SubtreeClasses.join(Succ->NodeNum, PredNum);
01398     return true;
01399   }
01400 
01401   /// Called by finalize() to record a connection between trees.
01402   void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
01403     if (!Depth)
01404       return;
01405 
01406     do {
01407       SmallVectorImpl<SchedDFSResult::Connection> &Connections =
01408         R.SubtreeConnections[FromTree];
01409       for (SmallVectorImpl<SchedDFSResult::Connection>::iterator
01410              I = Connections.begin(), E = Connections.end(); I != E; ++I) {
01411         if (I->TreeID == ToTree) {
01412           I->Level = std::max(I->Level, Depth);
01413           return;
01414         }
01415       }
01416       Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
01417       FromTree = R.DFSTreeData[FromTree].ParentTreeID;
01418     } while (FromTree != SchedDFSResult::InvalidSubtreeID);
01419   }
01420 };
01421 } // namespace llvm
01422 
01423 namespace {
01424 /// \brief Manage the stack used by a reverse depth-first search over the DAG.
01425 class SchedDAGReverseDFS {
01426   std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
01427 public:
01428   bool isComplete() const { return DFSStack.empty(); }
01429 
01430   void follow(const SUnit *SU) {
01431     DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
01432   }
01433   void advance() { ++DFSStack.back().second; }
01434 
01435   const SDep *backtrack() {
01436     DFSStack.pop_back();
01437     return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
01438   }
01439 
01440   const SUnit *getCurr() const { return DFSStack.back().first; }
01441 
01442   SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
01443 
01444   SUnit::const_pred_iterator getPredEnd() const {
01445     return getCurr()->Preds.end();
01446   }
01447 };
01448 } // anonymous
01449 
01450 static bool hasDataSucc(const SUnit *SU) {
01451   for (SUnit::const_succ_iterator
01452          SI = SU->Succs.begin(), SE = SU->Succs.end(); SI != SE; ++SI) {
01453     if (SI->getKind() == SDep::Data && !SI->getSUnit()->isBoundaryNode())
01454       return true;
01455   }
01456   return false;
01457 }
01458 
01459 /// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
01460 /// search from this root.
01461 void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
01462   if (!IsBottomUp)
01463     llvm_unreachable("Top-down ILP metric is unimplemnted");
01464 
01465   SchedDFSImpl Impl(*this);
01466   for (ArrayRef<SUnit>::const_iterator
01467          SI = SUnits.begin(), SE = SUnits.end(); SI != SE; ++SI) {
01468     const SUnit *SU = &*SI;
01469     if (Impl.isVisited(SU) || hasDataSucc(SU))
01470       continue;
01471 
01472     SchedDAGReverseDFS DFS;
01473     Impl.visitPreorder(SU);
01474     DFS.follow(SU);
01475     for (;;) {
01476       // Traverse the leftmost path as far as possible.
01477       while (DFS.getPred() != DFS.getPredEnd()) {
01478         const SDep &PredDep = *DFS.getPred();
01479         DFS.advance();
01480         // Ignore non-data edges.
01481         if (PredDep.getKind() != SDep::Data
01482             || PredDep.getSUnit()->isBoundaryNode()) {
01483           continue;
01484         }
01485         // An already visited edge is a cross edge, assuming an acyclic DAG.
01486         if (Impl.isVisited(PredDep.getSUnit())) {
01487           Impl.visitCrossEdge(PredDep, DFS.getCurr());
01488           continue;
01489         }
01490         Impl.visitPreorder(PredDep.getSUnit());
01491         DFS.follow(PredDep.getSUnit());
01492       }
01493       // Visit the top of the stack in postorder and backtrack.
01494       const SUnit *Child = DFS.getCurr();
01495       const SDep *PredDep = DFS.backtrack();
01496       Impl.visitPostorderNode(Child);
01497       if (PredDep)
01498         Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
01499       if (DFS.isComplete())
01500         break;
01501     }
01502   }
01503   Impl.finalize();
01504 }
01505 
01506 /// The root of the given SubtreeID was just scheduled. For all subtrees
01507 /// connected to this tree, record the depth of the connection so that the
01508 /// nearest connected subtrees can be prioritized.
01509 void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
01510   for (SmallVectorImpl<Connection>::const_iterator
01511          I = SubtreeConnections[SubtreeID].begin(),
01512          E = SubtreeConnections[SubtreeID].end(); I != E; ++I) {
01513     SubtreeConnectLevels[I->TreeID] =
01514       std::max(SubtreeConnectLevels[I->TreeID], I->Level);
01515     DEBUG(dbgs() << "  Tree: " << I->TreeID
01516           << " @" << SubtreeConnectLevels[I->TreeID] << '\n');
01517   }
01518 }
01519 
01520 LLVM_DUMP_METHOD
01521 void ILPValue::print(raw_ostream &OS) const {
01522   OS << InstrCount << " / " << Length << " = ";
01523   if (!Length)
01524     OS << "BADILP";
01525   else
01526     OS << format("%g", ((double)InstrCount / Length));
01527 }
01528 
01529 LLVM_DUMP_METHOD
01530 void ILPValue::dump() const {
01531   dbgs() << *this << '\n';
01532 }
01533 
01534 namespace llvm {
01535 
01536 LLVM_DUMP_METHOD
01537 raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
01538   Val.print(OS);
01539   return OS;
01540 }
01541 
01542 } // namespace llvm