1 //===-- TargetInstrInfo.cpp - Target Instruction Information --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the TargetInstrInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/TargetInstrInfo.h"
14 #include "llvm/ADT/StringExtras.h"
15 #include "llvm/CodeGen/MachineFrameInfo.h"
16 #include "llvm/CodeGen/MachineInstrBuilder.h"
17 #include "llvm/CodeGen/MachineMemOperand.h"
18 #include "llvm/CodeGen/MachineRegisterInfo.h"
19 #include "llvm/CodeGen/MachineScheduler.h"
20 #include "llvm/CodeGen/PseudoSourceValue.h"
21 #include "llvm/CodeGen/ScoreboardHazardRecognizer.h"
22 #include "llvm/CodeGen/StackMaps.h"
23 #include "llvm/CodeGen/TargetFrameLowering.h"
24 #include "llvm/CodeGen/TargetLowering.h"
25 #include "llvm/CodeGen/TargetRegisterInfo.h"
26 #include "llvm/CodeGen/TargetSchedule.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfoMetadata.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCInstrItineraries.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include <cctype>
36 
37 using namespace llvm;
38 
39 static cl::opt<bool> DisableHazardRecognizer(
40   "disable-sched-hazard", cl::Hidden, cl::init(false),
41   cl::desc("Disable hazard detection during preRA scheduling"));
42 
43 TargetInstrInfo::~TargetInstrInfo() {
44 }
45 
46 const TargetRegisterClass*
47 TargetInstrInfo::getRegClass(const MCInstrDesc &MCID, unsigned OpNum,
48                              const TargetRegisterInfo *TRI,
49                              const MachineFunction &MF) const {
50   if (OpNum >= MCID.getNumOperands())
51     return nullptr;
52 
53   short RegClass = MCID.OpInfo[OpNum].RegClass;
54   if (MCID.OpInfo[OpNum].isLookupPtrRegClass())
55     return TRI->getPointerRegClass(MF, RegClass);
56 
57   // Instructions like INSERT_SUBREG do not have fixed register classes.
58   if (RegClass < 0)
59     return nullptr;
60 
61   // Otherwise just look it up normally.
62   return TRI->getRegClass(RegClass);
63 }
64 
65 /// insertNoop - Insert a noop into the instruction stream at the specified
66 /// point.
67 void TargetInstrInfo::insertNoop(MachineBasicBlock &MBB,
68                                  MachineBasicBlock::iterator MI) const {
69   llvm_unreachable("Target didn't implement insertNoop!");
70 }
71 
72 static bool isAsmComment(const char *Str, const MCAsmInfo &MAI) {
73   return strncmp(Str, MAI.getCommentString().data(),
74                  MAI.getCommentString().size()) == 0;
75 }
76 
77 /// Measure the specified inline asm to determine an approximation of its
78 /// length.
79 /// Comments (which run till the next SeparatorString or newline) do not
80 /// count as an instruction.
81 /// Any other non-whitespace text is considered an instruction, with
82 /// multiple instructions separated by SeparatorString or newlines.
83 /// Variable-length instructions are not handled here; this function
84 /// may be overloaded in the target code to do that.
85 /// We implement a special case of the .space directive which takes only a
86 /// single integer argument in base 10 that is the size in bytes. This is a
87 /// restricted form of the GAS directive in that we only interpret
88 /// simple--i.e. not a logical or arithmetic expression--size values without
89 /// the optional fill value. This is primarily used for creating arbitrary
90 /// sized inline asm blocks for testing purposes.
91 unsigned TargetInstrInfo::getInlineAsmLength(
92   const char *Str,
93   const MCAsmInfo &MAI, const TargetSubtargetInfo *STI) const {
94   // Count the number of instructions in the asm.
95   bool AtInsnStart = true;
96   unsigned Length = 0;
97   const unsigned MaxInstLength = MAI.getMaxInstLength(STI);
98   for (; *Str; ++Str) {
99     if (*Str == '\n' || strncmp(Str, MAI.getSeparatorString(),
100                                 strlen(MAI.getSeparatorString())) == 0) {
101       AtInsnStart = true;
102     } else if (isAsmComment(Str, MAI)) {
103       // Stop counting as an instruction after a comment until the next
104       // separator.
105       AtInsnStart = false;
106     }
107 
108     if (AtInsnStart && !isSpace(static_cast<unsigned char>(*Str))) {
109       unsigned AddLength = MaxInstLength;
110       if (strncmp(Str, ".space", 6) == 0) {
111         char *EStr;
112         int SpaceSize;
113         SpaceSize = strtol(Str + 6, &EStr, 10);
114         SpaceSize = SpaceSize < 0 ? 0 : SpaceSize;
115         while (*EStr != '\n' && isSpace(static_cast<unsigned char>(*EStr)))
116           ++EStr;
117         if (*EStr == '\0' || *EStr == '\n' ||
118             isAsmComment(EStr, MAI)) // Successfully parsed .space argument
119           AddLength = SpaceSize;
120       }
121       Length += AddLength;
122       AtInsnStart = false;
123     }
124   }
125 
126   return Length;
127 }
128 
129 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
130 /// after it, replacing it with an unconditional branch to NewDest.
131 void
132 TargetInstrInfo::ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
133                                          MachineBasicBlock *NewDest) const {
134   MachineBasicBlock *MBB = Tail->getParent();
135 
136   // Remove all the old successors of MBB from the CFG.
137   while (!MBB->succ_empty())
138     MBB->removeSuccessor(MBB->succ_begin());
139 
140   // Save off the debug loc before erasing the instruction.
141   DebugLoc DL = Tail->getDebugLoc();
142 
143   // Update call site info and remove all the dead instructions
144   // from the end of MBB.
145   while (Tail != MBB->end()) {
146     auto MI = Tail++;
147     if (MI->shouldUpdateCallSiteInfo())
148       MBB->getParent()->eraseCallSiteInfo(&*MI);
149     MBB->erase(MI);
150   }
151 
152   // If MBB isn't immediately before MBB, insert a branch to it.
153   if (++MachineFunction::iterator(MBB) != MachineFunction::iterator(NewDest))
154     insertBranch(*MBB, NewDest, nullptr, SmallVector<MachineOperand, 0>(), DL);
155   MBB->addSuccessor(NewDest);
156 }
157 
158 MachineInstr *TargetInstrInfo::commuteInstructionImpl(MachineInstr &MI,
159                                                       bool NewMI, unsigned Idx1,
160                                                       unsigned Idx2) const {
161   const MCInstrDesc &MCID = MI.getDesc();
162   bool HasDef = MCID.getNumDefs();
163   if (HasDef && !MI.getOperand(0).isReg())
164     // No idea how to commute this instruction. Target should implement its own.
165     return nullptr;
166 
167   unsigned CommutableOpIdx1 = Idx1; (void)CommutableOpIdx1;
168   unsigned CommutableOpIdx2 = Idx2; (void)CommutableOpIdx2;
169   assert(findCommutedOpIndices(MI, CommutableOpIdx1, CommutableOpIdx2) &&
170          CommutableOpIdx1 == Idx1 && CommutableOpIdx2 == Idx2 &&
171          "TargetInstrInfo::CommuteInstructionImpl(): not commutable operands.");
172   assert(MI.getOperand(Idx1).isReg() && MI.getOperand(Idx2).isReg() &&
173          "This only knows how to commute register operands so far");
174 
175   Register Reg0 = HasDef ? MI.getOperand(0).getReg() : Register();
176   Register Reg1 = MI.getOperand(Idx1).getReg();
177   Register Reg2 = MI.getOperand(Idx2).getReg();
178   unsigned SubReg0 = HasDef ? MI.getOperand(0).getSubReg() : 0;
179   unsigned SubReg1 = MI.getOperand(Idx1).getSubReg();
180   unsigned SubReg2 = MI.getOperand(Idx2).getSubReg();
181   bool Reg1IsKill = MI.getOperand(Idx1).isKill();
182   bool Reg2IsKill = MI.getOperand(Idx2).isKill();
183   bool Reg1IsUndef = MI.getOperand(Idx1).isUndef();
184   bool Reg2IsUndef = MI.getOperand(Idx2).isUndef();
185   bool Reg1IsInternal = MI.getOperand(Idx1).isInternalRead();
186   bool Reg2IsInternal = MI.getOperand(Idx2).isInternalRead();
187   // Avoid calling isRenamable for virtual registers since we assert that
188   // renamable property is only queried/set for physical registers.
189   bool Reg1IsRenamable = Register::isPhysicalRegister(Reg1)
190                              ? MI.getOperand(Idx1).isRenamable()
191                              : false;
192   bool Reg2IsRenamable = Register::isPhysicalRegister(Reg2)
193                              ? MI.getOperand(Idx2).isRenamable()
194                              : false;
195   // If destination is tied to either of the commuted source register, then
196   // it must be updated.
197   if (HasDef && Reg0 == Reg1 &&
198       MI.getDesc().getOperandConstraint(Idx1, MCOI::TIED_TO) == 0) {
199     Reg2IsKill = false;
200     Reg0 = Reg2;
201     SubReg0 = SubReg2;
202   } else if (HasDef && Reg0 == Reg2 &&
203              MI.getDesc().getOperandConstraint(Idx2, MCOI::TIED_TO) == 0) {
204     Reg1IsKill = false;
205     Reg0 = Reg1;
206     SubReg0 = SubReg1;
207   }
208 
209   MachineInstr *CommutedMI = nullptr;
210   if (NewMI) {
211     // Create a new instruction.
212     MachineFunction &MF = *MI.getMF();
213     CommutedMI = MF.CloneMachineInstr(&MI);
214   } else {
215     CommutedMI = &MI;
216   }
217 
218   if (HasDef) {
219     CommutedMI->getOperand(0).setReg(Reg0);
220     CommutedMI->getOperand(0).setSubReg(SubReg0);
221   }
222   CommutedMI->getOperand(Idx2).setReg(Reg1);
223   CommutedMI->getOperand(Idx1).setReg(Reg2);
224   CommutedMI->getOperand(Idx2).setSubReg(SubReg1);
225   CommutedMI->getOperand(Idx1).setSubReg(SubReg2);
226   CommutedMI->getOperand(Idx2).setIsKill(Reg1IsKill);
227   CommutedMI->getOperand(Idx1).setIsKill(Reg2IsKill);
228   CommutedMI->getOperand(Idx2).setIsUndef(Reg1IsUndef);
229   CommutedMI->getOperand(Idx1).setIsUndef(Reg2IsUndef);
230   CommutedMI->getOperand(Idx2).setIsInternalRead(Reg1IsInternal);
231   CommutedMI->getOperand(Idx1).setIsInternalRead(Reg2IsInternal);
232   // Avoid calling setIsRenamable for virtual registers since we assert that
233   // renamable property is only queried/set for physical registers.
234   if (Register::isPhysicalRegister(Reg1))
235     CommutedMI->getOperand(Idx2).setIsRenamable(Reg1IsRenamable);
236   if (Register::isPhysicalRegister(Reg2))
237     CommutedMI->getOperand(Idx1).setIsRenamable(Reg2IsRenamable);
238   return CommutedMI;
239 }
240 
241 MachineInstr *TargetInstrInfo::commuteInstruction(MachineInstr &MI, bool NewMI,
242                                                   unsigned OpIdx1,
243                                                   unsigned OpIdx2) const {
244   // If OpIdx1 or OpIdx2 is not specified, then this method is free to choose
245   // any commutable operand, which is done in findCommutedOpIndices() method
246   // called below.
247   if ((OpIdx1 == CommuteAnyOperandIndex || OpIdx2 == CommuteAnyOperandIndex) &&
248       !findCommutedOpIndices(MI, OpIdx1, OpIdx2)) {
249     assert(MI.isCommutable() &&
250            "Precondition violation: MI must be commutable.");
251     return nullptr;
252   }
253   return commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
254 }
255 
256 bool TargetInstrInfo::fixCommutedOpIndices(unsigned &ResultIdx1,
257                                            unsigned &ResultIdx2,
258                                            unsigned CommutableOpIdx1,
259                                            unsigned CommutableOpIdx2) {
260   if (ResultIdx1 == CommuteAnyOperandIndex &&
261       ResultIdx2 == CommuteAnyOperandIndex) {
262     ResultIdx1 = CommutableOpIdx1;
263     ResultIdx2 = CommutableOpIdx2;
264   } else if (ResultIdx1 == CommuteAnyOperandIndex) {
265     if (ResultIdx2 == CommutableOpIdx1)
266       ResultIdx1 = CommutableOpIdx2;
267     else if (ResultIdx2 == CommutableOpIdx2)
268       ResultIdx1 = CommutableOpIdx1;
269     else
270       return false;
271   } else if (ResultIdx2 == CommuteAnyOperandIndex) {
272     if (ResultIdx1 == CommutableOpIdx1)
273       ResultIdx2 = CommutableOpIdx2;
274     else if (ResultIdx1 == CommutableOpIdx2)
275       ResultIdx2 = CommutableOpIdx1;
276     else
277       return false;
278   } else
279     // Check that the result operand indices match the given commutable
280     // operand indices.
281     return (ResultIdx1 == CommutableOpIdx1 && ResultIdx2 == CommutableOpIdx2) ||
282            (ResultIdx1 == CommutableOpIdx2 && ResultIdx2 == CommutableOpIdx1);
283 
284   return true;
285 }
286 
287 bool TargetInstrInfo::findCommutedOpIndices(const MachineInstr &MI,
288                                             unsigned &SrcOpIdx1,
289                                             unsigned &SrcOpIdx2) const {
290   assert(!MI.isBundle() &&
291          "TargetInstrInfo::findCommutedOpIndices() can't handle bundles");
292 
293   const MCInstrDesc &MCID = MI.getDesc();
294   if (!MCID.isCommutable())
295     return false;
296 
297   // This assumes v0 = op v1, v2 and commuting would swap v1 and v2. If this
298   // is not true, then the target must implement this.
299   unsigned CommutableOpIdx1 = MCID.getNumDefs();
300   unsigned CommutableOpIdx2 = CommutableOpIdx1 + 1;
301   if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2,
302                             CommutableOpIdx1, CommutableOpIdx2))
303     return false;
304 
305   if (!MI.getOperand(SrcOpIdx1).isReg() || !MI.getOperand(SrcOpIdx2).isReg())
306     // No idea.
307     return false;
308   return true;
309 }
310 
311 bool TargetInstrInfo::isUnpredicatedTerminator(const MachineInstr &MI) const {
312   if (!MI.isTerminator()) return false;
313 
314   // Conditional branch is a special case.
315   if (MI.isBranch() && !MI.isBarrier())
316     return true;
317   if (!MI.isPredicable())
318     return true;
319   return !isPredicated(MI);
320 }
321 
322 bool TargetInstrInfo::PredicateInstruction(
323     MachineInstr &MI, ArrayRef<MachineOperand> Pred) const {
324   bool MadeChange = false;
325 
326   assert(!MI.isBundle() &&
327          "TargetInstrInfo::PredicateInstruction() can't handle bundles");
328 
329   const MCInstrDesc &MCID = MI.getDesc();
330   if (!MI.isPredicable())
331     return false;
332 
333   for (unsigned j = 0, i = 0, e = MI.getNumOperands(); i != e; ++i) {
334     if (MCID.OpInfo[i].isPredicate()) {
335       MachineOperand &MO = MI.getOperand(i);
336       if (MO.isReg()) {
337         MO.setReg(Pred[j].getReg());
338         MadeChange = true;
339       } else if (MO.isImm()) {
340         MO.setImm(Pred[j].getImm());
341         MadeChange = true;
342       } else if (MO.isMBB()) {
343         MO.setMBB(Pred[j].getMBB());
344         MadeChange = true;
345       }
346       ++j;
347     }
348   }
349   return MadeChange;
350 }
351 
352 bool TargetInstrInfo::hasLoadFromStackSlot(
353     const MachineInstr &MI,
354     SmallVectorImpl<const MachineMemOperand *> &Accesses) const {
355   size_t StartSize = Accesses.size();
356   for (MachineInstr::mmo_iterator o = MI.memoperands_begin(),
357                                   oe = MI.memoperands_end();
358        o != oe; ++o) {
359     if ((*o)->isLoad() &&
360         dyn_cast_or_null<FixedStackPseudoSourceValue>((*o)->getPseudoValue()))
361       Accesses.push_back(*o);
362   }
363   return Accesses.size() != StartSize;
364 }
365 
366 bool TargetInstrInfo::hasStoreToStackSlot(
367     const MachineInstr &MI,
368     SmallVectorImpl<const MachineMemOperand *> &Accesses) const {
369   size_t StartSize = Accesses.size();
370   for (MachineInstr::mmo_iterator o = MI.memoperands_begin(),
371                                   oe = MI.memoperands_end();
372        o != oe; ++o) {
373     if ((*o)->isStore() &&
374         dyn_cast_or_null<FixedStackPseudoSourceValue>((*o)->getPseudoValue()))
375       Accesses.push_back(*o);
376   }
377   return Accesses.size() != StartSize;
378 }
379 
380 bool TargetInstrInfo::getStackSlotRange(const TargetRegisterClass *RC,
381                                         unsigned SubIdx, unsigned &Size,
382                                         unsigned &Offset,
383                                         const MachineFunction &MF) const {
384   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
385   if (!SubIdx) {
386     Size = TRI->getSpillSize(*RC);
387     Offset = 0;
388     return true;
389   }
390   unsigned BitSize = TRI->getSubRegIdxSize(SubIdx);
391   // Convert bit size to byte size.
392   if (BitSize % 8)
393     return false;
394 
395   int BitOffset = TRI->getSubRegIdxOffset(SubIdx);
396   if (BitOffset < 0 || BitOffset % 8)
397     return false;
398 
399   Size = BitSize / 8;
400   Offset = (unsigned)BitOffset / 8;
401 
402   assert(TRI->getSpillSize(*RC) >= (Offset + Size) && "bad subregister range");
403 
404   if (!MF.getDataLayout().isLittleEndian()) {
405     Offset = TRI->getSpillSize(*RC) - (Offset + Size);
406   }
407   return true;
408 }
409 
410 void TargetInstrInfo::reMaterialize(MachineBasicBlock &MBB,
411                                     MachineBasicBlock::iterator I,
412                                     Register DestReg, unsigned SubIdx,
413                                     const MachineInstr &Orig,
414                                     const TargetRegisterInfo &TRI) const {
415   MachineInstr *MI = MBB.getParent()->CloneMachineInstr(&Orig);
416   MI->substituteRegister(MI->getOperand(0).getReg(), DestReg, SubIdx, TRI);
417   MBB.insert(I, MI);
418 }
419 
420 bool TargetInstrInfo::produceSameValue(const MachineInstr &MI0,
421                                        const MachineInstr &MI1,
422                                        const MachineRegisterInfo *MRI) const {
423   return MI0.isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
424 }
425 
426 MachineInstr &TargetInstrInfo::duplicate(MachineBasicBlock &MBB,
427     MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) const {
428   assert(!Orig.isNotDuplicable() && "Instruction cannot be duplicated");
429   MachineFunction &MF = *MBB.getParent();
430   return MF.CloneMachineInstrBundle(MBB, InsertBefore, Orig);
431 }
432 
433 // If the COPY instruction in MI can be folded to a stack operation, return
434 // the register class to use.
435 static const TargetRegisterClass *canFoldCopy(const MachineInstr &MI,
436                                               unsigned FoldIdx) {
437   assert(MI.isCopy() && "MI must be a COPY instruction");
438   if (MI.getNumOperands() != 2)
439     return nullptr;
440   assert(FoldIdx<2 && "FoldIdx refers no nonexistent operand");
441 
442   const MachineOperand &FoldOp = MI.getOperand(FoldIdx);
443   const MachineOperand &LiveOp = MI.getOperand(1 - FoldIdx);
444 
445   if (FoldOp.getSubReg() || LiveOp.getSubReg())
446     return nullptr;
447 
448   Register FoldReg = FoldOp.getReg();
449   Register LiveReg = LiveOp.getReg();
450 
451   assert(Register::isVirtualRegister(FoldReg) && "Cannot fold physregs");
452 
453   const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
454   const TargetRegisterClass *RC = MRI.getRegClass(FoldReg);
455 
456   if (Register::isPhysicalRegister(LiveOp.getReg()))
457     return RC->contains(LiveOp.getReg()) ? RC : nullptr;
458 
459   if (RC->hasSubClassEq(MRI.getRegClass(LiveReg)))
460     return RC;
461 
462   // FIXME: Allow folding when register classes are memory compatible.
463   return nullptr;
464 }
465 
466 void TargetInstrInfo::getNoop(MCInst &NopInst) const {
467   llvm_unreachable("Not implemented");
468 }
469 
470 static MachineInstr *foldPatchpoint(MachineFunction &MF, MachineInstr &MI,
471                                     ArrayRef<unsigned> Ops, int FrameIndex,
472                                     const TargetInstrInfo &TII) {
473   unsigned StartIdx = 0;
474   switch (MI.getOpcode()) {
475   case TargetOpcode::STACKMAP: {
476     // StackMapLiveValues are foldable
477     StartIdx = StackMapOpers(&MI).getVarIdx();
478     break;
479   }
480   case TargetOpcode::PATCHPOINT: {
481     // For PatchPoint, the call args are not foldable (even if reported in the
482     // stackmap e.g. via anyregcc).
483     StartIdx = PatchPointOpers(&MI).getVarIdx();
484     break;
485   }
486   case TargetOpcode::STATEPOINT: {
487     // For statepoints, fold deopt and gc arguments, but not call arguments.
488     StartIdx = StatepointOpers(&MI).getVarIdx();
489     break;
490   }
491   default:
492     llvm_unreachable("unexpected stackmap opcode");
493   }
494 
495   // Return false if any operands requested for folding are not foldable (not
496   // part of the stackmap's live values).
497   for (unsigned Op : Ops) {
498     if (Op < StartIdx)
499       return nullptr;
500   }
501 
502   MachineInstr *NewMI =
503       MF.CreateMachineInstr(TII.get(MI.getOpcode()), MI.getDebugLoc(), true);
504   MachineInstrBuilder MIB(MF, NewMI);
505 
506   // No need to fold return, the meta data, and function arguments
507   for (unsigned i = 0; i < StartIdx; ++i)
508     MIB.add(MI.getOperand(i));
509 
510   for (unsigned i = StartIdx; i < MI.getNumOperands(); ++i) {
511     MachineOperand &MO = MI.getOperand(i);
512     if (is_contained(Ops, i)) {
513       unsigned SpillSize;
514       unsigned SpillOffset;
515       // Compute the spill slot size and offset.
516       const TargetRegisterClass *RC =
517         MF.getRegInfo().getRegClass(MO.getReg());
518       bool Valid =
519           TII.getStackSlotRange(RC, MO.getSubReg(), SpillSize, SpillOffset, MF);
520       if (!Valid)
521         report_fatal_error("cannot spill patchpoint subregister operand");
522       MIB.addImm(StackMaps::IndirectMemRefOp);
523       MIB.addImm(SpillSize);
524       MIB.addFrameIndex(FrameIndex);
525       MIB.addImm(SpillOffset);
526     }
527     else
528       MIB.add(MO);
529   }
530   return NewMI;
531 }
532 
533 MachineInstr *TargetInstrInfo::foldMemoryOperand(MachineInstr &MI,
534                                                  ArrayRef<unsigned> Ops, int FI,
535                                                  LiveIntervals *LIS,
536                                                  VirtRegMap *VRM) const {
537   auto Flags = MachineMemOperand::MONone;
538   for (unsigned OpIdx : Ops)
539     Flags |= MI.getOperand(OpIdx).isDef() ? MachineMemOperand::MOStore
540                                           : MachineMemOperand::MOLoad;
541 
542   MachineBasicBlock *MBB = MI.getParent();
543   assert(MBB && "foldMemoryOperand needs an inserted instruction");
544   MachineFunction &MF = *MBB->getParent();
545 
546   // If we're not folding a load into a subreg, the size of the load is the
547   // size of the spill slot. But if we are, we need to figure out what the
548   // actual load size is.
549   int64_t MemSize = 0;
550   const MachineFrameInfo &MFI = MF.getFrameInfo();
551   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
552 
553   if (Flags & MachineMemOperand::MOStore) {
554     MemSize = MFI.getObjectSize(FI);
555   } else {
556     for (unsigned OpIdx : Ops) {
557       int64_t OpSize = MFI.getObjectSize(FI);
558 
559       if (auto SubReg = MI.getOperand(OpIdx).getSubReg()) {
560         unsigned SubRegSize = TRI->getSubRegIdxSize(SubReg);
561         if (SubRegSize > 0 && !(SubRegSize % 8))
562           OpSize = SubRegSize / 8;
563       }
564 
565       MemSize = std::max(MemSize, OpSize);
566     }
567   }
568 
569   assert(MemSize && "Did not expect a zero-sized stack slot");
570 
571   MachineInstr *NewMI = nullptr;
572 
573   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
574       MI.getOpcode() == TargetOpcode::PATCHPOINT ||
575       MI.getOpcode() == TargetOpcode::STATEPOINT) {
576     // Fold stackmap/patchpoint.
577     NewMI = foldPatchpoint(MF, MI, Ops, FI, *this);
578     if (NewMI)
579       MBB->insert(MI, NewMI);
580   } else {
581     // Ask the target to do the actual folding.
582     NewMI = foldMemoryOperandImpl(MF, MI, Ops, MI, FI, LIS, VRM);
583   }
584 
585   if (NewMI) {
586     NewMI->setMemRefs(MF, MI.memoperands());
587     // Add a memory operand, foldMemoryOperandImpl doesn't do that.
588     assert((!(Flags & MachineMemOperand::MOStore) ||
589             NewMI->mayStore()) &&
590            "Folded a def to a non-store!");
591     assert((!(Flags & MachineMemOperand::MOLoad) ||
592             NewMI->mayLoad()) &&
593            "Folded a use to a non-load!");
594     assert(MFI.getObjectOffset(FI) != -1);
595     MachineMemOperand *MMO =
596         MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
597                                 Flags, MemSize, MFI.getObjectAlign(FI));
598     NewMI->addMemOperand(MF, MMO);
599 
600     return NewMI;
601   }
602 
603   // Straight COPY may fold as load/store.
604   if (!MI.isCopy() || Ops.size() != 1)
605     return nullptr;
606 
607   const TargetRegisterClass *RC = canFoldCopy(MI, Ops[0]);
608   if (!RC)
609     return nullptr;
610 
611   const MachineOperand &MO = MI.getOperand(1 - Ops[0]);
612   MachineBasicBlock::iterator Pos = MI;
613 
614   if (Flags == MachineMemOperand::MOStore)
615     storeRegToStackSlot(*MBB, Pos, MO.getReg(), MO.isKill(), FI, RC, TRI);
616   else
617     loadRegFromStackSlot(*MBB, Pos, MO.getReg(), FI, RC, TRI);
618   return &*--Pos;
619 }
620 
621 MachineInstr *TargetInstrInfo::foldMemoryOperand(MachineInstr &MI,
622                                                  ArrayRef<unsigned> Ops,
623                                                  MachineInstr &LoadMI,
624                                                  LiveIntervals *LIS) const {
625   assert(LoadMI.canFoldAsLoad() && "LoadMI isn't foldable!");
626 #ifndef NDEBUG
627   for (unsigned OpIdx : Ops)
628     assert(MI.getOperand(OpIdx).isUse() && "Folding load into def!");
629 #endif
630 
631   MachineBasicBlock &MBB = *MI.getParent();
632   MachineFunction &MF = *MBB.getParent();
633 
634   // Ask the target to do the actual folding.
635   MachineInstr *NewMI = nullptr;
636   int FrameIndex = 0;
637 
638   if ((MI.getOpcode() == TargetOpcode::STACKMAP ||
639        MI.getOpcode() == TargetOpcode::PATCHPOINT ||
640        MI.getOpcode() == TargetOpcode::STATEPOINT) &&
641       isLoadFromStackSlot(LoadMI, FrameIndex)) {
642     // Fold stackmap/patchpoint.
643     NewMI = foldPatchpoint(MF, MI, Ops, FrameIndex, *this);
644     if (NewMI)
645       NewMI = &*MBB.insert(MI, NewMI);
646   } else {
647     // Ask the target to do the actual folding.
648     NewMI = foldMemoryOperandImpl(MF, MI, Ops, MI, LoadMI, LIS);
649   }
650 
651   if (!NewMI)
652     return nullptr;
653 
654   // Copy the memoperands from the load to the folded instruction.
655   if (MI.memoperands_empty()) {
656     NewMI->setMemRefs(MF, LoadMI.memoperands());
657   } else {
658     // Handle the rare case of folding multiple loads.
659     NewMI->setMemRefs(MF, MI.memoperands());
660     for (MachineInstr::mmo_iterator I = LoadMI.memoperands_begin(),
661                                     E = LoadMI.memoperands_end();
662          I != E; ++I) {
663       NewMI->addMemOperand(MF, *I);
664     }
665   }
666   return NewMI;
667 }
668 
669 bool TargetInstrInfo::hasReassociableOperands(
670     const MachineInstr &Inst, const MachineBasicBlock *MBB) const {
671   const MachineOperand &Op1 = Inst.getOperand(1);
672   const MachineOperand &Op2 = Inst.getOperand(2);
673   const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
674 
675   // We need virtual register definitions for the operands that we will
676   // reassociate.
677   MachineInstr *MI1 = nullptr;
678   MachineInstr *MI2 = nullptr;
679   if (Op1.isReg() && Register::isVirtualRegister(Op1.getReg()))
680     MI1 = MRI.getUniqueVRegDef(Op1.getReg());
681   if (Op2.isReg() && Register::isVirtualRegister(Op2.getReg()))
682     MI2 = MRI.getUniqueVRegDef(Op2.getReg());
683 
684   // And they need to be in the trace (otherwise, they won't have a depth).
685   return MI1 && MI2 && MI1->getParent() == MBB && MI2->getParent() == MBB;
686 }
687 
688 bool TargetInstrInfo::hasReassociableSibling(const MachineInstr &Inst,
689                                              bool &Commuted) const {
690   const MachineBasicBlock *MBB = Inst.getParent();
691   const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
692   MachineInstr *MI1 = MRI.getUniqueVRegDef(Inst.getOperand(1).getReg());
693   MachineInstr *MI2 = MRI.getUniqueVRegDef(Inst.getOperand(2).getReg());
694   unsigned AssocOpcode = Inst.getOpcode();
695 
696   // If only one operand has the same opcode and it's the second source operand,
697   // the operands must be commuted.
698   Commuted = MI1->getOpcode() != AssocOpcode && MI2->getOpcode() == AssocOpcode;
699   if (Commuted)
700     std::swap(MI1, MI2);
701 
702   // 1. The previous instruction must be the same type as Inst.
703   // 2. The previous instruction must also be associative/commutative (this can
704   //    be different even for instructions with the same opcode if traits like
705   //    fast-math-flags are included).
706   // 3. The previous instruction must have virtual register definitions for its
707   //    operands in the same basic block as Inst.
708   // 4. The previous instruction's result must only be used by Inst.
709   return MI1->getOpcode() == AssocOpcode && isAssociativeAndCommutative(*MI1) &&
710          hasReassociableOperands(*MI1, MBB) &&
711          MRI.hasOneNonDBGUse(MI1->getOperand(0).getReg());
712 }
713 
714 // 1. The operation must be associative and commutative.
715 // 2. The instruction must have virtual register definitions for its
716 //    operands in the same basic block.
717 // 3. The instruction must have a reassociable sibling.
718 bool TargetInstrInfo::isReassociationCandidate(const MachineInstr &Inst,
719                                                bool &Commuted) const {
720   return isAssociativeAndCommutative(Inst) &&
721          hasReassociableOperands(Inst, Inst.getParent()) &&
722          hasReassociableSibling(Inst, Commuted);
723 }
724 
725 // The concept of the reassociation pass is that these operations can benefit
726 // from this kind of transformation:
727 //
728 // A = ? op ?
729 // B = A op X (Prev)
730 // C = B op Y (Root)
731 // -->
732 // A = ? op ?
733 // B = X op Y
734 // C = A op B
735 //
736 // breaking the dependency between A and B, allowing them to be executed in
737 // parallel (or back-to-back in a pipeline) instead of depending on each other.
738 
739 // FIXME: This has the potential to be expensive (compile time) while not
740 // improving the code at all. Some ways to limit the overhead:
741 // 1. Track successful transforms; bail out if hit rate gets too low.
742 // 2. Only enable at -O3 or some other non-default optimization level.
743 // 3. Pre-screen pattern candidates here: if an operand of the previous
744 //    instruction is known to not increase the critical path, then don't match
745 //    that pattern.
746 bool TargetInstrInfo::getMachineCombinerPatterns(
747     MachineInstr &Root,
748     SmallVectorImpl<MachineCombinerPattern> &Patterns) const {
749   bool Commute;
750   if (isReassociationCandidate(Root, Commute)) {
751     // We found a sequence of instructions that may be suitable for a
752     // reassociation of operands to increase ILP. Specify each commutation
753     // possibility for the Prev instruction in the sequence and let the
754     // machine combiner decide if changing the operands is worthwhile.
755     if (Commute) {
756       Patterns.push_back(MachineCombinerPattern::REASSOC_AX_YB);
757       Patterns.push_back(MachineCombinerPattern::REASSOC_XA_YB);
758     } else {
759       Patterns.push_back(MachineCombinerPattern::REASSOC_AX_BY);
760       Patterns.push_back(MachineCombinerPattern::REASSOC_XA_BY);
761     }
762     return true;
763   }
764 
765   return false;
766 }
767 
768 /// Return true when a code sequence can improve loop throughput.
769 bool
770 TargetInstrInfo::isThroughputPattern(MachineCombinerPattern Pattern) const {
771   return false;
772 }
773 
774 /// Attempt the reassociation transformation to reduce critical path length.
775 /// See the above comments before getMachineCombinerPatterns().
776 void TargetInstrInfo::reassociateOps(
777     MachineInstr &Root, MachineInstr &Prev,
778     MachineCombinerPattern Pattern,
779     SmallVectorImpl<MachineInstr *> &InsInstrs,
780     SmallVectorImpl<MachineInstr *> &DelInstrs,
781     DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const {
782   MachineFunction *MF = Root.getMF();
783   MachineRegisterInfo &MRI = MF->getRegInfo();
784   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
785   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
786   const TargetRegisterClass *RC = Root.getRegClassConstraint(0, TII, TRI);
787 
788   // This array encodes the operand index for each parameter because the
789   // operands may be commuted. Each row corresponds to a pattern value,
790   // and each column specifies the index of A, B, X, Y.
791   unsigned OpIdx[4][4] = {
792     { 1, 1, 2, 2 },
793     { 1, 2, 2, 1 },
794     { 2, 1, 1, 2 },
795     { 2, 2, 1, 1 }
796   };
797 
798   int Row;
799   switch (Pattern) {
800   case MachineCombinerPattern::REASSOC_AX_BY: Row = 0; break;
801   case MachineCombinerPattern::REASSOC_AX_YB: Row = 1; break;
802   case MachineCombinerPattern::REASSOC_XA_BY: Row = 2; break;
803   case MachineCombinerPattern::REASSOC_XA_YB: Row = 3; break;
804   default: llvm_unreachable("unexpected MachineCombinerPattern");
805   }
806 
807   MachineOperand &OpA = Prev.getOperand(OpIdx[Row][0]);
808   MachineOperand &OpB = Root.getOperand(OpIdx[Row][1]);
809   MachineOperand &OpX = Prev.getOperand(OpIdx[Row][2]);
810   MachineOperand &OpY = Root.getOperand(OpIdx[Row][3]);
811   MachineOperand &OpC = Root.getOperand(0);
812 
813   Register RegA = OpA.getReg();
814   Register RegB = OpB.getReg();
815   Register RegX = OpX.getReg();
816   Register RegY = OpY.getReg();
817   Register RegC = OpC.getReg();
818 
819   if (Register::isVirtualRegister(RegA))
820     MRI.constrainRegClass(RegA, RC);
821   if (Register::isVirtualRegister(RegB))
822     MRI.constrainRegClass(RegB, RC);
823   if (Register::isVirtualRegister(RegX))
824     MRI.constrainRegClass(RegX, RC);
825   if (Register::isVirtualRegister(RegY))
826     MRI.constrainRegClass(RegY, RC);
827   if (Register::isVirtualRegister(RegC))
828     MRI.constrainRegClass(RegC, RC);
829 
830   // Create a new virtual register for the result of (X op Y) instead of
831   // recycling RegB because the MachineCombiner's computation of the critical
832   // path requires a new register definition rather than an existing one.
833   Register NewVR = MRI.createVirtualRegister(RC);
834   InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
835 
836   unsigned Opcode = Root.getOpcode();
837   bool KillA = OpA.isKill();
838   bool KillX = OpX.isKill();
839   bool KillY = OpY.isKill();
840 
841   // Create new instructions for insertion.
842   MachineInstrBuilder MIB1 =
843       BuildMI(*MF, Prev.getDebugLoc(), TII->get(Opcode), NewVR)
844           .addReg(RegX, getKillRegState(KillX))
845           .addReg(RegY, getKillRegState(KillY));
846   MachineInstrBuilder MIB2 =
847       BuildMI(*MF, Root.getDebugLoc(), TII->get(Opcode), RegC)
848           .addReg(RegA, getKillRegState(KillA))
849           .addReg(NewVR, getKillRegState(true));
850 
851   setSpecialOperandAttr(Root, Prev, *MIB1, *MIB2);
852 
853   // Record new instructions for insertion and old instructions for deletion.
854   InsInstrs.push_back(MIB1);
855   InsInstrs.push_back(MIB2);
856   DelInstrs.push_back(&Prev);
857   DelInstrs.push_back(&Root);
858 }
859 
860 void TargetInstrInfo::genAlternativeCodeSequence(
861     MachineInstr &Root, MachineCombinerPattern Pattern,
862     SmallVectorImpl<MachineInstr *> &InsInstrs,
863     SmallVectorImpl<MachineInstr *> &DelInstrs,
864     DenseMap<unsigned, unsigned> &InstIdxForVirtReg) const {
865   MachineRegisterInfo &MRI = Root.getMF()->getRegInfo();
866 
867   // Select the previous instruction in the sequence based on the input pattern.
868   MachineInstr *Prev = nullptr;
869   switch (Pattern) {
870   case MachineCombinerPattern::REASSOC_AX_BY:
871   case MachineCombinerPattern::REASSOC_XA_BY:
872     Prev = MRI.getUniqueVRegDef(Root.getOperand(1).getReg());
873     break;
874   case MachineCombinerPattern::REASSOC_AX_YB:
875   case MachineCombinerPattern::REASSOC_XA_YB:
876     Prev = MRI.getUniqueVRegDef(Root.getOperand(2).getReg());
877     break;
878   default:
879     break;
880   }
881 
882   assert(Prev && "Unknown pattern for machine combiner");
883 
884   reassociateOps(Root, *Prev, Pattern, InsInstrs, DelInstrs, InstIdxForVirtReg);
885 }
886 
887 bool TargetInstrInfo::isReallyTriviallyReMaterializableGeneric(
888     const MachineInstr &MI, AAResults *AA) const {
889   const MachineFunction &MF = *MI.getMF();
890   const MachineRegisterInfo &MRI = MF.getRegInfo();
891 
892   // Remat clients assume operand 0 is the defined register.
893   if (!MI.getNumOperands() || !MI.getOperand(0).isReg())
894     return false;
895   Register DefReg = MI.getOperand(0).getReg();
896 
897   // A sub-register definition can only be rematerialized if the instruction
898   // doesn't read the other parts of the register.  Otherwise it is really a
899   // read-modify-write operation on the full virtual register which cannot be
900   // moved safely.
901   if (Register::isVirtualRegister(DefReg) && MI.getOperand(0).getSubReg() &&
902       MI.readsVirtualRegister(DefReg))
903     return false;
904 
905   // A load from a fixed stack slot can be rematerialized. This may be
906   // redundant with subsequent checks, but it's target-independent,
907   // simple, and a common case.
908   int FrameIdx = 0;
909   if (isLoadFromStackSlot(MI, FrameIdx) &&
910       MF.getFrameInfo().isImmutableObjectIndex(FrameIdx))
911     return true;
912 
913   // Avoid instructions obviously unsafe for remat.
914   if (MI.isNotDuplicable() || MI.mayStore() || MI.mayRaiseFPException() ||
915       MI.hasUnmodeledSideEffects())
916     return false;
917 
918   // Don't remat inline asm. We have no idea how expensive it is
919   // even if it's side effect free.
920   if (MI.isInlineAsm())
921     return false;
922 
923   // Avoid instructions which load from potentially varying memory.
924   if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad(AA))
925     return false;
926 
927   // If any of the registers accessed are non-constant, conservatively assume
928   // the instruction is not rematerializable.
929   for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
930     const MachineOperand &MO = MI.getOperand(i);
931     if (!MO.isReg()) continue;
932     Register Reg = MO.getReg();
933     if (Reg == 0)
934       continue;
935 
936     // Check for a well-behaved physical register.
937     if (Register::isPhysicalRegister(Reg)) {
938       if (MO.isUse()) {
939         // If the physreg has no defs anywhere, it's just an ambient register
940         // and we can freely move its uses. Alternatively, if it's allocatable,
941         // it could get allocated to something with a def during allocation.
942         if (!MRI.isConstantPhysReg(Reg))
943           return false;
944       } else {
945         // A physreg def. We can't remat it.
946         return false;
947       }
948       continue;
949     }
950 
951     // Only allow one virtual-register def.  There may be multiple defs of the
952     // same virtual register, though.
953     if (MO.isDef() && Reg != DefReg)
954       return false;
955 
956     // Don't allow any virtual-register uses. Rematting an instruction with
957     // virtual register uses would length the live ranges of the uses, which
958     // is not necessarily a good idea, certainly not "trivial".
959     if (MO.isUse())
960       return false;
961   }
962 
963   // Everything checked out.
964   return true;
965 }
966 
967 int TargetInstrInfo::getSPAdjust(const MachineInstr &MI) const {
968   const MachineFunction *MF = MI.getMF();
969   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
970   bool StackGrowsDown =
971     TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
972 
973   unsigned FrameSetupOpcode = getCallFrameSetupOpcode();
974   unsigned FrameDestroyOpcode = getCallFrameDestroyOpcode();
975 
976   if (!isFrameInstr(MI))
977     return 0;
978 
979   int SPAdj = TFI->alignSPAdjust(getFrameSize(MI));
980 
981   if ((!StackGrowsDown && MI.getOpcode() == FrameSetupOpcode) ||
982       (StackGrowsDown && MI.getOpcode() == FrameDestroyOpcode))
983     SPAdj = -SPAdj;
984 
985   return SPAdj;
986 }
987 
988 /// isSchedulingBoundary - Test if the given instruction should be
989 /// considered a scheduling boundary. This primarily includes labels
990 /// and terminators.
991 bool TargetInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
992                                            const MachineBasicBlock *MBB,
993                                            const MachineFunction &MF) const {
994   // Terminators and labels can't be scheduled around.
995   if (MI.isTerminator() || MI.isPosition())
996     return true;
997 
998   // Don't attempt to schedule around any instruction that defines
999   // a stack-oriented pointer, as it's unlikely to be profitable. This
1000   // saves compile time, because it doesn't require every single
1001   // stack slot reference to depend on the instruction that does the
1002   // modification.
1003   const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
1004   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1005   return MI.modifiesRegister(TLI.getStackPointerRegisterToSaveRestore(), TRI);
1006 }
1007 
1008 // Provide a global flag for disabling the PreRA hazard recognizer that targets
1009 // may choose to honor.
1010 bool TargetInstrInfo::usePreRAHazardRecognizer() const {
1011   return !DisableHazardRecognizer;
1012 }
1013 
1014 // Default implementation of CreateTargetRAHazardRecognizer.
1015 ScheduleHazardRecognizer *TargetInstrInfo::
1016 CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
1017                              const ScheduleDAG *DAG) const {
1018   // Dummy hazard recognizer allows all instructions to issue.
1019   return new ScheduleHazardRecognizer();
1020 }
1021 
1022 // Default implementation of CreateTargetMIHazardRecognizer.
1023 ScheduleHazardRecognizer *TargetInstrInfo::CreateTargetMIHazardRecognizer(
1024     const InstrItineraryData *II, const ScheduleDAGMI *DAG) const {
1025   return new ScoreboardHazardRecognizer(II, DAG, "machine-scheduler");
1026 }
1027 
1028 // Default implementation of CreateTargetPostRAHazardRecognizer.
1029 ScheduleHazardRecognizer *TargetInstrInfo::
1030 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
1031                                    const ScheduleDAG *DAG) const {
1032   return new ScoreboardHazardRecognizer(II, DAG, "post-RA-sched");
1033 }
1034 
1035 // Default implementation of getMemOperandWithOffset.
1036 bool TargetInstrInfo::getMemOperandWithOffset(
1037     const MachineInstr &MI, const MachineOperand *&BaseOp, int64_t &Offset,
1038     bool &OffsetIsScalable, const TargetRegisterInfo *TRI) const {
1039   SmallVector<const MachineOperand *, 4> BaseOps;
1040   if (!getMemOperandsWithOffset(MI, BaseOps, Offset, OffsetIsScalable, TRI) ||
1041       BaseOps.size() != 1)
1042     return false;
1043   BaseOp = BaseOps.front();
1044   return true;
1045 }
1046 
1047 //===----------------------------------------------------------------------===//
1048 //  SelectionDAG latency interface.
1049 //===----------------------------------------------------------------------===//
1050 
1051 int
1052 TargetInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
1053                                    SDNode *DefNode, unsigned DefIdx,
1054                                    SDNode *UseNode, unsigned UseIdx) const {
1055   if (!ItinData || ItinData->isEmpty())
1056     return -1;
1057 
1058   if (!DefNode->isMachineOpcode())
1059     return -1;
1060 
1061   unsigned DefClass = get(DefNode->getMachineOpcode()).getSchedClass();
1062   if (!UseNode->isMachineOpcode())
1063     return ItinData->getOperandCycle(DefClass, DefIdx);
1064   unsigned UseClass = get(UseNode->getMachineOpcode()).getSchedClass();
1065   return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
1066 }
1067 
1068 int TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
1069                                      SDNode *N) const {
1070   if (!ItinData || ItinData->isEmpty())
1071     return 1;
1072 
1073   if (!N->isMachineOpcode())
1074     return 1;
1075 
1076   return ItinData->getStageLatency(get(N->getMachineOpcode()).getSchedClass());
1077 }
1078 
1079 //===----------------------------------------------------------------------===//
1080 //  MachineInstr latency interface.
1081 //===----------------------------------------------------------------------===//
1082 
1083 unsigned TargetInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
1084                                          const MachineInstr &MI) const {
1085   if (!ItinData || ItinData->isEmpty())
1086     return 1;
1087 
1088   unsigned Class = MI.getDesc().getSchedClass();
1089   int UOps = ItinData->Itineraries[Class].NumMicroOps;
1090   if (UOps >= 0)
1091     return UOps;
1092 
1093   // The # of u-ops is dynamically determined. The specific target should
1094   // override this function to return the right number.
1095   return 1;
1096 }
1097 
1098 /// Return the default expected latency for a def based on it's opcode.
1099 unsigned TargetInstrInfo::defaultDefLatency(const MCSchedModel &SchedModel,
1100                                             const MachineInstr &DefMI) const {
1101   if (DefMI.isTransient())
1102     return 0;
1103   if (DefMI.mayLoad())
1104     return SchedModel.LoadLatency;
1105   if (isHighLatencyDef(DefMI.getOpcode()))
1106     return SchedModel.HighLatency;
1107   return 1;
1108 }
1109 
1110 unsigned TargetInstrInfo::getPredicationCost(const MachineInstr &) const {
1111   return 0;
1112 }
1113 
1114 unsigned TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
1115                                           const MachineInstr &MI,
1116                                           unsigned *PredCost) const {
1117   // Default to one cycle for no itinerary. However, an "empty" itinerary may
1118   // still have a MinLatency property, which getStageLatency checks.
1119   if (!ItinData)
1120     return MI.mayLoad() ? 2 : 1;
1121 
1122   return ItinData->getStageLatency(MI.getDesc().getSchedClass());
1123 }
1124 
1125 bool TargetInstrInfo::hasLowDefLatency(const TargetSchedModel &SchedModel,
1126                                        const MachineInstr &DefMI,
1127                                        unsigned DefIdx) const {
1128   const InstrItineraryData *ItinData = SchedModel.getInstrItineraries();
1129   if (!ItinData || ItinData->isEmpty())
1130     return false;
1131 
1132   unsigned DefClass = DefMI.getDesc().getSchedClass();
1133   int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
1134   return (DefCycle != -1 && DefCycle <= 1);
1135 }
1136 
1137 Optional<ParamLoadedValue>
1138 TargetInstrInfo::describeLoadedValue(const MachineInstr &MI,
1139                                      Register Reg) const {
1140   const MachineFunction *MF = MI.getMF();
1141   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
1142   DIExpression *Expr = DIExpression::get(MF->getFunction().getContext(), {});
1143   int64_t Offset;
1144   bool OffsetIsScalable;
1145 
1146   // To simplify the sub-register handling, verify that we only need to
1147   // consider physical registers.
1148   assert(MF->getProperties().hasProperty(
1149       MachineFunctionProperties::Property::NoVRegs));
1150 
1151   if (auto DestSrc = isCopyInstr(MI)) {
1152     Register DestReg = DestSrc->Destination->getReg();
1153 
1154     // If the copy destination is the forwarding reg, describe the forwarding
1155     // reg using the copy source as the backup location. Example:
1156     //
1157     //   x0 = MOV x7
1158     //   call callee(x0)      ; x0 described as x7
1159     if (Reg == DestReg)
1160       return ParamLoadedValue(*DestSrc->Source, Expr);
1161 
1162     // Cases where super- or sub-registers needs to be described should
1163     // be handled by the target's hook implementation.
1164     assert(!TRI->isSuperOrSubRegisterEq(Reg, DestReg) &&
1165            "TargetInstrInfo::describeLoadedValue can't describe super- or "
1166            "sub-regs for copy instructions");
1167     return None;
1168   } else if (auto RegImm = isAddImmediate(MI, Reg)) {
1169     Register SrcReg = RegImm->Reg;
1170     Offset = RegImm->Imm;
1171     Expr = DIExpression::prepend(Expr, DIExpression::ApplyOffset, Offset);
1172     return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
1173   } else if (MI.hasOneMemOperand()) {
1174     // Only describe memory which provably does not escape the function. As
1175     // described in llvm.org/PR43343, escaped memory may be clobbered by the
1176     // callee (or by another thread).
1177     const auto &TII = MF->getSubtarget().getInstrInfo();
1178     const MachineFrameInfo &MFI = MF->getFrameInfo();
1179     const MachineMemOperand *MMO = MI.memoperands()[0];
1180     const PseudoSourceValue *PSV = MMO->getPseudoValue();
1181 
1182     // If the address points to "special" memory (e.g. a spill slot), it's
1183     // sufficient to check that it isn't aliased by any high-level IR value.
1184     if (!PSV || PSV->mayAlias(&MFI))
1185       return None;
1186 
1187     const MachineOperand *BaseOp;
1188     if (!TII->getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable,
1189                                       TRI))
1190       return None;
1191 
1192     // FIXME: Scalable offsets are not yet handled in the offset code below.
1193     if (OffsetIsScalable)
1194       return None;
1195 
1196     // TODO: Can currently only handle mem instructions with a single define.
1197     // An example from the x86 target:
1198     //    ...
1199     //    DIV64m $rsp, 1, $noreg, 24, $noreg, implicit-def dead $rax, implicit-def $rdx
1200     //    ...
1201     //
1202     if (MI.getNumExplicitDefs() != 1)
1203       return None;
1204 
1205     // TODO: In what way do we need to take Reg into consideration here?
1206 
1207     SmallVector<uint64_t, 8> Ops;
1208     DIExpression::appendOffset(Ops, Offset);
1209     Ops.push_back(dwarf::DW_OP_deref_size);
1210     Ops.push_back(MMO->getSize());
1211     Expr = DIExpression::prependOpcodes(Expr, Ops);
1212     return ParamLoadedValue(*BaseOp, Expr);
1213   }
1214 
1215   return None;
1216 }
1217 
1218 /// Both DefMI and UseMI must be valid.  By default, call directly to the
1219 /// itinerary. This may be overriden by the target.
1220 int TargetInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
1221                                        const MachineInstr &DefMI,
1222                                        unsigned DefIdx,
1223                                        const MachineInstr &UseMI,
1224                                        unsigned UseIdx) const {
1225   unsigned DefClass = DefMI.getDesc().getSchedClass();
1226   unsigned UseClass = UseMI.getDesc().getSchedClass();
1227   return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
1228 }
1229 
1230 /// If we can determine the operand latency from the def only, without itinerary
1231 /// lookup, do so. Otherwise return -1.
1232 int TargetInstrInfo::computeDefOperandLatency(
1233     const InstrItineraryData *ItinData, const MachineInstr &DefMI) const {
1234 
1235   // Let the target hook getInstrLatency handle missing itineraries.
1236   if (!ItinData)
1237     return getInstrLatency(ItinData, DefMI);
1238 
1239   if(ItinData->isEmpty())
1240     return defaultDefLatency(ItinData->SchedModel, DefMI);
1241 
1242   // ...operand lookup required
1243   return -1;
1244 }
1245 
1246 bool TargetInstrInfo::getRegSequenceInputs(
1247     const MachineInstr &MI, unsigned DefIdx,
1248     SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
1249   assert((MI.isRegSequence() ||
1250           MI.isRegSequenceLike()) && "Instruction do not have the proper type");
1251 
1252   if (!MI.isRegSequence())
1253     return getRegSequenceLikeInputs(MI, DefIdx, InputRegs);
1254 
1255   // We are looking at:
1256   // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1257   assert(DefIdx == 0 && "REG_SEQUENCE only has one def");
1258   for (unsigned OpIdx = 1, EndOpIdx = MI.getNumOperands(); OpIdx != EndOpIdx;
1259        OpIdx += 2) {
1260     const MachineOperand &MOReg = MI.getOperand(OpIdx);
1261     if (MOReg.isUndef())
1262       continue;
1263     const MachineOperand &MOSubIdx = MI.getOperand(OpIdx + 1);
1264     assert(MOSubIdx.isImm() &&
1265            "One of the subindex of the reg_sequence is not an immediate");
1266     // Record Reg:SubReg, SubIdx.
1267     InputRegs.push_back(RegSubRegPairAndIdx(MOReg.getReg(), MOReg.getSubReg(),
1268                                             (unsigned)MOSubIdx.getImm()));
1269   }
1270   return true;
1271 }
1272 
1273 bool TargetInstrInfo::getExtractSubregInputs(
1274     const MachineInstr &MI, unsigned DefIdx,
1275     RegSubRegPairAndIdx &InputReg) const {
1276   assert((MI.isExtractSubreg() ||
1277       MI.isExtractSubregLike()) && "Instruction do not have the proper type");
1278 
1279   if (!MI.isExtractSubreg())
1280     return getExtractSubregLikeInputs(MI, DefIdx, InputReg);
1281 
1282   // We are looking at:
1283   // Def = EXTRACT_SUBREG v0.sub1, sub0.
1284   assert(DefIdx == 0 && "EXTRACT_SUBREG only has one def");
1285   const MachineOperand &MOReg = MI.getOperand(1);
1286   if (MOReg.isUndef())
1287     return false;
1288   const MachineOperand &MOSubIdx = MI.getOperand(2);
1289   assert(MOSubIdx.isImm() &&
1290          "The subindex of the extract_subreg is not an immediate");
1291 
1292   InputReg.Reg = MOReg.getReg();
1293   InputReg.SubReg = MOReg.getSubReg();
1294   InputReg.SubIdx = (unsigned)MOSubIdx.getImm();
1295   return true;
1296 }
1297 
1298 bool TargetInstrInfo::getInsertSubregInputs(
1299     const MachineInstr &MI, unsigned DefIdx,
1300     RegSubRegPair &BaseReg, RegSubRegPairAndIdx &InsertedReg) const {
1301   assert((MI.isInsertSubreg() ||
1302       MI.isInsertSubregLike()) && "Instruction do not have the proper type");
1303 
1304   if (!MI.isInsertSubreg())
1305     return getInsertSubregLikeInputs(MI, DefIdx, BaseReg, InsertedReg);
1306 
1307   // We are looking at:
1308   // Def = INSERT_SEQUENCE v0, v1, sub0.
1309   assert(DefIdx == 0 && "INSERT_SUBREG only has one def");
1310   const MachineOperand &MOBaseReg = MI.getOperand(1);
1311   const MachineOperand &MOInsertedReg = MI.getOperand(2);
1312   if (MOInsertedReg.isUndef())
1313     return false;
1314   const MachineOperand &MOSubIdx = MI.getOperand(3);
1315   assert(MOSubIdx.isImm() &&
1316          "One of the subindex of the reg_sequence is not an immediate");
1317   BaseReg.Reg = MOBaseReg.getReg();
1318   BaseReg.SubReg = MOBaseReg.getSubReg();
1319 
1320   InsertedReg.Reg = MOInsertedReg.getReg();
1321   InsertedReg.SubReg = MOInsertedReg.getSubReg();
1322   InsertedReg.SubIdx = (unsigned)MOSubIdx.getImm();
1323   return true;
1324 }
1325 
1326 // Returns a MIRPrinter comment for this machine operand.
1327 std::string TargetInstrInfo::createMIROperandComment(
1328     const MachineInstr &MI, const MachineOperand &Op, unsigned OpIdx,
1329     const TargetRegisterInfo *TRI) const {
1330 
1331   if (!MI.isInlineAsm())
1332     return "";
1333 
1334   std::string Flags;
1335   raw_string_ostream OS(Flags);
1336 
1337   if (OpIdx == InlineAsm::MIOp_ExtraInfo) {
1338     // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1339     unsigned ExtraInfo = Op.getImm();
1340     bool First = true;
1341     for (StringRef Info : InlineAsm::getExtraInfoNames(ExtraInfo)) {
1342       if (!First)
1343         OS << " ";
1344       First = false;
1345       OS << Info;
1346     }
1347 
1348     return OS.str();
1349   }
1350 
1351   int FlagIdx = MI.findInlineAsmFlagIdx(OpIdx);
1352   if (FlagIdx < 0 || (unsigned)FlagIdx != OpIdx)
1353     return "";
1354 
1355   assert(Op.isImm() && "Expected flag operand to be an immediate");
1356   // Pretty print the inline asm operand descriptor.
1357   unsigned Flag = Op.getImm();
1358   unsigned Kind = InlineAsm::getKind(Flag);
1359   OS << InlineAsm::getKindName(Kind);
1360 
1361   unsigned RCID = 0;
1362   if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
1363       InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1364     if (TRI) {
1365       OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
1366     } else
1367       OS << ":RC" << RCID;
1368   }
1369 
1370   if (InlineAsm::isMemKind(Flag)) {
1371     unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
1372     OS << ":" << InlineAsm::getMemConstraintName(MCID);
1373   }
1374 
1375   unsigned TiedTo = 0;
1376   if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1377     OS << " tiedto:$" << TiedTo;
1378 
1379   return OS.str();
1380 }
1381 
1382 TargetInstrInfo::PipelinerLoopInfo::~PipelinerLoopInfo() {}
1383