blob: 683011d3deeee948cb55a19c0ba6622f75299d83 [file] [log] [blame]
Dan Gohmana629b482008-12-08 17:50:35 +00001//===---- ScheduleDAGInstrs.cpp - MachineInstr Rescheduling ---------------===//
Dan Gohman343f0c02008-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 Gohmana629b482008-12-08 17:50:35 +000010// This implements the ScheduleDAGInstrs class, which implements re-scheduling
11// of MachineInstrs.
Dan Gohman343f0c02008-11-19 23:18:57 +000012//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "sched-instrs"
Dan Gohman8906f952009-07-17 20:58:59 +000016#include "llvm/Operator.h"
Dan Gohman3311a1f2009-01-30 02:49:14 +000017#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohman5034dd32010-12-15 20:02:24 +000018#include "llvm/Analysis/ValueTracking.h"
Andrew Trickb4566a92012-02-22 06:08:11 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Dan Gohman3f237442008-12-16 03:25:46 +000020#include "llvm/CodeGen/MachineFunctionPass.h"
Dan Gohmanc76909a2009-09-25 20:36:54 +000021#include "llvm/CodeGen/MachineMemOperand.h"
Dan Gohman3f237442008-12-16 03:25:46 +000022#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohman6a9041e2008-12-04 01:35:46 +000023#include "llvm/CodeGen/PseudoSourceValue.h"
Andrew Trickafc26572012-06-06 19:47:35 +000024#include "llvm/CodeGen/RegisterPressure.h"
Andrew Trick1e94e982012-10-15 18:02:27 +000025#include "llvm/CodeGen/ScheduleDAGILP.h"
Andrew Tricked395c82012-03-07 23:01:06 +000026#include "llvm/CodeGen/ScheduleDAGInstrs.h"
Evan Chengab8be962011-06-29 01:14:12 +000027#include "llvm/MC/MCInstrItineraries.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000028#include "llvm/Target/TargetMachine.h"
29#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetRegisterInfo.h"
Evan Cheng5b1b44892011-07-01 21:01:15 +000031#include "llvm/Target/TargetSubtargetInfo.h"
Andrew Trickeb05b972012-05-15 18:59:41 +000032#include "llvm/Support/CommandLine.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000033#include "llvm/Support/Debug.h"
Andrew Trick1e94e982012-10-15 18:02:27 +000034#include "llvm/Support/Format.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000035#include "llvm/Support/raw_ostream.h"
Sergei Larin009cf9e2012-11-15 17:45:50 +000036#include "llvm/ADT/MapVector.h"
Dan Gohman3f237442008-12-16 03:25:46 +000037#include "llvm/ADT/SmallSet.h"
Andrew Trickeb05b972012-05-15 18:59:41 +000038#include "llvm/ADT/SmallPtrSet.h"
Dan Gohman343f0c02008-11-19 23:18:57 +000039using namespace llvm;
40
Andrew Trickeb05b972012-05-15 18:59:41 +000041static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
42 cl::ZeroOrMore, cl::init(false),
43 cl::desc("Enable use of AA during MI GAD construction"));
44
Dan Gohman79ce2762009-01-15 19:20:50 +000045ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
Dan Gohman3f237442008-12-16 03:25:46 +000046 const MachineLoopInfo &mli,
Andrew Trick5e920d72012-01-14 02:17:12 +000047 const MachineDominatorTree &mdt,
Andrew Trickb4566a92012-02-22 06:08:11 +000048 bool IsPostRAFlag,
49 LiveIntervals *lis)
Andrew Trick412cd2f2012-10-10 05:43:09 +000050 : ScheduleDAG(mf), MLI(mli), MDT(mdt), MFI(mf.getFrameInfo()), LIS(lis),
Andrew Trick714973e2012-10-09 23:44:23 +000051 IsPostRA(IsPostRAFlag), CanHandleTerminators(false), FirstDbgValue(0) {
Andrew Trickb4566a92012-02-22 06:08:11 +000052 assert((IsPostRA || LIS) && "PreRA scheduling requires LiveIntervals");
Devang Patelcf4cc842011-06-02 20:07:12 +000053 DbgValues.clear();
Andrew Trickcc77b542012-02-22 06:08:13 +000054 assert(!(IsPostRA && MRI.getNumVirtRegs()) &&
Andrew Trick19273ae2012-02-21 04:51:23 +000055 "Virtual registers must be removed prior to PostRA scheduling");
Andrew Trick781ab472012-09-18 18:20:00 +000056
57 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
58 SchedModel.init(*ST.getSchedModel(), &ST, TII);
Evan Cheng38bdfc62009-10-18 19:58:47 +000059}
Dan Gohman343f0c02008-11-19 23:18:57 +000060
Dan Gohman3311a1f2009-01-30 02:49:14 +000061/// getUnderlyingObjectFromInt - This is the function that does the work of
62/// looking through basic ptrtoint+arithmetic+inttoptr sequences.
63static const Value *getUnderlyingObjectFromInt(const Value *V) {
64 do {
Dan Gohman8906f952009-07-17 20:58:59 +000065 if (const Operator *U = dyn_cast<Operator>(V)) {
Dan Gohman3311a1f2009-01-30 02:49:14 +000066 // If we find a ptrtoint, we can transfer control back to the
67 // regular getUnderlyingObjectFromInt.
Dan Gohman8906f952009-07-17 20:58:59 +000068 if (U->getOpcode() == Instruction::PtrToInt)
Dan Gohman3311a1f2009-01-30 02:49:14 +000069 return U->getOperand(0);
70 // If we find an add of a constant or a multiplied value, it's
71 // likely that the other operand will lead us to the base
72 // object. We don't have to worry about the case where the
Dan Gohman748f98f2009-08-07 01:26:06 +000073 // object address is somehow being computed by the multiply,
Dan Gohman3311a1f2009-01-30 02:49:14 +000074 // because our callers only care when the result is an
Nick Lewycky6b0db5f2012-10-26 04:27:49 +000075 // identifiable object.
Dan Gohman8906f952009-07-17 20:58:59 +000076 if (U->getOpcode() != Instruction::Add ||
Dan Gohman3311a1f2009-01-30 02:49:14 +000077 (!isa<ConstantInt>(U->getOperand(1)) &&
Dan Gohman8906f952009-07-17 20:58:59 +000078 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul))
Dan Gohman3311a1f2009-01-30 02:49:14 +000079 return V;
80 V = U->getOperand(0);
81 } else {
82 return V;
83 }
Duncan Sands1df98592010-02-16 11:11:14 +000084 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
Dan Gohman3311a1f2009-01-30 02:49:14 +000085 } while (1);
86}
87
Dan Gohman5034dd32010-12-15 20:02:24 +000088/// getUnderlyingObject - This is a wrapper around GetUnderlyingObject
Dan Gohman3311a1f2009-01-30 02:49:14 +000089/// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
90static const Value *getUnderlyingObject(const Value *V) {
91 // First just call Value::getUnderlyingObject to let it do what it does.
92 do {
Dan Gohman5034dd32010-12-15 20:02:24 +000093 V = GetUnderlyingObject(V);
Dan Gohman3311a1f2009-01-30 02:49:14 +000094 // If it found an inttoptr, use special code to continue climing.
Dan Gohman8906f952009-07-17 20:58:59 +000095 if (Operator::getOpcode(V) != Instruction::IntToPtr)
Dan Gohman3311a1f2009-01-30 02:49:14 +000096 break;
97 const Value *O = getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
98 // If that succeeded in finding a pointer, continue the search.
Duncan Sands1df98592010-02-16 11:11:14 +000099 if (!O->getType()->isPointerTy())
Dan Gohman3311a1f2009-01-30 02:49:14 +0000100 break;
101 V = O;
102 } while (1);
103 return V;
104}
105
106/// getUnderlyingObjectForInstr - If this machine instr has memory reference
107/// information and it can be tracked to a normal reference to a known
108/// object, return the Value for that object. Otherwise return null.
Evan Cheng38bdfc62009-10-18 19:58:47 +0000109static const Value *getUnderlyingObjectForInstr(const MachineInstr *MI,
David Goodwina9e61072009-11-03 20:15:00 +0000110 const MachineFrameInfo *MFI,
111 bool &MayAlias) {
112 MayAlias = true;
Dan Gohman3311a1f2009-01-30 02:49:14 +0000113 if (!MI->hasOneMemOperand() ||
Dan Gohmanc76909a2009-09-25 20:36:54 +0000114 !(*MI->memoperands_begin())->getValue() ||
115 (*MI->memoperands_begin())->isVolatile())
Dan Gohman3311a1f2009-01-30 02:49:14 +0000116 return 0;
117
Dan Gohmanc76909a2009-09-25 20:36:54 +0000118 const Value *V = (*MI->memoperands_begin())->getValue();
Dan Gohman3311a1f2009-01-30 02:49:14 +0000119 if (!V)
120 return 0;
121
122 V = getUnderlyingObject(V);
Evan Chengff89dcb2009-10-18 18:16:27 +0000123 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
124 // For now, ignore PseudoSourceValues which may alias LLVM IR values
125 // because the code that uses this function has no way to cope with
126 // such aliases.
Evan Cheng38bdfc62009-10-18 19:58:47 +0000127 if (PSV->isAliased(MFI))
Evan Chengff89dcb2009-10-18 18:16:27 +0000128 return 0;
Andrew Trickf405b1a2011-05-05 19:24:06 +0000129
David Goodwin980d4942009-11-09 19:22:17 +0000130 MayAlias = PSV->mayAlias(MFI);
Evan Chengff89dcb2009-10-18 18:16:27 +0000131 return V;
132 }
Dan Gohman3311a1f2009-01-30 02:49:14 +0000133
Evan Chengff89dcb2009-10-18 18:16:27 +0000134 if (isIdentifiedObject(V))
135 return V;
136
137 return 0;
Dan Gohman3311a1f2009-01-30 02:49:14 +0000138}
139
Andrew Trick918f38a2012-04-20 20:05:21 +0000140void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
141 BB = bb;
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000142}
143
Andrew Trick953be892012-03-07 23:00:49 +0000144void ScheduleDAGInstrs::finishBlock() {
Andrew Tricka30444a2012-04-20 20:24:33 +0000145 // Subclasses should no longer refer to the old block.
Andrew Trick918f38a2012-04-20 20:05:21 +0000146 BB = 0;
Andrew Trick47c14452012-03-07 05:21:52 +0000147}
148
Andrew Trick702d4892012-02-24 07:04:55 +0000149/// Initialize the map with the number of registers.
Andrew Trick035ec402012-03-07 23:00:57 +0000150void Reg2SUnitsMap::setRegLimit(unsigned Limit) {
Andrew Trick702d4892012-02-24 07:04:55 +0000151 PhysRegSet.setUniverse(Limit);
152 SUnits.resize(Limit);
153}
154
155/// Clear the map without deallocating storage.
Andrew Trick035ec402012-03-07 23:00:57 +0000156void Reg2SUnitsMap::clear() {
Andrew Trick702d4892012-02-24 07:04:55 +0000157 for (const_iterator I = reg_begin(), E = reg_end(); I != E; ++I) {
158 SUnits[*I].clear();
159 }
160 PhysRegSet.clear();
161}
162
Andrew Trick47c14452012-03-07 05:21:52 +0000163/// Initialize the DAG and common scheduler state for the current scheduling
164/// region. This does not actually create the DAG, only clears it. The
165/// scheduling driver may call BuildSchedGraph multiple times per scheduling
166/// region.
167void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
168 MachineBasicBlock::iterator begin,
169 MachineBasicBlock::iterator end,
170 unsigned endcount) {
Andrew Trick918f38a2012-04-20 20:05:21 +0000171 assert(bb == BB && "startBlock should set BB");
Andrew Trick68675c62012-03-09 04:29:02 +0000172 RegionBegin = begin;
173 RegionEnd = end;
Andrew Trickcf46b5a2012-03-07 23:00:52 +0000174 EndIndex = endcount;
Andrew Trick17d35e52012-03-14 04:00:41 +0000175 MISUnitMap.clear();
Andrew Trick47c14452012-03-07 05:21:52 +0000176
Andrew Trick47c14452012-03-07 05:21:52 +0000177 ScheduleDAG::clearDAG();
178}
179
180/// Close the current scheduling region. Don't clear any state in case the
181/// driver wants to refer to the previous scheduling region.
182void ScheduleDAGInstrs::exitRegion() {
183 // Nothing to do.
184}
185
Andrew Trick953be892012-03-07 23:00:49 +0000186/// addSchedBarrierDeps - Add dependencies from instructions in the current
Evan Chengec6906b2010-10-23 02:10:46 +0000187/// list of instructions being scheduled to scheduling barrier by adding
188/// the exit SU to the register defs and use list. This is because we want to
189/// make sure instructions which define registers that are either used by
190/// the terminator or are live-out are properly scheduled. This is
191/// especially important when the definition latency of the return value(s)
192/// are too high to be hidden by the branch or when the liveout registers
193/// used by instructions in the fallthrough block.
Andrew Trick953be892012-03-07 23:00:49 +0000194void ScheduleDAGInstrs::addSchedBarrierDeps() {
Andrew Trick68675c62012-03-09 04:29:02 +0000195 MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : 0;
Evan Chengec6906b2010-10-23 02:10:46 +0000196 ExitSU.setInstr(ExitMI);
197 bool AllDepKnown = ExitMI &&
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000198 (ExitMI->isCall() || ExitMI->isBarrier());
Evan Chengec6906b2010-10-23 02:10:46 +0000199 if (ExitMI && AllDepKnown) {
200 // If it's a call or a barrier, add dependencies on the defs and uses of
201 // instruction.
202 for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
203 const MachineOperand &MO = ExitMI->getOperand(i);
204 if (!MO.isReg() || MO.isDef()) continue;
205 unsigned Reg = MO.getReg();
206 if (Reg == 0) continue;
207
Andrew Trick3c58ba82012-01-14 02:17:18 +0000208 if (TRI->isPhysicalRegister(Reg))
Andrew Trickffd25262012-08-23 00:39:43 +0000209 Uses[Reg].push_back(PhysRegSUOper(&ExitSU, -1));
Andrew Trickd3a74862012-03-16 05:04:25 +0000210 else {
Andrew Trick3c58ba82012-01-14 02:17:18 +0000211 assert(!IsPostRA && "Virtual register encountered after regalloc.");
Andrew Trickd3a74862012-03-16 05:04:25 +0000212 addVRegUseDeps(&ExitSU, i);
213 }
Evan Chengec6906b2010-10-23 02:10:46 +0000214 }
215 } else {
216 // For others, e.g. fallthrough, conditional branch, assume the exit
Evan Chengde5fa932010-10-27 23:17:17 +0000217 // uses all the registers that are livein to the successor blocks.
Benjamin Kramera82d5262012-03-16 17:38:19 +0000218 assert(Uses.empty() && "Uses in set before adding deps?");
Evan Chengde5fa932010-10-27 23:17:17 +0000219 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
220 SE = BB->succ_end(); SI != SE; ++SI)
221 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
Andrew Trickf405b1a2011-05-05 19:24:06 +0000222 E = (*SI)->livein_end(); I != E; ++I) {
Evan Chengde5fa932010-10-27 23:17:17 +0000223 unsigned Reg = *I;
Benjamin Kramera82d5262012-03-16 17:38:19 +0000224 if (!Uses.contains(Reg))
Andrew Trickffd25262012-08-23 00:39:43 +0000225 Uses[Reg].push_back(PhysRegSUOper(&ExitSU, -1));
Evan Chengde5fa932010-10-27 23:17:17 +0000226 }
Evan Chengec6906b2010-10-23 02:10:46 +0000227 }
228}
229
Andrew Trick81a682a2012-02-23 01:52:38 +0000230/// MO is an operand of SU's instruction that defines a physical register. Add
231/// data dependencies from SU to any uses of the physical register.
Andrew Trickffd25262012-08-23 00:39:43 +0000232void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
233 const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
Andrew Trick81a682a2012-02-23 01:52:38 +0000234 assert(MO.isDef() && "expect physreg def");
235
236 // Ask the target if address-backscheduling is desirable, and if so how much.
237 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
Andrew Trick81a682a2012-02-23 01:52:38 +0000238
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000239 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
240 Alias.isValid(); ++Alias) {
Andrew Trick702d4892012-02-24 07:04:55 +0000241 if (!Uses.contains(*Alias))
Andrew Trick81a682a2012-02-23 01:52:38 +0000242 continue;
Andrew Trickffd25262012-08-23 00:39:43 +0000243 std::vector<PhysRegSUOper> &UseList = Uses[*Alias];
Andrew Trick81a682a2012-02-23 01:52:38 +0000244 for (unsigned i = 0, e = UseList.size(); i != e; ++i) {
Andrew Trickffd25262012-08-23 00:39:43 +0000245 SUnit *UseSU = UseList[i].SU;
Andrew Trick81a682a2012-02-23 01:52:38 +0000246 if (UseSU == SU)
247 continue;
Andrew Trick39817f92012-10-08 18:54:00 +0000248
Andrew Trick39817f92012-10-08 18:54:00 +0000249 // Adjust the dependence latency using operand def/use information,
250 // then allow the target to perform its own adjustments.
Andrew Trickffd25262012-08-23 00:39:43 +0000251 int UseOp = UseList[i].OpIdx;
Andrew Trickae692f22012-11-12 19:28:57 +0000252 MachineInstr *RegUse = 0;
253 SDep Dep;
254 if (UseOp < 0)
255 Dep = SDep(SU, SDep::Artificial);
256 else {
257 Dep = SDep(SU, SDep::Data, *Alias);
258 RegUse = UseSU->getInstr();
259 Dep.setMinLatency(
260 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx,
261 RegUse, UseOp, /*FindMin=*/true));
262 }
263 Dep.setLatency(
Andrew Tricka98f6002012-10-08 18:53:57 +0000264 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx,
265 RegUse, UseOp, /*FindMin=*/false));
Andrew Trickb7e02892012-06-05 21:11:27 +0000266
Andrew Trickae692f22012-11-12 19:28:57 +0000267 ST.adjustSchedDependency(SU, UseSU, Dep);
268 UseSU->addPred(Dep);
Andrew Trick81a682a2012-02-23 01:52:38 +0000269 }
270 }
271}
272
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000273/// addPhysRegDeps - Add register dependencies (data, anti, and output) from
274/// this SUnit to following instructions in the same scheduling region that
275/// depend the physical register referenced at OperIdx.
276void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
277 const MachineInstr *MI = SU->getInstr();
278 const MachineOperand &MO = MI->getOperand(OperIdx);
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000279
280 // Optionally add output and anti dependencies. For anti
281 // dependencies we use a latency of 0 because for a multi-issue
282 // target we want to allow the defining instruction to issue
283 // in the same cycle as the using instruction.
284 // TODO: Using a latency of 1 here for output dependencies assumes
285 // there's no cost for reusing registers.
286 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
Jakob Stoklund Olesen396618b2012-06-01 23:28:30 +0000287 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
288 Alias.isValid(); ++Alias) {
Andrew Trick702d4892012-02-24 07:04:55 +0000289 if (!Defs.contains(*Alias))
Andrew Trick81a682a2012-02-23 01:52:38 +0000290 continue;
Andrew Trickffd25262012-08-23 00:39:43 +0000291 std::vector<PhysRegSUOper> &DefList = Defs[*Alias];
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000292 for (unsigned i = 0, e = DefList.size(); i != e; ++i) {
Andrew Trickffd25262012-08-23 00:39:43 +0000293 SUnit *DefSU = DefList[i].SU;
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000294 if (DefSU == &ExitSU)
295 continue;
296 if (DefSU != SU &&
297 (Kind != SDep::Output || !MO.isDead() ||
298 !DefSU->getInstr()->registerDefIsDead(*Alias))) {
299 if (Kind == SDep::Anti)
Andrew Tricka78d3222012-11-06 03:13:46 +0000300 DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000301 else {
Andrew Tricka78d3222012-11-06 03:13:46 +0000302 SDep Dep(SU, Kind, /*Reg=*/*Alias);
303 unsigned OutLatency =
Andrew Trick412cd2f2012-10-10 05:43:09 +0000304 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr());
Andrew Tricka78d3222012-11-06 03:13:46 +0000305 Dep.setMinLatency(OutLatency);
306 Dep.setLatency(OutLatency);
307 DefSU->addPred(Dep);
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000308 }
309 }
310 }
311 }
312
Andrew Trick81a682a2012-02-23 01:52:38 +0000313 if (!MO.isDef()) {
314 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
315 // retrieve the existing SUnits list for this register's uses.
316 // Push this SUnit on the use list.
Andrew Trickffd25262012-08-23 00:39:43 +0000317 Uses[MO.getReg()].push_back(PhysRegSUOper(SU, OperIdx));
Andrew Trick81a682a2012-02-23 01:52:38 +0000318 }
319 else {
Andrew Trickffd25262012-08-23 00:39:43 +0000320 addPhysRegDataDeps(SU, OperIdx);
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000321
Andrew Trick81a682a2012-02-23 01:52:38 +0000322 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
323 // retrieve the existing SUnits list for this register's defs.
Andrew Trickffd25262012-08-23 00:39:43 +0000324 std::vector<PhysRegSUOper> &DefList = Defs[MO.getReg()];
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000325
Andrew Trick81a682a2012-02-23 01:52:38 +0000326 // clear this register's use list
Andrew Trick702d4892012-02-24 07:04:55 +0000327 if (Uses.contains(MO.getReg()))
328 Uses[MO.getReg()].clear();
Andrew Trick81a682a2012-02-23 01:52:38 +0000329
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000330 if (!MO.isDead())
331 DefList.clear();
332
333 // Calls will not be reordered because of chain dependencies (see
334 // below). Since call operands are dead, calls may continue to be added
335 // to the DefList making dependence checking quadratic in the size of
336 // the block. Instead, we leave only one call at the back of the
337 // DefList.
338 if (SU->isCall) {
Andrew Trickffd25262012-08-23 00:39:43 +0000339 while (!DefList.empty() && DefList.back().SU->isCall)
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000340 DefList.pop_back();
341 }
Andrew Trick81a682a2012-02-23 01:52:38 +0000342 // Defs are pushed in the order they are visited and never reordered.
Andrew Trickffd25262012-08-23 00:39:43 +0000343 DefList.push_back(PhysRegSUOper(SU, OperIdx));
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000344 }
345}
346
Andrew Trick3c58ba82012-01-14 02:17:18 +0000347/// addVRegDefDeps - Add register output and data dependencies from this SUnit
348/// to instructions that occur later in the same scheduling region if they read
349/// from or write to the virtual register defined at OperIdx.
350///
351/// TODO: Hoist loop induction variable increments. This has to be
352/// reevaluated. Generally, IV scheduling should be done before coalescing.
353void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
354 const MachineInstr *MI = SU->getInstr();
355 unsigned Reg = MI->getOperand(OperIdx).getReg();
356
Andrew Trick4b72ada2012-07-28 01:48:15 +0000357 // Singly defined vregs do not have output/anti dependencies.
Andrew Trick2fc09772012-02-22 18:34:49 +0000358 // The current operand is a def, so we have at least one.
Andrew Trick4b72ada2012-07-28 01:48:15 +0000359 // Check here if there are any others...
Andrew Trick8b5704f2012-07-30 23:48:17 +0000360 if (MRI.hasOneDef(Reg))
Andrew Trick4b72ada2012-07-28 01:48:15 +0000361 return;
Andrew Trickcc77b542012-02-22 06:08:13 +0000362
Andrew Trick3c58ba82012-01-14 02:17:18 +0000363 // Add output dependence to the next nearest def of this vreg.
364 //
365 // Unless this definition is dead, the output dependence should be
366 // transitively redundant with antidependencies from this definition's
367 // uses. We're conservative for now until we have a way to guarantee the uses
368 // are not eliminated sometime during scheduling. The output dependence edge
369 // is also useful if output latency exceeds def-use latency.
Andrew Trickc0ccb8b2012-04-20 20:05:28 +0000370 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000371 if (DefI == VRegDefs.end())
372 VRegDefs.insert(VReg2SUnit(Reg, SU));
373 else {
374 SUnit *DefSU = DefI->SU;
375 if (DefSU != SU && DefSU != &ExitSU) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000376 SDep Dep(SU, SDep::Output, Reg);
Andrew Trick412cd2f2012-10-10 05:43:09 +0000377 unsigned OutLatency =
378 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr());
Andrew Tricka78d3222012-11-06 03:13:46 +0000379 Dep.setMinLatency(OutLatency);
380 Dep.setLatency(OutLatency);
381 DefSU->addPred(Dep);
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000382 }
383 DefI->SU = SU;
Andrew Trick3c58ba82012-01-14 02:17:18 +0000384 }
Andrew Trick3c58ba82012-01-14 02:17:18 +0000385}
386
Andrew Trickb4566a92012-02-22 06:08:11 +0000387/// addVRegUseDeps - Add a register data dependency if the instruction that
388/// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
389/// register antidependency from this SUnit to instructions that occur later in
390/// the same scheduling region if they write the virtual register.
391///
392/// TODO: Handle ExitSU "uses" properly.
Andrew Trick3c58ba82012-01-14 02:17:18 +0000393void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
Andrew Trickb4566a92012-02-22 06:08:11 +0000394 MachineInstr *MI = SU->getInstr();
395 unsigned Reg = MI->getOperand(OperIdx).getReg();
396
397 // Lookup this operand's reaching definition.
398 assert(LIS && "vreg dependencies requires LiveIntervals");
Jakob Stoklund Olesen93e29ce2012-05-20 02:44:38 +0000399 LiveRangeQuery LRQ(LIS->getInterval(Reg), LIS->getInstructionIndex(MI));
400 VNInfo *VNI = LRQ.valueIn();
Andrew Trickc3ad8852012-04-24 18:04:41 +0000401
Andrew Trick63d578b2012-02-23 03:16:24 +0000402 // VNI will be valid because MachineOperand::readsReg() is checked by caller.
Jakob Stoklund Olesen93e29ce2012-05-20 02:44:38 +0000403 assert(VNI && "No value to read by operand");
Andrew Trickb4566a92012-02-22 06:08:11 +0000404 MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def);
Andrew Trick63d578b2012-02-23 03:16:24 +0000405 // Phis and other noninstructions (after coalescing) have a NULL Def.
Andrew Trickb4566a92012-02-22 06:08:11 +0000406 if (Def) {
407 SUnit *DefSU = getSUnit(Def);
408 if (DefSU) {
409 // The reaching Def lives within this scheduling region.
410 // Create a data dependence.
Andrew Tricka78d3222012-11-06 03:13:46 +0000411 SDep dep(DefSU, SDep::Data, Reg);
Andrew Tricka98f6002012-10-08 18:53:57 +0000412 // Adjust the dependence latency using operand def/use information, then
413 // allow the target to perform its own adjustments.
414 int DefOp = Def->findRegisterDefOperandIdx(Reg);
415 dep.setLatency(
416 SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx, false));
417 dep.setMinLatency(
418 SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx, true));
Andrew Trickb7e02892012-06-05 21:11:27 +0000419
Andrew Tricka98f6002012-10-08 18:53:57 +0000420 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
421 ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
Andrew Trickb4566a92012-02-22 06:08:11 +0000422 SU->addPred(dep);
423 }
424 }
Andrew Trick3c58ba82012-01-14 02:17:18 +0000425
426 // Add antidependence to the following def of the vreg it uses.
Andrew Trickc0ccb8b2012-04-20 20:05:28 +0000427 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000428 if (DefI != VRegDefs.end() && DefI->SU != SU)
Andrew Tricka78d3222012-11-06 03:13:46 +0000429 DefI->SU->addPred(SDep(SU, SDep::Anti, Reg));
Andrew Trickb4566a92012-02-22 06:08:11 +0000430}
Andrew Trick3c58ba82012-01-14 02:17:18 +0000431
Andrew Trickeb05b972012-05-15 18:59:41 +0000432/// Return true if MI is an instruction we are unable to reason about
433/// (like a call or something with unmodeled side effects).
434static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
435 if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
Jakob Stoklund Olesenf036f7a2012-08-29 21:19:21 +0000436 (MI->hasOrderedMemoryRef() &&
Andrew Trickeb05b972012-05-15 18:59:41 +0000437 (!MI->mayLoad() || !MI->isInvariantLoad(AA))))
438 return true;
439 return false;
440}
441
442// This MI might have either incomplete info, or known to be unsafe
443// to deal with (i.e. volatile object).
444static inline bool isUnsafeMemoryObject(MachineInstr *MI,
445 const MachineFrameInfo *MFI) {
446 if (!MI || MI->memoperands_empty())
447 return true;
448 // We purposefully do no check for hasOneMemOperand() here
449 // in hope to trigger an assert downstream in order to
450 // finish implementation.
451 if ((*MI->memoperands_begin())->isVolatile() ||
452 MI->hasUnmodeledSideEffects())
453 return true;
454
455 const Value *V = (*MI->memoperands_begin())->getValue();
456 if (!V)
457 return true;
458
459 V = getUnderlyingObject(V);
460 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
461 // Similarly to getUnderlyingObjectForInstr:
462 // For now, ignore PseudoSourceValues which may alias LLVM IR values
463 // because the code that uses this function has no way to cope with
464 // such aliases.
465 if (PSV->isAliased(MFI))
466 return true;
467 }
468 // Does this pointer refer to a distinct and identifiable object?
469 if (!isIdentifiedObject(V))
470 return true;
471
472 return false;
473}
474
475/// This returns true if the two MIs need a chain edge betwee them.
476/// If these are not even memory operations, we still may need
477/// chain deps between them. The question really is - could
478/// these two MIs be reordered during scheduling from memory dependency
479/// point of view.
480static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
481 MachineInstr *MIa,
482 MachineInstr *MIb) {
483 // Cover a trivial case - no edge is need to itself.
484 if (MIa == MIb)
485 return false;
486
487 if (isUnsafeMemoryObject(MIa, MFI) || isUnsafeMemoryObject(MIb, MFI))
488 return true;
489
490 // If we are dealing with two "normal" loads, we do not need an edge
491 // between them - they could be reordered.
492 if (!MIa->mayStore() && !MIb->mayStore())
493 return false;
494
495 // To this point analysis is generic. From here on we do need AA.
496 if (!AA)
497 return true;
498
499 MachineMemOperand *MMOa = *MIa->memoperands_begin();
500 MachineMemOperand *MMOb = *MIb->memoperands_begin();
501
502 // FIXME: Need to handle multiple memory operands to support all targets.
503 if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
504 llvm_unreachable("Multiple memory operands.");
505
506 // The following interface to AA is fashioned after DAGCombiner::isAlias
507 // and operates with MachineMemOperand offset with some important
508 // assumptions:
509 // - LLVM fundamentally assumes flat address spaces.
510 // - MachineOperand offset can *only* result from legalization and
511 // cannot affect queries other than the trivial case of overlap
512 // checking.
513 // - These offsets never wrap and never step outside
514 // of allocated objects.
515 // - There should never be any negative offsets here.
516 //
517 // FIXME: Modify API to hide this math from "user"
518 // FIXME: Even before we go to AA we can reason locally about some
519 // memory objects. It can save compile time, and possibly catch some
520 // corner cases not currently covered.
521
522 assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
523 assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
524
525 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
526 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
527 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
528
529 AliasAnalysis::AliasResult AAResult = AA->alias(
530 AliasAnalysis::Location(MMOa->getValue(), Overlapa,
531 MMOa->getTBAAInfo()),
532 AliasAnalysis::Location(MMOb->getValue(), Overlapb,
533 MMOb->getTBAAInfo()));
534
535 return (AAResult != AliasAnalysis::NoAlias);
536}
537
538/// This recursive function iterates over chain deps of SUb looking for
539/// "latest" node that needs a chain edge to SUa.
540static unsigned
541iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI,
542 SUnit *SUa, SUnit *SUb, SUnit *ExitSU, unsigned *Depth,
543 SmallPtrSet<const SUnit*, 16> &Visited) {
544 if (!SUa || !SUb || SUb == ExitSU)
545 return *Depth;
546
547 // Remember visited nodes.
548 if (!Visited.insert(SUb))
549 return *Depth;
550 // If there is _some_ dependency already in place, do not
551 // descend any further.
552 // TODO: Need to make sure that if that dependency got eliminated or ignored
553 // for any reason in the future, we would not violate DAG topology.
554 // Currently it does not happen, but makes an implicit assumption about
555 // future implementation.
556 //
557 // Independently, if we encounter node that is some sort of global
558 // object (like a call) we already have full set of dependencies to it
559 // and we can stop descending.
560 if (SUa->isSucc(SUb) ||
561 isGlobalMemoryObject(AA, SUb->getInstr()))
562 return *Depth;
563
564 // If we do need an edge, or we have exceeded depth budget,
565 // add that edge to the predecessors chain of SUb,
566 // and stop descending.
567 if (*Depth > 200 ||
568 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000569 SUb->addPred(SDep(SUa, SDep::MayAliasMem));
Andrew Trickeb05b972012-05-15 18:59:41 +0000570 return *Depth;
571 }
572 // Track current depth.
573 (*Depth)++;
574 // Iterate over chain dependencies only.
575 for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end();
576 I != E; ++I)
577 if (I->isCtrl())
578 iterateChainSucc (AA, MFI, SUa, I->getSUnit(), ExitSU, Depth, Visited);
579 return *Depth;
580}
581
582/// This function assumes that "downward" from SU there exist
583/// tail/leaf of already constructed DAG. It iterates downward and
584/// checks whether SU can be aliasing any node dominated
585/// by it.
586static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI,
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000587 SUnit *SU, SUnit *ExitSU, std::set<SUnit *> &CheckList,
588 unsigned LatencyToLoad) {
Andrew Trickeb05b972012-05-15 18:59:41 +0000589 if (!SU)
590 return;
591
592 SmallPtrSet<const SUnit*, 16> Visited;
593 unsigned Depth = 0;
594
595 for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end();
596 I != IE; ++I) {
597 if (SU == *I)
598 continue;
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000599 if (MIsNeedChainEdge(AA, MFI, SU->getInstr(), (*I)->getInstr())) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000600 SDep Dep(SU, SDep::MayAliasMem);
601 Dep.setLatency(((*I)->getInstr()->mayLoad()) ? LatencyToLoad : 0);
602 (*I)->addPred(Dep);
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000603 }
Andrew Trickeb05b972012-05-15 18:59:41 +0000604 // Now go through all the chain successors and iterate from them.
605 // Keep track of visited nodes.
606 for (SUnit::const_succ_iterator J = (*I)->Succs.begin(),
607 JE = (*I)->Succs.end(); J != JE; ++J)
608 if (J->isCtrl())
609 iterateChainSucc (AA, MFI, SU, J->getSUnit(),
610 ExitSU, &Depth, Visited);
611 }
612}
613
614/// Check whether two objects need a chain edge, if so, add it
615/// otherwise remember the rejected SU.
616static inline
617void addChainDependency (AliasAnalysis *AA, const MachineFrameInfo *MFI,
618 SUnit *SUa, SUnit *SUb,
619 std::set<SUnit *> &RejectList,
620 unsigned TrueMemOrderLatency = 0,
621 bool isNormalMemory = false) {
622 // If this is a false dependency,
623 // do not add the edge, but rememeber the rejected node.
624 if (!EnableAASchedMI ||
Andrew Tricka78d3222012-11-06 03:13:46 +0000625 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
626 SDep Dep(SUa, isNormalMemory ? SDep::MayAliasMem : SDep::Barrier);
627 Dep.setLatency(TrueMemOrderLatency);
628 SUb->addPred(Dep);
629 }
Andrew Trickeb05b972012-05-15 18:59:41 +0000630 else {
631 // Duplicate entries should be ignored.
632 RejectList.insert(SUb);
633 DEBUG(dbgs() << "\tReject chain dep between SU("
634 << SUa->NodeNum << ") and SU("
635 << SUb->NodeNum << ")\n");
636 }
637}
638
Andrew Trickb4566a92012-02-22 06:08:11 +0000639/// Create an SUnit for each real instruction, numbered in top-down toplological
640/// order. The instruction order A < B, implies that no edge exists from B to A.
641///
642/// Map each real instruction to its SUnit.
643///
Andrew Trick17d35e52012-03-14 04:00:41 +0000644/// After initSUnits, the SUnits vector cannot be resized and the scheduler may
645/// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
646/// instead of pointers.
647///
648/// MachineScheduler relies on initSUnits numbering the nodes by their order in
649/// the original instruction list.
Andrew Trickb4566a92012-02-22 06:08:11 +0000650void ScheduleDAGInstrs::initSUnits() {
651 // We'll be allocating one SUnit for each real instruction in the region,
652 // which is contained within a basic block.
653 SUnits.reserve(BB->size());
654
Andrew Trick68675c62012-03-09 04:29:02 +0000655 for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
Andrew Trickb4566a92012-02-22 06:08:11 +0000656 MachineInstr *MI = I;
657 if (MI->isDebugValue())
658 continue;
659
Andrew Trick953be892012-03-07 23:00:49 +0000660 SUnit *SU = newSUnit(MI);
Andrew Trickb4566a92012-02-22 06:08:11 +0000661 MISUnitMap[MI] = SU;
662
663 SU->isCall = MI->isCall();
664 SU->isCommutable = MI->isCommutable();
665
666 // Assign the Latency field of SU using target-provided information.
Andrew Trick412cd2f2012-10-10 05:43:09 +0000667 SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
Andrew Trickb4566a92012-02-22 06:08:11 +0000668 }
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000669}
670
Andrew Trick006e1ab2012-04-24 17:56:43 +0000671/// If RegPressure is non null, compute register pressure as a side effect. The
672/// DAG builder is an efficient place to do it because it already visits
673/// operands.
674void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
675 RegPressureTracker *RPTracker) {
Andrew Trickb4566a92012-02-22 06:08:11 +0000676 // Create an SUnit for each real instruction.
677 initSUnits();
Dan Gohman343f0c02008-11-19 23:18:57 +0000678
Dan Gohman6a9041e2008-12-04 01:35:46 +0000679 // We build scheduling units by walking a block's instruction list from bottom
680 // to top.
681
David Goodwin980d4942009-11-09 19:22:17 +0000682 // Remember where a generic side-effecting instruction is as we procede.
683 SUnit *BarrierChain = 0, *AliasChain = 0;
Dan Gohman6a9041e2008-12-04 01:35:46 +0000684
David Goodwin980d4942009-11-09 19:22:17 +0000685 // Memory references to specific known memory locations are tracked
686 // so that they can be given more precise dependencies. We track
687 // separately the known memory locations that may alias and those
688 // that are known not to alias
Sergei Larin009cf9e2012-11-15 17:45:50 +0000689 MapVector<const Value *, SUnit *> AliasMemDefs, NonAliasMemDefs;
690 MapVector<const Value *, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
Andrew Trickeb05b972012-05-15 18:59:41 +0000691 std::set<SUnit*> RejectMemNodes;
Dan Gohman6a9041e2008-12-04 01:35:46 +0000692
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000693 // Remove any stale debug info; sometimes BuildSchedGraph is called again
694 // without emitting the info from the previous call.
Devang Patelcf4cc842011-06-02 20:07:12 +0000695 DbgValues.clear();
696 FirstDbgValue = NULL;
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000697
Andrew Trick81a682a2012-02-23 01:52:38 +0000698 assert(Defs.empty() && Uses.empty() &&
699 "Only BuildGraph should update Defs/Uses");
Andrew Trick702d4892012-02-24 07:04:55 +0000700 Defs.setRegLimit(TRI->getNumRegs());
701 Uses.setRegLimit(TRI->getNumRegs());
Andrew Trick9b668532011-05-06 21:52:52 +0000702
Andrew Trick8ae3ac72012-02-22 21:59:00 +0000703 assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
704 // FIXME: Allow SparseSet to reserve space for the creation of virtual
705 // registers during scheduling. Don't artificially inflate the Universe
706 // because we want to assert that vregs are not created during DAG building.
707 VRegDefs.setUniverse(MRI.getNumVirtRegs());
Andrew Trick3c58ba82012-01-14 02:17:18 +0000708
Andrew Trick81a682a2012-02-23 01:52:38 +0000709 // Model data dependencies between instructions being scheduled and the
710 // ExitSU.
Andrew Trick953be892012-03-07 23:00:49 +0000711 addSchedBarrierDeps();
Andrew Trick81a682a2012-02-23 01:52:38 +0000712
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000713 // Walk the list of instructions, from bottom moving up.
Devang Patelcf4cc842011-06-02 20:07:12 +0000714 MachineInstr *PrevMI = NULL;
Andrew Trick68675c62012-03-09 04:29:02 +0000715 for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
Dan Gohman343f0c02008-11-19 23:18:57 +0000716 MII != MIE; --MII) {
717 MachineInstr *MI = prior(MII);
Devang Patelcf4cc842011-06-02 20:07:12 +0000718 if (MI && PrevMI) {
719 DbgValues.push_back(std::make_pair(PrevMI, MI));
720 PrevMI = NULL;
721 }
722
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000723 if (MI->isDebugValue()) {
Devang Patelcf4cc842011-06-02 20:07:12 +0000724 PrevMI = MI;
Dale Johannesenbfdf7f32010-03-10 22:13:47 +0000725 continue;
726 }
Andrew Trick006e1ab2012-04-24 17:56:43 +0000727 if (RPTracker) {
728 RPTracker->recede();
729 assert(RPTracker->getPos() == prior(MII) && "RPTracker can't find MI");
730 }
Devang Patelcf4cc842011-06-02 20:07:12 +0000731
Andrew Trick00707922012-04-13 23:29:54 +0000732 assert((!MI->isTerminator() || CanHandleTerminators) && !MI->isLabel() &&
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000733 "Cannot schedule terminators or labels!");
Dan Gohman343f0c02008-11-19 23:18:57 +0000734
Andrew Trickb4566a92012-02-22 06:08:11 +0000735 SUnit *SU = MISUnitMap[MI];
736 assert(SU && "No SUnit mapped to this MI");
Dan Gohman54e4c362008-12-09 22:54:47 +0000737
Dan Gohman6a9041e2008-12-04 01:35:46 +0000738 // Add register-based dependencies (data, anti, and output).
Dan Gohman343f0c02008-11-19 23:18:57 +0000739 for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
740 const MachineOperand &MO = MI->getOperand(j);
741 if (!MO.isReg()) continue;
742 unsigned Reg = MO.getReg();
743 if (Reg == 0) continue;
744
Andrew Trick7ebcaf42012-01-14 02:17:15 +0000745 if (TRI->isPhysicalRegister(Reg))
746 addPhysRegDeps(SU, j);
747 else {
748 assert(!IsPostRA && "Virtual register encountered!");
Andrew Trick3c58ba82012-01-14 02:17:18 +0000749 if (MO.isDef())
750 addVRegDefDeps(SU, j);
Andrew Trick63d578b2012-02-23 03:16:24 +0000751 else if (MO.readsReg()) // ignore undef operands
Andrew Trick3c58ba82012-01-14 02:17:18 +0000752 addVRegUseDeps(SU, j);
Dan Gohman343f0c02008-11-19 23:18:57 +0000753 }
754 }
Dan Gohman6a9041e2008-12-04 01:35:46 +0000755
756 // Add chain dependencies.
David Goodwin7c9b1ac2009-11-02 17:06:28 +0000757 // Chain dependencies used to enforce memory order should have
758 // latency of 0 (except for true dependency of Store followed by
759 // aliased Load... we estimate that with a single cycle of latency
760 // assuming the hardware will bypass)
Dan Gohman6a9041e2008-12-04 01:35:46 +0000761 // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
762 // after stack slots are lowered to actual addresses.
763 // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
764 // produce more precise dependence information.
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000765 unsigned TrueMemOrderLatency = MI->mayStore() ? 1 : 0;
Andrew Trickeb05b972012-05-15 18:59:41 +0000766 if (isGlobalMemoryObject(AA, MI)) {
David Goodwin980d4942009-11-09 19:22:17 +0000767 // Be conservative with these and add dependencies on all memory
768 // references, even those that are known to not alias.
Sergei Larin009cf9e2012-11-15 17:45:50 +0000769 for (MapVector<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000770 NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000771 I->second->addPred(SDep(SU, SDep::Barrier));
Dan Gohman6a9041e2008-12-04 01:35:46 +0000772 }
Sergei Larin009cf9e2012-11-15 17:45:50 +0000773 for (MapVector<const Value *, std::vector<SUnit *> >::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000774 NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
Andrew Tricka78d3222012-11-06 03:13:46 +0000775 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
776 SDep Dep(SU, SDep::Barrier);
777 Dep.setLatency(TrueMemOrderLatency);
778 I->second[i]->addPred(Dep);
779 }
Dan Gohman6a9041e2008-12-04 01:35:46 +0000780 }
David Goodwin980d4942009-11-09 19:22:17 +0000781 // Add SU to the barrier chain.
782 if (BarrierChain)
Andrew Tricka78d3222012-11-06 03:13:46 +0000783 BarrierChain->addPred(SDep(SU, SDep::Barrier));
David Goodwin980d4942009-11-09 19:22:17 +0000784 BarrierChain = SU;
Andrew Trickeb05b972012-05-15 18:59:41 +0000785 // This is a barrier event that acts as a pivotal node in the DAG,
786 // so it is safe to clear list of exposed nodes.
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000787 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
788 TrueMemOrderLatency);
Andrew Trickeb05b972012-05-15 18:59:41 +0000789 RejectMemNodes.clear();
790 NonAliasMemDefs.clear();
791 NonAliasMemUses.clear();
David Goodwin980d4942009-11-09 19:22:17 +0000792
793 // fall-through
794 new_alias_chain:
795 // Chain all possibly aliasing memory references though SU.
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000796 if (AliasChain) {
797 unsigned ChainLatency = 0;
798 if (AliasChain->getInstr()->mayLoad())
799 ChainLatency = TrueMemOrderLatency;
800 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes,
801 ChainLatency);
802 }
David Goodwin980d4942009-11-09 19:22:17 +0000803 AliasChain = SU;
804 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
Andrew Trickeb05b972012-05-15 18:59:41 +0000805 addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
806 TrueMemOrderLatency);
Sergei Larin009cf9e2012-11-15 17:45:50 +0000807 for (MapVector<const Value *, SUnit *>::iterator I = AliasMemDefs.begin(),
Andrew Trickeb05b972012-05-15 18:59:41 +0000808 E = AliasMemDefs.end(); I != E; ++I)
809 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
Sergei Larin009cf9e2012-11-15 17:45:50 +0000810 for (MapVector<const Value *, std::vector<SUnit *> >::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000811 AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
812 for (unsigned i = 0, e = I->second.size(); i != e; ++i)
Andrew Trickeb05b972012-05-15 18:59:41 +0000813 addChainDependency(AA, MFI, SU, I->second[i], RejectMemNodes,
814 TrueMemOrderLatency);
David Goodwin980d4942009-11-09 19:22:17 +0000815 }
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000816 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
817 TrueMemOrderLatency);
David Goodwin980d4942009-11-09 19:22:17 +0000818 PendingLoads.clear();
819 AliasMemDefs.clear();
820 AliasMemUses.clear();
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000821 } else if (MI->mayStore()) {
David Goodwina9e61072009-11-03 20:15:00 +0000822 bool MayAlias = true;
David Goodwina9e61072009-11-03 20:15:00 +0000823 if (const Value *V = getUnderlyingObjectForInstr(MI, MFI, MayAlias)) {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000824 // A store to a specific PseudoSourceValue. Add precise dependencies.
David Goodwin980d4942009-11-09 19:22:17 +0000825 // Record the def in MemDefs, first adding a dep if there is
826 // an existing def.
Sergei Larin009cf9e2012-11-15 17:45:50 +0000827 MapVector<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000828 ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
Sergei Larin009cf9e2012-11-15 17:45:50 +0000829 MapVector<const Value *, SUnit *>::iterator IE =
David Goodwin980d4942009-11-09 19:22:17 +0000830 ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
831 if (I != IE) {
Sergei Larin009cf9e2012-11-15 17:45:50 +0000832 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true);
Dan Gohman6a9041e2008-12-04 01:35:46 +0000833 I->second = SU;
834 } else {
David Goodwin980d4942009-11-09 19:22:17 +0000835 if (MayAlias)
836 AliasMemDefs[V] = SU;
837 else
838 NonAliasMemDefs[V] = SU;
Dan Gohman6a9041e2008-12-04 01:35:46 +0000839 }
840 // Handle the uses in MemUses, if there are any.
Sergei Larin009cf9e2012-11-15 17:45:50 +0000841 MapVector<const Value *, std::vector<SUnit *> >::iterator J =
David Goodwin980d4942009-11-09 19:22:17 +0000842 ((MayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
Sergei Larin009cf9e2012-11-15 17:45:50 +0000843 MapVector<const Value *, std::vector<SUnit *> >::iterator JE =
David Goodwin980d4942009-11-09 19:22:17 +0000844 ((MayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
845 if (J != JE) {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000846 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
Andrew Trickeb05b972012-05-15 18:59:41 +0000847 addChainDependency(AA, MFI, SU, J->second[i], RejectMemNodes,
848 TrueMemOrderLatency, true);
Dan Gohman6a9041e2008-12-04 01:35:46 +0000849 J->second.clear();
850 }
David Goodwina9e61072009-11-03 20:15:00 +0000851 if (MayAlias) {
David Goodwin980d4942009-11-09 19:22:17 +0000852 // Add dependencies from all the PendingLoads, i.e. loads
853 // with no underlying object.
David Goodwina9e61072009-11-03 20:15:00 +0000854 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
Andrew Trickeb05b972012-05-15 18:59:41 +0000855 addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
856 TrueMemOrderLatency);
David Goodwin980d4942009-11-09 19:22:17 +0000857 // Add dependence on alias chain, if needed.
858 if (AliasChain)
Andrew Trickeb05b972012-05-15 18:59:41 +0000859 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
860 // But we also should check dependent instructions for the
861 // SU in question.
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000862 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
863 TrueMemOrderLatency);
David Goodwina9e61072009-11-03 20:15:00 +0000864 }
David Goodwin980d4942009-11-09 19:22:17 +0000865 // Add dependence on barrier chain, if needed.
Andrew Trickeb05b972012-05-15 18:59:41 +0000866 // There is no point to check aliasing on barrier event. Even if
867 // SU and barrier _could_ be reordered, they should not. In addition,
868 // we have lost all RejectMemNodes below barrier.
David Goodwin980d4942009-11-09 19:22:17 +0000869 if (BarrierChain)
Andrew Tricka78d3222012-11-06 03:13:46 +0000870 BarrierChain->addPred(SDep(SU, SDep::Barrier));
David Goodwin5be870a2009-11-05 00:16:44 +0000871 } else {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000872 // Treat all other stores conservatively.
David Goodwin980d4942009-11-09 19:22:17 +0000873 goto new_alias_chain;
David Goodwin7c9b1ac2009-11-02 17:06:28 +0000874 }
Evan Chengec6906b2010-10-23 02:10:46 +0000875
876 if (!ExitSU.isPred(SU))
877 // Push store's up a bit to avoid them getting in between cmp
878 // and branches.
Andrew Tricka78d3222012-11-06 03:13:46 +0000879 ExitSU.addPred(SDep(SU, SDep::Artificial));
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000880 } else if (MI->mayLoad()) {
David Goodwina9e61072009-11-03 20:15:00 +0000881 bool MayAlias = true;
Dan Gohmana70dca12009-10-09 23:27:56 +0000882 if (MI->isInvariantLoad(AA)) {
Dan Gohman6a9041e2008-12-04 01:35:46 +0000883 // Invariant load, no chain dependencies needed!
David Goodwin5be870a2009-11-05 00:16:44 +0000884 } else {
Andrew Trickf405b1a2011-05-05 19:24:06 +0000885 if (const Value *V =
David Goodwin980d4942009-11-09 19:22:17 +0000886 getUnderlyingObjectForInstr(MI, MFI, MayAlias)) {
887 // A load from a specific PseudoSourceValue. Add precise dependencies.
Sergei Larin009cf9e2012-11-15 17:45:50 +0000888 MapVector<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000889 ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
Sergei Larin009cf9e2012-11-15 17:45:50 +0000890 MapVector<const Value *, SUnit *>::iterator IE =
David Goodwin980d4942009-11-09 19:22:17 +0000891 ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
892 if (I != IE)
Andrew Trickeb05b972012-05-15 18:59:41 +0000893 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true);
David Goodwin980d4942009-11-09 19:22:17 +0000894 if (MayAlias)
895 AliasMemUses[V].push_back(SU);
Andrew Trickf405b1a2011-05-05 19:24:06 +0000896 else
David Goodwin980d4942009-11-09 19:22:17 +0000897 NonAliasMemUses[V].push_back(SU);
898 } else {
899 // A load with no underlying object. Depend on all
900 // potentially aliasing stores.
Sergei Larin009cf9e2012-11-15 17:45:50 +0000901 for (MapVector<const Value *, SUnit *>::iterator I =
David Goodwin980d4942009-11-09 19:22:17 +0000902 AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
Andrew Trickeb05b972012-05-15 18:59:41 +0000903 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
Andrew Trickf405b1a2011-05-05 19:24:06 +0000904
David Goodwin980d4942009-11-09 19:22:17 +0000905 PendingLoads.push_back(SU);
906 MayAlias = true;
David Goodwina9e61072009-11-03 20:15:00 +0000907 }
Andrew Trickeb05b972012-05-15 18:59:41 +0000908 if (MayAlias)
Andrew Trick1c2d3c52012-06-13 02:39:03 +0000909 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, /*Latency=*/0);
David Goodwin980d4942009-11-09 19:22:17 +0000910 // Add dependencies on alias and barrier chains, if needed.
911 if (MayAlias && AliasChain)
Andrew Trickeb05b972012-05-15 18:59:41 +0000912 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
David Goodwin980d4942009-11-09 19:22:17 +0000913 if (BarrierChain)
Andrew Tricka78d3222012-11-06 03:13:46 +0000914 BarrierChain->addPred(SDep(SU, SDep::Barrier));
Andrew Trickf405b1a2011-05-05 19:24:06 +0000915 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000916 }
Dan Gohman343f0c02008-11-19 23:18:57 +0000917 }
Devang Patelcf4cc842011-06-02 20:07:12 +0000918 if (PrevMI)
919 FirstDbgValue = PrevMI;
Dan Gohman79ce2762009-01-15 19:20:50 +0000920
Andrew Trick81a682a2012-02-23 01:52:38 +0000921 Defs.clear();
922 Uses.clear();
Andrew Trick3c58ba82012-01-14 02:17:18 +0000923 VRegDefs.clear();
Dan Gohman79ce2762009-01-15 19:20:50 +0000924 PendingLoads.clear();
Dan Gohman343f0c02008-11-19 23:18:57 +0000925}
926
Dan Gohman343f0c02008-11-19 23:18:57 +0000927void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
Manman Renb720be62012-09-11 22:23:19 +0000928#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Dan Gohman343f0c02008-11-19 23:18:57 +0000929 SU->getInstr()->dump();
Manman Ren77e300e2012-09-06 19:06:06 +0000930#endif
Dan Gohman343f0c02008-11-19 23:18:57 +0000931}
932
933std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
934 std::string s;
935 raw_string_ostream oss(s);
Dan Gohman9e64bbb2009-02-10 23:27:53 +0000936 if (SU == &EntrySU)
937 oss << "<entry>";
938 else if (SU == &ExitSU)
939 oss << "<exit>";
940 else
941 SU->getInstr()->print(oss);
Dan Gohman343f0c02008-11-19 23:18:57 +0000942 return oss.str();
943}
944
Andrew Trick56b94c52012-03-07 00:18:22 +0000945/// Return the basic block label. It is not necessarilly unique because a block
946/// contains multiple scheduling regions. But it is fine for visualization.
947std::string ScheduleDAGInstrs::getDAGName() const {
948 return "dag." + BB->getFullName();
949}
Andrew Trick1e94e982012-10-15 18:02:27 +0000950
951namespace {
952/// \brief Manage the stack used by a reverse depth-first search over the DAG.
953class SchedDAGReverseDFS {
954 std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
955public:
956 bool isComplete() const { return DFSStack.empty(); }
957
958 void follow(const SUnit *SU) {
959 DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
960 }
961 void advance() { ++DFSStack.back().second; }
962
963 void backtrack() { DFSStack.pop_back(); }
964
965 const SUnit *getCurr() const { return DFSStack.back().first; }
966
967 SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
968
969 SUnit::const_pred_iterator getPredEnd() const {
970 return getCurr()->Preds.end();
971 }
972};
973} // anonymous
974
975void ScheduleDAGILP::resize(unsigned NumSUnits) {
976 ILPValues.resize(NumSUnits);
977}
978
979ILPValue ScheduleDAGILP::getILP(const SUnit *SU) {
980 return ILPValues[SU->NodeNum];
981}
982
983// A leaf node has an ILP of 1/1.
984static ILPValue initILP(const SUnit *SU) {
985 unsigned Cnt = SU->getInstr()->isTransient() ? 0 : 1;
986 return ILPValue(Cnt, 1 + SU->getDepth());
987}
988
989/// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
990/// search from this root.
991void ScheduleDAGILP::computeILP(const SUnit *Root) {
992 if (!IsBottomUp)
993 llvm_unreachable("Top-down ILP metric is unimplemnted");
994
995 SchedDAGReverseDFS DFS;
996 // Mark a node visited by validating it.
997 ILPValues[Root->NodeNum] = initILP(Root);
998 DFS.follow(Root);
999 for (;;) {
1000 // Traverse the leftmost path as far as possible.
1001 while (DFS.getPred() != DFS.getPredEnd()) {
1002 const SUnit *PredSU = DFS.getPred()->getSUnit();
1003 DFS.advance();
1004 // If the pred is already valid, skip it.
1005 if (ILPValues[PredSU->NodeNum].isValid())
1006 continue;
1007 ILPValues[PredSU->NodeNum] = initILP(PredSU);
1008 DFS.follow(PredSU);
1009 }
1010 // Visit the top of the stack in postorder and backtrack.
1011 unsigned PredCount = ILPValues[DFS.getCurr()->NodeNum].InstrCount;
1012 DFS.backtrack();
1013 if (DFS.isComplete())
1014 break;
1015 // Add the recently finished predecessor's bottom-up descendent count.
1016 ILPValues[DFS.getCurr()->NodeNum].InstrCount += PredCount;
1017 }
1018}
1019
1020#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1021void ILPValue::print(raw_ostream &OS) const {
1022 if (!isValid())
1023 OS << "BADILP";
1024 OS << InstrCount << " / " << Cycles << " = "
1025 << format("%g", ((double)InstrCount / Cycles));
1026}
1027
1028void ILPValue::dump() const {
1029 dbgs() << *this << '\n';
1030}
1031
1032namespace llvm {
1033
1034raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1035 Val.print(OS);
1036 return OS;
1037}
1038
1039} // namespace llvm
1040#endif // !NDEBUG || LLVM_ENABLE_DUMP