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 DAG construction"));
00048 
00049 static cl::opt<bool> UseTBAA("use-tbaa-in-sched-mi", cl::Hidden,
00050     cl::init(true), cl::desc("Enable use of TBAA during MI DAG construction"));
00051 
00052 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
00053                                      const MachineLoopInfo *mli,
00054                                      bool IsPostRAFlag, bool RemoveKillFlags,
00055                                      LiveIntervals *lis)
00056     : ScheduleDAG(mf), MLI(mli), MFI(mf.getFrameInfo()), LIS(lis),
00057       IsPostRA(IsPostRAFlag), RemoveKillFlags(RemoveKillFlags),
00058       CanHandleTerminators(false), FirstDbgValue(nullptr) {
00059   assert((IsPostRA || LIS) && "PreRA scheduling requires LiveIntervals");
00060   DbgValues.clear();
00061   assert(!(IsPostRA && MRI.getNumVirtRegs()) &&
00062          "Virtual registers must be removed prior to PostRA scheduling");
00063 
00064   const TargetSubtargetInfo &ST = mf.getSubtarget();
00065   SchedModel.init(ST.getSchedModel(), &ST, TII);
00066 }
00067 
00068 /// getUnderlyingObjectFromInt - This is the function that does the work of
00069 /// looking through basic ptrtoint+arithmetic+inttoptr sequences.
00070 static const Value *getUnderlyingObjectFromInt(const Value *V) {
00071   do {
00072     if (const Operator *U = dyn_cast<Operator>(V)) {
00073       // If we find a ptrtoint, we can transfer control back to the
00074       // regular getUnderlyingObjectFromInt.
00075       if (U->getOpcode() == Instruction::PtrToInt)
00076         return U->getOperand(0);
00077       // If we find an add of a constant, a multiplied value, or a phi, it's
00078       // likely that the other operand will lead us to the base
00079       // object. We don't have to worry about the case where the
00080       // object address is somehow being computed by the multiply,
00081       // because our callers only care when the result is an
00082       // identifiable object.
00083       if (U->getOpcode() != Instruction::Add ||
00084           (!isa<ConstantInt>(U->getOperand(1)) &&
00085            Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
00086            !isa<PHINode>(U->getOperand(1))))
00087         return V;
00088       V = U->getOperand(0);
00089     } else {
00090       return V;
00091     }
00092     assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
00093   } while (1);
00094 }
00095 
00096 /// getUnderlyingObjects - This is a wrapper around GetUnderlyingObjects
00097 /// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
00098 static void getUnderlyingObjects(const Value *V,
00099                                  SmallVectorImpl<Value *> &Objects) {
00100   SmallPtrSet<const Value *, 16> Visited;
00101   SmallVector<const Value *, 4> Working(1, V);
00102   do {
00103     V = Working.pop_back_val();
00104 
00105     SmallVector<Value *, 4> Objs;
00106     GetUnderlyingObjects(const_cast<Value *>(V), Objs);
00107 
00108     for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), IE = Objs.end();
00109          I != IE; ++I) {
00110       V = *I;
00111       if (!Visited.insert(V).second)
00112         continue;
00113       if (Operator::getOpcode(V) == Instruction::IntToPtr) {
00114         const Value *O =
00115           getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
00116         if (O->getType()->isPointerTy()) {
00117           Working.push_back(O);
00118           continue;
00119         }
00120       }
00121       Objects.push_back(const_cast<Value *>(V));
00122     }
00123   } while (!Working.empty());
00124 }
00125 
00126 typedef PointerUnion<const Value *, const PseudoSourceValue *> ValueType;
00127 typedef SmallVector<PointerIntPair<ValueType, 1, bool>, 4>
00128 UnderlyingObjectsVector;
00129 
00130 /// getUnderlyingObjectsForInstr - If this machine instr has memory reference
00131 /// information and it can be tracked to a normal reference to a known
00132 /// object, return the Value for that object.
00133 static void getUnderlyingObjectsForInstr(const MachineInstr *MI,
00134                                          const MachineFrameInfo *MFI,
00135                                          UnderlyingObjectsVector &Objects) {
00136   if (!MI->hasOneMemOperand() ||
00137       (!(*MI->memoperands_begin())->getValue() &&
00138        !(*MI->memoperands_begin())->getPseudoValue()) ||
00139       (*MI->memoperands_begin())->isVolatile())
00140     return;
00141 
00142   if (const PseudoSourceValue *PSV =
00143       (*MI->memoperands_begin())->getPseudoValue()) {
00144     // For now, ignore PseudoSourceValues which may alias LLVM IR values
00145     // because the code that uses this function has no way to cope with
00146     // such aliases.
00147     if (!PSV->isAliased(MFI)) {
00148       bool MayAlias = PSV->mayAlias(MFI);
00149       Objects.push_back(UnderlyingObjectsVector::value_type(PSV, MayAlias));
00150     }
00151     return;
00152   }
00153 
00154   const Value *V = (*MI->memoperands_begin())->getValue();
00155   if (!V)
00156     return;
00157 
00158   SmallVector<Value *, 4> Objs;
00159   getUnderlyingObjects(V, Objs);
00160 
00161   for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), IE = Objs.end();
00162          I != IE; ++I) {
00163     V = *I;
00164 
00165     if (!isIdentifiedObject(V)) {
00166       Objects.clear();
00167       return;
00168     }
00169 
00170     Objects.push_back(UnderlyingObjectsVector::value_type(V, true));
00171   }
00172 }
00173 
00174 void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
00175   BB = bb;
00176 }
00177 
00178 void ScheduleDAGInstrs::finishBlock() {
00179   // Subclasses should no longer refer to the old block.
00180   BB = nullptr;
00181 }
00182 
00183 /// Initialize the DAG and common scheduler state for the current scheduling
00184 /// region. This does not actually create the DAG, only clears it. The
00185 /// scheduling driver may call BuildSchedGraph multiple times per scheduling
00186 /// region.
00187 void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
00188                                     MachineBasicBlock::iterator begin,
00189                                     MachineBasicBlock::iterator end,
00190                                     unsigned regioninstrs) {
00191   assert(bb == BB && "startBlock should set BB");
00192   RegionBegin = begin;
00193   RegionEnd = end;
00194   NumRegionInstrs = regioninstrs;
00195 }
00196 
00197 /// Close the current scheduling region. Don't clear any state in case the
00198 /// driver wants to refer to the previous scheduling region.
00199 void ScheduleDAGInstrs::exitRegion() {
00200   // Nothing to do.
00201 }
00202 
00203 /// addSchedBarrierDeps - Add dependencies from instructions in the current
00204 /// list of instructions being scheduled to scheduling barrier by adding
00205 /// the exit SU to the register defs and use list. This is because we want to
00206 /// make sure instructions which define registers that are either used by
00207 /// the terminator or are live-out are properly scheduled. This is
00208 /// especially important when the definition latency of the return value(s)
00209 /// are too high to be hidden by the branch or when the liveout registers
00210 /// used by instructions in the fallthrough block.
00211 void ScheduleDAGInstrs::addSchedBarrierDeps() {
00212   MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : nullptr;
00213   ExitSU.setInstr(ExitMI);
00214   bool AllDepKnown = ExitMI &&
00215     (ExitMI->isCall() || ExitMI->isBarrier());
00216   if (ExitMI && AllDepKnown) {
00217     // If it's a call or a barrier, add dependencies on the defs and uses of
00218     // instruction.
00219     for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
00220       const MachineOperand &MO = ExitMI->getOperand(i);
00221       if (!MO.isReg() || MO.isDef()) continue;
00222       unsigned Reg = MO.getReg();
00223       if (Reg == 0) continue;
00224 
00225       if (TRI->isPhysicalRegister(Reg))
00226         Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
00227       else {
00228         assert(!IsPostRA && "Virtual register encountered after regalloc.");
00229         if (MO.readsReg()) // ignore undef operands
00230           addVRegUseDeps(&ExitSU, i);
00231       }
00232     }
00233   } else {
00234     // For others, e.g. fallthrough, conditional branch, assume the exit
00235     // uses all the registers that are livein to the successor blocks.
00236     assert(Uses.empty() && "Uses in set before adding deps?");
00237     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
00238            SE = BB->succ_end(); SI != SE; ++SI)
00239       for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
00240              E = (*SI)->livein_end(); I != E; ++I) {
00241         unsigned Reg = *I;
00242         if (!Uses.contains(Reg))
00243           Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
00244       }
00245   }
00246 }
00247 
00248 /// MO is an operand of SU's instruction that defines a physical register. Add
00249 /// data dependencies from SU to any uses of the physical register.
00250 void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
00251   const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
00252   assert(MO.isDef() && "expect physreg def");
00253 
00254   // Ask the target if address-backscheduling is desirable, and if so how much.
00255   const TargetSubtargetInfo &ST = MF.getSubtarget();
00256 
00257   for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
00258        Alias.isValid(); ++Alias) {
00259     if (!Uses.contains(*Alias))
00260       continue;
00261     for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
00262       SUnit *UseSU = I->SU;
00263       if (UseSU == SU)
00264         continue;
00265 
00266       // Adjust the dependence latency using operand def/use information,
00267       // then allow the target to perform its own adjustments.
00268       int UseOp = I->OpIdx;
00269       MachineInstr *RegUse = nullptr;
00270       SDep Dep;
00271       if (UseOp < 0)
00272         Dep = SDep(SU, SDep::Artificial);
00273       else {
00274         // Set the hasPhysRegDefs only for physreg defs that have a use within
00275         // the scheduling region.
00276         SU->hasPhysRegDefs = true;
00277         Dep = SDep(SU, SDep::Data, *Alias);
00278         RegUse = UseSU->getInstr();
00279       }
00280       Dep.setLatency(
00281         SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, RegUse,
00282                                          UseOp));
00283 
00284       ST.adjustSchedDependency(SU, UseSU, Dep);
00285       UseSU->addPred(Dep);
00286     }
00287   }
00288 }
00289 
00290 /// addPhysRegDeps - Add register dependencies (data, anti, and output) from
00291 /// this SUnit to following instructions in the same scheduling region that
00292 /// depend the physical register referenced at OperIdx.
00293 void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
00294   MachineInstr *MI = SU->getInstr();
00295   MachineOperand &MO = MI->getOperand(OperIdx);
00296 
00297   // Optionally add output and anti dependencies. For anti
00298   // dependencies we use a latency of 0 because for a multi-issue
00299   // target we want to allow the defining instruction to issue
00300   // in the same cycle as the using instruction.
00301   // TODO: Using a latency of 1 here for output dependencies assumes
00302   //       there's no cost for reusing registers.
00303   SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
00304   for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
00305        Alias.isValid(); ++Alias) {
00306     if (!Defs.contains(*Alias))
00307       continue;
00308     for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
00309       SUnit *DefSU = I->SU;
00310       if (DefSU == &ExitSU)
00311         continue;
00312       if (DefSU != SU &&
00313           (Kind != SDep::Output || !MO.isDead() ||
00314            !DefSU->getInstr()->registerDefIsDead(*Alias))) {
00315         if (Kind == SDep::Anti)
00316           DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
00317         else {
00318           SDep Dep(SU, Kind, /*Reg=*/*Alias);
00319           Dep.setLatency(
00320             SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
00321           DefSU->addPred(Dep);
00322         }
00323       }
00324     }
00325   }
00326 
00327   if (!MO.isDef()) {
00328     SU->hasPhysRegUses = true;
00329     // Either insert a new Reg2SUnits entry with an empty SUnits list, or
00330     // retrieve the existing SUnits list for this register's uses.
00331     // Push this SUnit on the use list.
00332     Uses.insert(PhysRegSUOper(SU, OperIdx, MO.getReg()));
00333     if (RemoveKillFlags)
00334       MO.setIsKill(false);
00335   }
00336   else {
00337     addPhysRegDataDeps(SU, OperIdx);
00338     unsigned Reg = MO.getReg();
00339 
00340     // clear this register's use list
00341     if (Uses.contains(Reg))
00342       Uses.eraseAll(Reg);
00343 
00344     if (!MO.isDead()) {
00345       Defs.eraseAll(Reg);
00346     } else if (SU->isCall) {
00347       // Calls will not be reordered because of chain dependencies (see
00348       // below). Since call operands are dead, calls may continue to be added
00349       // to the DefList making dependence checking quadratic in the size of
00350       // the block. Instead, we leave only one call at the back of the
00351       // DefList.
00352       Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
00353       Reg2SUnitsMap::iterator B = P.first;
00354       Reg2SUnitsMap::iterator I = P.second;
00355       for (bool isBegin = I == B; !isBegin; /* empty */) {
00356         isBegin = (--I) == B;
00357         if (!I->SU->isCall)
00358           break;
00359         I = Defs.erase(I);
00360       }
00361     }
00362 
00363     // Defs are pushed in the order they are visited and never reordered.
00364     Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
00365   }
00366 }
00367 
00368 /// addVRegDefDeps - Add register output and data dependencies from this SUnit
00369 /// to instructions that occur later in the same scheduling region if they read
00370 /// from or write to the virtual register defined at OperIdx.
00371 ///
00372 /// TODO: Hoist loop induction variable increments. This has to be
00373 /// reevaluated. Generally, IV scheduling should be done before coalescing.
00374 void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
00375   const MachineInstr *MI = SU->getInstr();
00376   unsigned Reg = MI->getOperand(OperIdx).getReg();
00377 
00378   // Singly defined vregs do not have output/anti dependencies.
00379   // The current operand is a def, so we have at least one.
00380   // Check here if there are any others...
00381   if (MRI.hasOneDef(Reg))
00382     return;
00383 
00384   // Add output dependence to the next nearest def of this vreg.
00385   //
00386   // Unless this definition is dead, the output dependence should be
00387   // transitively redundant with antidependencies from this definition's
00388   // uses. We're conservative for now until we have a way to guarantee the uses
00389   // are not eliminated sometime during scheduling. The output dependence edge
00390   // is also useful if output latency exceeds def-use latency.
00391   VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
00392   if (DefI == VRegDefs.end())
00393     VRegDefs.insert(VReg2SUnit(Reg, SU));
00394   else {
00395     SUnit *DefSU = DefI->SU;
00396     if (DefSU != SU && DefSU != &ExitSU) {
00397       SDep Dep(SU, SDep::Output, Reg);
00398       Dep.setLatency(
00399         SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
00400       DefSU->addPred(Dep);
00401     }
00402     DefI->SU = SU;
00403   }
00404 }
00405 
00406 /// addVRegUseDeps - Add a register data dependency if the instruction that
00407 /// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
00408 /// register antidependency from this SUnit to instructions that occur later in
00409 /// the same scheduling region if they write the virtual register.
00410 ///
00411 /// TODO: Handle ExitSU "uses" properly.
00412 void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
00413   MachineInstr *MI = SU->getInstr();
00414   unsigned Reg = MI->getOperand(OperIdx).getReg();
00415 
00416   // Record this local VReg use.
00417   VReg2UseMap::iterator UI = VRegUses.find(Reg);
00418   for (; UI != VRegUses.end(); ++UI) {
00419     if (UI->SU == SU)
00420       break;
00421   }
00422   if (UI == VRegUses.end())
00423     VRegUses.insert(VReg2SUnit(Reg, SU));
00424 
00425   // Lookup this operand's reaching definition.
00426   assert(LIS && "vreg dependencies requires LiveIntervals");
00427   LiveQueryResult LRQ
00428     = LIS->getInterval(Reg).Query(LIS->getInstructionIndex(MI));
00429   VNInfo *VNI = LRQ.valueIn();
00430 
00431   // VNI will be valid because MachineOperand::readsReg() is checked by caller.
00432   assert(VNI && "No value to read by operand");
00433   MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def);
00434   // Phis and other noninstructions (after coalescing) have a NULL Def.
00435   if (Def) {
00436     SUnit *DefSU = getSUnit(Def);
00437     if (DefSU) {
00438       // The reaching Def lives within this scheduling region.
00439       // Create a data dependence.
00440       SDep dep(DefSU, SDep::Data, Reg);
00441       // Adjust the dependence latency using operand def/use information, then
00442       // allow the target to perform its own adjustments.
00443       int DefOp = Def->findRegisterDefOperandIdx(Reg);
00444       dep.setLatency(SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx));
00445 
00446       const TargetSubtargetInfo &ST = MF.getSubtarget();
00447       ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
00448       SU->addPred(dep);
00449     }
00450   }
00451 
00452   // Add antidependence to the following def of the vreg it uses.
00453   VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
00454   if (DefI != VRegDefs.end() && DefI->SU != SU)
00455     DefI->SU->addPred(SDep(SU, SDep::Anti, Reg));
00456 }
00457 
00458 /// Return true if MI is an instruction we are unable to reason about
00459 /// (like a call or something with unmodeled side effects).
00460 static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
00461   if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
00462       (MI->hasOrderedMemoryRef() &&
00463        (!MI->mayLoad() || !MI->isInvariantLoad(AA))))
00464     return true;
00465   return false;
00466 }
00467 
00468 // This MI might have either incomplete info, or known to be unsafe
00469 // to deal with (i.e. volatile object).
00470 static inline bool isUnsafeMemoryObject(MachineInstr *MI,
00471                                         const MachineFrameInfo *MFI) {
00472   if (!MI || MI->memoperands_empty())
00473     return true;
00474   // We purposefully do no check for hasOneMemOperand() here
00475   // in hope to trigger an assert downstream in order to
00476   // finish implementation.
00477   if ((*MI->memoperands_begin())->isVolatile() ||
00478        MI->hasUnmodeledSideEffects())
00479     return true;
00480 
00481   if ((*MI->memoperands_begin())->getPseudoValue()) {
00482     // Similarly to getUnderlyingObjectForInstr:
00483     // For now, ignore PseudoSourceValues which may alias LLVM IR values
00484     // because the code that uses this function has no way to cope with
00485     // such aliases.
00486     return true;
00487   }
00488 
00489   const Value *V = (*MI->memoperands_begin())->getValue();
00490   if (!V)
00491     return true;
00492 
00493   SmallVector<Value *, 4> Objs;
00494   getUnderlyingObjects(V, Objs);
00495   for (SmallVectorImpl<Value *>::iterator I = Objs.begin(),
00496          IE = Objs.end(); I != IE; ++I) {
00497     // Does this pointer refer to a distinct and identifiable object?
00498     if (!isIdentifiedObject(*I))
00499       return true;
00500   }
00501 
00502   return false;
00503 }
00504 
00505 /// This returns true if the two MIs need a chain edge betwee them.
00506 /// If these are not even memory operations, we still may need
00507 /// chain deps between them. The question really is - could
00508 /// these two MIs be reordered during scheduling from memory dependency
00509 /// point of view.
00510 static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
00511                              MachineInstr *MIa,
00512                              MachineInstr *MIb) {
00513   const MachineFunction *MF = MIa->getParent()->getParent();
00514   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
00515 
00516   // Cover a trivial case - no edge is need to itself.
00517   if (MIa == MIb)
00518     return false;
00519  
00520   // Let the target decide if memory accesses cannot possibly overlap.
00521   if ((MIa->mayLoad() || MIa->mayStore()) &&
00522       (MIb->mayLoad() || MIb->mayStore()))
00523     if (TII->areMemAccessesTriviallyDisjoint(MIa, MIb, AA))
00524       return false;
00525 
00526   // FIXME: Need to handle multiple memory operands to support all targets.
00527   if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
00528     return true;
00529 
00530   if (isUnsafeMemoryObject(MIa, MFI) || isUnsafeMemoryObject(MIb, MFI))
00531     return true;
00532 
00533   // If we are dealing with two "normal" loads, we do not need an edge
00534   // between them - they could be reordered.
00535   if (!MIa->mayStore() && !MIb->mayStore())
00536     return false;
00537 
00538   // To this point analysis is generic. From here on we do need AA.
00539   if (!AA)
00540     return true;
00541 
00542   MachineMemOperand *MMOa = *MIa->memoperands_begin();
00543   MachineMemOperand *MMOb = *MIb->memoperands_begin();
00544 
00545   if (!MMOa->getValue() || !MMOb->getValue())
00546     return true;
00547 
00548   // The following interface to AA is fashioned after DAGCombiner::isAlias
00549   // and operates with MachineMemOperand offset with some important
00550   // assumptions:
00551   //   - LLVM fundamentally assumes flat address spaces.
00552   //   - MachineOperand offset can *only* result from legalization and
00553   //     cannot affect queries other than the trivial case of overlap
00554   //     checking.
00555   //   - These offsets never wrap and never step outside
00556   //     of allocated objects.
00557   //   - There should never be any negative offsets here.
00558   //
00559   // FIXME: Modify API to hide this math from "user"
00560   // FIXME: Even before we go to AA we can reason locally about some
00561   // memory objects. It can save compile time, and possibly catch some
00562   // corner cases not currently covered.
00563 
00564   assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
00565   assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
00566 
00567   int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
00568   int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
00569   int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
00570 
00571   AliasAnalysis::AliasResult AAResult = AA->alias(
00572       AliasAnalysis::Location(MMOa->getValue(), Overlapa,
00573                               UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
00574       AliasAnalysis::Location(MMOb->getValue(), Overlapb,
00575                               UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
00576 
00577   return (AAResult != AliasAnalysis::NoAlias);
00578 }
00579 
00580 /// This recursive function iterates over chain deps of SUb looking for
00581 /// "latest" node that needs a chain edge to SUa.
00582 static unsigned
00583 iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI,
00584                  SUnit *SUa, SUnit *SUb, SUnit *ExitSU, unsigned *Depth,
00585                  SmallPtrSetImpl<const SUnit*> &Visited) {
00586   if (!SUa || !SUb || SUb == ExitSU)
00587     return *Depth;
00588 
00589   // Remember visited nodes.
00590   if (!Visited.insert(SUb).second)
00591       return *Depth;
00592   // If there is _some_ dependency already in place, do not
00593   // descend any further.
00594   // TODO: Need to make sure that if that dependency got eliminated or ignored
00595   // for any reason in the future, we would not violate DAG topology.
00596   // Currently it does not happen, but makes an implicit assumption about
00597   // future implementation.
00598   //
00599   // Independently, if we encounter node that is some sort of global
00600   // object (like a call) we already have full set of dependencies to it
00601   // and we can stop descending.
00602   if (SUa->isSucc(SUb) ||
00603       isGlobalMemoryObject(AA, SUb->getInstr()))
00604     return *Depth;
00605 
00606   // If we do need an edge, or we have exceeded depth budget,
00607   // add that edge to the predecessors chain of SUb,
00608   // and stop descending.
00609   if (*Depth > 200 ||
00610       MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
00611     SUb->addPred(SDep(SUa, SDep::MayAliasMem));
00612     return *Depth;
00613   }
00614   // Track current depth.
00615   (*Depth)++;
00616   // Iterate over memory dependencies only.
00617   for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end();
00618        I != E; ++I)
00619     if (I->isNormalMemoryOrBarrier())
00620       iterateChainSucc (AA, MFI, SUa, I->getSUnit(), ExitSU, Depth, Visited);
00621   return *Depth;
00622 }
00623 
00624 /// This function assumes that "downward" from SU there exist
00625 /// tail/leaf of already constructed DAG. It iterates downward and
00626 /// checks whether SU can be aliasing any node dominated
00627 /// by it.
00628 static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI,
00629                             SUnit *SU, SUnit *ExitSU, std::set<SUnit *> &CheckList,
00630                             unsigned LatencyToLoad) {
00631   if (!SU)
00632     return;
00633 
00634   SmallPtrSet<const SUnit*, 16> Visited;
00635   unsigned Depth = 0;
00636 
00637   for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end();
00638        I != IE; ++I) {
00639     if (SU == *I)
00640       continue;
00641     if (MIsNeedChainEdge(AA, MFI, SU->getInstr(), (*I)->getInstr())) {
00642       SDep Dep(SU, SDep::MayAliasMem);
00643       Dep.setLatency(((*I)->getInstr()->mayLoad()) ? LatencyToLoad : 0);
00644       (*I)->addPred(Dep);
00645     }
00646 
00647     // Iterate recursively over all previously added memory chain
00648     // successors. 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->isNormalMemoryOrBarrier())
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 = MF.getSubtarget();
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 through 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       }
00995       adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
00996                       TrueMemOrderLatency);
00997     } else if (MI->mayLoad()) {
00998       bool MayAlias = true;
00999       if (MI->isInvariantLoad(AA)) {
01000         // Invariant load, no chain dependencies needed!
01001       } else {
01002         UnderlyingObjectsVector Objs;
01003         getUnderlyingObjectsForInstr(MI, MFI, Objs);
01004 
01005         if (Objs.empty()) {
01006           // A load with no underlying object. Depend on all
01007           // potentially aliasing stores.
01008           for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
01009                  AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
01010             for (unsigned i = 0, e = I->second.size(); i != e; ++i)
01011               addChainDependency(AAForDep, MFI, SU, I->second[i],
01012                                  RejectMemNodes);
01013 
01014           PendingLoads.push_back(SU);
01015           MayAlias = true;
01016         } else {
01017           MayAlias = false;
01018         }
01019 
01020         for (UnderlyingObjectsVector::iterator
01021              J = Objs.begin(), JE = Objs.end(); J != JE; ++J) {
01022           ValueType V = J->getPointer();
01023           bool ThisMayAlias = J->getInt();
01024 
01025           if (ThisMayAlias)
01026             MayAlias = true;
01027 
01028           // A load from a specific PseudoSourceValue. Add precise dependencies.
01029           MapVector<ValueType, std::vector<SUnit *> >::iterator I =
01030             ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
01031           MapVector<ValueType, std::vector<SUnit *> >::iterator IE =
01032             ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
01033           if (I != IE)
01034             for (unsigned i = 0, e = I->second.size(); i != e; ++i)
01035               addChainDependency(AAForDep, MFI, SU, I->second[i],
01036                                  RejectMemNodes, 0, true);
01037           if (ThisMayAlias)
01038             AliasMemUses[V].push_back(SU);
01039           else
01040             NonAliasMemUses[V].push_back(SU);
01041         }
01042         if (MayAlias)
01043           adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, /*Latency=*/0);
01044         // Add dependencies on alias and barrier chains, if needed.
01045         if (MayAlias && AliasChain)
01046           addChainDependency(AAForDep, MFI, SU, AliasChain, RejectMemNodes);
01047         if (BarrierChain)
01048           BarrierChain->addPred(SDep(SU, SDep::Barrier));
01049       }
01050     }
01051   }
01052   if (DbgMI)
01053     FirstDbgValue = DbgMI;
01054 
01055   Defs.clear();
01056   Uses.clear();
01057   VRegDefs.clear();
01058   PendingLoads.clear();
01059 }
01060 
01061 /// \brief Initialize register live-range state for updating kills.
01062 void ScheduleDAGInstrs::startBlockForKills(MachineBasicBlock *BB) {
01063   // Start with no live registers.
01064   LiveRegs.reset();
01065 
01066   // Examine the live-in regs of all successors.
01067   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
01068        SE = BB->succ_end(); SI != SE; ++SI) {
01069     for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
01070          E = (*SI)->livein_end(); I != E; ++I) {
01071       unsigned Reg = *I;
01072       // Repeat, for reg and all subregs.
01073       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
01074            SubRegs.isValid(); ++SubRegs)
01075         LiveRegs.set(*SubRegs);
01076     }
01077   }
01078 }
01079 
01080 bool ScheduleDAGInstrs::toggleKillFlag(MachineInstr *MI, MachineOperand &MO) {
01081   // Setting kill flag...
01082   if (!MO.isKill()) {
01083     MO.setIsKill(true);
01084     return false;
01085   }
01086 
01087   // If MO itself is live, clear the kill flag...
01088   if (LiveRegs.test(MO.getReg())) {
01089     MO.setIsKill(false);
01090     return false;
01091   }
01092 
01093   // If any subreg of MO is live, then create an imp-def for that
01094   // subreg and keep MO marked as killed.
01095   MO.setIsKill(false);
01096   bool AllDead = true;
01097   const unsigned SuperReg = MO.getReg();
01098   MachineInstrBuilder MIB(MF, MI);
01099   for (MCSubRegIterator SubRegs(SuperReg, TRI); SubRegs.isValid(); ++SubRegs) {
01100     if (LiveRegs.test(*SubRegs)) {
01101       MIB.addReg(*SubRegs, RegState::ImplicitDefine);
01102       AllDead = false;
01103     }
01104   }
01105 
01106   if(AllDead)
01107     MO.setIsKill(true);
01108   return false;
01109 }
01110 
01111 // FIXME: Reuse the LivePhysRegs utility for this.
01112 void ScheduleDAGInstrs::fixupKills(MachineBasicBlock *MBB) {
01113   DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
01114 
01115   LiveRegs.resize(TRI->getNumRegs());
01116   BitVector killedRegs(TRI->getNumRegs());
01117 
01118   startBlockForKills(MBB);
01119 
01120   // Examine block from end to start...
01121   unsigned Count = MBB->size();
01122   for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
01123        I != E; --Count) {
01124     MachineInstr *MI = --I;
01125     if (MI->isDebugValue())
01126       continue;
01127 
01128     // Update liveness.  Registers that are defed but not used in this
01129     // instruction are now dead. Mark register and all subregs as they
01130     // are completely defined.
01131     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01132       MachineOperand &MO = MI->getOperand(i);
01133       if (MO.isRegMask())
01134         LiveRegs.clearBitsNotInMask(MO.getRegMask());
01135       if (!MO.isReg()) continue;
01136       unsigned Reg = MO.getReg();
01137       if (Reg == 0) continue;
01138       if (!MO.isDef()) continue;
01139       // Ignore two-addr defs.
01140       if (MI->isRegTiedToUseOperand(i)) continue;
01141 
01142       // Repeat for reg and all subregs.
01143       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
01144            SubRegs.isValid(); ++SubRegs)
01145         LiveRegs.reset(*SubRegs);
01146     }
01147 
01148     // Examine all used registers and set/clear kill flag. When a
01149     // register is used multiple times we only set the kill flag on
01150     // the first use. Don't set kill flags on undef operands.
01151     killedRegs.reset();
01152     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01153       MachineOperand &MO = MI->getOperand(i);
01154       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
01155       unsigned Reg = MO.getReg();
01156       if ((Reg == 0) || MRI.isReserved(Reg)) continue;
01157 
01158       bool kill = false;
01159       if (!killedRegs.test(Reg)) {
01160         kill = true;
01161         // A register is not killed if any subregs are live...
01162         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
01163           if (LiveRegs.test(*SubRegs)) {
01164             kill = false;
01165             break;
01166           }
01167         }
01168 
01169         // If subreg is not live, then register is killed if it became
01170         // live in this instruction
01171         if (kill)
01172           kill = !LiveRegs.test(Reg);
01173       }
01174 
01175       if (MO.isKill() != kill) {
01176         DEBUG(dbgs() << "Fixing " << MO << " in ");
01177         // Warning: toggleKillFlag may invalidate MO.
01178         toggleKillFlag(MI, MO);
01179         DEBUG(MI->dump());
01180       }
01181 
01182       killedRegs.set(Reg);
01183     }
01184 
01185     // Mark any used register (that is not using undef) and subregs as
01186     // now live...
01187     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
01188       MachineOperand &MO = MI->getOperand(i);
01189       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
01190       unsigned Reg = MO.getReg();
01191       if ((Reg == 0) || MRI.isReserved(Reg)) continue;
01192 
01193       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
01194            SubRegs.isValid(); ++SubRegs)
01195         LiveRegs.set(*SubRegs);
01196     }
01197   }
01198 }
01199 
01200 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
01201 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01202   SU->getInstr()->dump();
01203 #endif
01204 }
01205 
01206 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
01207   std::string s;
01208   raw_string_ostream oss(s);
01209   if (SU == &EntrySU)
01210     oss << "<entry>";
01211   else if (SU == &ExitSU)
01212     oss << "<exit>";
01213   else
01214     SU->getInstr()->print(oss, /*SkipOpers=*/true);
01215   return oss.str();
01216 }
01217 
01218 /// Return the basic block label. It is not necessarilly unique because a block
01219 /// contains multiple scheduling regions. But it is fine for visualization.
01220 std::string ScheduleDAGInstrs::getDAGName() const {
01221   return "dag." + BB->getFullName();
01222 }
01223 
01224 //===----------------------------------------------------------------------===//
01225 // SchedDFSResult Implementation
01226 //===----------------------------------------------------------------------===//
01227 
01228 namespace llvm {
01229 /// \brief Internal state used to compute SchedDFSResult.
01230 class SchedDFSImpl {
01231   SchedDFSResult &R;
01232 
01233   /// Join DAG nodes into equivalence classes by their subtree.
01234   IntEqClasses SubtreeClasses;
01235   /// List PredSU, SuccSU pairs that represent data edges between subtrees.
01236   std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs;
01237 
01238   struct RootData {
01239     unsigned NodeID;
01240     unsigned ParentNodeID;  // Parent node (member of the parent subtree).
01241     unsigned SubInstrCount; // Instr count in this tree only, not children.
01242 
01243     RootData(unsigned id): NodeID(id),
01244                            ParentNodeID(SchedDFSResult::InvalidSubtreeID),
01245                            SubInstrCount(0) {}
01246 
01247     unsigned getSparseSetIndex() const { return NodeID; }
01248   };
01249 
01250   SparseSet<RootData> RootSet;
01251 
01252 public:
01253   SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
01254     RootSet.setUniverse(R.DFSNodeData.size());
01255   }
01256 
01257   /// Return true if this node been visited by the DFS traversal.
01258   ///
01259   /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
01260   /// ID. Later, SubtreeID is updated but remains valid.
01261   bool isVisited(const SUnit *SU) const {
01262     return R.DFSNodeData[SU->NodeNum].SubtreeID
01263       != SchedDFSResult::InvalidSubtreeID;
01264   }
01265 
01266   /// Initialize this node's instruction count. We don't need to flag the node
01267   /// visited until visitPostorder because the DAG cannot have cycles.
01268   void visitPreorder(const SUnit *SU) {
01269     R.DFSNodeData[SU->NodeNum].InstrCount =
01270       SU->getInstr()->isTransient() ? 0 : 1;
01271   }
01272 
01273   /// Called once for each node after all predecessors are visited. Revisit this
01274   /// node's predecessors and potentially join them now that we know the ILP of
01275   /// the other predecessors.
01276   void visitPostorderNode(const SUnit *SU) {
01277     // Mark this node as the root of a subtree. It may be joined with its
01278     // successors later.
01279     R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
01280     RootData RData(SU->NodeNum);
01281     RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
01282 
01283     // If any predecessors are still in their own subtree, they either cannot be
01284     // joined or are large enough to remain separate. If this parent node's
01285     // total instruction count is not greater than a child subtree by at least
01286     // the subtree limit, then try to join it now since splitting subtrees is
01287     // only useful if multiple high-pressure paths are possible.
01288     unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
01289     for (SUnit::const_pred_iterator
01290            PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
01291       if (PI->getKind() != SDep::Data)
01292         continue;
01293       unsigned PredNum = PI->getSUnit()->NodeNum;
01294       if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
01295         joinPredSubtree(*PI, SU, /*CheckLimit=*/false);
01296 
01297       // Either link or merge the TreeData entry from the child to the parent.
01298       if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
01299         // If the predecessor's parent is invalid, this is a tree edge and the
01300         // current node is the parent.
01301         if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
01302           RootSet[PredNum].ParentNodeID = SU->NodeNum;
01303       }
01304       else if (RootSet.count(PredNum)) {
01305         // The predecessor is not a root, but is still in the root set. This
01306         // must be the new parent that it was just joined to. Note that
01307         // RootSet[PredNum].ParentNodeID may either be invalid or may still be
01308         // set to the original parent.
01309         RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
01310         RootSet.erase(PredNum);
01311       }
01312     }
01313     RootSet[SU->NodeNum] = RData;
01314   }
01315 
01316   /// Called once for each tree edge after calling visitPostOrderNode on the
01317   /// predecessor. Increment the parent node's instruction count and
01318   /// preemptively join this subtree to its parent's if it is small enough.
01319   void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
01320     R.DFSNodeData[Succ->NodeNum].InstrCount
01321       += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
01322     joinPredSubtree(PredDep, Succ);
01323   }
01324 
01325   /// Add a connection for cross edges.
01326   void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
01327     ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
01328   }
01329 
01330   /// Set each node's subtree ID to the representative ID and record connections
01331   /// between trees.
01332   void finalize() {
01333     SubtreeClasses.compress();
01334     R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
01335     assert(SubtreeClasses.getNumClasses() == RootSet.size()
01336            && "number of roots should match trees");
01337     for (SparseSet<RootData>::const_iterator
01338            RI = RootSet.begin(), RE = RootSet.end(); RI != RE; ++RI) {
01339       unsigned TreeID = SubtreeClasses[RI->NodeID];
01340       if (RI->ParentNodeID != SchedDFSResult::InvalidSubtreeID)
01341         R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[RI->ParentNodeID];
01342       R.DFSTreeData[TreeID].SubInstrCount = RI->SubInstrCount;
01343       // Note that SubInstrCount may be greater than InstrCount if we joined
01344       // subtrees across a cross edge. InstrCount will be attributed to the
01345       // original parent, while SubInstrCount will be attributed to the joined
01346       // parent.
01347     }
01348     R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
01349     R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
01350     DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
01351     for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
01352       R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
01353       DEBUG(dbgs() << "  SU(" << Idx << ") in tree "
01354             << R.DFSNodeData[Idx].SubtreeID << '\n');
01355     }
01356     for (std::vector<std::pair<const SUnit*, const SUnit*> >::const_iterator
01357            I = ConnectionPairs.begin(), E = ConnectionPairs.end();
01358          I != E; ++I) {
01359       unsigned PredTree = SubtreeClasses[I->first->NodeNum];
01360       unsigned SuccTree = SubtreeClasses[I->second->NodeNum];
01361       if (PredTree == SuccTree)
01362         continue;
01363       unsigned Depth = I->first->getDepth();
01364       addConnection(PredTree, SuccTree, Depth);
01365       addConnection(SuccTree, PredTree, Depth);
01366     }
01367   }
01368 
01369 protected:
01370   /// Join the predecessor subtree with the successor that is its DFS
01371   /// parent. Apply some heuristics before joining.
01372   bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
01373                        bool CheckLimit = true) {
01374     assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
01375 
01376     // Check if the predecessor is already joined.
01377     const SUnit *PredSU = PredDep.getSUnit();
01378     unsigned PredNum = PredSU->NodeNum;
01379     if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
01380       return false;
01381 
01382     // Four is the magic number of successors before a node is considered a
01383     // pinch point.
01384     unsigned NumDataSucs = 0;
01385     for (SUnit::const_succ_iterator SI = PredSU->Succs.begin(),
01386            SE = PredSU->Succs.end(); SI != SE; ++SI) {
01387       if (SI->getKind() == SDep::Data) {
01388         if (++NumDataSucs >= 4)
01389           return false;
01390       }
01391     }
01392     if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
01393       return false;
01394     R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
01395     SubtreeClasses.join(Succ->NodeNum, PredNum);
01396     return true;
01397   }
01398 
01399   /// Called by finalize() to record a connection between trees.
01400   void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
01401     if (!Depth)
01402       return;
01403 
01404     do {
01405       SmallVectorImpl<SchedDFSResult::Connection> &Connections =
01406         R.SubtreeConnections[FromTree];
01407       for (SmallVectorImpl<SchedDFSResult::Connection>::iterator
01408              I = Connections.begin(), E = Connections.end(); I != E; ++I) {
01409         if (I->TreeID == ToTree) {
01410           I->Level = std::max(I->Level, Depth);
01411           return;
01412         }
01413       }
01414       Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
01415       FromTree = R.DFSTreeData[FromTree].ParentTreeID;
01416     } while (FromTree != SchedDFSResult::InvalidSubtreeID);
01417   }
01418 };
01419 } // namespace llvm
01420 
01421 namespace {
01422 /// \brief Manage the stack used by a reverse depth-first search over the DAG.
01423 class SchedDAGReverseDFS {
01424   std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
01425 public:
01426   bool isComplete() const { return DFSStack.empty(); }
01427 
01428   void follow(const SUnit *SU) {
01429     DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
01430   }
01431   void advance() { ++DFSStack.back().second; }
01432 
01433   const SDep *backtrack() {
01434     DFSStack.pop_back();
01435     return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
01436   }
01437 
01438   const SUnit *getCurr() const { return DFSStack.back().first; }
01439 
01440   SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
01441 
01442   SUnit::const_pred_iterator getPredEnd() const {
01443     return getCurr()->Preds.end();
01444   }
01445 };
01446 } // anonymous
01447 
01448 static bool hasDataSucc(const SUnit *SU) {
01449   for (SUnit::const_succ_iterator
01450          SI = SU->Succs.begin(), SE = SU->Succs.end(); SI != SE; ++SI) {
01451     if (SI->getKind() == SDep::Data && !SI->getSUnit()->isBoundaryNode())
01452       return true;
01453   }
01454   return false;
01455 }
01456 
01457 /// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
01458 /// search from this root.
01459 void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
01460   if (!IsBottomUp)
01461     llvm_unreachable("Top-down ILP metric is unimplemnted");
01462 
01463   SchedDFSImpl Impl(*this);
01464   for (ArrayRef<SUnit>::const_iterator
01465          SI = SUnits.begin(), SE = SUnits.end(); SI != SE; ++SI) {
01466     const SUnit *SU = &*SI;
01467     if (Impl.isVisited(SU) || hasDataSucc(SU))
01468       continue;
01469 
01470     SchedDAGReverseDFS DFS;
01471     Impl.visitPreorder(SU);
01472     DFS.follow(SU);
01473     for (;;) {
01474       // Traverse the leftmost path as far as possible.
01475       while (DFS.getPred() != DFS.getPredEnd()) {
01476         const SDep &PredDep = *DFS.getPred();
01477         DFS.advance();
01478         // Ignore non-data edges.
01479         if (PredDep.getKind() != SDep::Data
01480             || PredDep.getSUnit()->isBoundaryNode()) {
01481           continue;
01482         }
01483         // An already visited edge is a cross edge, assuming an acyclic DAG.
01484         if (Impl.isVisited(PredDep.getSUnit())) {
01485           Impl.visitCrossEdge(PredDep, DFS.getCurr());
01486           continue;
01487         }
01488         Impl.visitPreorder(PredDep.getSUnit());
01489         DFS.follow(PredDep.getSUnit());
01490       }
01491       // Visit the top of the stack in postorder and backtrack.
01492       const SUnit *Child = DFS.getCurr();
01493       const SDep *PredDep = DFS.backtrack();
01494       Impl.visitPostorderNode(Child);
01495       if (PredDep)
01496         Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
01497       if (DFS.isComplete())
01498         break;
01499     }
01500   }
01501   Impl.finalize();
01502 }
01503 
01504 /// The root of the given SubtreeID was just scheduled. For all subtrees
01505 /// connected to this tree, record the depth of the connection so that the
01506 /// nearest connected subtrees can be prioritized.
01507 void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
01508   for (SmallVectorImpl<Connection>::const_iterator
01509          I = SubtreeConnections[SubtreeID].begin(),
01510          E = SubtreeConnections[SubtreeID].end(); I != E; ++I) {
01511     SubtreeConnectLevels[I->TreeID] =
01512       std::max(SubtreeConnectLevels[I->TreeID], I->Level);
01513     DEBUG(dbgs() << "  Tree: " << I->TreeID
01514           << " @" << SubtreeConnectLevels[I->TreeID] << '\n');
01515   }
01516 }
01517 
01518 LLVM_DUMP_METHOD
01519 void ILPValue::print(raw_ostream &OS) const {
01520   OS << InstrCount << " / " << Length << " = ";
01521   if (!Length)
01522     OS << "BADILP";
01523   else
01524     OS << format("%g", ((double)InstrCount / Length));
01525 }
01526 
01527 LLVM_DUMP_METHOD
01528 void ILPValue::dump() const {
01529   dbgs() << *this << '\n';
01530 }
01531 
01532 namespace llvm {
01533 
01534 LLVM_DUMP_METHOD
01535 raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
01536   Val.print(OS);
01537   return OS;
01538 }
01539 
01540 } // namespace llvm