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