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