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