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/SmallSet.h"
15#include "llvm/ADT/StringExtras.h"
16#include "llvm/BinaryFormat/Dwarf.h"
17#include "llvm/CodeGen/MachineCombinerPattern.h"
18#include "llvm/CodeGen/MachineFrameInfo.h"
19#include "llvm/CodeGen/MachineInstrBuilder.h"
20#include "llvm/CodeGen/MachineMemOperand.h"
21#include "llvm/CodeGen/MachineRegisterInfo.h"
22#include "llvm/CodeGen/MachineScheduler.h"
23#include "llvm/CodeGen/MachineTraceMetrics.h"
24#include "llvm/CodeGen/PseudoSourceValue.h"
25#include "llvm/CodeGen/ScoreboardHazardRecognizer.h"
26#include "llvm/CodeGen/StackMaps.h"
27#include "llvm/CodeGen/TargetFrameLowering.h"
28#include "llvm/CodeGen/TargetLowering.h"
29#include "llvm/CodeGen/TargetRegisterInfo.h"
30#include "llvm/CodeGen/TargetSchedule.h"
31#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/DebugInfoMetadata.h"
33#include "llvm/MC/MCAsmInfo.h"
34#include "llvm/MC/MCInstrItineraries.h"
35#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/InterleavedRange.h"
38#include "llvm/Support/raw_ostream.h"
39#include "llvm/Target/TargetMachine.h"
40
41using namespace llvm;
42
43static cl::opt<bool> DisableHazardRecognizer(
44 "disable-sched-hazard", cl::Hidden, cl::init(Val: false),
45 cl::desc("Disable hazard detection during preRA scheduling"));
46
47static cl::opt<bool> EnableAccReassociation(
48 "acc-reassoc", cl::Hidden, cl::init(Val: true),
49 cl::desc("Enable reassociation of accumulation chains"));
50
51static cl::opt<unsigned int>
52 MinAccumulatorDepth("acc-min-depth", cl::Hidden, cl::init(Val: 8),
53 cl::desc("Minimum length of accumulator chains "
54 "required for the optimization to kick in"));
55
56static cl::opt<unsigned int> MaxAccumulatorWidth(
57 "acc-max-width", cl::Hidden, cl::init(Val: 3),
58 cl::desc("Maximum number of branches in the accumulator tree"));
59
60TargetInstrInfo::~TargetInstrInfo() = default;
61
62const TargetRegisterClass *TargetInstrInfo::getRegClass(const MCInstrDesc &MCID,
63 unsigned OpNum) const {
64 if (OpNum >= MCID.getNumOperands())
65 return nullptr;
66
67 const MCOperandInfo &OpInfo = MCID.operands()[OpNum];
68 int16_t RegClass = getOpRegClassID(OpInfo);
69
70 // Instructions like INSERT_SUBREG do not have fixed register classes.
71 if (RegClass < 0)
72 return nullptr;
73
74 // Otherwise just look it up normally.
75 return TRI.getRegClass(i: RegClass);
76}
77
78/// insertNoop - Insert a noop into the instruction stream at the specified
79/// point.
80void TargetInstrInfo::insertNoop(MachineBasicBlock &MBB,
81 MachineBasicBlock::iterator MI) const {
82 llvm_unreachable("Target didn't implement insertNoop!");
83}
84
85/// insertNoops - Insert noops into the instruction stream at the specified
86/// point.
87void TargetInstrInfo::insertNoops(MachineBasicBlock &MBB,
88 MachineBasicBlock::iterator MI,
89 unsigned Quantity) const {
90 for (unsigned i = 0; i < Quantity; ++i)
91 insertNoop(MBB, MI);
92}
93
94static bool isAsmComment(const char *Str, const MCAsmInfo &MAI) {
95 return strncmp(s1: Str, s2: MAI.getCommentString().data(),
96 n: MAI.getCommentString().size()) == 0;
97}
98
99/// Measure the specified inline asm to determine an approximation of its
100/// length.
101/// Comments (which run till the next SeparatorString or newline) do not
102/// count as an instruction.
103/// Any other non-whitespace text is considered an instruction, with
104/// multiple instructions separated by SeparatorString or newlines.
105/// Variable-length instructions are not handled here; this function
106/// may be overloaded in the target code to do that.
107/// We implement a special case of the .space directive which takes only a
108/// single integer argument in base 10 that is the size in bytes. This is a
109/// restricted form of the GAS directive in that we only interpret
110/// simple--i.e. not a logical or arithmetic expression--size values without
111/// the optional fill value. This is primarily used for creating arbitrary
112/// sized inline asm blocks for testing purposes.
113unsigned TargetInstrInfo::getInlineAsmLength(
114 const char *Str,
115 const MCAsmInfo &MAI, const TargetSubtargetInfo *STI) const {
116 // Count the number of instructions in the asm.
117 bool AtInsnStart = true;
118 unsigned Length = 0;
119 const unsigned MaxInstLength = MAI.getMaxInstLength(STI);
120 for (; *Str; ++Str) {
121 if (*Str == '\n' || strncmp(s1: Str, s2: MAI.getSeparatorString(),
122 n: strlen(s: MAI.getSeparatorString())) == 0) {
123 AtInsnStart = true;
124 } else if (isAsmComment(Str, MAI)) {
125 // Stop counting as an instruction after a comment until the next
126 // separator.
127 AtInsnStart = false;
128 }
129
130 if (AtInsnStart && !isSpace(C: static_cast<unsigned char>(*Str))) {
131 unsigned AddLength = MaxInstLength;
132 if (strncmp(s1: Str, s2: ".space", n: 6) == 0) {
133 char *EStr;
134 int SpaceSize;
135 SpaceSize = strtol(nptr: Str + 6, endptr: &EStr, base: 10);
136 SpaceSize = SpaceSize < 0 ? 0 : SpaceSize;
137 while (*EStr != '\n' && isSpace(C: static_cast<unsigned char>(*EStr)))
138 ++EStr;
139 if (*EStr == '\0' || *EStr == '\n' ||
140 isAsmComment(Str: EStr, MAI)) // Successfully parsed .space argument
141 AddLength = SpaceSize;
142 }
143 Length += AddLength;
144 AtInsnStart = false;
145 }
146 }
147
148 return Length;
149}
150
151unsigned TargetInstrInfo::getInstBundleSize(const MachineInstr &MI) const {
152 unsigned Size = 0;
153 MachineBasicBlock::const_instr_iterator I = MI.getIterator();
154 MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
155 while (++I != E && I->isInsideBundle()) {
156 assert(!I->isBundle() && "No nested bundle!");
157 Size += getInstSizeInBytes(MI: *I);
158 }
159
160 return Size;
161}
162
163/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
164/// after it, replacing it with an unconditional branch to NewDest.
165void
166TargetInstrInfo::ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail,
167 MachineBasicBlock *NewDest) const {
168 MachineBasicBlock *MBB = Tail->getParent();
169
170 // Remove all the old successors of MBB from the CFG.
171 while (!MBB->succ_empty())
172 MBB->removeSuccessor(I: MBB->succ_begin());
173
174 // Save off the debug loc before erasing the instruction.
175 DebugLoc DL = Tail->getDebugLoc();
176
177 // Update call info and remove all the dead instructions
178 // from the end of MBB.
179 while (Tail != MBB->end()) {
180 auto MI = Tail++;
181 if (MI->shouldUpdateAdditionalCallInfo())
182 MBB->getParent()->eraseAdditionalCallInfo(MI: &*MI);
183 MBB->erase(I: MI);
184 }
185
186 // If MBB isn't immediately before MBB, insert a branch to it.
187 if (++MachineFunction::iterator(MBB) != MachineFunction::iterator(NewDest))
188 insertBranch(MBB&: *MBB, TBB: NewDest, FBB: nullptr, Cond: SmallVector<MachineOperand, 0>(), DL);
189 MBB->addSuccessor(Succ: NewDest);
190}
191
192MachineInstr *TargetInstrInfo::commuteInstructionImpl(MachineInstr &MI,
193 bool NewMI, unsigned Idx1,
194 unsigned Idx2) const {
195 const MCInstrDesc &MCID = MI.getDesc();
196 bool HasDef = MCID.getNumDefs();
197 if (HasDef && !MI.getOperand(i: 0).isReg())
198 // No idea how to commute this instruction. Target should implement its own.
199 return nullptr;
200
201 unsigned CommutableOpIdx1 = Idx1; (void)CommutableOpIdx1;
202 unsigned CommutableOpIdx2 = Idx2; (void)CommutableOpIdx2;
203 assert(findCommutedOpIndices(MI, CommutableOpIdx1, CommutableOpIdx2) &&
204 CommutableOpIdx1 == Idx1 && CommutableOpIdx2 == Idx2 &&
205 "TargetInstrInfo::CommuteInstructionImpl(): not commutable operands.");
206 assert(MI.getOperand(Idx1).isReg() && MI.getOperand(Idx2).isReg() &&
207 "This only knows how to commute register operands so far");
208
209 Register Reg0 = HasDef ? MI.getOperand(i: 0).getReg() : Register();
210 Register Reg1 = MI.getOperand(i: Idx1).getReg();
211 Register Reg2 = MI.getOperand(i: Idx2).getReg();
212 unsigned SubReg0 = HasDef ? MI.getOperand(i: 0).getSubReg() : 0;
213 unsigned SubReg1 = MI.getOperand(i: Idx1).getSubReg();
214 unsigned SubReg2 = MI.getOperand(i: Idx2).getSubReg();
215 bool Reg1IsKill = MI.getOperand(i: Idx1).isKill();
216 bool Reg2IsKill = MI.getOperand(i: Idx2).isKill();
217 bool Reg1IsUndef = MI.getOperand(i: Idx1).isUndef();
218 bool Reg2IsUndef = MI.getOperand(i: Idx2).isUndef();
219 bool Reg1IsInternal = MI.getOperand(i: Idx1).isInternalRead();
220 bool Reg2IsInternal = MI.getOperand(i: Idx2).isInternalRead();
221 // Avoid calling isRenamable for virtual registers since we assert that
222 // renamable property is only queried/set for physical registers.
223 bool Reg1IsRenamable =
224 Reg1.isPhysical() ? MI.getOperand(i: Idx1).isRenamable() : false;
225 bool Reg2IsRenamable =
226 Reg2.isPhysical() ? MI.getOperand(i: Idx2).isRenamable() : false;
227
228 // For a case like this:
229 // %0.sub = INST %0.sub(tied), %1.sub, implicit-def %0
230 // we need to update the implicit-def after commuting to result in:
231 // %1.sub = INST %1.sub(tied), %0.sub, implicit-def %1
232 SmallVector<unsigned> UpdateImplicitDefIdx;
233 if (HasDef && MI.hasImplicitDef()) {
234 for (auto [OpNo, MO] : llvm::enumerate(First: MI.implicit_operands())) {
235 Register ImplReg = MO.getReg();
236 if ((ImplReg.isVirtual() && ImplReg == Reg0) ||
237 (ImplReg.isPhysical() && Reg0.isPhysical() &&
238 TRI.isSubRegisterEq(RegA: ImplReg, RegB: Reg0)))
239 UpdateImplicitDefIdx.push_back(Elt: OpNo + MI.getNumExplicitOperands());
240 }
241 }
242
243 // If destination is tied to either of the commuted source register, then
244 // it must be updated.
245 if (HasDef && Reg0 == Reg1 &&
246 MI.getDesc().getOperandConstraint(OpNum: Idx1, Constraint: MCOI::TIED_TO) == 0) {
247 Reg2IsKill = false;
248 Reg0 = Reg2;
249 SubReg0 = SubReg2;
250 } else if (HasDef && Reg0 == Reg2 &&
251 MI.getDesc().getOperandConstraint(OpNum: Idx2, Constraint: MCOI::TIED_TO) == 0) {
252 Reg1IsKill = false;
253 Reg0 = Reg1;
254 SubReg0 = SubReg1;
255 }
256
257 MachineInstr *CommutedMI = nullptr;
258 if (NewMI) {
259 // Create a new instruction.
260 MachineFunction &MF = *MI.getMF();
261 CommutedMI = MF.CloneMachineInstr(Orig: &MI);
262 } else {
263 CommutedMI = &MI;
264 }
265
266 if (HasDef) {
267 CommutedMI->getOperand(i: 0).setReg(Reg0);
268 CommutedMI->getOperand(i: 0).setSubReg(SubReg0);
269 for (unsigned Idx : UpdateImplicitDefIdx)
270 CommutedMI->getOperand(i: Idx).setReg(Reg0);
271 }
272 CommutedMI->getOperand(i: Idx2).setReg(Reg1);
273 CommutedMI->getOperand(i: Idx1).setReg(Reg2);
274 CommutedMI->getOperand(i: Idx2).setSubReg(SubReg1);
275 CommutedMI->getOperand(i: Idx1).setSubReg(SubReg2);
276 CommutedMI->getOperand(i: Idx2).setIsKill(Reg1IsKill);
277 CommutedMI->getOperand(i: Idx1).setIsKill(Reg2IsKill);
278 CommutedMI->getOperand(i: Idx2).setIsUndef(Reg1IsUndef);
279 CommutedMI->getOperand(i: Idx1).setIsUndef(Reg2IsUndef);
280 CommutedMI->getOperand(i: Idx2).setIsInternalRead(Reg1IsInternal);
281 CommutedMI->getOperand(i: Idx1).setIsInternalRead(Reg2IsInternal);
282 // Avoid calling setIsRenamable for virtual registers since we assert that
283 // renamable property is only queried/set for physical registers.
284 if (Reg1.isPhysical())
285 CommutedMI->getOperand(i: Idx2).setIsRenamable(Reg1IsRenamable);
286 if (Reg2.isPhysical())
287 CommutedMI->getOperand(i: Idx1).setIsRenamable(Reg2IsRenamable);
288 return CommutedMI;
289}
290
291MachineInstr *TargetInstrInfo::commuteInstruction(MachineInstr &MI, bool NewMI,
292 unsigned OpIdx1,
293 unsigned OpIdx2) const {
294 // If OpIdx1 or OpIdx2 is not specified, then this method is free to choose
295 // any commutable operand, which is done in findCommutedOpIndices() method
296 // called below.
297 if ((OpIdx1 == CommuteAnyOperandIndex || OpIdx2 == CommuteAnyOperandIndex) &&
298 !findCommutedOpIndices(MI, SrcOpIdx1&: OpIdx1, SrcOpIdx2&: OpIdx2)) {
299 assert(MI.isCommutable() &&
300 "Precondition violation: MI must be commutable.");
301 return nullptr;
302 }
303 return commuteInstructionImpl(MI, NewMI, Idx1: OpIdx1, Idx2: OpIdx2);
304}
305
306bool TargetInstrInfo::fixCommutedOpIndices(unsigned &ResultIdx1,
307 unsigned &ResultIdx2,
308 unsigned CommutableOpIdx1,
309 unsigned CommutableOpIdx2) {
310 if (ResultIdx1 == CommuteAnyOperandIndex &&
311 ResultIdx2 == CommuteAnyOperandIndex) {
312 ResultIdx1 = CommutableOpIdx1;
313 ResultIdx2 = CommutableOpIdx2;
314 } else if (ResultIdx1 == CommuteAnyOperandIndex) {
315 if (ResultIdx2 == CommutableOpIdx1)
316 ResultIdx1 = CommutableOpIdx2;
317 else if (ResultIdx2 == CommutableOpIdx2)
318 ResultIdx1 = CommutableOpIdx1;
319 else
320 return false;
321 } else if (ResultIdx2 == CommuteAnyOperandIndex) {
322 if (ResultIdx1 == CommutableOpIdx1)
323 ResultIdx2 = CommutableOpIdx2;
324 else if (ResultIdx1 == CommutableOpIdx2)
325 ResultIdx2 = CommutableOpIdx1;
326 else
327 return false;
328 } else
329 // Check that the result operand indices match the given commutable
330 // operand indices.
331 return (ResultIdx1 == CommutableOpIdx1 && ResultIdx2 == CommutableOpIdx2) ||
332 (ResultIdx1 == CommutableOpIdx2 && ResultIdx2 == CommutableOpIdx1);
333
334 return true;
335}
336
337bool TargetInstrInfo::findCommutedOpIndices(const MachineInstr &MI,
338 unsigned &SrcOpIdx1,
339 unsigned &SrcOpIdx2) const {
340 assert(!MI.isBundle() &&
341 "TargetInstrInfo::findCommutedOpIndices() can't handle bundles");
342
343 const MCInstrDesc &MCID = MI.getDesc();
344 if (!MCID.isCommutable())
345 return false;
346
347 // This assumes v0 = op v1, v2 and commuting would swap v1 and v2. If this
348 // is not true, then the target must implement this.
349 unsigned CommutableOpIdx1 = MCID.getNumDefs();
350 unsigned CommutableOpIdx2 = CommutableOpIdx1 + 1;
351 if (!fixCommutedOpIndices(ResultIdx1&: SrcOpIdx1, ResultIdx2&: SrcOpIdx2,
352 CommutableOpIdx1, CommutableOpIdx2))
353 return false;
354
355 if (!MI.getOperand(i: SrcOpIdx1).isReg() || !MI.getOperand(i: SrcOpIdx2).isReg())
356 // No idea.
357 return false;
358 return true;
359}
360
361bool TargetInstrInfo::isUnpredicatedTerminator(const MachineInstr &MI) const {
362 if (!MI.isTerminator()) return false;
363
364 // Conditional branch is a special case.
365 if (MI.isBranch() && !MI.isBarrier())
366 return true;
367 if (!MI.isPredicable())
368 return true;
369 return !isPredicated(MI);
370}
371
372bool TargetInstrInfo::PredicateInstruction(
373 MachineInstr &MI, ArrayRef<MachineOperand> Pred) const {
374 bool MadeChange = false;
375
376 assert(!MI.isBundle() &&
377 "TargetInstrInfo::PredicateInstruction() can't handle bundles");
378
379 const MCInstrDesc &MCID = MI.getDesc();
380 if (!MI.isPredicable())
381 return false;
382
383 for (unsigned j = 0, i = 0, e = MI.getNumOperands(); i != e; ++i) {
384 if (MCID.operands()[i].isPredicate()) {
385 MachineOperand &MO = MI.getOperand(i);
386 if (MO.isReg()) {
387 MO.setReg(Pred[j].getReg());
388 MadeChange = true;
389 } else if (MO.isImm()) {
390 MO.setImm(Pred[j].getImm());
391 MadeChange = true;
392 } else if (MO.isMBB()) {
393 MO.setMBB(Pred[j].getMBB());
394 MadeChange = true;
395 }
396 ++j;
397 }
398 }
399 return MadeChange;
400}
401
402bool TargetInstrInfo::hasLoadFromStackSlot(
403 const MachineInstr &MI,
404 SmallVectorImpl<const MachineMemOperand *> &Accesses) const {
405 size_t StartSize = Accesses.size();
406 for (MachineInstr::mmo_iterator o = MI.memoperands_begin(),
407 oe = MI.memoperands_end();
408 o != oe; ++o) {
409 if ((*o)->isLoad() &&
410 isa_and_nonnull<FixedStackPseudoSourceValue>(Val: (*o)->getPseudoValue()))
411 Accesses.push_back(Elt: *o);
412 }
413 return Accesses.size() != StartSize;
414}
415
416bool TargetInstrInfo::hasStoreToStackSlot(
417 const MachineInstr &MI,
418 SmallVectorImpl<const MachineMemOperand *> &Accesses) const {
419 size_t StartSize = Accesses.size();
420 for (MachineInstr::mmo_iterator o = MI.memoperands_begin(),
421 oe = MI.memoperands_end();
422 o != oe; ++o) {
423 if ((*o)->isStore() &&
424 isa_and_nonnull<FixedStackPseudoSourceValue>(Val: (*o)->getPseudoValue()))
425 Accesses.push_back(Elt: *o);
426 }
427 return Accesses.size() != StartSize;
428}
429
430bool TargetInstrInfo::getStackSlotRange(const TargetRegisterClass *RC,
431 unsigned SubIdx, unsigned &Size,
432 unsigned &Offset,
433 const MachineFunction &MF) const {
434 if (!SubIdx) {
435 Size = TRI.getSpillSize(RC: *RC);
436 Offset = 0;
437 return true;
438 }
439 unsigned BitSize = TRI.getSubRegIdxSize(Idx: SubIdx);
440 // Convert bit size to byte size.
441 if (BitSize % 8)
442 return false;
443
444 int BitOffset = TRI.getSubRegIdxOffset(Idx: SubIdx);
445 if (BitOffset < 0 || BitOffset % 8)
446 return false;
447
448 Size = BitSize / 8;
449 Offset = (unsigned)BitOffset / 8;
450
451 assert(TRI.getSpillSize(*RC) >= (Offset + Size) && "bad subregister range");
452
453 if (!MF.getDataLayout().isLittleEndian()) {
454 Offset = TRI.getSpillSize(RC: *RC) - (Offset + Size);
455 }
456 return true;
457}
458
459void TargetInstrInfo::reMaterialize(MachineBasicBlock &MBB,
460 MachineBasicBlock::iterator I,
461 Register DestReg, unsigned SubIdx,
462 const MachineInstr &Orig,
463 LaneBitmask UsedLanes) const {
464 MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig: &Orig);
465 MI->substituteRegister(FromReg: MI->getOperand(i: 0).getReg(), ToReg: DestReg, SubIdx, RegInfo: TRI);
466 MBB.insert(I, MI);
467}
468
469bool TargetInstrInfo::produceSameValue(const MachineInstr &MI0,
470 const MachineInstr &MI1,
471 const MachineRegisterInfo *MRI) const {
472 return MI0.isIdenticalTo(Other: MI1, Check: MachineInstr::IgnoreVRegDefs);
473}
474
475MachineInstr &
476TargetInstrInfo::duplicate(MachineBasicBlock &MBB,
477 MachineBasicBlock::iterator InsertBefore,
478 const MachineInstr &Orig) const {
479 MachineFunction &MF = *MBB.getParent();
480 // CFI instructions are marked as non-duplicable, because Darwin compact
481 // unwind info emission can't handle multiple prologue setups.
482 assert((!Orig.isNotDuplicable() ||
483 (!MF.getTarget().getTargetTriple().isOSDarwin() &&
484 Orig.isCFIInstruction())) &&
485 "Instruction cannot be duplicated");
486
487 return MF.cloneMachineInstrBundle(MBB, InsertBefore, Orig);
488}
489
490// If the COPY instruction in MI can be folded to a stack operation, return
491// the register class to use.
492static const TargetRegisterClass *canFoldCopy(const MachineInstr &MI,
493 const TargetInstrInfo &TII,
494 unsigned FoldIdx) {
495 assert(TII.isCopyInstr(MI) && "MI must be a COPY instruction");
496 if (MI.getNumOperands() != 2)
497 return nullptr;
498 assert(FoldIdx<2 && "FoldIdx refers no nonexistent operand");
499
500 const MachineOperand &FoldOp = MI.getOperand(i: FoldIdx);
501 const MachineOperand &LiveOp = MI.getOperand(i: 1 - FoldIdx);
502
503 if (FoldOp.getSubReg() || LiveOp.getSubReg())
504 return nullptr;
505
506 Register FoldReg = FoldOp.getReg();
507 Register LiveReg = LiveOp.getReg();
508
509 assert(FoldReg.isVirtual() && "Cannot fold physregs");
510
511 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
512 const TargetRegisterClass *RC = MRI.getRegClass(Reg: FoldReg);
513
514 if (LiveOp.getReg().isPhysical())
515 return RC->contains(Reg: LiveOp.getReg()) ? RC : nullptr;
516
517 if (RC->hasSubClassEq(RC: MRI.getRegClass(Reg: LiveReg)))
518 return RC;
519
520 // FIXME: Allow folding when register classes are memory compatible.
521 return nullptr;
522}
523
524MCInst TargetInstrInfo::getNop() const { llvm_unreachable("Not implemented"); }
525
526/// Try to remove the load by folding it to a register
527/// operand at the use. We fold the load instructions if load defines a virtual
528/// register, the virtual register is used once in the same BB, and the
529/// instructions in-between do not load or store, and have no side effects.
530MachineInstr *TargetInstrInfo::optimizeLoadInstr(MachineInstr &MI,
531 const MachineRegisterInfo *MRI,
532 Register &FoldAsLoadDefReg,
533 MachineInstr *&DefMI,
534 MachineInstr *&CopyMI) const {
535 // Check whether we can move DefMI here.
536 DefMI = MRI->getVRegDef(Reg: FoldAsLoadDefReg);
537 assert(DefMI);
538 bool SawStore = false;
539 if (!DefMI->isSafeToMove(SawStore))
540 return nullptr;
541
542 // Collect information about virtual register operands of MI.
543 SmallVector<unsigned, 1> SrcOperandIds;
544 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
545 MachineOperand &MO = MI.getOperand(i);
546 if (!MO.isReg())
547 continue;
548 Register Reg = MO.getReg();
549 if (Reg != FoldAsLoadDefReg)
550 continue;
551 // Do not fold if we have a subreg use or a def.
552 if (MO.getSubReg() || MO.isDef())
553 return nullptr;
554 SrcOperandIds.push_back(Elt: i);
555 }
556 if (SrcOperandIds.empty())
557 return nullptr;
558
559 // Check whether we can fold the def into SrcOperandId.
560 if (MachineInstr *FoldMI =
561 foldMemoryOperand(MI, Ops: SrcOperandIds, LoadMI&: *DefMI, CopyMI)) {
562 FoldAsLoadDefReg = 0;
563 return FoldMI;
564 }
565
566 return nullptr;
567}
568
569std::pair<unsigned, unsigned>
570TargetInstrInfo::getPatchpointUnfoldableRange(const MachineInstr &MI) const {
571 switch (MI.getOpcode()) {
572 case TargetOpcode::STACKMAP:
573 // StackMapLiveValues are foldable
574 return std::make_pair(x: 0, y: StackMapOpers(&MI).getVarIdx());
575 case TargetOpcode::PATCHPOINT:
576 // For PatchPoint, the call args are not foldable (even if reported in the
577 // stackmap e.g. via anyregcc).
578 return std::make_pair(x: 0, y: PatchPointOpers(&MI).getVarIdx());
579 case TargetOpcode::STATEPOINT:
580 // For statepoints, fold deopt and gc arguments, but not call arguments.
581 return std::make_pair(x: MI.getNumDefs(), y: StatepointOpers(&MI).getVarIdx());
582 default:
583 llvm_unreachable("unexpected stackmap opcode");
584 }
585}
586
587static MachineInstr *foldPatchpoint(MachineFunction &MF, MachineInstr &MI,
588 ArrayRef<unsigned> Ops, int FrameIndex,
589 const TargetInstrInfo &TII) {
590 unsigned StartIdx = 0;
591 unsigned NumDefs = 0;
592 // getPatchpointUnfoldableRange throws guarantee if MI is not a patchpoint.
593 std::tie(args&: NumDefs, args&: StartIdx) = TII.getPatchpointUnfoldableRange(MI);
594
595 unsigned DefToFoldIdx = MI.getNumOperands();
596
597 // Return false if any operands requested for folding are not foldable (not
598 // part of the stackmap's live values).
599 for (unsigned Op : Ops) {
600 if (Op < NumDefs) {
601 assert(DefToFoldIdx == MI.getNumOperands() && "Folding multiple defs");
602 DefToFoldIdx = Op;
603 } else if (Op < StartIdx) {
604 return nullptr;
605 }
606 if (MI.getOperand(i: Op).isTied())
607 return nullptr;
608 }
609
610 MachineInstr *NewMI =
611 MF.CreateMachineInstr(MCID: TII.get(Opcode: MI.getOpcode()), DL: MI.getDebugLoc(), NoImplicit: true);
612 MachineInstrBuilder MIB(MF, NewMI);
613
614 // No need to fold return, the meta data, and function arguments
615 for (unsigned i = 0; i < StartIdx; ++i)
616 if (i != DefToFoldIdx)
617 MIB.add(MO: MI.getOperand(i));
618
619 for (unsigned i = StartIdx, e = MI.getNumOperands(); i < e; ++i) {
620 MachineOperand &MO = MI.getOperand(i);
621 unsigned TiedTo = e;
622 (void)MI.isRegTiedToDefOperand(UseOpIdx: i, DefOpIdx: &TiedTo);
623
624 if (is_contained(Range&: Ops, Element: i)) {
625 assert(TiedTo == e && "Cannot fold tied operands");
626 unsigned SpillSize;
627 unsigned SpillOffset;
628 // Compute the spill slot size and offset.
629 const TargetRegisterClass *RC =
630 MF.getRegInfo().getRegClass(Reg: MO.getReg());
631 bool Valid =
632 TII.getStackSlotRange(RC, SubIdx: MO.getSubReg(), Size&: SpillSize, Offset&: SpillOffset, MF);
633 if (!Valid)
634 report_fatal_error(reason: "cannot spill patchpoint subregister operand");
635 MIB.addImm(Val: StackMaps::IndirectMemRefOp);
636 MIB.addImm(Val: SpillSize);
637 MIB.addFrameIndex(Idx: FrameIndex);
638 MIB.addImm(Val: SpillOffset);
639 } else {
640 MIB.add(MO);
641 if (TiedTo < e) {
642 assert(TiedTo < NumDefs && "Bad tied operand");
643 if (TiedTo > DefToFoldIdx)
644 --TiedTo;
645 NewMI->tieOperands(DefIdx: TiedTo, UseIdx: NewMI->getNumOperands() - 1);
646 }
647 }
648 }
649 return NewMI;
650}
651
652static void foldInlineAsmMemOperand(MachineInstr *MI, unsigned OpNo, int FI,
653 const TargetInstrInfo &TII) {
654 // If the machine operand is tied, untie it first.
655 if (MI->getOperand(i: OpNo).isTied()) {
656 unsigned TiedTo = MI->findTiedOperandIdx(OpIdx: OpNo);
657 MI->untieRegOperand(OpIdx: OpNo);
658 // Intentional recursion!
659 foldInlineAsmMemOperand(MI, OpNo: TiedTo, FI, TII);
660 }
661
662 SmallVector<MachineOperand, 5> NewOps;
663 TII.getFrameIndexOperands(Ops&: NewOps, FI);
664 assert(!NewOps.empty() && "getFrameIndexOperands didn't create any operands");
665 MI->removeOperand(OpNo);
666 MI->insert(InsertBefore: MI->operands_begin() + OpNo, Ops: NewOps);
667
668 // Change the previous operand to a MemKind InlineAsm::Flag. The second param
669 // is the per-target number of operands that represent the memory operand
670 // excluding this one (MD). This includes MO.
671 InlineAsm::Flag F(InlineAsm::Kind::Mem, NewOps.size());
672 F.setMemConstraint(InlineAsm::ConstraintCode::m);
673 MachineOperand &MD = MI->getOperand(i: OpNo - 1);
674 MD.setImm(F);
675}
676
677// Returns nullptr if not possible to fold.
678static MachineInstr *foldInlineAsmMemOperand(MachineInstr &MI,
679 ArrayRef<unsigned> Ops, int FI,
680 const TargetInstrInfo &TII) {
681 assert(MI.isInlineAsm() && "wrong opcode");
682 if (Ops.size() > 1)
683 return nullptr;
684 unsigned Op = Ops[0];
685 assert(Op && "should never be first operand");
686 assert(MI.getOperand(Op).isReg() && "shouldn't be folding non-reg operands");
687
688 if (!MI.mayFoldInlineAsmRegOp(OpId: Op))
689 return nullptr;
690
691 MachineInstr &NewMI = TII.duplicate(MBB&: *MI.getParent(), InsertBefore: MI.getIterator(), Orig: MI);
692
693 foldInlineAsmMemOperand(MI: &NewMI, OpNo: Op, FI, TII);
694
695 // Update mayload/maystore metadata, and memoperands.
696 const VirtRegInfo &RI =
697 AnalyzeVirtRegInBundle(MI, Reg: MI.getOperand(i: Op).getReg());
698 MachineOperand &ExtraMO = NewMI.getOperand(i: InlineAsm::MIOp_ExtraInfo);
699 MachineMemOperand::Flags Flags = MachineMemOperand::MONone;
700 if (RI.Reads) {
701 ExtraMO.setImm(ExtraMO.getImm() | InlineAsm::Extra_MayLoad);
702 Flags |= MachineMemOperand::MOLoad;
703 }
704 if (RI.Writes) {
705 ExtraMO.setImm(ExtraMO.getImm() | InlineAsm::Extra_MayStore);
706 Flags |= MachineMemOperand::MOStore;
707 }
708 MachineFunction *MF = NewMI.getMF();
709 const MachineFrameInfo &MFI = MF->getFrameInfo();
710 MachineMemOperand *MMO = MF->getMachineMemOperand(
711 PtrInfo: MachinePointerInfo::getFixedStack(MF&: *MF, FI), F: Flags, Size: MFI.getObjectSize(ObjectIdx: FI),
712 BaseAlignment: MFI.getObjectAlign(ObjectIdx: FI));
713 NewMI.addMemOperand(MF&: *MF, MO: MMO);
714
715 return &NewMI;
716}
717
718MachineInstr *TargetInstrInfo::foldMemoryOperand(MachineInstr &MI,
719 ArrayRef<unsigned> Ops, int FI,
720 MachineInstr *&CopyMI,
721 LiveIntervals *LIS,
722 VirtRegMap *VRM) const {
723 auto Flags = MachineMemOperand::MONone;
724 for (unsigned OpIdx : Ops)
725 Flags |= MI.getOperand(i: OpIdx).isDef() ? MachineMemOperand::MOStore
726 : MachineMemOperand::MOLoad;
727
728 MachineBasicBlock *MBB = MI.getParent();
729 assert(MBB && "foldMemoryOperand needs an inserted instruction");
730 MachineFunction &MF = *MBB->getParent();
731
732 // If we're not folding a load into a subreg, the size of the load is the
733 // size of the spill slot. But if we are, we need to figure out what the
734 // actual load size is.
735 int64_t MemSize = 0;
736 const MachineFrameInfo &MFI = MF.getFrameInfo();
737
738 if (Flags & MachineMemOperand::MOStore) {
739 MemSize = MFI.getObjectSize(ObjectIdx: FI);
740 } else {
741 for (unsigned OpIdx : Ops) {
742 int64_t OpSize = MFI.getObjectSize(ObjectIdx: FI);
743
744 if (auto SubReg = MI.getOperand(i: OpIdx).getSubReg()) {
745 unsigned SubRegSize = TRI.getSubRegIdxSize(Idx: SubReg);
746 if (SubRegSize > 0 && !(SubRegSize % 8))
747 OpSize = SubRegSize / 8;
748 }
749
750 MemSize = std::max(a: MemSize, b: OpSize);
751 }
752 }
753
754 assert(MemSize && "Did not expect a zero-sized stack slot");
755
756 MachineInstr *NewMI = nullptr;
757
758 if (MI.getOpcode() == TargetOpcode::STACKMAP ||
759 MI.getOpcode() == TargetOpcode::PATCHPOINT ||
760 MI.getOpcode() == TargetOpcode::STATEPOINT) {
761 // Fold stackmap/patchpoint.
762 NewMI = foldPatchpoint(MF, MI, Ops, FrameIndex: FI, TII: *this);
763 if (NewMI)
764 MBB->insert(I: MI, MI: NewMI);
765 } else if (MI.isInlineAsm()) {
766 return foldInlineAsmMemOperand(MI, Ops, FI, TII: *this);
767 } else {
768 // Ask the target to do the actual folding.
769 NewMI = foldMemoryOperandImpl(MF, MI, Ops, FrameIndex: FI, CopyMI, LIS, VRM);
770 }
771
772 if (NewMI) {
773 NewMI->setMemRefs(MF, MemRefs: MI.memoperands());
774 // Add a memory operand, foldMemoryOperandImpl doesn't do that.
775 assert((!(Flags & MachineMemOperand::MOStore) ||
776 NewMI->mayStore()) &&
777 "Folded a def to a non-store!");
778 assert((!(Flags & MachineMemOperand::MOLoad) ||
779 NewMI->mayLoad()) &&
780 "Folded a use to a non-load!");
781 assert(MFI.getObjectOffset(FI) != -1);
782 MachineMemOperand *MMO =
783 MF.getMachineMemOperand(PtrInfo: MachinePointerInfo::getFixedStack(MF, FI),
784 F: Flags, Size: MemSize, BaseAlignment: MFI.getObjectAlign(ObjectIdx: FI));
785 NewMI->addMemOperand(MF, MO: MMO);
786
787 // The pass "x86 speculative load hardening" always attaches symbols to
788 // call instructions. We need copy it form old instruction.
789 NewMI->cloneInstrSymbols(MF, MI);
790
791 return NewMI;
792 }
793
794 // Straight COPY may fold as load/store.
795 if (!isCopyInstr(MI) || Ops.size() != 1)
796 return nullptr;
797
798 const TargetRegisterClass *RC = canFoldCopy(MI, TII: *this, FoldIdx: Ops[0]);
799 if (!RC)
800 return nullptr;
801
802 const MachineOperand &MO = MI.getOperand(i: 1 - Ops[0]);
803 MachineBasicBlock::iterator Pos = MI;
804 if (Flags == MachineMemOperand::MOStore) {
805 if (MO.isUndef()) {
806 // If this is an undef copy, we do not need to bother we inserting spill
807 // code.
808 BuildMI(BB&: *MBB, I: Pos, MIMD: MI.getDebugLoc(), MCID: get(Opcode: TargetOpcode::KILL)).add(MO);
809 } else {
810 storeRegToStackSlot(MBB&: *MBB, MI: Pos, SrcReg: MO.getReg(), isKill: MO.isKill(), FrameIndex: FI, RC,
811 VReg: Register());
812 }
813 } else
814 loadRegFromStackSlot(MBB&: *MBB, MI: Pos, DestReg: MO.getReg(), FrameIndex: FI, RC, VReg: Register());
815
816 return &*--Pos;
817}
818
819MachineInstr *
820TargetInstrInfo::foldMemoryOperand(MachineInstr &MI, ArrayRef<unsigned> Ops,
821 MachineInstr &LoadMI, MachineInstr *&CopyMI,
822 LiveIntervals *LIS, VirtRegMap *VRM) const {
823 assert(LoadMI.canFoldAsLoad() && "LoadMI isn't foldable!");
824#ifndef NDEBUG
825 for (unsigned OpIdx : Ops)
826 assert(MI.getOperand(OpIdx).isUse() && "Folding load into def!");
827#endif
828
829 MachineBasicBlock &MBB = *MI.getParent();
830 MachineFunction &MF = *MBB.getParent();
831
832 // Ask the target to do the actual folding.
833 MachineInstr *NewMI = nullptr;
834 int FrameIndex = 0;
835
836 if ((MI.getOpcode() == TargetOpcode::STACKMAP ||
837 MI.getOpcode() == TargetOpcode::PATCHPOINT ||
838 MI.getOpcode() == TargetOpcode::STATEPOINT) &&
839 isLoadFromStackSlot(MI: LoadMI, FrameIndex)) {
840 // Fold stackmap/patchpoint.
841 NewMI = foldPatchpoint(MF, MI, Ops, FrameIndex, TII: *this);
842 if (NewMI)
843 NewMI = &*MBB.insert(I: MI, MI: NewMI);
844 } else if (MI.isInlineAsm() && isLoadFromStackSlot(MI: LoadMI, FrameIndex)) {
845 return foldInlineAsmMemOperand(MI, Ops, FI: FrameIndex, TII: *this);
846 } else {
847 // Ask the target to do the actual folding.
848 NewMI = foldMemoryOperandImpl(MF, MI, Ops, LoadMI, CopyMI, LIS, VRM);
849 }
850
851 if (!NewMI)
852 return nullptr;
853
854 // Copy the memoperands from the load to the folded instruction.
855 if (MI.memoperands_empty()) {
856 NewMI->setMemRefs(MF, MemRefs: LoadMI.memoperands());
857 } else {
858 // Handle the rare case of folding multiple loads.
859 NewMI->setMemRefs(MF, MemRefs: MI.memoperands());
860 for (MachineInstr::mmo_iterator I = LoadMI.memoperands_begin(),
861 E = LoadMI.memoperands_end();
862 I != E; ++I) {
863 NewMI->addMemOperand(MF, MO: *I);
864 }
865 }
866 return NewMI;
867}
868
869/// transferImplicitOperands - MI is a pseudo-instruction, and the lowered
870/// replacement instructions immediately precede it. Copy any implicit
871/// operands from MI to the replacement instruction.
872static void transferImplicitOperands(MachineInstr *MI,
873 const TargetRegisterInfo *TRI) {
874 MachineBasicBlock::iterator CopyMI = MI;
875 --CopyMI;
876
877 Register DstReg = MI->getOperand(i: 0).getReg();
878 for (const MachineOperand &MO : MI->implicit_operands()) {
879 CopyMI->addOperand(Op: MO);
880
881 // Be conservative about preserving kills when subregister defs are
882 // involved. If there was implicit kill of a super-register overlapping the
883 // copy result, we would kill the subregisters previous copies defined.
884
885 if (MO.isKill() && TRI->regsOverlap(RegA: DstReg, RegB: MO.getReg()))
886 CopyMI->getOperand(i: CopyMI->getNumOperands() - 1).setIsKill(false);
887 }
888}
889
890void TargetInstrInfo::lowerCopy(
891 MachineInstr *MI, const TargetRegisterInfo * /*Remove me*/) const {
892 if (MI->allDefsAreDead()) {
893 MI->setDesc(get(Opcode: TargetOpcode::KILL));
894 return;
895 }
896
897 MachineOperand &DstMO = MI->getOperand(i: 0);
898 MachineOperand &SrcMO = MI->getOperand(i: 1);
899
900 bool IdentityCopy = (SrcMO.getReg() == DstMO.getReg());
901 if (IdentityCopy || SrcMO.isUndef()) {
902 // No need to insert an identity copy instruction, but replace with a KILL
903 // if liveness is changed.
904 if (SrcMO.isUndef() || MI->getNumOperands() > 2) {
905 // We must make sure the super-register gets killed. Replace the
906 // instruction with KILL.
907 MI->setDesc(get(Opcode: TargetOpcode::KILL));
908 return;
909 }
910 // Vanilla identity copy.
911 MI->eraseFromParent();
912 return;
913 }
914
915 copyPhysReg(MBB&: *MI->getParent(), MI, DL: MI->getDebugLoc(), DestReg: DstMO.getReg(),
916 SrcReg: SrcMO.getReg(), KillSrc: SrcMO.isKill(),
917 RenamableDest: DstMO.getReg().isPhysical() ? DstMO.isRenamable() : false,
918 RenamableSrc: SrcMO.getReg().isPhysical() ? SrcMO.isRenamable() : false);
919
920 if (MI->getNumOperands() > 2)
921 transferImplicitOperands(MI, TRI: &TRI);
922 MI->eraseFromParent();
923}
924
925bool TargetInstrInfo::hasReassociableOperands(
926 const MachineInstr &Inst, const MachineBasicBlock *MBB) const {
927 const MachineOperand &Op1 = Inst.getOperand(i: 1);
928 const MachineOperand &Op2 = Inst.getOperand(i: 2);
929 const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
930
931 // We need virtual register definitions for the operands that we will
932 // reassociate.
933 MachineInstr *MI1 = nullptr;
934 MachineInstr *MI2 = nullptr;
935 if (Op1.isReg() && Op1.getReg().isVirtual())
936 MI1 = MRI.getUniqueVRegDef(Reg: Op1.getReg());
937 if (Op2.isReg() && Op2.getReg().isVirtual())
938 MI2 = MRI.getUniqueVRegDef(Reg: Op2.getReg());
939
940 // And at least one operand must be defined in MBB.
941 return MI1 && MI2 && (MI1->getParent() == MBB || MI2->getParent() == MBB);
942}
943
944bool TargetInstrInfo::areOpcodesEqualOrInverse(unsigned Opcode1,
945 unsigned Opcode2) const {
946 return Opcode1 == Opcode2 || getInverseOpcode(Opcode: Opcode1) == Opcode2;
947}
948
949bool TargetInstrInfo::hasReassociableSibling(const MachineInstr &Inst,
950 bool &Commuted) const {
951 const MachineBasicBlock *MBB = Inst.getParent();
952 const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
953 MachineInstr *MI1 = MRI.getUniqueVRegDef(Reg: Inst.getOperand(i: 1).getReg());
954 MachineInstr *MI2 = MRI.getUniqueVRegDef(Reg: Inst.getOperand(i: 2).getReg());
955 unsigned Opcode = Inst.getOpcode();
956
957 // If only one operand has the same or inverse opcode and it's the second
958 // source operand, the operands must be commuted.
959 Commuted = !areOpcodesEqualOrInverse(Opcode1: Opcode, Opcode2: MI1->getOpcode()) &&
960 areOpcodesEqualOrInverse(Opcode1: Opcode, Opcode2: MI2->getOpcode());
961 if (Commuted)
962 std::swap(a&: MI1, b&: MI2);
963
964 // 1. The previous instruction must be the same type as Inst.
965 // 2. The previous instruction must also be associative/commutative or be the
966 // inverse of such an operation (this can be different even for
967 // instructions with the same opcode if traits like fast-math-flags are
968 // included).
969 // 3. The previous instruction must have virtual register definitions for its
970 // operands in the same basic block as Inst.
971 // 4. The previous instruction's result must only be used by Inst.
972 return areOpcodesEqualOrInverse(Opcode1: Opcode, Opcode2: MI1->getOpcode()) &&
973 (isAssociativeAndCommutative(Inst: *MI1) ||
974 isAssociativeAndCommutative(Inst: *MI1, /* Invert */ true)) &&
975 hasReassociableOperands(Inst: *MI1, MBB) &&
976 MRI.hasOneNonDBGUse(RegNo: MI1->getOperand(i: 0).getReg());
977}
978
979// 1. The operation must be associative and commutative or be the inverse of
980// such an operation.
981// 2. The instruction must have virtual register definitions for its
982// operands in the same basic block.
983// 3. The instruction must have a reassociable sibling.
984bool TargetInstrInfo::isReassociationCandidate(const MachineInstr &Inst,
985 bool &Commuted) const {
986 return (isAssociativeAndCommutative(Inst) ||
987 isAssociativeAndCommutative(Inst, /* Invert */ true)) &&
988 hasReassociableOperands(Inst, MBB: Inst.getParent()) &&
989 hasReassociableSibling(Inst, Commuted);
990}
991
992// Utility routine that checks if \param MO is defined by an
993// \param CombineOpc instruction in the basic block \param MBB.
994// If \param CombineOpc is not provided, the OpCode check will
995// be skipped.
996static bool canCombine(MachineBasicBlock &MBB, MachineOperand &MO,
997 unsigned CombineOpc = 0) {
998 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
999 MachineInstr *MI = nullptr;
1000
1001 if (MO.isReg() && MO.getReg().isVirtual())
1002 MI = MRI.getUniqueVRegDef(Reg: MO.getReg());
1003 // And it needs to be in the trace (otherwise, it won't have a depth).
1004 if (!MI || MI->getParent() != &MBB ||
1005 (MI->getOpcode() != CombineOpc && CombineOpc != 0))
1006 return false;
1007 // Must only used by the user we combine with.
1008 if (!MRI.hasOneNonDBGUse(RegNo: MO.getReg()))
1009 return false;
1010
1011 return true;
1012}
1013
1014// A chain of accumulation instructions will be selected IFF:
1015// 1. All the accumulation instructions in the chain have the same opcode,
1016// besides the first that has a slightly different opcode because it does
1017// not accumulate into a register.
1018// 2. All the instructions in the chain are combinable (have a single use
1019// which itself is part of the chain).
1020// 3. Meets the required minimum length.
1021void TargetInstrInfo::getAccumulatorChain(
1022 MachineInstr *CurrentInstr, SmallVectorImpl<Register> &Chain) const {
1023 // Walk up the chain of accumulation instructions and collect them in the
1024 // vector.
1025 MachineBasicBlock &MBB = *CurrentInstr->getParent();
1026 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1027 unsigned AccumulatorOpcode = CurrentInstr->getOpcode();
1028 std::optional<unsigned> ChainStartOpCode =
1029 getAccumulationStartOpcode(Opcode: AccumulatorOpcode);
1030
1031 if (!ChainStartOpCode.has_value())
1032 return;
1033
1034 // Push the first accumulator result to the start of the chain.
1035 Chain.push_back(Elt: CurrentInstr->getOperand(i: 0).getReg());
1036
1037 // Collect the accumulator input register from all instructions in the chain.
1038 while (CurrentInstr &&
1039 canCombine(MBB, MO&: CurrentInstr->getOperand(i: 1), CombineOpc: AccumulatorOpcode)) {
1040 Chain.push_back(Elt: CurrentInstr->getOperand(i: 1).getReg());
1041 CurrentInstr = MRI.getUniqueVRegDef(Reg: CurrentInstr->getOperand(i: 1).getReg());
1042 }
1043
1044 // Add the instruction at the top of the chain.
1045 if (CurrentInstr->getOpcode() == AccumulatorOpcode &&
1046 canCombine(MBB, MO&: CurrentInstr->getOperand(i: 1)))
1047 Chain.push_back(Elt: CurrentInstr->getOperand(i: 1).getReg());
1048}
1049
1050/// Find chains of accumulations that can be rewritten as a tree for increased
1051/// ILP.
1052bool TargetInstrInfo::getAccumulatorReassociationPatterns(
1053 MachineInstr &Root, SmallVectorImpl<unsigned> &Patterns) const {
1054 if (!EnableAccReassociation)
1055 return false;
1056
1057 unsigned Opc = Root.getOpcode();
1058 if (!isAccumulationOpcode(Opcode: Opc))
1059 return false;
1060
1061 // Verify that this is the end of the chain.
1062 MachineBasicBlock &MBB = *Root.getParent();
1063 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1064 if (!MRI.hasOneNonDBGUser(RegNo: Root.getOperand(i: 0).getReg()))
1065 return false;
1066
1067 auto User = MRI.use_instr_begin(RegNo: Root.getOperand(i: 0).getReg());
1068 if (User->getOpcode() == Opc)
1069 return false;
1070
1071 // Walk up the use chain and collect the reduction chain.
1072 SmallVector<Register, 32> Chain;
1073 getAccumulatorChain(CurrentInstr: &Root, Chain);
1074
1075 // Reject chains which are too short to be worth modifying.
1076 if (Chain.size() < MinAccumulatorDepth)
1077 return false;
1078
1079 // Check if the MBB this instruction is a part of contains any other chains.
1080 // If so, don't apply it.
1081 SmallSet<Register, 32> ReductionChain(llvm::from_range, Chain);
1082 for (const auto &I : MBB) {
1083 if (I.getOpcode() == Opc &&
1084 !ReductionChain.contains(V: I.getOperand(i: 0).getReg()))
1085 return false;
1086 }
1087
1088 Patterns.push_back(Elt: MachineCombinerPattern::ACC_CHAIN);
1089 return true;
1090}
1091
1092// Reduce branches of the accumulator tree by adding them together.
1093void TargetInstrInfo::reduceAccumulatorTree(
1094 SmallVectorImpl<Register> &RegistersToReduce,
1095 SmallVectorImpl<MachineInstr *> &InsInstrs, MachineFunction &MF,
1096 MachineInstr &Root, MachineRegisterInfo &MRI,
1097 DenseMap<Register, unsigned> &InstrIdxForVirtReg,
1098 Register ResultReg) const {
1099 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
1100 SmallVector<Register, 8> NewRegs;
1101
1102 // Get the opcode for the reduction instruction we will need to build.
1103 // If for some reason it is not defined, early exit and don't apply this.
1104 unsigned ReduceOpCode = getReduceOpcodeForAccumulator(AccumulatorOpCode: Root.getOpcode());
1105
1106 for (unsigned int i = 1; i <= (RegistersToReduce.size() / 2); i += 2) {
1107 auto RHS = RegistersToReduce[i - 1];
1108 auto LHS = RegistersToReduce[i];
1109 Register Dest;
1110 // If we are reducing 2 registers, reuse the original result register.
1111 if (RegistersToReduce.size() == 2)
1112 Dest = ResultReg;
1113 // Otherwise, create a new virtual register to hold the partial sum.
1114 else {
1115 auto NewVR = MRI.createVirtualRegister(
1116 RegClass: MRI.getRegClass(Reg: Root.getOperand(i: 0).getReg()));
1117 Dest = NewVR;
1118 NewRegs.push_back(Elt: Dest);
1119 InstrIdxForVirtReg.insert(KV: std::make_pair(x&: Dest, y: InsInstrs.size()));
1120 }
1121
1122 // Create the new reduction instruction.
1123 MachineInstrBuilder MIB =
1124 BuildMI(MF, MIMD: MIMetadata(Root), MCID: TII->get(Opcode: ReduceOpCode), DestReg: Dest)
1125 .addReg(RegNo: RHS, Flags: getKillRegState(B: true))
1126 .addReg(RegNo: LHS, Flags: getKillRegState(B: true));
1127 // Copy any flags needed from the original instruction.
1128 MIB->setFlags(Root.getFlags());
1129 InsInstrs.push_back(Elt: MIB);
1130 }
1131
1132 // If the number of registers to reduce is odd, add the remaining register to
1133 // the vector of registers to reduce.
1134 if (RegistersToReduce.size() % 2 != 0)
1135 NewRegs.push_back(Elt: RegistersToReduce[RegistersToReduce.size() - 1]);
1136
1137 RegistersToReduce = std::move(NewRegs);
1138}
1139
1140// The concept of the reassociation pass is that these operations can benefit
1141// from this kind of transformation:
1142//
1143// A = ? op ?
1144// B = A op X (Prev)
1145// C = B op Y (Root)
1146// -->
1147// A = ? op ?
1148// B = X op Y
1149// C = A op B
1150//
1151// breaking the dependency between A and B, allowing them to be executed in
1152// parallel (or back-to-back in a pipeline) instead of depending on each other.
1153
1154// FIXME: This has the potential to be expensive (compile time) while not
1155// improving the code at all. Some ways to limit the overhead:
1156// 1. Track successful transforms; bail out if hit rate gets too low.
1157// 2. Only enable at -O3 or some other non-default optimization level.
1158// 3. Pre-screen pattern candidates here: if an operand of the previous
1159// instruction is known to not increase the critical path, then don't match
1160// that pattern.
1161bool TargetInstrInfo::getMachineCombinerPatterns(
1162 MachineInstr &Root, SmallVectorImpl<unsigned> &Patterns,
1163 bool DoRegPressureReduce) const {
1164 bool Commute;
1165 if (isReassociationCandidate(Inst: Root, Commuted&: Commute)) {
1166 // We found a sequence of instructions that may be suitable for a
1167 // reassociation of operands to increase ILP. Specify each commutation
1168 // possibility for the Prev instruction in the sequence and let the
1169 // machine combiner decide if changing the operands is worthwhile.
1170 if (Commute) {
1171 Patterns.push_back(Elt: MachineCombinerPattern::REASSOC_AX_YB);
1172 Patterns.push_back(Elt: MachineCombinerPattern::REASSOC_XA_YB);
1173 } else {
1174 Patterns.push_back(Elt: MachineCombinerPattern::REASSOC_AX_BY);
1175 Patterns.push_back(Elt: MachineCombinerPattern::REASSOC_XA_BY);
1176 }
1177 return true;
1178 }
1179 if (getAccumulatorReassociationPatterns(Root, Patterns))
1180 return true;
1181
1182 return false;
1183}
1184
1185/// Return true when a code sequence can improve loop throughput.
1186bool TargetInstrInfo::isThroughputPattern(unsigned Pattern) const {
1187 return false;
1188}
1189
1190CombinerObjective
1191TargetInstrInfo::getCombinerObjective(unsigned Pattern) const {
1192 switch (Pattern) {
1193 case MachineCombinerPattern::ACC_CHAIN:
1194 return CombinerObjective::MustReduceDepth;
1195 default:
1196 return CombinerObjective::Default;
1197 }
1198}
1199
1200std::pair<unsigned, unsigned>
1201TargetInstrInfo::getReassociationOpcodes(unsigned Pattern,
1202 const MachineInstr &Root,
1203 const MachineInstr &Prev) const {
1204 bool AssocCommutRoot = isAssociativeAndCommutative(Inst: Root);
1205 bool AssocCommutPrev = isAssociativeAndCommutative(Inst: Prev);
1206
1207 // Early exit if both opcodes are associative and commutative. It's a trivial
1208 // reassociation when we only change operands order. In this case opcodes are
1209 // not required to have inverse versions.
1210 if (AssocCommutRoot && AssocCommutPrev) {
1211 assert(Root.getOpcode() == Prev.getOpcode() && "Expected to be equal");
1212 return std::make_pair(x: Root.getOpcode(), y: Root.getOpcode());
1213 }
1214
1215 // At least one instruction is not associative or commutative.
1216 // Since we have matched one of the reassociation patterns, we expect that the
1217 // instructions' opcodes are equal or one of them is the inversion of the
1218 // other.
1219 assert(areOpcodesEqualOrInverse(Root.getOpcode(), Prev.getOpcode()) &&
1220 "Incorrectly matched pattern");
1221 unsigned AssocCommutOpcode = Root.getOpcode();
1222 unsigned InverseOpcode = *getInverseOpcode(Opcode: Root.getOpcode());
1223 if (!AssocCommutRoot)
1224 std::swap(a&: AssocCommutOpcode, b&: InverseOpcode);
1225
1226 // The transformation rule (`+` is any associative and commutative binary
1227 // operation, `-` is the inverse):
1228 // REASSOC_AX_BY:
1229 // (A + X) + Y => A + (X + Y)
1230 // (A + X) - Y => A + (X - Y)
1231 // (A - X) + Y => A - (X - Y)
1232 // (A - X) - Y => A - (X + Y)
1233 // REASSOC_XA_BY:
1234 // (X + A) + Y => (X + Y) + A
1235 // (X + A) - Y => (X - Y) + A
1236 // (X - A) + Y => (X + Y) - A
1237 // (X - A) - Y => (X - Y) - A
1238 // REASSOC_AX_YB:
1239 // Y + (A + X) => (Y + X) + A
1240 // Y - (A + X) => (Y - X) - A
1241 // Y + (A - X) => (Y - X) + A
1242 // Y - (A - X) => (Y + X) - A
1243 // REASSOC_XA_YB:
1244 // Y + (X + A) => (Y + X) + A
1245 // Y - (X + A) => (Y - X) - A
1246 // Y + (X - A) => (Y + X) - A
1247 // Y - (X - A) => (Y - X) + A
1248 switch (Pattern) {
1249 default:
1250 llvm_unreachable("Unexpected pattern");
1251 case MachineCombinerPattern::REASSOC_AX_BY:
1252 if (!AssocCommutRoot && AssocCommutPrev)
1253 return {AssocCommutOpcode, InverseOpcode};
1254 if (AssocCommutRoot && !AssocCommutPrev)
1255 return {InverseOpcode, InverseOpcode};
1256 if (!AssocCommutRoot && !AssocCommutPrev)
1257 return {InverseOpcode, AssocCommutOpcode};
1258 break;
1259 case MachineCombinerPattern::REASSOC_XA_BY:
1260 if (!AssocCommutRoot && AssocCommutPrev)
1261 return {AssocCommutOpcode, InverseOpcode};
1262 if (AssocCommutRoot && !AssocCommutPrev)
1263 return {InverseOpcode, AssocCommutOpcode};
1264 if (!AssocCommutRoot && !AssocCommutPrev)
1265 return {InverseOpcode, InverseOpcode};
1266 break;
1267 case MachineCombinerPattern::REASSOC_AX_YB:
1268 if (!AssocCommutRoot && AssocCommutPrev)
1269 return {InverseOpcode, InverseOpcode};
1270 if (AssocCommutRoot && !AssocCommutPrev)
1271 return {AssocCommutOpcode, InverseOpcode};
1272 if (!AssocCommutRoot && !AssocCommutPrev)
1273 return {InverseOpcode, AssocCommutOpcode};
1274 break;
1275 case MachineCombinerPattern::REASSOC_XA_YB:
1276 if (!AssocCommutRoot && AssocCommutPrev)
1277 return {InverseOpcode, InverseOpcode};
1278 if (AssocCommutRoot && !AssocCommutPrev)
1279 return {InverseOpcode, AssocCommutOpcode};
1280 if (!AssocCommutRoot && !AssocCommutPrev)
1281 return {AssocCommutOpcode, InverseOpcode};
1282 break;
1283 }
1284 llvm_unreachable("Unhandled combination");
1285}
1286
1287// Return a pair of boolean flags showing if the new root and new prev operands
1288// must be swapped. See visual example of the rule in
1289// TargetInstrInfo::getReassociationOpcodes.
1290static std::pair<bool, bool> mustSwapOperands(unsigned Pattern) {
1291 switch (Pattern) {
1292 default:
1293 llvm_unreachable("Unexpected pattern");
1294 case MachineCombinerPattern::REASSOC_AX_BY:
1295 return {false, false};
1296 case MachineCombinerPattern::REASSOC_XA_BY:
1297 return {true, false};
1298 case MachineCombinerPattern::REASSOC_AX_YB:
1299 return {true, true};
1300 case MachineCombinerPattern::REASSOC_XA_YB:
1301 return {true, true};
1302 }
1303}
1304
1305void TargetInstrInfo::getReassociateOperandIndices(
1306 const MachineInstr &Root, unsigned Pattern,
1307 std::array<unsigned, 5> &OperandIndices) const {
1308 switch (Pattern) {
1309 case MachineCombinerPattern::REASSOC_AX_BY:
1310 OperandIndices = {1, 1, 1, 2, 2};
1311 break;
1312 case MachineCombinerPattern::REASSOC_AX_YB:
1313 OperandIndices = {2, 1, 2, 2, 1};
1314 break;
1315 case MachineCombinerPattern::REASSOC_XA_BY:
1316 OperandIndices = {1, 2, 1, 1, 2};
1317 break;
1318 case MachineCombinerPattern::REASSOC_XA_YB:
1319 OperandIndices = {2, 2, 2, 1, 1};
1320 break;
1321 default:
1322 llvm_unreachable("unexpected MachineCombinerPattern");
1323 }
1324}
1325
1326/// Attempt the reassociation transformation to reduce critical path length.
1327/// See the above comments before getMachineCombinerPatterns().
1328void TargetInstrInfo::reassociateOps(
1329 MachineInstr &Root, MachineInstr &Prev, unsigned Pattern,
1330 SmallVectorImpl<MachineInstr *> &InsInstrs,
1331 SmallVectorImpl<MachineInstr *> &DelInstrs,
1332 ArrayRef<unsigned> OperandIndices,
1333 DenseMap<Register, unsigned> &InstrIdxForVirtReg) const {
1334 MachineFunction *MF = Root.getMF();
1335 MachineRegisterInfo &MRI = MF->getRegInfo();
1336 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1337 const TargetRegisterClass *RC = Root.getRegClassConstraint(OpIdx: 0, TII, TRI: &TRI);
1338
1339 MachineOperand &OpA = Prev.getOperand(i: OperandIndices[1]);
1340 MachineOperand &OpB = Root.getOperand(i: OperandIndices[2]);
1341 MachineOperand &OpX = Prev.getOperand(i: OperandIndices[3]);
1342 MachineOperand &OpY = Root.getOperand(i: OperandIndices[4]);
1343 MachineOperand &OpC = Root.getOperand(i: 0);
1344
1345 Register RegA = OpA.getReg();
1346 unsigned SubRegA = OpA.getSubReg();
1347 Register RegB = OpB.getReg();
1348 Register RegX = OpX.getReg();
1349 unsigned SubRegX = OpX.getSubReg();
1350 Register RegY = OpY.getReg();
1351 unsigned SubRegY = OpY.getSubReg();
1352 Register RegC = OpC.getReg();
1353
1354 if (RegA.isVirtual())
1355 MRI.constrainRegClass(Reg: RegA, RC);
1356 if (RegB.isVirtual())
1357 MRI.constrainRegClass(Reg: RegB, RC);
1358 if (RegX.isVirtual())
1359 MRI.constrainRegClass(Reg: RegX, RC);
1360 if (RegY.isVirtual())
1361 MRI.constrainRegClass(Reg: RegY, RC);
1362 if (RegC.isVirtual())
1363 MRI.constrainRegClass(Reg: RegC, RC);
1364
1365 // Create a new virtual register for the result of (X op Y) instead of
1366 // recycling RegB because the MachineCombiner's computation of the critical
1367 // path requires a new register definition rather than an existing one.
1368 Register NewVR = MRI.createVirtualRegister(RegClass: RC);
1369 unsigned SubRegNewVR = 0;
1370 InstrIdxForVirtReg.insert(KV: std::make_pair(x&: NewVR, y: 0));
1371
1372 auto [NewRootOpc, NewPrevOpc] = getReassociationOpcodes(Pattern, Root, Prev);
1373 bool KillA = OpA.isKill();
1374 bool KillX = OpX.isKill();
1375 bool KillY = OpY.isKill();
1376 bool KillNewVR = true;
1377
1378 auto [SwapRootOperands, SwapPrevOperands] = mustSwapOperands(Pattern);
1379
1380 if (SwapPrevOperands) {
1381 std::swap(a&: RegX, b&: RegY);
1382 std::swap(a&: SubRegX, b&: SubRegY);
1383 std::swap(a&: KillX, b&: KillY);
1384 }
1385
1386 unsigned PrevFirstOpIdx, PrevSecondOpIdx;
1387 unsigned RootFirstOpIdx, RootSecondOpIdx;
1388 switch (Pattern) {
1389 case MachineCombinerPattern::REASSOC_AX_BY:
1390 PrevFirstOpIdx = OperandIndices[1];
1391 PrevSecondOpIdx = OperandIndices[3];
1392 RootFirstOpIdx = OperandIndices[2];
1393 RootSecondOpIdx = OperandIndices[4];
1394 break;
1395 case MachineCombinerPattern::REASSOC_AX_YB:
1396 PrevFirstOpIdx = OperandIndices[1];
1397 PrevSecondOpIdx = OperandIndices[3];
1398 RootFirstOpIdx = OperandIndices[4];
1399 RootSecondOpIdx = OperandIndices[2];
1400 break;
1401 case MachineCombinerPattern::REASSOC_XA_BY:
1402 PrevFirstOpIdx = OperandIndices[3];
1403 PrevSecondOpIdx = OperandIndices[1];
1404 RootFirstOpIdx = OperandIndices[2];
1405 RootSecondOpIdx = OperandIndices[4];
1406 break;
1407 case MachineCombinerPattern::REASSOC_XA_YB:
1408 PrevFirstOpIdx = OperandIndices[3];
1409 PrevSecondOpIdx = OperandIndices[1];
1410 RootFirstOpIdx = OperandIndices[4];
1411 RootSecondOpIdx = OperandIndices[2];
1412 break;
1413 default:
1414 llvm_unreachable("unexpected MachineCombinerPattern");
1415 }
1416
1417 // Basically BuildMI but doesn't add implicit operands by default.
1418 auto buildMINoImplicit = [](MachineFunction &MF, const MIMetadata &MIMD,
1419 const MCInstrDesc &MCID, Register DestReg) {
1420 return MachineInstrBuilder(
1421 MF, MF.CreateMachineInstr(MCID, DL: MIMD.getDL(), /*NoImpl=*/NoImplicit: true))
1422 .copyMIMetadata(MIMD)
1423 .addReg(RegNo: DestReg, Flags: RegState::Define);
1424 };
1425
1426 // Create new instructions for insertion.
1427 MachineInstrBuilder MIB1 =
1428 buildMINoImplicit(*MF, MIMetadata(Prev), TII->get(Opcode: NewPrevOpc), NewVR);
1429 for (const auto &MO : Prev.explicit_operands()) {
1430 unsigned Idx = MO.getOperandNo();
1431 // Skip the result operand we'd already added.
1432 if (Idx == 0)
1433 continue;
1434 if (Idx == PrevFirstOpIdx)
1435 MIB1.addReg(RegNo: RegX, Flags: getKillRegState(B: KillX), SubReg: SubRegX);
1436 else if (Idx == PrevSecondOpIdx)
1437 MIB1.addReg(RegNo: RegY, Flags: getKillRegState(B: KillY), SubReg: SubRegY);
1438 else
1439 MIB1.add(MO);
1440 }
1441 MIB1.copyImplicitOps(OtherMI: Prev);
1442
1443 if (SwapRootOperands) {
1444 std::swap(a&: RegA, b&: NewVR);
1445 std::swap(a&: SubRegA, b&: SubRegNewVR);
1446 std::swap(a&: KillA, b&: KillNewVR);
1447 }
1448
1449 MachineInstrBuilder MIB2 =
1450 buildMINoImplicit(*MF, MIMetadata(Root), TII->get(Opcode: NewRootOpc), RegC);
1451 for (const auto &MO : Root.explicit_operands()) {
1452 unsigned Idx = MO.getOperandNo();
1453 // Skip the result operand.
1454 if (Idx == 0)
1455 continue;
1456 if (Idx == RootFirstOpIdx)
1457 MIB2 = MIB2.addReg(RegNo: RegA, Flags: getKillRegState(B: KillA), SubReg: SubRegA);
1458 else if (Idx == RootSecondOpIdx)
1459 MIB2 = MIB2.addReg(RegNo: NewVR, Flags: getKillRegState(B: KillNewVR), SubReg: SubRegNewVR);
1460 else
1461 MIB2 = MIB2.add(MO);
1462 }
1463 MIB2.copyImplicitOps(OtherMI: Root);
1464
1465 // Propagate FP flags from the original instructions.
1466 // But clear poison-generating flags because those may not be valid now.
1467 // TODO: There should be a helper function for copying only fast-math-flags.
1468 uint32_t IntersectedFlags = Root.getFlags() & Prev.getFlags();
1469 MIB1->setFlags(IntersectedFlags);
1470 MIB1->clearFlag(Flag: MachineInstr::MIFlag::NoSWrap);
1471 MIB1->clearFlag(Flag: MachineInstr::MIFlag::NoUWrap);
1472 MIB1->clearFlag(Flag: MachineInstr::MIFlag::IsExact);
1473 MIB1->clearFlag(Flag: MachineInstr::MIFlag::Disjoint);
1474
1475 MIB2->setFlags(IntersectedFlags);
1476 MIB2->clearFlag(Flag: MachineInstr::MIFlag::NoSWrap);
1477 MIB2->clearFlag(Flag: MachineInstr::MIFlag::NoUWrap);
1478 MIB2->clearFlag(Flag: MachineInstr::MIFlag::IsExact);
1479 MIB2->clearFlag(Flag: MachineInstr::MIFlag::Disjoint);
1480
1481 setSpecialOperandAttr(OldMI1&: Root, OldMI2&: Prev, NewMI1&: *MIB1, NewMI2&: *MIB2);
1482
1483 // Record new instructions for insertion and old instructions for deletion.
1484 InsInstrs.push_back(Elt: MIB1);
1485 InsInstrs.push_back(Elt: MIB2);
1486 DelInstrs.push_back(Elt: &Prev);
1487 DelInstrs.push_back(Elt: &Root);
1488
1489 // We transformed:
1490 // B = A op X (Prev)
1491 // C = B op Y (Root)
1492 // Into:
1493 // B = X op Y (MIB1)
1494 // C = A op B (MIB2)
1495 // C has the same value as before, B doesn't; as such, keep the debug number
1496 // of C but not of B.
1497 if (unsigned OldRootNum = Root.peekDebugInstrNum())
1498 MIB2.getInstr()->setDebugInstrNum(OldRootNum);
1499}
1500
1501void TargetInstrInfo::genAlternativeCodeSequence(
1502 MachineInstr &Root, unsigned Pattern,
1503 SmallVectorImpl<MachineInstr *> &InsInstrs,
1504 SmallVectorImpl<MachineInstr *> &DelInstrs,
1505 DenseMap<Register, unsigned> &InstIdxForVirtReg) const {
1506 MachineRegisterInfo &MRI = Root.getMF()->getRegInfo();
1507 MachineBasicBlock &MBB = *Root.getParent();
1508 MachineFunction &MF = *MBB.getParent();
1509 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
1510
1511 switch (Pattern) {
1512 case MachineCombinerPattern::REASSOC_AX_BY:
1513 case MachineCombinerPattern::REASSOC_AX_YB:
1514 case MachineCombinerPattern::REASSOC_XA_BY:
1515 case MachineCombinerPattern::REASSOC_XA_YB: {
1516 // Select the previous instruction in the sequence based on the input
1517 // pattern.
1518 std::array<unsigned, 5> OperandIndices;
1519 getReassociateOperandIndices(Root, Pattern, OperandIndices);
1520 MachineInstr *Prev =
1521 MRI.getUniqueVRegDef(Reg: Root.getOperand(i: OperandIndices[0]).getReg());
1522
1523 // Don't reassociate if Prev and Root are in different blocks.
1524 if (Prev->getParent() != Root.getParent())
1525 return;
1526
1527 reassociateOps(Root, Prev&: *Prev, Pattern, InsInstrs, DelInstrs, OperandIndices,
1528 InstrIdxForVirtReg&: InstIdxForVirtReg);
1529 break;
1530 }
1531 case MachineCombinerPattern::ACC_CHAIN: {
1532 SmallVector<Register, 32> ChainRegs;
1533 getAccumulatorChain(CurrentInstr: &Root, Chain&: ChainRegs);
1534 unsigned int Depth = ChainRegs.size();
1535 assert(MaxAccumulatorWidth > 1 &&
1536 "Max accumulator width set to illegal value");
1537 unsigned int MaxWidth = Log2_32(Value: Depth) < MaxAccumulatorWidth
1538 ? Log2_32(Value: Depth)
1539 : MaxAccumulatorWidth;
1540
1541 // Walk down the chain and rewrite it as a tree.
1542 for (auto IndexedReg : llvm::enumerate(First: llvm::reverse(C&: ChainRegs))) {
1543 // No need to rewrite the first node, it is already perfect as it is.
1544 if (IndexedReg.index() == 0)
1545 continue;
1546
1547 // FIXME: Losing subregisters
1548 MachineInstr *Instr = MRI.getUniqueVRegDef(Reg: IndexedReg.value());
1549 MachineInstrBuilder MIB;
1550 Register AccReg;
1551 if (IndexedReg.index() < MaxWidth) {
1552 // Now we need to create new instructions for the first row.
1553 AccReg = Instr->getOperand(i: 0).getReg();
1554 unsigned OpCode = getAccumulationStartOpcode(Opcode: Root.getOpcode());
1555
1556 MIB = BuildMI(MF, MIMD: MIMetadata(*Instr), MCID: TII->get(Opcode: OpCode), DestReg: AccReg)
1557 .addReg(RegNo: Instr->getOperand(i: 2).getReg(),
1558 Flags: getKillRegState(B: Instr->getOperand(i: 2).isKill()))
1559 .addReg(RegNo: Instr->getOperand(i: 3).getReg(),
1560 Flags: getKillRegState(B: Instr->getOperand(i: 3).isKill()));
1561 } else {
1562 // For the remaining cases, we need to use an output register of one of
1563 // the newly inserted instuctions as operand 1
1564 AccReg = Instr->getOperand(i: 0).getReg() == Root.getOperand(i: 0).getReg()
1565 ? MRI.createVirtualRegister(
1566 RegClass: MRI.getRegClass(Reg: Root.getOperand(i: 0).getReg()))
1567 : Instr->getOperand(i: 0).getReg();
1568 assert(IndexedReg.index() >= MaxWidth);
1569 auto AccumulatorInput =
1570 ChainRegs[Depth - (IndexedReg.index() - MaxWidth) - 1];
1571 MIB = BuildMI(MF, MIMD: MIMetadata(*Instr), MCID: TII->get(Opcode: Instr->getOpcode()),
1572 DestReg: AccReg)
1573 .addReg(RegNo: AccumulatorInput, Flags: getKillRegState(B: true))
1574 .addReg(RegNo: Instr->getOperand(i: 2).getReg(),
1575 Flags: getKillRegState(B: Instr->getOperand(i: 2).isKill()))
1576 .addReg(RegNo: Instr->getOperand(i: 3).getReg(),
1577 Flags: getKillRegState(B: Instr->getOperand(i: 3).isKill()));
1578 }
1579
1580 MIB->setFlags(Instr->getFlags());
1581 InstIdxForVirtReg.insert(KV: std::make_pair(x&: AccReg, y: InsInstrs.size()));
1582 InsInstrs.push_back(Elt: MIB);
1583 DelInstrs.push_back(Elt: Instr);
1584 }
1585
1586 SmallVector<Register, 8> RegistersToReduce;
1587 for (unsigned i = (InsInstrs.size() - MaxWidth); i < InsInstrs.size();
1588 ++i) {
1589 auto Reg = InsInstrs[i]->getOperand(i: 0).getReg();
1590 RegistersToReduce.push_back(Elt: Reg);
1591 }
1592
1593 while (RegistersToReduce.size() > 1)
1594 reduceAccumulatorTree(RegistersToReduce, InsInstrs, MF, Root, MRI,
1595 InstrIdxForVirtReg&: InstIdxForVirtReg, ResultReg: Root.getOperand(i: 0).getReg());
1596
1597 break;
1598 }
1599 }
1600}
1601
1602MachineTraceStrategy TargetInstrInfo::getMachineCombinerTraceStrategy() const {
1603 return MachineTraceStrategy::TS_MinInstrCount;
1604}
1605
1606bool TargetInstrInfo::isReMaterializableImpl(
1607 const MachineInstr &MI) const {
1608 const MachineFunction &MF = *MI.getMF();
1609 const MachineRegisterInfo &MRI = MF.getRegInfo();
1610
1611 // Remat clients assume operand 0 is the defined register.
1612 if (!MI.getNumOperands() || !MI.getOperand(i: 0).isReg())
1613 return false;
1614 Register DefReg = MI.getOperand(i: 0).getReg();
1615
1616 // A sub-register definition can only be rematerialized if the instruction
1617 // doesn't read the other parts of the register. Otherwise it is really a
1618 // read-modify-write operation on the full virtual register which cannot be
1619 // moved safely.
1620 if (DefReg.isVirtual() && MI.getOperand(i: 0).getSubReg() &&
1621 MI.readsVirtualRegister(Reg: DefReg))
1622 return false;
1623
1624 // A load from a fixed stack slot can be rematerialized. This may be
1625 // redundant with subsequent checks, but it's target-independent,
1626 // simple, and a common case.
1627 int FrameIdx = 0;
1628 if (isLoadFromStackSlot(MI, FrameIndex&: FrameIdx) &&
1629 MF.getFrameInfo().isImmutableObjectIndex(ObjectIdx: FrameIdx))
1630 return true;
1631
1632 // Avoid instructions obviously unsafe for remat.
1633 if (MI.isNotDuplicable() || MI.mayStore() || MI.mayRaiseFPException() ||
1634 MI.hasUnmodeledSideEffects())
1635 return false;
1636
1637 // Don't remat inline asm. We have no idea how expensive it is
1638 // even if it's side effect free.
1639 if (MI.isInlineAsm())
1640 return false;
1641
1642 // Avoid instructions which load from potentially varying memory.
1643 if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad())
1644 return false;
1645
1646 // If any of the registers accessed are non-constant, conservatively assume
1647 // the instruction is not rematerializable.
1648 for (const MachineOperand &MO : MI.operands()) {
1649 if (!MO.isReg()) continue;
1650 Register Reg = MO.getReg();
1651 if (Reg == 0)
1652 continue;
1653
1654 // Check for a well-behaved physical register.
1655 if (Reg.isPhysical()) {
1656 if (MO.isUse()) {
1657 // If the physreg has no defs anywhere, it's just an ambient register
1658 // and we can freely move its uses. Alternatively, if it's allocatable,
1659 // it could get allocated to something with a def during allocation.
1660 if (!MRI.isConstantPhysReg(PhysReg: Reg))
1661 return false;
1662 } else {
1663 // A physreg def. We can't remat it.
1664 return false;
1665 }
1666 continue;
1667 }
1668
1669 // Only allow one virtual-register def. There may be multiple defs of the
1670 // same virtual register, though.
1671 if (MO.isDef() && Reg != DefReg)
1672 return false;
1673 }
1674
1675 // Everything checked out.
1676 return true;
1677}
1678
1679int TargetInstrInfo::getSPAdjust(const MachineInstr &MI) const {
1680 const MachineFunction *MF = MI.getMF();
1681 const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
1682 bool StackGrowsDown =
1683 TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown;
1684
1685 unsigned FrameSetupOpcode = getCallFrameSetupOpcode();
1686 unsigned FrameDestroyOpcode = getCallFrameDestroyOpcode();
1687
1688 if (!isFrameInstr(I: MI))
1689 return 0;
1690
1691 int SPAdj = TFI->alignSPAdjust(SPAdj: getFrameSize(I: MI));
1692
1693 if ((!StackGrowsDown && MI.getOpcode() == FrameSetupOpcode) ||
1694 (StackGrowsDown && MI.getOpcode() == FrameDestroyOpcode))
1695 SPAdj = -SPAdj;
1696
1697 return SPAdj;
1698}
1699
1700/// isSchedulingBoundary - Test if the given instruction should be
1701/// considered a scheduling boundary. This primarily includes labels
1702/// and terminators.
1703bool TargetInstrInfo::isSchedulingBoundary(const MachineInstr &MI,
1704 const MachineBasicBlock *MBB,
1705 const MachineFunction &MF) const {
1706 // Terminators and labels can't be scheduled around.
1707 if (MI.isTerminator() || MI.isPosition())
1708 return true;
1709
1710 // INLINEASM_BR can jump to another block
1711 if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
1712 return true;
1713
1714 // Don't attempt to schedule around any instruction that defines
1715 // a stack-oriented pointer, as it's unlikely to be profitable. This
1716 // saves compile time, because it doesn't require every single
1717 // stack slot reference to depend on the instruction that does the
1718 // modification.
1719 const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
1720 return MI.modifiesRegister(Reg: TLI.getStackPointerRegisterToSaveRestore(), TRI: &TRI);
1721}
1722
1723// Provide a global flag for disabling the PreRA hazard recognizer that targets
1724// may choose to honor.
1725bool TargetInstrInfo::usePreRAHazardRecognizer() const {
1726 return !DisableHazardRecognizer;
1727}
1728
1729// Default implementation of CreateTargetRAHazardRecognizer.
1730ScheduleHazardRecognizer *TargetInstrInfo::
1731CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
1732 const ScheduleDAG *DAG) const {
1733 // Dummy hazard recognizer allows all instructions to issue.
1734 return new ScheduleHazardRecognizer();
1735}
1736
1737// Default implementation of CreateTargetMIHazardRecognizer.
1738ScheduleHazardRecognizer *TargetInstrInfo::CreateTargetMIHazardRecognizer(
1739 const InstrItineraryData *II, const ScheduleDAGMI *DAG) const {
1740 return new ScoreboardHazardRecognizer(II, DAG, "machine-scheduler");
1741}
1742
1743// Default implementation of CreateTargetPostRAHazardRecognizer.
1744ScheduleHazardRecognizer *TargetInstrInfo::
1745CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
1746 const ScheduleDAG *DAG) const {
1747 return new ScoreboardHazardRecognizer(II, DAG, "post-RA-sched");
1748}
1749
1750// Default implementation of getMemOperandWithOffset.
1751bool TargetInstrInfo::getMemOperandWithOffset(
1752 const MachineInstr &MI, const MachineOperand *&BaseOp, int64_t &Offset,
1753 bool &OffsetIsScalable, const TargetRegisterInfo * /*RemoveMe*/) const {
1754 SmallVector<const MachineOperand *, 4> BaseOps;
1755 LocationSize Width = LocationSize::precise(Value: 0);
1756 if (!getMemOperandsWithOffsetWidth(MI, BaseOps, Offset, OffsetIsScalable,
1757 Width, TRI: &TRI) ||
1758 BaseOps.size() != 1)
1759 return false;
1760 BaseOp = BaseOps.front();
1761 return true;
1762}
1763
1764//===----------------------------------------------------------------------===//
1765// SelectionDAG latency interface.
1766//===----------------------------------------------------------------------===//
1767
1768std::optional<unsigned>
1769TargetInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
1770 SDNode *DefNode, unsigned DefIdx,
1771 SDNode *UseNode, unsigned UseIdx) const {
1772 if (!ItinData || ItinData->isEmpty())
1773 return std::nullopt;
1774
1775 if (!DefNode->isMachineOpcode())
1776 return std::nullopt;
1777
1778 unsigned DefClass = get(Opcode: DefNode->getMachineOpcode()).getSchedClass();
1779 if (!UseNode->isMachineOpcode())
1780 return ItinData->getOperandCycle(ItinClassIndx: DefClass, OperandIdx: DefIdx);
1781 unsigned UseClass = get(Opcode: UseNode->getMachineOpcode()).getSchedClass();
1782 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
1783}
1784
1785unsigned TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
1786 SDNode *N) const {
1787 if (!ItinData || ItinData->isEmpty())
1788 return 1;
1789
1790 if (!N->isMachineOpcode())
1791 return 1;
1792
1793 return ItinData->getStageLatency(ItinClassIndx: get(Opcode: N->getMachineOpcode()).getSchedClass());
1794}
1795
1796//===----------------------------------------------------------------------===//
1797// MachineInstr latency interface.
1798//===----------------------------------------------------------------------===//
1799
1800unsigned TargetInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
1801 const MachineInstr &MI) const {
1802 if (!ItinData || ItinData->isEmpty())
1803 return 1;
1804
1805 unsigned Class = MI.getDesc().getSchedClass();
1806 int UOps = ItinData->Itineraries[Class].NumMicroOps;
1807 if (UOps >= 0)
1808 return UOps;
1809
1810 // The # of u-ops is dynamically determined. The specific target should
1811 // override this function to return the right number.
1812 return 1;
1813}
1814
1815/// Return the default expected latency for a def based on it's opcode.
1816unsigned TargetInstrInfo::defaultDefLatency(const MCSchedModel &SchedModel,
1817 const MachineInstr &DefMI) const {
1818 if (DefMI.isTransient())
1819 return 0;
1820 if (DefMI.mayLoad())
1821 return SchedModel.LoadLatency;
1822 if (isHighLatencyDef(opc: DefMI.getOpcode()))
1823 return SchedModel.HighLatency;
1824 return 1;
1825}
1826
1827unsigned TargetInstrInfo::getPredicationCost(const MachineInstr &) const {
1828 return 0;
1829}
1830
1831unsigned TargetInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
1832 const MachineInstr &MI,
1833 unsigned *PredCost) const {
1834 // Default to one cycle for no itinerary. However, an "empty" itinerary may
1835 // still have a MinLatency property, which getStageLatency checks.
1836 if (!ItinData)
1837 return MI.mayLoad() ? 2 : 1;
1838
1839 return ItinData->getStageLatency(ItinClassIndx: MI.getDesc().getSchedClass());
1840}
1841
1842bool TargetInstrInfo::hasLowDefLatency(const TargetSchedModel &SchedModel,
1843 const MachineInstr &DefMI,
1844 unsigned DefIdx) const {
1845 const InstrItineraryData *ItinData = SchedModel.getInstrItineraries();
1846 if (!ItinData || ItinData->isEmpty())
1847 return false;
1848
1849 unsigned DefClass = DefMI.getDesc().getSchedClass();
1850 std::optional<unsigned> DefCycle =
1851 ItinData->getOperandCycle(ItinClassIndx: DefClass, OperandIdx: DefIdx);
1852 return DefCycle && DefCycle <= 1U;
1853}
1854
1855bool TargetInstrInfo::isFunctionSafeToSplit(const MachineFunction &MF) const {
1856 // TODO: We don't split functions where a section attribute has been set
1857 // since the split part may not be placed in a contiguous region. It may also
1858 // be more beneficial to augment the linker to ensure contiguous layout of
1859 // split functions within the same section as specified by the attribute.
1860 if (MF.getFunction().hasSection())
1861 return false;
1862
1863 // We don't want to proceed further for cold functions
1864 // or functions of unknown hotness. Lukewarm functions have no prefix.
1865 std::optional<StringRef> SectionPrefix = MF.getFunction().getSectionPrefix();
1866 if (SectionPrefix &&
1867 (*SectionPrefix == "unlikely" || *SectionPrefix == "unknown")) {
1868 return false;
1869 }
1870
1871 return true;
1872}
1873
1874std::optional<ParamLoadedValue>
1875TargetInstrInfo::describeLoadedValue(const MachineInstr &MI,
1876 Register Reg) const {
1877 const MachineFunction *MF = MI.getMF();
1878 DIExpression *Expr = DIExpression::get(Context&: MF->getFunction().getContext(), Elements: {});
1879 int64_t Offset;
1880 bool OffsetIsScalable;
1881
1882 // To simplify the sub-register handling, verify that we only need to
1883 // consider physical registers.
1884 assert(MF->getProperties().hasNoVRegs());
1885
1886 if (auto DestSrc = isCopyInstr(MI)) {
1887 Register DestReg = DestSrc->Destination->getReg();
1888
1889 // If the copy destination is the forwarding reg, describe the forwarding
1890 // reg using the copy source as the backup location. Example:
1891 //
1892 // x0 = MOV x7
1893 // call callee(x0) ; x0 described as x7
1894 if (Reg == DestReg)
1895 return ParamLoadedValue(*DestSrc->Source, Expr);
1896
1897 // If the target's hook couldn't describe this copy, give up.
1898 return std::nullopt;
1899 } else if (auto RegImm = isAddImmediate(MI, Reg)) {
1900 Register SrcReg = RegImm->Reg;
1901 Offset = RegImm->Imm;
1902 Expr = DIExpression::prepend(Expr, Flags: DIExpression::ApplyOffset, Offset);
1903 return ParamLoadedValue(MachineOperand::CreateReg(Reg: SrcReg, isDef: false), Expr);
1904 } else if (MI.hasOneMemOperand()) {
1905 // Only describe memory which provably does not escape the function. As
1906 // described in llvm.org/PR43343, escaped memory may be clobbered by the
1907 // callee (or by another thread).
1908 const MachineFrameInfo &MFI = MF->getFrameInfo();
1909 const MachineMemOperand *MMO = MI.memoperands()[0];
1910 const PseudoSourceValue *PSV = MMO->getPseudoValue();
1911
1912 // If the address points to "special" memory (e.g. a spill slot), it's
1913 // sufficient to check that it isn't aliased by any high-level IR value.
1914 if (!PSV || PSV->mayAlias(&MFI))
1915 return std::nullopt;
1916
1917 const MachineOperand *BaseOp;
1918 if (!getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable, &TRI))
1919 return std::nullopt;
1920
1921 // FIXME: Scalable offsets are not yet handled in the offset code below.
1922 if (OffsetIsScalable)
1923 return std::nullopt;
1924
1925 // TODO: Can currently only handle mem instructions with a single define.
1926 // An example from the x86 target:
1927 // ...
1928 // DIV64m $rsp, 1, $noreg, 24, $noreg, implicit-def dead $rax, implicit-def $rdx
1929 // ...
1930 //
1931 if (MI.getNumExplicitDefs() != 1)
1932 return std::nullopt;
1933
1934 // TODO: In what way do we need to take Reg into consideration here?
1935
1936 SmallVector<uint64_t, 8> Ops;
1937 DIExpression::appendOffset(Ops, Offset);
1938 Ops.push_back(Elt: dwarf::DW_OP_deref_size);
1939 Ops.push_back(Elt: MMO->getSize().hasValue() ? MMO->getSize().getValue()
1940 : ~UINT64_C(0));
1941 Expr = DIExpression::prependOpcodes(Expr, Ops);
1942 return ParamLoadedValue(*BaseOp, Expr);
1943 }
1944
1945 return std::nullopt;
1946}
1947
1948// Get the call frame size just before MI.
1949unsigned TargetInstrInfo::getCallFrameSizeAt(MachineInstr &MI) const {
1950 // Search backwards from MI for the most recent call frame instruction.
1951 MachineBasicBlock *MBB = MI.getParent();
1952 for (auto &AdjI : reverse(C: make_range(x: MBB->instr_begin(), y: MI.getIterator()))) {
1953 if (AdjI.getOpcode() == getCallFrameSetupOpcode())
1954 return getFrameTotalSize(I: AdjI);
1955 if (AdjI.getOpcode() == getCallFrameDestroyOpcode())
1956 return 0;
1957 }
1958
1959 // If none was found, use the call frame size from the start of the basic
1960 // block.
1961 return MBB->getCallFrameSize();
1962}
1963
1964/// Both DefMI and UseMI must be valid. By default, call directly to the
1965/// itinerary. This may be overriden by the target.
1966std::optional<unsigned> TargetInstrInfo::getOperandLatency(
1967 const InstrItineraryData *ItinData, const MachineInstr &DefMI,
1968 unsigned DefIdx, const MachineInstr &UseMI, unsigned UseIdx) const {
1969 unsigned DefClass = DefMI.getDesc().getSchedClass();
1970 unsigned UseClass = UseMI.getDesc().getSchedClass();
1971 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
1972}
1973
1974bool TargetInstrInfo::getRegSequenceInputs(
1975 const MachineInstr &MI, unsigned DefIdx,
1976 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
1977 assert((MI.isRegSequence() ||
1978 MI.isRegSequenceLike()) && "Instruction do not have the proper type");
1979
1980 if (!MI.isRegSequence())
1981 return getRegSequenceLikeInputs(MI, DefIdx, InputRegs);
1982
1983 // We are looking at:
1984 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
1985 assert(DefIdx == 0 && "REG_SEQUENCE only has one def");
1986 for (unsigned OpIdx = 1, EndOpIdx = MI.getNumOperands(); OpIdx != EndOpIdx;
1987 OpIdx += 2) {
1988 const MachineOperand &MOReg = MI.getOperand(i: OpIdx);
1989 if (MOReg.isUndef())
1990 continue;
1991 const MachineOperand &MOSubIdx = MI.getOperand(i: OpIdx + 1);
1992 assert(MOSubIdx.isImm() &&
1993 "One of the subindex of the reg_sequence is not an immediate");
1994 // Record Reg:SubReg, SubIdx.
1995 InputRegs.push_back(Elt: RegSubRegPairAndIdx(MOReg.getReg(), MOReg.getSubReg(),
1996 (unsigned)MOSubIdx.getImm()));
1997 }
1998 return true;
1999}
2000
2001bool TargetInstrInfo::getExtractSubregInputs(
2002 const MachineInstr &MI, unsigned DefIdx,
2003 RegSubRegPairAndIdx &InputReg) const {
2004 assert((MI.isExtractSubreg() ||
2005 MI.isExtractSubregLike()) && "Instruction do not have the proper type");
2006
2007 if (!MI.isExtractSubreg())
2008 return getExtractSubregLikeInputs(MI, DefIdx, InputReg);
2009
2010 // We are looking at:
2011 // Def = EXTRACT_SUBREG v0.sub1, sub0.
2012 assert(DefIdx == 0 && "EXTRACT_SUBREG only has one def");
2013 const MachineOperand &MOReg = MI.getOperand(i: 1);
2014 if (MOReg.isUndef())
2015 return false;
2016 const MachineOperand &MOSubIdx = MI.getOperand(i: 2);
2017 assert(MOSubIdx.isImm() &&
2018 "The subindex of the extract_subreg is not an immediate");
2019
2020 InputReg.Reg = MOReg.getReg();
2021 InputReg.SubReg = MOReg.getSubReg();
2022 InputReg.SubIdx = (unsigned)MOSubIdx.getImm();
2023 return true;
2024}
2025
2026bool TargetInstrInfo::getInsertSubregInputs(
2027 const MachineInstr &MI, unsigned DefIdx,
2028 RegSubRegPair &BaseReg, RegSubRegPairAndIdx &InsertedReg) const {
2029 assert((MI.isInsertSubreg() ||
2030 MI.isInsertSubregLike()) && "Instruction do not have the proper type");
2031
2032 if (!MI.isInsertSubreg())
2033 return getInsertSubregLikeInputs(MI, DefIdx, BaseReg, InsertedReg);
2034
2035 // We are looking at:
2036 // Def = INSERT_SEQUENCE v0, v1, sub0.
2037 assert(DefIdx == 0 && "INSERT_SUBREG only has one def");
2038 const MachineOperand &MOBaseReg = MI.getOperand(i: 1);
2039 const MachineOperand &MOInsertedReg = MI.getOperand(i: 2);
2040 if (MOInsertedReg.isUndef())
2041 return false;
2042 const MachineOperand &MOSubIdx = MI.getOperand(i: 3);
2043 assert(MOSubIdx.isImm() &&
2044 "One of the subindex of the reg_sequence is not an immediate");
2045 BaseReg.Reg = MOBaseReg.getReg();
2046 BaseReg.SubReg = MOBaseReg.getSubReg();
2047
2048 InsertedReg.Reg = MOInsertedReg.getReg();
2049 InsertedReg.SubReg = MOInsertedReg.getSubReg();
2050 InsertedReg.SubIdx = (unsigned)MOSubIdx.getImm();
2051 return true;
2052}
2053
2054// Returns a MIRPrinter comment for this machine operand.
2055std::string TargetInstrInfo::createMIROperandComment(
2056 const MachineInstr &MI, const MachineOperand &Op, unsigned OpIdx,
2057 const TargetRegisterInfo * /*RemoveMe*/) const {
2058
2059 if (!MI.isInlineAsm())
2060 return "";
2061
2062 std::string Flags;
2063 raw_string_ostream OS(Flags);
2064
2065 if (OpIdx == InlineAsm::MIOp_ExtraInfo) {
2066 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
2067 unsigned ExtraInfo = Op.getImm();
2068 OS << interleaved(R: InlineAsm::getExtraInfoNames(ExtraInfo), Separator: " ");
2069 return Flags;
2070 }
2071
2072 int FlagIdx = MI.findInlineAsmFlagIdx(OpIdx);
2073 if (FlagIdx < 0 || (unsigned)FlagIdx != OpIdx)
2074 return "";
2075
2076 assert(Op.isImm() && "Expected flag operand to be an immediate");
2077 // Pretty print the inline asm operand descriptor.
2078 unsigned Flag = Op.getImm();
2079 const InlineAsm::Flag F(Flag);
2080 OS << F.getKindName();
2081
2082 unsigned RCID;
2083 if (!F.isImmKind() && !F.isMemKind() && F.hasRegClassConstraint(RC&: RCID))
2084 OS << ':' << TRI.getRegClassName(Class: TRI.getRegClass(i: RCID));
2085
2086 if (F.isMemKind()) {
2087 InlineAsm::ConstraintCode MCID = F.getMemoryConstraintID();
2088 OS << ":" << InlineAsm::getMemConstraintName(C: MCID);
2089 }
2090
2091 unsigned TiedTo;
2092 if (F.isUseOperandTiedToDef(Idx&: TiedTo))
2093 OS << " tiedto:$" << TiedTo;
2094
2095 if ((F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isRegUseKind()) &&
2096 F.getRegMayBeFolded())
2097 OS << " foldable";
2098
2099 return Flags;
2100}
2101
2102TargetInstrInfo::PipelinerLoopInfo::~PipelinerLoopInfo() = default;
2103
2104void TargetInstrInfo::mergeOutliningCandidateAttributes(
2105 Function &F, std::vector<outliner::Candidate> &Candidates) const {
2106 // Include target features from an arbitrary candidate for the outlined
2107 // function. This makes sure the outlined function knows what kinds of
2108 // instructions are going into it. This is fine, since all parent functions
2109 // must necessarily support the instructions that are in the outlined region.
2110 outliner::Candidate &FirstCand = Candidates.front();
2111 const Function &ParentFn = FirstCand.getMF()->getFunction();
2112 if (ParentFn.hasFnAttribute(Kind: "target-features"))
2113 F.addFnAttr(Attr: ParentFn.getFnAttribute(Kind: "target-features"));
2114 if (ParentFn.hasFnAttribute(Kind: "target-cpu"))
2115 F.addFnAttr(Attr: ParentFn.getFnAttribute(Kind: "target-cpu"));
2116
2117 // Set nounwind, so we don't generate eh_frame.
2118 if (llvm::all_of(Range&: Candidates, P: [](const outliner::Candidate &C) {
2119 return C.getMF()->getFunction().hasFnAttribute(Kind: Attribute::NoUnwind);
2120 }))
2121 F.addFnAttr(Kind: Attribute::NoUnwind);
2122}
2123
2124outliner::InstrType
2125TargetInstrInfo::getOutliningType(const MachineModuleInfo &MMI,
2126 MachineBasicBlock::iterator &MIT,
2127 unsigned Flags) const {
2128 MachineInstr &MI = *MIT;
2129
2130 // NOTE: MI.isMetaInstruction() will match CFI_INSTRUCTION, but some targets
2131 // have support for outlining those. Special-case that here.
2132 if (MI.isCFIInstruction())
2133 // Just go right to the target implementation.
2134 return getOutliningTypeImpl(MMI, MIT, Flags);
2135
2136 // Be conservative about inline assembly.
2137 if (MI.isInlineAsm())
2138 return outliner::InstrType::Illegal;
2139
2140 // Labels generally can't safely be outlined.
2141 if (MI.isLabel())
2142 return outliner::InstrType::Illegal;
2143
2144 // Don't let debug instructions impact analysis.
2145 if (MI.isDebugInstr())
2146 return outliner::InstrType::Invisible;
2147
2148 // Some other special cases.
2149 switch (MI.getOpcode()) {
2150 case TargetOpcode::IMPLICIT_DEF:
2151 case TargetOpcode::KILL:
2152 case TargetOpcode::LIFETIME_START:
2153 case TargetOpcode::LIFETIME_END:
2154 return outliner::InstrType::Invisible;
2155 default:
2156 break;
2157 }
2158
2159 // Is this a terminator for a basic block?
2160 if (MI.isTerminator()) {
2161 // If this is a branch to another block, we can't outline it.
2162 if (!MI.getParent()->succ_empty())
2163 return outliner::InstrType::Illegal;
2164
2165 // Don't outline if the branch is not unconditional.
2166 if (isPredicated(MI))
2167 return outliner::InstrType::Illegal;
2168 }
2169
2170 // Make sure none of the operands of this instruction do anything that
2171 // might break if they're moved outside their current function.
2172 // This includes MachineBasicBlock references, BlockAddressses,
2173 // Constant pool indices and jump table indices.
2174 //
2175 // A quick note on MO_TargetIndex:
2176 // This doesn't seem to be used in any of the architectures that the
2177 // MachineOutliner supports, but it was still filtered out in all of them.
2178 // There was one exception (RISC-V), but MO_TargetIndex also isn't used there.
2179 // As such, this check is removed both here and in the target-specific
2180 // implementations. Instead, we assert to make sure this doesn't
2181 // catch anyone off-guard somewhere down the line.
2182 for (const MachineOperand &MOP : MI.operands()) {
2183 // If you hit this assertion, please remove it and adjust
2184 // `getOutliningTypeImpl` for your target appropriately if necessary.
2185 // Adding the assertion back to other supported architectures
2186 // would be nice too :)
2187 assert(!MOP.isTargetIndex() && "This isn't used quite yet!");
2188
2189 // CFI instructions should already have been filtered out at this point.
2190 assert(!MOP.isCFIIndex() && "CFI instructions handled elsewhere!");
2191
2192 // PrologEpilogInserter should've already run at this point.
2193 assert(!MOP.isFI() && "FrameIndex instructions should be gone by now!");
2194
2195 if (MOP.isMBB() || MOP.isBlockAddress() || MOP.isCPI() || MOP.isJTI())
2196 return outliner::InstrType::Illegal;
2197 }
2198
2199 // If we don't know, delegate to the target-specific hook.
2200 return getOutliningTypeImpl(MMI, MIT, Flags);
2201}
2202
2203bool TargetInstrInfo::isMBBSafeToOutlineFrom(MachineBasicBlock &MBB,
2204 unsigned &Flags) const {
2205 // Some instrumentations create special TargetOpcode at the start which
2206 // expands to special code sequences which must be present.
2207 auto First = MBB.getFirstNonDebugInstr();
2208 if (First == MBB.end())
2209 return true;
2210
2211 if (First->getOpcode() == TargetOpcode::FENTRY_CALL ||
2212 First->getOpcode() == TargetOpcode::PATCHABLE_FUNCTION_ENTER)
2213 return false;
2214
2215 // Some instrumentations create special pseudo-instructions at or just before
2216 // the end that must be present.
2217 auto Last = MBB.getLastNonDebugInstr();
2218 if (Last->getOpcode() == TargetOpcode::PATCHABLE_RET ||
2219 Last->getOpcode() == TargetOpcode::PATCHABLE_TAIL_CALL)
2220 return false;
2221
2222 if (Last != First && Last->isReturn()) {
2223 --Last;
2224 if (Last->getOpcode() == TargetOpcode::PATCHABLE_FUNCTION_EXIT ||
2225 Last->getOpcode() == TargetOpcode::PATCHABLE_TAIL_CALL)
2226 return false;
2227 }
2228 return true;
2229}
2230
2231bool TargetInstrInfo::isGlobalMemoryObject(const MachineInstr *MI) const {
2232 return MI->isCall() || MI->hasUnmodeledSideEffects() ||
2233 (MI->hasOrderedMemoryRef() && !MI->isDereferenceableInvariantLoad());
2234}
2235