Add -enable-aa-sched-mi, off by default, for AliasAnalysis inside MachineScheduler.
[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 "RegisterPressure.h"
17 #include "llvm/Operator.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Analysis/ValueTracking.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineMemOperand.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/PseudoSourceValue.h"
25 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
26 #include "llvm/MC/MCInstrItineraries.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30 #include "llvm/Target/TargetSubtargetInfo.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/SmallSet.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 using namespace llvm;
37
38 static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
39     cl::ZeroOrMore, cl::init(false),
40     cl::desc("Enable use of AA during MI GAD construction"));
41
42 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
43                                      const MachineLoopInfo &mli,
44                                      const MachineDominatorTree &mdt,
45                                      bool IsPostRAFlag,
46                                      LiveIntervals *lis)
47   : ScheduleDAG(mf), MLI(mli), MDT(mdt), MFI(mf.getFrameInfo()),
48     InstrItins(mf.getTarget().getInstrItineraryData()), LIS(lis),
49     IsPostRA(IsPostRAFlag), UnitLatencies(false), CanHandleTerminators(false),
50     LoopRegs(MLI, MDT), FirstDbgValue(0) {
51   assert((IsPostRA || LIS) && "PreRA scheduling requires LiveIntervals");
52   DbgValues.clear();
53   assert(!(IsPostRA && MRI.getNumVirtRegs()) &&
54          "Virtual registers must be removed prior to PostRA scheduling");
55 }
56
57 /// getUnderlyingObjectFromInt - This is the function that does the work of
58 /// looking through basic ptrtoint+arithmetic+inttoptr sequences.
59 static const Value *getUnderlyingObjectFromInt(const Value *V) {
60   do {
61     if (const Operator *U = dyn_cast<Operator>(V)) {
62       // If we find a ptrtoint, we can transfer control back to the
63       // regular getUnderlyingObjectFromInt.
64       if (U->getOpcode() == Instruction::PtrToInt)
65         return U->getOperand(0);
66       // If we find an add of a constant or a multiplied value, it's
67       // likely that the other operand will lead us to the base
68       // object. We don't have to worry about the case where the
69       // object address is somehow being computed by the multiply,
70       // because our callers only care when the result is an
71       // identifibale object.
72       if (U->getOpcode() != Instruction::Add ||
73           (!isa<ConstantInt>(U->getOperand(1)) &&
74            Operator::getOpcode(U->getOperand(1)) != Instruction::Mul))
75         return V;
76       V = U->getOperand(0);
77     } else {
78       return V;
79     }
80     assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
81   } while (1);
82 }
83
84 /// getUnderlyingObject - This is a wrapper around GetUnderlyingObject
85 /// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
86 static const Value *getUnderlyingObject(const Value *V) {
87   // First just call Value::getUnderlyingObject to let it do what it does.
88   do {
89     V = GetUnderlyingObject(V);
90     // If it found an inttoptr, use special code to continue climing.
91     if (Operator::getOpcode(V) != Instruction::IntToPtr)
92       break;
93     const Value *O = getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
94     // If that succeeded in finding a pointer, continue the search.
95     if (!O->getType()->isPointerTy())
96       break;
97     V = O;
98   } while (1);
99   return V;
100 }
101
102 /// getUnderlyingObjectForInstr - If this machine instr has memory reference
103 /// information and it can be tracked to a normal reference to a known
104 /// object, return the Value for that object. Otherwise return null.
105 static const Value *getUnderlyingObjectForInstr(const MachineInstr *MI,
106                                                 const MachineFrameInfo *MFI,
107                                                 bool &MayAlias) {
108   MayAlias = true;
109   if (!MI->hasOneMemOperand() ||
110       !(*MI->memoperands_begin())->getValue() ||
111       (*MI->memoperands_begin())->isVolatile())
112     return 0;
113
114   const Value *V = (*MI->memoperands_begin())->getValue();
115   if (!V)
116     return 0;
117
118   V = getUnderlyingObject(V);
119   if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
120     // For now, ignore PseudoSourceValues which may alias LLVM IR values
121     // because the code that uses this function has no way to cope with
122     // such aliases.
123     if (PSV->isAliased(MFI))
124       return 0;
125
126     MayAlias = PSV->mayAlias(MFI);
127     return V;
128   }
129
130   if (isIdentifiedObject(V))
131     return V;
132
133   return 0;
134 }
135
136 void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
137   BB = bb;
138   LoopRegs.Deps.clear();
139   if (MachineLoop *ML = MLI.getLoopFor(BB))
140     if (BB == ML->getLoopLatch())
141       LoopRegs.VisitLoop(ML);
142 }
143
144 void ScheduleDAGInstrs::finishBlock() {
145   // Subclasses should no longer refer to the old block.
146   BB = 0;
147 }
148
149 /// Initialize the map with the number of registers.
150 void Reg2SUnitsMap::setRegLimit(unsigned Limit) {
151   PhysRegSet.setUniverse(Limit);
152   SUnits.resize(Limit);
153 }
154
155 /// Clear the map without deallocating storage.
156 void Reg2SUnitsMap::clear() {
157   for (const_iterator I = reg_begin(), E = reg_end(); I != E; ++I) {
158     SUnits[*I].clear();
159   }
160   PhysRegSet.clear();
161 }
162
163 /// Initialize the DAG and common scheduler state for the current scheduling
164 /// region. This does not actually create the DAG, only clears it. The
165 /// scheduling driver may call BuildSchedGraph multiple times per scheduling
166 /// region.
167 void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
168                                     MachineBasicBlock::iterator begin,
169                                     MachineBasicBlock::iterator end,
170                                     unsigned endcount) {
171   assert(bb == BB && "startBlock should set BB");
172   RegionBegin = begin;
173   RegionEnd = end;
174   EndIndex = endcount;
175   MISUnitMap.clear();
176
177   // Check to see if the scheduler cares about latencies.
178   UnitLatencies = forceUnitLatencies();
179
180   ScheduleDAG::clearDAG();
181 }
182
183 /// Close the current scheduling region. Don't clear any state in case the
184 /// driver wants to refer to the previous scheduling region.
185 void ScheduleDAGInstrs::exitRegion() {
186   // Nothing to do.
187 }
188
189 /// addSchedBarrierDeps - Add dependencies from instructions in the current
190 /// list of instructions being scheduled to scheduling barrier by adding
191 /// the exit SU to the register defs and use list. This is because we want to
192 /// make sure instructions which define registers that are either used by
193 /// the terminator or are live-out are properly scheduled. This is
194 /// especially important when the definition latency of the return value(s)
195 /// are too high to be hidden by the branch or when the liveout registers
196 /// used by instructions in the fallthrough block.
197 void ScheduleDAGInstrs::addSchedBarrierDeps() {
198   MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : 0;
199   ExitSU.setInstr(ExitMI);
200   bool AllDepKnown = ExitMI &&
201     (ExitMI->isCall() || ExitMI->isBarrier());
202   if (ExitMI && AllDepKnown) {
203     // If it's a call or a barrier, add dependencies on the defs and uses of
204     // instruction.
205     for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
206       const MachineOperand &MO = ExitMI->getOperand(i);
207       if (!MO.isReg() || MO.isDef()) continue;
208       unsigned Reg = MO.getReg();
209       if (Reg == 0) continue;
210
211       if (TRI->isPhysicalRegister(Reg))
212         Uses[Reg].push_back(&ExitSU);
213       else {
214         assert(!IsPostRA && "Virtual register encountered after regalloc.");
215         addVRegUseDeps(&ExitSU, i);
216       }
217     }
218   } else {
219     // For others, e.g. fallthrough, conditional branch, assume the exit
220     // uses all the registers that are livein to the successor blocks.
221     assert(Uses.empty() && "Uses in set before adding deps?");
222     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
223            SE = BB->succ_end(); SI != SE; ++SI)
224       for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
225              E = (*SI)->livein_end(); I != E; ++I) {
226         unsigned Reg = *I;
227         if (!Uses.contains(Reg))
228           Uses[Reg].push_back(&ExitSU);
229       }
230   }
231 }
232
233 /// MO is an operand of SU's instruction that defines a physical register. Add
234 /// data dependencies from SU to any uses of the physical register.
235 void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU,
236                                            const MachineOperand &MO) {
237   assert(MO.isDef() && "expect physreg def");
238
239   // Ask the target if address-backscheduling is desirable, and if so how much.
240   const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
241   unsigned SpecialAddressLatency = ST.getSpecialAddressLatency();
242   unsigned DataLatency = SU->Latency;
243
244   for (const uint16_t *Alias = TRI->getOverlaps(MO.getReg()); *Alias; ++Alias) {
245     if (!Uses.contains(*Alias))
246       continue;
247     std::vector<SUnit*> &UseList = Uses[*Alias];
248     for (unsigned i = 0, e = UseList.size(); i != e; ++i) {
249       SUnit *UseSU = UseList[i];
250       if (UseSU == SU)
251         continue;
252       unsigned LDataLatency = DataLatency;
253       // Optionally add in a special extra latency for nodes that
254       // feed addresses.
255       // TODO: Perhaps we should get rid of
256       // SpecialAddressLatency and just move this into
257       // adjustSchedDependency for the targets that care about it.
258       if (SpecialAddressLatency != 0 && !UnitLatencies &&
259           UseSU != &ExitSU) {
260         MachineInstr *UseMI = UseSU->getInstr();
261         const MCInstrDesc &UseMCID = UseMI->getDesc();
262         int RegUseIndex = UseMI->findRegisterUseOperandIdx(*Alias);
263         assert(RegUseIndex >= 0 && "UseMI doesn't use register!");
264         if (RegUseIndex >= 0 &&
265             (UseMI->mayLoad() || UseMI->mayStore()) &&
266             (unsigned)RegUseIndex < UseMCID.getNumOperands() &&
267             UseMCID.OpInfo[RegUseIndex].isLookupPtrRegClass())
268           LDataLatency += SpecialAddressLatency;
269       }
270       // Adjust the dependence latency using operand def/use
271       // information (if any), and then allow the target to
272       // perform its own adjustments.
273       const SDep& dep = SDep(SU, SDep::Data, LDataLatency, *Alias);
274       if (!UnitLatencies) {
275         computeOperandLatency(SU, UseSU, const_cast<SDep &>(dep));
276         ST.adjustSchedDependency(SU, UseSU, const_cast<SDep &>(dep));
277       }
278       UseSU->addPred(dep);
279     }
280   }
281 }
282
283 /// addPhysRegDeps - Add register dependencies (data, anti, and output) from
284 /// this SUnit to following instructions in the same scheduling region that
285 /// depend the physical register referenced at OperIdx.
286 void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
287   const MachineInstr *MI = SU->getInstr();
288   const MachineOperand &MO = MI->getOperand(OperIdx);
289
290   // Optionally add output and anti dependencies. For anti
291   // dependencies we use a latency of 0 because for a multi-issue
292   // target we want to allow the defining instruction to issue
293   // in the same cycle as the using instruction.
294   // TODO: Using a latency of 1 here for output dependencies assumes
295   //       there's no cost for reusing registers.
296   SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
297   for (const uint16_t *Alias = TRI->getOverlaps(MO.getReg()); *Alias; ++Alias) {
298     if (!Defs.contains(*Alias))
299       continue;
300     std::vector<SUnit *> &DefList = Defs[*Alias];
301     for (unsigned i = 0, e = DefList.size(); i != e; ++i) {
302       SUnit *DefSU = DefList[i];
303       if (DefSU == &ExitSU)
304         continue;
305       if (DefSU != SU &&
306           (Kind != SDep::Output || !MO.isDead() ||
307            !DefSU->getInstr()->registerDefIsDead(*Alias))) {
308         if (Kind == SDep::Anti)
309           DefSU->addPred(SDep(SU, Kind, 0, /*Reg=*/*Alias));
310         else {
311           unsigned AOLat = TII->getOutputLatency(InstrItins, MI, OperIdx,
312                                                  DefSU->getInstr());
313           DefSU->addPred(SDep(SU, Kind, AOLat, /*Reg=*/*Alias));
314         }
315       }
316     }
317   }
318
319   if (!MO.isDef()) {
320     // Either insert a new Reg2SUnits entry with an empty SUnits list, or
321     // retrieve the existing SUnits list for this register's uses.
322     // Push this SUnit on the use list.
323     Uses[MO.getReg()].push_back(SU);
324   }
325   else {
326     addPhysRegDataDeps(SU, MO);
327
328     // Either insert a new Reg2SUnits entry with an empty SUnits list, or
329     // retrieve the existing SUnits list for this register's defs.
330     std::vector<SUnit *> &DefList = Defs[MO.getReg()];
331
332     // If a def is going to wrap back around to the top of the loop,
333     // backschedule it.
334     if (!UnitLatencies && DefList.empty()) {
335       LoopDependencies::LoopDeps::iterator I = LoopRegs.Deps.find(MO.getReg());
336       if (I != LoopRegs.Deps.end()) {
337         const MachineOperand *UseMO = I->second.first;
338         unsigned Count = I->second.second;
339         const MachineInstr *UseMI = UseMO->getParent();
340         unsigned UseMOIdx = UseMO - &UseMI->getOperand(0);
341         const MCInstrDesc &UseMCID = UseMI->getDesc();
342         const TargetSubtargetInfo &ST =
343           TM.getSubtarget<TargetSubtargetInfo>();
344         unsigned SpecialAddressLatency = ST.getSpecialAddressLatency();
345         // TODO: If we knew the total depth of the region here, we could
346         // handle the case where the whole loop is inside the region but
347         // is large enough that the isScheduleHigh trick isn't needed.
348         if (UseMOIdx < UseMCID.getNumOperands()) {
349           // Currently, we only support scheduling regions consisting of
350           // single basic blocks. Check to see if the instruction is in
351           // the same region by checking to see if it has the same parent.
352           if (UseMI->getParent() != MI->getParent()) {
353             unsigned Latency = SU->Latency;
354             if (UseMCID.OpInfo[UseMOIdx].isLookupPtrRegClass())
355               Latency += SpecialAddressLatency;
356             // This is a wild guess as to the portion of the latency which
357             // will be overlapped by work done outside the current
358             // scheduling region.
359             Latency -= std::min(Latency, Count);
360             // Add the artificial edge.
361             ExitSU.addPred(SDep(SU, SDep::Order, Latency,
362                                 /*Reg=*/0, /*isNormalMemory=*/false,
363                                 /*isMustAlias=*/false,
364                                 /*isArtificial=*/true));
365           } else if (SpecialAddressLatency > 0 &&
366                      UseMCID.OpInfo[UseMOIdx].isLookupPtrRegClass()) {
367             // The entire loop body is within the current scheduling region
368             // and the latency of this operation is assumed to be greater
369             // than the latency of the loop.
370             // TODO: Recursively mark data-edge predecessors as
371             //       isScheduleHigh too.
372             SU->isScheduleHigh = true;
373           }
374         }
375         LoopRegs.Deps.erase(I);
376       }
377     }
378
379     // clear this register's use list
380     if (Uses.contains(MO.getReg()))
381       Uses[MO.getReg()].clear();
382
383     if (!MO.isDead())
384       DefList.clear();
385
386     // Calls will not be reordered because of chain dependencies (see
387     // below). Since call operands are dead, calls may continue to be added
388     // to the DefList making dependence checking quadratic in the size of
389     // the block. Instead, we leave only one call at the back of the
390     // DefList.
391     if (SU->isCall) {
392       while (!DefList.empty() && DefList.back()->isCall)
393         DefList.pop_back();
394     }
395     // Defs are pushed in the order they are visited and never reordered.
396     DefList.push_back(SU);
397   }
398 }
399
400 /// addVRegDefDeps - Add register output and data dependencies from this SUnit
401 /// to instructions that occur later in the same scheduling region if they read
402 /// from or write to the virtual register defined at OperIdx.
403 ///
404 /// TODO: Hoist loop induction variable increments. This has to be
405 /// reevaluated. Generally, IV scheduling should be done before coalescing.
406 void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
407   const MachineInstr *MI = SU->getInstr();
408   unsigned Reg = MI->getOperand(OperIdx).getReg();
409
410   // SSA defs do not have output/anti dependencies.
411   // The current operand is a def, so we have at least one.
412   if (llvm::next(MRI.def_begin(Reg)) == MRI.def_end())
413     return;
414
415   // Add output dependence to the next nearest def of this vreg.
416   //
417   // Unless this definition is dead, the output dependence should be
418   // transitively redundant with antidependencies from this definition's
419   // uses. We're conservative for now until we have a way to guarantee the uses
420   // are not eliminated sometime during scheduling. The output dependence edge
421   // is also useful if output latency exceeds def-use latency.
422   VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
423   if (DefI == VRegDefs.end())
424     VRegDefs.insert(VReg2SUnit(Reg, SU));
425   else {
426     SUnit *DefSU = DefI->SU;
427     if (DefSU != SU && DefSU != &ExitSU) {
428       unsigned OutLatency = TII->getOutputLatency(InstrItins, MI, OperIdx,
429                                                   DefSU->getInstr());
430       DefSU->addPred(SDep(SU, SDep::Output, OutLatency, Reg));
431     }
432     DefI->SU = SU;
433   }
434 }
435
436 /// addVRegUseDeps - Add a register data dependency if the instruction that
437 /// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
438 /// register antidependency from this SUnit to instructions that occur later in
439 /// the same scheduling region if they write the virtual register.
440 ///
441 /// TODO: Handle ExitSU "uses" properly.
442 void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
443   MachineInstr *MI = SU->getInstr();
444   unsigned Reg = MI->getOperand(OperIdx).getReg();
445
446   // Lookup this operand's reaching definition.
447   assert(LIS && "vreg dependencies requires LiveIntervals");
448   SlotIndex UseIdx = LIS->getInstructionIndex(MI).getRegSlot();
449   LiveInterval *LI = &LIS->getInterval(Reg);
450   VNInfo *VNI = LI->getVNInfoBefore(UseIdx);
451
452   // Special case: An early-clobber tied operand reads and writes the
453   // register one slot early. e.g. InlineAsm.
454   //
455   // FIXME: Same special case is in shrinkToUses. Hide under an API.
456   if (SlotIndex::isSameInstr(VNI->def, UseIdx)) {
457     UseIdx = VNI->def;
458     VNI = LI->getVNInfoBefore(UseIdx);
459   }
460   // VNI will be valid because MachineOperand::readsReg() is checked by caller.
461   MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def);
462   // Phis and other noninstructions (after coalescing) have a NULL Def.
463   if (Def) {
464     SUnit *DefSU = getSUnit(Def);
465     if (DefSU) {
466       // The reaching Def lives within this scheduling region.
467       // Create a data dependence.
468       //
469       // TODO: Handle "special" address latencies cleanly.
470       const SDep &dep = SDep(DefSU, SDep::Data, DefSU->Latency, Reg);
471       if (!UnitLatencies) {
472         // Adjust the dependence latency using operand def/use information, then
473         // allow the target to perform its own adjustments.
474         computeOperandLatency(DefSU, SU, const_cast<SDep &>(dep));
475         const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
476         ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
477       }
478       SU->addPred(dep);
479     }
480   }
481
482   // Add antidependence to the following def of the vreg it uses.
483   VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
484   if (DefI != VRegDefs.end() && DefI->SU != SU)
485     DefI->SU->addPred(SDep(SU, SDep::Anti, 0, Reg));
486 }
487
488 /// Return true if MI is an instruction we are unable to reason about
489 /// (like a call or something with unmodeled side effects).
490 static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
491   if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
492       (MI->hasVolatileMemoryRef() &&
493        (!MI->mayLoad() || !MI->isInvariantLoad(AA))))
494     return true;
495   return false;
496 }
497
498 // This MI might have either incomplete info, or known to be unsafe
499 // to deal with (i.e. volatile object).
500 static inline bool isUnsafeMemoryObject(MachineInstr *MI,
501                                         const MachineFrameInfo *MFI) {
502   if (!MI || MI->memoperands_empty())
503     return true;
504   // We purposefully do no check for hasOneMemOperand() here
505   // in hope to trigger an assert downstream in order to
506   // finish implementation.
507   if ((*MI->memoperands_begin())->isVolatile() ||
508        MI->hasUnmodeledSideEffects())
509     return true;
510
511   const Value *V = (*MI->memoperands_begin())->getValue();
512   if (!V)
513     return true;
514
515   V = getUnderlyingObject(V);
516   if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
517     // Similarly to getUnderlyingObjectForInstr:
518     // For now, ignore PseudoSourceValues which may alias LLVM IR values
519     // because the code that uses this function has no way to cope with
520     // such aliases.
521     if (PSV->isAliased(MFI))
522       return true;
523   }
524   // Does this pointer refer to a distinct and identifiable object?
525   if (!isIdentifiedObject(V))
526     return true;
527
528   return false;
529 }
530
531 /// This returns true if the two MIs need a chain edge betwee them.
532 /// If these are not even memory operations, we still may need
533 /// chain deps between them. The question really is - could
534 /// these two MIs be reordered during scheduling from memory dependency
535 /// point of view.
536 static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
537                              MachineInstr *MIa,
538                              MachineInstr *MIb) {
539   // Cover a trivial case - no edge is need to itself.
540   if (MIa == MIb)
541     return false;
542
543   if (isUnsafeMemoryObject(MIa, MFI) || isUnsafeMemoryObject(MIb, MFI))
544     return true;
545
546   // If we are dealing with two "normal" loads, we do not need an edge
547   // between them - they could be reordered.
548   if (!MIa->mayStore() && !MIb->mayStore())
549     return false;
550
551   // To this point analysis is generic. From here on we do need AA.
552   if (!AA)
553     return true;
554
555   MachineMemOperand *MMOa = *MIa->memoperands_begin();
556   MachineMemOperand *MMOb = *MIb->memoperands_begin();
557
558   // FIXME: Need to handle multiple memory operands to support all targets.
559   if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
560     llvm_unreachable("Multiple memory operands.");
561
562   // The following interface to AA is fashioned after DAGCombiner::isAlias
563   // and operates with MachineMemOperand offset with some important
564   // assumptions:
565   //   - LLVM fundamentally assumes flat address spaces.
566   //   - MachineOperand offset can *only* result from legalization and
567   //     cannot affect queries other than the trivial case of overlap
568   //     checking.
569   //   - These offsets never wrap and never step outside
570   //     of allocated objects.
571   //   - There should never be any negative offsets here.
572   //
573   // FIXME: Modify API to hide this math from "user"
574   // FIXME: Even before we go to AA we can reason locally about some
575   // memory objects. It can save compile time, and possibly catch some
576   // corner cases not currently covered.
577
578   assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
579   assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
580
581   int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
582   int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
583   int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
584
585   AliasAnalysis::AliasResult AAResult = AA->alias(
586   AliasAnalysis::Location(MMOa->getValue(), Overlapa,
587                           MMOa->getTBAAInfo()),
588   AliasAnalysis::Location(MMOb->getValue(), Overlapb,
589                           MMOb->getTBAAInfo()));
590
591   return (AAResult != AliasAnalysis::NoAlias);
592 }
593
594 /// This recursive function iterates over chain deps of SUb looking for
595 /// "latest" node that needs a chain edge to SUa.
596 static unsigned
597 iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI,
598                  SUnit *SUa, SUnit *SUb, SUnit *ExitSU, unsigned *Depth,
599                  SmallPtrSet<const SUnit*, 16> &Visited) {
600   if (!SUa || !SUb || SUb == ExitSU)
601     return *Depth;
602
603   // Remember visited nodes.
604   if (!Visited.insert(SUb))
605       return *Depth;
606   // If there is _some_ dependency already in place, do not
607   // descend any further.
608   // TODO: Need to make sure that if that dependency got eliminated or ignored
609   // for any reason in the future, we would not violate DAG topology.
610   // Currently it does not happen, but makes an implicit assumption about
611   // future implementation.
612   //
613   // Independently, if we encounter node that is some sort of global
614   // object (like a call) we already have full set of dependencies to it
615   // and we can stop descending.
616   if (SUa->isSucc(SUb) ||
617       isGlobalMemoryObject(AA, SUb->getInstr()))
618     return *Depth;
619
620   // If we do need an edge, or we have exceeded depth budget,
621   // add that edge to the predecessors chain of SUb,
622   // and stop descending.
623   if (*Depth > 200 ||
624       MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
625     SUb->addPred(SDep(SUa, SDep::Order, /*Latency=*/0, /*Reg=*/0,
626                       /*isNormalMemory=*/true));
627     return *Depth;
628   }
629   // Track current depth.
630   (*Depth)++;
631   // Iterate over chain dependencies only.
632   for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end();
633        I != E; ++I)
634     if (I->isCtrl())
635       iterateChainSucc (AA, MFI, SUa, I->getSUnit(), ExitSU, Depth, Visited);
636   return *Depth;
637 }
638
639 /// This function assumes that "downward" from SU there exist
640 /// tail/leaf of already constructed DAG. It iterates downward and
641 /// checks whether SU can be aliasing any node dominated
642 /// by it.
643 static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI,
644             SUnit *SU, SUnit *ExitSU, std::set<SUnit *> &CheckList) {
645   if (!SU)
646     return;
647
648   SmallPtrSet<const SUnit*, 16> Visited;
649   unsigned Depth = 0;
650
651   for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end();
652        I != IE; ++I) {
653     if (SU == *I)
654       continue;
655     if (MIsNeedChainEdge(AA, MFI, SU->getInstr(), (*I)->getInstr()))
656       (*I)->addPred(SDep(SU, SDep::Order, /*Latency=*/0, /*Reg=*/0,
657                          /*isNormalMemory=*/true));
658     // Now go through all the chain successors and iterate from them.
659     // Keep track of visited nodes.
660     for (SUnit::const_succ_iterator J = (*I)->Succs.begin(),
661          JE = (*I)->Succs.end(); J != JE; ++J)
662       if (J->isCtrl())
663         iterateChainSucc (AA, MFI, SU, J->getSUnit(),
664                           ExitSU, &Depth, Visited);
665   }
666 }
667
668 /// Check whether two objects need a chain edge, if so, add it
669 /// otherwise remember the rejected SU.
670 static inline
671 void addChainDependency (AliasAnalysis *AA, const MachineFrameInfo *MFI,
672                          SUnit *SUa, SUnit *SUb,
673                          std::set<SUnit *> &RejectList,
674                          unsigned TrueMemOrderLatency = 0,
675                          bool isNormalMemory = false) {
676   // If this is a false dependency,
677   // do not add the edge, but rememeber the rejected node.
678   if (!EnableAASchedMI ||
679       MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr()))
680     SUb->addPred(SDep(SUa, SDep::Order, TrueMemOrderLatency, /*Reg=*/0,
681                       isNormalMemory));
682   else {
683     // Duplicate entries should be ignored.
684     RejectList.insert(SUb);
685     DEBUG(dbgs() << "\tReject chain dep between SU("
686           << SUa->NodeNum << ") and SU("
687           << SUb->NodeNum << ")\n");
688   }
689 }
690
691 /// Create an SUnit for each real instruction, numbered in top-down toplological
692 /// order. The instruction order A < B, implies that no edge exists from B to A.
693 ///
694 /// Map each real instruction to its SUnit.
695 ///
696 /// After initSUnits, the SUnits vector cannot be resized and the scheduler may
697 /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
698 /// instead of pointers.
699 ///
700 /// MachineScheduler relies on initSUnits numbering the nodes by their order in
701 /// the original instruction list.
702 void ScheduleDAGInstrs::initSUnits() {
703   // We'll be allocating one SUnit for each real instruction in the region,
704   // which is contained within a basic block.
705   SUnits.reserve(BB->size());
706
707   for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
708     MachineInstr *MI = I;
709     if (MI->isDebugValue())
710       continue;
711
712     SUnit *SU = newSUnit(MI);
713     MISUnitMap[MI] = SU;
714
715     SU->isCall = MI->isCall();
716     SU->isCommutable = MI->isCommutable();
717
718     // Assign the Latency field of SU using target-provided information.
719     if (UnitLatencies)
720       SU->Latency = 1;
721     else
722       computeLatency(SU);
723   }
724 }
725
726 /// If RegPressure is non null, compute register pressure as a side effect. The
727 /// DAG builder is an efficient place to do it because it already visits
728 /// operands.
729 void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
730                                         RegPressureTracker *RPTracker) {
731   // Create an SUnit for each real instruction.
732   initSUnits();
733
734   // We build scheduling units by walking a block's instruction list from bottom
735   // to top.
736
737   // Remember where a generic side-effecting instruction is as we procede.
738   SUnit *BarrierChain = 0, *AliasChain = 0;
739
740   // Memory references to specific known memory locations are tracked
741   // so that they can be given more precise dependencies. We track
742   // separately the known memory locations that may alias and those
743   // that are known not to alias
744   std::map<const Value *, SUnit *> AliasMemDefs, NonAliasMemDefs;
745   std::map<const Value *, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
746   std::set<SUnit*> RejectMemNodes;
747
748   // Remove any stale debug info; sometimes BuildSchedGraph is called again
749   // without emitting the info from the previous call.
750   DbgValues.clear();
751   FirstDbgValue = NULL;
752
753   assert(Defs.empty() && Uses.empty() &&
754          "Only BuildGraph should update Defs/Uses");
755   Defs.setRegLimit(TRI->getNumRegs());
756   Uses.setRegLimit(TRI->getNumRegs());
757
758   assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
759   // FIXME: Allow SparseSet to reserve space for the creation of virtual
760   // registers during scheduling. Don't artificially inflate the Universe
761   // because we want to assert that vregs are not created during DAG building.
762   VRegDefs.setUniverse(MRI.getNumVirtRegs());
763
764   // Model data dependencies between instructions being scheduled and the
765   // ExitSU.
766   addSchedBarrierDeps();
767
768   // Walk the list of instructions, from bottom moving up.
769   MachineInstr *PrevMI = NULL;
770   for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
771        MII != MIE; --MII) {
772     MachineInstr *MI = prior(MII);
773     if (MI && PrevMI) {
774       DbgValues.push_back(std::make_pair(PrevMI, MI));
775       PrevMI = NULL;
776     }
777
778     if (MI->isDebugValue()) {
779       PrevMI = MI;
780       continue;
781     }
782     if (RPTracker) {
783       RPTracker->recede();
784       assert(RPTracker->getPos() == prior(MII) && "RPTracker can't find MI");
785     }
786
787     assert((!MI->isTerminator() || CanHandleTerminators) && !MI->isLabel() &&
788            "Cannot schedule terminators or labels!");
789
790     SUnit *SU = MISUnitMap[MI];
791     assert(SU && "No SUnit mapped to this MI");
792
793     // Add register-based dependencies (data, anti, and output).
794     for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
795       const MachineOperand &MO = MI->getOperand(j);
796       if (!MO.isReg()) continue;
797       unsigned Reg = MO.getReg();
798       if (Reg == 0) continue;
799
800       if (TRI->isPhysicalRegister(Reg))
801         addPhysRegDeps(SU, j);
802       else {
803         assert(!IsPostRA && "Virtual register encountered!");
804         if (MO.isDef())
805           addVRegDefDeps(SU, j);
806         else if (MO.readsReg()) // ignore undef operands
807           addVRegUseDeps(SU, j);
808       }
809     }
810
811     // Add chain dependencies.
812     // Chain dependencies used to enforce memory order should have
813     // latency of 0 (except for true dependency of Store followed by
814     // aliased Load... we estimate that with a single cycle of latency
815     // assuming the hardware will bypass)
816     // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
817     // after stack slots are lowered to actual addresses.
818     // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
819     // produce more precise dependence information.
820 #define STORE_LOAD_LATENCY 1
821     unsigned TrueMemOrderLatency = 0;
822     if (isGlobalMemoryObject(AA, MI)) {
823       // Be conservative with these and add dependencies on all memory
824       // references, even those that are known to not alias.
825       for (std::map<const Value *, SUnit *>::iterator I =
826              NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
827         I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
828       }
829       for (std::map<const Value *, std::vector<SUnit *> >::iterator I =
830              NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
831         for (unsigned i = 0, e = I->second.size(); i != e; ++i)
832           I->second[i]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency));
833       }
834       // Add SU to the barrier chain.
835       if (BarrierChain)
836         BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
837       BarrierChain = SU;
838       // This is a barrier event that acts as a pivotal node in the DAG,
839       // so it is safe to clear list of exposed nodes.
840       adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes);
841       RejectMemNodes.clear();
842       NonAliasMemDefs.clear();
843       NonAliasMemUses.clear();
844
845       // fall-through
846     new_alias_chain:
847       // Chain all possibly aliasing memory references though SU.
848       if (AliasChain)
849         addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
850       AliasChain = SU;
851       for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
852         addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
853                            TrueMemOrderLatency);
854       for (std::map<const Value *, SUnit *>::iterator I = AliasMemDefs.begin(),
855            E = AliasMemDefs.end(); I != E; ++I)
856         addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
857       for (std::map<const Value *, std::vector<SUnit *> >::iterator I =
858            AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
859         for (unsigned i = 0, e = I->second.size(); i != e; ++i)
860           addChainDependency(AA, MFI, SU, I->second[i], RejectMemNodes,
861                              TrueMemOrderLatency);
862       }
863       adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes);
864       PendingLoads.clear();
865       AliasMemDefs.clear();
866       AliasMemUses.clear();
867     } else if (MI->mayStore()) {
868       bool MayAlias = true;
869       TrueMemOrderLatency = STORE_LOAD_LATENCY;
870       if (const Value *V = getUnderlyingObjectForInstr(MI, MFI, MayAlias)) {
871         // A store to a specific PseudoSourceValue. Add precise dependencies.
872         // Record the def in MemDefs, first adding a dep if there is
873         // an existing def.
874         std::map<const Value *, SUnit *>::iterator I =
875           ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
876         std::map<const Value *, SUnit *>::iterator IE =
877           ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
878         if (I != IE) {
879           addChainDependency(AA, MFI, SU, I->second, RejectMemNodes,
880                              0, true);
881           I->second = SU;
882         } else {
883           if (MayAlias)
884             AliasMemDefs[V] = SU;
885           else
886             NonAliasMemDefs[V] = SU;
887         }
888         // Handle the uses in MemUses, if there are any.
889         std::map<const Value *, std::vector<SUnit *> >::iterator J =
890           ((MayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
891         std::map<const Value *, std::vector<SUnit *> >::iterator JE =
892           ((MayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
893         if (J != JE) {
894           for (unsigned i = 0, e = J->second.size(); i != e; ++i)
895             addChainDependency(AA, MFI, SU, J->second[i], RejectMemNodes,
896                                TrueMemOrderLatency, true);
897           J->second.clear();
898         }
899         if (MayAlias) {
900           // Add dependencies from all the PendingLoads, i.e. loads
901           // with no underlying object.
902           for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
903             addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
904                                TrueMemOrderLatency);
905           // Add dependence on alias chain, if needed.
906           if (AliasChain)
907             addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
908           // But we also should check dependent instructions for the
909           // SU in question.
910           adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes);
911         }
912         // Add dependence on barrier chain, if needed.
913         // There is no point to check aliasing on barrier event. Even if
914         // SU and barrier _could_ be reordered, they should not. In addition,
915         // we have lost all RejectMemNodes below barrier.
916         if (BarrierChain)
917           BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
918       } else {
919         // Treat all other stores conservatively.
920         goto new_alias_chain;
921       }
922
923       if (!ExitSU.isPred(SU))
924         // Push store's up a bit to avoid them getting in between cmp
925         // and branches.
926         ExitSU.addPred(SDep(SU, SDep::Order, 0,
927                             /*Reg=*/0, /*isNormalMemory=*/false,
928                             /*isMustAlias=*/false,
929                             /*isArtificial=*/true));
930     } else if (MI->mayLoad()) {
931       bool MayAlias = true;
932       TrueMemOrderLatency = 0;
933       if (MI->isInvariantLoad(AA)) {
934         // Invariant load, no chain dependencies needed!
935       } else {
936         if (const Value *V =
937             getUnderlyingObjectForInstr(MI, MFI, MayAlias)) {
938           // A load from a specific PseudoSourceValue. Add precise dependencies.
939           std::map<const Value *, SUnit *>::iterator I =
940             ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
941           std::map<const Value *, SUnit *>::iterator IE =
942             ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
943           if (I != IE)
944             addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true);
945           if (MayAlias)
946             AliasMemUses[V].push_back(SU);
947           else
948             NonAliasMemUses[V].push_back(SU);
949         } else {
950           // A load with no underlying object. Depend on all
951           // potentially aliasing stores.
952           for (std::map<const Value *, SUnit *>::iterator I =
953                  AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
954             addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
955
956           PendingLoads.push_back(SU);
957           MayAlias = true;
958         }
959         if (MayAlias)
960           adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes);
961         // Add dependencies on alias and barrier chains, if needed.
962         if (MayAlias && AliasChain)
963           addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
964         if (BarrierChain)
965           BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
966       }
967     }
968   }
969   if (PrevMI)
970     FirstDbgValue = PrevMI;
971
972   Defs.clear();
973   Uses.clear();
974   VRegDefs.clear();
975   PendingLoads.clear();
976 }
977
978 void ScheduleDAGInstrs::computeLatency(SUnit *SU) {
979   // Compute the latency for the node.
980   if (!InstrItins || InstrItins->isEmpty()) {
981     SU->Latency = 1;
982
983     // Simplistic target-independent heuristic: assume that loads take
984     // extra time.
985     if (SU->getInstr()->mayLoad())
986       SU->Latency += 2;
987   } else {
988     SU->Latency = TII->getInstrLatency(InstrItins, SU->getInstr());
989   }
990 }
991
992 void ScheduleDAGInstrs::computeOperandLatency(SUnit *Def, SUnit *Use,
993                                               SDep& dep) const {
994   if (!InstrItins || InstrItins->isEmpty())
995     return;
996
997   // For a data dependency with a known register...
998   if ((dep.getKind() != SDep::Data) || (dep.getReg() == 0))
999     return;
1000
1001   const unsigned Reg = dep.getReg();
1002
1003   // ... find the definition of the register in the defining
1004   // instruction
1005   MachineInstr *DefMI = Def->getInstr();
1006   int DefIdx = DefMI->findRegisterDefOperandIdx(Reg);
1007   if (DefIdx != -1) {
1008     const MachineOperand &MO = DefMI->getOperand(DefIdx);
1009     if (MO.isReg() && MO.isImplicit() &&
1010         DefIdx >= (int)DefMI->getDesc().getNumOperands()) {
1011       // This is an implicit def, getOperandLatency() won't return the correct
1012       // latency. e.g.
1013       //   %D6<def>, %D7<def> = VLD1q16 %R2<kill>, 0, ..., %Q3<imp-def>
1014       //   %Q1<def> = VMULv8i16 %Q1<kill>, %Q3<kill>, ...
1015       // What we want is to compute latency between def of %D6/%D7 and use of
1016       // %Q3 instead.
1017       unsigned Op2 = DefMI->findRegisterDefOperandIdx(Reg, false, true, TRI);
1018       if (DefMI->getOperand(Op2).isReg())
1019         DefIdx = Op2;
1020     }
1021     MachineInstr *UseMI = Use->getInstr();
1022     // For all uses of the register, calculate the maxmimum latency
1023     int Latency = -1;
1024     if (UseMI) {
1025       for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
1026         const MachineOperand &MO = UseMI->getOperand(i);
1027         if (!MO.isReg() || !MO.isUse())
1028           continue;
1029         unsigned MOReg = MO.getReg();
1030         if (MOReg != Reg)
1031           continue;
1032
1033         int UseCycle = TII->getOperandLatency(InstrItins, DefMI, DefIdx,
1034                                               UseMI, i);
1035         Latency = std::max(Latency, UseCycle);
1036       }
1037     } else {
1038       // UseMI is null, then it must be a scheduling barrier.
1039       if (!InstrItins || InstrItins->isEmpty())
1040         return;
1041       unsigned DefClass = DefMI->getDesc().getSchedClass();
1042       Latency = InstrItins->getOperandCycle(DefClass, DefIdx);
1043     }
1044
1045     // If we found a latency, then replace the existing dependence latency.
1046     if (Latency >= 0)
1047       dep.setLatency(Latency);
1048   }
1049 }
1050
1051 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
1052   SU->getInstr()->dump();
1053 }
1054
1055 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
1056   std::string s;
1057   raw_string_ostream oss(s);
1058   if (SU == &EntrySU)
1059     oss << "<entry>";
1060   else if (SU == &ExitSU)
1061     oss << "<exit>";
1062   else
1063     SU->getInstr()->print(oss);
1064   return oss.str();
1065 }
1066
1067 /// Return the basic block label. It is not necessarilly unique because a block
1068 /// contains multiple scheduling regions. But it is fine for visualization.
1069 std::string ScheduleDAGInstrs::getDAGName() const {
1070   return "dag." + BB->getFullName();
1071 }