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