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