39cad7f35d20d46b12dc660d349e598991c5dcd3
[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 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
16 #include "llvm/ADT/MapVector.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineMemOperand.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/PseudoSourceValue.h"
28 #include "llvm/CodeGen/RegisterPressure.h"
29 #include "llvm/CodeGen/ScheduleDFS.h"
30 #include "llvm/IR/Operator.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/Format.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
39 #include <queue>
40
41 using namespace llvm;
42
43 #define DEBUG_TYPE "misched"
44
45 static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
46     cl::ZeroOrMore, cl::init(false),
47     cl::desc("Enable use of AA during MI DAG construction"));
48
49 static cl::opt<bool> UseTBAA("use-tbaa-in-sched-mi", cl::Hidden,
50     cl::init(true), cl::desc("Enable use of TBAA during MI DAG construction"));
51
52 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
53                                      const MachineLoopInfo *mli,
54                                      bool IsPostRAFlag, bool RemoveKillFlags,
55                                      LiveIntervals *lis)
56     : ScheduleDAG(mf), MLI(mli), MFI(mf.getFrameInfo()), LIS(lis),
57       IsPostRA(IsPostRAFlag), RemoveKillFlags(RemoveKillFlags),
58       CanHandleTerminators(false), FirstDbgValue(nullptr) {
59   assert((IsPostRA || LIS) && "PreRA scheduling requires LiveIntervals");
60   DbgValues.clear();
61   assert(!(IsPostRA && MRI.getNumVirtRegs()) &&
62          "Virtual registers must be removed prior to PostRA scheduling");
63
64   const TargetSubtargetInfo &ST = mf.getSubtarget();
65   SchedModel.init(ST.getSchedModel(), &ST, TII);
66 }
67
68 /// getUnderlyingObjectFromInt - This is the function that does the work of
69 /// looking through basic ptrtoint+arithmetic+inttoptr sequences.
70 static const Value *getUnderlyingObjectFromInt(const Value *V) {
71   do {
72     if (const Operator *U = dyn_cast<Operator>(V)) {
73       // If we find a ptrtoint, we can transfer control back to the
74       // regular getUnderlyingObjectFromInt.
75       if (U->getOpcode() == Instruction::PtrToInt)
76         return U->getOperand(0);
77       // If we find an add of a constant, a multiplied value, or a phi, it's
78       // likely that the other operand will lead us to the base
79       // object. We don't have to worry about the case where the
80       // object address is somehow being computed by the multiply,
81       // because our callers only care when the result is an
82       // identifiable object.
83       if (U->getOpcode() != Instruction::Add ||
84           (!isa<ConstantInt>(U->getOperand(1)) &&
85            Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
86            !isa<PHINode>(U->getOperand(1))))
87         return V;
88       V = U->getOperand(0);
89     } else {
90       return V;
91     }
92     assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
93   } while (1);
94 }
95
96 /// getUnderlyingObjects - This is a wrapper around GetUnderlyingObjects
97 /// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
98 static void getUnderlyingObjects(const Value *V,
99                                  SmallVectorImpl<Value *> &Objects,
100                                  const DataLayout &DL) {
101   SmallPtrSet<const Value *, 16> Visited;
102   SmallVector<const Value *, 4> Working(1, V);
103   do {
104     V = Working.pop_back_val();
105
106     SmallVector<Value *, 4> Objs;
107     GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
108
109     for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), IE = Objs.end();
110          I != IE; ++I) {
111       V = *I;
112       if (!Visited.insert(V).second)
113         continue;
114       if (Operator::getOpcode(V) == Instruction::IntToPtr) {
115         const Value *O =
116           getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
117         if (O->getType()->isPointerTy()) {
118           Working.push_back(O);
119           continue;
120         }
121       }
122       Objects.push_back(const_cast<Value *>(V));
123     }
124   } while (!Working.empty());
125 }
126
127 typedef PointerUnion<const Value *, const PseudoSourceValue *> ValueType;
128 typedef SmallVector<PointerIntPair<ValueType, 1, bool>, 4>
129 UnderlyingObjectsVector;
130
131 /// getUnderlyingObjectsForInstr - If this machine instr has memory reference
132 /// information and it can be tracked to a normal reference to a known
133 /// object, return the Value for that object.
134 static void getUnderlyingObjectsForInstr(const MachineInstr *MI,
135                                          const MachineFrameInfo *MFI,
136                                          UnderlyingObjectsVector &Objects,
137                                          const DataLayout &DL) {
138   if (!MI->hasOneMemOperand() ||
139       (!(*MI->memoperands_begin())->getValue() &&
140        !(*MI->memoperands_begin())->getPseudoValue()) ||
141       (*MI->memoperands_begin())->isVolatile())
142     return;
143
144   if (const PseudoSourceValue *PSV =
145       (*MI->memoperands_begin())->getPseudoValue()) {
146     // Function that contain tail calls don't have unique PseudoSourceValue
147     // objects. Two PseudoSourceValues might refer to the same or overlapping
148     // locations. The client code calling this function assumes this is not the
149     // case. So return a conservative answer of no known object.
150     if (MFI->hasTailCall())
151       return;
152
153     // For now, ignore PseudoSourceValues which may alias LLVM IR values
154     // because the code that uses this function has no way to cope with
155     // such aliases.
156     if (!PSV->isAliased(MFI)) {
157       bool MayAlias = PSV->mayAlias(MFI);
158       Objects.push_back(UnderlyingObjectsVector::value_type(PSV, MayAlias));
159     }
160     return;
161   }
162
163   const Value *V = (*MI->memoperands_begin())->getValue();
164   if (!V)
165     return;
166
167   SmallVector<Value *, 4> Objs;
168   getUnderlyingObjects(V, Objs, DL);
169
170   for (Value *V : Objs) {
171     if (!isIdentifiedObject(V)) {
172       Objects.clear();
173       return;
174     }
175
176     Objects.push_back(UnderlyingObjectsVector::value_type(V, true));
177   }
178 }
179
180 void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
181   BB = bb;
182 }
183
184 void ScheduleDAGInstrs::finishBlock() {
185   // Subclasses should no longer refer to the old block.
186   BB = nullptr;
187 }
188
189 /// Initialize the DAG and common scheduler state for the current scheduling
190 /// region. This does not actually create the DAG, only clears it. The
191 /// scheduling driver may call BuildSchedGraph multiple times per scheduling
192 /// region.
193 void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
194                                     MachineBasicBlock::iterator begin,
195                                     MachineBasicBlock::iterator end,
196                                     unsigned regioninstrs) {
197   assert(bb == BB && "startBlock should set BB");
198   RegionBegin = begin;
199   RegionEnd = end;
200   NumRegionInstrs = regioninstrs;
201 }
202
203 /// Close the current scheduling region. Don't clear any state in case the
204 /// driver wants to refer to the previous scheduling region.
205 void ScheduleDAGInstrs::exitRegion() {
206   // Nothing to do.
207 }
208
209 /// addSchedBarrierDeps - Add dependencies from instructions in the current
210 /// list of instructions being scheduled to scheduling barrier by adding
211 /// the exit SU to the register defs and use list. This is because we want to
212 /// make sure instructions which define registers that are either used by
213 /// the terminator or are live-out are properly scheduled. This is
214 /// especially important when the definition latency of the return value(s)
215 /// are too high to be hidden by the branch or when the liveout registers
216 /// used by instructions in the fallthrough block.
217 void ScheduleDAGInstrs::addSchedBarrierDeps() {
218   MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : nullptr;
219   ExitSU.setInstr(ExitMI);
220   bool AllDepKnown = ExitMI &&
221     (ExitMI->isCall() || ExitMI->isBarrier());
222   if (ExitMI && AllDepKnown) {
223     // If it's a call or a barrier, add dependencies on the defs and uses of
224     // instruction.
225     for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
226       const MachineOperand &MO = ExitMI->getOperand(i);
227       if (!MO.isReg() || MO.isDef()) continue;
228       unsigned Reg = MO.getReg();
229       if (Reg == 0) continue;
230
231       if (TRI->isPhysicalRegister(Reg))
232         Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
233       else {
234         assert(!IsPostRA && "Virtual register encountered after regalloc.");
235         if (MO.readsReg()) // ignore undef operands
236           addVRegUseDeps(&ExitSU, i);
237       }
238     }
239   } else {
240     // For others, e.g. fallthrough, conditional branch, assume the exit
241     // uses all the registers that are livein to the successor blocks.
242     assert(Uses.empty() && "Uses in set before adding deps?");
243     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
244            SE = BB->succ_end(); SI != SE; ++SI)
245       for (const auto &LI : (*SI)->liveins()) {
246         if (!Uses.contains(LI.PhysReg))
247           Uses.insert(PhysRegSUOper(&ExitSU, -1, LI.PhysReg));
248       }
249   }
250 }
251
252 /// MO is an operand of SU's instruction that defines a physical register. Add
253 /// data dependencies from SU to any uses of the physical register.
254 void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
255   const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
256   assert(MO.isDef() && "expect physreg def");
257
258   // Ask the target if address-backscheduling is desirable, and if so how much.
259   const TargetSubtargetInfo &ST = MF.getSubtarget();
260
261   for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
262        Alias.isValid(); ++Alias) {
263     if (!Uses.contains(*Alias))
264       continue;
265     for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
266       SUnit *UseSU = I->SU;
267       if (UseSU == SU)
268         continue;
269
270       // Adjust the dependence latency using operand def/use information,
271       // then allow the target to perform its own adjustments.
272       int UseOp = I->OpIdx;
273       MachineInstr *RegUse = nullptr;
274       SDep Dep;
275       if (UseOp < 0)
276         Dep = SDep(SU, SDep::Artificial);
277       else {
278         // Set the hasPhysRegDefs only for physreg defs that have a use within
279         // the scheduling region.
280         SU->hasPhysRegDefs = true;
281         Dep = SDep(SU, SDep::Data, *Alias);
282         RegUse = UseSU->getInstr();
283       }
284       Dep.setLatency(
285         SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, RegUse,
286                                          UseOp));
287
288       ST.adjustSchedDependency(SU, UseSU, Dep);
289       UseSU->addPred(Dep);
290     }
291   }
292 }
293
294 /// addPhysRegDeps - Add register dependencies (data, anti, and output) from
295 /// this SUnit to following instructions in the same scheduling region that
296 /// depend the physical register referenced at OperIdx.
297 void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
298   MachineInstr *MI = SU->getInstr();
299   MachineOperand &MO = MI->getOperand(OperIdx);
300
301   // Optionally add output and anti dependencies. For anti
302   // dependencies we use a latency of 0 because for a multi-issue
303   // target we want to allow the defining instruction to issue
304   // in the same cycle as the using instruction.
305   // TODO: Using a latency of 1 here for output dependencies assumes
306   //       there's no cost for reusing registers.
307   SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
308   for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
309        Alias.isValid(); ++Alias) {
310     if (!Defs.contains(*Alias))
311       continue;
312     for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
313       SUnit *DefSU = I->SU;
314       if (DefSU == &ExitSU)
315         continue;
316       if (DefSU != SU &&
317           (Kind != SDep::Output || !MO.isDead() ||
318            !DefSU->getInstr()->registerDefIsDead(*Alias))) {
319         if (Kind == SDep::Anti)
320           DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
321         else {
322           SDep Dep(SU, Kind, /*Reg=*/*Alias);
323           Dep.setLatency(
324             SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
325           DefSU->addPred(Dep);
326         }
327       }
328     }
329   }
330
331   if (!MO.isDef()) {
332     SU->hasPhysRegUses = true;
333     // Either insert a new Reg2SUnits entry with an empty SUnits list, or
334     // retrieve the existing SUnits list for this register's uses.
335     // Push this SUnit on the use list.
336     Uses.insert(PhysRegSUOper(SU, OperIdx, MO.getReg()));
337     if (RemoveKillFlags)
338       MO.setIsKill(false);
339   }
340   else {
341     addPhysRegDataDeps(SU, OperIdx);
342     unsigned Reg = MO.getReg();
343
344     // clear this register's use list
345     if (Uses.contains(Reg))
346       Uses.eraseAll(Reg);
347
348     if (!MO.isDead()) {
349       Defs.eraseAll(Reg);
350     } else if (SU->isCall) {
351       // Calls will not be reordered because of chain dependencies (see
352       // below). Since call operands are dead, calls may continue to be added
353       // to the DefList making dependence checking quadratic in the size of
354       // the block. Instead, we leave only one call at the back of the
355       // DefList.
356       Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
357       Reg2SUnitsMap::iterator B = P.first;
358       Reg2SUnitsMap::iterator I = P.second;
359       for (bool isBegin = I == B; !isBegin; /* empty */) {
360         isBegin = (--I) == B;
361         if (!I->SU->isCall)
362           break;
363         I = Defs.erase(I);
364       }
365     }
366
367     // Defs are pushed in the order they are visited and never reordered.
368     Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
369   }
370 }
371
372 /// addVRegDefDeps - Add register output and data dependencies from this SUnit
373 /// to instructions that occur later in the same scheduling region if they read
374 /// from or write to the virtual register defined at OperIdx.
375 ///
376 /// TODO: Hoist loop induction variable increments. This has to be
377 /// reevaluated. Generally, IV scheduling should be done before coalescing.
378 void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
379   const MachineInstr *MI = SU->getInstr();
380   unsigned Reg = MI->getOperand(OperIdx).getReg();
381
382   // Singly defined vregs do not have output/anti dependencies.
383   // The current operand is a def, so we have at least one.
384   // Check here if there are any others...
385   if (MRI.hasOneDef(Reg))
386     return;
387
388   // Add output dependence to the next nearest def of this vreg.
389   //
390   // Unless this definition is dead, the output dependence should be
391   // transitively redundant with antidependencies from this definition's
392   // uses. We're conservative for now until we have a way to guarantee the uses
393   // are not eliminated sometime during scheduling. The output dependence edge
394   // is also useful if output latency exceeds def-use latency.
395   VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
396   if (DefI == VRegDefs.end())
397     VRegDefs.insert(VReg2SUnit(Reg, SU));
398   else {
399     SUnit *DefSU = DefI->SU;
400     if (DefSU != SU && DefSU != &ExitSU) {
401       SDep Dep(SU, SDep::Output, Reg);
402       Dep.setLatency(
403         SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
404       DefSU->addPred(Dep);
405     }
406     DefI->SU = SU;
407   }
408 }
409
410 /// addVRegUseDeps - Add a register data dependency if the instruction that
411 /// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
412 /// register antidependency from this SUnit to instructions that occur later in
413 /// the same scheduling region if they write the virtual register.
414 ///
415 /// TODO: Handle ExitSU "uses" properly.
416 void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
417   MachineInstr *MI = SU->getInstr();
418   unsigned Reg = MI->getOperand(OperIdx).getReg();
419
420   // Record this local VReg use.
421   VReg2UseMap::iterator UI = VRegUses.find(Reg);
422   for (; UI != VRegUses.end(); ++UI) {
423     if (UI->SU == SU)
424       break;
425   }
426   if (UI == VRegUses.end())
427     VRegUses.insert(VReg2SUnit(Reg, SU));
428
429   // Lookup this operand's reaching definition.
430   assert(LIS && "vreg dependencies requires LiveIntervals");
431   LiveQueryResult LRQ
432     = LIS->getInterval(Reg).Query(LIS->getInstructionIndex(MI));
433   VNInfo *VNI = LRQ.valueIn();
434
435   // VNI will be valid because MachineOperand::readsReg() is checked by caller.
436   assert(VNI && "No value to read by operand");
437   MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def);
438   // Phis and other noninstructions (after coalescing) have a NULL Def.
439   if (Def) {
440     SUnit *DefSU = getSUnit(Def);
441     if (DefSU) {
442       // The reaching Def lives within this scheduling region.
443       // Create a data dependence.
444       SDep dep(DefSU, SDep::Data, Reg);
445       // Adjust the dependence latency using operand def/use information, then
446       // allow the target to perform its own adjustments.
447       int DefOp = Def->findRegisterDefOperandIdx(Reg);
448       dep.setLatency(SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx));
449
450       const TargetSubtargetInfo &ST = MF.getSubtarget();
451       ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
452       SU->addPred(dep);
453     }
454   }
455
456   // Add antidependence to the following def of the vreg it uses.
457   VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
458   if (DefI != VRegDefs.end() && DefI->SU != SU)
459     DefI->SU->addPred(SDep(SU, SDep::Anti, Reg));
460 }
461
462 /// Return true if MI is an instruction we are unable to reason about
463 /// (like a call or something with unmodeled side effects).
464 static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
465   if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
466       (MI->hasOrderedMemoryRef() &&
467        (!MI->mayLoad() || !MI->isInvariantLoad(AA))))
468     return true;
469   return false;
470 }
471
472 // This MI might have either incomplete info, or known to be unsafe
473 // to deal with (i.e. volatile object).
474 static inline bool isUnsafeMemoryObject(MachineInstr *MI,
475                                         const MachineFrameInfo *MFI,
476                                         const DataLayout &DL) {
477   if (!MI || MI->memoperands_empty())
478     return true;
479   // We purposefully do no check for hasOneMemOperand() here
480   // in hope to trigger an assert downstream in order to
481   // finish implementation.
482   if ((*MI->memoperands_begin())->isVolatile() ||
483        MI->hasUnmodeledSideEffects())
484     return true;
485
486   if ((*MI->memoperands_begin())->getPseudoValue()) {
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     return true;
492   }
493
494   const Value *V = (*MI->memoperands_begin())->getValue();
495   if (!V)
496     return true;
497
498   SmallVector<Value *, 4> Objs;
499   getUnderlyingObjects(V, Objs, DL);
500   for (Value *V : Objs) {
501     // Does this pointer refer to a distinct and identifiable object?
502     if (!isIdentifiedObject(V))
503       return true;
504   }
505
506   return false;
507 }
508
509 /// This returns true if the two MIs need a chain edge between them.
510 /// If these are not even memory operations, we still may need
511 /// chain deps between them. The question really is - could
512 /// these two MIs be reordered during scheduling from memory dependency
513 /// point of view.
514 static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
515                              const DataLayout &DL, MachineInstr *MIa,
516                              MachineInstr *MIb) {
517   const MachineFunction *MF = MIa->getParent()->getParent();
518   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
519
520   // Cover a trivial case - no edge is need to itself.
521   if (MIa == MIb)
522     return false;
523  
524   // Let the target decide if memory accesses cannot possibly overlap.
525   if ((MIa->mayLoad() || MIa->mayStore()) &&
526       (MIb->mayLoad() || MIb->mayStore()))
527     if (TII->areMemAccessesTriviallyDisjoint(MIa, MIb, AA))
528       return false;
529
530   // FIXME: Need to handle multiple memory operands to support all targets.
531   if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
532     return true;
533
534   if (isUnsafeMemoryObject(MIa, MFI, DL) || isUnsafeMemoryObject(MIb, MFI, DL))
535     return true;
536
537   // If we are dealing with two "normal" loads, we do not need an edge
538   // between them - they could be reordered.
539   if (!MIa->mayStore() && !MIb->mayStore())
540     return false;
541
542   // To this point analysis is generic. From here on we do need AA.
543   if (!AA)
544     return true;
545
546   MachineMemOperand *MMOa = *MIa->memoperands_begin();
547   MachineMemOperand *MMOb = *MIb->memoperands_begin();
548
549   if (!MMOa->getValue() || !MMOb->getValue())
550     return true;
551
552   // The following interface to AA is fashioned after DAGCombiner::isAlias
553   // and operates with MachineMemOperand offset with some important
554   // assumptions:
555   //   - LLVM fundamentally assumes flat address spaces.
556   //   - MachineOperand offset can *only* result from legalization and
557   //     cannot affect queries other than the trivial case of overlap
558   //     checking.
559   //   - These offsets never wrap and never step outside
560   //     of allocated objects.
561   //   - There should never be any negative offsets here.
562   //
563   // FIXME: Modify API to hide this math from "user"
564   // FIXME: Even before we go to AA we can reason locally about some
565   // memory objects. It can save compile time, and possibly catch some
566   // corner cases not currently covered.
567
568   assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
569   assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
570
571   int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
572   int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
573   int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
574
575   AliasResult AAResult =
576       AA->alias(MemoryLocation(MMOa->getValue(), Overlapa,
577                                UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
578                 MemoryLocation(MMOb->getValue(), Overlapb,
579                                UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
580
581   return (AAResult != NoAlias);
582 }
583
584 /// This recursive function iterates over chain deps of SUb looking for
585 /// "latest" node that needs a chain edge to SUa.
586 static unsigned iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI,
587                                  const DataLayout &DL, SUnit *SUa, SUnit *SUb,
588                                  SUnit *ExitSU, unsigned *Depth,
589                                  SmallPtrSetImpl<const SUnit *> &Visited) {
590   if (!SUa || !SUb || SUb == ExitSU)
591     return *Depth;
592
593   // Remember visited nodes.
594   if (!Visited.insert(SUb).second)
595       return *Depth;
596   // If there is _some_ dependency already in place, do not
597   // descend any further.
598   // TODO: Need to make sure that if that dependency got eliminated or ignored
599   // for any reason in the future, we would not violate DAG topology.
600   // Currently it does not happen, but makes an implicit assumption about
601   // future implementation.
602   //
603   // Independently, if we encounter node that is some sort of global
604   // object (like a call) we already have full set of dependencies to it
605   // and we can stop descending.
606   if (SUa->isSucc(SUb) ||
607       isGlobalMemoryObject(AA, SUb->getInstr()))
608     return *Depth;
609
610   // If we do need an edge, or we have exceeded depth budget,
611   // add that edge to the predecessors chain of SUb,
612   // and stop descending.
613   if (*Depth > 200 ||
614       MIsNeedChainEdge(AA, MFI, DL, SUa->getInstr(), SUb->getInstr())) {
615     SUb->addPred(SDep(SUa, SDep::MayAliasMem));
616     return *Depth;
617   }
618   // Track current depth.
619   (*Depth)++;
620   // Iterate over memory dependencies only.
621   for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end();
622        I != E; ++I)
623     if (I->isNormalMemoryOrBarrier())
624       iterateChainSucc(AA, MFI, DL, SUa, I->getSUnit(), ExitSU, Depth, Visited);
625   return *Depth;
626 }
627
628 /// This function assumes that "downward" from SU there exist
629 /// tail/leaf of already constructed DAG. It iterates downward and
630 /// checks whether SU can be aliasing any node dominated
631 /// by it.
632 static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI,
633                             const DataLayout &DL, SUnit *SU, SUnit *ExitSU,
634                             std::set<SUnit *> &CheckList,
635                             unsigned LatencyToLoad) {
636   if (!SU)
637     return;
638
639   SmallPtrSet<const SUnit*, 16> Visited;
640   unsigned Depth = 0;
641
642   for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end();
643        I != IE; ++I) {
644     if (SU == *I)
645       continue;
646     if (MIsNeedChainEdge(AA, MFI, DL, SU->getInstr(), (*I)->getInstr())) {
647       SDep Dep(SU, SDep::MayAliasMem);
648       Dep.setLatency(((*I)->getInstr()->mayLoad()) ? LatencyToLoad : 0);
649       (*I)->addPred(Dep);
650     }
651
652     // Iterate recursively over all previously added memory chain
653     // successors. Keep track of visited nodes.
654     for (SUnit::const_succ_iterator J = (*I)->Succs.begin(),
655          JE = (*I)->Succs.end(); J != JE; ++J)
656       if (J->isNormalMemoryOrBarrier())
657         iterateChainSucc(AA, MFI, DL, SU, J->getSUnit(), ExitSU, &Depth,
658                          Visited);
659   }
660 }
661
662 /// Check whether two objects need a chain edge, if so, add it
663 /// otherwise remember the rejected SU.
664 static inline void addChainDependency(AliasAnalysis *AA,
665                                       const MachineFrameInfo *MFI,
666                                       const DataLayout &DL, SUnit *SUa,
667                                       SUnit *SUb, std::set<SUnit *> &RejectList,
668                                       unsigned TrueMemOrderLatency = 0,
669                                       bool isNormalMemory = false) {
670   // If this is a false dependency,
671   // do not add the edge, but remember the rejected node.
672   if (MIsNeedChainEdge(AA, MFI, DL, SUa->getInstr(), SUb->getInstr())) {
673     SDep Dep(SUa, isNormalMemory ? SDep::MayAliasMem : SDep::Barrier);
674     Dep.setLatency(TrueMemOrderLatency);
675     SUb->addPred(Dep);
676   }
677   else {
678     // Duplicate entries should be ignored.
679     RejectList.insert(SUb);
680     DEBUG(dbgs() << "\tReject chain dep between SU("
681           << SUa->NodeNum << ") and SU("
682           << SUb->NodeNum << ")\n");
683   }
684 }
685
686 /// Create an SUnit for each real instruction, numbered in top-down topological
687 /// order. The instruction order A < B, implies that no edge exists from B to A.
688 ///
689 /// Map each real instruction to its SUnit.
690 ///
691 /// After initSUnits, the SUnits vector cannot be resized and the scheduler may
692 /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
693 /// instead of pointers.
694 ///
695 /// MachineScheduler relies on initSUnits numbering the nodes by their order in
696 /// the original instruction list.
697 void ScheduleDAGInstrs::initSUnits() {
698   // We'll be allocating one SUnit for each real instruction in the region,
699   // which is contained within a basic block.
700   SUnits.reserve(NumRegionInstrs);
701
702   for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
703     MachineInstr *MI = I;
704     if (MI->isDebugValue())
705       continue;
706
707     SUnit *SU = newSUnit(MI);
708     MISUnitMap[MI] = SU;
709
710     SU->isCall = MI->isCall();
711     SU->isCommutable = MI->isCommutable();
712
713     // Assign the Latency field of SU using target-provided information.
714     SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
715
716     // If this SUnit uses a reserved or unbuffered resource, mark it as such.
717     //
718     // Reserved resources block an instruction from issuing and stall the
719     // entire pipeline. These are identified by BufferSize=0.
720     //
721     // Unbuffered resources prevent execution of subsequent instructions that
722     // require the same resources. This is used for in-order execution pipelines
723     // within an out-of-order core. These are identified by BufferSize=1.
724     if (SchedModel.hasInstrSchedModel()) {
725       const MCSchedClassDesc *SC = getSchedClass(SU);
726       for (TargetSchedModel::ProcResIter
727              PI = SchedModel.getWriteProcResBegin(SC),
728              PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
729         switch (SchedModel.getProcResource(PI->ProcResourceIdx)->BufferSize) {
730         case 0:
731           SU->hasReservedResource = true;
732           break;
733         case 1:
734           SU->isUnbuffered = true;
735           break;
736         default:
737           break;
738         }
739       }
740     }
741   }
742 }
743
744 /// If RegPressure is non-null, compute register pressure as a side effect. The
745 /// DAG builder is an efficient place to do it because it already visits
746 /// operands.
747 void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
748                                         RegPressureTracker *RPTracker,
749                                         PressureDiffs *PDiffs) {
750   const TargetSubtargetInfo &ST = MF.getSubtarget();
751   bool UseAA = EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI
752                                                        : ST.useAA();
753   AliasAnalysis *AAForDep = UseAA ? AA : nullptr;
754
755   MISUnitMap.clear();
756   ScheduleDAG::clearDAG();
757
758   // Create an SUnit for each real instruction.
759   initSUnits();
760
761   if (PDiffs)
762     PDiffs->init(SUnits.size());
763
764   // We build scheduling units by walking a block's instruction list from bottom
765   // to top.
766
767   // Remember where a generic side-effecting instruction is as we proceed.
768   SUnit *BarrierChain = nullptr, *AliasChain = nullptr;
769
770   // Memory references to specific known memory locations are tracked
771   // so that they can be given more precise dependencies. We track
772   // separately the known memory locations that may alias and those
773   // that are known not to alias
774   MapVector<ValueType, std::vector<SUnit *> > AliasMemDefs, NonAliasMemDefs;
775   MapVector<ValueType, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
776   std::set<SUnit*> RejectMemNodes;
777
778   // Remove any stale debug info; sometimes BuildSchedGraph is called again
779   // without emitting the info from the previous call.
780   DbgValues.clear();
781   FirstDbgValue = nullptr;
782
783   assert(Defs.empty() && Uses.empty() &&
784          "Only BuildGraph should update Defs/Uses");
785   Defs.setUniverse(TRI->getNumRegs());
786   Uses.setUniverse(TRI->getNumRegs());
787
788   assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
789   VRegUses.clear();
790   VRegDefs.setUniverse(MRI.getNumVirtRegs());
791   VRegUses.setUniverse(MRI.getNumVirtRegs());
792
793   // Model data dependencies between instructions being scheduled and the
794   // ExitSU.
795   addSchedBarrierDeps();
796
797   // Walk the list of instructions, from bottom moving up.
798   MachineInstr *DbgMI = nullptr;
799   for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
800        MII != MIE; --MII) {
801     MachineInstr *MI = std::prev(MII);
802     if (MI && DbgMI) {
803       DbgValues.push_back(std::make_pair(DbgMI, MI));
804       DbgMI = nullptr;
805     }
806
807     if (MI->isDebugValue()) {
808       DbgMI = MI;
809       continue;
810     }
811     SUnit *SU = MISUnitMap[MI];
812     assert(SU && "No SUnit mapped to this MI");
813
814     if (RPTracker) {
815       PressureDiff *PDiff = PDiffs ? &(*PDiffs)[SU->NodeNum] : nullptr;
816       RPTracker->recede(/*LiveUses=*/nullptr, PDiff);
817       assert(RPTracker->getPos() == std::prev(MII) &&
818              "RPTracker can't find MI");
819     }
820
821     assert(
822         (CanHandleTerminators || (!MI->isTerminator() && !MI->isPosition())) &&
823         "Cannot schedule terminators or labels!");
824
825     // Add register-based dependencies (data, anti, and output).
826     bool HasVRegDef = false;
827     for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
828       const MachineOperand &MO = MI->getOperand(j);
829       if (!MO.isReg()) continue;
830       unsigned Reg = MO.getReg();
831       if (Reg == 0) continue;
832
833       if (TRI->isPhysicalRegister(Reg))
834         addPhysRegDeps(SU, j);
835       else {
836         assert(!IsPostRA && "Virtual register encountered!");
837         if (MO.isDef()) {
838           HasVRegDef = true;
839           addVRegDefDeps(SU, j);
840         }
841         else if (MO.readsReg()) // ignore undef operands
842           addVRegUseDeps(SU, j);
843       }
844     }
845     // If we haven't seen any uses in this scheduling region, create a
846     // dependence edge to ExitSU to model the live-out latency. This is required
847     // for vreg defs with no in-region use, and prefetches with no vreg def.
848     //
849     // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
850     // check currently relies on being called before adding chain deps.
851     if (SU->NumSuccs == 0 && SU->Latency > 1
852         && (HasVRegDef || MI->mayLoad())) {
853       SDep Dep(SU, SDep::Artificial);
854       Dep.setLatency(SU->Latency - 1);
855       ExitSU.addPred(Dep);
856     }
857
858     // Add chain dependencies.
859     // Chain dependencies used to enforce memory order should have
860     // latency of 0 (except for true dependency of Store followed by
861     // aliased Load... we estimate that with a single cycle of latency
862     // assuming the hardware will bypass)
863     // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
864     // after stack slots are lowered to actual addresses.
865     // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
866     // produce more precise dependence information.
867     unsigned TrueMemOrderLatency = MI->mayStore() ? 1 : 0;
868     if (isGlobalMemoryObject(AA, MI)) {
869       // Be conservative with these and add dependencies on all memory
870       // references, even those that are known to not alias.
871       for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
872              NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
873         for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
874           I->second[i]->addPred(SDep(SU, SDep::Barrier));
875         }
876       }
877       for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
878              NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
879         for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
880           SDep Dep(SU, SDep::Barrier);
881           Dep.setLatency(TrueMemOrderLatency);
882           I->second[i]->addPred(Dep);
883         }
884       }
885       // Add SU to the barrier chain.
886       if (BarrierChain)
887         BarrierChain->addPred(SDep(SU, SDep::Barrier));
888       BarrierChain = SU;
889       // This is a barrier event that acts as a pivotal node in the DAG,
890       // so it is safe to clear list of exposed nodes.
891       adjustChainDeps(AA, MFI, MF.getDataLayout(), SU, &ExitSU, RejectMemNodes,
892                       TrueMemOrderLatency);
893       RejectMemNodes.clear();
894       NonAliasMemDefs.clear();
895       NonAliasMemUses.clear();
896
897       // fall-through
898     new_alias_chain:
899       // Chain all possibly aliasing memory references through SU.
900       if (AliasChain) {
901         unsigned ChainLatency = 0;
902         if (AliasChain->getInstr()->mayLoad())
903           ChainLatency = TrueMemOrderLatency;
904         addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU, AliasChain,
905                            RejectMemNodes, ChainLatency);
906       }
907       AliasChain = SU;
908       for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
909         addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU,
910                            PendingLoads[k], RejectMemNodes,
911                            TrueMemOrderLatency);
912       for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
913            AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I) {
914         for (unsigned i = 0, e = I->second.size(); i != e; ++i)
915           addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU,
916                              I->second[i], RejectMemNodes);
917       }
918       for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
919            AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
920         for (unsigned i = 0, e = I->second.size(); i != e; ++i)
921           addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU,
922                              I->second[i], RejectMemNodes, TrueMemOrderLatency);
923       }
924       adjustChainDeps(AA, MFI, MF.getDataLayout(), SU, &ExitSU, RejectMemNodes,
925                       TrueMemOrderLatency);
926       PendingLoads.clear();
927       AliasMemDefs.clear();
928       AliasMemUses.clear();
929     } else if (MI->mayStore()) {
930       // Add dependence on barrier chain, if needed.
931       // There is no point to check aliasing on barrier event. Even if
932       // SU and barrier _could_ be reordered, they should not. In addition,
933       // we have lost all RejectMemNodes below barrier.
934       if (BarrierChain)
935         BarrierChain->addPred(SDep(SU, SDep::Barrier));
936
937       UnderlyingObjectsVector Objs;
938       getUnderlyingObjectsForInstr(MI, MFI, Objs, MF.getDataLayout());
939
940       if (Objs.empty()) {
941         // Treat all other stores conservatively.
942         goto new_alias_chain;
943       }
944
945       bool MayAlias = false;
946       for (UnderlyingObjectsVector::iterator K = Objs.begin(), KE = Objs.end();
947            K != KE; ++K) {
948         ValueType V = K->getPointer();
949         bool ThisMayAlias = K->getInt();
950         if (ThisMayAlias)
951           MayAlias = true;
952
953         // A store to a specific PseudoSourceValue. Add precise dependencies.
954         // Record the def in MemDefs, first adding a dep if there is
955         // an existing def.
956         MapVector<ValueType, std::vector<SUnit *> >::iterator I =
957           ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
958         MapVector<ValueType, std::vector<SUnit *> >::iterator IE =
959           ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
960         if (I != IE) {
961           for (unsigned i = 0, e = I->second.size(); i != e; ++i)
962             addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU,
963                                I->second[i], RejectMemNodes, 0, true);
964
965           // If we're not using AA, then we only need one store per object.
966           if (!AAForDep)
967             I->second.clear();
968           I->second.push_back(SU);
969         } else {
970           if (ThisMayAlias) {
971             if (!AAForDep)
972               AliasMemDefs[V].clear();
973             AliasMemDefs[V].push_back(SU);
974           } else {
975             if (!AAForDep)
976               NonAliasMemDefs[V].clear();
977             NonAliasMemDefs[V].push_back(SU);
978           }
979         }
980         // Handle the uses in MemUses, if there are any.
981         MapVector<ValueType, std::vector<SUnit *> >::iterator J =
982           ((ThisMayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
983         MapVector<ValueType, std::vector<SUnit *> >::iterator JE =
984           ((ThisMayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
985         if (J != JE) {
986           for (unsigned i = 0, e = J->second.size(); i != e; ++i)
987             addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU,
988                                J->second[i], RejectMemNodes,
989                                TrueMemOrderLatency, true);
990           J->second.clear();
991         }
992       }
993       if (MayAlias) {
994         // Add dependencies from all the PendingLoads, i.e. loads
995         // with no underlying object.
996         for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
997           addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU,
998                              PendingLoads[k], RejectMemNodes,
999                              TrueMemOrderLatency);
1000         // Add dependence on alias chain, if needed.
1001         if (AliasChain)
1002           addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU, AliasChain,
1003                              RejectMemNodes);
1004       }
1005       adjustChainDeps(AA, MFI, MF.getDataLayout(), SU, &ExitSU, RejectMemNodes,
1006                       TrueMemOrderLatency);
1007     } else if (MI->mayLoad()) {
1008       bool MayAlias = true;
1009       if (MI->isInvariantLoad(AA)) {
1010         // Invariant load, no chain dependencies needed!
1011       } else {
1012         UnderlyingObjectsVector Objs;
1013         getUnderlyingObjectsForInstr(MI, MFI, Objs, MF.getDataLayout());
1014
1015         if (Objs.empty()) {
1016           // A load with no underlying object. Depend on all
1017           // potentially aliasing stores.
1018           for (MapVector<ValueType, std::vector<SUnit *> >::iterator I =
1019                  AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
1020             for (unsigned i = 0, e = I->second.size(); i != e; ++i)
1021               addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU,
1022                                  I->second[i], RejectMemNodes);
1023
1024           PendingLoads.push_back(SU);
1025           MayAlias = true;
1026         } else {
1027           MayAlias = false;
1028         }
1029
1030         for (UnderlyingObjectsVector::iterator
1031              J = Objs.begin(), JE = Objs.end(); J != JE; ++J) {
1032           ValueType V = J->getPointer();
1033           bool ThisMayAlias = J->getInt();
1034
1035           if (ThisMayAlias)
1036             MayAlias = true;
1037
1038           // A load from a specific PseudoSourceValue. Add precise dependencies.
1039           MapVector<ValueType, std::vector<SUnit *> >::iterator I =
1040             ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
1041           MapVector<ValueType, std::vector<SUnit *> >::iterator IE =
1042             ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
1043           if (I != IE)
1044             for (unsigned i = 0, e = I->second.size(); i != e; ++i)
1045               addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU,
1046                                  I->second[i], RejectMemNodes, 0, true);
1047           if (ThisMayAlias)
1048             AliasMemUses[V].push_back(SU);
1049           else
1050             NonAliasMemUses[V].push_back(SU);
1051         }
1052         if (MayAlias)
1053           adjustChainDeps(AA, MFI, MF.getDataLayout(), SU, &ExitSU,
1054                           RejectMemNodes, /*Latency=*/0);
1055         // Add dependencies on alias and barrier chains, if needed.
1056         if (MayAlias && AliasChain)
1057           addChainDependency(AAForDep, MFI, MF.getDataLayout(), SU, AliasChain,
1058                              RejectMemNodes);
1059         if (BarrierChain)
1060           BarrierChain->addPred(SDep(SU, SDep::Barrier));
1061       }
1062     }
1063   }
1064   if (DbgMI)
1065     FirstDbgValue = DbgMI;
1066
1067   Defs.clear();
1068   Uses.clear();
1069   VRegDefs.clear();
1070   PendingLoads.clear();
1071 }
1072
1073 /// \brief Initialize register live-range state for updating kills.
1074 void ScheduleDAGInstrs::startBlockForKills(MachineBasicBlock *BB) {
1075   // Start with no live registers.
1076   LiveRegs.reset();
1077
1078   // Examine the live-in regs of all successors.
1079   for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
1080        SE = BB->succ_end(); SI != SE; ++SI) {
1081     for (const auto &LI : (*SI)->liveins()) {
1082       // Repeat, for reg and all subregs.
1083       for (MCSubRegIterator SubRegs(LI.PhysReg, TRI, /*IncludeSelf=*/true);
1084            SubRegs.isValid(); ++SubRegs)
1085         LiveRegs.set(*SubRegs);
1086     }
1087   }
1088 }
1089
1090 /// \brief If we change a kill flag on the bundle instruction implicit register
1091 /// operands, then we also need to propagate that to any instructions inside
1092 /// the bundle which had the same kill state.
1093 static void toggleBundleKillFlag(MachineInstr *MI, unsigned Reg,
1094                                  bool NewKillState) {
1095   if (MI->getOpcode() != TargetOpcode::BUNDLE)
1096     return;
1097
1098   // Walk backwards from the last instruction in the bundle to the first.
1099   // Once we set a kill flag on an instruction, we bail out, as otherwise we
1100   // might set it on too many operands.  We will clear as many flags as we
1101   // can though.
1102   MachineBasicBlock::instr_iterator Begin = MI;
1103   MachineBasicBlock::instr_iterator End = getBundleEnd(MI);
1104   while (Begin != End) {
1105     for (MachineOperand &MO : (--End)->operands()) {
1106       if (!MO.isReg() || MO.isDef() || Reg != MO.getReg())
1107         continue;
1108
1109       // DEBUG_VALUE nodes do not contribute to code generation and should
1110       // always be ignored.  Failure to do so may result in trying to modify
1111       // KILL flags on DEBUG_VALUE nodes, which is distressing.
1112       if (MO.isDebug())
1113         continue;
1114
1115       // If the register has the internal flag then it could be killing an
1116       // internal def of the register.  In this case, just skip.  We only want
1117       // to toggle the flag on operands visible outside the bundle.
1118       if (MO.isInternalRead())
1119         continue;
1120
1121       if (MO.isKill() == NewKillState)
1122         continue;
1123       MO.setIsKill(NewKillState);
1124       if (NewKillState)
1125         return;
1126     }
1127   }
1128 }
1129
1130 bool ScheduleDAGInstrs::toggleKillFlag(MachineInstr *MI, MachineOperand &MO) {
1131   // Setting kill flag...
1132   if (!MO.isKill()) {
1133     MO.setIsKill(true);
1134     toggleBundleKillFlag(MI, MO.getReg(), true);
1135     return false;
1136   }
1137
1138   // If MO itself is live, clear the kill flag...
1139   if (LiveRegs.test(MO.getReg())) {
1140     MO.setIsKill(false);
1141     toggleBundleKillFlag(MI, MO.getReg(), false);
1142     return false;
1143   }
1144
1145   // If any subreg of MO is live, then create an imp-def for that
1146   // subreg and keep MO marked as killed.
1147   MO.setIsKill(false);
1148   toggleBundleKillFlag(MI, MO.getReg(), false);
1149   bool AllDead = true;
1150   const unsigned SuperReg = MO.getReg();
1151   MachineInstrBuilder MIB(MF, MI);
1152   for (MCSubRegIterator SubRegs(SuperReg, TRI); SubRegs.isValid(); ++SubRegs) {
1153     if (LiveRegs.test(*SubRegs)) {
1154       MIB.addReg(*SubRegs, RegState::ImplicitDefine);
1155       AllDead = false;
1156     }
1157   }
1158
1159   if(AllDead) {
1160     MO.setIsKill(true);
1161     toggleBundleKillFlag(MI, MO.getReg(), true);
1162   }
1163   return false;
1164 }
1165
1166 // FIXME: Reuse the LivePhysRegs utility for this.
1167 void ScheduleDAGInstrs::fixupKills(MachineBasicBlock *MBB) {
1168   DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
1169
1170   LiveRegs.resize(TRI->getNumRegs());
1171   BitVector killedRegs(TRI->getNumRegs());
1172
1173   startBlockForKills(MBB);
1174
1175   // Examine block from end to start...
1176   unsigned Count = MBB->size();
1177   for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
1178        I != E; --Count) {
1179     MachineInstr *MI = --I;
1180     if (MI->isDebugValue())
1181       continue;
1182
1183     // Update liveness.  Registers that are defed but not used in this
1184     // instruction are now dead. Mark register and all subregs as they
1185     // are completely defined.
1186     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1187       MachineOperand &MO = MI->getOperand(i);
1188       if (MO.isRegMask())
1189         LiveRegs.clearBitsNotInMask(MO.getRegMask());
1190       if (!MO.isReg()) continue;
1191       unsigned Reg = MO.getReg();
1192       if (Reg == 0) continue;
1193       if (!MO.isDef()) continue;
1194       // Ignore two-addr defs.
1195       if (MI->isRegTiedToUseOperand(i)) continue;
1196
1197       // Repeat for reg and all subregs.
1198       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1199            SubRegs.isValid(); ++SubRegs)
1200         LiveRegs.reset(*SubRegs);
1201     }
1202
1203     // Examine all used registers and set/clear kill flag. When a
1204     // register is used multiple times we only set the kill flag on
1205     // the first use. Don't set kill flags on undef operands.
1206     killedRegs.reset();
1207     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1208       MachineOperand &MO = MI->getOperand(i);
1209       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
1210       unsigned Reg = MO.getReg();
1211       if ((Reg == 0) || MRI.isReserved(Reg)) continue;
1212
1213       bool kill = false;
1214       if (!killedRegs.test(Reg)) {
1215         kill = true;
1216         // A register is not killed if any subregs are live...
1217         for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
1218           if (LiveRegs.test(*SubRegs)) {
1219             kill = false;
1220             break;
1221           }
1222         }
1223
1224         // If subreg is not live, then register is killed if it became
1225         // live in this instruction
1226         if (kill)
1227           kill = !LiveRegs.test(Reg);
1228       }
1229
1230       if (MO.isKill() != kill) {
1231         DEBUG(dbgs() << "Fixing " << MO << " in ");
1232         // Warning: toggleKillFlag may invalidate MO.
1233         toggleKillFlag(MI, MO);
1234         DEBUG(MI->dump());
1235         DEBUG(if (MI->getOpcode() == TargetOpcode::BUNDLE) {
1236           MachineBasicBlock::instr_iterator Begin = MI;
1237           MachineBasicBlock::instr_iterator End = getBundleEnd(MI);
1238           while (++Begin != End)
1239             DEBUG(Begin->dump());
1240         });
1241       }
1242
1243       killedRegs.set(Reg);
1244     }
1245
1246     // Mark any used register (that is not using undef) and subregs as
1247     // now live...
1248     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1249       MachineOperand &MO = MI->getOperand(i);
1250       if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
1251       unsigned Reg = MO.getReg();
1252       if ((Reg == 0) || MRI.isReserved(Reg)) continue;
1253
1254       for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1255            SubRegs.isValid(); ++SubRegs)
1256         LiveRegs.set(*SubRegs);
1257     }
1258   }
1259 }
1260
1261 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
1262 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1263   SU->getInstr()->dump();
1264 #endif
1265 }
1266
1267 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
1268   std::string s;
1269   raw_string_ostream oss(s);
1270   if (SU == &EntrySU)
1271     oss << "<entry>";
1272   else if (SU == &ExitSU)
1273     oss << "<exit>";
1274   else
1275     SU->getInstr()->print(oss, /*SkipOpers=*/true);
1276   return oss.str();
1277 }
1278
1279 /// Return the basic block label. It is not necessarilly unique because a block
1280 /// contains multiple scheduling regions. But it is fine for visualization.
1281 std::string ScheduleDAGInstrs::getDAGName() const {
1282   return "dag." + BB->getFullName();
1283 }
1284
1285 //===----------------------------------------------------------------------===//
1286 // SchedDFSResult Implementation
1287 //===----------------------------------------------------------------------===//
1288
1289 namespace llvm {
1290 /// \brief Internal state used to compute SchedDFSResult.
1291 class SchedDFSImpl {
1292   SchedDFSResult &R;
1293
1294   /// Join DAG nodes into equivalence classes by their subtree.
1295   IntEqClasses SubtreeClasses;
1296   /// List PredSU, SuccSU pairs that represent data edges between subtrees.
1297   std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs;
1298
1299   struct RootData {
1300     unsigned NodeID;
1301     unsigned ParentNodeID;  // Parent node (member of the parent subtree).
1302     unsigned SubInstrCount; // Instr count in this tree only, not children.
1303
1304     RootData(unsigned id): NodeID(id),
1305                            ParentNodeID(SchedDFSResult::InvalidSubtreeID),
1306                            SubInstrCount(0) {}
1307
1308     unsigned getSparseSetIndex() const { return NodeID; }
1309   };
1310
1311   SparseSet<RootData> RootSet;
1312
1313 public:
1314   SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
1315     RootSet.setUniverse(R.DFSNodeData.size());
1316   }
1317
1318   /// Return true if this node been visited by the DFS traversal.
1319   ///
1320   /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
1321   /// ID. Later, SubtreeID is updated but remains valid.
1322   bool isVisited(const SUnit *SU) const {
1323     return R.DFSNodeData[SU->NodeNum].SubtreeID
1324       != SchedDFSResult::InvalidSubtreeID;
1325   }
1326
1327   /// Initialize this node's instruction count. We don't need to flag the node
1328   /// visited until visitPostorder because the DAG cannot have cycles.
1329   void visitPreorder(const SUnit *SU) {
1330     R.DFSNodeData[SU->NodeNum].InstrCount =
1331       SU->getInstr()->isTransient() ? 0 : 1;
1332   }
1333
1334   /// Called once for each node after all predecessors are visited. Revisit this
1335   /// node's predecessors and potentially join them now that we know the ILP of
1336   /// the other predecessors.
1337   void visitPostorderNode(const SUnit *SU) {
1338     // Mark this node as the root of a subtree. It may be joined with its
1339     // successors later.
1340     R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
1341     RootData RData(SU->NodeNum);
1342     RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
1343
1344     // If any predecessors are still in their own subtree, they either cannot be
1345     // joined or are large enough to remain separate. If this parent node's
1346     // total instruction count is not greater than a child subtree by at least
1347     // the subtree limit, then try to join it now since splitting subtrees is
1348     // only useful if multiple high-pressure paths are possible.
1349     unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
1350     for (SUnit::const_pred_iterator
1351            PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1352       if (PI->getKind() != SDep::Data)
1353         continue;
1354       unsigned PredNum = PI->getSUnit()->NodeNum;
1355       if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
1356         joinPredSubtree(*PI, SU, /*CheckLimit=*/false);
1357
1358       // Either link or merge the TreeData entry from the child to the parent.
1359       if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
1360         // If the predecessor's parent is invalid, this is a tree edge and the
1361         // current node is the parent.
1362         if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
1363           RootSet[PredNum].ParentNodeID = SU->NodeNum;
1364       }
1365       else if (RootSet.count(PredNum)) {
1366         // The predecessor is not a root, but is still in the root set. This
1367         // must be the new parent that it was just joined to. Note that
1368         // RootSet[PredNum].ParentNodeID may either be invalid or may still be
1369         // set to the original parent.
1370         RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
1371         RootSet.erase(PredNum);
1372       }
1373     }
1374     RootSet[SU->NodeNum] = RData;
1375   }
1376
1377   /// Called once for each tree edge after calling visitPostOrderNode on the
1378   /// predecessor. Increment the parent node's instruction count and
1379   /// preemptively join this subtree to its parent's if it is small enough.
1380   void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
1381     R.DFSNodeData[Succ->NodeNum].InstrCount
1382       += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
1383     joinPredSubtree(PredDep, Succ);
1384   }
1385
1386   /// Add a connection for cross edges.
1387   void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
1388     ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
1389   }
1390
1391   /// Set each node's subtree ID to the representative ID and record connections
1392   /// between trees.
1393   void finalize() {
1394     SubtreeClasses.compress();
1395     R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
1396     assert(SubtreeClasses.getNumClasses() == RootSet.size()
1397            && "number of roots should match trees");
1398     for (SparseSet<RootData>::const_iterator
1399            RI = RootSet.begin(), RE = RootSet.end(); RI != RE; ++RI) {
1400       unsigned TreeID = SubtreeClasses[RI->NodeID];
1401       if (RI->ParentNodeID != SchedDFSResult::InvalidSubtreeID)
1402         R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[RI->ParentNodeID];
1403       R.DFSTreeData[TreeID].SubInstrCount = RI->SubInstrCount;
1404       // Note that SubInstrCount may be greater than InstrCount if we joined
1405       // subtrees across a cross edge. InstrCount will be attributed to the
1406       // original parent, while SubInstrCount will be attributed to the joined
1407       // parent.
1408     }
1409     R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1410     R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1411     DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
1412     for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
1413       R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
1414       DEBUG(dbgs() << "  SU(" << Idx << ") in tree "
1415             << R.DFSNodeData[Idx].SubtreeID << '\n');
1416     }
1417     for (std::vector<std::pair<const SUnit*, const SUnit*> >::const_iterator
1418            I = ConnectionPairs.begin(), E = ConnectionPairs.end();
1419          I != E; ++I) {
1420       unsigned PredTree = SubtreeClasses[I->first->NodeNum];
1421       unsigned SuccTree = SubtreeClasses[I->second->NodeNum];
1422       if (PredTree == SuccTree)
1423         continue;
1424       unsigned Depth = I->first->getDepth();
1425       addConnection(PredTree, SuccTree, Depth);
1426       addConnection(SuccTree, PredTree, Depth);
1427     }
1428   }
1429
1430 protected:
1431   /// Join the predecessor subtree with the successor that is its DFS
1432   /// parent. Apply some heuristics before joining.
1433   bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
1434                        bool CheckLimit = true) {
1435     assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
1436
1437     // Check if the predecessor is already joined.
1438     const SUnit *PredSU = PredDep.getSUnit();
1439     unsigned PredNum = PredSU->NodeNum;
1440     if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
1441       return false;
1442
1443     // Four is the magic number of successors before a node is considered a
1444     // pinch point.
1445     unsigned NumDataSucs = 0;
1446     for (SUnit::const_succ_iterator SI = PredSU->Succs.begin(),
1447            SE = PredSU->Succs.end(); SI != SE; ++SI) {
1448       if (SI->getKind() == SDep::Data) {
1449         if (++NumDataSucs >= 4)
1450           return false;
1451       }
1452     }
1453     if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
1454       return false;
1455     R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
1456     SubtreeClasses.join(Succ->NodeNum, PredNum);
1457     return true;
1458   }
1459
1460   /// Called by finalize() to record a connection between trees.
1461   void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
1462     if (!Depth)
1463       return;
1464
1465     do {
1466       SmallVectorImpl<SchedDFSResult::Connection> &Connections =
1467         R.SubtreeConnections[FromTree];
1468       for (SmallVectorImpl<SchedDFSResult::Connection>::iterator
1469              I = Connections.begin(), E = Connections.end(); I != E; ++I) {
1470         if (I->TreeID == ToTree) {
1471           I->Level = std::max(I->Level, Depth);
1472           return;
1473         }
1474       }
1475       Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
1476       FromTree = R.DFSTreeData[FromTree].ParentTreeID;
1477     } while (FromTree != SchedDFSResult::InvalidSubtreeID);
1478   }
1479 };
1480 } // namespace llvm
1481
1482 namespace {
1483 /// \brief Manage the stack used by a reverse depth-first search over the DAG.
1484 class SchedDAGReverseDFS {
1485   std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
1486 public:
1487   bool isComplete() const { return DFSStack.empty(); }
1488
1489   void follow(const SUnit *SU) {
1490     DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
1491   }
1492   void advance() { ++DFSStack.back().second; }
1493
1494   const SDep *backtrack() {
1495     DFSStack.pop_back();
1496     return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
1497   }
1498
1499   const SUnit *getCurr() const { return DFSStack.back().first; }
1500
1501   SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
1502
1503   SUnit::const_pred_iterator getPredEnd() const {
1504     return getCurr()->Preds.end();
1505   }
1506 };
1507 } // anonymous
1508
1509 static bool hasDataSucc(const SUnit *SU) {
1510   for (SUnit::const_succ_iterator
1511          SI = SU->Succs.begin(), SE = SU->Succs.end(); SI != SE; ++SI) {
1512     if (SI->getKind() == SDep::Data && !SI->getSUnit()->isBoundaryNode())
1513       return true;
1514   }
1515   return false;
1516 }
1517
1518 /// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
1519 /// search from this root.
1520 void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
1521   if (!IsBottomUp)
1522     llvm_unreachable("Top-down ILP metric is unimplemnted");
1523
1524   SchedDFSImpl Impl(*this);
1525   for (ArrayRef<SUnit>::const_iterator
1526          SI = SUnits.begin(), SE = SUnits.end(); SI != SE; ++SI) {
1527     const SUnit *SU = &*SI;
1528     if (Impl.isVisited(SU) || hasDataSucc(SU))
1529       continue;
1530
1531     SchedDAGReverseDFS DFS;
1532     Impl.visitPreorder(SU);
1533     DFS.follow(SU);
1534     for (;;) {
1535       // Traverse the leftmost path as far as possible.
1536       while (DFS.getPred() != DFS.getPredEnd()) {
1537         const SDep &PredDep = *DFS.getPred();
1538         DFS.advance();
1539         // Ignore non-data edges.
1540         if (PredDep.getKind() != SDep::Data
1541             || PredDep.getSUnit()->isBoundaryNode()) {
1542           continue;
1543         }
1544         // An already visited edge is a cross edge, assuming an acyclic DAG.
1545         if (Impl.isVisited(PredDep.getSUnit())) {
1546           Impl.visitCrossEdge(PredDep, DFS.getCurr());
1547           continue;
1548         }
1549         Impl.visitPreorder(PredDep.getSUnit());
1550         DFS.follow(PredDep.getSUnit());
1551       }
1552       // Visit the top of the stack in postorder and backtrack.
1553       const SUnit *Child = DFS.getCurr();
1554       const SDep *PredDep = DFS.backtrack();
1555       Impl.visitPostorderNode(Child);
1556       if (PredDep)
1557         Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
1558       if (DFS.isComplete())
1559         break;
1560     }
1561   }
1562   Impl.finalize();
1563 }
1564
1565 /// The root of the given SubtreeID was just scheduled. For all subtrees
1566 /// connected to this tree, record the depth of the connection so that the
1567 /// nearest connected subtrees can be prioritized.
1568 void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
1569   for (SmallVectorImpl<Connection>::const_iterator
1570          I = SubtreeConnections[SubtreeID].begin(),
1571          E = SubtreeConnections[SubtreeID].end(); I != E; ++I) {
1572     SubtreeConnectLevels[I->TreeID] =
1573       std::max(SubtreeConnectLevels[I->TreeID], I->Level);
1574     DEBUG(dbgs() << "  Tree: " << I->TreeID
1575           << " @" << SubtreeConnectLevels[I->TreeID] << '\n');
1576   }
1577 }
1578
1579 LLVM_DUMP_METHOD
1580 void ILPValue::print(raw_ostream &OS) const {
1581   OS << InstrCount << " / " << Length << " = ";
1582   if (!Length)
1583     OS << "BADILP";
1584   else
1585     OS << format("%g", ((double)InstrCount / Length));
1586 }
1587
1588 LLVM_DUMP_METHOD
1589 void ILPValue::dump() const {
1590   dbgs() << *this << '\n';
1591 }
1592
1593 namespace llvm {
1594
1595 LLVM_DUMP_METHOD
1596 raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1597   Val.print(OS);
1598   return OS;
1599 }
1600
1601 } // namespace llvm