blob: 08224ecafd30dd9116420adad0bdd4f0386032f1 [file] [log] [blame]
Dan Gohmanf90d3b02008-12-08 17:50:35 +00001//===---- ScheduleDAGInstrs.cpp - MachineInstr Rescheduling ---------------===//
Dan Gohman60cb69e2008-11-19 23:18:57 +00002//
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//
Dan Gohmanf90d3b02008-12-08 17:50:35 +000010// This implements the ScheduleDAGInstrs class, which implements re-scheduling
11// of MachineInstrs.
Dan Gohman60cb69e2008-11-19 23:18:57 +000012//
13//===----------------------------------------------------------------------===//
14
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/CodeGen/ScheduleDAGInstrs.h"
Matthias Braun97d0ffb2015-12-04 01:51:19 +000016#include "llvm/ADT/IntEqClasses.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/SmallPtrSet.h"
18#include "llvm/ADT/SmallSet.h"
Dan Gohman1ee0d412009-01-30 02:49:14 +000019#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohmana4fcd242010-12-15 20:02:24 +000020#include "llvm/Analysis/ValueTracking.h"
Matthias Braund4f64092016-01-20 00:23:32 +000021#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Dan Gohmandddc1ac2008-12-16 03:25:46 +000022#include "llvm/CodeGen/MachineFunctionPass.h"
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +000023#include "llvm/CodeGen/MachineFrameInfo.h"
Andrew Trick6b104f82013-12-28 21:56:55 +000024#include "llvm/CodeGen/MachineInstrBuilder.h"
Dan Gohman48b185d2009-09-25 20:36:54 +000025#include "llvm/CodeGen/MachineMemOperand.h"
Dan Gohmandddc1ac2008-12-16 03:25:46 +000026#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman3aab10b2008-12-04 01:35:46 +000027#include "llvm/CodeGen/PseudoSourceValue.h"
Andrew Trick88517f62012-06-06 19:47:35 +000028#include "llvm/CodeGen/RegisterPressure.h"
Andrew Trickcd1c2f92012-11-28 05:13:24 +000029#include "llvm/CodeGen/ScheduleDFS.h"
Jonas Paulssonac29f012016-02-03 17:52:29 +000030#include "llvm/IR/Function.h"
31#include "llvm/IR/Type.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/Operator.h"
Andrew Trickda01ba32012-05-15 18:59:41 +000033#include "llvm/Support/CommandLine.h"
Dan Gohman60cb69e2008-11-19 23:18:57 +000034#include "llvm/Support/Debug.h"
Andrew Trick90f711d2012-10-15 18:02:27 +000035#include "llvm/Support/Format.h"
Dan Gohman60cb69e2008-11-19 23:18:57 +000036#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000037#include "llvm/Target/TargetInstrInfo.h"
38#include "llvm/Target/TargetMachine.h"
39#include "llvm/Target/TargetRegisterInfo.h"
40#include "llvm/Target/TargetSubtargetInfo.h"
Andrew Trickc01b0042013-08-23 17:48:43 +000041
Dan Gohman60cb69e2008-11-19 23:18:57 +000042using namespace llvm;
43
Chandler Carruth1b9dde02014-04-22 02:02:50 +000044#define DEBUG_TYPE "misched"
45
Andrew Trickda01ba32012-05-15 18:59:41 +000046static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
47 cl::ZeroOrMore, cl::init(false),
Jonas Paulssonbf408bb2015-01-07 13:20:57 +000048 cl::desc("Enable use of AA during MI DAG construction"));
Andrew Trickda01ba32012-05-15 18:59:41 +000049
Hal Finkeldbebb522014-01-25 19:24:54 +000050static cl::opt<bool> UseTBAA("use-tbaa-in-sched-mi", cl::Hidden,
Jonas Paulssonbf408bb2015-01-07 13:20:57 +000051 cl::init(true), cl::desc("Enable use of TBAA during MI DAG construction"));
Hal Finkeldbebb522014-01-25 19:24:54 +000052
Jonas Paulssonac29f012016-02-03 17:52:29 +000053// Note: the two options below might be used in tuning compile time vs
54// output quality. Setting HugeRegion so large that it will never be
55// reached means best-effort, but may be slow.
56
57// When Stores and Loads maps (or NonAliasStores and NonAliasLoads)
58// together hold this many SUs, a reduction of maps will be done.
59static cl::opt<unsigned> HugeRegion("dag-maps-huge-region", cl::Hidden,
60 cl::init(1000), cl::desc("The limit to use while constructing the DAG "
61 "prior to scheduling, at which point a trade-off "
62 "is made to avoid excessive compile time."));
63
Mehdi Amini59ae8542016-04-16 04:58:30 +000064static cl::opt<unsigned> ReductionSize(
65 "dag-maps-reduction-size", cl::Hidden,
Jonas Paulssonac29f012016-02-03 17:52:29 +000066 cl::desc("A huge scheduling region will have maps reduced by this many "
Mehdi Amini59ae8542016-04-16 04:58:30 +000067 "nodes at a time. Defaults to HugeRegion / 2."));
68
69static unsigned getReductionSize() {
70 // Always reduce a huge region with half of the elements, except
71 // when user sets this number explicitly.
72 if (ReductionSize.getNumOccurrences() == 0)
73 return HugeRegion / 2;
74 return ReductionSize;
75}
Jonas Paulssonac29f012016-02-03 17:52:29 +000076
77static void dumpSUList(ScheduleDAGInstrs::SUList &L) {
78#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
79 dbgs() << "{ ";
80 for (auto *su : L) {
81 dbgs() << "SU(" << su->NodeNum << ")";
82 if (su != L.back())
83 dbgs() << ", ";
84 }
85 dbgs() << "}\n";
86#endif
87}
88
Dan Gohman619ef482009-01-15 19:20:50 +000089ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
Alexey Samsonov8968e6d2014-08-20 19:36:05 +000090 const MachineLoopInfo *mli,
Matthias Braun93563e72015-11-03 01:53:29 +000091 bool RemoveKillFlags)
Matthias Braunb17e8b12015-12-04 19:54:24 +000092 : ScheduleDAG(mf), MLI(mli), MFI(mf.getFrameInfo()),
Matthias Braun93563e72015-11-03 01:53:29 +000093 RemoveKillFlags(RemoveKillFlags), CanHandleTerminators(false),
Jonas Paulssonac29f012016-02-03 17:52:29 +000094 TrackLaneMasks(false), AAForDep(nullptr), BarrierChain(nullptr),
95 UnknownValue(UndefValue::get(
96 Type::getVoidTy(mf.getFunction()->getContext()))),
97 FirstDbgValue(nullptr) {
Devang Patele5feef02011-06-02 20:07:12 +000098 DbgValues.clear();
Andrew Trick9b635132012-09-18 18:20:00 +000099
Eric Christopher2c635492015-01-27 07:54:39 +0000100 const TargetSubtargetInfo &ST = mf.getSubtarget();
Pete Cooper11759452014-09-02 17:43:54 +0000101 SchedModel.init(ST.getSchedModel(), &ST, TII);
Evan Chengf0236e02009-10-18 19:58:47 +0000102}
Dan Gohman60cb69e2008-11-19 23:18:57 +0000103
Dan Gohman1ee0d412009-01-30 02:49:14 +0000104/// getUnderlyingObjectFromInt - This is the function that does the work of
105/// looking through basic ptrtoint+arithmetic+inttoptr sequences.
106static const Value *getUnderlyingObjectFromInt(const Value *V) {
107 do {
Dan Gohman58b0e712009-07-17 20:58:59 +0000108 if (const Operator *U = dyn_cast<Operator>(V)) {
Dan Gohman1ee0d412009-01-30 02:49:14 +0000109 // If we find a ptrtoint, we can transfer control back to the
110 // regular getUnderlyingObjectFromInt.
Dan Gohman58b0e712009-07-17 20:58:59 +0000111 if (U->getOpcode() == Instruction::PtrToInt)
Dan Gohman1ee0d412009-01-30 02:49:14 +0000112 return U->getOperand(0);
Andrew Trick0be19362012-11-28 03:42:49 +0000113 // If we find an add of a constant, a multiplied value, or a phi, it's
Dan Gohman1ee0d412009-01-30 02:49:14 +0000114 // likely that the other operand will lead us to the base
115 // object. We don't have to worry about the case where the
Dan Gohman6c0c2192009-08-07 01:26:06 +0000116 // object address is somehow being computed by the multiply,
Dan Gohman1ee0d412009-01-30 02:49:14 +0000117 // because our callers only care when the result is an
Nick Lewycky1a329542012-10-26 04:27:49 +0000118 // identifiable object.
Dan Gohman58b0e712009-07-17 20:58:59 +0000119 if (U->getOpcode() != Instruction::Add ||
Dan Gohman1ee0d412009-01-30 02:49:14 +0000120 (!isa<ConstantInt>(U->getOperand(1)) &&
Andrew Trick0be19362012-11-28 03:42:49 +0000121 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
122 !isa<PHINode>(U->getOperand(1))))
Dan Gohman1ee0d412009-01-30 02:49:14 +0000123 return V;
124 V = U->getOperand(0);
125 } else {
126 return V;
127 }
Duncan Sands19d0b472010-02-16 11:11:14 +0000128 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
Dan Gohman1ee0d412009-01-30 02:49:14 +0000129 } while (1);
130}
131
Hal Finkel66859ae2012-12-10 18:49:16 +0000132/// getUnderlyingObjects - This is a wrapper around GetUnderlyingObjects
Dan Gohman1ee0d412009-01-30 02:49:14 +0000133/// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
Hal Finkel66859ae2012-12-10 18:49:16 +0000134static void getUnderlyingObjects(const Value *V,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000135 SmallVectorImpl<Value *> &Objects,
136 const DataLayout &DL) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000137 SmallPtrSet<const Value *, 16> Visited;
Hal Finkel66859ae2012-12-10 18:49:16 +0000138 SmallVector<const Value *, 4> Working(1, V);
Dan Gohman1ee0d412009-01-30 02:49:14 +0000139 do {
Hal Finkel66859ae2012-12-10 18:49:16 +0000140 V = Working.pop_back_val();
141
142 SmallVector<Value *, 4> Objs;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000143 GetUnderlyingObjects(const_cast<Value *>(V), Objs, DL);
Hal Finkel66859ae2012-12-10 18:49:16 +0000144
Craig Toppere1c1d362013-07-03 05:11:49 +0000145 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), IE = Objs.end();
Hal Finkel66859ae2012-12-10 18:49:16 +0000146 I != IE; ++I) {
147 V = *I;
David Blaikie70573dc2014-11-19 07:49:26 +0000148 if (!Visited.insert(V).second)
Hal Finkel66859ae2012-12-10 18:49:16 +0000149 continue;
150 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
151 const Value *O =
152 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
153 if (O->getType()->isPointerTy()) {
154 Working.push_back(O);
155 continue;
156 }
157 }
158 Objects.push_back(const_cast<Value *>(V));
159 }
160 } while (!Working.empty());
Dan Gohman1ee0d412009-01-30 02:49:14 +0000161}
162
Hal Finkel66859ae2012-12-10 18:49:16 +0000163/// getUnderlyingObjectsForInstr - If this machine instr has memory reference
Dan Gohman1ee0d412009-01-30 02:49:14 +0000164/// information and it can be tracked to a normal reference to a known
Hal Finkel66859ae2012-12-10 18:49:16 +0000165/// object, return the Value for that object.
166static void getUnderlyingObjectsForInstr(const MachineInstr *MI,
Matthias Braun941a7052016-07-28 18:40:00 +0000167 const MachineFrameInfo &MFI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000168 UnderlyingObjectsVector &Objects,
169 const DataLayout &DL) {
Geoff Berry63817132016-04-14 21:31:07 +0000170 auto allMMOsOkay = [&]() {
171 for (const MachineMemOperand *MMO : MI->memoperands()) {
172 if (MMO->isVolatile())
173 return false;
Hal Finkel66859ae2012-12-10 18:49:16 +0000174
Geoff Berry63817132016-04-14 21:31:07 +0000175 if (const PseudoSourceValue *PSV = MMO->getPseudoValue()) {
176 // Function that contain tail calls don't have unique PseudoSourceValue
177 // objects. Two PseudoSourceValues might refer to the same or
178 // overlapping locations. The client code calling this function assumes
179 // this is not the case. So return a conservative answer of no known
180 // object.
Matthias Braun941a7052016-07-28 18:40:00 +0000181 if (MFI.hasTailCall())
Geoff Berry63817132016-04-14 21:31:07 +0000182 return false;
Geoff Berryc0739d82016-04-12 15:50:19 +0000183
Geoff Berry63817132016-04-14 21:31:07 +0000184 // For now, ignore PseudoSourceValues which may alias LLVM IR values
185 // because the code that uses this function has no way to cope with
186 // such aliases.
Matthias Braun941a7052016-07-28 18:40:00 +0000187 if (PSV->isAliased(&MFI))
Geoff Berry63817132016-04-14 21:31:07 +0000188 return false;
Geoff Berryc0739d82016-04-12 15:50:19 +0000189
Matthias Braun941a7052016-07-28 18:40:00 +0000190 bool MayAlias = PSV->mayAlias(&MFI);
Geoff Berry63817132016-04-14 21:31:07 +0000191 Objects.push_back(UnderlyingObjectsVector::value_type(PSV, MayAlias));
192 } else if (const Value *V = MMO->getValue()) {
193 SmallVector<Value *, 4> Objs;
194 getUnderlyingObjects(V, Objs, DL);
Geoff Berryc0739d82016-04-12 15:50:19 +0000195
Geoff Berry63817132016-04-14 21:31:07 +0000196 for (Value *V : Objs) {
197 if (!isIdentifiedObject(V))
198 return false;
199
200 Objects.push_back(UnderlyingObjectsVector::value_type(V, true));
Geoff Berryc0739d82016-04-12 15:50:19 +0000201 }
Geoff Berry63817132016-04-14 21:31:07 +0000202 } else
203 return false;
Geoff Berryc0739d82016-04-12 15:50:19 +0000204 }
Geoff Berry63817132016-04-14 21:31:07 +0000205 return true;
206 };
207
208 if (!allMMOsOkay())
209 Objects.clear();
Dan Gohman1ee0d412009-01-30 02:49:14 +0000210}
211
Andrew Trick7405c6d2012-04-20 20:05:21 +0000212void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
213 BB = bb;
Dan Gohmanb9543432009-02-10 23:27:53 +0000214}
215
Andrew Trick52226d42012-03-07 23:00:49 +0000216void ScheduleDAGInstrs::finishBlock() {
Andrew Trick51ee9362012-04-20 20:24:33 +0000217 // Subclasses should no longer refer to the old block.
Craig Topperc0196b12014-04-14 00:51:57 +0000218 BB = nullptr;
Andrew Trick60cf03e2012-03-07 05:21:52 +0000219}
220
Andrew Trick60cf03e2012-03-07 05:21:52 +0000221/// Initialize the DAG and common scheduler state for the current scheduling
222/// region. This does not actually create the DAG, only clears it. The
223/// scheduling driver may call BuildSchedGraph multiple times per scheduling
224/// region.
225void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
226 MachineBasicBlock::iterator begin,
227 MachineBasicBlock::iterator end,
Andrew Tricka53e1012013-08-23 17:48:33 +0000228 unsigned regioninstrs) {
Andrew Trick7405c6d2012-04-20 20:05:21 +0000229 assert(bb == BB && "startBlock should set BB");
Andrew Trick8c207e42012-03-09 04:29:02 +0000230 RegionBegin = begin;
231 RegionEnd = end;
Andrew Tricka53e1012013-08-23 17:48:33 +0000232 NumRegionInstrs = regioninstrs;
Andrew Trick60cf03e2012-03-07 05:21:52 +0000233}
234
235/// Close the current scheduling region. Don't clear any state in case the
236/// driver wants to refer to the previous scheduling region.
237void ScheduleDAGInstrs::exitRegion() {
238 // Nothing to do.
239}
240
Andrew Trick52226d42012-03-07 23:00:49 +0000241/// addSchedBarrierDeps - Add dependencies from instructions in the current
Evan Cheng15459b62010-10-23 02:10:46 +0000242/// list of instructions being scheduled to scheduling barrier by adding
243/// the exit SU to the register defs and use list. This is because we want to
244/// make sure instructions which define registers that are either used by
245/// the terminator or are live-out are properly scheduled. This is
246/// especially important when the definition latency of the return value(s)
247/// are too high to be hidden by the branch or when the liveout registers
248/// used by instructions in the fallthrough block.
Andrew Trick52226d42012-03-07 23:00:49 +0000249void ScheduleDAGInstrs::addSchedBarrierDeps() {
Craig Topperc0196b12014-04-14 00:51:57 +0000250 MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : nullptr;
Evan Cheng15459b62010-10-23 02:10:46 +0000251 ExitSU.setInstr(ExitMI);
252 bool AllDepKnown = ExitMI &&
Evan Cheng7f8e5632011-12-07 07:15:52 +0000253 (ExitMI->isCall() || ExitMI->isBarrier());
Evan Cheng15459b62010-10-23 02:10:46 +0000254 if (ExitMI && AllDepKnown) {
255 // If it's a call or a barrier, add dependencies on the defs and uses of
256 // instruction.
257 for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
258 const MachineOperand &MO = ExitMI->getOperand(i);
259 if (!MO.isReg() || MO.isDef()) continue;
260 unsigned Reg = MO.getReg();
261 if (Reg == 0) continue;
262
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000263 if (TRI->isPhysicalRegister(Reg))
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000264 Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
Matthias Braun93563e72015-11-03 01:53:29 +0000265 else if (MO.readsReg()) // ignore undef operands
266 addVRegUseDeps(&ExitSU, i);
Evan Cheng15459b62010-10-23 02:10:46 +0000267 }
268 } else {
269 // For others, e.g. fallthrough, conditional branch, assume the exit
Evan Chengcbdf7e82010-10-27 23:17:17 +0000270 // uses all the registers that are livein to the successor blocks.
Benjamin Kramer411d5a22012-03-16 17:38:19 +0000271 assert(Uses.empty() && "Uses in set before adding deps?");
Evan Chengcbdf7e82010-10-27 23:17:17 +0000272 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
273 SE = BB->succ_end(); SI != SE; ++SI)
Matthias Braund9da1622015-09-09 18:08:03 +0000274 for (const auto &LI : (*SI)->liveins()) {
275 if (!Uses.contains(LI.PhysReg))
276 Uses.insert(PhysRegSUOper(&ExitSU, -1, LI.PhysReg));
Evan Chengcbdf7e82010-10-27 23:17:17 +0000277 }
Evan Cheng15459b62010-10-23 02:10:46 +0000278 }
279}
280
Andrew Trickd675a4c2012-02-23 01:52:38 +0000281/// MO is an operand of SU's instruction that defines a physical register. Add
282/// data dependencies from SU to any uses of the physical register.
Andrew Trickae535612012-08-23 00:39:43 +0000283void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
284 const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000285 assert(MO.isDef() && "expect physreg def");
286
287 // Ask the target if address-backscheduling is desirable, and if so how much.
Eric Christopher2c635492015-01-27 07:54:39 +0000288 const TargetSubtargetInfo &ST = MF.getSubtarget();
Andrew Trickd675a4c2012-02-23 01:52:38 +0000289
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000290 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
291 Alias.isValid(); ++Alias) {
Andrew Trick9dbbd3e2012-02-24 07:04:55 +0000292 if (!Uses.contains(*Alias))
Andrew Trickd675a4c2012-02-23 01:52:38 +0000293 continue;
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000294 for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
295 SUnit *UseSU = I->SU;
Andrew Trickd675a4c2012-02-23 01:52:38 +0000296 if (UseSU == SU)
297 continue;
Andrew Trick07dced62012-10-08 18:54:00 +0000298
Andrew Trick07dced62012-10-08 18:54:00 +0000299 // Adjust the dependence latency using operand def/use information,
300 // then allow the target to perform its own adjustments.
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000301 int UseOp = I->OpIdx;
Craig Topperc0196b12014-04-14 00:51:57 +0000302 MachineInstr *RegUse = nullptr;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000303 SDep Dep;
304 if (UseOp < 0)
305 Dep = SDep(SU, SDep::Artificial);
306 else {
Andrew Tricke833e1c2013-04-13 06:07:40 +0000307 // Set the hasPhysRegDefs only for physreg defs that have a use within
308 // the scheduling region.
309 SU->hasPhysRegDefs = true;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000310 Dep = SDep(SU, SDep::Data, *Alias);
311 RegUse = UseSU->getInstr();
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000312 }
313 Dep.setLatency(
Andrew Trickde2109e2013-06-15 04:49:57 +0000314 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, RegUse,
315 UseOp));
Andrew Trick45446062012-06-05 21:11:27 +0000316
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000317 ST.adjustSchedDependency(SU, UseSU, Dep);
318 UseSU->addPred(Dep);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000319 }
320 }
321}
322
Andrew Trickdbee9d82012-01-14 02:17:15 +0000323/// addPhysRegDeps - Add register dependencies (data, anti, and output) from
324/// this SUnit to following instructions in the same scheduling region that
325/// depend the physical register referenced at OperIdx.
326void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
Andrew Trick6b104f82013-12-28 21:56:55 +0000327 MachineInstr *MI = SU->getInstr();
328 MachineOperand &MO = MI->getOperand(OperIdx);
Andrew Trickdbee9d82012-01-14 02:17:15 +0000329
330 // Optionally add output and anti dependencies. For anti
331 // dependencies we use a latency of 0 because for a multi-issue
332 // target we want to allow the defining instruction to issue
333 // in the same cycle as the using instruction.
334 // TODO: Using a latency of 1 here for output dependencies assumes
335 // there's no cost for reusing registers.
336 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000337 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
338 Alias.isValid(); ++Alias) {
Andrew Trick9dbbd3e2012-02-24 07:04:55 +0000339 if (!Defs.contains(*Alias))
Andrew Trickd675a4c2012-02-23 01:52:38 +0000340 continue;
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000341 for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
342 SUnit *DefSU = I->SU;
Andrew Trickdbee9d82012-01-14 02:17:15 +0000343 if (DefSU == &ExitSU)
344 continue;
345 if (DefSU != SU &&
346 (Kind != SDep::Output || !MO.isDead() ||
Hal Finkel66d77912014-12-05 02:07:35 +0000347 !DefSU->getInstr()->registerDefIsDead(*Alias))) {
Andrew Trickdbee9d82012-01-14 02:17:15 +0000348 if (Kind == SDep::Anti)
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000349 DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
Andrew Trickdbee9d82012-01-14 02:17:15 +0000350 else {
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000351 SDep Dep(SU, Kind, /*Reg=*/*Alias);
Andrew Trickde2109e2013-06-15 04:49:57 +0000352 Dep.setLatency(
353 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000354 DefSU->addPred(Dep);
Andrew Trickdbee9d82012-01-14 02:17:15 +0000355 }
356 }
357 }
358 }
359
Andrew Trickd675a4c2012-02-23 01:52:38 +0000360 if (!MO.isDef()) {
Andrew Tricke833e1c2013-04-13 06:07:40 +0000361 SU->hasPhysRegUses = true;
Andrew Trickd675a4c2012-02-23 01:52:38 +0000362 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
363 // retrieve the existing SUnits list for this register's uses.
364 // Push this SUnit on the use list.
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000365 Uses.insert(PhysRegSUOper(SU, OperIdx, MO.getReg()));
Andrew Trick6b104f82013-12-28 21:56:55 +0000366 if (RemoveKillFlags)
367 MO.setIsKill(false);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000368 }
369 else {
Andrew Trickae535612012-08-23 00:39:43 +0000370 addPhysRegDataDeps(SU, OperIdx);
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000371 unsigned Reg = MO.getReg();
Andrew Trickdbee9d82012-01-14 02:17:15 +0000372
Andrew Trickd675a4c2012-02-23 01:52:38 +0000373 // clear this register's use list
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000374 if (Uses.contains(Reg))
375 Uses.eraseAll(Reg);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000376
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000377 if (!MO.isDead()) {
378 Defs.eraseAll(Reg);
379 } else if (SU->isCall) {
380 // Calls will not be reordered because of chain dependencies (see
381 // below). Since call operands are dead, calls may continue to be added
382 // to the DefList making dependence checking quadratic in the size of
383 // the block. Instead, we leave only one call at the back of the
384 // DefList.
385 Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
386 Reg2SUnitsMap::iterator B = P.first;
387 Reg2SUnitsMap::iterator I = P.second;
388 for (bool isBegin = I == B; !isBegin; /* empty */) {
389 isBegin = (--I) == B;
390 if (!I->SU->isCall)
391 break;
392 I = Defs.erase(I);
393 }
Andrew Trickdbee9d82012-01-14 02:17:15 +0000394 }
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000395
Andrew Trickd675a4c2012-02-23 01:52:38 +0000396 // Defs are pushed in the order they are visited and never reordered.
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000397 Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
Andrew Trickdbee9d82012-01-14 02:17:15 +0000398 }
399}
400
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000401LaneBitmask ScheduleDAGInstrs::getLaneMaskForMO(const MachineOperand &MO) const
402{
403 unsigned Reg = MO.getReg();
404 // No point in tracking lanemasks if we don't have interesting subregisters.
405 const TargetRegisterClass &RC = *MRI.getRegClass(Reg);
406 if (!RC.HasDisjunctSubRegs)
407 return ~0u;
408
409 unsigned SubReg = MO.getSubReg();
410 if (SubReg == 0)
411 return RC.getLaneMask();
412 return TRI->getSubRegIndexLaneMask(SubReg);
413}
414
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000415/// addVRegDefDeps - Add register output and data dependencies from this SUnit
416/// to instructions that occur later in the same scheduling region if they read
417/// from or write to the virtual register defined at OperIdx.
418///
419/// TODO: Hoist loop induction variable increments. This has to be
420/// reevaluated. Generally, IV scheduling should be done before coalescing.
421void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000422 MachineInstr *MI = SU->getInstr();
423 MachineOperand &MO = MI->getOperand(OperIdx);
424 unsigned Reg = MO.getReg();
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000425
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000426 LaneBitmask DefLaneMask;
427 LaneBitmask KillLaneMask;
428 if (TrackLaneMasks) {
429 bool IsKill = MO.getSubReg() == 0 || MO.isUndef();
430 DefLaneMask = getLaneMaskForMO(MO);
431 // If we have a <read-undef> flag, none of the lane values comes from an
432 // earlier instruction.
433 KillLaneMask = IsKill ? ~0u : DefLaneMask;
434
435 // Clear undef flag, we'll re-add it later once we know which subregister
436 // Def is first.
437 MO.setIsUndef(false);
438 } else {
439 DefLaneMask = ~0u;
440 KillLaneMask = ~0u;
441 }
442
443 if (MO.isDead()) {
444 assert(CurrentVRegUses.find(Reg) == CurrentVRegUses.end() &&
445 "Dead defs should have no uses");
446 } else {
447 // Add data dependence to all uses we found so far.
448 const TargetSubtargetInfo &ST = MF.getSubtarget();
449 for (VReg2SUnitOperIdxMultiMap::iterator I = CurrentVRegUses.find(Reg),
450 E = CurrentVRegUses.end(); I != E; /*empty*/) {
451 LaneBitmask LaneMask = I->LaneMask;
452 // Ignore uses of other lanes.
453 if ((LaneMask & KillLaneMask) == 0) {
454 ++I;
455 continue;
456 }
457
458 if ((LaneMask & DefLaneMask) != 0) {
459 SUnit *UseSU = I->SU;
460 MachineInstr *Use = UseSU->getInstr();
461 SDep Dep(SU, SDep::Data, Reg);
462 Dep.setLatency(SchedModel.computeOperandLatency(MI, OperIdx, Use,
463 I->OperandIndex));
464 ST.adjustSchedDependency(SU, UseSU, Dep);
465 UseSU->addPred(Dep);
466 }
467
468 LaneMask &= ~KillLaneMask;
469 // If we found a Def for all lanes of this use, remove it from the list.
470 if (LaneMask != 0) {
471 I->LaneMask = LaneMask;
472 ++I;
473 } else
474 I = CurrentVRegUses.erase(I);
475 }
476 }
477
478 // Shortcut: Singly defined vregs do not have output/anti dependencies.
Andrew Trick79795892012-07-30 23:48:17 +0000479 if (MRI.hasOneDef(Reg))
Andrew Trick94053432012-07-28 01:48:15 +0000480 return;
Andrew Trickdb42c6f2012-02-22 06:08:13 +0000481
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000482 // Add output dependence to the next nearest defs of this vreg.
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000483 //
484 // Unless this definition is dead, the output dependence should be
485 // transitively redundant with antidependencies from this definition's
486 // uses. We're conservative for now until we have a way to guarantee the uses
487 // are not eliminated sometime during scheduling. The output dependence edge
488 // is also useful if output latency exceeds def-use latency.
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000489 LaneBitmask LaneMask = DefLaneMask;
490 for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
491 CurrentVRegDefs.end())) {
492 // Ignore defs for other lanes.
493 if ((V2SU.LaneMask & LaneMask) == 0)
494 continue;
495 // Add an output dependence.
496 SUnit *DefSU = V2SU.SU;
497 // Ignore additional defs of the same lanes in one instruction. This can
498 // happen because lanemasks are shared for targets with too many
499 // subregisters. We also use some representration tricks/hacks where we
500 // add super-register defs/uses, to imply that although we only access parts
501 // of the reg we care about the full one.
502 if (DefSU == SU)
503 continue;
504 SDep Dep(SU, SDep::Output, Reg);
505 Dep.setLatency(
506 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
507 DefSU->addPred(Dep);
508
509 // Update current definition. This can get tricky if the def was about a
510 // bigger lanemask before. We then have to shrink it and create a new
511 // VReg2SUnit for the non-overlapping part.
512 LaneBitmask OverlapMask = V2SU.LaneMask & LaneMask;
513 LaneBitmask NonOverlapMask = V2SU.LaneMask & ~LaneMask;
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000514 V2SU.SU = SU;
515 V2SU.LaneMask = OverlapMask;
Matthias Braun4c994ee2016-05-25 01:18:00 +0000516 if (NonOverlapMask != 0)
517 CurrentVRegDefs.insert(VReg2SUnit(Reg, NonOverlapMask, DefSU));
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000518 }
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000519 // If there was no CurrentVRegDefs entry for some lanes yet, create one.
520 if (LaneMask != 0)
521 CurrentVRegDefs.insert(VReg2SUnit(Reg, LaneMask, SU));
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000522}
523
Andrew Trick46cc9a42012-02-22 06:08:11 +0000524/// addVRegUseDeps - Add a register data dependency if the instruction that
525/// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
526/// register antidependency from this SUnit to instructions that occur later in
527/// the same scheduling region if they write the virtual register.
528///
529/// TODO: Handle ExitSU "uses" properly.
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000530void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000531 const MachineInstr *MI = SU->getInstr();
532 const MachineOperand &MO = MI->getOperand(OperIdx);
533 unsigned Reg = MO.getReg();
Andrew Trick46cc9a42012-02-22 06:08:11 +0000534
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000535 // Remember the use. Data dependencies will be added when we find the def.
536 LaneBitmask LaneMask = TrackLaneMasks ? getLaneMaskForMO(MO) : ~0u;
537 CurrentVRegUses.insert(VReg2SUnitOperIdx(Reg, LaneMask, OperIdx, SU));
538
539 // Add antidependences to the following defs of the vreg.
540 for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
541 CurrentVRegDefs.end())) {
542 // Ignore defs for unrelated lanes.
543 LaneBitmask PrevDefLaneMask = V2SU.LaneMask;
544 if ((PrevDefLaneMask & LaneMask) == 0)
545 continue;
546 if (V2SU.SU == SU)
547 continue;
548
549 V2SU.SU->addPred(SDep(SU, SDep::Anti, Reg));
Andrew Trick2bc74c22013-08-30 04:36:57 +0000550 }
Andrew Trick46cc9a42012-02-22 06:08:11 +0000551}
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000552
Andrew Trickda01ba32012-05-15 18:59:41 +0000553/// Return true if MI is an instruction we are unable to reason about
554/// (like a call or something with unmodeled side effects).
555static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
Rafael Espindola84921b92015-10-24 23:11:13 +0000556 return MI->isCall() || MI->hasUnmodeledSideEffects() ||
Justin Lebard98cf002016-09-10 01:03:20 +0000557 (MI->hasOrderedMemoryRef() && !MI->isDereferenceableInvariantLoad(AA));
Andrew Trickda01ba32012-05-15 18:59:41 +0000558}
559
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000560/// This returns true if the two MIs need a chain edge between them.
Jonas Paulssonac29f012016-02-03 17:52:29 +0000561/// This is called on normal stores and loads.
Andrew Trickda01ba32012-05-15 18:59:41 +0000562static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000563 const DataLayout &DL, MachineInstr *MIa,
Andrew Trickda01ba32012-05-15 18:59:41 +0000564 MachineInstr *MIb) {
Chad Rosier3528c1e2014-09-08 14:43:48 +0000565 const MachineFunction *MF = MIa->getParent()->getParent();
566 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
567
Jonas Paulssonac29f012016-02-03 17:52:29 +0000568 assert ((MIa->mayStore() || MIb->mayStore()) &&
569 "Dependency checked between two loads");
570
Jonas Paulsson8c738632016-01-29 17:22:43 +0000571 // Let the target decide if memory accesses cannot possibly overlap.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000572 if (TII->areMemAccessesTriviallyDisjoint(*MIa, *MIb, AA))
Jonas Paulssonac29f012016-02-03 17:52:29 +0000573 return false;
Andrew Trickda01ba32012-05-15 18:59:41 +0000574
Andrew Trickda01ba32012-05-15 18:59:41 +0000575 // To this point analysis is generic. From here on we do need AA.
576 if (!AA)
577 return true;
578
Jonas Paulsson98963fe2016-02-15 16:43:15 +0000579 // FIXME: Need to handle multiple memory operands to support all targets.
580 if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
581 return true;
582
Andrew Trickda01ba32012-05-15 18:59:41 +0000583 MachineMemOperand *MMOa = *MIa->memoperands_begin();
584 MachineMemOperand *MMOb = *MIb->memoperands_begin();
585
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000586 if (!MMOa->getValue() || !MMOb->getValue())
587 return true;
588
Andrew Trickda01ba32012-05-15 18:59:41 +0000589 // The following interface to AA is fashioned after DAGCombiner::isAlias
590 // and operates with MachineMemOperand offset with some important
591 // assumptions:
592 // - LLVM fundamentally assumes flat address spaces.
593 // - MachineOperand offset can *only* result from legalization and
594 // cannot affect queries other than the trivial case of overlap
595 // checking.
596 // - These offsets never wrap and never step outside
597 // of allocated objects.
598 // - There should never be any negative offsets here.
599 //
600 // FIXME: Modify API to hide this math from "user"
601 // FIXME: Even before we go to AA we can reason locally about some
602 // memory objects. It can save compile time, and possibly catch some
603 // corner cases not currently covered.
604
605 assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
606 assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
607
608 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
609 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
610 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
611
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000612 AliasResult AAResult =
Chandler Carruthac80dc72015-06-17 07:18:54 +0000613 AA->alias(MemoryLocation(MMOa->getValue(), Overlapa,
614 UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
615 MemoryLocation(MMOb->getValue(), Overlapb,
616 UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
Andrew Trickda01ba32012-05-15 18:59:41 +0000617
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000618 return (AAResult != NoAlias);
Andrew Trickda01ba32012-05-15 18:59:41 +0000619}
620
Jonas Paulssonac29f012016-02-03 17:52:29 +0000621/// Check whether two objects need a chain edge and add it if needed.
622void ScheduleDAGInstrs::addChainDependency (SUnit *SUa, SUnit *SUb,
623 unsigned Latency) {
Matthias Braun941a7052016-07-28 18:40:00 +0000624 if (MIsNeedChainEdge(AAForDep, &MFI, MF.getDataLayout(), SUa->getInstr(),
NAKAMURA Takumid6ddc7e2016-07-25 00:59:51 +0000625 SUb->getInstr())) {
Jonas Paulssonac29f012016-02-03 17:52:29 +0000626 SDep Dep(SUa, SDep::MayAliasMem);
627 Dep.setLatency(Latency);
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000628 SUb->addPred(Dep);
629 }
Andrew Trickda01ba32012-05-15 18:59:41 +0000630}
631
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000632/// Create an SUnit for each real instruction, numbered in top-down topological
Andrew Trick46cc9a42012-02-22 06:08:11 +0000633/// order. The instruction order A < B, implies that no edge exists from B to A.
634///
635/// Map each real instruction to its SUnit.
636///
Andrew Trick8823dec2012-03-14 04:00:41 +0000637/// After initSUnits, the SUnits vector cannot be resized and the scheduler may
638/// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
639/// instead of pointers.
640///
641/// MachineScheduler relies on initSUnits numbering the nodes by their order in
642/// the original instruction list.
Andrew Trick46cc9a42012-02-22 06:08:11 +0000643void ScheduleDAGInstrs::initSUnits() {
644 // We'll be allocating one SUnit for each real instruction in the region,
645 // which is contained within a basic block.
Andrew Tricka53e1012013-08-23 17:48:33 +0000646 SUnits.reserve(NumRegionInstrs);
Andrew Trick46cc9a42012-02-22 06:08:11 +0000647
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000648 for (MachineInstr &MI : llvm::make_range(RegionBegin, RegionEnd)) {
649 if (MI.isDebugValue())
Andrew Trick46cc9a42012-02-22 06:08:11 +0000650 continue;
651
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000652 SUnit *SU = newSUnit(&MI);
653 MISUnitMap[&MI] = SU;
Andrew Trick46cc9a42012-02-22 06:08:11 +0000654
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000655 SU->isCall = MI.isCall();
656 SU->isCommutable = MI.isCommutable();
Andrew Trick46cc9a42012-02-22 06:08:11 +0000657
658 // Assign the Latency field of SU using target-provided information.
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000659 SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
Andrew Trick880e5732013-12-05 17:55:58 +0000660
Andrew Trick1766f932014-04-18 17:35:08 +0000661 // If this SUnit uses a reserved or unbuffered resource, mark it as such.
662 //
Alp Tokerbeaca192014-05-15 01:52:21 +0000663 // Reserved resources block an instruction from issuing and stall the
Andrew Trick1766f932014-04-18 17:35:08 +0000664 // entire pipeline. These are identified by BufferSize=0.
665 //
Alp Tokerbeaca192014-05-15 01:52:21 +0000666 // Unbuffered resources prevent execution of subsequent instructions that
Andrew Trick1766f932014-04-18 17:35:08 +0000667 // require the same resources. This is used for in-order execution pipelines
668 // within an out-of-order core. These are identified by BufferSize=1.
Andrew Trick880e5732013-12-05 17:55:58 +0000669 if (SchedModel.hasInstrSchedModel()) {
670 const MCSchedClassDesc *SC = getSchedClass(SU);
671 for (TargetSchedModel::ProcResIter
672 PI = SchedModel.getWriteProcResBegin(SC),
673 PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
Andrew Trick5a22df42013-12-05 17:56:02 +0000674 switch (SchedModel.getProcResource(PI->ProcResourceIdx)->BufferSize) {
675 case 0:
676 SU->hasReservedResource = true;
677 break;
678 case 1:
Andrew Trick880e5732013-12-05 17:55:58 +0000679 SU->isUnbuffered = true;
680 break;
Andrew Trick5a22df42013-12-05 17:56:02 +0000681 default:
682 break;
Andrew Trick880e5732013-12-05 17:55:58 +0000683 }
684 }
685 }
Andrew Trick46cc9a42012-02-22 06:08:11 +0000686 }
Andrew Trickdbee9d82012-01-14 02:17:15 +0000687}
688
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000689void ScheduleDAGInstrs::collectVRegUses(SUnit *SU) {
690 const MachineInstr *MI = SU->getInstr();
691 for (const MachineOperand &MO : MI->operands()) {
692 if (!MO.isReg())
693 continue;
694 if (!MO.readsReg())
695 continue;
696 if (TrackLaneMasks && !MO.isUse())
697 continue;
698
699 unsigned Reg = MO.getReg();
700 if (!TargetRegisterInfo::isVirtualRegister(Reg))
701 continue;
702
Matthias Braund4f64092016-01-20 00:23:32 +0000703 // Ignore re-defs.
704 if (TrackLaneMasks) {
705 bool FoundDef = false;
706 for (const MachineOperand &MO2 : MI->operands()) {
707 if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
708 FoundDef = true;
709 break;
710 }
711 }
712 if (FoundDef)
713 continue;
714 }
715
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000716 // Record this local VReg use.
717 VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg);
718 for (; UI != VRegUses.end(); ++UI) {
719 if (UI->SU == SU)
720 break;
721 }
722 if (UI == VRegUses.end())
723 VRegUses.insert(VReg2SUnit(Reg, 0, SU));
724 }
725}
726
Jonas Paulssonac29f012016-02-03 17:52:29 +0000727class ScheduleDAGInstrs::Value2SUsMap : public MapVector<ValueType, SUList> {
728
729 /// Current total number of SUs in map.
730 unsigned NumNodes;
731
732 /// 1 for loads, 0 for stores. (see comment in SUList)
733 unsigned TrueMemOrderLatency;
734public:
735
736 Value2SUsMap(unsigned lat = 0) : NumNodes(0), TrueMemOrderLatency(lat) {}
737
738 /// To keep NumNodes up to date, insert() is used instead of
739 /// this operator w/ push_back().
740 ValueType &operator[](const SUList &Key) {
741 llvm_unreachable("Don't use. Use insert() instead."); };
742
743 /// Add SU to the SUList of V. If Map grows huge, reduce its size
744 /// by calling reduce().
745 void inline insert(SUnit *SU, ValueType V) {
746 MapVector::operator[](V).push_back(SU);
747 NumNodes++;
748 }
749
750 /// Clears the list of SUs mapped to V.
751 void inline clearList(ValueType V) {
752 iterator Itr = find(V);
753 if (Itr != end()) {
754 assert (NumNodes >= Itr->second.size());
755 NumNodes -= Itr->second.size();
756
757 Itr->second.clear();
758 }
759 }
760
761 /// Clears map from all contents.
762 void clear() {
763 MapVector<ValueType, SUList>::clear();
764 NumNodes = 0;
765 }
766
767 unsigned inline size() const { return NumNodes; }
768
769 /// Count the number of SUs in this map after a reduction.
770 void reComputeSize(void) {
771 NumNodes = 0;
772 for (auto &I : *this)
773 NumNodes += I.second.size();
774 }
775
776 unsigned inline getTrueMemOrderLatency() const {
777 return TrueMemOrderLatency;
778 }
779
780 void dump();
781};
782
783void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
784 Value2SUsMap &Val2SUsMap) {
785 for (auto &I : Val2SUsMap)
786 addChainDependencies(SU, I.second,
787 Val2SUsMap.getTrueMemOrderLatency());
788}
789
790void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
791 Value2SUsMap &Val2SUsMap,
792 ValueType V) {
793 Value2SUsMap::iterator Itr = Val2SUsMap.find(V);
794 if (Itr != Val2SUsMap.end())
795 addChainDependencies(SU, Itr->second,
796 Val2SUsMap.getTrueMemOrderLatency());
797}
798
799void ScheduleDAGInstrs::addBarrierChain(Value2SUsMap &map) {
800 assert (BarrierChain != nullptr);
801
802 for (auto &I : map) {
803 SUList &sus = I.second;
804 for (auto *SU : sus)
805 SU->addPredBarrier(BarrierChain);
806 }
807 map.clear();
808}
809
810void ScheduleDAGInstrs::insertBarrierChain(Value2SUsMap &map) {
811 assert (BarrierChain != nullptr);
812
813 // Go through all lists of SUs.
814 for (Value2SUsMap::iterator I = map.begin(), EE = map.end(); I != EE;) {
815 Value2SUsMap::iterator CurrItr = I++;
816 SUList &sus = CurrItr->second;
817 SUList::iterator SUItr = sus.begin(), SUEE = sus.end();
818 for (; SUItr != SUEE; ++SUItr) {
819 // Stop on BarrierChain or any instruction above it.
820 if ((*SUItr)->NodeNum <= BarrierChain->NodeNum)
821 break;
822
823 (*SUItr)->addPredBarrier(BarrierChain);
824 }
825
826 // Remove also the BarrierChain from list if present.
NAKAMURA Takumibc46f622016-05-02 17:29:55 +0000827 if (SUItr != SUEE && *SUItr == BarrierChain)
Jonas Paulssonac29f012016-02-03 17:52:29 +0000828 SUItr++;
829
830 // Remove all SUs that are now successors of BarrierChain.
831 if (SUItr != sus.begin())
832 sus.erase(sus.begin(), SUItr);
833 }
834
835 // Remove all entries with empty su lists.
836 map.remove_if([&](std::pair<ValueType, SUList> &mapEntry) {
837 return (mapEntry.second.empty()); });
838
839 // Recompute the size of the map (NumNodes).
840 map.reComputeSize();
841}
842
Alp Tokerf907b892013-12-05 05:44:44 +0000843/// If RegPressure is non-null, compute register pressure as a side effect. The
Andrew Trick88639922012-04-24 17:56:43 +0000844/// DAG builder is an efficient place to do it because it already visits
845/// operands.
846void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
Andrew Trick1a831342013-08-30 03:49:48 +0000847 RegPressureTracker *RPTracker,
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000848 PressureDiffs *PDiffs,
Matthias Braund4f64092016-01-20 00:23:32 +0000849 LiveIntervals *LIS,
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000850 bool TrackLaneMasks) {
Eric Christopher2c635492015-01-27 07:54:39 +0000851 const TargetSubtargetInfo &ST = MF.getSubtarget();
Hal Finkelb350ffd2013-08-29 03:25:05 +0000852 bool UseAA = EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI
853 : ST.useAA();
Jonas Paulssonac29f012016-02-03 17:52:29 +0000854 AAForDep = UseAA ? AA : nullptr;
855
856 BarrierChain = nullptr;
Hal Finkelb350ffd2013-08-29 03:25:05 +0000857
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000858 this->TrackLaneMasks = TrackLaneMasks;
Andrew Trick310190e2013-09-04 21:00:02 +0000859 MISUnitMap.clear();
860 ScheduleDAG::clearDAG();
861
Andrew Trick46cc9a42012-02-22 06:08:11 +0000862 // Create an SUnit for each real instruction.
863 initSUnits();
Dan Gohman60cb69e2008-11-19 23:18:57 +0000864
Andrew Trick1a831342013-08-30 03:49:48 +0000865 if (PDiffs)
866 PDiffs->init(SUnits.size());
867
Jonas Paulssonac29f012016-02-03 17:52:29 +0000868 // We build scheduling units by walking a block's instruction list
869 // from bottom to top.
Dan Gohman3aab10b2008-12-04 01:35:46 +0000870
Jonas Paulssonac29f012016-02-03 17:52:29 +0000871 // Each MIs' memory operand(s) is analyzed to a list of underlying
Jonas Paulsson22936852016-02-04 13:08:48 +0000872 // objects. The SU is then inserted in the SUList(s) mapped from the
873 // Value(s). Each Value thus gets mapped to lists of SUs depending
874 // on it, stores and loads kept separately. Two SUs are trivially
875 // non-aliasing if they both depend on only identified Values and do
876 // not share any common Value.
Jonas Paulssonac29f012016-02-03 17:52:29 +0000877 Value2SUsMap Stores, Loads(1 /*TrueMemOrderLatency*/);
Dan Gohman3aab10b2008-12-04 01:35:46 +0000878
Jonas Paulssonac29f012016-02-03 17:52:29 +0000879 // Certain memory accesses are known to not alias any SU in Stores
880 // or Loads, and have therefore their own 'NonAlias'
881 // domain. E.g. spill / reload instructions never alias LLVM I/R
Jonas Paulsson22936852016-02-04 13:08:48 +0000882 // Values. It would be nice to assume that this type of memory
883 // accesses always have a proper memory operand modelling, and are
884 // therefore never unanalyzable, but this is conservatively not
885 // done.
Jonas Paulssonac29f012016-02-03 17:52:29 +0000886 Value2SUsMap NonAliasStores, NonAliasLoads(1 /*TrueMemOrderLatency*/);
887
Dale Johannesen49de0602010-03-10 22:13:47 +0000888 // Remove any stale debug info; sometimes BuildSchedGraph is called again
889 // without emitting the info from the previous call.
Devang Patele5feef02011-06-02 20:07:12 +0000890 DbgValues.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000891 FirstDbgValue = nullptr;
Dale Johannesen49de0602010-03-10 22:13:47 +0000892
Andrew Trickd675a4c2012-02-23 01:52:38 +0000893 assert(Defs.empty() && Uses.empty() &&
894 "Only BuildGraph should update Defs/Uses");
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000895 Defs.setUniverse(TRI->getNumRegs());
896 Uses.setUniverse(TRI->getNumRegs());
Andrew Trick2e116a42011-05-06 21:52:52 +0000897
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000898 assert(CurrentVRegDefs.empty() && "nobody else should use CurrentVRegDefs");
899 assert(CurrentVRegUses.empty() && "nobody else should use CurrentVRegUses");
900 unsigned NumVirtRegs = MRI.getNumVirtRegs();
901 CurrentVRegDefs.setUniverse(NumVirtRegs);
902 CurrentVRegUses.setUniverse(NumVirtRegs);
903
Andrew Trick8dd26f02013-08-23 17:48:39 +0000904 VRegUses.clear();
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000905 VRegUses.setUniverse(NumVirtRegs);
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000906
Andrew Trickd675a4c2012-02-23 01:52:38 +0000907 // Model data dependencies between instructions being scheduled and the
908 // ExitSU.
Andrew Trick52226d42012-03-07 23:00:49 +0000909 addSchedBarrierDeps();
Andrew Trickd675a4c2012-02-23 01:52:38 +0000910
Dan Gohmanb9543432009-02-10 23:27:53 +0000911 // Walk the list of instructions, from bottom moving up.
Craig Topperc0196b12014-04-14 00:51:57 +0000912 MachineInstr *DbgMI = nullptr;
Andrew Trick8c207e42012-03-09 04:29:02 +0000913 for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000914 MII != MIE; --MII) {
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000915 MachineInstr &MI = *std::prev(MII);
916 if (DbgMI) {
917 DbgValues.push_back(std::make_pair(DbgMI, &MI));
Craig Topperc0196b12014-04-14 00:51:57 +0000918 DbgMI = nullptr;
Devang Patele5feef02011-06-02 20:07:12 +0000919 }
920
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000921 if (MI.isDebugValue()) {
922 DbgMI = &MI;
Dale Johannesen49de0602010-03-10 22:13:47 +0000923 continue;
924 }
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000925 SUnit *SU = MISUnitMap[&MI];
Andrew Trick1a831342013-08-30 03:49:48 +0000926 assert(SU && "No SUnit mapped to this MI");
927
Andrew Trick88639922012-04-24 17:56:43 +0000928 if (RPTracker) {
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000929 collectVRegUses(SU);
Matthias Braunb505c762016-01-12 22:57:35 +0000930
931 RegisterOperands RegOpers;
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000932 RegOpers.collect(MI, *TRI, MRI, TrackLaneMasks, false);
Matthias Braund4f64092016-01-20 00:23:32 +0000933 if (TrackLaneMasks) {
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000934 SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
Matthias Braund4f64092016-01-20 00:23:32 +0000935 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx);
936 }
Matthias Braunb505c762016-01-12 22:57:35 +0000937 if (PDiffs != nullptr)
938 PDiffs->addInstruction(SU->NodeNum, RegOpers, MRI);
939
940 RPTracker->recedeSkipDebugValues();
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000941 assert(&*RPTracker->getPos() == &MI && "RPTracker in sync");
Matthias Braunb505c762016-01-12 22:57:35 +0000942 RPTracker->recede(RegOpers);
Andrew Trick88639922012-04-24 17:56:43 +0000943 }
Devang Patele5feef02011-06-02 20:07:12 +0000944
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000945 assert(
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000946 (CanHandleTerminators || (!MI.isTerminator() && !MI.isPosition())) &&
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000947 "Cannot schedule terminators or labels!");
Dan Gohman60cb69e2008-11-19 23:18:57 +0000948
Dan Gohman3aab10b2008-12-04 01:35:46 +0000949 // Add register-based dependencies (data, anti, and output).
Krzysztof Parzyszeka356bb72016-05-10 16:50:30 +0000950 // For some instructions (calls, returns, inline-asm, etc.) there can
951 // be explicit uses and implicit defs, in which case the use will appear
952 // on the operand list before the def. Do two passes over the operand
953 // list to make sure that defs are processed before any uses.
Andrew Trickec256482012-12-18 20:53:01 +0000954 bool HasVRegDef = false;
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000955 for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
956 const MachineOperand &MO = MI.getOperand(j);
Krzysztof Parzyszeka356bb72016-05-10 16:50:30 +0000957 if (!MO.isReg() || !MO.isDef())
958 continue;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000959 unsigned Reg = MO.getReg();
Krzysztof Parzyszeka356bb72016-05-10 16:50:30 +0000960 if (Reg == 0)
961 continue;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000962
Andrew Trickdbee9d82012-01-14 02:17:15 +0000963 if (TRI->isPhysicalRegister(Reg))
964 addPhysRegDeps(SU, j);
965 else {
Krzysztof Parzyszeka356bb72016-05-10 16:50:30 +0000966 HasVRegDef = true;
967 addVRegDefDeps(SU, j);
Dan Gohman60cb69e2008-11-19 23:18:57 +0000968 }
969 }
Krzysztof Parzyszeka356bb72016-05-10 16:50:30 +0000970 // Now process all uses.
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000971 for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
972 const MachineOperand &MO = MI.getOperand(j);
Matthias Braun8a5b4672016-05-10 20:11:58 +0000973 // Only look at use operands.
974 // We do not need to check for MO.readsReg() here because subsequent
975 // subregister defs will get output dependence edges and need no
976 // additional use dependencies.
Krzysztof Parzyszeka356bb72016-05-10 16:50:30 +0000977 if (!MO.isReg() || !MO.isUse())
978 continue;
979 unsigned Reg = MO.getReg();
980 if (Reg == 0)
981 continue;
982
983 if (TRI->isPhysicalRegister(Reg))
984 addPhysRegDeps(SU, j);
985 else if (MO.readsReg()) // ignore undef operands
986 addVRegUseDeps(SU, j);
987 }
988
Andrew Trickec256482012-12-18 20:53:01 +0000989 // If we haven't seen any uses in this scheduling region, create a
990 // dependence edge to ExitSU to model the live-out latency. This is required
991 // for vreg defs with no in-region use, and prefetches with no vreg def.
992 //
993 // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
994 // check currently relies on being called before adding chain deps.
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000995 if (SU->NumSuccs == 0 && SU->Latency > 1 && (HasVRegDef || MI.mayLoad())) {
Andrew Trickec256482012-12-18 20:53:01 +0000996 SDep Dep(SU, SDep::Artificial);
997 Dep.setLatency(SU->Latency - 1);
998 ExitSU.addPred(Dep);
999 }
Dan Gohman3aab10b2008-12-04 01:35:46 +00001000
Jonas Paulssonac29f012016-02-03 17:52:29 +00001001 // Add memory dependencies (Note: isStoreToStackSlot and
1002 // isLoadFromStackSLot are not usable after stack slots are lowered to
1003 // actual addresses).
1004
1005 // This is a barrier event that acts as a pivotal node in the DAG.
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +00001006 if (isGlobalMemoryObject(AA, &MI)) {
Jonas Paulssonac29f012016-02-03 17:52:29 +00001007
1008 // Become the barrier chain.
David Goodwind2f9c042009-11-09 19:22:17 +00001009 if (BarrierChain)
Jonas Paulssonac29f012016-02-03 17:52:29 +00001010 BarrierChain->addPredBarrier(SU);
David Goodwind2f9c042009-11-09 19:22:17 +00001011 BarrierChain = SU;
1012
Jonas Paulssonac29f012016-02-03 17:52:29 +00001013 DEBUG(dbgs() << "Global memory object and new barrier chain: SU("
1014 << BarrierChain->NodeNum << ").\n";);
Tom Stellard3e01d472014-12-08 23:36:48 +00001015
Jonas Paulssonac29f012016-02-03 17:52:29 +00001016 // Add dependencies against everything below it and clear maps.
1017 addBarrierChain(Stores);
1018 addBarrierChain(Loads);
1019 addBarrierChain(NonAliasStores);
1020 addBarrierChain(NonAliasLoads);
Hal Finkel66859ae2012-12-10 18:49:16 +00001021
Jonas Paulssonac29f012016-02-03 17:52:29 +00001022 continue;
1023 }
1024
1025 // If it's not a store or a variant load, we're done.
Justin Lebard98cf002016-09-10 01:03:20 +00001026 if (!MI.mayStore() &&
1027 !(MI.mayLoad() && !MI.isDereferenceableInvariantLoad(AA)))
Jonas Paulssonac29f012016-02-03 17:52:29 +00001028 continue;
1029
1030 // Always add dependecy edge to BarrierChain if present.
1031 if (BarrierChain)
1032 BarrierChain->addPredBarrier(SU);
1033
1034 // Find the underlying objects for MI. The Objs vector is either
1035 // empty, or filled with the Values of memory locations which this
1036 // SU depends on. An empty vector means the memory location is
Jonas Paulsson98963fe2016-02-15 16:43:15 +00001037 // unknown, and may alias anything.
Jonas Paulssonac29f012016-02-03 17:52:29 +00001038 UnderlyingObjectsVector Objs;
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +00001039 getUnderlyingObjectsForInstr(&MI, MFI, Objs, MF.getDataLayout());
Jonas Paulssonac29f012016-02-03 17:52:29 +00001040
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +00001041 if (MI.mayStore()) {
Hal Finkel66859ae2012-12-10 18:49:16 +00001042 if (Objs.empty()) {
Jonas Paulssonac29f012016-02-03 17:52:29 +00001043 // An unknown store depends on all stores and loads.
1044 addChainDependencies(SU, Stores);
1045 addChainDependencies(SU, NonAliasStores);
1046 addChainDependencies(SU, Loads);
1047 addChainDependencies(SU, NonAliasLoads);
1048
1049 // Map this store to 'UnknownValue'.
1050 Stores.insert(SU, UnknownValue);
Chandler Carruthb4728562016-03-31 21:55:58 +00001051 } else {
1052 // Add precise dependencies against all previously seen memory
1053 // accesses mapped to the same Value(s).
Geoff Berry63817132016-04-14 21:31:07 +00001054 for (const UnderlyingObject &UnderlObj : Objs) {
1055 ValueType V = UnderlObj.getValue();
1056 bool ThisMayAlias = UnderlObj.mayAlias();
Chandler Carruthb4728562016-03-31 21:55:58 +00001057
1058 // Add dependencies to previous stores and loads mapped to V.
Geoff Berry63817132016-04-14 21:31:07 +00001059 addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
Chandler Carruthb4728562016-03-31 21:55:58 +00001060 addChainDependencies(SU, (ThisMayAlias ? Loads : NonAliasLoads), V);
Geoff Berryc0739d82016-04-12 15:50:19 +00001061 }
1062 // Update the store map after all chains have been added to avoid adding
1063 // self-loop edge if multiple underlying objects are present.
Geoff Berry63817132016-04-14 21:31:07 +00001064 for (const UnderlyingObject &UnderlObj : Objs) {
1065 ValueType V = UnderlObj.getValue();
1066 bool ThisMayAlias = UnderlObj.mayAlias();
Chandler Carruthb4728562016-03-31 21:55:58 +00001067
1068 // Map this store to V.
Geoff Berry63817132016-04-14 21:31:07 +00001069 (ThisMayAlias ? Stores : NonAliasStores).insert(SU, V);
Chandler Carruthb4728562016-03-31 21:55:58 +00001070 }
1071 // The store may have dependencies to unanalyzable loads and
1072 // stores.
1073 addChainDependencies(SU, Loads, UnknownValue);
1074 addChainDependencies(SU, Stores, UnknownValue);
Hal Finkel66859ae2012-12-10 18:49:16 +00001075 }
Chandler Carruthb4728562016-03-31 21:55:58 +00001076 } else { // SU is a load.
Jonas Paulssonac29f012016-02-03 17:52:29 +00001077 if (Objs.empty()) {
1078 // An unknown load depends on all stores.
1079 addChainDependencies(SU, Stores);
1080 addChainDependencies(SU, NonAliasStores);
1081
1082 Loads.insert(SU, UnknownValue);
Chandler Carruthb4728562016-03-31 21:55:58 +00001083 } else {
Geoff Berry63817132016-04-14 21:31:07 +00001084 for (const UnderlyingObject &UnderlObj : Objs) {
1085 ValueType V = UnderlObj.getValue();
1086 bool ThisMayAlias = UnderlObj.mayAlias();
Chandler Carruthb4728562016-03-31 21:55:58 +00001087
1088 // Add precise dependencies against all previously seen stores
1089 // mapping to the same Value(s).
1090 addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
1091
1092 // Map this load to V.
1093 (ThisMayAlias ? Loads : NonAliasLoads).insert(SU, V);
1094 }
1095 // The load may have dependencies to unanalyzable stores.
1096 addChainDependencies(SU, Stores, UnknownValue);
Hal Finkel66859ae2012-12-10 18:49:16 +00001097 }
Jonas Paulssonac29f012016-02-03 17:52:29 +00001098 }
1099
1100 // Reduce maps if they grow huge.
1101 if (Stores.size() + Loads.size() >= HugeRegion) {
1102 DEBUG(dbgs() << "Reducing Stores and Loads maps.\n";);
Mehdi Amini59ae8542016-04-16 04:58:30 +00001103 reduceHugeMemNodeMaps(Stores, Loads, getReductionSize());
Jonas Paulssonac29f012016-02-03 17:52:29 +00001104 }
1105 if (NonAliasStores.size() + NonAliasLoads.size() >= HugeRegion) {
1106 DEBUG(dbgs() << "Reducing NonAliasStores and NonAliasLoads maps.\n";);
Mehdi Amini59ae8542016-04-16 04:58:30 +00001107 reduceHugeMemNodeMaps(NonAliasStores, NonAliasLoads, getReductionSize());
Dan Gohman60cb69e2008-11-19 23:18:57 +00001108 }
Dan Gohman60cb69e2008-11-19 23:18:57 +00001109 }
Jonas Paulssonac29f012016-02-03 17:52:29 +00001110
Andrew Trickb767d1e2012-12-01 01:22:49 +00001111 if (DbgMI)
1112 FirstDbgValue = DbgMI;
Dan Gohman619ef482009-01-15 19:20:50 +00001113
Andrew Trickd675a4c2012-02-23 01:52:38 +00001114 Defs.clear();
1115 Uses.clear();
Matthias Braun97d0ffb2015-12-04 01:51:19 +00001116 CurrentVRegDefs.clear();
1117 CurrentVRegUses.clear();
Jonas Paulssonac29f012016-02-03 17:52:29 +00001118}
1119
1120raw_ostream &llvm::operator<<(raw_ostream &OS, const PseudoSourceValue* PSV) {
1121 PSV->printCustom(OS);
1122 return OS;
1123}
1124
1125void ScheduleDAGInstrs::Value2SUsMap::dump() {
1126 for (auto &Itr : *this) {
1127 if (Itr.first.is<const Value*>()) {
1128 const Value *V = Itr.first.get<const Value*>();
1129 if (isa<UndefValue>(V))
1130 dbgs() << "Unknown";
1131 else
1132 V->printAsOperand(dbgs());
1133 }
1134 else if (Itr.first.is<const PseudoSourceValue*>())
1135 dbgs() << Itr.first.get<const PseudoSourceValue*>();
1136 else
1137 llvm_unreachable("Unknown Value type.");
1138
1139 dbgs() << " : ";
1140 dumpSUList(Itr.second);
1141 }
1142}
1143
1144/// Reduce maps in FIFO order, by N SUs. This is better than turning
1145/// every Nth memory SU into BarrierChain in buildSchedGraph(), since
1146/// it avoids unnecessary edges between seen SUs above the new
1147/// BarrierChain, and those below it.
1148void ScheduleDAGInstrs::reduceHugeMemNodeMaps(Value2SUsMap &stores,
1149 Value2SUsMap &loads, unsigned N) {
1150 DEBUG(dbgs() << "Before reduction:\nStoring SUnits:\n";
1151 stores.dump();
1152 dbgs() << "Loading SUnits:\n";
1153 loads.dump());
1154
1155 // Insert all SU's NodeNums into a vector and sort it.
1156 std::vector<unsigned> NodeNums;
1157 NodeNums.reserve(stores.size() + loads.size());
1158 for (auto &I : stores)
1159 for (auto *SU : I.second)
1160 NodeNums.push_back(SU->NodeNum);
1161 for (auto &I : loads)
1162 for (auto *SU : I.second)
1163 NodeNums.push_back(SU->NodeNum);
1164 std::sort(NodeNums.begin(), NodeNums.end());
1165
1166 // The N last elements in NodeNums will be removed, and the SU with
1167 // the lowest NodeNum of them will become the new BarrierChain to
1168 // let the not yet seen SUs have a dependency to the removed SUs.
1169 assert (N <= NodeNums.size());
1170 SUnit *newBarrierChain = &SUnits[*(NodeNums.end() - N)];
1171 if (BarrierChain) {
1172 // The aliasing and non-aliasing maps reduce independently of each
1173 // other, but share a common BarrierChain. Check if the
1174 // newBarrierChain is above the former one. If it is not, it may
1175 // introduce a loop to use newBarrierChain, so keep the old one.
1176 if (newBarrierChain->NodeNum < BarrierChain->NodeNum) {
1177 BarrierChain->addPredBarrier(newBarrierChain);
1178 BarrierChain = newBarrierChain;
1179 DEBUG(dbgs() << "Inserting new barrier chain: SU("
1180 << BarrierChain->NodeNum << ").\n";);
1181 }
1182 else
1183 DEBUG(dbgs() << "Keeping old barrier chain: SU("
1184 << BarrierChain->NodeNum << ").\n";);
1185 }
1186 else
1187 BarrierChain = newBarrierChain;
1188
1189 insertBarrierChain(stores);
1190 insertBarrierChain(loads);
1191
1192 DEBUG(dbgs() << "After reduction:\nStoring SUnits:\n";
1193 stores.dump();
1194 dbgs() << "Loading SUnits:\n";
1195 loads.dump());
Dan Gohman60cb69e2008-11-19 23:18:57 +00001196}
1197
Andrew Trick6b104f82013-12-28 21:56:55 +00001198/// \brief Initialize register live-range state for updating kills.
1199void ScheduleDAGInstrs::startBlockForKills(MachineBasicBlock *BB) {
1200 // Start with no live registers.
1201 LiveRegs.reset();
1202
1203 // Examine the live-in regs of all successors.
1204 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
1205 SE = BB->succ_end(); SI != SE; ++SI) {
Matthias Braund9da1622015-09-09 18:08:03 +00001206 for (const auto &LI : (*SI)->liveins()) {
Andrew Trick6b104f82013-12-28 21:56:55 +00001207 // Repeat, for reg and all subregs.
Matthias Braund9da1622015-09-09 18:08:03 +00001208 for (MCSubRegIterator SubRegs(LI.PhysReg, TRI, /*IncludeSelf=*/true);
Andrew Trick6b104f82013-12-28 21:56:55 +00001209 SubRegs.isValid(); ++SubRegs)
1210 LiveRegs.set(*SubRegs);
1211 }
1212 }
1213}
1214
Pete Cooper300069a2015-05-04 16:52:06 +00001215/// \brief If we change a kill flag on the bundle instruction implicit register
1216/// operands, then we also need to propagate that to any instructions inside
1217/// the bundle which had the same kill state.
1218static void toggleBundleKillFlag(MachineInstr *MI, unsigned Reg,
Mandeep Singh Grange5a2f112016-05-10 17:57:27 +00001219 bool NewKillState,
1220 const TargetRegisterInfo *TRI) {
Pete Cooper300069a2015-05-04 16:52:06 +00001221 if (MI->getOpcode() != TargetOpcode::BUNDLE)
1222 return;
1223
1224 // Walk backwards from the last instruction in the bundle to the first.
1225 // Once we set a kill flag on an instruction, we bail out, as otherwise we
1226 // might set it on too many operands. We will clear as many flags as we
1227 // can though.
Duncan P. N. Exon Smithc5b668d2016-02-22 20:49:58 +00001228 MachineBasicBlock::instr_iterator Begin = MI->getIterator();
Duncan P. N. Exon Smithf9ab4162016-02-27 17:05:33 +00001229 MachineBasicBlock::instr_iterator End = getBundleEnd(*MI);
Pete Cooper300069a2015-05-04 16:52:06 +00001230 while (Begin != End) {
Mandeep Singh Grange5a2f112016-05-10 17:57:27 +00001231 if (NewKillState) {
1232 if ((--End)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
1233 return;
1234 } else
1235 (--End)->clearRegisterKills(Reg, TRI);
Pete Cooper300069a2015-05-04 16:52:06 +00001236 }
1237}
1238
Andrew Trick6b104f82013-12-28 21:56:55 +00001239bool ScheduleDAGInstrs::toggleKillFlag(MachineInstr *MI, MachineOperand &MO) {
1240 // Setting kill flag...
1241 if (!MO.isKill()) {
1242 MO.setIsKill(true);
Mandeep Singh Grange5a2f112016-05-10 17:57:27 +00001243 toggleBundleKillFlag(MI, MO.getReg(), true, TRI);
Andrew Trick6b104f82013-12-28 21:56:55 +00001244 return false;
1245 }
1246
1247 // If MO itself is live, clear the kill flag...
1248 if (LiveRegs.test(MO.getReg())) {
1249 MO.setIsKill(false);
Mandeep Singh Grange5a2f112016-05-10 17:57:27 +00001250 toggleBundleKillFlag(MI, MO.getReg(), false, TRI);
Andrew Trick6b104f82013-12-28 21:56:55 +00001251 return false;
1252 }
1253
1254 // If any subreg of MO is live, then create an imp-def for that
1255 // subreg and keep MO marked as killed.
1256 MO.setIsKill(false);
Mandeep Singh Grange5a2f112016-05-10 17:57:27 +00001257 toggleBundleKillFlag(MI, MO.getReg(), false, TRI);
Andrew Trick6b104f82013-12-28 21:56:55 +00001258 bool AllDead = true;
1259 const unsigned SuperReg = MO.getReg();
1260 MachineInstrBuilder MIB(MF, MI);
1261 for (MCSubRegIterator SubRegs(SuperReg, TRI); SubRegs.isValid(); ++SubRegs) {
1262 if (LiveRegs.test(*SubRegs)) {
1263 MIB.addReg(*SubRegs, RegState::ImplicitDefine);
1264 AllDead = false;
1265 }
1266 }
1267
Pete Cooper300069a2015-05-04 16:52:06 +00001268 if(AllDead) {
Andrew Trick6b104f82013-12-28 21:56:55 +00001269 MO.setIsKill(true);
Mandeep Singh Grange5a2f112016-05-10 17:57:27 +00001270 toggleBundleKillFlag(MI, MO.getReg(), true, TRI);
Pete Cooper300069a2015-05-04 16:52:06 +00001271 }
Andrew Trick6b104f82013-12-28 21:56:55 +00001272 return false;
1273}
1274
1275// FIXME: Reuse the LivePhysRegs utility for this.
1276void ScheduleDAGInstrs::fixupKills(MachineBasicBlock *MBB) {
1277 DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
1278
1279 LiveRegs.resize(TRI->getNumRegs());
1280 BitVector killedRegs(TRI->getNumRegs());
1281
1282 startBlockForKills(MBB);
1283
1284 // Examine block from end to start...
1285 unsigned Count = MBB->size();
1286 for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
1287 I != E; --Count) {
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +00001288 MachineInstr &MI = *--I;
1289 if (MI.isDebugValue())
Andrew Trick6b104f82013-12-28 21:56:55 +00001290 continue;
1291
1292 // Update liveness. Registers that are defed but not used in this
1293 // instruction are now dead. Mark register and all subregs as they
1294 // are completely defined.
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +00001295 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1296 MachineOperand &MO = MI.getOperand(i);
Andrew Trick6b104f82013-12-28 21:56:55 +00001297 if (MO.isRegMask())
1298 LiveRegs.clearBitsNotInMask(MO.getRegMask());
1299 if (!MO.isReg()) continue;
1300 unsigned Reg = MO.getReg();
1301 if (Reg == 0) continue;
1302 if (!MO.isDef()) continue;
1303 // Ignore two-addr defs.
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +00001304 if (MI.isRegTiedToUseOperand(i)) continue;
Andrew Trick6b104f82013-12-28 21:56:55 +00001305
1306 // Repeat for reg and all subregs.
1307 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1308 SubRegs.isValid(); ++SubRegs)
1309 LiveRegs.reset(*SubRegs);
1310 }
1311
1312 // Examine all used registers and set/clear kill flag. When a
1313 // register is used multiple times we only set the kill flag on
1314 // the first use. Don't set kill flags on undef operands.
1315 killedRegs.reset();
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +00001316 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1317 MachineOperand &MO = MI.getOperand(i);
Andrew Trick6b104f82013-12-28 21:56:55 +00001318 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
1319 unsigned Reg = MO.getReg();
1320 if ((Reg == 0) || MRI.isReserved(Reg)) continue;
1321
1322 bool kill = false;
1323 if (!killedRegs.test(Reg)) {
1324 kill = true;
1325 // A register is not killed if any subregs are live...
1326 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
1327 if (LiveRegs.test(*SubRegs)) {
1328 kill = false;
1329 break;
1330 }
1331 }
1332
1333 // If subreg is not live, then register is killed if it became
1334 // live in this instruction
1335 if (kill)
1336 kill = !LiveRegs.test(Reg);
1337 }
1338
1339 if (MO.isKill() != kill) {
1340 DEBUG(dbgs() << "Fixing " << MO << " in ");
1341 // Warning: toggleKillFlag may invalidate MO.
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +00001342 toggleKillFlag(&MI, MO);
1343 DEBUG(MI.dump());
1344 DEBUG({
1345 if (MI.getOpcode() == TargetOpcode::BUNDLE) {
1346 MachineBasicBlock::instr_iterator Begin = MI.getIterator();
1347 MachineBasicBlock::instr_iterator End = getBundleEnd(MI);
1348 while (++Begin != End)
1349 DEBUG(Begin->dump());
1350 }
Pete Cooper300069a2015-05-04 16:52:06 +00001351 });
Andrew Trick6b104f82013-12-28 21:56:55 +00001352 }
1353
1354 killedRegs.set(Reg);
1355 }
1356
1357 // Mark any used register (that is not using undef) and subregs as
1358 // now live...
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +00001359 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1360 MachineOperand &MO = MI.getOperand(i);
Andrew Trick6b104f82013-12-28 21:56:55 +00001361 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
1362 unsigned Reg = MO.getReg();
1363 if ((Reg == 0) || MRI.isReserved(Reg)) continue;
1364
1365 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1366 SubRegs.isValid(); ++SubRegs)
1367 LiveRegs.set(*SubRegs);
1368 }
1369 }
1370}
1371
Dan Gohman60cb69e2008-11-19 23:18:57 +00001372void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
Manman Ren19f49ac2012-09-11 22:23:19 +00001373#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman60cb69e2008-11-19 23:18:57 +00001374 SU->getInstr()->dump();
Manman Ren742534c2012-09-06 19:06:06 +00001375#endif
Dan Gohman60cb69e2008-11-19 23:18:57 +00001376}
1377
1378std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
Alp Tokere69170a2014-06-26 22:52:05 +00001379 std::string s;
1380 raw_string_ostream oss(s);
Dan Gohmanb9543432009-02-10 23:27:53 +00001381 if (SU == &EntrySU)
1382 oss << "<entry>";
1383 else if (SU == &ExitSU)
1384 oss << "<exit>";
1385 else
Eric Christopher1cdefae2015-02-27 00:11:34 +00001386 SU->getInstr()->print(oss, /*SkipOpers=*/true);
Dan Gohman60cb69e2008-11-19 23:18:57 +00001387 return oss.str();
1388}
1389
Andrew Trick1b2324d2012-03-07 00:18:22 +00001390/// Return the basic block label. It is not necessarilly unique because a block
1391/// contains multiple scheduling regions. But it is fine for visualization.
1392std::string ScheduleDAGInstrs::getDAGName() const {
1393 return "dag." + BB->getFullName();
1394}
Andrew Trick90f711d2012-10-15 18:02:27 +00001395
Andrew Trick48d392e2012-11-28 05:13:28 +00001396//===----------------------------------------------------------------------===//
1397// SchedDFSResult Implementation
1398//===----------------------------------------------------------------------===//
1399
1400namespace llvm {
1401/// \brief Internal state used to compute SchedDFSResult.
1402class SchedDFSImpl {
1403 SchedDFSResult &R;
1404
1405 /// Join DAG nodes into equivalence classes by their subtree.
1406 IntEqClasses SubtreeClasses;
1407 /// List PredSU, SuccSU pairs that represent data edges between subtrees.
1408 std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs;
1409
Andrew Trickffc80972013-01-25 06:52:27 +00001410 struct RootData {
1411 unsigned NodeID;
1412 unsigned ParentNodeID; // Parent node (member of the parent subtree).
1413 unsigned SubInstrCount; // Instr count in this tree only, not children.
1414
1415 RootData(unsigned id): NodeID(id),
1416 ParentNodeID(SchedDFSResult::InvalidSubtreeID),
1417 SubInstrCount(0) {}
1418
1419 unsigned getSparseSetIndex() const { return NodeID; }
1420 };
1421
1422 SparseSet<RootData> RootSet;
1423
Andrew Trick48d392e2012-11-28 05:13:28 +00001424public:
Andrew Trickffc80972013-01-25 06:52:27 +00001425 SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
1426 RootSet.setUniverse(R.DFSNodeData.size());
1427 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001428
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001429 /// Return true if this node been visited by the DFS traversal.
1430 ///
1431 /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
1432 /// ID. Later, SubtreeID is updated but remains valid.
Andrew Trick48d392e2012-11-28 05:13:28 +00001433 bool isVisited(const SUnit *SU) const {
Andrew Trickffc80972013-01-25 06:52:27 +00001434 return R.DFSNodeData[SU->NodeNum].SubtreeID
1435 != SchedDFSResult::InvalidSubtreeID;
Andrew Trick48d392e2012-11-28 05:13:28 +00001436 }
1437
1438 /// Initialize this node's instruction count. We don't need to flag the node
1439 /// visited until visitPostorder because the DAG cannot have cycles.
1440 void visitPreorder(const SUnit *SU) {
Andrew Trickffc80972013-01-25 06:52:27 +00001441 R.DFSNodeData[SU->NodeNum].InstrCount =
1442 SU->getInstr()->isTransient() ? 0 : 1;
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001443 }
1444
1445 /// Called once for each node after all predecessors are visited. Revisit this
1446 /// node's predecessors and potentially join them now that we know the ILP of
1447 /// the other predecessors.
1448 void visitPostorderNode(const SUnit *SU) {
1449 // Mark this node as the root of a subtree. It may be joined with its
1450 // successors later.
Andrew Trickffc80972013-01-25 06:52:27 +00001451 R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
1452 RootData RData(SU->NodeNum);
1453 RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
Andrew Trick48d392e2012-11-28 05:13:28 +00001454
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001455 // If any predecessors are still in their own subtree, they either cannot be
1456 // joined or are large enough to remain separate. If this parent node's
1457 // total instruction count is not greater than a child subtree by at least
1458 // the subtree limit, then try to join it now since splitting subtrees is
1459 // only useful if multiple high-pressure paths are possible.
Andrew Trickffc80972013-01-25 06:52:27 +00001460 unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001461 for (SUnit::const_pred_iterator
1462 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1463 if (PI->getKind() != SDep::Data)
1464 continue;
1465 unsigned PredNum = PI->getSUnit()->NodeNum;
Andrew Trickffc80972013-01-25 06:52:27 +00001466 if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001467 joinPredSubtree(*PI, SU, /*CheckLimit=*/false);
Andrew Trickffc80972013-01-25 06:52:27 +00001468
1469 // Either link or merge the TreeData entry from the child to the parent.
Andrew Trick646eeb62013-01-25 06:52:30 +00001470 if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
1471 // If the predecessor's parent is invalid, this is a tree edge and the
1472 // current node is the parent.
1473 if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
1474 RootSet[PredNum].ParentNodeID = SU->NodeNum;
1475 }
1476 else if (RootSet.count(PredNum)) {
1477 // The predecessor is not a root, but is still in the root set. This
1478 // must be the new parent that it was just joined to. Note that
1479 // RootSet[PredNum].ParentNodeID may either be invalid or may still be
1480 // set to the original parent.
Andrew Trickffc80972013-01-25 06:52:27 +00001481 RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
1482 RootSet.erase(PredNum);
1483 }
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001484 }
Andrew Trickffc80972013-01-25 06:52:27 +00001485 RootSet[SU->NodeNum] = RData;
1486 }
1487
1488 /// Called once for each tree edge after calling visitPostOrderNode on the
1489 /// predecessor. Increment the parent node's instruction count and
1490 /// preemptively join this subtree to its parent's if it is small enough.
1491 void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
1492 R.DFSNodeData[Succ->NodeNum].InstrCount
1493 += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
1494 joinPredSubtree(PredDep, Succ);
Andrew Trick48d392e2012-11-28 05:13:28 +00001495 }
1496
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001497 /// Add a connection for cross edges.
1498 void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
Andrew Trick48d392e2012-11-28 05:13:28 +00001499 ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
1500 }
1501
1502 /// Set each node's subtree ID to the representative ID and record connections
1503 /// between trees.
1504 void finalize() {
1505 SubtreeClasses.compress();
Andrew Trickffc80972013-01-25 06:52:27 +00001506 R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
1507 assert(SubtreeClasses.getNumClasses() == RootSet.size()
1508 && "number of roots should match trees");
1509 for (SparseSet<RootData>::const_iterator
1510 RI = RootSet.begin(), RE = RootSet.end(); RI != RE; ++RI) {
1511 unsigned TreeID = SubtreeClasses[RI->NodeID];
1512 if (RI->ParentNodeID != SchedDFSResult::InvalidSubtreeID)
1513 R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[RI->ParentNodeID];
1514 R.DFSTreeData[TreeID].SubInstrCount = RI->SubInstrCount;
Andrew Trick646eeb62013-01-25 06:52:30 +00001515 // Note that SubInstrCount may be greater than InstrCount if we joined
1516 // subtrees across a cross edge. InstrCount will be attributed to the
1517 // original parent, while SubInstrCount will be attributed to the joined
1518 // parent.
Andrew Trickffc80972013-01-25 06:52:27 +00001519 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001520 R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1521 R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1522 DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
Andrew Trickffc80972013-01-25 06:52:27 +00001523 for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
1524 R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
Andrew Trick48d392e2012-11-28 05:13:28 +00001525 DEBUG(dbgs() << " SU(" << Idx << ") in tree "
Andrew Trickffc80972013-01-25 06:52:27 +00001526 << R.DFSNodeData[Idx].SubtreeID << '\n');
Andrew Trick48d392e2012-11-28 05:13:28 +00001527 }
1528 for (std::vector<std::pair<const SUnit*, const SUnit*> >::const_iterator
1529 I = ConnectionPairs.begin(), E = ConnectionPairs.end();
1530 I != E; ++I) {
1531 unsigned PredTree = SubtreeClasses[I->first->NodeNum];
1532 unsigned SuccTree = SubtreeClasses[I->second->NodeNum];
1533 if (PredTree == SuccTree)
1534 continue;
1535 unsigned Depth = I->first->getDepth();
1536 addConnection(PredTree, SuccTree, Depth);
1537 addConnection(SuccTree, PredTree, Depth);
1538 }
1539 }
1540
1541protected:
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001542 /// Join the predecessor subtree with the successor that is its DFS
1543 /// parent. Apply some heuristics before joining.
1544 bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
1545 bool CheckLimit = true) {
1546 assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
1547
1548 // Check if the predecessor is already joined.
1549 const SUnit *PredSU = PredDep.getSUnit();
1550 unsigned PredNum = PredSU->NodeNum;
Andrew Trickffc80972013-01-25 06:52:27 +00001551 if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001552 return false;
Andrew Trickb52a8562013-01-25 00:12:57 +00001553
1554 // Four is the magic number of successors before a node is considered a
1555 // pinch point.
1556 unsigned NumDataSucs = 0;
Andrew Trickb52a8562013-01-25 00:12:57 +00001557 for (SUnit::const_succ_iterator SI = PredSU->Succs.begin(),
1558 SE = PredSU->Succs.end(); SI != SE; ++SI) {
1559 if (SI->getKind() == SDep::Data) {
1560 if (++NumDataSucs >= 4)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001561 return false;
Andrew Trickb52a8562013-01-25 00:12:57 +00001562 }
1563 }
Andrew Trickffc80972013-01-25 06:52:27 +00001564 if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001565 return false;
Andrew Trickffc80972013-01-25 06:52:27 +00001566 R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001567 SubtreeClasses.join(Succ->NodeNum, PredNum);
1568 return true;
Andrew Trickb52a8562013-01-25 00:12:57 +00001569 }
1570
Andrew Trick48d392e2012-11-28 05:13:28 +00001571 /// Called by finalize() to record a connection between trees.
1572 void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
1573 if (!Depth)
1574 return;
1575
Andrew Trickffc80972013-01-25 06:52:27 +00001576 do {
1577 SmallVectorImpl<SchedDFSResult::Connection> &Connections =
1578 R.SubtreeConnections[FromTree];
1579 for (SmallVectorImpl<SchedDFSResult::Connection>::iterator
1580 I = Connections.begin(), E = Connections.end(); I != E; ++I) {
1581 if (I->TreeID == ToTree) {
1582 I->Level = std::max(I->Level, Depth);
1583 return;
1584 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001585 }
Andrew Trickffc80972013-01-25 06:52:27 +00001586 Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
1587 FromTree = R.DFSTreeData[FromTree].ParentTreeID;
1588 } while (FromTree != SchedDFSResult::InvalidSubtreeID);
Andrew Trick48d392e2012-11-28 05:13:28 +00001589 }
1590};
1591} // namespace llvm
1592
Andrew Trick90f711d2012-10-15 18:02:27 +00001593namespace {
1594/// \brief Manage the stack used by a reverse depth-first search over the DAG.
1595class SchedDAGReverseDFS {
1596 std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
1597public:
1598 bool isComplete() const { return DFSStack.empty(); }
1599
1600 void follow(const SUnit *SU) {
1601 DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
1602 }
1603 void advance() { ++DFSStack.back().second; }
1604
Andrew Trick48d392e2012-11-28 05:13:28 +00001605 const SDep *backtrack() {
1606 DFSStack.pop_back();
Craig Topperc0196b12014-04-14 00:51:57 +00001607 return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
Andrew Trick48d392e2012-11-28 05:13:28 +00001608 }
Andrew Trick90f711d2012-10-15 18:02:27 +00001609
1610 const SUnit *getCurr() const { return DFSStack.back().first; }
1611
1612 SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
1613
1614 SUnit::const_pred_iterator getPredEnd() const {
1615 return getCurr()->Preds.end();
1616 }
1617};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001618} // anonymous
Andrew Trick90f711d2012-10-15 18:02:27 +00001619
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001620static bool hasDataSucc(const SUnit *SU) {
1621 for (SUnit::const_succ_iterator
1622 SI = SU->Succs.begin(), SE = SU->Succs.end(); SI != SE; ++SI) {
Andrew Trick646eeb62013-01-25 06:52:30 +00001623 if (SI->getKind() == SDep::Data && !SI->getSUnit()->isBoundaryNode())
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001624 return true;
1625 }
1626 return false;
1627}
1628
Andrew Trick90f711d2012-10-15 18:02:27 +00001629/// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
1630/// search from this root.
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001631void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
Andrew Trick90f711d2012-10-15 18:02:27 +00001632 if (!IsBottomUp)
1633 llvm_unreachable("Top-down ILP metric is unimplemnted");
1634
Andrew Trick48d392e2012-11-28 05:13:28 +00001635 SchedDFSImpl Impl(*this);
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001636 for (ArrayRef<SUnit>::const_iterator
1637 SI = SUnits.begin(), SE = SUnits.end(); SI != SE; ++SI) {
1638 const SUnit *SU = &*SI;
1639 if (Impl.isVisited(SU) || hasDataSucc(SU))
1640 continue;
1641
Andrew Trick48d392e2012-11-28 05:13:28 +00001642 SchedDAGReverseDFS DFS;
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001643 Impl.visitPreorder(SU);
1644 DFS.follow(SU);
Andrew Trick48d392e2012-11-28 05:13:28 +00001645 for (;;) {
1646 // Traverse the leftmost path as far as possible.
1647 while (DFS.getPred() != DFS.getPredEnd()) {
1648 const SDep &PredDep = *DFS.getPred();
1649 DFS.advance();
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001650 // Ignore non-data edges.
Andrew Trick646eeb62013-01-25 06:52:30 +00001651 if (PredDep.getKind() != SDep::Data
1652 || PredDep.getSUnit()->isBoundaryNode()) {
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001653 continue;
Andrew Trick646eeb62013-01-25 06:52:30 +00001654 }
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001655 // An already visited edge is a cross edge, assuming an acyclic DAG.
Andrew Trick48d392e2012-11-28 05:13:28 +00001656 if (Impl.isVisited(PredDep.getSUnit())) {
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001657 Impl.visitCrossEdge(PredDep, DFS.getCurr());
Andrew Trick48d392e2012-11-28 05:13:28 +00001658 continue;
1659 }
1660 Impl.visitPreorder(PredDep.getSUnit());
1661 DFS.follow(PredDep.getSUnit());
1662 }
1663 // Visit the top of the stack in postorder and backtrack.
1664 const SUnit *Child = DFS.getCurr();
1665 const SDep *PredDep = DFS.backtrack();
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001666 Impl.visitPostorderNode(Child);
1667 if (PredDep)
1668 Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
Andrew Trick48d392e2012-11-28 05:13:28 +00001669 if (DFS.isComplete())
1670 break;
Andrew Trick90f711d2012-10-15 18:02:27 +00001671 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001672 }
1673 Impl.finalize();
1674}
1675
1676/// The root of the given SubtreeID was just scheduled. For all subtrees
1677/// connected to this tree, record the depth of the connection so that the
1678/// nearest connected subtrees can be prioritized.
1679void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
1680 for (SmallVectorImpl<Connection>::const_iterator
1681 I = SubtreeConnections[SubtreeID].begin(),
1682 E = SubtreeConnections[SubtreeID].end(); I != E; ++I) {
1683 SubtreeConnectLevels[I->TreeID] =
1684 std::max(SubtreeConnectLevels[I->TreeID], I->Level);
1685 DEBUG(dbgs() << " Tree: " << I->TreeID
1686 << " @" << SubtreeConnectLevels[I->TreeID] << '\n');
Andrew Trick90f711d2012-10-15 18:02:27 +00001687 }
1688}
1689
Alp Tokerd8d510a2014-07-01 21:19:13 +00001690LLVM_DUMP_METHOD
Andrew Trick90f711d2012-10-15 18:02:27 +00001691void ILPValue::print(raw_ostream &OS) const {
Andrew Trick48d392e2012-11-28 05:13:28 +00001692 OS << InstrCount << " / " << Length << " = ";
1693 if (!Length)
Andrew Trick90f711d2012-10-15 18:02:27 +00001694 OS << "BADILP";
Andrew Trick48d392e2012-11-28 05:13:28 +00001695 else
1696 OS << format("%g", ((double)InstrCount / Length));
Andrew Trick90f711d2012-10-15 18:02:27 +00001697}
1698
Alp Tokerd8d510a2014-07-01 21:19:13 +00001699LLVM_DUMP_METHOD
Andrew Trick90f711d2012-10-15 18:02:27 +00001700void ILPValue::dump() const {
1701 dbgs() << *this << '\n';
1702}
1703
1704namespace llvm {
1705
Alp Tokerd8d510a2014-07-01 21:19:13 +00001706LLVM_DUMP_METHOD
Andrew Trick90f711d2012-10-15 18:02:27 +00001707raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1708 Val.print(OS);
1709 return OS;
1710}
1711
1712} // namespace llvm