blob: 2d8b656bb12650dfa40b4ed56785a20308d75220 [file] [log] [blame]
Chris Lattner0d5644b2003-01-13 00:26:36 +00001//===-- TargetInstrInfo.cpp - Target Instruction Information --------------===//
Misha Brukman10468d82005-04-21 22:55:34 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman10468d82005-04-21 22:55:34 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner910b82f2002-10-28 23:55:33 +00009//
Chris Lattnerf6932b72005-01-19 06:53:34 +000010// This file implements the TargetInstrInfo class.
Chris Lattner910b82f2002-10-28 23:55:33 +000011//
12//===----------------------------------------------------------------------===//
13
Eric Christopher4fdc7652014-06-11 16:59:33 +000014#include "llvm/Target/TargetInstrInfo.h"
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +000015#include "llvm/CodeGen/MachineFrameInfo.h"
Lang Hames39609992013-11-29 03:07:54 +000016#include "llvm/CodeGen/MachineInstrBuilder.h"
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +000017#include "llvm/CodeGen/MachineMemOperand.h"
18#include "llvm/CodeGen/MachineRegisterInfo.h"
19#include "llvm/CodeGen/PseudoSourceValue.h"
20#include "llvm/CodeGen/ScoreboardHazardRecognizer.h"
Lang Hames39609992013-11-29 03:07:54 +000021#include "llvm/CodeGen/StackMaps.h"
Andrew Trick10d5be42013-11-17 01:36:23 +000022#include "llvm/IR/DataLayout.h"
Evan Cheng49d4c0b2010-10-06 06:27:31 +000023#include "llvm/MC/MCAsmInfo.h"
Evan Cheng8264e272011-06-29 01:14:12 +000024#include "llvm/MC/MCInstrItineraries.h"
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +000025#include "llvm/Support/CommandLine.h"
Chris Lattner01614192009-08-02 04:58:19 +000026#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +000027#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +000028#include "llvm/Target/TargetLowering.h"
29#include "llvm/Target/TargetMachine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/Target/TargetRegisterInfo.h"
Nick Lewycky0de20af2010-12-19 20:43:38 +000031#include <cctype>
Chris Lattnerf6932b72005-01-19 06:53:34 +000032using namespace llvm;
Chris Lattner910b82f2002-10-28 23:55:33 +000033
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +000034static cl::opt<bool> DisableHazardRecognizer(
35 "disable-sched-hazard", cl::Hidden, cl::init(false),
36 cl::desc("Disable hazard detection during preRA scheduling"));
Chris Lattnere98a3c32009-08-02 05:20:37 +000037
Chris Lattner0d5644b2003-01-13 00:26:36 +000038TargetInstrInfo::~TargetInstrInfo() {
Chris Lattner910b82f2002-10-28 23:55:33 +000039}
40
Evan Cheng8d71a752011-06-27 21:26:13 +000041const TargetRegisterClass*
Evan Cheng6cc775f2011-06-28 19:10:37 +000042TargetInstrInfo::getRegClass(const MCInstrDesc &MCID, unsigned OpNum,
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +000043 const TargetRegisterInfo *TRI,
44 const MachineFunction &MF) const {
Evan Cheng6cc775f2011-06-28 19:10:37 +000045 if (OpNum >= MCID.getNumOperands())
Craig Topperc0196b12014-04-14 00:51:57 +000046 return nullptr;
Evan Cheng8d71a752011-06-27 21:26:13 +000047
Evan Cheng6cc775f2011-06-28 19:10:37 +000048 short RegClass = MCID.OpInfo[OpNum].RegClass;
49 if (MCID.OpInfo[OpNum].isLookupPtrRegClass())
Jakob Stoklund Olesen3c52f022012-05-07 22:10:26 +000050 return TRI->getPointerRegClass(MF, RegClass);
Evan Cheng8d71a752011-06-27 21:26:13 +000051
52 // Instructions like INSERT_SUBREG do not have fixed register classes.
53 if (RegClass < 0)
Craig Topperc0196b12014-04-14 00:51:57 +000054 return nullptr;
Evan Cheng8d71a752011-06-27 21:26:13 +000055
56 // Otherwise just look it up normally.
57 return TRI->getRegClass(RegClass);
58}
59
Chris Lattner01614192009-08-02 04:58:19 +000060/// insertNoop - Insert a noop into the instruction stream at the specified
61/// point.
Andrew Trickc416ba62010-12-24 04:28:06 +000062void TargetInstrInfo::insertNoop(MachineBasicBlock &MBB,
Chris Lattner01614192009-08-02 04:58:19 +000063 MachineBasicBlock::iterator MI) const {
64 llvm_unreachable("Target didn't implement insertNoop!");
65}
66
Chris Lattnere98a3c32009-08-02 05:20:37 +000067/// Measure the specified inline asm to determine an approximation of its
68/// length.
Jim Grosbacha3df87f2011-03-24 18:46:34 +000069/// Comments (which run till the next SeparatorString or newline) do not
Chris Lattnere98a3c32009-08-02 05:20:37 +000070/// count as an instruction.
71/// Any other non-whitespace text is considered an instruction, with
Jim Grosbacha3df87f2011-03-24 18:46:34 +000072/// multiple instructions separated by SeparatorString or newlines.
Chris Lattnere98a3c32009-08-02 05:20:37 +000073/// Variable-length instructions are not handled here; this function
74/// may be overloaded in the target code to do that.
75unsigned TargetInstrInfo::getInlineAsmLength(const char *Str,
Chris Lattnere9a75a62009-08-22 21:43:10 +000076 const MCAsmInfo &MAI) const {
Andrew Trickc416ba62010-12-24 04:28:06 +000077
78
Chris Lattnere98a3c32009-08-02 05:20:37 +000079 // Count the number of instructions in the asm.
80 bool atInsnStart = true;
81 unsigned Length = 0;
82 for (; *Str; ++Str) {
Jim Grosbacha3df87f2011-03-24 18:46:34 +000083 if (*Str == '\n' || strncmp(Str, MAI.getSeparatorString(),
84 strlen(MAI.getSeparatorString())) == 0)
Chris Lattnere98a3c32009-08-02 05:20:37 +000085 atInsnStart = true;
Guy Benyei83c74e92013-02-12 21:21:59 +000086 if (atInsnStart && !std::isspace(static_cast<unsigned char>(*Str))) {
Chris Lattnere9a75a62009-08-22 21:43:10 +000087 Length += MAI.getMaxInstLength();
Chris Lattnere98a3c32009-08-02 05:20:37 +000088 atInsnStart = false;
89 }
Chris Lattnere9a75a62009-08-22 21:43:10 +000090 if (atInsnStart && strncmp(Str, MAI.getCommentString(),
91 strlen(MAI.getCommentString())) == 0)
Chris Lattnere98a3c32009-08-02 05:20:37 +000092 atInsnStart = false;
93 }
Andrew Trickc416ba62010-12-24 04:28:06 +000094
Chris Lattnere98a3c32009-08-02 05:20:37 +000095 return Length;
96}
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +000097
98/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
99/// after it, replacing it with an unconditional branch to NewDest.
100void
101TargetInstrInfo::ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
102 MachineBasicBlock *NewDest) const {
103 MachineBasicBlock *MBB = Tail->getParent();
104
105 // Remove all the old successors of MBB from the CFG.
106 while (!MBB->succ_empty())
107 MBB->removeSuccessor(MBB->succ_begin());
108
109 // Remove all the dead instructions from the end of MBB.
110 MBB->erase(Tail, MBB->end());
111
112 // If MBB isn't immediately before MBB, insert a branch to it.
113 if (++MachineFunction::iterator(MBB) != MachineFunction::iterator(NewDest))
Craig Topperc0196b12014-04-14 00:51:57 +0000114 InsertBranch(*MBB, NewDest, nullptr, SmallVector<MachineOperand, 0>(),
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000115 Tail->getDebugLoc());
116 MBB->addSuccessor(NewDest);
117}
118
119// commuteInstruction - The default implementation of this method just exchanges
120// the two operands returned by findCommutedOpIndices.
121MachineInstr *TargetInstrInfo::commuteInstruction(MachineInstr *MI,
122 bool NewMI) const {
123 const MCInstrDesc &MCID = MI->getDesc();
124 bool HasDef = MCID.getNumDefs();
125 if (HasDef && !MI->getOperand(0).isReg())
126 // No idea how to commute this instruction. Target should implement its own.
Craig Topperc0196b12014-04-14 00:51:57 +0000127 return nullptr;
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000128 unsigned Idx1, Idx2;
129 if (!findCommutedOpIndices(MI, Idx1, Idx2)) {
Quentin Colombet2eb151e2014-05-08 23:12:27 +0000130 assert(MI->isCommutable() && "Precondition violation: MI must be commutable.");
131 return nullptr;
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000132 }
133
134 assert(MI->getOperand(Idx1).isReg() && MI->getOperand(Idx2).isReg() &&
135 "This only knows how to commute register operands so far");
136 unsigned Reg0 = HasDef ? MI->getOperand(0).getReg() : 0;
137 unsigned Reg1 = MI->getOperand(Idx1).getReg();
138 unsigned Reg2 = MI->getOperand(Idx2).getReg();
139 unsigned SubReg0 = HasDef ? MI->getOperand(0).getSubReg() : 0;
140 unsigned SubReg1 = MI->getOperand(Idx1).getSubReg();
141 unsigned SubReg2 = MI->getOperand(Idx2).getSubReg();
142 bool Reg1IsKill = MI->getOperand(Idx1).isKill();
143 bool Reg2IsKill = MI->getOperand(Idx2).isKill();
144 // If destination is tied to either of the commuted source register, then
145 // it must be updated.
146 if (HasDef && Reg0 == Reg1 &&
147 MI->getDesc().getOperandConstraint(Idx1, MCOI::TIED_TO) == 0) {
148 Reg2IsKill = false;
149 Reg0 = Reg2;
150 SubReg0 = SubReg2;
151 } else if (HasDef && Reg0 == Reg2 &&
152 MI->getDesc().getOperandConstraint(Idx2, MCOI::TIED_TO) == 0) {
153 Reg1IsKill = false;
154 Reg0 = Reg1;
155 SubReg0 = SubReg1;
156 }
157
158 if (NewMI) {
159 // Create a new instruction.
160 MachineFunction &MF = *MI->getParent()->getParent();
161 MI = MF.CloneMachineInstr(MI);
162 }
163
164 if (HasDef) {
165 MI->getOperand(0).setReg(Reg0);
166 MI->getOperand(0).setSubReg(SubReg0);
167 }
168 MI->getOperand(Idx2).setReg(Reg1);
169 MI->getOperand(Idx1).setReg(Reg2);
170 MI->getOperand(Idx2).setSubReg(SubReg1);
171 MI->getOperand(Idx1).setSubReg(SubReg2);
172 MI->getOperand(Idx2).setIsKill(Reg1IsKill);
173 MI->getOperand(Idx1).setIsKill(Reg2IsKill);
174 return MI;
175}
176
177/// findCommutedOpIndices - If specified MI is commutable, return the two
178/// operand indices that would swap value. Return true if the instruction
179/// is not in a form which this routine understands.
180bool TargetInstrInfo::findCommutedOpIndices(MachineInstr *MI,
181 unsigned &SrcOpIdx1,
182 unsigned &SrcOpIdx2) const {
183 assert(!MI->isBundle() &&
184 "TargetInstrInfo::findCommutedOpIndices() can't handle bundles");
185
186 const MCInstrDesc &MCID = MI->getDesc();
187 if (!MCID.isCommutable())
188 return false;
189 // This assumes v0 = op v1, v2 and commuting would swap v1 and v2. If this
190 // is not true, then the target must implement this.
191 SrcOpIdx1 = MCID.getNumDefs();
192 SrcOpIdx2 = SrcOpIdx1 + 1;
193 if (!MI->getOperand(SrcOpIdx1).isReg() ||
194 !MI->getOperand(SrcOpIdx2).isReg())
195 // No idea.
196 return false;
197 return true;
198}
199
200
201bool
202TargetInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
203 if (!MI->isTerminator()) return false;
204
205 // Conditional branch is a special case.
206 if (MI->isBranch() && !MI->isBarrier())
207 return true;
208 if (!MI->isPredicable())
209 return true;
210 return !isPredicated(MI);
211}
212
213
214bool TargetInstrInfo::PredicateInstruction(MachineInstr *MI,
215 const SmallVectorImpl<MachineOperand> &Pred) const {
216 bool MadeChange = false;
217
218 assert(!MI->isBundle() &&
219 "TargetInstrInfo::PredicateInstruction() can't handle bundles");
220
221 const MCInstrDesc &MCID = MI->getDesc();
222 if (!MI->isPredicable())
223 return false;
224
225 for (unsigned j = 0, i = 0, e = MI->getNumOperands(); i != e; ++i) {
226 if (MCID.OpInfo[i].isPredicate()) {
227 MachineOperand &MO = MI->getOperand(i);
228 if (MO.isReg()) {
229 MO.setReg(Pred[j].getReg());
230 MadeChange = true;
231 } else if (MO.isImm()) {
232 MO.setImm(Pred[j].getImm());
233 MadeChange = true;
234 } else if (MO.isMBB()) {
235 MO.setMBB(Pred[j].getMBB());
236 MadeChange = true;
237 }
238 ++j;
239 }
240 }
241 return MadeChange;
242}
243
244bool TargetInstrInfo::hasLoadFromStackSlot(const MachineInstr *MI,
245 const MachineMemOperand *&MMO,
246 int &FrameIndex) const {
247 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
248 oe = MI->memoperands_end();
249 o != oe;
250 ++o) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000251 if ((*o)->isLoad()) {
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000252 if (const FixedStackPseudoSourceValue *Value =
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000253 dyn_cast_or_null<FixedStackPseudoSourceValue>(
254 (*o)->getPseudoValue())) {
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000255 FrameIndex = Value->getFrameIndex();
256 MMO = *o;
257 return true;
258 }
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000259 }
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000260 }
261 return false;
262}
263
264bool TargetInstrInfo::hasStoreToStackSlot(const MachineInstr *MI,
265 const MachineMemOperand *&MMO,
266 int &FrameIndex) const {
267 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
268 oe = MI->memoperands_end();
269 o != oe;
270 ++o) {
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000271 if ((*o)->isStore()) {
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000272 if (const FixedStackPseudoSourceValue *Value =
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000273 dyn_cast_or_null<FixedStackPseudoSourceValue>(
274 (*o)->getPseudoValue())) {
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000275 FrameIndex = Value->getFrameIndex();
276 MMO = *o;
277 return true;
278 }
Nick Lewyckyaad475b2014-04-15 07:22:52 +0000279 }
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000280 }
281 return false;
282}
283
Andrew Trick10d5be42013-11-17 01:36:23 +0000284bool TargetInstrInfo::getStackSlotRange(const TargetRegisterClass *RC,
285 unsigned SubIdx, unsigned &Size,
286 unsigned &Offset,
287 const TargetMachine *TM) const {
288 if (!SubIdx) {
289 Size = RC->getSize();
290 Offset = 0;
291 return true;
292 }
Eric Christopherd9134482014-08-04 21:25:23 +0000293 unsigned BitSize =
294 TM->getSubtargetImpl()->getRegisterInfo()->getSubRegIdxSize(SubIdx);
Andrew Trick10d5be42013-11-17 01:36:23 +0000295 // Convert bit size to byte size to be consistent with
296 // MCRegisterClass::getSize().
297 if (BitSize % 8)
298 return false;
299
Eric Christopherd9134482014-08-04 21:25:23 +0000300 int BitOffset =
301 TM->getSubtargetImpl()->getRegisterInfo()->getSubRegIdxOffset(SubIdx);
Andrew Trick10d5be42013-11-17 01:36:23 +0000302 if (BitOffset < 0 || BitOffset % 8)
303 return false;
304
305 Size = BitSize /= 8;
306 Offset = (unsigned)BitOffset / 8;
307
308 assert(RC->getSize() >= (Offset + Size) && "bad subregister range");
309
Eric Christopherd9134482014-08-04 21:25:23 +0000310 if (!TM->getSubtargetImpl()->getDataLayout()->isLittleEndian()) {
Andrew Trick10d5be42013-11-17 01:36:23 +0000311 Offset = RC->getSize() - (Offset + Size);
312 }
313 return true;
314}
315
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000316void TargetInstrInfo::reMaterialize(MachineBasicBlock &MBB,
317 MachineBasicBlock::iterator I,
318 unsigned DestReg,
319 unsigned SubIdx,
320 const MachineInstr *Orig,
321 const TargetRegisterInfo &TRI) const {
322 MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
323 MI->substituteRegister(MI->getOperand(0).getReg(), DestReg, SubIdx, TRI);
324 MBB.insert(I, MI);
325}
326
327bool
328TargetInstrInfo::produceSameValue(const MachineInstr *MI0,
329 const MachineInstr *MI1,
330 const MachineRegisterInfo *MRI) const {
331 return MI0->isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
332}
333
334MachineInstr *TargetInstrInfo::duplicate(MachineInstr *Orig,
335 MachineFunction &MF) const {
336 assert(!Orig->isNotDuplicable() &&
337 "Instruction cannot be duplicated");
338 return MF.CloneMachineInstr(Orig);
339}
340
341// If the COPY instruction in MI can be folded to a stack operation, return
342// the register class to use.
343static const TargetRegisterClass *canFoldCopy(const MachineInstr *MI,
344 unsigned FoldIdx) {
345 assert(MI->isCopy() && "MI must be a COPY instruction");
346 if (MI->getNumOperands() != 2)
Craig Topperc0196b12014-04-14 00:51:57 +0000347 return nullptr;
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000348 assert(FoldIdx<2 && "FoldIdx refers no nonexistent operand");
349
350 const MachineOperand &FoldOp = MI->getOperand(FoldIdx);
351 const MachineOperand &LiveOp = MI->getOperand(1-FoldIdx);
352
353 if (FoldOp.getSubReg() || LiveOp.getSubReg())
Craig Topperc0196b12014-04-14 00:51:57 +0000354 return nullptr;
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000355
356 unsigned FoldReg = FoldOp.getReg();
357 unsigned LiveReg = LiveOp.getReg();
358
359 assert(TargetRegisterInfo::isVirtualRegister(FoldReg) &&
360 "Cannot fold physregs");
361
362 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
363 const TargetRegisterClass *RC = MRI.getRegClass(FoldReg);
364
365 if (TargetRegisterInfo::isPhysicalRegister(LiveOp.getReg()))
Craig Topperc0196b12014-04-14 00:51:57 +0000366 return RC->contains(LiveOp.getReg()) ? RC : nullptr;
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000367
368 if (RC->hasSubClassEq(MRI.getRegClass(LiveReg)))
369 return RC;
370
371 // FIXME: Allow folding when register classes are memory compatible.
Craig Topperc0196b12014-04-14 00:51:57 +0000372 return nullptr;
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000373}
374
375bool TargetInstrInfo::
376canFoldMemoryOperand(const MachineInstr *MI,
377 const SmallVectorImpl<unsigned> &Ops) const {
378 return MI->isCopy() && Ops.size() == 1 && canFoldCopy(MI, Ops[0]);
379}
380
Lang Hames39609992013-11-29 03:07:54 +0000381static MachineInstr* foldPatchpoint(MachineFunction &MF,
382 MachineInstr *MI,
383 const SmallVectorImpl<unsigned> &Ops,
384 int FrameIndex,
385 const TargetInstrInfo &TII) {
386 unsigned StartIdx = 0;
387 switch (MI->getOpcode()) {
388 case TargetOpcode::STACKMAP:
389 StartIdx = 2; // Skip ID, nShadowBytes.
390 break;
391 case TargetOpcode::PATCHPOINT: {
392 // For PatchPoint, the call args are not foldable.
393 PatchPointOpers opers(MI);
394 StartIdx = opers.getVarIdx();
395 break;
396 }
397 default:
398 llvm_unreachable("unexpected stackmap opcode");
399 }
400
401 // Return false if any operands requested for folding are not foldable (not
402 // part of the stackmap's live values).
403 for (SmallVectorImpl<unsigned>::const_iterator I = Ops.begin(), E = Ops.end();
404 I != E; ++I) {
405 if (*I < StartIdx)
Craig Topperc0196b12014-04-14 00:51:57 +0000406 return nullptr;
Lang Hames39609992013-11-29 03:07:54 +0000407 }
408
409 MachineInstr *NewMI =
410 MF.CreateMachineInstr(TII.get(MI->getOpcode()), MI->getDebugLoc(), true);
411 MachineInstrBuilder MIB(MF, NewMI);
412
413 // No need to fold return, the meta data, and function arguments
414 for (unsigned i = 0; i < StartIdx; ++i)
415 MIB.addOperand(MI->getOperand(i));
416
417 for (unsigned i = StartIdx; i < MI->getNumOperands(); ++i) {
418 MachineOperand &MO = MI->getOperand(i);
419 if (std::find(Ops.begin(), Ops.end(), i) != Ops.end()) {
420 unsigned SpillSize;
421 unsigned SpillOffset;
422 // Compute the spill slot size and offset.
423 const TargetRegisterClass *RC =
424 MF.getRegInfo().getRegClass(MO.getReg());
425 bool Valid = TII.getStackSlotRange(RC, MO.getSubReg(), SpillSize,
426 SpillOffset, &MF.getTarget());
427 if (!Valid)
428 report_fatal_error("cannot spill patchpoint subregister operand");
429 MIB.addImm(StackMaps::IndirectMemRefOp);
430 MIB.addImm(SpillSize);
431 MIB.addFrameIndex(FrameIndex);
Lang Hames2ce64a72013-12-07 03:30:59 +0000432 MIB.addImm(SpillOffset);
Lang Hames39609992013-11-29 03:07:54 +0000433 }
434 else
435 MIB.addOperand(MO);
436 }
437 return NewMI;
438}
439
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000440/// foldMemoryOperand - Attempt to fold a load or store of the specified stack
441/// slot into the specified machine instruction for the specified operand(s).
442/// If this is possible, a new instruction is returned with the specified
443/// operand folded, otherwise NULL is returned. The client is responsible for
444/// removing the old instruction and adding the new one in the instruction
445/// stream.
446MachineInstr*
447TargetInstrInfo::foldMemoryOperand(MachineBasicBlock::iterator MI,
448 const SmallVectorImpl<unsigned> &Ops,
449 int FI) const {
450 unsigned Flags = 0;
451 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
452 if (MI->getOperand(Ops[i]).isDef())
453 Flags |= MachineMemOperand::MOStore;
454 else
455 Flags |= MachineMemOperand::MOLoad;
456
457 MachineBasicBlock *MBB = MI->getParent();
458 assert(MBB && "foldMemoryOperand needs an inserted instruction");
459 MachineFunction &MF = *MBB->getParent();
460
Craig Topperc0196b12014-04-14 00:51:57 +0000461 MachineInstr *NewMI = nullptr;
Lang Hames39609992013-11-29 03:07:54 +0000462
463 if (MI->getOpcode() == TargetOpcode::STACKMAP ||
464 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
465 // Fold stackmap/patchpoint.
466 NewMI = foldPatchpoint(MF, MI, Ops, FI, *this);
467 } else {
468 // Ask the target to do the actual folding.
469 NewMI =foldMemoryOperandImpl(MF, MI, Ops, FI);
470 }
471
472 if (NewMI) {
Andrew Tricka9f4d922013-11-14 23:45:04 +0000473 NewMI->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000474 // Add a memory operand, foldMemoryOperandImpl doesn't do that.
475 assert((!(Flags & MachineMemOperand::MOStore) ||
476 NewMI->mayStore()) &&
477 "Folded a def to a non-store!");
478 assert((!(Flags & MachineMemOperand::MOLoad) ||
479 NewMI->mayLoad()) &&
480 "Folded a use to a non-load!");
481 const MachineFrameInfo &MFI = *MF.getFrameInfo();
482 assert(MFI.getObjectOffset(FI) != -1);
483 MachineMemOperand *MMO =
484 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
485 Flags, MFI.getObjectSize(FI),
486 MFI.getObjectAlignment(FI));
487 NewMI->addMemOperand(MF, MMO);
488
489 // FIXME: change foldMemoryOperandImpl semantics to also insert NewMI.
490 return MBB->insert(MI, NewMI);
491 }
492
493 // Straight COPY may fold as load/store.
494 if (!MI->isCopy() || Ops.size() != 1)
Craig Topperc0196b12014-04-14 00:51:57 +0000495 return nullptr;
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000496
497 const TargetRegisterClass *RC = canFoldCopy(MI, Ops[0]);
498 if (!RC)
Craig Topperc0196b12014-04-14 00:51:57 +0000499 return nullptr;
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000500
501 const MachineOperand &MO = MI->getOperand(1-Ops[0]);
502 MachineBasicBlock::iterator Pos = MI;
Eric Christopherd9134482014-08-04 21:25:23 +0000503 const TargetRegisterInfo *TRI =
504 MF.getTarget().getSubtargetImpl()->getRegisterInfo();
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000505
506 if (Flags == MachineMemOperand::MOStore)
507 storeRegToStackSlot(*MBB, Pos, MO.getReg(), MO.isKill(), FI, RC, TRI);
508 else
509 loadRegFromStackSlot(*MBB, Pos, MO.getReg(), FI, RC, TRI);
510 return --Pos;
511}
512
513/// foldMemoryOperand - Same as the previous version except it allows folding
514/// of any load and store from / to any address, not just from a specific
515/// stack slot.
516MachineInstr*
517TargetInstrInfo::foldMemoryOperand(MachineBasicBlock::iterator MI,
518 const SmallVectorImpl<unsigned> &Ops,
519 MachineInstr* LoadMI) const {
520 assert(LoadMI->canFoldAsLoad() && "LoadMI isn't foldable!");
521#ifndef NDEBUG
522 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
523 assert(MI->getOperand(Ops[i]).isUse() && "Folding load into def!");
524#endif
525 MachineBasicBlock &MBB = *MI->getParent();
526 MachineFunction &MF = *MBB.getParent();
527
528 // Ask the target to do the actual folding.
Craig Topperc0196b12014-04-14 00:51:57 +0000529 MachineInstr *NewMI = nullptr;
Lang Hames39609992013-11-29 03:07:54 +0000530 int FrameIndex = 0;
531
532 if ((MI->getOpcode() == TargetOpcode::STACKMAP ||
533 MI->getOpcode() == TargetOpcode::PATCHPOINT) &&
534 isLoadFromStackSlot(LoadMI, FrameIndex)) {
535 // Fold stackmap/patchpoint.
536 NewMI = foldPatchpoint(MF, MI, Ops, FrameIndex, *this);
537 } else {
538 // Ask the target to do the actual folding.
Lang Hames8e6e6ab2014-01-02 19:38:41 +0000539 NewMI = foldMemoryOperandImpl(MF, MI, Ops, LoadMI);
Lang Hames39609992013-11-29 03:07:54 +0000540 }
Lang Hames39609992013-11-29 03:07:54 +0000541
Craig Topperc0196b12014-04-14 00:51:57 +0000542 if (!NewMI) return nullptr;
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000543
544 NewMI = MBB.insert(MI, NewMI);
545
546 // Copy the memoperands from the load to the folded instruction.
Andrew Tricka9f4d922013-11-14 23:45:04 +0000547 if (MI->memoperands_empty()) {
548 NewMI->setMemRefs(LoadMI->memoperands_begin(),
549 LoadMI->memoperands_end());
550 }
551 else {
552 // Handle the rare case of folding multiple loads.
553 NewMI->setMemRefs(MI->memoperands_begin(),
554 MI->memoperands_end());
555 for (MachineInstr::mmo_iterator I = LoadMI->memoperands_begin(),
556 E = LoadMI->memoperands_end(); I != E; ++I) {
557 NewMI->addMemOperand(MF, *I);
558 }
559 }
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000560 return NewMI;
561}
562
563bool TargetInstrInfo::
564isReallyTriviallyReMaterializableGeneric(const MachineInstr *MI,
565 AliasAnalysis *AA) const {
566 const MachineFunction &MF = *MI->getParent()->getParent();
567 const MachineRegisterInfo &MRI = MF.getRegInfo();
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000568
569 // Remat clients assume operand 0 is the defined register.
570 if (!MI->getNumOperands() || !MI->getOperand(0).isReg())
571 return false;
572 unsigned DefReg = MI->getOperand(0).getReg();
573
574 // A sub-register definition can only be rematerialized if the instruction
575 // doesn't read the other parts of the register. Otherwise it is really a
576 // read-modify-write operation on the full virtual register which cannot be
577 // moved safely.
578 if (TargetRegisterInfo::isVirtualRegister(DefReg) &&
579 MI->getOperand(0).getSubReg() && MI->readsVirtualRegister(DefReg))
580 return false;
581
582 // A load from a fixed stack slot can be rematerialized. This may be
583 // redundant with subsequent checks, but it's target-independent,
584 // simple, and a common case.
585 int FrameIdx = 0;
Eric Christopher9d916792014-07-23 22:12:03 +0000586 if (isLoadFromStackSlot(MI, FrameIdx) &&
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000587 MF.getFrameInfo()->isImmutableObjectIndex(FrameIdx))
588 return true;
589
590 // Avoid instructions obviously unsafe for remat.
591 if (MI->isNotDuplicable() || MI->mayStore() ||
592 MI->hasUnmodeledSideEffects())
593 return false;
594
595 // Don't remat inline asm. We have no idea how expensive it is
596 // even if it's side effect free.
597 if (MI->isInlineAsm())
598 return false;
599
600 // Avoid instructions which load from potentially varying memory.
601 if (MI->mayLoad() && !MI->isInvariantLoad(AA))
602 return false;
603
604 // If any of the registers accessed are non-constant, conservatively assume
605 // the instruction is not rematerializable.
606 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
607 const MachineOperand &MO = MI->getOperand(i);
608 if (!MO.isReg()) continue;
609 unsigned Reg = MO.getReg();
610 if (Reg == 0)
611 continue;
612
613 // Check for a well-behaved physical register.
614 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
615 if (MO.isUse()) {
616 // If the physreg has no defs anywhere, it's just an ambient register
617 // and we can freely move its uses. Alternatively, if it's allocatable,
618 // it could get allocated to something with a def during allocation.
619 if (!MRI.isConstantPhysReg(Reg, MF))
620 return false;
621 } else {
622 // A physreg def. We can't remat it.
623 return false;
624 }
625 continue;
626 }
627
628 // Only allow one virtual-register def. There may be multiple defs of the
629 // same virtual register, though.
630 if (MO.isDef() && Reg != DefReg)
631 return false;
632
633 // Don't allow any virtual-register uses. Rematting an instruction with
634 // virtual register uses would length the live ranges of the uses, which
635 // is not necessarily a good idea, certainly not "trivial".
636 if (MO.isUse())
637 return false;
638 }
639
640 // Everything checked out.
641 return true;
642}
643
644/// isSchedulingBoundary - Test if the given instruction should be
645/// considered a scheduling boundary. This primarily includes labels
646/// and terminators.
647bool TargetInstrInfo::isSchedulingBoundary(const MachineInstr *MI,
648 const MachineBasicBlock *MBB,
649 const MachineFunction &MF) const {
650 // Terminators and labels can't be scheduled around.
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000651 if (MI->isTerminator() || MI->isPosition())
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000652 return true;
653
654 // Don't attempt to schedule around any instruction that defines
655 // a stack-oriented pointer, as it's unlikely to be profitable. This
656 // saves compile time, because it doesn't require every single
657 // stack slot reference to depend on the instruction that does the
658 // modification.
Eric Christopherd9134482014-08-04 21:25:23 +0000659 const TargetLowering &TLI =
660 *MF.getTarget().getSubtargetImpl()->getTargetLowering();
661 const TargetRegisterInfo *TRI =
662 MF.getTarget().getSubtargetImpl()->getRegisterInfo();
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000663 if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore(), TRI))
664 return true;
665
666 return false;
667}
668
669// Provide a global flag for disabling the PreRA hazard recognizer that targets
670// may choose to honor.
671bool TargetInstrInfo::usePreRAHazardRecognizer() const {
672 return !DisableHazardRecognizer;
673}
674
675// Default implementation of CreateTargetRAHazardRecognizer.
676ScheduleHazardRecognizer *TargetInstrInfo::
Eric Christopherf047bfd2014-06-13 22:38:52 +0000677CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000678 const ScheduleDAG *DAG) const {
679 // Dummy hazard recognizer allows all instructions to issue.
680 return new ScheduleHazardRecognizer();
681}
682
683// Default implementation of CreateTargetMIHazardRecognizer.
684ScheduleHazardRecognizer *TargetInstrInfo::
685CreateTargetMIHazardRecognizer(const InstrItineraryData *II,
686 const ScheduleDAG *DAG) const {
687 return (ScheduleHazardRecognizer *)
688 new ScoreboardHazardRecognizer(II, DAG, "misched");
689}
690
691// Default implementation of CreateTargetPostRAHazardRecognizer.
692ScheduleHazardRecognizer *TargetInstrInfo::
693CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
694 const ScheduleDAG *DAG) const {
695 return (ScheduleHazardRecognizer *)
696 new ScoreboardHazardRecognizer(II, DAG, "post-RA-sched");
697}
698
699//===----------------------------------------------------------------------===//
700// SelectionDAG latency interface.
701//===----------------------------------------------------------------------===//
702
703int
704TargetInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
705 SDNode *DefNode, unsigned DefIdx,
706 SDNode *UseNode, unsigned UseIdx) const {
707 if (!ItinData || ItinData->isEmpty())
708 return -1;
709
710 if (!DefNode->isMachineOpcode())
711 return -1;
712
713 unsigned DefClass = get(DefNode->getMachineOpcode()).getSchedClass();
714 if (!UseNode->isMachineOpcode())
715 return ItinData->getOperandCycle(DefClass, DefIdx);
716 unsigned UseClass = get(UseNode->getMachineOpcode()).getSchedClass();
717 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
718}
719
720int TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
721 SDNode *N) const {
722 if (!ItinData || ItinData->isEmpty())
723 return 1;
724
725 if (!N->isMachineOpcode())
726 return 1;
727
728 return ItinData->getStageLatency(get(N->getMachineOpcode()).getSchedClass());
729}
730
731//===----------------------------------------------------------------------===//
732// MachineInstr latency interface.
733//===----------------------------------------------------------------------===//
734
735unsigned
736TargetInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
737 const MachineInstr *MI) const {
738 if (!ItinData || ItinData->isEmpty())
739 return 1;
740
741 unsigned Class = MI->getDesc().getSchedClass();
742 int UOps = ItinData->Itineraries[Class].NumMicroOps;
743 if (UOps >= 0)
744 return UOps;
745
746 // The # of u-ops is dynamically determined. The specific target should
747 // override this function to return the right number.
748 return 1;
749}
750
751/// Return the default expected latency for a def based on it's opcode.
752unsigned TargetInstrInfo::defaultDefLatency(const MCSchedModel *SchedModel,
753 const MachineInstr *DefMI) const {
754 if (DefMI->isTransient())
755 return 0;
756 if (DefMI->mayLoad())
757 return SchedModel->LoadLatency;
758 if (isHighLatencyDef(DefMI->getOpcode()))
759 return SchedModel->HighLatency;
760 return 1;
761}
762
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000763unsigned TargetInstrInfo::getPredicationCost(const MachineInstr *) const {
764 return 0;
765}
766
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000767unsigned TargetInstrInfo::
768getInstrLatency(const InstrItineraryData *ItinData,
769 const MachineInstr *MI,
770 unsigned *PredCost) const {
771 // Default to one cycle for no itinerary. However, an "empty" itinerary may
772 // still have a MinLatency property, which getStageLatency checks.
773 if (!ItinData)
774 return MI->mayLoad() ? 2 : 1;
775
776 return ItinData->getStageLatency(MI->getDesc().getSchedClass());
777}
778
779bool TargetInstrInfo::hasLowDefLatency(const InstrItineraryData *ItinData,
780 const MachineInstr *DefMI,
781 unsigned DefIdx) const {
782 if (!ItinData || ItinData->isEmpty())
783 return false;
784
785 unsigned DefClass = DefMI->getDesc().getSchedClass();
786 int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
787 return (DefCycle != -1 && DefCycle <= 1);
788}
789
790/// Both DefMI and UseMI must be valid. By default, call directly to the
791/// itinerary. This may be overriden by the target.
792int TargetInstrInfo::
793getOperandLatency(const InstrItineraryData *ItinData,
794 const MachineInstr *DefMI, unsigned DefIdx,
795 const MachineInstr *UseMI, unsigned UseIdx) const {
796 unsigned DefClass = DefMI->getDesc().getSchedClass();
797 unsigned UseClass = UseMI->getDesc().getSchedClass();
798 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
799}
800
801/// If we can determine the operand latency from the def only, without itinerary
802/// lookup, do so. Otherwise return -1.
803int TargetInstrInfo::computeDefOperandLatency(
804 const InstrItineraryData *ItinData,
Andrew Trickde2109e2013-06-15 04:49:57 +0000805 const MachineInstr *DefMI) const {
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000806
807 // Let the target hook getInstrLatency handle missing itineraries.
808 if (!ItinData)
809 return getInstrLatency(ItinData, DefMI);
810
Andrew Trickde2109e2013-06-15 04:49:57 +0000811 if(ItinData->isEmpty())
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000812 return defaultDefLatency(ItinData->SchedModel, DefMI);
813
814 // ...operand lookup required
815 return -1;
816}
817
818/// computeOperandLatency - Compute and return the latency of the given data
819/// dependent def and use when the operand indices are already known. UseMI may
820/// be NULL for an unknown use.
821///
822/// FindMin may be set to get the minimum vs. expected latency. Minimum
823/// latency is used for scheduling groups, while expected latency is for
824/// instruction cost and critical path.
825///
826/// Depending on the subtarget's itinerary properties, this may or may not need
827/// to call getOperandLatency(). For most subtargets, we don't need DefIdx or
828/// UseIdx to compute min latency.
829unsigned TargetInstrInfo::
830computeOperandLatency(const InstrItineraryData *ItinData,
831 const MachineInstr *DefMI, unsigned DefIdx,
Andrew Trickde2109e2013-06-15 04:49:57 +0000832 const MachineInstr *UseMI, unsigned UseIdx) const {
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000833
Andrew Trickde2109e2013-06-15 04:49:57 +0000834 int DefLatency = computeDefOperandLatency(ItinData, DefMI);
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000835 if (DefLatency >= 0)
836 return DefLatency;
837
838 assert(ItinData && !ItinData->isEmpty() && "computeDefOperandLatency fail");
839
840 int OperLatency = 0;
841 if (UseMI)
842 OperLatency = getOperandLatency(ItinData, DefMI, DefIdx, UseMI, UseIdx);
843 else {
844 unsigned DefClass = DefMI->getDesc().getSchedClass();
845 OperLatency = ItinData->getOperandCycle(DefClass, DefIdx);
846 }
847 if (OperLatency >= 0)
848 return OperLatency;
849
850 // No operand latency was found.
851 unsigned InstrLatency = getInstrLatency(ItinData, DefMI);
852
853 // Expected latency is the max of the stage latency and itinerary props.
Andrew Trickde2109e2013-06-15 04:49:57 +0000854 InstrLatency = std::max(InstrLatency,
855 defaultDefLatency(ItinData->SchedModel, DefMI));
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000856 return InstrLatency;
857}