SparseSet: Add support for key-derived indexes and arbitrary key types.
[oota-llvm.git] / lib / CodeGen / ScheduleDAGInstrs.cpp
1 //===---- ScheduleDAGInstrs.cpp - MachineInstr Rescheduling ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the ScheduleDAGInstrs class, which implements re-scheduling
11 // of MachineInstrs.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "sched-instrs"
16 #include "llvm/Operator.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/Analysis/ValueTracking.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/MachineMemOperand.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/PseudoSourceValue.h"
24 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
25 #include "llvm/MC/MCInstrItineraries.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Target/TargetSubtargetInfo.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/ADT/SmallSet.h"
33 using namespace llvm;
34
35 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
36                                      const MachineLoopInfo &mli,
37                                      const MachineDominatorTree &mdt,
38                                      bool IsPostRAFlag,
39                                      LiveIntervals *lis)
40   : ScheduleDAG(mf), MLI(mli), MDT(mdt), MFI(mf.getFrameInfo()),
41     InstrItins(mf.getTarget().getInstrItineraryData()), LIS(lis),
42     IsPostRA(IsPostRAFlag), UnitLatencies(false), CanHandleTerminators(false),
43     LoopRegs(MLI, MDT), FirstDbgValue(0) {
44   assert((IsPostRA || LIS) && "PreRA scheduling requires LiveIntervals");
45   DbgValues.clear();
46   assert(!(IsPostRA && MRI.getNumVirtRegs()) &&
47          "Virtual registers must be removed prior to PostRA scheduling");
48 }
49
50 /// getUnderlyingObjectFromInt - This is the function that does the work of
51 /// looking through basic ptrtoint+arithmetic+inttoptr sequences.
52 static const Value *getUnderlyingObjectFromInt(const Value *V) {
53   do {
54     if (const Operator *U = dyn_cast<Operator>(V)) {
55       // If we find a ptrtoint, we can transfer control back to the
56       // regular getUnderlyingObjectFromInt.
57       if (U->getOpcode() == Instruction::PtrToInt)
58         return U->getOperand(0);
59       // If we find an add of a constant or a multiplied value, it's
60       // likely that the other operand will lead us to the base
61       // object. We don't have to worry about the case where the
62       // object address is somehow being computed by the multiply,
63       // because our callers only care when the result is an
64       // identifibale object.
65       if (U->getOpcode() != Instruction::Add ||
66           (!isa<ConstantInt>(U->getOperand(1)) &&
67            Operator::getOpcode(U->getOperand(1)) != Instruction::Mul))
68         return V;
69       V = U->getOperand(0);
70     } else {
71       return V;
72     }
73     assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
74   } while (1);
75 }
76
77 /// getUnderlyingObject - This is a wrapper around GetUnderlyingObject
78 /// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
79 static const Value *getUnderlyingObject(const Value *V) {
80   // First just call Value::getUnderlyingObject to let it do what it does.
81   do {
82     V = GetUnderlyingObject(V);
83     // If it found an inttoptr, use special code to continue climing.
84     if (Operator::getOpcode(V) != Instruction::IntToPtr)
85       break;
86     const Value *O = getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
87     // If that succeeded in finding a pointer, continue the search.
88     if (!O->getType()->isPointerTy())
89       break;
90     V = O;
91   } while (1);
92   return V;
93 }
94
95 /// getUnderlyingObjectForInstr - If this machine instr has memory reference
96 /// information and it can be tracked to a normal reference to a known
97 /// object, return the Value for that object. Otherwise return null.
98 static const Value *getUnderlyingObjectForInstr(const MachineInstr *MI,
99                                                 const MachineFrameInfo *MFI,
100                                                 bool &MayAlias) {
101   MayAlias = true;
102   if (!MI->hasOneMemOperand() ||
103       !(*MI->memoperands_begin())->getValue() ||
104       (*MI->memoperands_begin())->isVolatile())
105     return 0;
106
107   const Value *V = (*MI->memoperands_begin())->getValue();
108   if (!V)
109     return 0;
110
111   V = getUnderlyingObject(V);
112   if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
113     // For now, ignore PseudoSourceValues which may alias LLVM IR values
114     // because the code that uses this function has no way to cope with
115     // such aliases.
116     if (PSV->isAliased(MFI))
117       return 0;
118
119     MayAlias = PSV->mayAlias(MFI);
120     return V;
121   }
122
123   if (isIdentifiedObject(V))
124     return V;
125
126   return 0;
127 }
128
129 void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
130   BB = bb;
131   LoopRegs.Deps.clear();
132   if (MachineLoop *ML = MLI.getLoopFor(BB))
133     if (BB == ML->getLoopLatch())
134       LoopRegs.VisitLoop(ML);
135 }
136
137 void ScheduleDAGInstrs::finishBlock() {
138   BB = 0;
139   // Nothing to do.
140 }
141
142 /// Initialize the map with the number of registers.
143 void Reg2SUnitsMap::setRegLimit(unsigned Limit) {
144   PhysRegSet.setUniverse(Limit);
145   SUnits.resize(Limit);
146 }
147
148 /// Clear the map without deallocating storage.
149 void Reg2SUnitsMap::clear() {
150   for (const_iterator I = reg_begin(), E = reg_end(); I != E; ++I) {
151     SUnits[*I].clear();
152   }
153   PhysRegSet.clear();
154 }
155
156 /// Initialize the DAG and common scheduler state for the current scheduling
157 /// region. This does not actually create the DAG, only clears it. The
158 /// scheduling driver may call BuildSchedGraph multiple times per scheduling
159 /// region.
160 void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
161                                     MachineBasicBlock::iterator begin,
162                                     MachineBasicBlock::iterator end,
163                                     unsigned endcount) {
164   assert(bb == BB && "startBlock should set BB");
165   RegionBegin = begin;
166   RegionEnd = end;
167   EndIndex = endcount;
168   MISUnitMap.clear();
169
170   // Check to see if the scheduler cares about latencies.
171   UnitLatencies = forceUnitLatencies();
172
173   ScheduleDAG::clearDAG();
174 }
175
176 /// Close the current scheduling region. Don't clear any state in case the
177 /// driver wants to refer to the previous scheduling region.
178 void ScheduleDAGInstrs::exitRegion() {
179   // Nothing to do.
180 }
181
182 /// addSchedBarrierDeps - Add dependencies from instructions in the current
183 /// list of instructions being scheduled to scheduling barrier by adding
184 /// the exit SU to the register defs and use list. This is because we want to
185 /// make sure instructions which define registers that are either used by
186 /// the terminator or are live-out are properly scheduled. This is
187 /// especially important when the definition latency of the return value(s)
188 /// are too high to be hidden by the branch or when the liveout registers
189 /// used by instructions in the fallthrough block.
190 void ScheduleDAGInstrs::addSchedBarrierDeps() {
191   MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : 0;
192   ExitSU.setInstr(ExitMI);
193   bool AllDepKnown = ExitMI &&
194     (ExitMI->isCall() || ExitMI->isBarrier());
195   if (ExitMI && AllDepKnown) {
196     // If it's a call or a barrier, add dependencies on the defs and uses of
197     // instruction.
198     for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
199       const MachineOperand &MO = ExitMI->getOperand(i);
200       if (!MO.isReg() || MO.isDef()) continue;
201       unsigned Reg = MO.getReg();
202       if (Reg == 0) continue;
203
204       if (TRI->isPhysicalRegister(Reg))
205         Uses[Reg].push_back(&ExitSU);
206       else {
207         assert(!IsPostRA && "Virtual register encountered after regalloc.");
208         addVRegUseDeps(&ExitSU, i);
209       }
210     }
211   } else {
212     // For others, e.g. fallthrough, conditional branch, assume the exit
213     // uses all the registers that are livein to the successor blocks.
214     assert(Uses.empty() && "Uses in set before adding deps?");
215     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
216            SE = BB->succ_end(); SI != SE; ++SI)
217       for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
218              E = (*SI)->livein_end(); I != E; ++I) {
219         unsigned Reg = *I;
220         if (!Uses.contains(Reg))
221           Uses[Reg].push_back(&ExitSU);
222       }
223   }
224 }
225
226 /// MO is an operand of SU's instruction that defines a physical register. Add
227 /// data dependencies from SU to any uses of the physical register.
228 void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU,
229                                            const MachineOperand &MO) {
230   assert(MO.isDef() && "expect physreg def");
231
232   // Ask the target if address-backscheduling is desirable, and if so how much.
233   const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
234   unsigned SpecialAddressLatency = ST.getSpecialAddressLatency();
235   unsigned DataLatency = SU->Latency;
236
237   for (const uint16_t *Alias = TRI->getOverlaps(MO.getReg()); *Alias; ++Alias) {
238     if (!Uses.contains(*Alias))
239       continue;
240     std::vector<SUnit*> &UseList = Uses[*Alias];
241     for (unsigned i = 0, e = UseList.size(); i != e; ++i) {
242       SUnit *UseSU = UseList[i];
243       if (UseSU == SU)
244         continue;
245       unsigned LDataLatency = DataLatency;
246       // Optionally add in a special extra latency for nodes that
247       // feed addresses.
248       // TODO: Perhaps we should get rid of
249       // SpecialAddressLatency and just move this into
250       // adjustSchedDependency for the targets that care about it.
251       if (SpecialAddressLatency != 0 && !UnitLatencies &&
252           UseSU != &ExitSU) {
253         MachineInstr *UseMI = UseSU->getInstr();
254         const MCInstrDesc &UseMCID = UseMI->getDesc();
255         int RegUseIndex = UseMI->findRegisterUseOperandIdx(*Alias);
256         assert(RegUseIndex >= 0 && "UseMI doesn't use register!");
257         if (RegUseIndex >= 0 &&
258             (UseMI->mayLoad() || UseMI->mayStore()) &&
259             (unsigned)RegUseIndex < UseMCID.getNumOperands() &&
260             UseMCID.OpInfo[RegUseIndex].isLookupPtrRegClass())
261           LDataLatency += SpecialAddressLatency;
262       }
263       // Adjust the dependence latency using operand def/use
264       // information (if any), and then allow the target to
265       // perform its own adjustments.
266       const SDep& dep = SDep(SU, SDep::Data, LDataLatency, *Alias);
267       if (!UnitLatencies) {
268         computeOperandLatency(SU, UseSU, const_cast<SDep &>(dep));
269         ST.adjustSchedDependency(SU, UseSU, const_cast<SDep &>(dep));
270       }
271       UseSU->addPred(dep);
272     }
273   }
274 }
275
276 /// addPhysRegDeps - Add register dependencies (data, anti, and output) from
277 /// this SUnit to following instructions in the same scheduling region that
278 /// depend the physical register referenced at OperIdx.
279 void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
280   const MachineInstr *MI = SU->getInstr();
281   const MachineOperand &MO = MI->getOperand(OperIdx);
282
283   // Optionally add output and anti dependencies. For anti
284   // dependencies we use a latency of 0 because for a multi-issue
285   // target we want to allow the defining instruction to issue
286   // in the same cycle as the using instruction.
287   // TODO: Using a latency of 1 here for output dependencies assumes
288   //       there's no cost for reusing registers.
289   SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
290   for (const uint16_t *Alias = TRI->getOverlaps(MO.getReg()); *Alias; ++Alias) {
291     if (!Defs.contains(*Alias))
292       continue;
293     std::vector<SUnit *> &DefList = Defs[*Alias];
294     for (unsigned i = 0, e = DefList.size(); i != e; ++i) {
295       SUnit *DefSU = DefList[i];
296       if (DefSU == &ExitSU)
297         continue;
298       if (DefSU != SU &&
299           (Kind != SDep::Output || !MO.isDead() ||
300            !DefSU->getInstr()->registerDefIsDead(*Alias))) {
301         if (Kind == SDep::Anti)
302           DefSU->addPred(SDep(SU, Kind, 0, /*Reg=*/*Alias));
303         else {
304           unsigned AOLat = TII->getOutputLatency(InstrItins, MI, OperIdx,
305                                                  DefSU->getInstr());
306           DefSU->addPred(SDep(SU, Kind, AOLat, /*Reg=*/*Alias));
307         }
308       }
309     }
310   }
311
312   if (!MO.isDef()) {
313     // Either insert a new Reg2SUnits entry with an empty SUnits list, or
314     // retrieve the existing SUnits list for this register's uses.
315     // Push this SUnit on the use list.
316     Uses[MO.getReg()].push_back(SU);
317   }
318   else {
319     addPhysRegDataDeps(SU, MO);
320
321     // Either insert a new Reg2SUnits entry with an empty SUnits list, or
322     // retrieve the existing SUnits list for this register's defs.
323     std::vector<SUnit *> &DefList = Defs[MO.getReg()];
324
325     // If a def is going to wrap back around to the top of the loop,
326     // backschedule it.
327     if (!UnitLatencies && DefList.empty()) {
328       LoopDependencies::LoopDeps::iterator I = LoopRegs.Deps.find(MO.getReg());
329       if (I != LoopRegs.Deps.end()) {
330         const MachineOperand *UseMO = I->second.first;
331         unsigned Count = I->second.second;
332         const MachineInstr *UseMI = UseMO->getParent();
333         unsigned UseMOIdx = UseMO - &UseMI->getOperand(0);
334         const MCInstrDesc &UseMCID = UseMI->getDesc();
335         const TargetSubtargetInfo &ST =
336           TM.getSubtarget<TargetSubtargetInfo>();
337         unsigned SpecialAddressLatency = ST.getSpecialAddressLatency();
338         // TODO: If we knew the total depth of the region here, we could
339         // handle the case where the whole loop is inside the region but
340         // is large enough that the isScheduleHigh trick isn't needed.
341         if (UseMOIdx < UseMCID.getNumOperands()) {
342           // Currently, we only support scheduling regions consisting of
343           // single basic blocks. Check to see if the instruction is in
344           // the same region by checking to see if it has the same parent.
345           if (UseMI->getParent() != MI->getParent()) {
346             unsigned Latency = SU->Latency;
347             if (UseMCID.OpInfo[UseMOIdx].isLookupPtrRegClass())
348               Latency += SpecialAddressLatency;
349             // This is a wild guess as to the portion of the latency which
350             // will be overlapped by work done outside the current
351             // scheduling region.
352             Latency -= std::min(Latency, Count);
353             // Add the artificial edge.
354             ExitSU.addPred(SDep(SU, SDep::Order, Latency,
355                                 /*Reg=*/0, /*isNormalMemory=*/false,
356                                 /*isMustAlias=*/false,
357                                 /*isArtificial=*/true));
358           } else if (SpecialAddressLatency > 0 &&
359                      UseMCID.OpInfo[UseMOIdx].isLookupPtrRegClass()) {
360             // The entire loop body is within the current scheduling region
361             // and the latency of this operation is assumed to be greater
362             // than the latency of the loop.
363             // TODO: Recursively mark data-edge predecessors as
364             //       isScheduleHigh too.
365             SU->isScheduleHigh = true;
366           }
367         }
368         LoopRegs.Deps.erase(I);
369       }
370     }
371
372     // clear this register's use list
373     if (Uses.contains(MO.getReg()))
374       Uses[MO.getReg()].clear();
375
376     if (!MO.isDead())
377       DefList.clear();
378
379     // Calls will not be reordered because of chain dependencies (see
380     // below). Since call operands are dead, calls may continue to be added
381     // to the DefList making dependence checking quadratic in the size of
382     // the block. Instead, we leave only one call at the back of the
383     // DefList.
384     if (SU->isCall) {
385       while (!DefList.empty() && DefList.back()->isCall)
386         DefList.pop_back();
387     }
388     // Defs are pushed in the order they are visited and never reordered.
389     DefList.push_back(SU);
390   }
391 }
392
393 /// addVRegDefDeps - Add register output and data dependencies from this SUnit
394 /// to instructions that occur later in the same scheduling region if they read
395 /// from or write to the virtual register defined at OperIdx.
396 ///
397 /// TODO: Hoist loop induction variable increments. This has to be
398 /// reevaluated. Generally, IV scheduling should be done before coalescing.
399 void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
400   const MachineInstr *MI = SU->getInstr();
401   unsigned Reg = MI->getOperand(OperIdx).getReg();
402
403   // SSA defs do not have output/anti dependencies.
404   // The current operand is a def, so we have at least one.
405   if (llvm::next(MRI.def_begin(Reg)) == MRI.def_end())
406     return;
407
408   // Add output dependence to the next nearest def of this vreg.
409   //
410   // Unless this definition is dead, the output dependence should be
411   // transitively redundant with antidependencies from this definition's
412   // uses. We're conservative for now until we have a way to guarantee the uses
413   // are not eliminated sometime during scheduling. The output dependence edge
414   // is also useful if output latency exceeds def-use latency.
415   VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
416   if (DefI == VRegDefs.end())
417     VRegDefs.insert(VReg2SUnit(Reg, SU));
418   else {
419     SUnit *DefSU = DefI->SU;
420     if (DefSU != SU && DefSU != &ExitSU) {
421       unsigned OutLatency = TII->getOutputLatency(InstrItins, MI, OperIdx,
422                                                   DefSU->getInstr());
423       DefSU->addPred(SDep(SU, SDep::Output, OutLatency, Reg));
424     }
425     DefI->SU = SU;
426   }
427 }
428
429 /// addVRegUseDeps - Add a register data dependency if the instruction that
430 /// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
431 /// register antidependency from this SUnit to instructions that occur later in
432 /// the same scheduling region if they write the virtual register.
433 ///
434 /// TODO: Handle ExitSU "uses" properly.
435 void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
436   MachineInstr *MI = SU->getInstr();
437   unsigned Reg = MI->getOperand(OperIdx).getReg();
438
439   // Lookup this operand's reaching definition.
440   assert(LIS && "vreg dependencies requires LiveIntervals");
441   SlotIndex UseIdx = LIS->getInstructionIndex(MI).getRegSlot();
442   LiveInterval *LI = &LIS->getInterval(Reg);
443   VNInfo *VNI = LI->getVNInfoBefore(UseIdx);
444   // VNI will be valid because MachineOperand::readsReg() is checked by caller.
445   MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def);
446   // Phis and other noninstructions (after coalescing) have a NULL Def.
447   if (Def) {
448     SUnit *DefSU = getSUnit(Def);
449     if (DefSU) {
450       // The reaching Def lives within this scheduling region.
451       // Create a data dependence.
452       //
453       // TODO: Handle "special" address latencies cleanly.
454       const SDep &dep = SDep(DefSU, SDep::Data, DefSU->Latency, Reg);
455       if (!UnitLatencies) {
456         // Adjust the dependence latency using operand def/use information, then
457         // allow the target to perform its own adjustments.
458         computeOperandLatency(DefSU, SU, const_cast<SDep &>(dep));
459         const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
460         ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
461       }
462       SU->addPred(dep);
463     }
464   }
465
466   // Add antidependence to the following def of the vreg it uses.
467   VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
468   if (DefI != VRegDefs.end() && DefI->SU != SU)
469     DefI->SU->addPred(SDep(SU, SDep::Anti, 0, Reg));
470 }
471
472 /// Create an SUnit for each real instruction, numbered in top-down toplological
473 /// order. The instruction order A < B, implies that no edge exists from B to A.
474 ///
475 /// Map each real instruction to its SUnit.
476 ///
477 /// After initSUnits, the SUnits vector cannot be resized and the scheduler may
478 /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
479 /// instead of pointers.
480 ///
481 /// MachineScheduler relies on initSUnits numbering the nodes by their order in
482 /// the original instruction list.
483 void ScheduleDAGInstrs::initSUnits() {
484   // We'll be allocating one SUnit for each real instruction in the region,
485   // which is contained within a basic block.
486   SUnits.reserve(BB->size());
487
488   for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
489     MachineInstr *MI = I;
490     if (MI->isDebugValue())
491       continue;
492
493     SUnit *SU = newSUnit(MI);
494     MISUnitMap[MI] = SU;
495
496     SU->isCall = MI->isCall();
497     SU->isCommutable = MI->isCommutable();
498
499     // Assign the Latency field of SU using target-provided information.
500     if (UnitLatencies)
501       SU->Latency = 1;
502     else
503       computeLatency(SU);
504   }
505 }
506
507 void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA) {
508   // Create an SUnit for each real instruction.
509   initSUnits();
510
511   // We build scheduling units by walking a block's instruction list from bottom
512   // to top.
513
514   // Remember where a generic side-effecting instruction is as we procede.
515   SUnit *BarrierChain = 0, *AliasChain = 0;
516
517   // Memory references to specific known memory locations are tracked
518   // so that they can be given more precise dependencies. We track
519   // separately the known memory locations that may alias and those
520   // that are known not to alias
521   std::map<const Value *, SUnit *> AliasMemDefs, NonAliasMemDefs;
522   std::map<const Value *, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
523
524   // Remove any stale debug info; sometimes BuildSchedGraph is called again
525   // without emitting the info from the previous call.
526   DbgValues.clear();
527   FirstDbgValue = NULL;
528
529   assert(Defs.empty() && Uses.empty() &&
530          "Only BuildGraph should update Defs/Uses");
531   Defs.setRegLimit(TRI->getNumRegs());
532   Uses.setRegLimit(TRI->getNumRegs());
533
534   assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
535   // FIXME: Allow SparseSet to reserve space for the creation of virtual
536   // registers during scheduling. Don't artificially inflate the Universe
537   // because we want to assert that vregs are not created during DAG building.
538   VRegDefs.setUniverse(MRI.getNumVirtRegs());
539
540   // Model data dependencies between instructions being scheduled and the
541   // ExitSU.
542   addSchedBarrierDeps();
543
544   // Walk the list of instructions, from bottom moving up.
545   MachineInstr *PrevMI = NULL;
546   for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
547        MII != MIE; --MII) {
548     MachineInstr *MI = prior(MII);
549     if (MI && PrevMI) {
550       DbgValues.push_back(std::make_pair(PrevMI, MI));
551       PrevMI = NULL;
552     }
553
554     if (MI->isDebugValue()) {
555       PrevMI = MI;
556       continue;
557     }
558
559     assert((!MI->isTerminator() || CanHandleTerminators) && !MI->isLabel() &&
560            "Cannot schedule terminators or labels!");
561
562     SUnit *SU = MISUnitMap[MI];
563     assert(SU && "No SUnit mapped to this MI");
564
565     // Add register-based dependencies (data, anti, and output).
566     for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
567       const MachineOperand &MO = MI->getOperand(j);
568       if (!MO.isReg()) continue;
569       unsigned Reg = MO.getReg();
570       if (Reg == 0) continue;
571
572       if (TRI->isPhysicalRegister(Reg))
573         addPhysRegDeps(SU, j);
574       else {
575         assert(!IsPostRA && "Virtual register encountered!");
576         if (MO.isDef())
577           addVRegDefDeps(SU, j);
578         else if (MO.readsReg()) // ignore undef operands
579           addVRegUseDeps(SU, j);
580       }
581     }
582
583     // Add chain dependencies.
584     // Chain dependencies used to enforce memory order should have
585     // latency of 0 (except for true dependency of Store followed by
586     // aliased Load... we estimate that with a single cycle of latency
587     // assuming the hardware will bypass)
588     // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
589     // after stack slots are lowered to actual addresses.
590     // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
591     // produce more precise dependence information.
592 #define STORE_LOAD_LATENCY 1
593     unsigned TrueMemOrderLatency = 0;
594     if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
595         (MI->hasVolatileMemoryRef() &&
596          (!MI->mayLoad() || !MI->isInvariantLoad(AA)))) {
597       // Be conservative with these and add dependencies on all memory
598       // references, even those that are known to not alias.
599       for (std::map<const Value *, SUnit *>::iterator I =
600              NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
601         I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
602       }
603       for (std::map<const Value *, std::vector<SUnit *> >::iterator I =
604              NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
605         for (unsigned i = 0, e = I->second.size(); i != e; ++i)
606           I->second[i]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency));
607       }
608       NonAliasMemDefs.clear();
609       NonAliasMemUses.clear();
610       // Add SU to the barrier chain.
611       if (BarrierChain)
612         BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
613       BarrierChain = SU;
614
615       // fall-through
616     new_alias_chain:
617       // Chain all possibly aliasing memory references though SU.
618       if (AliasChain)
619         AliasChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
620       AliasChain = SU;
621       for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
622         PendingLoads[k]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency));
623       for (std::map<const Value *, SUnit *>::iterator I = AliasMemDefs.begin(),
624            E = AliasMemDefs.end(); I != E; ++I) {
625         I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
626       }
627       for (std::map<const Value *, std::vector<SUnit *> >::iterator I =
628            AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
629         for (unsigned i = 0, e = I->second.size(); i != e; ++i)
630           I->second[i]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency));
631       }
632       PendingLoads.clear();
633       AliasMemDefs.clear();
634       AliasMemUses.clear();
635     } else if (MI->mayStore()) {
636       bool MayAlias = true;
637       TrueMemOrderLatency = STORE_LOAD_LATENCY;
638       if (const Value *V = getUnderlyingObjectForInstr(MI, MFI, MayAlias)) {
639         // A store to a specific PseudoSourceValue. Add precise dependencies.
640         // Record the def in MemDefs, first adding a dep if there is
641         // an existing def.
642         std::map<const Value *, SUnit *>::iterator I =
643           ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
644         std::map<const Value *, SUnit *>::iterator IE =
645           ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
646         if (I != IE) {
647           I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0, /*Reg=*/0,
648                                   /*isNormalMemory=*/true));
649           I->second = SU;
650         } else {
651           if (MayAlias)
652             AliasMemDefs[V] = SU;
653           else
654             NonAliasMemDefs[V] = SU;
655         }
656         // Handle the uses in MemUses, if there are any.
657         std::map<const Value *, std::vector<SUnit *> >::iterator J =
658           ((MayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
659         std::map<const Value *, std::vector<SUnit *> >::iterator JE =
660           ((MayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
661         if (J != JE) {
662           for (unsigned i = 0, e = J->second.size(); i != e; ++i)
663             J->second[i]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency,
664                                        /*Reg=*/0, /*isNormalMemory=*/true));
665           J->second.clear();
666         }
667         if (MayAlias) {
668           // Add dependencies from all the PendingLoads, i.e. loads
669           // with no underlying object.
670           for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
671             PendingLoads[k]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency));
672           // Add dependence on alias chain, if needed.
673           if (AliasChain)
674             AliasChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
675         }
676         // Add dependence on barrier chain, if needed.
677         if (BarrierChain)
678           BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
679       } else {
680         // Treat all other stores conservatively.
681         goto new_alias_chain;
682       }
683
684       if (!ExitSU.isPred(SU))
685         // Push store's up a bit to avoid them getting in between cmp
686         // and branches.
687         ExitSU.addPred(SDep(SU, SDep::Order, 0,
688                             /*Reg=*/0, /*isNormalMemory=*/false,
689                             /*isMustAlias=*/false,
690                             /*isArtificial=*/true));
691     } else if (MI->mayLoad()) {
692       bool MayAlias = true;
693       TrueMemOrderLatency = 0;
694       if (MI->isInvariantLoad(AA)) {
695         // Invariant load, no chain dependencies needed!
696       } else {
697         if (const Value *V =
698             getUnderlyingObjectForInstr(MI, MFI, MayAlias)) {
699           // A load from a specific PseudoSourceValue. Add precise dependencies.
700           std::map<const Value *, SUnit *>::iterator I =
701             ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
702           std::map<const Value *, SUnit *>::iterator IE =
703             ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
704           if (I != IE)
705             I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0, /*Reg=*/0,
706                                     /*isNormalMemory=*/true));
707           if (MayAlias)
708             AliasMemUses[V].push_back(SU);
709           else
710             NonAliasMemUses[V].push_back(SU);
711         } else {
712           // A load with no underlying object. Depend on all
713           // potentially aliasing stores.
714           for (std::map<const Value *, SUnit *>::iterator I =
715                  AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
716             I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
717
718           PendingLoads.push_back(SU);
719           MayAlias = true;
720         }
721
722         // Add dependencies on alias and barrier chains, if needed.
723         if (MayAlias && AliasChain)
724           AliasChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
725         if (BarrierChain)
726           BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
727       }
728     }
729   }
730   if (PrevMI)
731     FirstDbgValue = PrevMI;
732
733   Defs.clear();
734   Uses.clear();
735   VRegDefs.clear();
736   PendingLoads.clear();
737 }
738
739 void ScheduleDAGInstrs::computeLatency(SUnit *SU) {
740   // Compute the latency for the node.
741   if (!InstrItins || InstrItins->isEmpty()) {
742     SU->Latency = 1;
743
744     // Simplistic target-independent heuristic: assume that loads take
745     // extra time.
746     if (SU->getInstr()->mayLoad())
747       SU->Latency += 2;
748   } else {
749     SU->Latency = TII->getInstrLatency(InstrItins, SU->getInstr());
750   }
751 }
752
753 void ScheduleDAGInstrs::computeOperandLatency(SUnit *Def, SUnit *Use,
754                                               SDep& dep) const {
755   if (!InstrItins || InstrItins->isEmpty())
756     return;
757
758   // For a data dependency with a known register...
759   if ((dep.getKind() != SDep::Data) || (dep.getReg() == 0))
760     return;
761
762   const unsigned Reg = dep.getReg();
763
764   // ... find the definition of the register in the defining
765   // instruction
766   MachineInstr *DefMI = Def->getInstr();
767   int DefIdx = DefMI->findRegisterDefOperandIdx(Reg);
768   if (DefIdx != -1) {
769     const MachineOperand &MO = DefMI->getOperand(DefIdx);
770     if (MO.isReg() && MO.isImplicit() &&
771         DefIdx >= (int)DefMI->getDesc().getNumOperands()) {
772       // This is an implicit def, getOperandLatency() won't return the correct
773       // latency. e.g.
774       //   %D6<def>, %D7<def> = VLD1q16 %R2<kill>, 0, ..., %Q3<imp-def>
775       //   %Q1<def> = VMULv8i16 %Q1<kill>, %Q3<kill>, ...
776       // What we want is to compute latency between def of %D6/%D7 and use of
777       // %Q3 instead.
778       unsigned Op2 = DefMI->findRegisterDefOperandIdx(Reg, false, true, TRI);
779       if (DefMI->getOperand(Op2).isReg())
780         DefIdx = Op2;
781     }
782     MachineInstr *UseMI = Use->getInstr();
783     // For all uses of the register, calculate the maxmimum latency
784     int Latency = -1;
785     if (UseMI) {
786       for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
787         const MachineOperand &MO = UseMI->getOperand(i);
788         if (!MO.isReg() || !MO.isUse())
789           continue;
790         unsigned MOReg = MO.getReg();
791         if (MOReg != Reg)
792           continue;
793
794         int UseCycle = TII->getOperandLatency(InstrItins, DefMI, DefIdx,
795                                               UseMI, i);
796         Latency = std::max(Latency, UseCycle);
797       }
798     } else {
799       // UseMI is null, then it must be a scheduling barrier.
800       if (!InstrItins || InstrItins->isEmpty())
801         return;
802       unsigned DefClass = DefMI->getDesc().getSchedClass();
803       Latency = InstrItins->getOperandCycle(DefClass, DefIdx);
804     }
805
806     // If we found a latency, then replace the existing dependence latency.
807     if (Latency >= 0)
808       dep.setLatency(Latency);
809   }
810 }
811
812 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
813   SU->getInstr()->dump();
814 }
815
816 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
817   std::string s;
818   raw_string_ostream oss(s);
819   if (SU == &EntrySU)
820     oss << "<entry>";
821   else if (SU == &ExitSU)
822     oss << "<exit>";
823   else
824     SU->getInstr()->print(oss);
825   return oss.str();
826 }
827
828 /// Return the basic block label. It is not necessarilly unique because a block
829 /// contains multiple scheduling regions. But it is fine for visualization.
830 std::string ScheduleDAGInstrs::getDAGName() const {
831   return "dag." + BB->getFullName();
832 }