blob: ba9bf90629431e8070d6d6d18a4b8b01c3b33454 [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() << "{ ";
Matthias Braun298e0072016-09-30 23:08:07 +000080 for (const SUnit *su : L) {
Jonas Paulssonac29f012016-02-03 17:52:29 +000081 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
Matthias Braun298e0072016-09-30 23:08:07 +0000145 for (Value *V : Objs) {
David Blaikie70573dc2014-11-19 07:49:26 +0000146 if (!Visited.insert(V).second)
Hal Finkel66859ae2012-12-10 18:49:16 +0000147 continue;
148 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
149 const Value *O =
150 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
151 if (O->getType()->isPointerTy()) {
152 Working.push_back(O);
153 continue;
154 }
155 }
156 Objects.push_back(const_cast<Value *>(V));
157 }
158 } while (!Working.empty());
Dan Gohman1ee0d412009-01-30 02:49:14 +0000159}
160
Hal Finkel66859ae2012-12-10 18:49:16 +0000161/// getUnderlyingObjectsForInstr - If this machine instr has memory reference
Dan Gohman1ee0d412009-01-30 02:49:14 +0000162/// information and it can be tracked to a normal reference to a known
Hal Finkel66859ae2012-12-10 18:49:16 +0000163/// object, return the Value for that object.
164static void getUnderlyingObjectsForInstr(const MachineInstr *MI,
Matthias Braun941a7052016-07-28 18:40:00 +0000165 const MachineFrameInfo &MFI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000166 UnderlyingObjectsVector &Objects,
167 const DataLayout &DL) {
Geoff Berry63817132016-04-14 21:31:07 +0000168 auto allMMOsOkay = [&]() {
169 for (const MachineMemOperand *MMO : MI->memoperands()) {
170 if (MMO->isVolatile())
171 return false;
Hal Finkel66859ae2012-12-10 18:49:16 +0000172
Geoff Berry63817132016-04-14 21:31:07 +0000173 if (const PseudoSourceValue *PSV = MMO->getPseudoValue()) {
174 // Function that contain tail calls don't have unique PseudoSourceValue
175 // objects. Two PseudoSourceValues might refer to the same or
176 // overlapping locations. The client code calling this function assumes
177 // this is not the case. So return a conservative answer of no known
178 // object.
Matthias Braun941a7052016-07-28 18:40:00 +0000179 if (MFI.hasTailCall())
Geoff Berry63817132016-04-14 21:31:07 +0000180 return false;
Geoff Berryc0739d82016-04-12 15:50:19 +0000181
Geoff Berry63817132016-04-14 21:31:07 +0000182 // For now, ignore PseudoSourceValues which may alias LLVM IR values
183 // because the code that uses this function has no way to cope with
184 // such aliases.
Matthias Braun941a7052016-07-28 18:40:00 +0000185 if (PSV->isAliased(&MFI))
Geoff Berry63817132016-04-14 21:31:07 +0000186 return false;
Geoff Berryc0739d82016-04-12 15:50:19 +0000187
Matthias Braun941a7052016-07-28 18:40:00 +0000188 bool MayAlias = PSV->mayAlias(&MFI);
Geoff Berry63817132016-04-14 21:31:07 +0000189 Objects.push_back(UnderlyingObjectsVector::value_type(PSV, MayAlias));
190 } else if (const Value *V = MMO->getValue()) {
191 SmallVector<Value *, 4> Objs;
192 getUnderlyingObjects(V, Objs, DL);
Geoff Berryc0739d82016-04-12 15:50:19 +0000193
Geoff Berry63817132016-04-14 21:31:07 +0000194 for (Value *V : Objs) {
195 if (!isIdentifiedObject(V))
196 return false;
197
198 Objects.push_back(UnderlyingObjectsVector::value_type(V, true));
Geoff Berryc0739d82016-04-12 15:50:19 +0000199 }
Geoff Berry63817132016-04-14 21:31:07 +0000200 } else
201 return false;
Geoff Berryc0739d82016-04-12 15:50:19 +0000202 }
Geoff Berry63817132016-04-14 21:31:07 +0000203 return true;
204 };
205
206 if (!allMMOsOkay())
207 Objects.clear();
Dan Gohman1ee0d412009-01-30 02:49:14 +0000208}
209
Andrew Trick7405c6d2012-04-20 20:05:21 +0000210void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
211 BB = bb;
Dan Gohmanb9543432009-02-10 23:27:53 +0000212}
213
Andrew Trick52226d42012-03-07 23:00:49 +0000214void ScheduleDAGInstrs::finishBlock() {
Andrew Trick51ee9362012-04-20 20:24:33 +0000215 // Subclasses should no longer refer to the old block.
Craig Topperc0196b12014-04-14 00:51:57 +0000216 BB = nullptr;
Andrew Trick60cf03e2012-03-07 05:21:52 +0000217}
218
Andrew Trick60cf03e2012-03-07 05:21:52 +0000219/// Initialize the DAG and common scheduler state for the current scheduling
220/// region. This does not actually create the DAG, only clears it. The
221/// scheduling driver may call BuildSchedGraph multiple times per scheduling
222/// region.
223void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
224 MachineBasicBlock::iterator begin,
225 MachineBasicBlock::iterator end,
Andrew Tricka53e1012013-08-23 17:48:33 +0000226 unsigned regioninstrs) {
Andrew Trick7405c6d2012-04-20 20:05:21 +0000227 assert(bb == BB && "startBlock should set BB");
Andrew Trick8c207e42012-03-09 04:29:02 +0000228 RegionBegin = begin;
229 RegionEnd = end;
Andrew Tricka53e1012013-08-23 17:48:33 +0000230 NumRegionInstrs = regioninstrs;
Andrew Trick60cf03e2012-03-07 05:21:52 +0000231}
232
233/// Close the current scheduling region. Don't clear any state in case the
234/// driver wants to refer to the previous scheduling region.
235void ScheduleDAGInstrs::exitRegion() {
236 // Nothing to do.
237}
238
Andrew Trick52226d42012-03-07 23:00:49 +0000239/// addSchedBarrierDeps - Add dependencies from instructions in the current
Evan Cheng15459b62010-10-23 02:10:46 +0000240/// list of instructions being scheduled to scheduling barrier by adding
241/// the exit SU to the register defs and use list. This is because we want to
242/// make sure instructions which define registers that are either used by
243/// the terminator or are live-out are properly scheduled. This is
244/// especially important when the definition latency of the return value(s)
245/// are too high to be hidden by the branch or when the liveout registers
246/// used by instructions in the fallthrough block.
Andrew Trick52226d42012-03-07 23:00:49 +0000247void ScheduleDAGInstrs::addSchedBarrierDeps() {
Craig Topperc0196b12014-04-14 00:51:57 +0000248 MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : nullptr;
Evan Cheng15459b62010-10-23 02:10:46 +0000249 ExitSU.setInstr(ExitMI);
250 bool AllDepKnown = ExitMI &&
Evan Cheng7f8e5632011-12-07 07:15:52 +0000251 (ExitMI->isCall() || ExitMI->isBarrier());
Evan Cheng15459b62010-10-23 02:10:46 +0000252 if (ExitMI && AllDepKnown) {
253 // If it's a call or a barrier, add dependencies on the defs and uses of
254 // instruction.
Matthias Braun298e0072016-09-30 23:08:07 +0000255 for (const MachineOperand &MO : ExitMI->operands()) {
Evan Cheng15459b62010-10-23 02:10:46 +0000256 if (!MO.isReg() || MO.isDef()) continue;
257 unsigned Reg = MO.getReg();
258 if (Reg == 0) continue;
259
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000260 if (TRI->isPhysicalRegister(Reg))
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000261 Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
Matthias Braun93563e72015-11-03 01:53:29 +0000262 else if (MO.readsReg()) // ignore undef operands
Matthias Braun298e0072016-09-30 23:08:07 +0000263 addVRegUseDeps(&ExitSU, ExitMI->getOperandNo(&MO));
Evan Cheng15459b62010-10-23 02:10:46 +0000264 }
265 } else {
266 // For others, e.g. fallthrough, conditional branch, assume the exit
Evan Chengcbdf7e82010-10-27 23:17:17 +0000267 // uses all the registers that are livein to the successor blocks.
Benjamin Kramer411d5a22012-03-16 17:38:19 +0000268 assert(Uses.empty() && "Uses in set before adding deps?");
Matthias Braun298e0072016-09-30 23:08:07 +0000269 for (const MachineBasicBlock *Succ : BB->successors()) {
270 for (const auto &LI : Succ->liveins()) {
Matthias Braund9da1622015-09-09 18:08:03 +0000271 if (!Uses.contains(LI.PhysReg))
272 Uses.insert(PhysRegSUOper(&ExitSU, -1, LI.PhysReg));
Evan Chengcbdf7e82010-10-27 23:17:17 +0000273 }
Matthias Braun298e0072016-09-30 23:08:07 +0000274 }
Evan Cheng15459b62010-10-23 02:10:46 +0000275 }
276}
277
Andrew Trickd675a4c2012-02-23 01:52:38 +0000278/// MO is an operand of SU's instruction that defines a physical register. Add
279/// data dependencies from SU to any uses of the physical register.
Andrew Trickae535612012-08-23 00:39:43 +0000280void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
281 const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000282 assert(MO.isDef() && "expect physreg def");
283
284 // Ask the target if address-backscheduling is desirable, and if so how much.
Eric Christopher2c635492015-01-27 07:54:39 +0000285 const TargetSubtargetInfo &ST = MF.getSubtarget();
Andrew Trickd675a4c2012-02-23 01:52:38 +0000286
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000287 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
288 Alias.isValid(); ++Alias) {
Andrew Trick9dbbd3e2012-02-24 07:04:55 +0000289 if (!Uses.contains(*Alias))
Andrew Trickd675a4c2012-02-23 01:52:38 +0000290 continue;
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000291 for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
292 SUnit *UseSU = I->SU;
Andrew Trickd675a4c2012-02-23 01:52:38 +0000293 if (UseSU == SU)
294 continue;
Andrew Trick07dced62012-10-08 18:54:00 +0000295
Andrew Trick07dced62012-10-08 18:54:00 +0000296 // Adjust the dependence latency using operand def/use information,
297 // then allow the target to perform its own adjustments.
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000298 int UseOp = I->OpIdx;
Craig Topperc0196b12014-04-14 00:51:57 +0000299 MachineInstr *RegUse = nullptr;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000300 SDep Dep;
301 if (UseOp < 0)
302 Dep = SDep(SU, SDep::Artificial);
303 else {
Andrew Tricke833e1c2013-04-13 06:07:40 +0000304 // Set the hasPhysRegDefs only for physreg defs that have a use within
305 // the scheduling region.
306 SU->hasPhysRegDefs = true;
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000307 Dep = SDep(SU, SDep::Data, *Alias);
308 RegUse = UseSU->getInstr();
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000309 }
310 Dep.setLatency(
Andrew Trickde2109e2013-06-15 04:49:57 +0000311 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, RegUse,
312 UseOp));
Andrew Trick45446062012-06-05 21:11:27 +0000313
Andrew Trickf1ff84c2012-11-12 19:28:57 +0000314 ST.adjustSchedDependency(SU, UseSU, Dep);
315 UseSU->addPred(Dep);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000316 }
317 }
318}
319
Andrew Trickdbee9d82012-01-14 02:17:15 +0000320/// addPhysRegDeps - Add register dependencies (data, anti, and output) from
321/// this SUnit to following instructions in the same scheduling region that
322/// depend the physical register referenced at OperIdx.
323void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
Andrew Trick6b104f82013-12-28 21:56:55 +0000324 MachineInstr *MI = SU->getInstr();
325 MachineOperand &MO = MI->getOperand(OperIdx);
Andrew Trickdbee9d82012-01-14 02:17:15 +0000326
327 // Optionally add output and anti dependencies. For anti
328 // dependencies we use a latency of 0 because for a multi-issue
329 // target we want to allow the defining instruction to issue
330 // in the same cycle as the using instruction.
331 // TODO: Using a latency of 1 here for output dependencies assumes
332 // there's no cost for reusing registers.
333 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000334 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
335 Alias.isValid(); ++Alias) {
Andrew Trick9dbbd3e2012-02-24 07:04:55 +0000336 if (!Defs.contains(*Alias))
Andrew Trickd675a4c2012-02-23 01:52:38 +0000337 continue;
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000338 for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
339 SUnit *DefSU = I->SU;
Andrew Trickdbee9d82012-01-14 02:17:15 +0000340 if (DefSU == &ExitSU)
341 continue;
342 if (DefSU != SU &&
343 (Kind != SDep::Output || !MO.isDead() ||
Hal Finkel66d77912014-12-05 02:07:35 +0000344 !DefSU->getInstr()->registerDefIsDead(*Alias))) {
Andrew Trickdbee9d82012-01-14 02:17:15 +0000345 if (Kind == SDep::Anti)
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000346 DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
Andrew Trickdbee9d82012-01-14 02:17:15 +0000347 else {
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000348 SDep Dep(SU, Kind, /*Reg=*/*Alias);
Andrew Trickde2109e2013-06-15 04:49:57 +0000349 Dep.setLatency(
350 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000351 DefSU->addPred(Dep);
Andrew Trickdbee9d82012-01-14 02:17:15 +0000352 }
353 }
354 }
355 }
356
Andrew Trickd675a4c2012-02-23 01:52:38 +0000357 if (!MO.isDef()) {
Andrew Tricke833e1c2013-04-13 06:07:40 +0000358 SU->hasPhysRegUses = true;
Andrew Trickd675a4c2012-02-23 01:52:38 +0000359 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
360 // retrieve the existing SUnits list for this register's uses.
361 // Push this SUnit on the use list.
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000362 Uses.insert(PhysRegSUOper(SU, OperIdx, MO.getReg()));
Andrew Trick6b104f82013-12-28 21:56:55 +0000363 if (RemoveKillFlags)
364 MO.setIsKill(false);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000365 }
366 else {
Andrew Trickae535612012-08-23 00:39:43 +0000367 addPhysRegDataDeps(SU, OperIdx);
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000368 unsigned Reg = MO.getReg();
Andrew Trickdbee9d82012-01-14 02:17:15 +0000369
Andrew Trickd675a4c2012-02-23 01:52:38 +0000370 // clear this register's use list
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000371 if (Uses.contains(Reg))
372 Uses.eraseAll(Reg);
Andrew Trickd675a4c2012-02-23 01:52:38 +0000373
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000374 if (!MO.isDead()) {
375 Defs.eraseAll(Reg);
376 } else if (SU->isCall) {
377 // Calls will not be reordered because of chain dependencies (see
378 // below). Since call operands are dead, calls may continue to be added
379 // to the DefList making dependence checking quadratic in the size of
380 // the block. Instead, we leave only one call at the back of the
381 // DefList.
382 Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
383 Reg2SUnitsMap::iterator B = P.first;
384 Reg2SUnitsMap::iterator I = P.second;
385 for (bool isBegin = I == B; !isBegin; /* empty */) {
386 isBegin = (--I) == B;
387 if (!I->SU->isCall)
388 break;
389 I = Defs.erase(I);
390 }
Andrew Trickdbee9d82012-01-14 02:17:15 +0000391 }
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000392
Andrew Trickd675a4c2012-02-23 01:52:38 +0000393 // Defs are pushed in the order they are visited and never reordered.
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000394 Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
Andrew Trickdbee9d82012-01-14 02:17:15 +0000395 }
396}
397
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000398LaneBitmask ScheduleDAGInstrs::getLaneMaskForMO(const MachineOperand &MO) const
399{
400 unsigned Reg = MO.getReg();
401 // No point in tracking lanemasks if we don't have interesting subregisters.
402 const TargetRegisterClass &RC = *MRI.getRegClass(Reg);
403 if (!RC.HasDisjunctSubRegs)
404 return ~0u;
405
406 unsigned SubReg = MO.getSubReg();
407 if (SubReg == 0)
408 return RC.getLaneMask();
409 return TRI->getSubRegIndexLaneMask(SubReg);
410}
411
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000412/// addVRegDefDeps - Add register output and data dependencies from this SUnit
413/// to instructions that occur later in the same scheduling region if they read
414/// from or write to the virtual register defined at OperIdx.
415///
416/// TODO: Hoist loop induction variable increments. This has to be
417/// reevaluated. Generally, IV scheduling should be done before coalescing.
418void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000419 MachineInstr *MI = SU->getInstr();
420 MachineOperand &MO = MI->getOperand(OperIdx);
421 unsigned Reg = MO.getReg();
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000422
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000423 LaneBitmask DefLaneMask;
424 LaneBitmask KillLaneMask;
425 if (TrackLaneMasks) {
426 bool IsKill = MO.getSubReg() == 0 || MO.isUndef();
427 DefLaneMask = getLaneMaskForMO(MO);
428 // If we have a <read-undef> flag, none of the lane values comes from an
429 // earlier instruction.
430 KillLaneMask = IsKill ? ~0u : DefLaneMask;
431
432 // Clear undef flag, we'll re-add it later once we know which subregister
433 // Def is first.
434 MO.setIsUndef(false);
435 } else {
436 DefLaneMask = ~0u;
437 KillLaneMask = ~0u;
438 }
439
440 if (MO.isDead()) {
441 assert(CurrentVRegUses.find(Reg) == CurrentVRegUses.end() &&
442 "Dead defs should have no uses");
443 } else {
444 // Add data dependence to all uses we found so far.
445 const TargetSubtargetInfo &ST = MF.getSubtarget();
446 for (VReg2SUnitOperIdxMultiMap::iterator I = CurrentVRegUses.find(Reg),
447 E = CurrentVRegUses.end(); I != E; /*empty*/) {
448 LaneBitmask LaneMask = I->LaneMask;
449 // Ignore uses of other lanes.
450 if ((LaneMask & KillLaneMask) == 0) {
451 ++I;
452 continue;
453 }
454
455 if ((LaneMask & DefLaneMask) != 0) {
456 SUnit *UseSU = I->SU;
457 MachineInstr *Use = UseSU->getInstr();
458 SDep Dep(SU, SDep::Data, Reg);
459 Dep.setLatency(SchedModel.computeOperandLatency(MI, OperIdx, Use,
460 I->OperandIndex));
461 ST.adjustSchedDependency(SU, UseSU, Dep);
462 UseSU->addPred(Dep);
463 }
464
465 LaneMask &= ~KillLaneMask;
466 // If we found a Def for all lanes of this use, remove it from the list.
467 if (LaneMask != 0) {
468 I->LaneMask = LaneMask;
469 ++I;
470 } else
471 I = CurrentVRegUses.erase(I);
472 }
473 }
474
475 // Shortcut: Singly defined vregs do not have output/anti dependencies.
Andrew Trick79795892012-07-30 23:48:17 +0000476 if (MRI.hasOneDef(Reg))
Andrew Trick94053432012-07-28 01:48:15 +0000477 return;
Andrew Trickdb42c6f2012-02-22 06:08:13 +0000478
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000479 // Add output dependence to the next nearest defs of this vreg.
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000480 //
481 // Unless this definition is dead, the output dependence should be
482 // transitively redundant with antidependencies from this definition's
483 // uses. We're conservative for now until we have a way to guarantee the uses
484 // are not eliminated sometime during scheduling. The output dependence edge
485 // is also useful if output latency exceeds def-use latency.
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000486 LaneBitmask LaneMask = DefLaneMask;
487 for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
488 CurrentVRegDefs.end())) {
489 // Ignore defs for other lanes.
490 if ((V2SU.LaneMask & LaneMask) == 0)
491 continue;
492 // Add an output dependence.
493 SUnit *DefSU = V2SU.SU;
494 // Ignore additional defs of the same lanes in one instruction. This can
495 // happen because lanemasks are shared for targets with too many
496 // subregisters. We also use some representration tricks/hacks where we
497 // add super-register defs/uses, to imply that although we only access parts
498 // of the reg we care about the full one.
499 if (DefSU == SU)
500 continue;
501 SDep Dep(SU, SDep::Output, Reg);
502 Dep.setLatency(
503 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
504 DefSU->addPred(Dep);
505
506 // Update current definition. This can get tricky if the def was about a
507 // bigger lanemask before. We then have to shrink it and create a new
508 // VReg2SUnit for the non-overlapping part.
509 LaneBitmask OverlapMask = V2SU.LaneMask & LaneMask;
510 LaneBitmask NonOverlapMask = V2SU.LaneMask & ~LaneMask;
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000511 V2SU.SU = SU;
512 V2SU.LaneMask = OverlapMask;
Matthias Braun4c994ee2016-05-25 01:18:00 +0000513 if (NonOverlapMask != 0)
514 CurrentVRegDefs.insert(VReg2SUnit(Reg, NonOverlapMask, DefSU));
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000515 }
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000516 // If there was no CurrentVRegDefs entry for some lanes yet, create one.
517 if (LaneMask != 0)
518 CurrentVRegDefs.insert(VReg2SUnit(Reg, LaneMask, SU));
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000519}
520
Andrew Trick46cc9a42012-02-22 06:08:11 +0000521/// addVRegUseDeps - Add a register data dependency if the instruction that
522/// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
523/// register antidependency from this SUnit to instructions that occur later in
524/// the same scheduling region if they write the virtual register.
525///
526/// TODO: Handle ExitSU "uses" properly.
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000527void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000528 const MachineInstr *MI = SU->getInstr();
529 const MachineOperand &MO = MI->getOperand(OperIdx);
530 unsigned Reg = MO.getReg();
Andrew Trick46cc9a42012-02-22 06:08:11 +0000531
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000532 // Remember the use. Data dependencies will be added when we find the def.
533 LaneBitmask LaneMask = TrackLaneMasks ? getLaneMaskForMO(MO) : ~0u;
534 CurrentVRegUses.insert(VReg2SUnitOperIdx(Reg, LaneMask, OperIdx, SU));
535
536 // Add antidependences to the following defs of the vreg.
537 for (VReg2SUnit &V2SU : make_range(CurrentVRegDefs.find(Reg),
538 CurrentVRegDefs.end())) {
539 // Ignore defs for unrelated lanes.
540 LaneBitmask PrevDefLaneMask = V2SU.LaneMask;
541 if ((PrevDefLaneMask & LaneMask) == 0)
542 continue;
543 if (V2SU.SU == SU)
544 continue;
545
546 V2SU.SU->addPred(SDep(SU, SDep::Anti, Reg));
Andrew Trick2bc74c22013-08-30 04:36:57 +0000547 }
Andrew Trick46cc9a42012-02-22 06:08:11 +0000548}
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000549
Andrew Trickda01ba32012-05-15 18:59:41 +0000550/// Return true if MI is an instruction we are unable to reason about
551/// (like a call or something with unmodeled side effects).
552static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
Rafael Espindola84921b92015-10-24 23:11:13 +0000553 return MI->isCall() || MI->hasUnmodeledSideEffects() ||
Justin Lebard98cf002016-09-10 01:03:20 +0000554 (MI->hasOrderedMemoryRef() && !MI->isDereferenceableInvariantLoad(AA));
Andrew Trickda01ba32012-05-15 18:59:41 +0000555}
556
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000557/// This returns true if the two MIs need a chain edge between them.
Jonas Paulssonac29f012016-02-03 17:52:29 +0000558/// This is called on normal stores and loads.
Andrew Trickda01ba32012-05-15 18:59:41 +0000559static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000560 const DataLayout &DL, MachineInstr *MIa,
Andrew Trickda01ba32012-05-15 18:59:41 +0000561 MachineInstr *MIb) {
Chad Rosier3528c1e2014-09-08 14:43:48 +0000562 const MachineFunction *MF = MIa->getParent()->getParent();
563 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
564
Jonas Paulssonac29f012016-02-03 17:52:29 +0000565 assert ((MIa->mayStore() || MIb->mayStore()) &&
566 "Dependency checked between two loads");
567
Jonas Paulsson8c738632016-01-29 17:22:43 +0000568 // Let the target decide if memory accesses cannot possibly overlap.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000569 if (TII->areMemAccessesTriviallyDisjoint(*MIa, *MIb, AA))
Jonas Paulssonac29f012016-02-03 17:52:29 +0000570 return false;
Andrew Trickda01ba32012-05-15 18:59:41 +0000571
Andrew Trickda01ba32012-05-15 18:59:41 +0000572 // To this point analysis is generic. From here on we do need AA.
573 if (!AA)
574 return true;
575
Jonas Paulsson98963fe2016-02-15 16:43:15 +0000576 // FIXME: Need to handle multiple memory operands to support all targets.
577 if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
578 return true;
579
Andrew Trickda01ba32012-05-15 18:59:41 +0000580 MachineMemOperand *MMOa = *MIa->memoperands_begin();
581 MachineMemOperand *MMOb = *MIb->memoperands_begin();
582
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000583 if (!MMOa->getValue() || !MMOb->getValue())
584 return true;
585
Andrew Trickda01ba32012-05-15 18:59:41 +0000586 // The following interface to AA is fashioned after DAGCombiner::isAlias
587 // and operates with MachineMemOperand offset with some important
588 // assumptions:
589 // - LLVM fundamentally assumes flat address spaces.
590 // - MachineOperand offset can *only* result from legalization and
591 // cannot affect queries other than the trivial case of overlap
592 // checking.
593 // - These offsets never wrap and never step outside
594 // of allocated objects.
595 // - There should never be any negative offsets here.
596 //
597 // FIXME: Modify API to hide this math from "user"
598 // FIXME: Even before we go to AA we can reason locally about some
599 // memory objects. It can save compile time, and possibly catch some
600 // corner cases not currently covered.
601
602 assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
603 assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
604
605 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
606 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
607 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
608
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000609 AliasResult AAResult =
Chandler Carruthac80dc72015-06-17 07:18:54 +0000610 AA->alias(MemoryLocation(MMOa->getValue(), Overlapa,
611 UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
612 MemoryLocation(MMOb->getValue(), Overlapb,
613 UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
Andrew Trickda01ba32012-05-15 18:59:41 +0000614
Chandler Carruthc3f49eb2015-06-22 02:16:51 +0000615 return (AAResult != NoAlias);
Andrew Trickda01ba32012-05-15 18:59:41 +0000616}
617
Jonas Paulssonac29f012016-02-03 17:52:29 +0000618/// Check whether two objects need a chain edge and add it if needed.
619void ScheduleDAGInstrs::addChainDependency (SUnit *SUa, SUnit *SUb,
620 unsigned Latency) {
Matthias Braun941a7052016-07-28 18:40:00 +0000621 if (MIsNeedChainEdge(AAForDep, &MFI, MF.getDataLayout(), SUa->getInstr(),
NAKAMURA Takumid6ddc7e2016-07-25 00:59:51 +0000622 SUb->getInstr())) {
Jonas Paulssonac29f012016-02-03 17:52:29 +0000623 SDep Dep(SUa, SDep::MayAliasMem);
624 Dep.setLatency(Latency);
Andrew Trickbaeaabb2012-11-06 03:13:46 +0000625 SUb->addPred(Dep);
626 }
Andrew Trickda01ba32012-05-15 18:59:41 +0000627}
628
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000629/// Create an SUnit for each real instruction, numbered in top-down topological
Andrew Trick46cc9a42012-02-22 06:08:11 +0000630/// order. The instruction order A < B, implies that no edge exists from B to A.
631///
632/// Map each real instruction to its SUnit.
633///
Andrew Trick8823dec2012-03-14 04:00:41 +0000634/// After initSUnits, the SUnits vector cannot be resized and the scheduler may
635/// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
636/// instead of pointers.
637///
638/// MachineScheduler relies on initSUnits numbering the nodes by their order in
639/// the original instruction list.
Andrew Trick46cc9a42012-02-22 06:08:11 +0000640void ScheduleDAGInstrs::initSUnits() {
641 // We'll be allocating one SUnit for each real instruction in the region,
642 // which is contained within a basic block.
Andrew Tricka53e1012013-08-23 17:48:33 +0000643 SUnits.reserve(NumRegionInstrs);
Andrew Trick46cc9a42012-02-22 06:08:11 +0000644
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000645 for (MachineInstr &MI : llvm::make_range(RegionBegin, RegionEnd)) {
646 if (MI.isDebugValue())
Andrew Trick46cc9a42012-02-22 06:08:11 +0000647 continue;
648
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000649 SUnit *SU = newSUnit(&MI);
650 MISUnitMap[&MI] = SU;
Andrew Trick46cc9a42012-02-22 06:08:11 +0000651
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000652 SU->isCall = MI.isCall();
653 SU->isCommutable = MI.isCommutable();
Andrew Trick46cc9a42012-02-22 06:08:11 +0000654
655 // Assign the Latency field of SU using target-provided information.
Andrew Trickdd79f0f2012-10-10 05:43:09 +0000656 SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
Andrew Trick880e5732013-12-05 17:55:58 +0000657
Andrew Trick1766f932014-04-18 17:35:08 +0000658 // If this SUnit uses a reserved or unbuffered resource, mark it as such.
659 //
Alp Tokerbeaca192014-05-15 01:52:21 +0000660 // Reserved resources block an instruction from issuing and stall the
Andrew Trick1766f932014-04-18 17:35:08 +0000661 // entire pipeline. These are identified by BufferSize=0.
662 //
Alp Tokerbeaca192014-05-15 01:52:21 +0000663 // Unbuffered resources prevent execution of subsequent instructions that
Andrew Trick1766f932014-04-18 17:35:08 +0000664 // require the same resources. This is used for in-order execution pipelines
665 // within an out-of-order core. These are identified by BufferSize=1.
Andrew Trick880e5732013-12-05 17:55:58 +0000666 if (SchedModel.hasInstrSchedModel()) {
667 const MCSchedClassDesc *SC = getSchedClass(SU);
Matthias Braun298e0072016-09-30 23:08:07 +0000668 for (const MCWriteProcResEntry &PRE :
669 make_range(SchedModel.getWriteProcResBegin(SC),
670 SchedModel.getWriteProcResEnd(SC))) {
671 switch (SchedModel.getProcResource(PRE.ProcResourceIdx)->BufferSize) {
Andrew Trick5a22df42013-12-05 17:56:02 +0000672 case 0:
673 SU->hasReservedResource = true;
674 break;
675 case 1:
Andrew Trick880e5732013-12-05 17:55:58 +0000676 SU->isUnbuffered = true;
677 break;
Andrew Trick5a22df42013-12-05 17:56:02 +0000678 default:
679 break;
Andrew Trick880e5732013-12-05 17:55:58 +0000680 }
681 }
682 }
Andrew Trick46cc9a42012-02-22 06:08:11 +0000683 }
Andrew Trickdbee9d82012-01-14 02:17:15 +0000684}
685
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000686void ScheduleDAGInstrs::collectVRegUses(SUnit *SU) {
687 const MachineInstr *MI = SU->getInstr();
688 for (const MachineOperand &MO : MI->operands()) {
689 if (!MO.isReg())
690 continue;
691 if (!MO.readsReg())
692 continue;
693 if (TrackLaneMasks && !MO.isUse())
694 continue;
695
696 unsigned Reg = MO.getReg();
697 if (!TargetRegisterInfo::isVirtualRegister(Reg))
698 continue;
699
Matthias Braund4f64092016-01-20 00:23:32 +0000700 // Ignore re-defs.
701 if (TrackLaneMasks) {
702 bool FoundDef = false;
703 for (const MachineOperand &MO2 : MI->operands()) {
704 if (MO2.isReg() && MO2.isDef() && MO2.getReg() == Reg && !MO2.isDead()) {
705 FoundDef = true;
706 break;
707 }
708 }
709 if (FoundDef)
710 continue;
711 }
712
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000713 // Record this local VReg use.
714 VReg2SUnitMultiMap::iterator UI = VRegUses.find(Reg);
715 for (; UI != VRegUses.end(); ++UI) {
716 if (UI->SU == SU)
717 break;
718 }
719 if (UI == VRegUses.end())
720 VRegUses.insert(VReg2SUnit(Reg, 0, SU));
721 }
722}
723
Jonas Paulssonac29f012016-02-03 17:52:29 +0000724class ScheduleDAGInstrs::Value2SUsMap : public MapVector<ValueType, SUList> {
725
726 /// Current total number of SUs in map.
727 unsigned NumNodes;
728
729 /// 1 for loads, 0 for stores. (see comment in SUList)
730 unsigned TrueMemOrderLatency;
731public:
732
733 Value2SUsMap(unsigned lat = 0) : NumNodes(0), TrueMemOrderLatency(lat) {}
734
735 /// To keep NumNodes up to date, insert() is used instead of
736 /// this operator w/ push_back().
737 ValueType &operator[](const SUList &Key) {
738 llvm_unreachable("Don't use. Use insert() instead."); };
739
740 /// Add SU to the SUList of V. If Map grows huge, reduce its size
741 /// by calling reduce().
742 void inline insert(SUnit *SU, ValueType V) {
743 MapVector::operator[](V).push_back(SU);
744 NumNodes++;
745 }
746
747 /// Clears the list of SUs mapped to V.
748 void inline clearList(ValueType V) {
749 iterator Itr = find(V);
750 if (Itr != end()) {
751 assert (NumNodes >= Itr->second.size());
752 NumNodes -= Itr->second.size();
753
754 Itr->second.clear();
755 }
756 }
757
758 /// Clears map from all contents.
759 void clear() {
760 MapVector<ValueType, SUList>::clear();
761 NumNodes = 0;
762 }
763
764 unsigned inline size() const { return NumNodes; }
765
766 /// Count the number of SUs in this map after a reduction.
767 void reComputeSize(void) {
768 NumNodes = 0;
769 for (auto &I : *this)
770 NumNodes += I.second.size();
771 }
772
773 unsigned inline getTrueMemOrderLatency() const {
774 return TrueMemOrderLatency;
775 }
776
777 void dump();
778};
779
780void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
781 Value2SUsMap &Val2SUsMap) {
782 for (auto &I : Val2SUsMap)
783 addChainDependencies(SU, I.second,
784 Val2SUsMap.getTrueMemOrderLatency());
785}
786
787void ScheduleDAGInstrs::addChainDependencies(SUnit *SU,
788 Value2SUsMap &Val2SUsMap,
789 ValueType V) {
790 Value2SUsMap::iterator Itr = Val2SUsMap.find(V);
791 if (Itr != Val2SUsMap.end())
792 addChainDependencies(SU, Itr->second,
793 Val2SUsMap.getTrueMemOrderLatency());
794}
795
796void ScheduleDAGInstrs::addBarrierChain(Value2SUsMap &map) {
797 assert (BarrierChain != nullptr);
798
799 for (auto &I : map) {
800 SUList &sus = I.second;
801 for (auto *SU : sus)
802 SU->addPredBarrier(BarrierChain);
803 }
804 map.clear();
805}
806
807void ScheduleDAGInstrs::insertBarrierChain(Value2SUsMap &map) {
808 assert (BarrierChain != nullptr);
809
810 // Go through all lists of SUs.
811 for (Value2SUsMap::iterator I = map.begin(), EE = map.end(); I != EE;) {
812 Value2SUsMap::iterator CurrItr = I++;
813 SUList &sus = CurrItr->second;
814 SUList::iterator SUItr = sus.begin(), SUEE = sus.end();
815 for (; SUItr != SUEE; ++SUItr) {
816 // Stop on BarrierChain or any instruction above it.
817 if ((*SUItr)->NodeNum <= BarrierChain->NodeNum)
818 break;
819
820 (*SUItr)->addPredBarrier(BarrierChain);
821 }
822
823 // Remove also the BarrierChain from list if present.
NAKAMURA Takumibc46f622016-05-02 17:29:55 +0000824 if (SUItr != SUEE && *SUItr == BarrierChain)
Jonas Paulssonac29f012016-02-03 17:52:29 +0000825 SUItr++;
826
827 // Remove all SUs that are now successors of BarrierChain.
828 if (SUItr != sus.begin())
829 sus.erase(sus.begin(), SUItr);
830 }
831
832 // Remove all entries with empty su lists.
833 map.remove_if([&](std::pair<ValueType, SUList> &mapEntry) {
834 return (mapEntry.second.empty()); });
835
836 // Recompute the size of the map (NumNodes).
837 map.reComputeSize();
838}
839
Alp Tokerf907b892013-12-05 05:44:44 +0000840/// If RegPressure is non-null, compute register pressure as a side effect. The
Andrew Trick88639922012-04-24 17:56:43 +0000841/// DAG builder is an efficient place to do it because it already visits
842/// operands.
843void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
Andrew Trick1a831342013-08-30 03:49:48 +0000844 RegPressureTracker *RPTracker,
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000845 PressureDiffs *PDiffs,
Matthias Braund4f64092016-01-20 00:23:32 +0000846 LiveIntervals *LIS,
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000847 bool TrackLaneMasks) {
Eric Christopher2c635492015-01-27 07:54:39 +0000848 const TargetSubtargetInfo &ST = MF.getSubtarget();
Hal Finkelb350ffd2013-08-29 03:25:05 +0000849 bool UseAA = EnableAASchedMI.getNumOccurrences() > 0 ? EnableAASchedMI
850 : ST.useAA();
Jonas Paulssonac29f012016-02-03 17:52:29 +0000851 AAForDep = UseAA ? AA : nullptr;
852
853 BarrierChain = nullptr;
Hal Finkelb350ffd2013-08-29 03:25:05 +0000854
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000855 this->TrackLaneMasks = TrackLaneMasks;
Andrew Trick310190e2013-09-04 21:00:02 +0000856 MISUnitMap.clear();
857 ScheduleDAG::clearDAG();
858
Andrew Trick46cc9a42012-02-22 06:08:11 +0000859 // Create an SUnit for each real instruction.
860 initSUnits();
Dan Gohman60cb69e2008-11-19 23:18:57 +0000861
Andrew Trick1a831342013-08-30 03:49:48 +0000862 if (PDiffs)
863 PDiffs->init(SUnits.size());
864
Jonas Paulssonac29f012016-02-03 17:52:29 +0000865 // We build scheduling units by walking a block's instruction list
866 // from bottom to top.
Dan Gohman3aab10b2008-12-04 01:35:46 +0000867
Jonas Paulssonac29f012016-02-03 17:52:29 +0000868 // Each MIs' memory operand(s) is analyzed to a list of underlying
Jonas Paulsson22936852016-02-04 13:08:48 +0000869 // objects. The SU is then inserted in the SUList(s) mapped from the
870 // Value(s). Each Value thus gets mapped to lists of SUs depending
871 // on it, stores and loads kept separately. Two SUs are trivially
872 // non-aliasing if they both depend on only identified Values and do
873 // not share any common Value.
Jonas Paulssonac29f012016-02-03 17:52:29 +0000874 Value2SUsMap Stores, Loads(1 /*TrueMemOrderLatency*/);
Dan Gohman3aab10b2008-12-04 01:35:46 +0000875
Jonas Paulssonac29f012016-02-03 17:52:29 +0000876 // Certain memory accesses are known to not alias any SU in Stores
877 // or Loads, and have therefore their own 'NonAlias'
878 // domain. E.g. spill / reload instructions never alias LLVM I/R
Jonas Paulsson22936852016-02-04 13:08:48 +0000879 // Values. It would be nice to assume that this type of memory
880 // accesses always have a proper memory operand modelling, and are
881 // therefore never unanalyzable, but this is conservatively not
882 // done.
Jonas Paulssonac29f012016-02-03 17:52:29 +0000883 Value2SUsMap NonAliasStores, NonAliasLoads(1 /*TrueMemOrderLatency*/);
884
Dale Johannesen49de0602010-03-10 22:13:47 +0000885 // Remove any stale debug info; sometimes BuildSchedGraph is called again
886 // without emitting the info from the previous call.
Devang Patele5feef02011-06-02 20:07:12 +0000887 DbgValues.clear();
Craig Topperc0196b12014-04-14 00:51:57 +0000888 FirstDbgValue = nullptr;
Dale Johannesen49de0602010-03-10 22:13:47 +0000889
Andrew Trickd675a4c2012-02-23 01:52:38 +0000890 assert(Defs.empty() && Uses.empty() &&
891 "Only BuildGraph should update Defs/Uses");
Michael Ilseman3e3194f2013-01-21 18:18:53 +0000892 Defs.setUniverse(TRI->getNumRegs());
893 Uses.setUniverse(TRI->getNumRegs());
Andrew Trick2e116a42011-05-06 21:52:52 +0000894
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000895 assert(CurrentVRegDefs.empty() && "nobody else should use CurrentVRegDefs");
896 assert(CurrentVRegUses.empty() && "nobody else should use CurrentVRegUses");
897 unsigned NumVirtRegs = MRI.getNumVirtRegs();
898 CurrentVRegDefs.setUniverse(NumVirtRegs);
899 CurrentVRegUses.setUniverse(NumVirtRegs);
900
Andrew Trick8dd26f02013-08-23 17:48:39 +0000901 VRegUses.clear();
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000902 VRegUses.setUniverse(NumVirtRegs);
Andrew Trick59ac4fb2012-01-14 02:17:18 +0000903
Andrew Trickd675a4c2012-02-23 01:52:38 +0000904 // Model data dependencies between instructions being scheduled and the
905 // ExitSU.
Andrew Trick52226d42012-03-07 23:00:49 +0000906 addSchedBarrierDeps();
Andrew Trickd675a4c2012-02-23 01:52:38 +0000907
Dan Gohmanb9543432009-02-10 23:27:53 +0000908 // Walk the list of instructions, from bottom moving up.
Craig Topperc0196b12014-04-14 00:51:57 +0000909 MachineInstr *DbgMI = nullptr;
Andrew Trick8c207e42012-03-09 04:29:02 +0000910 for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000911 MII != MIE; --MII) {
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000912 MachineInstr &MI = *std::prev(MII);
913 if (DbgMI) {
914 DbgValues.push_back(std::make_pair(DbgMI, &MI));
Craig Topperc0196b12014-04-14 00:51:57 +0000915 DbgMI = nullptr;
Devang Patele5feef02011-06-02 20:07:12 +0000916 }
917
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000918 if (MI.isDebugValue()) {
919 DbgMI = &MI;
Dale Johannesen49de0602010-03-10 22:13:47 +0000920 continue;
921 }
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000922 SUnit *SU = MISUnitMap[&MI];
Andrew Trick1a831342013-08-30 03:49:48 +0000923 assert(SU && "No SUnit mapped to this MI");
924
Andrew Trick88639922012-04-24 17:56:43 +0000925 if (RPTracker) {
Matthias Braun97d0ffb2015-12-04 01:51:19 +0000926 collectVRegUses(SU);
Matthias Braunb505c762016-01-12 22:57:35 +0000927
928 RegisterOperands RegOpers;
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000929 RegOpers.collect(MI, *TRI, MRI, TrackLaneMasks, false);
Matthias Braund4f64092016-01-20 00:23:32 +0000930 if (TrackLaneMasks) {
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000931 SlotIndex SlotIdx = LIS->getInstructionIndex(MI);
Matthias Braund4f64092016-01-20 00:23:32 +0000932 RegOpers.adjustLaneLiveness(*LIS, MRI, SlotIdx);
933 }
Matthias Braunb505c762016-01-12 22:57:35 +0000934 if (PDiffs != nullptr)
935 PDiffs->addInstruction(SU->NodeNum, RegOpers, MRI);
936
937 RPTracker->recedeSkipDebugValues();
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000938 assert(&*RPTracker->getPos() == &MI && "RPTracker in sync");
Matthias Braunb505c762016-01-12 22:57:35 +0000939 RPTracker->recede(RegOpers);
Andrew Trick88639922012-04-24 17:56:43 +0000940 }
Devang Patele5feef02011-06-02 20:07:12 +0000941
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000942 assert(
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000943 (CanHandleTerminators || (!MI.isTerminator() && !MI.isPosition())) &&
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000944 "Cannot schedule terminators or labels!");
Dan Gohman60cb69e2008-11-19 23:18:57 +0000945
Dan Gohman3aab10b2008-12-04 01:35:46 +0000946 // Add register-based dependencies (data, anti, and output).
Krzysztof Parzyszeka356bb72016-05-10 16:50:30 +0000947 // For some instructions (calls, returns, inline-asm, etc.) there can
948 // be explicit uses and implicit defs, in which case the use will appear
949 // on the operand list before the def. Do two passes over the operand
950 // list to make sure that defs are processed before any uses.
Andrew Trickec256482012-12-18 20:53:01 +0000951 bool HasVRegDef = false;
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000952 for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
953 const MachineOperand &MO = MI.getOperand(j);
Krzysztof Parzyszeka356bb72016-05-10 16:50:30 +0000954 if (!MO.isReg() || !MO.isDef())
955 continue;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000956 unsigned Reg = MO.getReg();
Krzysztof Parzyszeka356bb72016-05-10 16:50:30 +0000957 if (Reg == 0)
958 continue;
Dan Gohman60cb69e2008-11-19 23:18:57 +0000959
Andrew Trickdbee9d82012-01-14 02:17:15 +0000960 if (TRI->isPhysicalRegister(Reg))
961 addPhysRegDeps(SU, j);
962 else {
Krzysztof Parzyszeka356bb72016-05-10 16:50:30 +0000963 HasVRegDef = true;
964 addVRegDefDeps(SU, j);
Dan Gohman60cb69e2008-11-19 23:18:57 +0000965 }
966 }
Krzysztof Parzyszeka356bb72016-05-10 16:50:30 +0000967 // Now process all uses.
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000968 for (unsigned j = 0, n = MI.getNumOperands(); j != n; ++j) {
969 const MachineOperand &MO = MI.getOperand(j);
Matthias Braun8a5b4672016-05-10 20:11:58 +0000970 // Only look at use operands.
971 // We do not need to check for MO.readsReg() here because subsequent
972 // subregister defs will get output dependence edges and need no
973 // additional use dependencies.
Krzysztof Parzyszeka356bb72016-05-10 16:50:30 +0000974 if (!MO.isReg() || !MO.isUse())
975 continue;
976 unsigned Reg = MO.getReg();
977 if (Reg == 0)
978 continue;
979
980 if (TRI->isPhysicalRegister(Reg))
981 addPhysRegDeps(SU, j);
982 else if (MO.readsReg()) // ignore undef operands
983 addVRegUseDeps(SU, j);
984 }
985
Andrew Trickec256482012-12-18 20:53:01 +0000986 // If we haven't seen any uses in this scheduling region, create a
987 // dependence edge to ExitSU to model the live-out latency. This is required
988 // for vreg defs with no in-region use, and prefetches with no vreg def.
989 //
990 // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
991 // check currently relies on being called before adding chain deps.
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +0000992 if (SU->NumSuccs == 0 && SU->Latency > 1 && (HasVRegDef || MI.mayLoad())) {
Andrew Trickec256482012-12-18 20:53:01 +0000993 SDep Dep(SU, SDep::Artificial);
994 Dep.setLatency(SU->Latency - 1);
995 ExitSU.addPred(Dep);
996 }
Dan Gohman3aab10b2008-12-04 01:35:46 +0000997
Jonas Paulssonac29f012016-02-03 17:52:29 +0000998 // Add memory dependencies (Note: isStoreToStackSlot and
999 // isLoadFromStackSLot are not usable after stack slots are lowered to
1000 // actual addresses).
1001
1002 // This is a barrier event that acts as a pivotal node in the DAG.
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +00001003 if (isGlobalMemoryObject(AA, &MI)) {
Jonas Paulssonac29f012016-02-03 17:52:29 +00001004
1005 // Become the barrier chain.
David Goodwind2f9c042009-11-09 19:22:17 +00001006 if (BarrierChain)
Jonas Paulssonac29f012016-02-03 17:52:29 +00001007 BarrierChain->addPredBarrier(SU);
David Goodwind2f9c042009-11-09 19:22:17 +00001008 BarrierChain = SU;
1009
Jonas Paulssonac29f012016-02-03 17:52:29 +00001010 DEBUG(dbgs() << "Global memory object and new barrier chain: SU("
1011 << BarrierChain->NodeNum << ").\n";);
Tom Stellard3e01d472014-12-08 23:36:48 +00001012
Jonas Paulssonac29f012016-02-03 17:52:29 +00001013 // Add dependencies against everything below it and clear maps.
1014 addBarrierChain(Stores);
1015 addBarrierChain(Loads);
1016 addBarrierChain(NonAliasStores);
1017 addBarrierChain(NonAliasLoads);
Hal Finkel66859ae2012-12-10 18:49:16 +00001018
Jonas Paulssonac29f012016-02-03 17:52:29 +00001019 continue;
1020 }
1021
1022 // If it's not a store or a variant load, we're done.
Justin Lebard98cf002016-09-10 01:03:20 +00001023 if (!MI.mayStore() &&
1024 !(MI.mayLoad() && !MI.isDereferenceableInvariantLoad(AA)))
Jonas Paulssonac29f012016-02-03 17:52:29 +00001025 continue;
1026
1027 // Always add dependecy edge to BarrierChain if present.
1028 if (BarrierChain)
1029 BarrierChain->addPredBarrier(SU);
1030
1031 // Find the underlying objects for MI. The Objs vector is either
1032 // empty, or filled with the Values of memory locations which this
1033 // SU depends on. An empty vector means the memory location is
Jonas Paulsson98963fe2016-02-15 16:43:15 +00001034 // unknown, and may alias anything.
Jonas Paulssonac29f012016-02-03 17:52:29 +00001035 UnderlyingObjectsVector Objs;
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +00001036 getUnderlyingObjectsForInstr(&MI, MFI, Objs, MF.getDataLayout());
Jonas Paulssonac29f012016-02-03 17:52:29 +00001037
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +00001038 if (MI.mayStore()) {
Hal Finkel66859ae2012-12-10 18:49:16 +00001039 if (Objs.empty()) {
Jonas Paulssonac29f012016-02-03 17:52:29 +00001040 // An unknown store depends on all stores and loads.
1041 addChainDependencies(SU, Stores);
1042 addChainDependencies(SU, NonAliasStores);
1043 addChainDependencies(SU, Loads);
1044 addChainDependencies(SU, NonAliasLoads);
1045
1046 // Map this store to 'UnknownValue'.
1047 Stores.insert(SU, UnknownValue);
Chandler Carruthb4728562016-03-31 21:55:58 +00001048 } else {
1049 // Add precise dependencies against all previously seen memory
1050 // accesses mapped to the same Value(s).
Geoff Berry63817132016-04-14 21:31:07 +00001051 for (const UnderlyingObject &UnderlObj : Objs) {
1052 ValueType V = UnderlObj.getValue();
1053 bool ThisMayAlias = UnderlObj.mayAlias();
Chandler Carruthb4728562016-03-31 21:55:58 +00001054
1055 // Add dependencies to previous stores and loads mapped to V.
Geoff Berry63817132016-04-14 21:31:07 +00001056 addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
Chandler Carruthb4728562016-03-31 21:55:58 +00001057 addChainDependencies(SU, (ThisMayAlias ? Loads : NonAliasLoads), V);
Geoff Berryc0739d82016-04-12 15:50:19 +00001058 }
1059 // Update the store map after all chains have been added to avoid adding
1060 // self-loop edge if multiple underlying objects are present.
Geoff Berry63817132016-04-14 21:31:07 +00001061 for (const UnderlyingObject &UnderlObj : Objs) {
1062 ValueType V = UnderlObj.getValue();
1063 bool ThisMayAlias = UnderlObj.mayAlias();
Chandler Carruthb4728562016-03-31 21:55:58 +00001064
1065 // Map this store to V.
Geoff Berry63817132016-04-14 21:31:07 +00001066 (ThisMayAlias ? Stores : NonAliasStores).insert(SU, V);
Chandler Carruthb4728562016-03-31 21:55:58 +00001067 }
1068 // The store may have dependencies to unanalyzable loads and
1069 // stores.
1070 addChainDependencies(SU, Loads, UnknownValue);
1071 addChainDependencies(SU, Stores, UnknownValue);
Hal Finkel66859ae2012-12-10 18:49:16 +00001072 }
Chandler Carruthb4728562016-03-31 21:55:58 +00001073 } else { // SU is a load.
Jonas Paulssonac29f012016-02-03 17:52:29 +00001074 if (Objs.empty()) {
1075 // An unknown load depends on all stores.
1076 addChainDependencies(SU, Stores);
1077 addChainDependencies(SU, NonAliasStores);
1078
1079 Loads.insert(SU, UnknownValue);
Chandler Carruthb4728562016-03-31 21:55:58 +00001080 } else {
Geoff Berry63817132016-04-14 21:31:07 +00001081 for (const UnderlyingObject &UnderlObj : Objs) {
1082 ValueType V = UnderlObj.getValue();
1083 bool ThisMayAlias = UnderlObj.mayAlias();
Chandler Carruthb4728562016-03-31 21:55:58 +00001084
1085 // Add precise dependencies against all previously seen stores
1086 // mapping to the same Value(s).
1087 addChainDependencies(SU, (ThisMayAlias ? Stores : NonAliasStores), V);
1088
1089 // Map this load to V.
1090 (ThisMayAlias ? Loads : NonAliasLoads).insert(SU, V);
1091 }
1092 // The load may have dependencies to unanalyzable stores.
1093 addChainDependencies(SU, Stores, UnknownValue);
Hal Finkel66859ae2012-12-10 18:49:16 +00001094 }
Jonas Paulssonac29f012016-02-03 17:52:29 +00001095 }
1096
1097 // Reduce maps if they grow huge.
1098 if (Stores.size() + Loads.size() >= HugeRegion) {
1099 DEBUG(dbgs() << "Reducing Stores and Loads maps.\n";);
Mehdi Amini59ae8542016-04-16 04:58:30 +00001100 reduceHugeMemNodeMaps(Stores, Loads, getReductionSize());
Jonas Paulssonac29f012016-02-03 17:52:29 +00001101 }
1102 if (NonAliasStores.size() + NonAliasLoads.size() >= HugeRegion) {
1103 DEBUG(dbgs() << "Reducing NonAliasStores and NonAliasLoads maps.\n";);
Mehdi Amini59ae8542016-04-16 04:58:30 +00001104 reduceHugeMemNodeMaps(NonAliasStores, NonAliasLoads, getReductionSize());
Dan Gohman60cb69e2008-11-19 23:18:57 +00001105 }
Dan Gohman60cb69e2008-11-19 23:18:57 +00001106 }
Jonas Paulssonac29f012016-02-03 17:52:29 +00001107
Andrew Trickb767d1e2012-12-01 01:22:49 +00001108 if (DbgMI)
1109 FirstDbgValue = DbgMI;
Dan Gohman619ef482009-01-15 19:20:50 +00001110
Andrew Trickd675a4c2012-02-23 01:52:38 +00001111 Defs.clear();
1112 Uses.clear();
Matthias Braun97d0ffb2015-12-04 01:51:19 +00001113 CurrentVRegDefs.clear();
1114 CurrentVRegUses.clear();
Jonas Paulssonac29f012016-02-03 17:52:29 +00001115}
1116
1117raw_ostream &llvm::operator<<(raw_ostream &OS, const PseudoSourceValue* PSV) {
1118 PSV->printCustom(OS);
1119 return OS;
1120}
1121
1122void ScheduleDAGInstrs::Value2SUsMap::dump() {
1123 for (auto &Itr : *this) {
1124 if (Itr.first.is<const Value*>()) {
1125 const Value *V = Itr.first.get<const Value*>();
1126 if (isa<UndefValue>(V))
1127 dbgs() << "Unknown";
1128 else
1129 V->printAsOperand(dbgs());
1130 }
1131 else if (Itr.first.is<const PseudoSourceValue*>())
1132 dbgs() << Itr.first.get<const PseudoSourceValue*>();
1133 else
1134 llvm_unreachable("Unknown Value type.");
1135
1136 dbgs() << " : ";
1137 dumpSUList(Itr.second);
1138 }
1139}
1140
1141/// Reduce maps in FIFO order, by N SUs. This is better than turning
1142/// every Nth memory SU into BarrierChain in buildSchedGraph(), since
1143/// it avoids unnecessary edges between seen SUs above the new
1144/// BarrierChain, and those below it.
1145void ScheduleDAGInstrs::reduceHugeMemNodeMaps(Value2SUsMap &stores,
1146 Value2SUsMap &loads, unsigned N) {
1147 DEBUG(dbgs() << "Before reduction:\nStoring SUnits:\n";
1148 stores.dump();
1149 dbgs() << "Loading SUnits:\n";
1150 loads.dump());
1151
1152 // Insert all SU's NodeNums into a vector and sort it.
1153 std::vector<unsigned> NodeNums;
1154 NodeNums.reserve(stores.size() + loads.size());
1155 for (auto &I : stores)
1156 for (auto *SU : I.second)
1157 NodeNums.push_back(SU->NodeNum);
1158 for (auto &I : loads)
1159 for (auto *SU : I.second)
1160 NodeNums.push_back(SU->NodeNum);
1161 std::sort(NodeNums.begin(), NodeNums.end());
1162
1163 // The N last elements in NodeNums will be removed, and the SU with
1164 // the lowest NodeNum of them will become the new BarrierChain to
1165 // let the not yet seen SUs have a dependency to the removed SUs.
1166 assert (N <= NodeNums.size());
1167 SUnit *newBarrierChain = &SUnits[*(NodeNums.end() - N)];
1168 if (BarrierChain) {
1169 // The aliasing and non-aliasing maps reduce independently of each
1170 // other, but share a common BarrierChain. Check if the
1171 // newBarrierChain is above the former one. If it is not, it may
1172 // introduce a loop to use newBarrierChain, so keep the old one.
1173 if (newBarrierChain->NodeNum < BarrierChain->NodeNum) {
1174 BarrierChain->addPredBarrier(newBarrierChain);
1175 BarrierChain = newBarrierChain;
1176 DEBUG(dbgs() << "Inserting new barrier chain: SU("
1177 << BarrierChain->NodeNum << ").\n";);
1178 }
1179 else
1180 DEBUG(dbgs() << "Keeping old barrier chain: SU("
1181 << BarrierChain->NodeNum << ").\n";);
1182 }
1183 else
1184 BarrierChain = newBarrierChain;
1185
1186 insertBarrierChain(stores);
1187 insertBarrierChain(loads);
1188
1189 DEBUG(dbgs() << "After reduction:\nStoring SUnits:\n";
1190 stores.dump();
1191 dbgs() << "Loading SUnits:\n";
1192 loads.dump());
Dan Gohman60cb69e2008-11-19 23:18:57 +00001193}
1194
Andrew Trick6b104f82013-12-28 21:56:55 +00001195/// \brief Initialize register live-range state for updating kills.
1196void ScheduleDAGInstrs::startBlockForKills(MachineBasicBlock *BB) {
1197 // Start with no live registers.
1198 LiveRegs.reset();
1199
1200 // Examine the live-in regs of all successors.
Matthias Braun298e0072016-09-30 23:08:07 +00001201 for (const MachineBasicBlock *Succ : BB->successors()) {
1202 for (const auto &LI : Succ->liveins()) {
Andrew Trick6b104f82013-12-28 21:56:55 +00001203 // Repeat, for reg and all subregs.
Matthias Braund9da1622015-09-09 18:08:03 +00001204 for (MCSubRegIterator SubRegs(LI.PhysReg, TRI, /*IncludeSelf=*/true);
Andrew Trick6b104f82013-12-28 21:56:55 +00001205 SubRegs.isValid(); ++SubRegs)
1206 LiveRegs.set(*SubRegs);
1207 }
1208 }
1209}
1210
Pete Cooper300069a2015-05-04 16:52:06 +00001211/// \brief If we change a kill flag on the bundle instruction implicit register
1212/// operands, then we also need to propagate that to any instructions inside
1213/// the bundle which had the same kill state.
1214static void toggleBundleKillFlag(MachineInstr *MI, unsigned Reg,
Mandeep Singh Grange5a2f112016-05-10 17:57:27 +00001215 bool NewKillState,
1216 const TargetRegisterInfo *TRI) {
Pete Cooper300069a2015-05-04 16:52:06 +00001217 if (MI->getOpcode() != TargetOpcode::BUNDLE)
1218 return;
1219
1220 // Walk backwards from the last instruction in the bundle to the first.
1221 // Once we set a kill flag on an instruction, we bail out, as otherwise we
1222 // might set it on too many operands. We will clear as many flags as we
1223 // can though.
Duncan P. N. Exon Smithc5b668d2016-02-22 20:49:58 +00001224 MachineBasicBlock::instr_iterator Begin = MI->getIterator();
Duncan P. N. Exon Smithf9ab4162016-02-27 17:05:33 +00001225 MachineBasicBlock::instr_iterator End = getBundleEnd(*MI);
Pete Cooper300069a2015-05-04 16:52:06 +00001226 while (Begin != End) {
Mandeep Singh Grange5a2f112016-05-10 17:57:27 +00001227 if (NewKillState) {
1228 if ((--End)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
1229 return;
1230 } else
1231 (--End)->clearRegisterKills(Reg, TRI);
Pete Cooper300069a2015-05-04 16:52:06 +00001232 }
1233}
1234
Andrew Trick6b104f82013-12-28 21:56:55 +00001235bool ScheduleDAGInstrs::toggleKillFlag(MachineInstr *MI, MachineOperand &MO) {
1236 // Setting kill flag...
1237 if (!MO.isKill()) {
1238 MO.setIsKill(true);
Mandeep Singh Grange5a2f112016-05-10 17:57:27 +00001239 toggleBundleKillFlag(MI, MO.getReg(), true, TRI);
Andrew Trick6b104f82013-12-28 21:56:55 +00001240 return false;
1241 }
1242
1243 // If MO itself is live, clear the kill flag...
1244 if (LiveRegs.test(MO.getReg())) {
1245 MO.setIsKill(false);
Mandeep Singh Grange5a2f112016-05-10 17:57:27 +00001246 toggleBundleKillFlag(MI, MO.getReg(), false, TRI);
Andrew Trick6b104f82013-12-28 21:56:55 +00001247 return false;
1248 }
1249
1250 // If any subreg of MO is live, then create an imp-def for that
1251 // subreg and keep MO marked as killed.
1252 MO.setIsKill(false);
Mandeep Singh Grange5a2f112016-05-10 17:57:27 +00001253 toggleBundleKillFlag(MI, MO.getReg(), false, TRI);
Andrew Trick6b104f82013-12-28 21:56:55 +00001254 bool AllDead = true;
1255 const unsigned SuperReg = MO.getReg();
1256 MachineInstrBuilder MIB(MF, MI);
1257 for (MCSubRegIterator SubRegs(SuperReg, TRI); SubRegs.isValid(); ++SubRegs) {
1258 if (LiveRegs.test(*SubRegs)) {
1259 MIB.addReg(*SubRegs, RegState::ImplicitDefine);
1260 AllDead = false;
1261 }
1262 }
1263
Pete Cooper300069a2015-05-04 16:52:06 +00001264 if(AllDead) {
Andrew Trick6b104f82013-12-28 21:56:55 +00001265 MO.setIsKill(true);
Mandeep Singh Grange5a2f112016-05-10 17:57:27 +00001266 toggleBundleKillFlag(MI, MO.getReg(), true, TRI);
Pete Cooper300069a2015-05-04 16:52:06 +00001267 }
Andrew Trick6b104f82013-12-28 21:56:55 +00001268 return false;
1269}
1270
1271// FIXME: Reuse the LivePhysRegs utility for this.
1272void ScheduleDAGInstrs::fixupKills(MachineBasicBlock *MBB) {
1273 DEBUG(dbgs() << "Fixup kills for BB#" << MBB->getNumber() << '\n');
1274
1275 LiveRegs.resize(TRI->getNumRegs());
1276 BitVector killedRegs(TRI->getNumRegs());
1277
1278 startBlockForKills(MBB);
1279
1280 // Examine block from end to start...
1281 unsigned Count = MBB->size();
1282 for (MachineBasicBlock::iterator I = MBB->end(), E = MBB->begin();
1283 I != E; --Count) {
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +00001284 MachineInstr &MI = *--I;
1285 if (MI.isDebugValue())
Andrew Trick6b104f82013-12-28 21:56:55 +00001286 continue;
1287
1288 // Update liveness. Registers that are defed but not used in this
1289 // instruction are now dead. Mark register and all subregs as they
1290 // are completely defined.
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +00001291 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1292 MachineOperand &MO = MI.getOperand(i);
Andrew Trick6b104f82013-12-28 21:56:55 +00001293 if (MO.isRegMask())
1294 LiveRegs.clearBitsNotInMask(MO.getRegMask());
1295 if (!MO.isReg()) continue;
1296 unsigned Reg = MO.getReg();
1297 if (Reg == 0) continue;
1298 if (!MO.isDef()) continue;
1299 // Ignore two-addr defs.
Duncan P. N. Exon Smithb77911b2016-07-01 16:21:48 +00001300 if (MI.isRegTiedToUseOperand(i)) continue;
Andrew Trick6b104f82013-12-28 21:56:55 +00001301
1302 // Repeat for reg and all subregs.
1303 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1304 SubRegs.isValid(); ++SubRegs)
1305 LiveRegs.reset(*SubRegs);
1306 }
1307
1308 // Examine all used registers and set/clear kill flag. When a
1309 // register is used multiple times we only set the kill flag on
1310 // the first use. Don't set kill flags on undef operands.
1311 killedRegs.reset();
Krzysztof Parzyszeke7c72cd2016-10-05 13:15:06 +00001312
1313 // toggleKillFlag can append new operands (implicit defs), so using
1314 // a range-based loop is not safe. The new operands will be appended
1315 // at the end of the operand list and they don't need to be visited,
1316 // so iterating until the currently last operand is ok.
1317 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1318 MachineOperand &MO = MI.getOperand(i);
Andrew Trick6b104f82013-12-28 21:56:55 +00001319 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
1320 unsigned Reg = MO.getReg();
1321 if ((Reg == 0) || MRI.isReserved(Reg)) continue;
1322
1323 bool kill = false;
1324 if (!killedRegs.test(Reg)) {
1325 kill = true;
1326 // A register is not killed if any subregs are live...
1327 for (MCSubRegIterator SubRegs(Reg, TRI); SubRegs.isValid(); ++SubRegs) {
1328 if (LiveRegs.test(*SubRegs)) {
1329 kill = false;
1330 break;
1331 }
1332 }
1333
1334 // If subreg is not live, then register is killed if it became
1335 // live in this instruction
1336 if (kill)
1337 kill = !LiveRegs.test(Reg);
1338 }
1339
1340 if (MO.isKill() != kill) {
1341 DEBUG(dbgs() << "Fixing " << MO << " in ");
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...
Matthias Braun298e0072016-09-30 23:08:07 +00001359 for (const MachineOperand &MO : MI.operands()) {
Andrew Trick6b104f82013-12-28 21:56:55 +00001360 if (!MO.isReg() || !MO.isUse() || MO.isUndef()) continue;
1361 unsigned Reg = MO.getReg();
1362 if ((Reg == 0) || MRI.isReserved(Reg)) continue;
1363
1364 for (MCSubRegIterator SubRegs(Reg, TRI, /*IncludeSelf=*/true);
1365 SubRegs.isValid(); ++SubRegs)
1366 LiveRegs.set(*SubRegs);
1367 }
1368 }
1369}
1370
Dan Gohman60cb69e2008-11-19 23:18:57 +00001371void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
Manman Ren19f49ac2012-09-11 22:23:19 +00001372#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman60cb69e2008-11-19 23:18:57 +00001373 SU->getInstr()->dump();
Manman Ren742534c2012-09-06 19:06:06 +00001374#endif
Dan Gohman60cb69e2008-11-19 23:18:57 +00001375}
1376
1377std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
Alp Tokere69170a2014-06-26 22:52:05 +00001378 std::string s;
1379 raw_string_ostream oss(s);
Dan Gohmanb9543432009-02-10 23:27:53 +00001380 if (SU == &EntrySU)
1381 oss << "<entry>";
1382 else if (SU == &ExitSU)
1383 oss << "<exit>";
1384 else
Eric Christopher1cdefae2015-02-27 00:11:34 +00001385 SU->getInstr()->print(oss, /*SkipOpers=*/true);
Dan Gohman60cb69e2008-11-19 23:18:57 +00001386 return oss.str();
1387}
1388
Andrew Trick1b2324d2012-03-07 00:18:22 +00001389/// Return the basic block label. It is not necessarilly unique because a block
1390/// contains multiple scheduling regions. But it is fine for visualization.
1391std::string ScheduleDAGInstrs::getDAGName() const {
1392 return "dag." + BB->getFullName();
1393}
Andrew Trick90f711d2012-10-15 18:02:27 +00001394
Andrew Trick48d392e2012-11-28 05:13:28 +00001395//===----------------------------------------------------------------------===//
1396// SchedDFSResult Implementation
1397//===----------------------------------------------------------------------===//
1398
1399namespace llvm {
1400/// \brief Internal state used to compute SchedDFSResult.
1401class SchedDFSImpl {
1402 SchedDFSResult &R;
1403
1404 /// Join DAG nodes into equivalence classes by their subtree.
1405 IntEqClasses SubtreeClasses;
1406 /// List PredSU, SuccSU pairs that represent data edges between subtrees.
1407 std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs;
1408
Andrew Trickffc80972013-01-25 06:52:27 +00001409 struct RootData {
1410 unsigned NodeID;
1411 unsigned ParentNodeID; // Parent node (member of the parent subtree).
1412 unsigned SubInstrCount; // Instr count in this tree only, not children.
1413
1414 RootData(unsigned id): NodeID(id),
1415 ParentNodeID(SchedDFSResult::InvalidSubtreeID),
1416 SubInstrCount(0) {}
1417
1418 unsigned getSparseSetIndex() const { return NodeID; }
1419 };
1420
1421 SparseSet<RootData> RootSet;
1422
Andrew Trick48d392e2012-11-28 05:13:28 +00001423public:
Andrew Trickffc80972013-01-25 06:52:27 +00001424 SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
1425 RootSet.setUniverse(R.DFSNodeData.size());
1426 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001427
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001428 /// Return true if this node been visited by the DFS traversal.
1429 ///
1430 /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
1431 /// ID. Later, SubtreeID is updated but remains valid.
Andrew Trick48d392e2012-11-28 05:13:28 +00001432 bool isVisited(const SUnit *SU) const {
Andrew Trickffc80972013-01-25 06:52:27 +00001433 return R.DFSNodeData[SU->NodeNum].SubtreeID
1434 != SchedDFSResult::InvalidSubtreeID;
Andrew Trick48d392e2012-11-28 05:13:28 +00001435 }
1436
1437 /// Initialize this node's instruction count. We don't need to flag the node
1438 /// visited until visitPostorder because the DAG cannot have cycles.
1439 void visitPreorder(const SUnit *SU) {
Andrew Trickffc80972013-01-25 06:52:27 +00001440 R.DFSNodeData[SU->NodeNum].InstrCount =
1441 SU->getInstr()->isTransient() ? 0 : 1;
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001442 }
1443
1444 /// Called once for each node after all predecessors are visited. Revisit this
1445 /// node's predecessors and potentially join them now that we know the ILP of
1446 /// the other predecessors.
1447 void visitPostorderNode(const SUnit *SU) {
1448 // Mark this node as the root of a subtree. It may be joined with its
1449 // successors later.
Andrew Trickffc80972013-01-25 06:52:27 +00001450 R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
1451 RootData RData(SU->NodeNum);
1452 RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
Andrew Trick48d392e2012-11-28 05:13:28 +00001453
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001454 // If any predecessors are still in their own subtree, they either cannot be
1455 // joined or are large enough to remain separate. If this parent node's
1456 // total instruction count is not greater than a child subtree by at least
1457 // the subtree limit, then try to join it now since splitting subtrees is
1458 // only useful if multiple high-pressure paths are possible.
Andrew Trickffc80972013-01-25 06:52:27 +00001459 unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
Matthias Braun298e0072016-09-30 23:08:07 +00001460 for (const SDep &PredDep : SU->Preds) {
1461 if (PredDep.getKind() != SDep::Data)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001462 continue;
Matthias Braun298e0072016-09-30 23:08:07 +00001463 unsigned PredNum = PredDep.getSUnit()->NodeNum;
Andrew Trickffc80972013-01-25 06:52:27 +00001464 if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
Matthias Braun298e0072016-09-30 23:08:07 +00001465 joinPredSubtree(PredDep, SU, /*CheckLimit=*/false);
Andrew Trickffc80972013-01-25 06:52:27 +00001466
1467 // Either link or merge the TreeData entry from the child to the parent.
Andrew Trick646eeb62013-01-25 06:52:30 +00001468 if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
1469 // If the predecessor's parent is invalid, this is a tree edge and the
1470 // current node is the parent.
1471 if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
1472 RootSet[PredNum].ParentNodeID = SU->NodeNum;
1473 }
1474 else if (RootSet.count(PredNum)) {
1475 // The predecessor is not a root, but is still in the root set. This
1476 // must be the new parent that it was just joined to. Note that
1477 // RootSet[PredNum].ParentNodeID may either be invalid or may still be
1478 // set to the original parent.
Andrew Trickffc80972013-01-25 06:52:27 +00001479 RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
1480 RootSet.erase(PredNum);
1481 }
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001482 }
Andrew Trickffc80972013-01-25 06:52:27 +00001483 RootSet[SU->NodeNum] = RData;
1484 }
1485
1486 /// Called once for each tree edge after calling visitPostOrderNode on the
1487 /// predecessor. Increment the parent node's instruction count and
1488 /// preemptively join this subtree to its parent's if it is small enough.
1489 void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
1490 R.DFSNodeData[Succ->NodeNum].InstrCount
1491 += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
1492 joinPredSubtree(PredDep, Succ);
Andrew Trick48d392e2012-11-28 05:13:28 +00001493 }
1494
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001495 /// Add a connection for cross edges.
1496 void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
Andrew Trick48d392e2012-11-28 05:13:28 +00001497 ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
1498 }
1499
1500 /// Set each node's subtree ID to the representative ID and record connections
1501 /// between trees.
1502 void finalize() {
1503 SubtreeClasses.compress();
Andrew Trickffc80972013-01-25 06:52:27 +00001504 R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
1505 assert(SubtreeClasses.getNumClasses() == RootSet.size()
1506 && "number of roots should match trees");
Matthias Braun298e0072016-09-30 23:08:07 +00001507 for (const RootData &Root : RootSet) {
1508 unsigned TreeID = SubtreeClasses[Root.NodeID];
1509 if (Root.ParentNodeID != SchedDFSResult::InvalidSubtreeID)
1510 R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[Root.ParentNodeID];
1511 R.DFSTreeData[TreeID].SubInstrCount = Root.SubInstrCount;
Andrew Trick646eeb62013-01-25 06:52:30 +00001512 // Note that SubInstrCount may be greater than InstrCount if we joined
1513 // subtrees across a cross edge. InstrCount will be attributed to the
1514 // original parent, while SubInstrCount will be attributed to the joined
1515 // parent.
Andrew Trickffc80972013-01-25 06:52:27 +00001516 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001517 R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1518 R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1519 DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
Andrew Trickffc80972013-01-25 06:52:27 +00001520 for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
1521 R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
Andrew Trick48d392e2012-11-28 05:13:28 +00001522 DEBUG(dbgs() << " SU(" << Idx << ") in tree "
Andrew Trickffc80972013-01-25 06:52:27 +00001523 << R.DFSNodeData[Idx].SubtreeID << '\n');
Andrew Trick48d392e2012-11-28 05:13:28 +00001524 }
Matthias Braun298e0072016-09-30 23:08:07 +00001525 for (const std::pair<const SUnit*, const SUnit*> &P : ConnectionPairs) {
1526 unsigned PredTree = SubtreeClasses[P.first->NodeNum];
1527 unsigned SuccTree = SubtreeClasses[P.second->NodeNum];
Andrew Trick48d392e2012-11-28 05:13:28 +00001528 if (PredTree == SuccTree)
1529 continue;
Matthias Braun298e0072016-09-30 23:08:07 +00001530 unsigned Depth = P.first->getDepth();
Andrew Trick48d392e2012-11-28 05:13:28 +00001531 addConnection(PredTree, SuccTree, Depth);
1532 addConnection(SuccTree, PredTree, Depth);
1533 }
1534 }
1535
1536protected:
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001537 /// Join the predecessor subtree with the successor that is its DFS
1538 /// parent. Apply some heuristics before joining.
1539 bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
1540 bool CheckLimit = true) {
1541 assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
1542
1543 // Check if the predecessor is already joined.
1544 const SUnit *PredSU = PredDep.getSUnit();
1545 unsigned PredNum = PredSU->NodeNum;
Andrew Trickffc80972013-01-25 06:52:27 +00001546 if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001547 return false;
Andrew Trickb52a8562013-01-25 00:12:57 +00001548
1549 // Four is the magic number of successors before a node is considered a
1550 // pinch point.
1551 unsigned NumDataSucs = 0;
Matthias Braun298e0072016-09-30 23:08:07 +00001552 for (const SDep &SuccDep : PredSU->Succs) {
1553 if (SuccDep.getKind() == SDep::Data) {
Andrew Trickb52a8562013-01-25 00:12:57 +00001554 if (++NumDataSucs >= 4)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001555 return false;
Andrew Trickb52a8562013-01-25 00:12:57 +00001556 }
1557 }
Andrew Trickffc80972013-01-25 06:52:27 +00001558 if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001559 return false;
Andrew Trickffc80972013-01-25 06:52:27 +00001560 R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001561 SubtreeClasses.join(Succ->NodeNum, PredNum);
1562 return true;
Andrew Trickb52a8562013-01-25 00:12:57 +00001563 }
1564
Andrew Trick48d392e2012-11-28 05:13:28 +00001565 /// Called by finalize() to record a connection between trees.
1566 void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
1567 if (!Depth)
1568 return;
1569
Andrew Trickffc80972013-01-25 06:52:27 +00001570 do {
1571 SmallVectorImpl<SchedDFSResult::Connection> &Connections =
1572 R.SubtreeConnections[FromTree];
Matthias Braun298e0072016-09-30 23:08:07 +00001573 for (SchedDFSResult::Connection &C : Connections) {
1574 if (C.TreeID == ToTree) {
1575 C.Level = std::max(C.Level, Depth);
Andrew Trickffc80972013-01-25 06:52:27 +00001576 return;
1577 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001578 }
Andrew Trickffc80972013-01-25 06:52:27 +00001579 Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
1580 FromTree = R.DFSTreeData[FromTree].ParentTreeID;
1581 } while (FromTree != SchedDFSResult::InvalidSubtreeID);
Andrew Trick48d392e2012-11-28 05:13:28 +00001582 }
1583};
1584} // namespace llvm
1585
Andrew Trick90f711d2012-10-15 18:02:27 +00001586namespace {
1587/// \brief Manage the stack used by a reverse depth-first search over the DAG.
1588class SchedDAGReverseDFS {
1589 std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
1590public:
1591 bool isComplete() const { return DFSStack.empty(); }
1592
1593 void follow(const SUnit *SU) {
1594 DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
1595 }
1596 void advance() { ++DFSStack.back().second; }
1597
Andrew Trick48d392e2012-11-28 05:13:28 +00001598 const SDep *backtrack() {
1599 DFSStack.pop_back();
Craig Topperc0196b12014-04-14 00:51:57 +00001600 return DFSStack.empty() ? nullptr : std::prev(DFSStack.back().second);
Andrew Trick48d392e2012-11-28 05:13:28 +00001601 }
Andrew Trick90f711d2012-10-15 18:02:27 +00001602
1603 const SUnit *getCurr() const { return DFSStack.back().first; }
1604
1605 SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
1606
1607 SUnit::const_pred_iterator getPredEnd() const {
1608 return getCurr()->Preds.end();
1609 }
1610};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001611} // anonymous
Andrew Trick90f711d2012-10-15 18:02:27 +00001612
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001613static bool hasDataSucc(const SUnit *SU) {
Matthias Braun298e0072016-09-30 23:08:07 +00001614 for (const SDep &SuccDep : SU->Succs) {
1615 if (SuccDep.getKind() == SDep::Data &&
1616 !SuccDep.getSUnit()->isBoundaryNode())
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001617 return true;
1618 }
1619 return false;
1620}
1621
Andrew Trick90f711d2012-10-15 18:02:27 +00001622/// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
1623/// search from this root.
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001624void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
Andrew Trick90f711d2012-10-15 18:02:27 +00001625 if (!IsBottomUp)
1626 llvm_unreachable("Top-down ILP metric is unimplemnted");
1627
Andrew Trick48d392e2012-11-28 05:13:28 +00001628 SchedDFSImpl Impl(*this);
Matthias Braun298e0072016-09-30 23:08:07 +00001629 for (const SUnit &SU : SUnits) {
1630 if (Impl.isVisited(&SU) || hasDataSucc(&SU))
Andrew Tricke2c3f5c2013-01-25 06:33:57 +00001631 continue;
1632
Andrew Trick48d392e2012-11-28 05:13:28 +00001633 SchedDAGReverseDFS DFS;
Matthias Braun298e0072016-09-30 23:08:07 +00001634 Impl.visitPreorder(&SU);
1635 DFS.follow(&SU);
Andrew Trick48d392e2012-11-28 05:13:28 +00001636 for (;;) {
1637 // Traverse the leftmost path as far as possible.
1638 while (DFS.getPred() != DFS.getPredEnd()) {
1639 const SDep &PredDep = *DFS.getPred();
1640 DFS.advance();
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001641 // Ignore non-data edges.
Andrew Trick646eeb62013-01-25 06:52:30 +00001642 if (PredDep.getKind() != SDep::Data
1643 || PredDep.getSUnit()->isBoundaryNode()) {
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001644 continue;
Andrew Trick646eeb62013-01-25 06:52:30 +00001645 }
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001646 // An already visited edge is a cross edge, assuming an acyclic DAG.
Andrew Trick48d392e2012-11-28 05:13:28 +00001647 if (Impl.isVisited(PredDep.getSUnit())) {
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001648 Impl.visitCrossEdge(PredDep, DFS.getCurr());
Andrew Trick48d392e2012-11-28 05:13:28 +00001649 continue;
1650 }
1651 Impl.visitPreorder(PredDep.getSUnit());
1652 DFS.follow(PredDep.getSUnit());
1653 }
1654 // Visit the top of the stack in postorder and backtrack.
1655 const SUnit *Child = DFS.getCurr();
1656 const SDep *PredDep = DFS.backtrack();
Andrew Trick5b07eeb2013-01-25 06:02:44 +00001657 Impl.visitPostorderNode(Child);
1658 if (PredDep)
1659 Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
Andrew Trick48d392e2012-11-28 05:13:28 +00001660 if (DFS.isComplete())
1661 break;
Andrew Trick90f711d2012-10-15 18:02:27 +00001662 }
Andrew Trick48d392e2012-11-28 05:13:28 +00001663 }
1664 Impl.finalize();
1665}
1666
1667/// The root of the given SubtreeID was just scheduled. For all subtrees
1668/// connected to this tree, record the depth of the connection so that the
1669/// nearest connected subtrees can be prioritized.
1670void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
Matthias Braun298e0072016-09-30 23:08:07 +00001671 for (const Connection &C : SubtreeConnections[SubtreeID]) {
1672 SubtreeConnectLevels[C.TreeID] =
1673 std::max(SubtreeConnectLevels[C.TreeID], C.Level);
1674 DEBUG(dbgs() << " Tree: " << C.TreeID
1675 << " @" << SubtreeConnectLevels[C.TreeID] << '\n');
Andrew Trick90f711d2012-10-15 18:02:27 +00001676 }
1677}
1678
Alp Tokerd8d510a2014-07-01 21:19:13 +00001679LLVM_DUMP_METHOD
Andrew Trick90f711d2012-10-15 18:02:27 +00001680void ILPValue::print(raw_ostream &OS) const {
Andrew Trick48d392e2012-11-28 05:13:28 +00001681 OS << InstrCount << " / " << Length << " = ";
1682 if (!Length)
Andrew Trick90f711d2012-10-15 18:02:27 +00001683 OS << "BADILP";
Andrew Trick48d392e2012-11-28 05:13:28 +00001684 else
1685 OS << format("%g", ((double)InstrCount / Length));
Andrew Trick90f711d2012-10-15 18:02:27 +00001686}
1687
Alp Tokerd8d510a2014-07-01 21:19:13 +00001688LLVM_DUMP_METHOD
Andrew Trick90f711d2012-10-15 18:02:27 +00001689void ILPValue::dump() const {
1690 dbgs() << *this << '\n';
1691}
1692
1693namespace llvm {
1694
Alp Tokerd8d510a2014-07-01 21:19:13 +00001695LLVM_DUMP_METHOD
Andrew Trick90f711d2012-10-15 18:02:27 +00001696raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1697 Val.print(OS);
1698 return OS;
1699}
1700
1701} // namespace llvm