blob: 7c5092bfa2efa18888c52f94f5822a02b2e5e9ad [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
Chris Lattnerb4d58d72003-01-14 22:00:31 +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())
Evan Cheng8d71a752011-06-27 21:26:13 +000046 return 0;
47
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)
54 return 0;
55
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))
114 InsertBranch(*MBB, NewDest, 0, SmallVector<MachineOperand, 0>(),
115 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.
127 return 0;
128 unsigned Idx1, Idx2;
129 if (!findCommutedOpIndices(MI, Idx1, Idx2)) {
130 std::string msg;
131 raw_string_ostream Msg(msg);
132 Msg << "Don't know how to commute: " << *MI;
133 report_fatal_error(Msg.str());
134 }
135
136 assert(MI->getOperand(Idx1).isReg() && MI->getOperand(Idx2).isReg() &&
137 "This only knows how to commute register operands so far");
138 unsigned Reg0 = HasDef ? MI->getOperand(0).getReg() : 0;
139 unsigned Reg1 = MI->getOperand(Idx1).getReg();
140 unsigned Reg2 = MI->getOperand(Idx2).getReg();
141 unsigned SubReg0 = HasDef ? MI->getOperand(0).getSubReg() : 0;
142 unsigned SubReg1 = MI->getOperand(Idx1).getSubReg();
143 unsigned SubReg2 = MI->getOperand(Idx2).getSubReg();
144 bool Reg1IsKill = MI->getOperand(Idx1).isKill();
145 bool Reg2IsKill = MI->getOperand(Idx2).isKill();
146 // If destination is tied to either of the commuted source register, then
147 // it must be updated.
148 if (HasDef && Reg0 == Reg1 &&
149 MI->getDesc().getOperandConstraint(Idx1, MCOI::TIED_TO) == 0) {
150 Reg2IsKill = false;
151 Reg0 = Reg2;
152 SubReg0 = SubReg2;
153 } else if (HasDef && Reg0 == Reg2 &&
154 MI->getDesc().getOperandConstraint(Idx2, MCOI::TIED_TO) == 0) {
155 Reg1IsKill = false;
156 Reg0 = Reg1;
157 SubReg0 = SubReg1;
158 }
159
160 if (NewMI) {
161 // Create a new instruction.
162 MachineFunction &MF = *MI->getParent()->getParent();
163 MI = MF.CloneMachineInstr(MI);
164 }
165
166 if (HasDef) {
167 MI->getOperand(0).setReg(Reg0);
168 MI->getOperand(0).setSubReg(SubReg0);
169 }
170 MI->getOperand(Idx2).setReg(Reg1);
171 MI->getOperand(Idx1).setReg(Reg2);
172 MI->getOperand(Idx2).setSubReg(SubReg1);
173 MI->getOperand(Idx1).setSubReg(SubReg2);
174 MI->getOperand(Idx2).setIsKill(Reg1IsKill);
175 MI->getOperand(Idx1).setIsKill(Reg2IsKill);
176 return MI;
177}
178
179/// findCommutedOpIndices - If specified MI is commutable, return the two
180/// operand indices that would swap value. Return true if the instruction
181/// is not in a form which this routine understands.
182bool TargetInstrInfo::findCommutedOpIndices(MachineInstr *MI,
183 unsigned &SrcOpIdx1,
184 unsigned &SrcOpIdx2) const {
185 assert(!MI->isBundle() &&
186 "TargetInstrInfo::findCommutedOpIndices() can't handle bundles");
187
188 const MCInstrDesc &MCID = MI->getDesc();
189 if (!MCID.isCommutable())
190 return false;
191 // This assumes v0 = op v1, v2 and commuting would swap v1 and v2. If this
192 // is not true, then the target must implement this.
193 SrcOpIdx1 = MCID.getNumDefs();
194 SrcOpIdx2 = SrcOpIdx1 + 1;
195 if (!MI->getOperand(SrcOpIdx1).isReg() ||
196 !MI->getOperand(SrcOpIdx2).isReg())
197 // No idea.
198 return false;
199 return true;
200}
201
202
203bool
204TargetInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
205 if (!MI->isTerminator()) return false;
206
207 // Conditional branch is a special case.
208 if (MI->isBranch() && !MI->isBarrier())
209 return true;
210 if (!MI->isPredicable())
211 return true;
212 return !isPredicated(MI);
213}
214
215
216bool TargetInstrInfo::PredicateInstruction(MachineInstr *MI,
217 const SmallVectorImpl<MachineOperand> &Pred) const {
218 bool MadeChange = false;
219
220 assert(!MI->isBundle() &&
221 "TargetInstrInfo::PredicateInstruction() can't handle bundles");
222
223 const MCInstrDesc &MCID = MI->getDesc();
224 if (!MI->isPredicable())
225 return false;
226
227 for (unsigned j = 0, i = 0, e = MI->getNumOperands(); i != e; ++i) {
228 if (MCID.OpInfo[i].isPredicate()) {
229 MachineOperand &MO = MI->getOperand(i);
230 if (MO.isReg()) {
231 MO.setReg(Pred[j].getReg());
232 MadeChange = true;
233 } else if (MO.isImm()) {
234 MO.setImm(Pred[j].getImm());
235 MadeChange = true;
236 } else if (MO.isMBB()) {
237 MO.setMBB(Pred[j].getMBB());
238 MadeChange = true;
239 }
240 ++j;
241 }
242 }
243 return MadeChange;
244}
245
246bool TargetInstrInfo::hasLoadFromStackSlot(const MachineInstr *MI,
247 const MachineMemOperand *&MMO,
248 int &FrameIndex) const {
249 for (MachineInstr::mmo_iterator o = MI->memoperands_begin(),
250 oe = MI->memoperands_end();
251 o != oe;
252 ++o) {
253 if ((*o)->isLoad() && (*o)->getValue())
254 if (const FixedStackPseudoSourceValue *Value =
255 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
256 FrameIndex = Value->getFrameIndex();
257 MMO = *o;
258 return true;
259 }
260 }
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) {
271 if ((*o)->isStore() && (*o)->getValue())
272 if (const FixedStackPseudoSourceValue *Value =
273 dyn_cast<const FixedStackPseudoSourceValue>((*o)->getValue())) {
274 FrameIndex = Value->getFrameIndex();
275 MMO = *o;
276 return true;
277 }
278 }
279 return false;
280}
281
Andrew Trick10d5be42013-11-17 01:36:23 +0000282bool TargetInstrInfo::getStackSlotRange(const TargetRegisterClass *RC,
283 unsigned SubIdx, unsigned &Size,
284 unsigned &Offset,
285 const TargetMachine *TM) const {
286 if (!SubIdx) {
287 Size = RC->getSize();
288 Offset = 0;
289 return true;
290 }
291 unsigned BitSize = TM->getRegisterInfo()->getSubRegIdxSize(SubIdx);
292 // Convert bit size to byte size to be consistent with
293 // MCRegisterClass::getSize().
294 if (BitSize % 8)
295 return false;
296
297 int BitOffset = TM->getRegisterInfo()->getSubRegIdxOffset(SubIdx);
298 if (BitOffset < 0 || BitOffset % 8)
299 return false;
300
301 Size = BitSize /= 8;
302 Offset = (unsigned)BitOffset / 8;
303
304 assert(RC->getSize() >= (Offset + Size) && "bad subregister range");
305
306 if (!TM->getDataLayout()->isLittleEndian()) {
307 Offset = RC->getSize() - (Offset + Size);
308 }
309 return true;
310}
311
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000312void TargetInstrInfo::reMaterialize(MachineBasicBlock &MBB,
313 MachineBasicBlock::iterator I,
314 unsigned DestReg,
315 unsigned SubIdx,
316 const MachineInstr *Orig,
317 const TargetRegisterInfo &TRI) const {
318 MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
319 MI->substituteRegister(MI->getOperand(0).getReg(), DestReg, SubIdx, TRI);
320 MBB.insert(I, MI);
321}
322
323bool
324TargetInstrInfo::produceSameValue(const MachineInstr *MI0,
325 const MachineInstr *MI1,
326 const MachineRegisterInfo *MRI) const {
327 return MI0->isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
328}
329
330MachineInstr *TargetInstrInfo::duplicate(MachineInstr *Orig,
331 MachineFunction &MF) const {
332 assert(!Orig->isNotDuplicable() &&
333 "Instruction cannot be duplicated");
334 return MF.CloneMachineInstr(Orig);
335}
336
337// If the COPY instruction in MI can be folded to a stack operation, return
338// the register class to use.
339static const TargetRegisterClass *canFoldCopy(const MachineInstr *MI,
340 unsigned FoldIdx) {
341 assert(MI->isCopy() && "MI must be a COPY instruction");
342 if (MI->getNumOperands() != 2)
343 return 0;
344 assert(FoldIdx<2 && "FoldIdx refers no nonexistent operand");
345
346 const MachineOperand &FoldOp = MI->getOperand(FoldIdx);
347 const MachineOperand &LiveOp = MI->getOperand(1-FoldIdx);
348
349 if (FoldOp.getSubReg() || LiveOp.getSubReg())
350 return 0;
351
352 unsigned FoldReg = FoldOp.getReg();
353 unsigned LiveReg = LiveOp.getReg();
354
355 assert(TargetRegisterInfo::isVirtualRegister(FoldReg) &&
356 "Cannot fold physregs");
357
358 const MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
359 const TargetRegisterClass *RC = MRI.getRegClass(FoldReg);
360
361 if (TargetRegisterInfo::isPhysicalRegister(LiveOp.getReg()))
362 return RC->contains(LiveOp.getReg()) ? RC : 0;
363
364 if (RC->hasSubClassEq(MRI.getRegClass(LiveReg)))
365 return RC;
366
367 // FIXME: Allow folding when register classes are memory compatible.
368 return 0;
369}
370
371bool TargetInstrInfo::
372canFoldMemoryOperand(const MachineInstr *MI,
373 const SmallVectorImpl<unsigned> &Ops) const {
374 return MI->isCopy() && Ops.size() == 1 && canFoldCopy(MI, Ops[0]);
375}
376
Lang Hames39609992013-11-29 03:07:54 +0000377static MachineInstr* foldPatchpoint(MachineFunction &MF,
378 MachineInstr *MI,
379 const SmallVectorImpl<unsigned> &Ops,
380 int FrameIndex,
381 const TargetInstrInfo &TII) {
382 unsigned StartIdx = 0;
383 switch (MI->getOpcode()) {
384 case TargetOpcode::STACKMAP:
385 StartIdx = 2; // Skip ID, nShadowBytes.
386 break;
387 case TargetOpcode::PATCHPOINT: {
388 // For PatchPoint, the call args are not foldable.
389 PatchPointOpers opers(MI);
390 StartIdx = opers.getVarIdx();
391 break;
392 }
393 default:
394 llvm_unreachable("unexpected stackmap opcode");
395 }
396
397 // Return false if any operands requested for folding are not foldable (not
398 // part of the stackmap's live values).
399 for (SmallVectorImpl<unsigned>::const_iterator I = Ops.begin(), E = Ops.end();
400 I != E; ++I) {
401 if (*I < StartIdx)
402 return 0;
403 }
404
405 MachineInstr *NewMI =
406 MF.CreateMachineInstr(TII.get(MI->getOpcode()), MI->getDebugLoc(), true);
407 MachineInstrBuilder MIB(MF, NewMI);
408
409 // No need to fold return, the meta data, and function arguments
410 for (unsigned i = 0; i < StartIdx; ++i)
411 MIB.addOperand(MI->getOperand(i));
412
413 for (unsigned i = StartIdx; i < MI->getNumOperands(); ++i) {
414 MachineOperand &MO = MI->getOperand(i);
415 if (std::find(Ops.begin(), Ops.end(), i) != Ops.end()) {
416 unsigned SpillSize;
417 unsigned SpillOffset;
418 // Compute the spill slot size and offset.
419 const TargetRegisterClass *RC =
420 MF.getRegInfo().getRegClass(MO.getReg());
421 bool Valid = TII.getStackSlotRange(RC, MO.getSubReg(), SpillSize,
422 SpillOffset, &MF.getTarget());
423 if (!Valid)
424 report_fatal_error("cannot spill patchpoint subregister operand");
425 MIB.addImm(StackMaps::IndirectMemRefOp);
426 MIB.addImm(SpillSize);
427 MIB.addFrameIndex(FrameIndex);
428 MIB.addImm(0);
429 }
430 else
431 MIB.addOperand(MO);
432 }
433 return NewMI;
434}
435
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000436/// foldMemoryOperand - Attempt to fold a load or store of the specified stack
437/// slot into the specified machine instruction for the specified operand(s).
438/// If this is possible, a new instruction is returned with the specified
439/// operand folded, otherwise NULL is returned. The client is responsible for
440/// removing the old instruction and adding the new one in the instruction
441/// stream.
442MachineInstr*
443TargetInstrInfo::foldMemoryOperand(MachineBasicBlock::iterator MI,
444 const SmallVectorImpl<unsigned> &Ops,
445 int FI) const {
446 unsigned Flags = 0;
447 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
448 if (MI->getOperand(Ops[i]).isDef())
449 Flags |= MachineMemOperand::MOStore;
450 else
451 Flags |= MachineMemOperand::MOLoad;
452
453 MachineBasicBlock *MBB = MI->getParent();
454 assert(MBB && "foldMemoryOperand needs an inserted instruction");
455 MachineFunction &MF = *MBB->getParent();
456
Lang Hames39609992013-11-29 03:07:54 +0000457 MachineInstr *NewMI = 0;
458
459 if (MI->getOpcode() == TargetOpcode::STACKMAP ||
460 MI->getOpcode() == TargetOpcode::PATCHPOINT) {
461 // Fold stackmap/patchpoint.
462 NewMI = foldPatchpoint(MF, MI, Ops, FI, *this);
463 } else {
464 // Ask the target to do the actual folding.
465 NewMI =foldMemoryOperandImpl(MF, MI, Ops, FI);
466 }
467
468 if (NewMI) {
Andrew Tricka9f4d922013-11-14 23:45:04 +0000469 NewMI->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000470 // Add a memory operand, foldMemoryOperandImpl doesn't do that.
471 assert((!(Flags & MachineMemOperand::MOStore) ||
472 NewMI->mayStore()) &&
473 "Folded a def to a non-store!");
474 assert((!(Flags & MachineMemOperand::MOLoad) ||
475 NewMI->mayLoad()) &&
476 "Folded a use to a non-load!");
477 const MachineFrameInfo &MFI = *MF.getFrameInfo();
478 assert(MFI.getObjectOffset(FI) != -1);
479 MachineMemOperand *MMO =
480 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
481 Flags, MFI.getObjectSize(FI),
482 MFI.getObjectAlignment(FI));
483 NewMI->addMemOperand(MF, MMO);
484
485 // FIXME: change foldMemoryOperandImpl semantics to also insert NewMI.
486 return MBB->insert(MI, NewMI);
487 }
488
489 // Straight COPY may fold as load/store.
490 if (!MI->isCopy() || Ops.size() != 1)
491 return 0;
492
493 const TargetRegisterClass *RC = canFoldCopy(MI, Ops[0]);
494 if (!RC)
495 return 0;
496
497 const MachineOperand &MO = MI->getOperand(1-Ops[0]);
498 MachineBasicBlock::iterator Pos = MI;
499 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
500
501 if (Flags == MachineMemOperand::MOStore)
502 storeRegToStackSlot(*MBB, Pos, MO.getReg(), MO.isKill(), FI, RC, TRI);
503 else
504 loadRegFromStackSlot(*MBB, Pos, MO.getReg(), FI, RC, TRI);
505 return --Pos;
506}
507
508/// foldMemoryOperand - Same as the previous version except it allows folding
509/// of any load and store from / to any address, not just from a specific
510/// stack slot.
511MachineInstr*
512TargetInstrInfo::foldMemoryOperand(MachineBasicBlock::iterator MI,
513 const SmallVectorImpl<unsigned> &Ops,
514 MachineInstr* LoadMI) const {
515 assert(LoadMI->canFoldAsLoad() && "LoadMI isn't foldable!");
516#ifndef NDEBUG
517 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
518 assert(MI->getOperand(Ops[i]).isUse() && "Folding load into def!");
519#endif
520 MachineBasicBlock &MBB = *MI->getParent();
521 MachineFunction &MF = *MBB.getParent();
522
523 // Ask the target to do the actual folding.
Lang Hames39609992013-11-29 03:07:54 +0000524 MachineInstr *NewMI = 0;
525 int FrameIndex = 0;
526
527 if ((MI->getOpcode() == TargetOpcode::STACKMAP ||
528 MI->getOpcode() == TargetOpcode::PATCHPOINT) &&
529 isLoadFromStackSlot(LoadMI, FrameIndex)) {
530 // Fold stackmap/patchpoint.
531 NewMI = foldPatchpoint(MF, MI, Ops, FrameIndex, *this);
532 } else {
533 // Ask the target to do the actual folding.
534 NewMI =foldMemoryOperandImpl(MF, MI, Ops, LoadMI);
535 }
536 foldMemoryOperandImpl(MF, MI, Ops, LoadMI);
537
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000538 if (!NewMI) return 0;
539
540 NewMI = MBB.insert(MI, NewMI);
541
542 // Copy the memoperands from the load to the folded instruction.
Andrew Tricka9f4d922013-11-14 23:45:04 +0000543 if (MI->memoperands_empty()) {
544 NewMI->setMemRefs(LoadMI->memoperands_begin(),
545 LoadMI->memoperands_end());
546 }
547 else {
548 // Handle the rare case of folding multiple loads.
549 NewMI->setMemRefs(MI->memoperands_begin(),
550 MI->memoperands_end());
551 for (MachineInstr::mmo_iterator I = LoadMI->memoperands_begin(),
552 E = LoadMI->memoperands_end(); I != E; ++I) {
553 NewMI->addMemOperand(MF, *I);
554 }
555 }
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000556 return NewMI;
557}
558
559bool TargetInstrInfo::
560isReallyTriviallyReMaterializableGeneric(const MachineInstr *MI,
561 AliasAnalysis *AA) const {
562 const MachineFunction &MF = *MI->getParent()->getParent();
563 const MachineRegisterInfo &MRI = MF.getRegInfo();
564 const TargetMachine &TM = MF.getTarget();
565 const TargetInstrInfo &TII = *TM.getInstrInfo();
566
567 // Remat clients assume operand 0 is the defined register.
568 if (!MI->getNumOperands() || !MI->getOperand(0).isReg())
569 return false;
570 unsigned DefReg = MI->getOperand(0).getReg();
571
572 // A sub-register definition can only be rematerialized if the instruction
573 // doesn't read the other parts of the register. Otherwise it is really a
574 // read-modify-write operation on the full virtual register which cannot be
575 // moved safely.
576 if (TargetRegisterInfo::isVirtualRegister(DefReg) &&
577 MI->getOperand(0).getSubReg() && MI->readsVirtualRegister(DefReg))
578 return false;
579
580 // A load from a fixed stack slot can be rematerialized. This may be
581 // redundant with subsequent checks, but it's target-independent,
582 // simple, and a common case.
583 int FrameIdx = 0;
584 if (TII.isLoadFromStackSlot(MI, FrameIdx) &&
585 MF.getFrameInfo()->isImmutableObjectIndex(FrameIdx))
586 return true;
587
588 // Avoid instructions obviously unsafe for remat.
589 if (MI->isNotDuplicable() || MI->mayStore() ||
590 MI->hasUnmodeledSideEffects())
591 return false;
592
593 // Don't remat inline asm. We have no idea how expensive it is
594 // even if it's side effect free.
595 if (MI->isInlineAsm())
596 return false;
597
598 // Avoid instructions which load from potentially varying memory.
599 if (MI->mayLoad() && !MI->isInvariantLoad(AA))
600 return false;
601
602 // If any of the registers accessed are non-constant, conservatively assume
603 // the instruction is not rematerializable.
604 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
605 const MachineOperand &MO = MI->getOperand(i);
606 if (!MO.isReg()) continue;
607 unsigned Reg = MO.getReg();
608 if (Reg == 0)
609 continue;
610
611 // Check for a well-behaved physical register.
612 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
613 if (MO.isUse()) {
614 // If the physreg has no defs anywhere, it's just an ambient register
615 // and we can freely move its uses. Alternatively, if it's allocatable,
616 // it could get allocated to something with a def during allocation.
617 if (!MRI.isConstantPhysReg(Reg, MF))
618 return false;
619 } else {
620 // A physreg def. We can't remat it.
621 return false;
622 }
623 continue;
624 }
625
626 // Only allow one virtual-register def. There may be multiple defs of the
627 // same virtual register, though.
628 if (MO.isDef() && Reg != DefReg)
629 return false;
630
631 // Don't allow any virtual-register uses. Rematting an instruction with
632 // virtual register uses would length the live ranges of the uses, which
633 // is not necessarily a good idea, certainly not "trivial".
634 if (MO.isUse())
635 return false;
636 }
637
638 // Everything checked out.
639 return true;
640}
641
642/// isSchedulingBoundary - Test if the given instruction should be
643/// considered a scheduling boundary. This primarily includes labels
644/// and terminators.
645bool TargetInstrInfo::isSchedulingBoundary(const MachineInstr *MI,
646 const MachineBasicBlock *MBB,
647 const MachineFunction &MF) const {
648 // Terminators and labels can't be scheduled around.
649 if (MI->isTerminator() || MI->isLabel())
650 return true;
651
652 // Don't attempt to schedule around any instruction that defines
653 // a stack-oriented pointer, as it's unlikely to be profitable. This
654 // saves compile time, because it doesn't require every single
655 // stack slot reference to depend on the instruction that does the
656 // modification.
657 const TargetLowering &TLI = *MF.getTarget().getTargetLowering();
658 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
659 if (MI->modifiesRegister(TLI.getStackPointerRegisterToSaveRestore(), TRI))
660 return true;
661
662 return false;
663}
664
665// Provide a global flag for disabling the PreRA hazard recognizer that targets
666// may choose to honor.
667bool TargetInstrInfo::usePreRAHazardRecognizer() const {
668 return !DisableHazardRecognizer;
669}
670
671// Default implementation of CreateTargetRAHazardRecognizer.
672ScheduleHazardRecognizer *TargetInstrInfo::
673CreateTargetHazardRecognizer(const TargetMachine *TM,
674 const ScheduleDAG *DAG) const {
675 // Dummy hazard recognizer allows all instructions to issue.
676 return new ScheduleHazardRecognizer();
677}
678
679// Default implementation of CreateTargetMIHazardRecognizer.
680ScheduleHazardRecognizer *TargetInstrInfo::
681CreateTargetMIHazardRecognizer(const InstrItineraryData *II,
682 const ScheduleDAG *DAG) const {
683 return (ScheduleHazardRecognizer *)
684 new ScoreboardHazardRecognizer(II, DAG, "misched");
685}
686
687// Default implementation of CreateTargetPostRAHazardRecognizer.
688ScheduleHazardRecognizer *TargetInstrInfo::
689CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
690 const ScheduleDAG *DAG) const {
691 return (ScheduleHazardRecognizer *)
692 new ScoreboardHazardRecognizer(II, DAG, "post-RA-sched");
693}
694
695//===----------------------------------------------------------------------===//
696// SelectionDAG latency interface.
697//===----------------------------------------------------------------------===//
698
699int
700TargetInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
701 SDNode *DefNode, unsigned DefIdx,
702 SDNode *UseNode, unsigned UseIdx) const {
703 if (!ItinData || ItinData->isEmpty())
704 return -1;
705
706 if (!DefNode->isMachineOpcode())
707 return -1;
708
709 unsigned DefClass = get(DefNode->getMachineOpcode()).getSchedClass();
710 if (!UseNode->isMachineOpcode())
711 return ItinData->getOperandCycle(DefClass, DefIdx);
712 unsigned UseClass = get(UseNode->getMachineOpcode()).getSchedClass();
713 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
714}
715
716int TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
717 SDNode *N) const {
718 if (!ItinData || ItinData->isEmpty())
719 return 1;
720
721 if (!N->isMachineOpcode())
722 return 1;
723
724 return ItinData->getStageLatency(get(N->getMachineOpcode()).getSchedClass());
725}
726
727//===----------------------------------------------------------------------===//
728// MachineInstr latency interface.
729//===----------------------------------------------------------------------===//
730
731unsigned
732TargetInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
733 const MachineInstr *MI) const {
734 if (!ItinData || ItinData->isEmpty())
735 return 1;
736
737 unsigned Class = MI->getDesc().getSchedClass();
738 int UOps = ItinData->Itineraries[Class].NumMicroOps;
739 if (UOps >= 0)
740 return UOps;
741
742 // The # of u-ops is dynamically determined. The specific target should
743 // override this function to return the right number.
744 return 1;
745}
746
747/// Return the default expected latency for a def based on it's opcode.
748unsigned TargetInstrInfo::defaultDefLatency(const MCSchedModel *SchedModel,
749 const MachineInstr *DefMI) const {
750 if (DefMI->isTransient())
751 return 0;
752 if (DefMI->mayLoad())
753 return SchedModel->LoadLatency;
754 if (isHighLatencyDef(DefMI->getOpcode()))
755 return SchedModel->HighLatency;
756 return 1;
757}
758
Arnold Schwaighoferd2f96b92013-09-30 15:28:56 +0000759unsigned TargetInstrInfo::getPredicationCost(const MachineInstr *) const {
760 return 0;
761}
762
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000763unsigned TargetInstrInfo::
764getInstrLatency(const InstrItineraryData *ItinData,
765 const MachineInstr *MI,
766 unsigned *PredCost) const {
767 // Default to one cycle for no itinerary. However, an "empty" itinerary may
768 // still have a MinLatency property, which getStageLatency checks.
769 if (!ItinData)
770 return MI->mayLoad() ? 2 : 1;
771
772 return ItinData->getStageLatency(MI->getDesc().getSchedClass());
773}
774
775bool TargetInstrInfo::hasLowDefLatency(const InstrItineraryData *ItinData,
776 const MachineInstr *DefMI,
777 unsigned DefIdx) const {
778 if (!ItinData || ItinData->isEmpty())
779 return false;
780
781 unsigned DefClass = DefMI->getDesc().getSchedClass();
782 int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
783 return (DefCycle != -1 && DefCycle <= 1);
784}
785
786/// Both DefMI and UseMI must be valid. By default, call directly to the
787/// itinerary. This may be overriden by the target.
788int TargetInstrInfo::
789getOperandLatency(const InstrItineraryData *ItinData,
790 const MachineInstr *DefMI, unsigned DefIdx,
791 const MachineInstr *UseMI, unsigned UseIdx) const {
792 unsigned DefClass = DefMI->getDesc().getSchedClass();
793 unsigned UseClass = UseMI->getDesc().getSchedClass();
794 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
795}
796
797/// If we can determine the operand latency from the def only, without itinerary
798/// lookup, do so. Otherwise return -1.
799int TargetInstrInfo::computeDefOperandLatency(
800 const InstrItineraryData *ItinData,
Andrew Trickde2109e2013-06-15 04:49:57 +0000801 const MachineInstr *DefMI) const {
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000802
803 // Let the target hook getInstrLatency handle missing itineraries.
804 if (!ItinData)
805 return getInstrLatency(ItinData, DefMI);
806
Andrew Trickde2109e2013-06-15 04:49:57 +0000807 if(ItinData->isEmpty())
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000808 return defaultDefLatency(ItinData->SchedModel, DefMI);
809
810 // ...operand lookup required
811 return -1;
812}
813
814/// computeOperandLatency - Compute and return the latency of the given data
815/// dependent def and use when the operand indices are already known. UseMI may
816/// be NULL for an unknown use.
817///
818/// FindMin may be set to get the minimum vs. expected latency. Minimum
819/// latency is used for scheduling groups, while expected latency is for
820/// instruction cost and critical path.
821///
822/// Depending on the subtarget's itinerary properties, this may or may not need
823/// to call getOperandLatency(). For most subtargets, we don't need DefIdx or
824/// UseIdx to compute min latency.
825unsigned TargetInstrInfo::
826computeOperandLatency(const InstrItineraryData *ItinData,
827 const MachineInstr *DefMI, unsigned DefIdx,
Andrew Trickde2109e2013-06-15 04:49:57 +0000828 const MachineInstr *UseMI, unsigned UseIdx) const {
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000829
Andrew Trickde2109e2013-06-15 04:49:57 +0000830 int DefLatency = computeDefOperandLatency(ItinData, DefMI);
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000831 if (DefLatency >= 0)
832 return DefLatency;
833
834 assert(ItinData && !ItinData->isEmpty() && "computeDefOperandLatency fail");
835
836 int OperLatency = 0;
837 if (UseMI)
838 OperLatency = getOperandLatency(ItinData, DefMI, DefIdx, UseMI, UseIdx);
839 else {
840 unsigned DefClass = DefMI->getDesc().getSchedClass();
841 OperLatency = ItinData->getOperandCycle(DefClass, DefIdx);
842 }
843 if (OperLatency >= 0)
844 return OperLatency;
845
846 // No operand latency was found.
847 unsigned InstrLatency = getInstrLatency(ItinData, DefMI);
848
849 // Expected latency is the max of the stage latency and itinerary props.
Andrew Trickde2109e2013-06-15 04:49:57 +0000850 InstrLatency = std::max(InstrLatency,
851 defaultDefLatency(ItinData->SchedModel, DefMI));
Jakob Stoklund Olesenc351aed2012-11-28 02:35:13 +0000852 return InstrLatency;
853}