LLVM 24.0.0git
TargetInstrInfo.cpp
Go to the documentation of this file.
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
14#include "llvm/ADT/Sequence.h"
15#include "llvm/ADT/SmallSet.h"
32#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/Module.h"
35#include "llvm/MC/MCAsmInfo.h"
42
43using namespace llvm;
44
46 "disable-sched-hazard", cl::Hidden, cl::init(false),
47 cl::desc("Disable hazard detection during preRA scheduling"));
48
50 "acc-reassoc", cl::Hidden, cl::init(true),
51 cl::desc("Enable reassociation of accumulation chains"));
52
55 cl::desc("Minimum length of accumulator chains "
56 "required for the optimization to kick in"));
57
59 "acc-max-width", cl::Hidden, cl::init(3),
60 cl::desc("Maximum number of branches in the accumulator tree"));
61
63
65 unsigned OpNum) const {
66 if (OpNum >= MCID.getNumOperands())
67 return nullptr;
68
69 const MCOperandInfo &OpInfo = MCID.operands()[OpNum];
70 int16_t RegClass = getOpRegClassID(OpInfo);
71
72 // Instructions like INSERT_SUBREG do not have fixed register classes.
73 if (RegClass < 0)
74 return nullptr;
75
76 // Otherwise just look it up normally.
77 return TRI.getRegClass(RegClass);
78}
79
80/// insertNoop - Insert a noop into the instruction stream at the specified
81/// point.
84 llvm_unreachable("Target didn't implement insertNoop!");
85}
86
87/// insertNoops - Insert noops into the instruction stream at the specified
88/// point.
91 unsigned Quantity) const {
92 for (unsigned i = 0; i < Quantity; ++i)
94}
95
96static bool isAsmComment(const char *Str, const MCAsmInfo &MAI) {
97 return strncmp(Str, MAI.getCommentString().data(),
98 MAI.getCommentString().size()) == 0;
99}
100
101/// Measure the specified inline asm to determine an approximation of its
102/// length.
103/// Comments (which run till the next SeparatorString or newline) do not
104/// count as an instruction.
105/// Any other non-whitespace text is considered an instruction, with
106/// multiple instructions separated by SeparatorString or newlines.
107/// Variable-length instructions are not handled here; this function
108/// may be overloaded in the target code to do that.
109/// We implement a special case of the .space directive which takes only a
110/// single integer argument in base 10 that is the size in bytes. This is a
111/// restricted form of the GAS directive in that we only interpret
112/// simple--i.e. not a logical or arithmetic expression--size values without
113/// the optional fill value. This is primarily used for creating arbitrary
114/// sized inline asm blocks for testing purposes.
115unsigned TargetInstrInfo::getInlineAsmLength(const char *Str,
116 const MCAsmInfo &MAI,
117 unsigned MaxInstLength) const {
118 // Count the number of instructions in the asm.
119 bool AtInsnStart = true;
120 unsigned Length = 0;
121 if (MaxInstLength == 0)
122 MaxInstLength = MAI.getMaxInstLength();
123 for (; *Str; ++Str) {
124 if (*Str == '\n' || strncmp(Str, MAI.getSeparatorString(),
125 strlen(MAI.getSeparatorString())) == 0) {
126 AtInsnStart = true;
127 } else if (isAsmComment(Str, MAI)) {
128 // Stop counting as an instruction after a comment until the next
129 // separator.
130 AtInsnStart = false;
131 }
132
133 if (AtInsnStart && !isSpace(static_cast<unsigned char>(*Str))) {
134 unsigned AddLength = MaxInstLength;
135 if (strncmp(Str, ".space", 6) == 0) {
136 char *EStr;
137 int SpaceSize;
138 SpaceSize = strtol(Str + 6, &EStr, 10);
139 SpaceSize = SpaceSize < 0 ? 0 : SpaceSize;
140 while (*EStr != '\n' && isSpace(static_cast<unsigned char>(*EStr)))
141 ++EStr;
142 if (*EStr == '\0' || *EStr == '\n' ||
143 isAsmComment(EStr, MAI)) // Successfully parsed .space argument
144 AddLength = SpaceSize;
145 }
146 Length += AddLength;
147 AtInsnStart = false;
148 }
149 }
150
151 return Length;
152}
153
155 unsigned Size = 0;
157 MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
158 while (++I != E && I->isInsideBundle()) {
159 assert(!I->isBundle() && "No nested bundle!");
161 }
162
163 return Size;
164}
165
166/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
167/// after it, replacing it with an unconditional branch to NewDest.
168void
170 MachineBasicBlock *NewDest) const {
171 MachineBasicBlock *MBB = Tail->getParent();
172
173 // Remove all the old successors of MBB from the CFG.
174 while (!MBB->succ_empty())
175 MBB->removeSuccessor(MBB->succ_begin());
176
177 // Save off the debug loc before erasing the instruction.
178 DebugLoc DL = Tail->getDebugLoc();
179
180 // Update call info and remove all the dead instructions
181 // from the end of MBB.
182 while (Tail != MBB->end()) {
183 auto MI = Tail++;
184 if (MI->shouldUpdateAdditionalCallInfo())
185 MBB->getParent()->eraseAdditionalCallInfo(&*MI);
186 MBB->erase(MI);
187 }
188
189 // If MBB isn't immediately before MBB, insert a branch to it.
191 insertBranch(*MBB, NewDest, nullptr, SmallVector<MachineOperand, 0>(), DL);
192 MBB->addSuccessor(NewDest);
193}
194
196 bool NewMI, unsigned Idx1,
197 unsigned Idx2) const {
198 const MCInstrDesc &MCID = MI.getDesc();
199 bool HasDef = MCID.getNumDefs();
200 if (HasDef && !MI.getOperand(0).isReg())
201 // No idea how to commute this instruction. Target should implement its own.
202 return nullptr;
203
204 unsigned CommutableOpIdx1 = Idx1; (void)CommutableOpIdx1;
205 unsigned CommutableOpIdx2 = Idx2; (void)CommutableOpIdx2;
206 assert(findCommutedOpIndices(MI, CommutableOpIdx1, CommutableOpIdx2) &&
207 CommutableOpIdx1 == Idx1 && CommutableOpIdx2 == Idx2 &&
208 "TargetInstrInfo::CommuteInstructionImpl(): not commutable operands.");
209 assert(MI.getOperand(Idx1).isReg() && MI.getOperand(Idx2).isReg() &&
210 "This only knows how to commute register operands so far");
211
212 Register Reg0 = HasDef ? MI.getOperand(0).getReg() : Register();
213 Register Reg1 = MI.getOperand(Idx1).getReg();
214 Register Reg2 = MI.getOperand(Idx2).getReg();
215 unsigned SubReg0 = HasDef ? MI.getOperand(0).getSubReg() : 0;
216 unsigned SubReg1 = MI.getOperand(Idx1).getSubReg();
217 unsigned SubReg2 = MI.getOperand(Idx2).getSubReg();
218 bool Reg1IsKill = MI.getOperand(Idx1).isKill();
219 bool Reg2IsKill = MI.getOperand(Idx2).isKill();
220 bool Reg1IsUndef = MI.getOperand(Idx1).isUndef();
221 bool Reg2IsUndef = MI.getOperand(Idx2).isUndef();
222 bool Reg1IsInternal = MI.getOperand(Idx1).isInternalRead();
223 bool Reg2IsInternal = MI.getOperand(Idx2).isInternalRead();
224 // Avoid calling isRenamable for virtual registers since we assert that
225 // renamable property is only queried/set for physical registers.
226 bool Reg1IsRenamable =
227 Reg1.isPhysical() ? MI.getOperand(Idx1).isRenamable() : false;
228 bool Reg2IsRenamable =
229 Reg2.isPhysical() ? MI.getOperand(Idx2).isRenamable() : false;
230
231 // For a case like this:
232 // %0.sub = INST %0.sub(tied), %1.sub, implicit-def %0
233 // we need to update the implicit-def after commuting to result in:
234 // %1.sub = INST %1.sub(tied), %0.sub, implicit-def %1
235 SmallVector<unsigned> UpdateImplicitDefIdx;
236 if (HasDef && MI.hasImplicitDef()) {
237 for (auto [OpNo, MO] : llvm::enumerate(MI.implicit_operands())) {
238 if (!MO.isReg())
239 continue;
240 Register ImplReg = MO.getReg();
241 if ((ImplReg.isVirtual() && ImplReg == Reg0) ||
242 (ImplReg.isPhysical() && Reg0.isPhysical() &&
243 TRI.isSubRegisterEq(ImplReg, Reg0)))
244 UpdateImplicitDefIdx.push_back(OpNo + MI.getNumExplicitOperands());
245 }
246 }
247
248 // If destination is tied to either of the commuted source register, then
249 // it must be updated.
250 if (HasDef && Reg0 == Reg1 &&
251 MI.getDesc().getOperandConstraint(Idx1, MCOI::TIED_TO) == 0) {
252 Reg2IsKill = false;
253 Reg0 = Reg2;
254 SubReg0 = SubReg2;
255 } else if (HasDef && Reg0 == Reg2 &&
256 MI.getDesc().getOperandConstraint(Idx2, MCOI::TIED_TO) == 0) {
257 Reg1IsKill = false;
258 Reg0 = Reg1;
259 SubReg0 = SubReg1;
260 }
261
262 MachineInstr *CommutedMI = nullptr;
263 if (NewMI) {
264 // Create a new instruction.
265 MachineFunction &MF = *MI.getMF();
266 CommutedMI = MF.CloneMachineInstr(&MI);
267 } else {
268 CommutedMI = &MI;
269 }
270
271 if (HasDef) {
272 CommutedMI->getOperand(0).setReg(Reg0);
273 CommutedMI->getOperand(0).setSubReg(SubReg0);
274 for (unsigned Idx : UpdateImplicitDefIdx)
275 CommutedMI->getOperand(Idx).setReg(Reg0);
276 }
277 CommutedMI->getOperand(Idx2).setReg(Reg1);
278 CommutedMI->getOperand(Idx1).setReg(Reg2);
279 CommutedMI->getOperand(Idx2).setSubReg(SubReg1);
280 CommutedMI->getOperand(Idx1).setSubReg(SubReg2);
281 CommutedMI->getOperand(Idx2).setIsKill(Reg1IsKill);
282 CommutedMI->getOperand(Idx1).setIsKill(Reg2IsKill);
283 CommutedMI->getOperand(Idx2).setIsUndef(Reg1IsUndef);
284 CommutedMI->getOperand(Idx1).setIsUndef(Reg2IsUndef);
285 CommutedMI->getOperand(Idx2).setIsInternalRead(Reg1IsInternal);
286 CommutedMI->getOperand(Idx1).setIsInternalRead(Reg2IsInternal);
287 // Avoid calling setIsRenamable for virtual registers since we assert that
288 // renamable property is only queried/set for physical registers.
289 if (Reg1.isPhysical())
290 CommutedMI->getOperand(Idx2).setIsRenamable(Reg1IsRenamable);
291 if (Reg2.isPhysical())
292 CommutedMI->getOperand(Idx1).setIsRenamable(Reg2IsRenamable);
293 return CommutedMI;
294}
295
297 unsigned OpIdx1,
298 unsigned OpIdx2) const {
299 // If OpIdx1 or OpIdx2 is not specified, then this method is free to choose
300 // any commutable operand, which is done in findCommutedOpIndices() method
301 // called below.
302 if ((OpIdx1 == CommuteAnyOperandIndex || OpIdx2 == CommuteAnyOperandIndex) &&
303 !findCommutedOpIndices(MI, OpIdx1, OpIdx2)) {
304 assert(MI.isCommutable() &&
305 "Precondition violation: MI must be commutable.");
306 return nullptr;
307 }
308 return commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2);
309}
310
312 unsigned &ResultIdx2,
313 unsigned CommutableOpIdx1,
314 unsigned CommutableOpIdx2) {
315 if (ResultIdx1 == CommuteAnyOperandIndex &&
316 ResultIdx2 == CommuteAnyOperandIndex) {
317 ResultIdx1 = CommutableOpIdx1;
318 ResultIdx2 = CommutableOpIdx2;
319 } else if (ResultIdx1 == CommuteAnyOperandIndex) {
320 if (ResultIdx2 == CommutableOpIdx1)
321 ResultIdx1 = CommutableOpIdx2;
322 else if (ResultIdx2 == CommutableOpIdx2)
323 ResultIdx1 = CommutableOpIdx1;
324 else
325 return false;
326 } else if (ResultIdx2 == CommuteAnyOperandIndex) {
327 if (ResultIdx1 == CommutableOpIdx1)
328 ResultIdx2 = CommutableOpIdx2;
329 else if (ResultIdx1 == CommutableOpIdx2)
330 ResultIdx2 = CommutableOpIdx1;
331 else
332 return false;
333 } else
334 // Check that the result operand indices match the given commutable
335 // operand indices.
336 return (ResultIdx1 == CommutableOpIdx1 && ResultIdx2 == CommutableOpIdx2) ||
337 (ResultIdx1 == CommutableOpIdx2 && ResultIdx2 == CommutableOpIdx1);
338
339 return true;
340}
341
343 unsigned &SrcOpIdx1,
344 unsigned &SrcOpIdx2) const {
345 assert(!MI.isBundle() &&
346 "TargetInstrInfo::findCommutedOpIndices() can't handle bundles");
347
348 const MCInstrDesc &MCID = MI.getDesc();
349 if (!MCID.isCommutable())
350 return false;
351
352 // This assumes v0 = op v1, v2 and commuting would swap v1 and v2. If this
353 // is not true, then the target must implement this.
354 unsigned CommutableOpIdx1 = MCID.getNumDefs();
355 unsigned CommutableOpIdx2 = CommutableOpIdx1 + 1;
356 if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2,
357 CommutableOpIdx1, CommutableOpIdx2))
358 return false;
359
360 if (!MI.getOperand(SrcOpIdx1).isReg() || !MI.getOperand(SrcOpIdx2).isReg())
361 // No idea.
362 return false;
363 return true;
364}
365
367 if (!MI.isTerminator()) return false;
368
369 // Conditional branch is a special case.
370 if (MI.isBranch() && !MI.isBarrier())
371 return true;
372 if (!MI.isPredicable())
373 return true;
374 return !isPredicated(MI);
375}
376
379 bool MadeChange = false;
380
381 assert(!MI.isBundle() &&
382 "TargetInstrInfo::PredicateInstruction() can't handle bundles");
383
384 const MCInstrDesc &MCID = MI.getDesc();
385 if (!MI.isPredicable())
386 return false;
387
388 for (unsigned j = 0, i = 0, e = MI.getNumOperands(); i != e; ++i) {
389 if (MCID.operands()[i].isPredicate()) {
390 MachineOperand &MO = MI.getOperand(i);
391 if (MO.isReg()) {
392 MO.setReg(Pred[j].getReg());
393 MadeChange = true;
394 } else if (MO.isImm()) {
395 MO.setImm(Pred[j].getImm());
396 MadeChange = true;
397 } else if (MO.isMBB()) {
398 MO.setMBB(Pred[j].getMBB());
399 MadeChange = true;
400 }
401 ++j;
402 }
403 }
404 return MadeChange;
405}
406
408 const MachineInstr &MI,
410 size_t StartSize = Accesses.size();
411 for (MachineInstr::mmo_iterator o = MI.memoperands_begin(),
412 oe = MI.memoperands_end();
413 o != oe; ++o) {
414 if ((*o)->isLoad() &&
415 isa_and_nonnull<FixedStackPseudoSourceValue>((*o)->getPseudoValue()))
416 Accesses.push_back(*o);
417 }
418 return Accesses.size() != StartSize;
419}
420
422 const MachineInstr &MI,
424 size_t StartSize = Accesses.size();
425 for (MachineInstr::mmo_iterator o = MI.memoperands_begin(),
426 oe = MI.memoperands_end();
427 o != oe; ++o) {
428 if ((*o)->isStore() &&
429 isa_and_nonnull<FixedStackPseudoSourceValue>((*o)->getPseudoValue()))
430 Accesses.push_back(*o);
431 }
432 return Accesses.size() != StartSize;
433}
434
436 unsigned SubIdx, unsigned &Size,
437 unsigned &Offset,
438 const MachineFunction &MF) const {
439 if (!SubIdx) {
440 Size = TRI.getSpillSize(*RC);
441 Offset = 0;
442 return true;
443 }
444 unsigned BitSize = TRI.getSubRegIdxSize(SubIdx);
445 // Convert bit size to byte size.
446 if (BitSize % 8)
447 return false;
448
449 int BitOffset = TRI.getSubRegIdxOffset(SubIdx);
450 if (BitOffset < 0 || BitOffset % 8)
451 return false;
452
453 Size = BitSize / 8;
454 Offset = (unsigned)BitOffset / 8;
455
456 assert(TRI.getSpillSize(*RC) >= (Offset + Size) && "bad subregister range");
457
458 if (!MF.getDataLayout().isLittleEndian()) {
459 Offset = TRI.getSpillSize(*RC) - (Offset + Size);
460 }
461 return true;
462}
463
466 Register DestReg, unsigned SubIdx,
467 const MachineInstr &Orig,
468 LaneBitmask UsedLanes) const {
469 MachineInstr *MI = MBB.getParent()->CloneMachineInstr(&Orig);
470 MI->substituteRegister(MI->getOperand(0).getReg(), DestReg, SubIdx, TRI);
471 MBB.insert(I, MI);
472}
473
475 const MachineInstr &MI1,
476 const MachineRegisterInfo *MRI) const {
478}
479
482 MachineBasicBlock::iterator InsertBefore,
483 const MachineInstr &Orig) const {
484 MachineFunction &MF = *MBB.getParent();
485 // CFI instructions are marked as non-duplicable, because Darwin compact
486 // unwind info emission can't handle multiple prologue setups.
487 assert((!Orig.isNotDuplicable() ||
489 Orig.isCFIInstruction())) &&
490 "Instruction cannot be duplicated");
491
492 return MF.cloneMachineInstrBundle(MBB, InsertBefore, Orig);
493}
494
495// If the COPY instruction in MI can be folded to a stack operation, return
496// the register class to use.
498 const TargetInstrInfo &TII,
499 unsigned FoldIdx) {
500 assert(TII.isCopyInstr(MI) && "MI must be a COPY instruction");
501 if (MI.getNumOperands() != 2)
502 return nullptr;
503 assert(FoldIdx<2 && "FoldIdx refers no nonexistent operand");
504
505 const MachineOperand &FoldOp = MI.getOperand(FoldIdx);
506 const MachineOperand &LiveOp = MI.getOperand(1 - FoldIdx);
507
508 if (FoldOp.getSubReg() || LiveOp.getSubReg())
509 return nullptr;
510
511 Register FoldReg = FoldOp.getReg();
512 Register LiveReg = LiveOp.getReg();
513
514 assert(FoldReg.isVirtual() && "Cannot fold physregs");
515
516 const MachineRegisterInfo &MRI = MI.getMF()->getRegInfo();
517 const TargetRegisterClass *RC = MRI.getRegClass(FoldReg);
518
519 if (LiveOp.getReg().isPhysical())
520 return RC->contains(LiveOp.getReg()) ? RC : nullptr;
521
522 if (RC->hasSubClassEq(MRI.getRegClass(LiveReg)))
523 return RC;
524
525 // FIXME: Allow folding when register classes are memory compatible.
526 return nullptr;
527}
528
529MCInst TargetInstrInfo::getNop() const { llvm_unreachable("Not implemented"); }
530
531/// Try to remove the load by folding it to a register
532/// operand at the use. We fold the load instructions if load defines a virtual
533/// register, the virtual register is used once in the same BB, and the
534/// instructions in-between do not load or store, and have no side effects.
537 Register &FoldAsLoadDefReg,
539 MachineInstr *&CopyMI) const {
540 // Check whether we can move DefMI here.
541 DefMI = MRI->getVRegDef(FoldAsLoadDefReg);
542 assert(DefMI);
543 bool SawStore = false;
544 if (!DefMI->isSafeToMove(SawStore))
545 return nullptr;
546
547 // Collect information about virtual register operands of MI.
548 SmallVector<unsigned, 1> SrcOperandIds;
549 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
550 MachineOperand &MO = MI.getOperand(i);
551 if (!MO.isReg())
552 continue;
553 Register Reg = MO.getReg();
554 if (Reg != FoldAsLoadDefReg)
555 continue;
556 // Do not fold if we have a subreg use or a def.
557 if (MO.getSubReg() || MO.isDef())
558 return nullptr;
559 SrcOperandIds.push_back(i);
560 }
561 if (SrcOperandIds.empty())
562 return nullptr;
563
564 // Check whether we can fold the def into SrcOperandId.
565 if (MachineInstr *FoldMI =
566 foldMemoryOperand(MI, SrcOperandIds, *DefMI, CopyMI)) {
567 FoldAsLoadDefReg = 0;
568 return FoldMI;
569 }
570
571 return nullptr;
572}
573
574std::pair<unsigned, unsigned>
576 switch (MI.getOpcode()) {
577 case TargetOpcode::STACKMAP:
578 // StackMapLiveValues are foldable
579 return std::make_pair(0, StackMapOpers(&MI).getVarIdx());
580 case TargetOpcode::PATCHPOINT:
581 // For PatchPoint, the call args are not foldable (even if reported in the
582 // stackmap e.g. via anyregcc).
583 return std::make_pair(0, PatchPointOpers(&MI).getVarIdx());
584 case TargetOpcode::STATEPOINT:
585 // For statepoints, fold deopt and gc arguments, but not call arguments.
586 return std::make_pair(MI.getNumDefs(), StatepointOpers(&MI).getVarIdx());
587 default:
588 llvm_unreachable("unexpected stackmap opcode");
589 }
590}
591
593 ArrayRef<unsigned> Ops, int FrameIndex,
594 const TargetInstrInfo &TII) {
595 unsigned StartIdx = 0;
596 unsigned NumDefs = 0;
597 // getPatchpointUnfoldableRange throws guarantee if MI is not a patchpoint.
598 std::tie(NumDefs, StartIdx) = TII.getPatchpointUnfoldableRange(MI);
599
600 unsigned DefToFoldIdx = MI.getNumOperands();
601
602 // Return false if any operands requested for folding are not foldable (not
603 // part of the stackmap's live values).
604 for (unsigned Op : Ops) {
605 if (Op < NumDefs) {
606 assert(DefToFoldIdx == MI.getNumOperands() && "Folding multiple defs");
607 DefToFoldIdx = Op;
608 } else if (Op < StartIdx) {
609 return nullptr;
610 }
611 if (MI.getOperand(Op).isTied())
612 return nullptr;
613 }
614
615 MachineInstr *NewMI =
616 MF.CreateMachineInstr(TII.get(MI.getOpcode()), MI.getDebugLoc(), true);
617 MachineInstrBuilder MIB(MF, NewMI);
618
619 // No need to fold return, the meta data, and function arguments
620 for (unsigned i = 0; i < StartIdx; ++i)
621 if (i != DefToFoldIdx)
622 MIB.add(MI.getOperand(i));
623
624 for (unsigned i = StartIdx, e = MI.getNumOperands(); i < e; ++i) {
625 MachineOperand &MO = MI.getOperand(i);
626 unsigned TiedTo = e;
627 (void)MI.isRegTiedToDefOperand(i, &TiedTo);
628
629 if (is_contained(Ops, i)) {
630 assert(TiedTo == e && "Cannot fold tied operands");
631 unsigned SpillSize;
632 unsigned SpillOffset;
633 // Compute the spill slot size and offset.
634 const TargetRegisterClass *RC =
635 MF.getRegInfo().getRegClass(MO.getReg());
636 bool Valid =
637 TII.getStackSlotRange(RC, MO.getSubReg(), SpillSize, SpillOffset, MF);
638 if (!Valid)
639 report_fatal_error("cannot spill patchpoint subregister operand");
640 MIB.addImm(StackMaps::IndirectMemRefOp);
641 MIB.addImm(SpillSize);
642 MIB.addFrameIndex(FrameIndex);
643 MIB.addImm(SpillOffset);
644 } else {
645 MIB.add(MO);
646 if (TiedTo < e) {
647 assert(TiedTo < NumDefs && "Bad tied operand");
648 if (TiedTo > DefToFoldIdx)
649 --TiedTo;
650 NewMI->tieOperands(TiedTo, NewMI->getNumOperands() - 1);
651 }
652 }
653 }
654 return NewMI;
655}
656
657static void foldInlineAsmMemOperand(MachineInstr *MI, unsigned OpNo, int FI,
658 const TargetInstrInfo &TII) {
659 // If the machine operand is tied, untie it first.
660 if (MI->getOperand(OpNo).isTied()) {
661 unsigned TiedTo = MI->findTiedOperandIdx(OpNo);
662 MI->untieRegOperand(OpNo);
663 // Intentional recursion!
664 foldInlineAsmMemOperand(MI, TiedTo, FI, TII);
665 }
666
668 TII.getFrameIndexOperands(NewOps, FI);
669 assert(!NewOps.empty() && "getFrameIndexOperands didn't create any operands");
670 MI->removeOperand(OpNo);
671 MI->insert(MI->operands_begin() + OpNo, NewOps);
672
673 // Change the previous operand to a MemKind InlineAsm::Flag. The second param
674 // is the per-target number of operands that represent the memory operand
675 // excluding this one (MD). This includes MO.
677 F.setMemConstraint(InlineAsm::ConstraintCode::m);
678 MachineOperand &MD = MI->getOperand(OpNo - 1);
679 MD.setImm(F);
680}
681
682// Returns nullptr if not possible to fold.
684 ArrayRef<unsigned> Ops, int FI,
685 const TargetInstrInfo &TII) {
686 assert(MI.isInlineAsm() && "wrong opcode");
687 if (Ops.size() > 1)
688 return nullptr;
689 unsigned Op = Ops[0];
690 assert(Op && "should never be first operand");
691 assert(MI.getOperand(Op).isReg() && "shouldn't be folding non-reg operands");
692
693 if (!MI.mayFoldInlineAsmRegOp(Op))
694 return nullptr;
695
696 MachineInstr &NewMI = TII.duplicate(*MI.getParent(), MI.getIterator(), MI);
697
698 foldInlineAsmMemOperand(&NewMI, Op, FI, TII);
699
700 // Update mayload/maystore metadata, and memoperands.
701 const VirtRegInfo &RI =
702 AnalyzeVirtRegInBundle(MI, MI.getOperand(Op).getReg());
705 if (RI.Reads) {
706 ExtraMO.setImm(ExtraMO.getImm() | InlineAsm::Extra_MayLoad);
708 }
709 if (RI.Writes) {
710 ExtraMO.setImm(ExtraMO.getImm() | InlineAsm::Extra_MayStore);
712 }
713 MachineFunction *MF = NewMI.getMF();
714 const MachineFrameInfo &MFI = MF->getFrameInfo();
716 MachinePointerInfo::getFixedStack(*MF, FI), Flags, MFI.getObjectSize(FI),
717 MFI.getObjectAlign(FI));
718 NewMI.addMemOperand(*MF, MMO);
719
720 return &NewMI;
721}
722
724 ArrayRef<unsigned> Ops, int FI,
725 MachineInstr *&CopyMI,
726 LiveIntervals *LIS,
727 VirtRegMap *VRM) const {
728 auto Flags = MachineMemOperand::MONone;
729 for (unsigned OpIdx : Ops)
730 Flags |= MI.getOperand(OpIdx).isDef() ? MachineMemOperand::MOStore
732
733 MachineBasicBlock *MBB = MI.getParent();
734 assert(MBB && "foldMemoryOperand needs an inserted instruction");
735 MachineFunction &MF = *MBB->getParent();
736
737 // If we're not folding a load into a subreg, the size of the load is the
738 // size of the spill slot. But if we are, we need to figure out what the
739 // actual load size is.
740 int64_t MemSize = 0;
741 const MachineFrameInfo &MFI = MF.getFrameInfo();
742
743 if (Flags & MachineMemOperand::MOStore) {
744 MemSize = MFI.getObjectSize(FI);
745 } else {
746 for (unsigned OpIdx : Ops) {
747 int64_t OpSize = MFI.getObjectSize(FI);
748
749 if (auto SubReg = MI.getOperand(OpIdx).getSubReg()) {
750 unsigned SubRegSize = TRI.getSubRegIdxSize(SubReg);
751 if (SubRegSize > 0 && !(SubRegSize % 8))
752 OpSize = SubRegSize / 8;
753 }
754
755 MemSize = std::max(MemSize, OpSize);
756 }
757 }
758
759 assert(MemSize && "Did not expect a zero-sized stack slot");
760
761 MachineInstr *NewMI = nullptr;
762
763 if (MI.getOpcode() == TargetOpcode::STACKMAP ||
764 MI.getOpcode() == TargetOpcode::PATCHPOINT ||
765 MI.getOpcode() == TargetOpcode::STATEPOINT) {
766 // Fold stackmap/patchpoint.
767 NewMI = foldPatchpoint(MF, MI, Ops, FI, *this);
768 if (NewMI)
769 MBB->insert(MI, NewMI);
770 } else if (MI.isInlineAsm()) {
771 return foldInlineAsmMemOperand(MI, Ops, FI, *this);
772 } else {
773 // Ask the target to do the actual folding.
774 NewMI = foldMemoryOperandImpl(MF, MI, Ops, FI, CopyMI, LIS, VRM);
775 }
776
777 if (NewMI) {
778 NewMI->setMemRefs(MF, MI.memoperands());
779 // Add a memory operand, foldMemoryOperandImpl doesn't do that.
781 NewMI->mayStore()) &&
782 "Folded a def to a non-store!");
783 assert((!(Flags & MachineMemOperand::MOLoad) ||
784 NewMI->mayLoad()) &&
785 "Folded a use to a non-load!");
786 assert(MFI.getObjectOffset(FI) != -1);
787 MachineMemOperand *MMO =
789 Flags, MemSize, MFI.getObjectAlign(FI));
790 NewMI->addMemOperand(MF, MMO);
791
792 // The pass "x86 speculative load hardening" always attaches symbols to
793 // call instructions. We need copy it form old instruction.
794 NewMI->cloneInstrSymbols(MF, MI);
795
796 return NewMI;
797 }
798
799 // Straight COPY may fold as load/store.
800 if (!isCopyInstr(MI) || Ops.size() != 1)
801 return nullptr;
802
803 const TargetRegisterClass *RC = canFoldCopy(MI, *this, Ops[0]);
804 if (!RC)
805 return nullptr;
806
807 const MachineOperand &MO = MI.getOperand(1 - Ops[0]);
809 if (Flags == MachineMemOperand::MOStore) {
810 if (MO.isUndef()) {
811 // If this is an undef copy, we do not need to bother we inserting spill
812 // code.
813 BuildMI(*MBB, Pos, MI.getDebugLoc(), get(TargetOpcode::KILL)).add(MO);
814 } else {
815 storeRegToStackSlot(*MBB, Pos, MO.getReg(), MO.isKill(), FI, RC,
816 Register());
817 }
818 } else
819 loadRegFromStackSlot(*MBB, Pos, MO.getReg(), FI, RC, Register());
820
821 return &*--Pos;
822}
823
826 MachineInstr &LoadMI, MachineInstr *&CopyMI,
827 LiveIntervals *LIS, VirtRegMap *VRM) const {
828 assert(LoadMI.canFoldAsLoad() && "LoadMI isn't foldable!");
829#ifndef NDEBUG
830 for (unsigned OpIdx : Ops)
831 assert(MI.getOperand(OpIdx).isUse() && "Folding load into def!");
832#endif
833
834 MachineBasicBlock &MBB = *MI.getParent();
835 MachineFunction &MF = *MBB.getParent();
836
837 // Ask the target to do the actual folding.
838 MachineInstr *NewMI = nullptr;
839 int FrameIndex = 0;
840
841 if ((MI.getOpcode() == TargetOpcode::STACKMAP ||
842 MI.getOpcode() == TargetOpcode::PATCHPOINT ||
843 MI.getOpcode() == TargetOpcode::STATEPOINT) &&
844 isLoadFromStackSlot(LoadMI, FrameIndex)) {
845 // Fold stackmap/patchpoint.
846 NewMI = foldPatchpoint(MF, MI, Ops, FrameIndex, *this);
847 if (NewMI)
848 NewMI = &*MBB.insert(MI, NewMI);
849 } else if (MI.isInlineAsm() && isLoadFromStackSlot(LoadMI, FrameIndex)) {
850 return foldInlineAsmMemOperand(MI, Ops, FrameIndex, *this);
851 } else {
852 // Ask the target to do the actual folding.
853 NewMI = foldMemoryOperandImpl(MF, MI, Ops, LoadMI, CopyMI, LIS, VRM);
854 }
855
856 if (!NewMI)
857 return nullptr;
858
859 // Copy the memoperands from the load to the folded instruction.
860 if (MI.memoperands_empty()) {
861 NewMI->setMemRefs(MF, LoadMI.memoperands());
862 } else {
863 // Handle the rare case of folding multiple loads.
864 NewMI->setMemRefs(MF, MI.memoperands());
866 E = LoadMI.memoperands_end();
867 I != E; ++I) {
868 NewMI->addMemOperand(MF, *I);
869 }
870 }
871 return NewMI;
872}
873
874/// transferImplicitOperands - MI is a pseudo-instruction, and the lowered
875/// replacement instructions immediately precede it. Copy any implicit
876/// operands from MI to the replacement instruction.
878 const TargetRegisterInfo *TRI) {
880 --CopyMI;
881
882 Register DstReg = MI->getOperand(0).getReg();
883 for (const MachineOperand &MO : MI->implicit_operands()) {
884 CopyMI->addOperand(MO);
885
886 // Be conservative about preserving kills when subregister defs are
887 // involved. If there was implicit kill of a super-register overlapping the
888 // copy result, we would kill the subregisters previous copies defined.
889
890 if (MO.isKill() && TRI->regsOverlap(DstReg, MO.getReg()))
891 CopyMI->getOperand(CopyMI->getNumOperands() - 1).setIsKill(false);
892 }
893}
894
896 if (MI->allDefsAreDead()) {
897 MI->setDesc(get(TargetOpcode::KILL));
898 return;
899 }
900
901 MachineOperand &DstMO = MI->getOperand(0);
902 MachineOperand &SrcMO = MI->getOperand(1);
903
904 bool IdentityCopy = (SrcMO.getReg() == DstMO.getReg());
905 if (IdentityCopy || SrcMO.isUndef()) {
906 // No need to insert an identity copy instruction, but replace with a KILL
907 // if liveness is changed.
908 if (SrcMO.isUndef() || MI->getNumOperands() > 2) {
909 // We must make sure the super-register gets killed. Replace the
910 // instruction with KILL.
911 MI->setDesc(get(TargetOpcode::KILL));
912 return;
913 }
914 // Vanilla identity copy.
915 MI->eraseFromParent();
916 return;
917 }
918
919 copyPhysReg(*MI->getParent(), MI, MI->getDebugLoc(), DstMO.getReg(),
920 SrcMO.getReg(), SrcMO.isKill(),
921 DstMO.getReg().isPhysical() ? DstMO.isRenamable() : false,
922 SrcMO.getReg().isPhysical() ? SrcMO.isRenamable() : false);
923
924 if (MI->getNumOperands() > 2)
926 MI->eraseFromParent();
927}
928
930 const MachineInstr &Inst, const MachineBasicBlock *MBB) const {
931 const MachineOperand &Op1 = Inst.getOperand(1);
932 const MachineOperand &Op2 = Inst.getOperand(2);
933 const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
934
935 // We need virtual register definitions for the operands that we will
936 // reassociate.
937 MachineInstr *MI1 = nullptr;
938 MachineInstr *MI2 = nullptr;
939 if (Op1.isReg() && Op1.getReg().isVirtual())
940 MI1 = MRI.getUniqueVRegDef(Op1.getReg());
941 if (Op2.isReg() && Op2.getReg().isVirtual())
942 MI2 = MRI.getUniqueVRegDef(Op2.getReg());
943
944 // And at least one operand must be defined in MBB.
945 return MI1 && MI2 && (MI1->getParent() == MBB || MI2->getParent() == MBB);
946}
947
949 unsigned Opcode2) const {
950 return Opcode1 == Opcode2 || getInverseOpcode(Opcode1) == Opcode2;
951}
952
954 bool &Commuted) const {
955 const MachineBasicBlock *MBB = Inst.getParent();
956 const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
957 MachineInstr *MI1 = MRI.getUniqueVRegDef(Inst.getOperand(1).getReg());
958 MachineInstr *MI2 = MRI.getUniqueVRegDef(Inst.getOperand(2).getReg());
959 unsigned Opcode = Inst.getOpcode();
960
961 // If only one operand has the same or inverse opcode and it's the second
962 // source operand, the operands must be commuted.
963 Commuted = !areOpcodesEqualOrInverse(Opcode, MI1->getOpcode()) &&
964 areOpcodesEqualOrInverse(Opcode, MI2->getOpcode());
965 if (Commuted)
966 std::swap(MI1, MI2);
967
968 // 1. The previous instruction must be the same type as Inst.
969 // 2. The previous instruction must also be associative/commutative or be the
970 // inverse of such an operation (this can be different even for
971 // instructions with the same opcode if traits like fast-math-flags are
972 // included).
973 // 3. The previous instruction must have virtual register definitions for its
974 // operands in the same basic block as Inst.
975 // 4. The previous instruction's result must only be used by Inst.
976 return areOpcodesEqualOrInverse(Opcode, MI1->getOpcode()) &&
978 isAssociativeAndCommutative(*MI1, /* Invert */ true)) &&
980 MRI.hasOneNonDBGUse(MI1->getOperand(0).getReg());
981}
982
983// 1. The operation must be associative and commutative or be the inverse of
984// such an operation.
985// 2. The instruction must have virtual register definitions for its
986// operands in the same basic block.
987// 3. The instruction must have a reassociable sibling.
989 bool &Commuted) const {
990 return (isAssociativeAndCommutative(Inst) ||
991 isAssociativeAndCommutative(Inst, /* Invert */ true)) &&
992 hasReassociableOperands(Inst, Inst.getParent()) &&
993 hasReassociableSibling(Inst, Commuted);
994}
995
996// Utility routine that checks if \param MO is defined by an
997// \param CombineOpc instruction in the basic block \param MBB.
998// If \param CombineOpc is not provided, the OpCode check will
999// be skipped.
1001 unsigned CombineOpc = 0) {
1002 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1003 MachineInstr *MI = nullptr;
1004
1005 if (MO.isReg() && MO.getReg().isVirtual())
1006 MI = MRI.getUniqueVRegDef(MO.getReg());
1007 // And it needs to be in the trace (otherwise, it won't have a depth).
1008 if (!MI || MI->getParent() != &MBB ||
1009 (MI->getOpcode() != CombineOpc && CombineOpc != 0))
1010 return false;
1011 // Must only used by the user we combine with.
1012 if (!MRI.hasOneNonDBGUse(MO.getReg()))
1013 return false;
1014
1015 return true;
1016}
1017
1018// A chain of accumulation instructions will be selected IFF:
1019// 1. All the accumulation instructions in the chain have the same opcode,
1020// besides the first that has a slightly different opcode because it does
1021// not accumulate into a register.
1022// 2. All the instructions in the chain are combinable (have a single use
1023// which itself is part of the chain).
1024// 3. Meets the required minimum length.
1026 MachineInstr *CurrentInstr, SmallVectorImpl<Register> &Chain) const {
1027 // Walk up the chain of accumulation instructions and collect them in the
1028 // vector.
1029 MachineBasicBlock &MBB = *CurrentInstr->getParent();
1030 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1031 unsigned AccumulatorOpcode = CurrentInstr->getOpcode();
1032 std::optional<unsigned> ChainStartOpCode =
1033 getAccumulationStartOpcode(AccumulatorOpcode);
1034
1035 if (!ChainStartOpCode.has_value())
1036 return;
1037
1038 // Push the first accumulator result to the start of the chain.
1039 Chain.push_back(CurrentInstr->getOperand(0).getReg());
1040
1041 // Collect the accumulator input register from all instructions in the chain.
1042 while (CurrentInstr &&
1043 canCombine(MBB, CurrentInstr->getOperand(1), AccumulatorOpcode)) {
1044 Chain.push_back(CurrentInstr->getOperand(1).getReg());
1045 CurrentInstr = MRI.getUniqueVRegDef(CurrentInstr->getOperand(1).getReg());
1046 }
1047
1048 // Add the instruction at the top of the chain.
1049 if (CurrentInstr->getOpcode() == AccumulatorOpcode &&
1050 canCombine(MBB, CurrentInstr->getOperand(1)))
1051 Chain.push_back(CurrentInstr->getOperand(1).getReg());
1052}
1053
1054/// Find chains of accumulations that can be rewritten as a tree for increased
1055/// ILP.
1057 MachineInstr &Root, SmallVectorImpl<unsigned> &Patterns) const {
1059 return false;
1060
1061 unsigned Opc = Root.getOpcode();
1063 return false;
1064
1065 // Verify that this is the end of the chain.
1066 MachineBasicBlock &MBB = *Root.getParent();
1067 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1068 if (!MRI.hasOneNonDBGUser(Root.getOperand(0).getReg()))
1069 return false;
1070
1071 auto User = MRI.use_instr_nodbg_begin(Root.getOperand(0).getReg());
1072 if (User->getOpcode() == Opc)
1073 return false;
1074
1075 // Walk up the use chain and collect the reduction chain.
1077 getAccumulatorChain(&Root, Chain);
1078
1079 // Reject chains which are too short to be worth modifying.
1080 if (Chain.size() < MinAccumulatorDepth)
1081 return false;
1082
1083 // Check if the MBB this instruction is a part of contains any other chains.
1084 // If so, don't apply it.
1085 SmallSet<Register, 32> ReductionChain(llvm::from_range, Chain);
1086 for (const auto &I : MBB) {
1087 if (I.getOpcode() == Opc &&
1088 !ReductionChain.contains(I.getOperand(0).getReg()))
1089 return false;
1090 }
1091
1093 return true;
1094}
1095
1096// Reduce branches of the accumulator tree by adding them together.
1098 SmallVectorImpl<Register> &RegistersToReduce,
1101 DenseMap<Register, unsigned> &InstrIdxForVirtReg,
1102 Register ResultReg) const {
1105
1106 // Get the opcode for the reduction instruction we will need to build.
1107 // If for some reason it is not defined, early exit and don't apply this.
1108 unsigned ReduceOpCode = getReduceOpcodeForAccumulator(Root.getOpcode());
1109
1110 for (unsigned int i = 1; i <= (RegistersToReduce.size() / 2); i += 2) {
1111 auto RHS = RegistersToReduce[i - 1];
1112 auto LHS = RegistersToReduce[i];
1113 Register Dest;
1114 // If we are reducing 2 registers, reuse the original result register.
1115 if (RegistersToReduce.size() == 2)
1116 Dest = ResultReg;
1117 // Otherwise, create a new virtual register to hold the partial sum.
1118 else {
1119 auto NewVR = MRI.createVirtualRegister(
1120 MRI.getRegClass(Root.getOperand(0).getReg()));
1121 Dest = NewVR;
1122 NewRegs.push_back(Dest);
1123 InstrIdxForVirtReg.insert(std::make_pair(Dest, InsInstrs.size()));
1124 }
1125
1126 // Create the new reduction instruction.
1128 BuildMI(MF, MIMetadata(Root), TII->get(ReduceOpCode), Dest)
1129 .addReg(RHS)
1130 .addReg(LHS);
1131 // Copy any flags needed from the original instruction.
1132 MIB->setFlags(Root.getFlags());
1133 InsInstrs.push_back(MIB);
1134 }
1135
1136 // If the number of registers to reduce is odd, add the remaining register to
1137 // the vector of registers to reduce.
1138 if (RegistersToReduce.size() % 2 != 0)
1139 NewRegs.push_back(RegistersToReduce[RegistersToReduce.size() - 1]);
1140
1141 RegistersToReduce = std::move(NewRegs);
1142}
1143
1145 return MO.isReg() && MO.getReg().isVirtual() && !MO.getSubReg() &&
1146 !MO.isUndef();
1147}
1148
1150 const MachineInstr &Link,
1151 const MachineInstr &Prev) {
1152 if (Info.isFused())
1153 return Info.AccOpIdx;
1154 // An unfused link accumulates the source defined by the previous link.
1155 return Link.getOperand(1).getReg() == Prev.getOperand(0).getReg() ? 1 : 2;
1156}
1157
1158// Collect the FP accumulation chain ending at Root, leaf first and Root last,
1159// or return an empty chain if Root does not end a chain that can be split.
1161 MachineInstr &Root) {
1162 MachineBasicBlock &MBB = *Root.getParent();
1163 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1164
1165 // The split reorders the additions and rounds one product separately, which
1166 // may change the result by a rounding and the sign of a zero.
1167 auto GetInfo = [&](const MachineInstr &MI)
1168 -> std::optional<TargetInstrInfo::FMAChainLinkInfo> {
1169 if (!MI.getFlag(MachineInstr::MIFlag::FmReassoc) ||
1170 !MI.getFlag(MachineInstr::MIFlag::FmNsz) || MI.mayRaiseFPException())
1171 return std::nullopt;
1172 return TII.getFMAChainLinkInfo(MI);
1173 };
1174
1175 std::optional<TargetInstrInfo::FMAChainLinkInfo> RootInfo = GetInfo(Root);
1176 if (!RootInfo || !isPlainVirtRegOperand(Root.getOperand(0)) ||
1177 Root.getOperand(0).isDead())
1178 return {};
1179 Register RootReg = Root.getOperand(0).getReg();
1180 if (MRI.use_nodbg_empty(RootReg))
1181 return {};
1182
1183 // All links share the add joining the halves, which takes their results.
1184 auto GetLinkInfo = [&](const MachineInstr &MI)
1185 -> std::optional<TargetInstrInfo::FMAChainLinkInfo> {
1186 std::optional<TargetInstrInfo::FMAChainLinkInfo> Info = GetInfo(MI);
1187 if (Info && Info->AddOpc != RootInfo->AddOpc)
1188 return std::nullopt;
1189 return Info;
1190 };
1191
1192 auto GetLinkDef = [&](const MachineOperand &MO) -> MachineInstr * {
1193 if (!isPlainVirtRegOperand(MO) || !MRI.hasOneNonDBGUse(MO.getReg()))
1194 return nullptr;
1195 MachineInstr *Def = MRI.getUniqueVRegDef(MO.getReg());
1196 if (!Def || Def->getParent() != &MBB || !GetLinkInfo(*Def) ||
1197 !isPlainVirtRegOperand(Def->getOperand(0)) ||
1198 Def->getOperand(0).getReg() != MO.getReg())
1199 return nullptr;
1200 return Def;
1201 };
1202
1203 // Both sources of an unfused link must be renamable, as its increment
1204 // becomes the accumulator of the next link when the link is dropped.
1205 auto GetPrevLink = [&](const MachineInstr &MI) -> MachineInstr * {
1206 std::optional<TargetInstrInfo::FMAChainLinkInfo> Info = GetLinkInfo(MI);
1207 if (!Info)
1208 return nullptr;
1209 if (Info->isFused())
1210 return GetLinkDef(MI.getOperand(Info->AccOpIdx));
1211 if (!isPlainVirtRegOperand(MI.getOperand(1)) ||
1212 !isPlainVirtRegOperand(MI.getOperand(2)))
1213 return nullptr;
1214 if (MachineInstr *Def = GetLinkDef(MI.getOperand(1)))
1215 return Def;
1216 return GetLinkDef(MI.getOperand(2));
1217 };
1218
1219 // Split only at the chain end, as shorter prefixes are not worth splitting.
1220 if (MachineOperand *Use = MRI.getOneNonDBGUse(RootReg)) {
1221 MachineInstr &User = *Use->getParent();
1222 if (User.getParent() == &MBB && GetPrevLink(User) == &Root)
1223 return {};
1224 }
1225
1226 SmallVector<MachineInstr *> Chain = {&Root};
1227 for (MachineInstr *Link = GetPrevLink(Root); Link; Link = GetPrevLink(*Link))
1228 Chain.push_back(Link);
1229 std::reverse(Chain.begin(), Chain.end());
1230 // Each half needs at least two links to reduce the depth.
1231 if (Chain.size() < 4)
1232 return {};
1233
1234 // The upper half moves to Root, so moved links cannot cross conflicting
1235 // memory or physical register accesses.
1236 unsigned SplitIdx = Chain.size() / 2;
1237 const TargetRegisterInfo *TRI = &TII.getRegisterInfo();
1238 SmallSet<Register, 2> ImplicitPhysRegs;
1239 bool MovesLoad = false;
1240 auto NextMoved = Chain.begin() + SplitIdx;
1241 for (MachineInstr &MI :
1242 llvm::make_range(Chain[SplitIdx]->getIterator(), MBB.instr_end())) {
1243 if (&MI == *NextMoved) {
1244 ++NextMoved;
1245 if (MI.isBundled() || MI.mayStore() || MI.isNotDuplicable() ||
1246 TII.isGlobalMemoryObject(&MI))
1247 return {};
1248 for (const MachineOperand &MO : llvm::drop_begin(MI.operands())) {
1249 if (MO.isRegMask())
1250 return {};
1251 if (!MO.isReg())
1252 continue;
1253 if (MO.isDef())
1254 return {};
1255 if (!MO.getReg().isPhysical())
1256 continue;
1257 if (!MO.isImplicit())
1258 return {};
1259 if (!MO.isUndef())
1260 ImplicitPhysRegs.insert(MO.getReg());
1261 }
1262 if (!MovesLoad && MI.mayLoad() && !MI.isDereferenceableInvariantLoad())
1263 MovesLoad = true;
1264 if (NextMoved == Chain.end())
1265 break;
1266 continue;
1267 }
1268 if (&MI == &Root)
1269 return {};
1270 if (MI.isDebugInstr())
1271 continue;
1272 if (MovesLoad && (MI.mayStore() || MI.isLifetimeMarker() ||
1273 TII.isGlobalMemoryObject(&MI)))
1274 return {};
1275 if (llvm::any_of(ImplicitPhysRegs, [&](Register Reg) {
1276 return MI.modifiesRegister(Reg, TRI);
1277 }))
1278 return {};
1279 }
1280 if (NextMoved != Chain.end())
1281 return {};
1282 return Chain;
1283}
1284
1287 Register Upper) {
1288 return BuildMI(*Root.getMF(), MIMetadata(Root),
1289 TII.get(TII.getFMAChainLinkInfo(Root)->AddOpc),
1290 Root.getOperand(0).getReg())
1291 .addReg(Lower)
1292 .addReg(Upper);
1293}
1294
1295// The split costs an add, so require accumulator forwarding between fused
1296// links and, in a loop, a shorter recurrence through the PHI.
1299 MachineInstr &Root = *Chain.back();
1300 const MachineInstr &Leaf = *Chain.front();
1301 MachineFunction &MF = *Root.getMF();
1302 TargetSchedModel SchedModel;
1303 SchedModel.init(&MF.getSubtarget());
1304 if (!SchedModel.hasInstrSchedModelOrItineraries())
1305 return false;
1306
1307 // Sum upper-half accumulator latencies and require forwarding between fused
1308 // links.
1309 unsigned SplitIdx = Chain.size() / 2;
1310 unsigned UpperAccLat = 0;
1311 bool PrevFused = TII.getFMAChainLinkInfo(Leaf)->isFused();
1312 for (auto [I, Prev, Link] :
1313 llvm::enumerate(Chain.drop_back(), Chain.drop_front())) {
1314 TargetInstrInfo::FMAChainLinkInfo Info = *TII.getFMAChainLinkInfo(*Link);
1315 unsigned Lat = SchedModel.computeOperandLatency(
1316 Prev, 0, Link, getFMAChainAccOpIdx(Info, *Link, *Prev));
1317 if (Info.isFused() && PrevFused &&
1318 Lat >= SchedModel.computeInstrLatency(Prev))
1319 return false;
1320 if (I >= SplitIdx - 1)
1321 UpperAccLat += Lat;
1322 PrevFused = Info.isFused();
1323 }
1324
1325 // Find the leaf operand reading Root through a PHI, which closes a loop
1326 // recurrence.
1327 int PhiOpIdx = -1;
1328 for (const MachineInstr &MI :
1330 if (!MI.isPHI())
1331 continue;
1332 PhiOpIdx = Leaf.findRegisterUseOperandIdx(MI.getOperand(0).getReg(),
1333 /*TRI=*/nullptr);
1334 if (PhiOpIdx >= 0)
1335 break;
1336 }
1337 if (PhiOpIdx < 0)
1338 return true;
1339
1340 // The split replaces the upper-half chain and old backedge with the add,
1341 // whose scheduling class may depend on the instruction.
1342 Register LowerReg = Chain[SplitIdx - 1]->getOperand(0).getReg();
1343 MachineInstr *Add = buildFMAChainAdd(TII, Root, LowerReg,
1344 Chain[SplitIdx]->getOperand(0).getReg());
1345 unsigned AddLat =
1346 SchedModel.computeOperandLatency(Chain[SplitIdx - 1], 0, Add, 1) +
1347 SchedModel.computeOperandLatency(Add, 0, &Leaf, PhiOpIdx);
1348 MF.deleteMachineInstr(Add);
1349 unsigned BackedgeLat =
1350 SchedModel.computeOperandLatency(&Root, 0, &Leaf, PhiOpIdx);
1351 return AddLat < UpperAccLat + BackedgeLat;
1352}
1353
1354// Add MachineCombinerPattern::FMA_CHAIN if Root ends an FP accumulation chain
1355// worth splitting into two shorter chains.
1357 SmallVectorImpl<unsigned> &Patterns,
1358 bool DoRegPressureReduce) {
1359 // The split adds an instruction and a second live accumulator.
1360 if (DoRegPressureReduce || !Root.getFlag(MachineInstr::MIFlag::FmReassoc) ||
1362 return false;
1363 const MachineFunction &MF = *Root.getMF();
1365 MF.getFunction().hasOptSize())
1366 return false;
1368 if (Chain.empty() || !isFMASplitProfitable(TII, Chain))
1369 return false;
1371 return true;
1372}
1373
1374// Split the chain ending at Root into two chains joined by an add, e.g.
1375// X -> FMA0 -> FMA1 -> FMA2 -> FMA3 -> FMA4 -> FMA5
1376// becomes
1377// X -> FMA0 -> FMA1 -> FMA2 --+
1378// MUL3 -> FMA4 -> FMA5 --+-> ADD
1379static void
1383 DenseMap<Register, unsigned> &InstrIdxForVirtReg) {
1384 MachineFunction *MF = Root.getMF();
1387 assert(!Chain.empty() && "expected an FMA chain");
1388 unsigned SplitIdx = Chain.size() / 2;
1389
1390 uint32_t Flags = ~0u;
1391 for (MachineInstr *Link : llvm::drop_begin(Chain, SplitIdx))
1392 Flags &= Link->getFlags();
1393
1394 DelInstrs.append(Chain.begin() + SplitIdx, Chain.end());
1395 const TargetRegisterClass *RC =
1396 Root.getRegClassConstraint(0, &TII, &TII.getRegisterInfo());
1397
1398 // Start the upper chain at an unfused link, if any, so that its increment
1399 // becomes the initial accumulator and no fused link becomes a multiply.
1400 MachineInstr *Unfused = nullptr;
1401 Register UpperAcc;
1402 for (unsigned I : llvm::seq<unsigned>(SplitIdx, Chain.size())) {
1404 *TII.getFMAChainLinkInfo(*Chain[I]);
1405 if (Info.isFused())
1406 continue;
1407 int AccIdx = getFMAChainAccOpIdx(Info, *Chain[I], *Chain[I - 1]);
1408 UpperAcc = Chain[I]->getOperand(AccIdx == 1 ? 2 : 1).getReg();
1409 Unfused = Chain[I];
1410 break;
1411 }
1412
1413 for (unsigned I : llvm::seq<unsigned>(SplitIdx, Chain.size())) {
1414 MachineInstr *Link = Chain[I];
1415 if (Link == Unfused)
1416 continue;
1417 TargetInstrInfo::FMAChainLinkInfo Info = *TII.getFMAChainLinkInfo(*Link);
1418 int AccIdx = getFMAChainAccOpIdx(Info, *Link, *Chain[I - 1]);
1419 Register NewDst = MRI.createVirtualRegister(RC);
1420 MachineInstr *NewInstr = MF->CloneMachineInstr(Link);
1421 // The add joining the halves may read registers a moved link killed.
1422 NewInstr->clearKillInfo();
1423 if (!UpperAcc) {
1424 NewInstr->untieRegOperand(0);
1425 NewInstr->removeOperand(AccIdx);
1426 NewInstr->setDesc(TII.get(Info.MulOpc));
1427 } else {
1428 NewInstr->getOperand(AccIdx).setReg(UpperAcc);
1429 }
1430 NewInstr->getOperand(0).setReg(NewDst);
1431 NewInstr->setFlags(Flags);
1432 InstrIdxForVirtReg.try_emplace(NewDst, InsInstrs.size());
1433 InsInstrs.push_back(NewInstr);
1434 UpperAcc = NewDst;
1435 }
1436
1438 TII, Root, Chain[SplitIdx - 1]->getOperand(0).getReg(), UpperAcc);
1439 Add->setFlags(Flags);
1440 if (unsigned OldRootNum = Root.peekDebugInstrNum())
1441 Add->setDebugInstrNum(OldRootNum);
1442 InsInstrs.push_back(Add);
1443}
1444
1445// The concept of the reassociation pass is that these operations can benefit
1446// from this kind of transformation:
1447//
1448// A = ? op ?
1449// B = A op X (Prev)
1450// C = B op Y (Root)
1451// -->
1452// A = ? op ?
1453// B = X op Y
1454// C = A op B
1455//
1456// breaking the dependency between A and B, allowing them to be executed in
1457// parallel (or back-to-back in a pipeline) instead of depending on each other.
1458
1459// FIXME: This has the potential to be expensive (compile time) while not
1460// improving the code at all. Some ways to limit the overhead:
1461// 1. Track successful transforms; bail out if hit rate gets too low.
1462// 2. Only enable at -O3 or some other non-default optimization level.
1463// 3. Pre-screen pattern candidates here: if an operand of the previous
1464// instruction is known to not increase the critical path, then don't match
1465// that pattern.
1467 MachineInstr &Root, SmallVectorImpl<unsigned> &Patterns,
1468 bool DoRegPressureReduce) const {
1469 // The split of a whole chain goes first. The reassociation of a single pair
1470 // stays as a fallback if the machine combiner rejects the split.
1471 bool FoundFMAChain =
1472 getFMAChainPatterns(*this, Root, Patterns, DoRegPressureReduce);
1473 bool Commute;
1474 if (isReassociationCandidate(Root, Commute)) {
1475 // We found a sequence of instructions that may be suitable for a
1476 // reassociation of operands to increase ILP. Specify each commutation
1477 // possibility for the Prev instruction in the sequence and let the
1478 // machine combiner decide if changing the operands is worthwhile.
1479 if (Commute) {
1482 } else {
1485 }
1486 return true;
1487 }
1488 if (getAccumulatorReassociationPatterns(Root, Patterns))
1489 return true;
1490
1491 return FoundFMAChain;
1492}
1493
1494/// Return true when a code sequence can improve loop throughput.
1496 return false;
1497}
1498
1509
1510std::pair<unsigned, unsigned>
1512 const MachineInstr &Root,
1513 const MachineInstr &Prev) const {
1514 bool AssocCommutRoot = isAssociativeAndCommutative(Root);
1515 bool AssocCommutPrev = isAssociativeAndCommutative(Prev);
1516
1517 // Early exit if both opcodes are associative and commutative. It's a trivial
1518 // reassociation when we only change operands order. In this case opcodes are
1519 // not required to have inverse versions.
1520 if (AssocCommutRoot && AssocCommutPrev) {
1521 assert(Root.getOpcode() == Prev.getOpcode() && "Expected to be equal");
1522 return std::make_pair(Root.getOpcode(), Root.getOpcode());
1523 }
1524
1525 // At least one instruction is not associative or commutative.
1526 // Since we have matched one of the reassociation patterns, we expect that the
1527 // instructions' opcodes are equal or one of them is the inversion of the
1528 // other.
1530 "Incorrectly matched pattern");
1531 unsigned AssocCommutOpcode = Root.getOpcode();
1532 unsigned InverseOpcode = *getInverseOpcode(Root.getOpcode());
1533 if (!AssocCommutRoot)
1534 std::swap(AssocCommutOpcode, InverseOpcode);
1535
1536 // The transformation rule (`+` is any associative and commutative binary
1537 // operation, `-` is the inverse):
1538 // REASSOC_AX_BY:
1539 // (A + X) + Y => A + (X + Y)
1540 // (A + X) - Y => A + (X - Y)
1541 // (A - X) + Y => A - (X - Y)
1542 // (A - X) - Y => A - (X + Y)
1543 // REASSOC_XA_BY:
1544 // (X + A) + Y => (X + Y) + A
1545 // (X + A) - Y => (X - Y) + A
1546 // (X - A) + Y => (X + Y) - A
1547 // (X - A) - Y => (X - Y) - A
1548 // REASSOC_AX_YB:
1549 // Y + (A + X) => (Y + X) + A
1550 // Y - (A + X) => (Y - X) - A
1551 // Y + (A - X) => (Y - X) + A
1552 // Y - (A - X) => (Y + X) - A
1553 // REASSOC_XA_YB:
1554 // Y + (X + A) => (Y + X) + A
1555 // Y - (X + A) => (Y - X) - A
1556 // Y + (X - A) => (Y + X) - A
1557 // Y - (X - A) => (Y - X) + A
1558 switch (Pattern) {
1559 default:
1560 llvm_unreachable("Unexpected pattern");
1562 if (!AssocCommutRoot && AssocCommutPrev)
1563 return {AssocCommutOpcode, InverseOpcode};
1564 if (AssocCommutRoot && !AssocCommutPrev)
1565 return {InverseOpcode, InverseOpcode};
1566 if (!AssocCommutRoot && !AssocCommutPrev)
1567 return {InverseOpcode, AssocCommutOpcode};
1568 break;
1570 if (!AssocCommutRoot && AssocCommutPrev)
1571 return {AssocCommutOpcode, InverseOpcode};
1572 if (AssocCommutRoot && !AssocCommutPrev)
1573 return {InverseOpcode, AssocCommutOpcode};
1574 if (!AssocCommutRoot && !AssocCommutPrev)
1575 return {InverseOpcode, InverseOpcode};
1576 break;
1578 if (!AssocCommutRoot && AssocCommutPrev)
1579 return {InverseOpcode, InverseOpcode};
1580 if (AssocCommutRoot && !AssocCommutPrev)
1581 return {AssocCommutOpcode, InverseOpcode};
1582 if (!AssocCommutRoot && !AssocCommutPrev)
1583 return {InverseOpcode, AssocCommutOpcode};
1584 break;
1586 if (!AssocCommutRoot && AssocCommutPrev)
1587 return {InverseOpcode, InverseOpcode};
1588 if (AssocCommutRoot && !AssocCommutPrev)
1589 return {InverseOpcode, AssocCommutOpcode};
1590 if (!AssocCommutRoot && !AssocCommutPrev)
1591 return {AssocCommutOpcode, InverseOpcode};
1592 break;
1593 }
1594 llvm_unreachable("Unhandled combination");
1595}
1596
1597// Return a pair of boolean flags showing if the new root and new prev operands
1598// must be swapped. See visual example of the rule in
1599// TargetInstrInfo::getReassociationOpcodes.
1600static std::pair<bool, bool> mustSwapOperands(unsigned Pattern) {
1601 switch (Pattern) {
1602 default:
1603 llvm_unreachable("Unexpected pattern");
1605 return {false, false};
1607 return {true, false};
1609 return {true, true};
1611 return {true, true};
1612 }
1613}
1614
1616 const MachineInstr &Root, unsigned Pattern,
1617 std::array<unsigned, 5> &OperandIndices) const {
1618 switch (Pattern) {
1620 OperandIndices = {1, 1, 1, 2, 2};
1621 break;
1623 OperandIndices = {2, 1, 2, 2, 1};
1624 break;
1626 OperandIndices = {1, 2, 1, 1, 2};
1627 break;
1629 OperandIndices = {2, 2, 2, 1, 1};
1630 break;
1631 default:
1632 llvm_unreachable("unexpected MachineCombinerPattern");
1633 }
1634}
1635
1636/// Attempt the reassociation transformation to reduce critical path length.
1637/// See the above comments before getMachineCombinerPatterns().
1639 MachineInstr &Root, MachineInstr &Prev, unsigned Pattern,
1643 DenseMap<Register, unsigned> &InstrIdxForVirtReg) const {
1644 MachineFunction *MF = Root.getMF();
1647 const TargetRegisterClass *RC = Root.getRegClassConstraint(0, TII, &TRI);
1648
1653 MachineOperand &OpC = Root.getOperand(0);
1654
1655 Register RegA = OpA.getReg();
1656 unsigned SubRegA = OpA.getSubReg();
1657 Register RegB = OpB.getReg();
1658 Register RegX = OpX.getReg();
1659 unsigned SubRegX = OpX.getSubReg();
1660 Register RegY = OpY.getReg();
1661 unsigned SubRegY = OpY.getSubReg();
1662 Register RegC = OpC.getReg();
1663
1664 if (RegA.isVirtual())
1665 MRI.constrainRegClass(RegA, RC);
1666 if (RegB.isVirtual())
1667 MRI.constrainRegClass(RegB, RC);
1668 if (RegX.isVirtual())
1669 MRI.constrainRegClass(RegX, RC);
1670 if (RegY.isVirtual())
1671 MRI.constrainRegClass(RegY, RC);
1672 if (RegC.isVirtual())
1673 MRI.constrainRegClass(RegC, RC);
1674
1675 // Create a new virtual register for the result of (X op Y) instead of
1676 // recycling RegB because the MachineCombiner's computation of the critical
1677 // path requires a new register definition rather than an existing one.
1678 Register NewVR = MRI.createVirtualRegister(RC);
1679 unsigned SubRegNewVR = 0;
1680 InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
1681
1682 auto [NewRootOpc, NewPrevOpc] = getReassociationOpcodes(Pattern, Root, Prev);
1683
1684 auto [SwapRootOperands, SwapPrevOperands] = mustSwapOperands(Pattern);
1685
1686 if (SwapPrevOperands) {
1687 std::swap(RegX, RegY);
1688 std::swap(SubRegX, SubRegY);
1689 }
1690
1691 unsigned PrevFirstOpIdx, PrevSecondOpIdx;
1692 unsigned RootFirstOpIdx, RootSecondOpIdx;
1693 switch (Pattern) {
1695 PrevFirstOpIdx = OperandIndices[1];
1696 PrevSecondOpIdx = OperandIndices[3];
1697 RootFirstOpIdx = OperandIndices[2];
1698 RootSecondOpIdx = OperandIndices[4];
1699 break;
1701 PrevFirstOpIdx = OperandIndices[1];
1702 PrevSecondOpIdx = OperandIndices[3];
1703 RootFirstOpIdx = OperandIndices[4];
1704 RootSecondOpIdx = OperandIndices[2];
1705 break;
1707 PrevFirstOpIdx = OperandIndices[3];
1708 PrevSecondOpIdx = OperandIndices[1];
1709 RootFirstOpIdx = OperandIndices[2];
1710 RootSecondOpIdx = OperandIndices[4];
1711 break;
1713 PrevFirstOpIdx = OperandIndices[3];
1714 PrevSecondOpIdx = OperandIndices[1];
1715 RootFirstOpIdx = OperandIndices[4];
1716 RootSecondOpIdx = OperandIndices[2];
1717 break;
1718 default:
1719 llvm_unreachable("unexpected MachineCombinerPattern");
1720 }
1721
1722 // Basically BuildMI but doesn't add implicit operands by default.
1723 auto buildMINoImplicit = [](MachineFunction &MF, const MIMetadata &MIMD,
1724 const MCInstrDesc &MCID, Register DestReg) {
1725 return MachineInstrBuilder(
1726 MF, MF.CreateMachineInstr(MCID, MIMD.getDL(), /*NoImpl=*/true))
1727 .copyMIMetadata(MIMD)
1728 .addReg(DestReg, RegState::Define);
1729 };
1730
1731 // Create new instructions for insertion.
1732 MachineInstrBuilder MIB1 =
1733 buildMINoImplicit(*MF, MIMetadata(Prev), TII->get(NewPrevOpc), NewVR);
1734 for (const auto &MO : Prev.explicit_operands()) {
1735 unsigned Idx = MO.getOperandNo();
1736 // Skip the result operand we'd already added.
1737 if (Idx == 0)
1738 continue;
1739 if (Idx == PrevFirstOpIdx)
1740 MIB1.addReg(RegX, {}, SubRegX);
1741 else if (Idx == PrevSecondOpIdx)
1742 MIB1.addReg(RegY, {}, SubRegY);
1743 else
1744 MIB1.add(MO);
1745 }
1746 MIB1.copyImplicitOps(Prev);
1747
1748 if (SwapRootOperands) {
1749 std::swap(RegA, NewVR);
1750 std::swap(SubRegA, SubRegNewVR);
1751 }
1752
1753 MachineInstrBuilder MIB2 =
1754 buildMINoImplicit(*MF, MIMetadata(Root), TII->get(NewRootOpc), RegC);
1755 for (const auto &MO : Root.explicit_operands()) {
1756 unsigned Idx = MO.getOperandNo();
1757 // Skip the result operand.
1758 if (Idx == 0)
1759 continue;
1760 if (Idx == RootFirstOpIdx)
1761 MIB2 = MIB2.addReg(RegA, {}, SubRegA);
1762 else if (Idx == RootSecondOpIdx)
1763 MIB2 = MIB2.addReg(NewVR, {}, SubRegNewVR);
1764 else
1765 MIB2 = MIB2.add(MO);
1766 }
1767 MIB2.copyImplicitOps(Root);
1768
1769 // Propagate FP flags from the original instructions.
1770 // But clear poison-generating flags because those may not be valid now.
1771 // TODO: There should be a helper function for copying only fast-math-flags.
1772 uint32_t IntersectedFlags = Root.getFlags() & Prev.getFlags();
1773 MIB1->setFlags(IntersectedFlags);
1778
1779 MIB2->setFlags(IntersectedFlags);
1784
1785 setSpecialOperandAttr(Root, Prev, *MIB1, *MIB2);
1786
1787 // Record new instructions for insertion and old instructions for deletion.
1788 InsInstrs.push_back(MIB1);
1789 InsInstrs.push_back(MIB2);
1790 DelInstrs.push_back(&Prev);
1791 DelInstrs.push_back(&Root);
1792
1793 // We transformed:
1794 // B = A op X (Prev)
1795 // C = B op Y (Root)
1796 // Into:
1797 // B = X op Y (MIB1)
1798 // C = A op B (MIB2)
1799 // C has the same value as before, B doesn't; as such, keep the debug number
1800 // of C but not of B.
1801 if (unsigned OldRootNum = Root.peekDebugInstrNum())
1802 MIB2.getInstr()->setDebugInstrNum(OldRootNum);
1803}
1804
1806 MachineInstr &Root, unsigned Pattern,
1809 DenseMap<Register, unsigned> &InstIdxForVirtReg) const {
1811 MachineBasicBlock &MBB = *Root.getParent();
1812 MachineFunction &MF = *MBB.getParent();
1814
1815 switch (Pattern) {
1820 // Select the previous instruction in the sequence based on the input
1821 // pattern.
1822 std::array<unsigned, 5> OperandIndices;
1824 MachineInstr *Prev =
1825 MRI.getUniqueVRegDef(Root.getOperand(OperandIndices[0]).getReg());
1826
1827 // Don't reassociate if Prev and Root are in different blocks.
1828 if (Prev->getParent() != Root.getParent())
1829 return;
1830
1831 reassociateOps(Root, *Prev, Pattern, InsInstrs, DelInstrs, OperandIndices,
1832 InstIdxForVirtReg);
1833 break;
1834 }
1836 SmallVector<Register, 32> ChainRegs;
1837 getAccumulatorChain(&Root, ChainRegs);
1838 unsigned int Depth = ChainRegs.size();
1840 "Max accumulator width set to illegal value");
1841 unsigned int MaxWidth = Log2_32(Depth) < MaxAccumulatorWidth
1842 ? Log2_32(Depth)
1844
1845 // Walk down the chain and rewrite it as a tree.
1846 for (auto IndexedReg : llvm::enumerate(llvm::reverse(ChainRegs))) {
1847 // No need to rewrite the first node, it is already perfect as it is.
1848 if (IndexedReg.index() == 0)
1849 continue;
1850
1851 // FIXME: Losing subregisters
1852 MachineInstr *Instr = MRI.getUniqueVRegDef(IndexedReg.value());
1854 Register AccReg;
1855 if (IndexedReg.index() < MaxWidth) {
1856 // Now we need to create new instructions for the first row.
1857 AccReg = Instr->getOperand(0).getReg();
1858 unsigned OpCode = getAccumulationStartOpcode(Root.getOpcode());
1859
1860 MIB = BuildMI(MF, MIMetadata(*Instr), TII->get(OpCode), AccReg)
1861 .addReg(Instr->getOperand(2).getReg())
1862 .addReg(Instr->getOperand(3).getReg());
1863 } else {
1864 // For the remaining cases, we need to use an output register of one of
1865 // the newly inserted instructions as operand 1
1866 AccReg = Instr->getOperand(0).getReg() == Root.getOperand(0).getReg()
1867 ? MRI.createVirtualRegister(
1868 MRI.getRegClass(Root.getOperand(0).getReg()))
1869 : Instr->getOperand(0).getReg();
1870 assert(IndexedReg.index() >= MaxWidth);
1871 auto AccumulatorInput =
1872 ChainRegs[Depth - (IndexedReg.index() - MaxWidth) - 1];
1873 MIB = BuildMI(MF, MIMetadata(*Instr), TII->get(Instr->getOpcode()),
1874 AccReg)
1875 .addReg(AccumulatorInput)
1876 .addReg(Instr->getOperand(2).getReg())
1877 .addReg(Instr->getOperand(3).getReg());
1878 }
1879
1880 MIB->setFlags(Instr->getFlags());
1881 InstIdxForVirtReg.insert(std::make_pair(AccReg, InsInstrs.size()));
1882 InsInstrs.push_back(MIB);
1883 DelInstrs.push_back(Instr);
1884 }
1885
1886 SmallVector<Register, 8> RegistersToReduce;
1887 for (unsigned i = (InsInstrs.size() - MaxWidth); i < InsInstrs.size();
1888 ++i) {
1889 auto Reg = InsInstrs[i]->getOperand(0).getReg();
1890 RegistersToReduce.push_back(Reg);
1891 }
1892
1893 while (RegistersToReduce.size() > 1)
1894 reduceAccumulatorTree(RegistersToReduce, InsInstrs, MF, Root, MRI,
1895 InstIdxForVirtReg, Root.getOperand(0).getReg());
1896
1897 break;
1898 }
1900 reassociateFMAChain(*this, Root, InsInstrs, DelInstrs, InstIdxForVirtReg);
1901 break;
1902 }
1903}
1904
1908
1910 const MachineInstr &MI) const {
1911 const MachineFunction &MF = *MI.getMF();
1912 const MachineRegisterInfo &MRI = MF.getRegInfo();
1913
1914 // Remat clients assume operand 0 is the defined register.
1915 if (!MI.getNumOperands() || !MI.getOperand(0).isReg())
1916 return false;
1917 Register DefReg = MI.getOperand(0).getReg();
1918
1919 // A sub-register definition can only be rematerialized if the instruction
1920 // doesn't read the other parts of the register. Otherwise it is really a
1921 // read-modify-write operation on the full virtual register which cannot be
1922 // moved safely.
1923 if (DefReg.isVirtual() && MI.getOperand(0).getSubReg() &&
1924 MI.readsVirtualRegister(DefReg))
1925 return false;
1926
1927 // A load from a fixed stack slot can be rematerialized. This may be
1928 // redundant with subsequent checks, but it's target-independent,
1929 // simple, and a common case.
1930 int FrameIdx = 0;
1931 if (isLoadFromStackSlot(MI, FrameIdx) &&
1932 MF.getFrameInfo().isImmutableObjectIndex(FrameIdx))
1933 return true;
1934
1935 // Avoid instructions obviously unsafe for remat.
1936 if (MI.isNotDuplicable() || MI.mayStore() || MI.mayRaiseFPException() ||
1937 MI.hasUnmodeledSideEffects())
1938 return false;
1939
1940 // Don't remat inline asm. We have no idea how expensive it is
1941 // even if it's side effect free.
1942 if (MI.isInlineAsm())
1943 return false;
1944
1945 // Avoid instructions which load from potentially varying memory.
1946 if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad())
1947 return false;
1948
1949 // If any of the registers accessed are non-constant, conservatively assume
1950 // the instruction is not rematerializable.
1951 for (const MachineOperand &MO : MI.operands()) {
1952 if (!MO.isReg()) continue;
1953 Register Reg = MO.getReg();
1954 if (Reg == 0)
1955 continue;
1956
1957 // Check for a well-behaved physical register.
1958 if (Reg.isPhysical()) {
1959 if (MO.isUse()) {
1960 // If the physreg has no defs anywhere, it's just an ambient register
1961 // and we can freely move its uses. Alternatively, if it's allocatable,
1962 // it could get allocated to something with a def during allocation.
1963 if (!MRI.isConstantPhysReg(Reg))
1964 return false;
1965 } else {
1966 // A physreg def. We can't remat it.
1967 return false;
1968 }
1969 continue;
1970 }
1971
1972 // Only allow one virtual-register def. There may be multiple defs of the
1973 // same virtual register, though.
1974 if (MO.isDef() && Reg != DefReg)
1975 return false;
1976 }
1977
1978 // Everything checked out.
1979 return true;
1980}
1981
1983 const MachineFunction *MF = MI.getMF();
1985 bool StackGrowsDown =
1987
1988 unsigned FrameSetupOpcode = getCallFrameSetupOpcode();
1989 unsigned FrameDestroyOpcode = getCallFrameDestroyOpcode();
1990
1991 if (!isFrameInstr(MI))
1992 return 0;
1993
1994 int SPAdj = TFI->alignSPAdjust(getFrameSize(MI));
1995
1996 if ((!StackGrowsDown && MI.getOpcode() == FrameSetupOpcode) ||
1997 (StackGrowsDown && MI.getOpcode() == FrameDestroyOpcode))
1998 SPAdj = -SPAdj;
1999
2000 return SPAdj;
2001}
2002
2003/// isSchedulingBoundary - Test if the given instruction should be
2004/// considered a scheduling boundary. This primarily includes labels
2005/// and terminators.
2007 const MachineBasicBlock *MBB,
2008 const MachineFunction &MF) const {
2009 // Terminators and labels can't be scheduled around.
2010 if (MI.isTerminator() || MI.isPosition())
2011 return true;
2012
2013 // INLINEASM_BR can jump to another block
2014 if (MI.getOpcode() == TargetOpcode::INLINEASM_BR)
2015 return true;
2016
2017 // Don't attempt to schedule around any instruction that defines
2018 // a stack-oriented pointer, as it's unlikely to be profitable. This
2019 // saves compile time, because it doesn't require every single
2020 // stack slot reference to depend on the instruction that does the
2021 // modification.
2023 return MI.modifiesRegister(TLI.getStackPointerRegisterToSaveRestore(), &TRI);
2024}
2025
2026// Provide a global flag for disabling the PreRA hazard recognizer that targets
2027// may choose to honor.
2031
2032// Default implementation of CreateTargetRAHazardRecognizer.
2035 const ScheduleDAG *DAG) const {
2036 // Dummy hazard recognizer allows all instructions to issue.
2037 return new ScheduleHazardRecognizer();
2038}
2039
2040// Default implementation of CreateTargetMIHazardRecognizer.
2042 const InstrItineraryData *II, const ScheduleDAGMI *DAG) const {
2043 return new ScoreboardHazardRecognizer(II, DAG, "machine-scheduler");
2044}
2045
2046// Default implementation of CreateTargetPostRAHazardRecognizer.
2052
2053// Default implementation of getMemOperandWithOffset.
2055 const MachineOperand *&BaseOp,
2056 int64_t &Offset,
2057 bool &OffsetIsScalable) const {
2060 if (!getMemOperandsWithOffsetWidth(MI, BaseOps, Offset, OffsetIsScalable,
2061 Width) ||
2062 BaseOps.size() != 1)
2063 return false;
2064 BaseOp = BaseOps.front();
2065 return true;
2066}
2067
2068//===----------------------------------------------------------------------===//
2069// SelectionDAG latency interface.
2070//===----------------------------------------------------------------------===//
2071
2072std::optional<unsigned>
2074 SDNode *DefNode, unsigned DefIdx,
2075 SDNode *UseNode, unsigned UseIdx) const {
2076 if (!ItinData || ItinData->isEmpty())
2077 return std::nullopt;
2078
2079 if (!DefNode->isMachineOpcode())
2080 return std::nullopt;
2081
2082 unsigned DefClass = get(DefNode->getMachineOpcode()).getSchedClass();
2083 if (!UseNode->isMachineOpcode())
2084 return ItinData->getOperandCycle(DefClass, DefIdx);
2085 unsigned UseClass = get(UseNode->getMachineOpcode()).getSchedClass();
2086 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
2087}
2088
2090 SDNode *N) const {
2091 if (!ItinData || ItinData->isEmpty())
2092 return 1;
2093
2094 if (!N->isMachineOpcode())
2095 return 1;
2096
2097 return ItinData->getStageLatency(get(N->getMachineOpcode()).getSchedClass());
2098}
2099
2100//===----------------------------------------------------------------------===//
2101// MachineInstr latency interface.
2102//===----------------------------------------------------------------------===//
2103
2105 const MachineInstr &MI) const {
2106 if (!ItinData || ItinData->isEmpty())
2107 return 1;
2108
2109 unsigned Class = MI.getDesc().getSchedClass();
2110 int UOps = ItinData->Itineraries[Class].NumMicroOps;
2111 if (UOps >= 0)
2112 return UOps;
2113
2114 // The # of u-ops is dynamically determined. The specific target should
2115 // override this function to return the right number.
2116 return 1;
2117}
2118
2119/// Return the default expected latency for a def based on it's opcode.
2121 const MCSchedModel &SchedModel,
2122 const MachineInstr &DefMI) const {
2123 if (DefMI.isTransient())
2124 return 0;
2125 if (DefMI.mayLoad())
2126 return STI.getLoadLatency();
2127 if (isHighLatencyDef(DefMI.getOpcode()))
2128 return SchedModel.HighLatency;
2129 return 1;
2130}
2131
2133 return 0;
2134}
2135
2137 const MachineInstr &MI,
2138 unsigned *PredCost) const {
2139 // Default to one cycle for no itinerary. However, an "empty" itinerary may
2140 // still have a MinLatency property, which getStageLatency checks.
2141 if (!ItinData)
2142 return MI.mayLoad() ? 2 : 1;
2143
2144 return ItinData->getStageLatency(MI.getDesc().getSchedClass());
2145}
2146
2148 const MachineInstr &DefMI,
2149 unsigned DefIdx) const {
2150 const InstrItineraryData *ItinData = SchedModel.getInstrItineraries();
2151 if (!ItinData || ItinData->isEmpty())
2152 return false;
2153
2154 unsigned DefClass = DefMI.getDesc().getSchedClass();
2155 std::optional<unsigned> DefCycle =
2156 ItinData->getOperandCycle(DefClass, DefIdx);
2157 return DefCycle && DefCycle <= 1U;
2158}
2159
2161 MachineFunction &MF, bool OutlineFromLinkOnceODRs) const {
2162 const Function &F = MF.getFunction();
2163
2164 // Can F be deduplicated by the linker? If it can, don't outline from it.
2165 if (!OutlineFromLinkOnceODRs && F.hasLinkOnceODRLinkage())
2166 return false;
2167
2168 // Allow outlining from named section functions if the target can place the
2169 // outlined function in the same section.
2170 if (F.hasSection() && !supportsSectionAwareOutlining())
2171 return false;
2172
2173 // It's safe to outline from MF.
2174 return true;
2175}
2176
2178 // TODO: We don't split functions where a section attribute has been set
2179 // since the split part may not be placed in a contiguous region. It may also
2180 // be more beneficial to augment the linker to ensure contiguous layout of
2181 // split functions within the same section as specified by the attribute.
2182 if (MF.getFunction().hasSection())
2183 return false;
2184
2185 // We don't want to proceed further for cold functions
2186 // or functions of unknown hotness. Lukewarm functions have no prefix.
2187 std::optional<StringRef> SectionPrefix = MF.getFunction().getSectionPrefix();
2188 if (SectionPrefix &&
2189 (*SectionPrefix == "unlikely" || *SectionPrefix == "unknown")) {
2190 return false;
2191 }
2192
2193 return true;
2194}
2195
2196std::optional<ParamLoadedValue>
2198 Register Reg) const {
2199 const MachineFunction *MF = MI.getMF();
2201 int64_t Offset;
2202 bool OffsetIsScalable;
2203
2204 // To simplify the sub-register handling, verify that we only need to
2205 // consider physical registers.
2206 assert(MF->getProperties().hasNoVRegs());
2207
2208 if (auto DestSrc = isCopyInstr(MI)) {
2209 Register DestReg = DestSrc->Destination->getReg();
2210
2211 // If the copy destination is the forwarding reg, describe the forwarding
2212 // reg using the copy source as the backup location. Example:
2213 //
2214 // x0 = MOV x7
2215 // call callee(x0) ; x0 described as x7
2216 if (Reg == DestReg)
2217 return ParamLoadedValue(*DestSrc->Source, Expr);
2218
2219 // If the target's hook couldn't describe this copy, give up.
2220 return std::nullopt;
2221 } else if (auto RegImm = isAddImmediate(MI, Reg)) {
2222 Register SrcReg = RegImm->Reg;
2223 Offset = RegImm->Imm;
2225 return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
2226 } else if (MI.hasOneMemOperand()) {
2227 // Only describe memory which provably does not escape the function. As
2228 // described in llvm.org/PR43343, escaped memory may be clobbered by the
2229 // callee (or by another thread).
2230 const MachineFrameInfo &MFI = MF->getFrameInfo();
2231 const MachineMemOperand *MMO = MI.memoperands()[0];
2232 const PseudoSourceValue *PSV = MMO->getPseudoValue();
2233
2234 // If the address points to "special" memory (e.g. a spill slot), it's
2235 // sufficient to check that it isn't aliased by any high-level IR value.
2236 if (!PSV || PSV->mayAlias(&MFI))
2237 return std::nullopt;
2238
2239 const MachineOperand *BaseOp;
2240 if (!getMemOperandWithOffset(MI, BaseOp, Offset, OffsetIsScalable))
2241 return std::nullopt;
2242
2243 // FIXME: Scalable offsets are not yet handled in the offset code below.
2244 if (OffsetIsScalable)
2245 return std::nullopt;
2246
2247 // TODO: Can currently only handle mem instructions with a single define.
2248 // An example from the x86 target:
2249 // ...
2250 // DIV64m $rsp, 1, $noreg, 24, $noreg, implicit-def dead $rax, implicit-def $rdx
2251 // ...
2252 //
2253 if (MI.getNumExplicitDefs() != 1)
2254 return std::nullopt;
2255
2256 // DW_OP_deref_size needs a known, fixed size that fits in its one-byte
2257 // operand and is no larger than the size of an address.
2258 if (!MMO->getSize().hasValue() || MMO->getSize().isScalable() ||
2259 !isUInt<8>(MMO->getSize().getValue().getFixedValue()) ||
2260 MMO->getSize().getValue().getFixedValue() >
2262 return std::nullopt;
2263
2264 // TODO: In what way do we need to take Reg into consideration here?
2265
2268 Ops.push_back(dwarf::DW_OP_deref_size);
2269 Ops.push_back(MMO->getSize().getValue().getFixedValue());
2270 Expr = DIExpression::prependOpcodes(Expr, Ops);
2271 return ParamLoadedValue(*BaseOp, Expr);
2272 }
2273
2274 return std::nullopt;
2275}
2276
2277// Get the call frame size just before MI.
2279 // Search backwards from MI for the most recent call frame instruction.
2280 MachineBasicBlock *MBB = MI.getParent();
2281 for (auto &AdjI : reverse(make_range(MBB->instr_begin(), MI.getIterator()))) {
2282 if (AdjI.getOpcode() == getCallFrameSetupOpcode())
2283 return getFrameTotalSize(AdjI);
2284 if (AdjI.getOpcode() == getCallFrameDestroyOpcode())
2285 return 0;
2286 }
2287
2288 // If none was found, use the call frame size from the start of the basic
2289 // block.
2290 return MBB->getCallFrameSize();
2291}
2292
2293/// Both DefMI and UseMI must be valid. By default, call directly to the
2294/// itinerary. This may be overriden by the target.
2296 const InstrItineraryData *ItinData, const MachineInstr &DefMI,
2297 unsigned DefIdx, const MachineInstr &UseMI, unsigned UseIdx) const {
2298 unsigned DefClass = DefMI.getDesc().getSchedClass();
2299 unsigned UseClass = UseMI.getDesc().getSchedClass();
2300 return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
2301}
2302
2304 const MachineInstr &MI, unsigned DefIdx,
2305 SmallVectorImpl<RegSubRegPairAndIdx> &InputRegs) const {
2306 assert((MI.isRegSequence() ||
2307 MI.isRegSequenceLike()) && "Instruction do not have the proper type");
2308
2309 if (!MI.isRegSequence())
2310 return getRegSequenceLikeInputs(MI, DefIdx, InputRegs);
2311
2312 // We are looking at:
2313 // Def = REG_SEQUENCE v0, sub0, v1, sub1, ...
2314 assert(DefIdx == 0 && "REG_SEQUENCE only has one def");
2315 for (unsigned OpIdx = 1, EndOpIdx = MI.getNumOperands(); OpIdx != EndOpIdx;
2316 OpIdx += 2) {
2317 const MachineOperand &MOReg = MI.getOperand(OpIdx);
2318 if (MOReg.isUndef())
2319 continue;
2320 const MachineOperand &MOSubIdx = MI.getOperand(OpIdx + 1);
2321 assert(MOSubIdx.isImm() &&
2322 "One of the subindex of the reg_sequence is not an immediate");
2323 // Record Reg:SubReg, SubIdx.
2324 InputRegs.push_back(RegSubRegPairAndIdx(MOReg.getReg(), MOReg.getSubReg(),
2325 (unsigned)MOSubIdx.getImm()));
2326 }
2327 return true;
2328}
2329
2331 const MachineInstr &MI, unsigned DefIdx,
2332 RegSubRegPairAndIdx &InputReg) const {
2333 assert((MI.isExtractSubreg() ||
2334 MI.isExtractSubregLike()) && "Instruction do not have the proper type");
2335
2336 if (!MI.isExtractSubreg())
2337 return getExtractSubregLikeInputs(MI, DefIdx, InputReg);
2338
2339 // We are looking at:
2340 // Def = EXTRACT_SUBREG v0.sub1, sub0.
2341 assert(DefIdx == 0 && "EXTRACT_SUBREG only has one def");
2342 const MachineOperand &MOReg = MI.getOperand(1);
2343 if (MOReg.isUndef())
2344 return false;
2345 const MachineOperand &MOSubIdx = MI.getOperand(2);
2346 assert(MOSubIdx.isImm() &&
2347 "The subindex of the extract_subreg is not an immediate");
2348
2349 InputReg.Reg = MOReg.getReg();
2350 InputReg.SubReg = MOReg.getSubReg();
2351 InputReg.SubIdx = (unsigned)MOSubIdx.getImm();
2352 return true;
2353}
2354
2356 const MachineInstr &MI, unsigned DefIdx,
2357 RegSubRegPair &BaseReg, RegSubRegPairAndIdx &InsertedReg) const {
2358 assert((MI.isInsertSubreg() ||
2359 MI.isInsertSubregLike()) && "Instruction do not have the proper type");
2360
2361 if (!MI.isInsertSubreg())
2362 return getInsertSubregLikeInputs(MI, DefIdx, BaseReg, InsertedReg);
2363
2364 // We are looking at:
2365 // Def = INSERT_SEQUENCE v0, v1, sub0.
2366 assert(DefIdx == 0 && "INSERT_SUBREG only has one def");
2367 const MachineOperand &MOBaseReg = MI.getOperand(1);
2368 const MachineOperand &MOInsertedReg = MI.getOperand(2);
2369 if (MOInsertedReg.isUndef())
2370 return false;
2371 const MachineOperand &MOSubIdx = MI.getOperand(3);
2372 assert(MOSubIdx.isImm() &&
2373 "One of the subindex of the reg_sequence is not an immediate");
2374 BaseReg.Reg = MOBaseReg.getReg();
2375 BaseReg.SubReg = MOBaseReg.getSubReg();
2376
2377 InsertedReg.Reg = MOInsertedReg.getReg();
2378 InsertedReg.SubReg = MOInsertedReg.getSubReg();
2379 InsertedReg.SubIdx = (unsigned)MOSubIdx.getImm();
2380 return true;
2381}
2382
2383// Returns a MIRPrinter comment for this machine operand.
2385 const MachineOperand &Op,
2386 unsigned OpIdx) const {
2387
2388 if (!MI.isInlineAsm())
2389 return "";
2390
2391 std::string Flags;
2392 raw_string_ostream OS(Flags);
2393
2394 if (OpIdx == InlineAsm::MIOp_ExtraInfo) {
2395 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
2396 unsigned ExtraInfo = Op.getImm();
2397 OS << interleaved(InlineAsm::getExtraInfoNames(ExtraInfo), " ");
2398 return Flags;
2399 }
2400
2401 int FlagIdx = MI.findInlineAsmFlagIdx(OpIdx);
2402 if (FlagIdx < 0 || (unsigned)FlagIdx != OpIdx)
2403 return "";
2404
2405 assert(Op.isImm() && "Expected flag operand to be an immediate");
2406 // Pretty print the inline asm operand descriptor.
2407 unsigned Flag = Op.getImm();
2408 const InlineAsm::Flag F(Flag);
2409 OS << F.getKindName();
2410
2411 unsigned RCID;
2412 if (!F.isImmKind() && !F.isMemKind() && !F.isFuncKind() &&
2413 F.hasRegClassConstraint(RCID))
2414 OS << ':' << TRI.getRegClassName(TRI.getRegClass(RCID));
2415
2416 if (F.isMemKind() || F.isFuncKind()) {
2417 InlineAsm::ConstraintCode MCID = F.getMemoryConstraintID();
2419 }
2420
2421 unsigned TiedTo;
2422 if (F.isUseOperandTiedToDef(TiedTo))
2423 OS << " tiedto:$" << TiedTo;
2424
2425 if ((F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isRegUseKind()) &&
2426 F.getRegMayBeFolded())
2427 OS << " foldable";
2428
2429 return Flags;
2430}
2431
2433
2435 Function &F, std::vector<outliner::Candidate> &Candidates) const {
2436 // Include target features from an arbitrary candidate for the outlined
2437 // function. This makes sure the outlined function knows what kinds of
2438 // instructions are going into it. This is fine, since all parent functions
2439 // must necessarily support the instructions that are in the outlined region.
2440 outliner::Candidate &FirstCand = Candidates.front();
2441 const Function &ParentFn = FirstCand.getMF()->getFunction();
2442 if (ParentFn.hasFnAttribute("target-features"))
2443 F.addFnAttr(ParentFn.getFnAttribute("target-features"));
2444 if (ParentFn.hasFnAttribute("target-cpu"))
2445 F.addFnAttr(ParentFn.getFnAttribute("target-cpu"));
2446
2447 // Set nounwind, so we don't generate eh_frame.
2448 if (llvm::all_of(Candidates, [](const outliner::Candidate &C) {
2449 return C.getMF()->getFunction().hasFnAttribute(Attribute::NoUnwind);
2450 }))
2451 F.addFnAttr(Attribute::NoUnwind);
2452}
2453
2457 unsigned Flags) const {
2458 MachineInstr &MI = *MIT;
2459
2460 // NOTE: MI.isMetaInstruction() will match CFI_INSTRUCTION, but some targets
2461 // have support for outlining those. Special-case that here.
2462 if (MI.isCFIInstruction())
2463 // Just go right to the target implementation.
2464 return getOutliningTypeImpl(MMI, MIT, Flags);
2465
2466 // Be conservative about inline assembly.
2467 if (MI.isInlineAsm())
2469
2470 // Labels generally can't safely be outlined.
2471 if (MI.isLabel())
2473
2474 if (MI.getFlag(MachineInstr::NoMerge))
2476
2477 // Don't let debug instructions impact analysis.
2478 if (MI.isDebugInstr())
2480
2481 // Some other special cases.
2482 switch (MI.getOpcode()) {
2483 case TargetOpcode::IMPLICIT_DEF:
2484 case TargetOpcode::KILL:
2485 case TargetOpcode::LIFETIME_START:
2486 case TargetOpcode::LIFETIME_END:
2488 default:
2489 break;
2490 }
2491
2492 // Is this a terminator for a basic block?
2493 if (MI.isTerminator()) {
2494 // If this is a branch to another block, we can't outline it.
2495 if (!MI.getParent()->succ_empty())
2497
2498 // Don't outline if the branch is not unconditional.
2499 if (isPredicated(MI))
2501 }
2502
2503 // Make sure none of the operands of this instruction do anything that
2504 // might break if they're moved outside their current function.
2505 // This includes MachineBasicBlock references, BlockAddressses,
2506 // Constant pool indices and jump table indices.
2507 //
2508 // A quick note on MO_TargetIndex:
2509 // This doesn't seem to be used in any of the architectures that the
2510 // MachineOutliner supports, but it was still filtered out in all of them.
2511 // There was one exception (RISC-V), but MO_TargetIndex also isn't used there.
2512 // As such, this check is removed both here and in the target-specific
2513 // implementations. Instead, we assert to make sure this doesn't
2514 // catch anyone off-guard somewhere down the line.
2515 for (const MachineOperand &MOP : MI.operands()) {
2516 // If you hit this assertion, please remove it and adjust
2517 // `getOutliningTypeImpl` for your target appropriately if necessary.
2518 // Adding the assertion back to other supported architectures
2519 // would be nice too :)
2520 assert(!MOP.isTargetIndex() && "This isn't used quite yet!");
2521
2522 // CFI instructions should already have been filtered out at this point.
2523 assert(!MOP.isCFIIndex() && "CFI instructions handled elsewhere!");
2524
2525 // PrologEpilogInserter should've already run at this point.
2526 assert(!MOP.isFI() && "FrameIndex instructions should be gone by now!");
2527
2528 if (MOP.isMBB() || MOP.isBlockAddress() || MOP.isCPI() || MOP.isJTI())
2530 }
2531
2532 // If we don't know, delegate to the target-specific hook.
2533 return getOutliningTypeImpl(MMI, MIT, Flags);
2534}
2535
2537 unsigned &Flags) const {
2538 // Some instrumentations create special TargetOpcode at the start which
2539 // expands to special code sequences which must be present.
2540 auto First = MBB.getFirstNonDebugInstr();
2541 if (First == MBB.end())
2542 return true;
2543
2544 if (First->getOpcode() == TargetOpcode::FENTRY_CALL ||
2545 First->getOpcode() == TargetOpcode::PATCHABLE_FUNCTION_ENTER)
2546 return false;
2547
2548 // Some instrumentations create special pseudo-instructions at or just before
2549 // the end that must be present.
2550 auto Last = MBB.getLastNonDebugInstr();
2551 if (Last->getOpcode() == TargetOpcode::PATCHABLE_RET ||
2552 Last->getOpcode() == TargetOpcode::PATCHABLE_TAIL_CALL)
2553 return false;
2554
2555 if (Last != First && Last->isReturn()) {
2556 Last = prev_nodbg(Last, First, /*SkipPseudoOp=*/false);
2557 if (Last->getOpcode() == TargetOpcode::PATCHABLE_FUNCTION_EXIT ||
2558 Last->getOpcode() == TargetOpcode::PATCHABLE_TAIL_CALL)
2559 return false;
2560 }
2561 return true;
2562}
2563
2565 return MI->isCall() || MI->hasUnmodeledSideEffects() ||
2566 (MI->hasOrderedMemoryRef() && !MI->isDereferenceableInvariantLoad());
2567}
MachineInstrBuilder & UseMI
MachineInstrBuilder MachineInstrBuilder & DefMI
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
SmallVector< int16_t, MAX_SRC_OPERANDS_NUM > OperandIndices
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
bpf unwind BPF Unwind Lower
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
DXIL Forward Handle Accesses
This file contains constants used for implementing Dwarf debug support.
IRTranslator LLVM IR MI
Module.h This file contains the declarations for the Module class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
unsigned Opc
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
static MCRegister getReg(const MCDisassembler *D, unsigned RC, unsigned RegNo)
uint64_t IntrinsicInst * II
TargetInstrInfo::RegSubRegPairAndIdx RegSubRegPairAndIdx
MachineRegisterInfo & MRI
Provides some synthesis utilities to produce sequences of values.
This file defines the SmallSet class.
This file contains some functions that are useful when dealing with strings.
static bool isAsmComment(const char *Str, const MCAsmInfo &MAI)
static void transferImplicitOperands(MachineInstr *MI, const TargetRegisterInfo *TRI)
transferImplicitOperands - MI is a pseudo-instruction, and the lowered replacement instructions immed...
static bool isFMASplitProfitable(const TargetInstrInfo &TII, ArrayRef< MachineInstr * > Chain)
static cl::opt< bool > EnableAccReassociation("acc-reassoc", cl::Hidden, cl::init(true), cl::desc("Enable reassociation of accumulation chains"))
static int getFMAChainAccOpIdx(const TargetInstrInfo::FMAChainLinkInfo &Info, const MachineInstr &Link, const MachineInstr &Prev)
static bool isPlainVirtRegOperand(const MachineOperand &MO)
static SmallVector< MachineInstr * > collectFMAChain(const TargetInstrInfo &TII, MachineInstr &Root)
static std::pair< bool, bool > mustSwapOperands(unsigned Pattern)
static const TargetRegisterClass * canFoldCopy(const MachineInstr &MI, const TargetInstrInfo &TII, unsigned FoldIdx)
static cl::opt< unsigned int > MinAccumulatorDepth("acc-min-depth", cl::Hidden, cl::init(8), cl::desc("Minimum length of accumulator chains " "required for the optimization to kick in"))
static void foldInlineAsmMemOperand(MachineInstr *MI, unsigned OpNo, int FI, const TargetInstrInfo &TII)
static void reassociateFMAChain(const TargetInstrInfo &TII, MachineInstr &Root, SmallVectorImpl< MachineInstr * > &InsInstrs, SmallVectorImpl< MachineInstr * > &DelInstrs, DenseMap< Register, unsigned > &InstrIdxForVirtReg)
static cl::opt< unsigned int > MaxAccumulatorWidth("acc-max-width", cl::Hidden, cl::init(3), cl::desc("Maximum number of branches in the accumulator tree"))
static bool getFMAChainPatterns(const TargetInstrInfo &TII, MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns, bool DoRegPressureReduce)
static bool canCombine(MachineBasicBlock &MBB, MachineOperand &MO, unsigned CombineOpc=0)
static MachineInstr * buildFMAChainAdd(const TargetInstrInfo &TII, MachineInstr &Root, Register Lower, Register Upper)
static cl::opt< bool > DisableHazardRecognizer("disable-sched-hazard", cl::Hidden, cl::init(false), cl::desc("Disable hazard detection during preRA scheduling"))
static MachineInstr * foldPatchpoint(MachineFunction &MF, MachineInstr &MI, ArrayRef< unsigned > Ops, int FrameIndex, const TargetInstrInfo &TII)
This file describes how to lower LLVM code to machine code.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & back() const
Get the last element.
Definition ArrayRef.h:150
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition ArrayRef.h:194
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
ArrayRef< T > drop_back(size_t N=1) const
Drop the last N elements of the array.
Definition ArrayRef.h:200
DWARF expression.
static LLVM_ABI void appendOffset(SmallVectorImpl< uint64_t > &Ops, int64_t Offset)
Append Ops with operations to apply the Offset.
static LLVM_ABI DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
static LLVM_ABI DIExpression * prependOpcodes(const DIExpression *Expr, SmallVectorImpl< uint64_t > &Ops, bool StackValue=false, bool EntryValue=false)
Prepend DIExpr with the given opcodes and optionally turn it into a stack value.
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:219
LLVM_ABI unsigned getPointerSize(unsigned AS=0) const
The pointer representation size in bytes, rounded up to a whole number of bytes.
A debug info location.
Definition DebugLoc.h:126
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Definition Function.h:708
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:766
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition Function.cpp:352
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
LLVM_ABI std::optional< StringRef > getSectionPrefix() const
Get the section prefix for this global object.
Definition Globals.cpp:382
bool hasSection() const
Check if this global has a custom object file section.
Module * getParent()
Get the module that this global value is contained inside of...
static std::vector< StringRef > getExtraInfoNames(unsigned ExtraInfo)
Definition InlineAsm.h:477
static StringRef getMemConstraintName(ConstraintCode C)
Definition InlineAsm.h:501
Itinerary data supplied by a subtarget to be used by a target.
std::optional< unsigned > getOperandCycle(unsigned ItinClassIndx, unsigned OperandIdx) const
Return the cycle for the given class and operand.
unsigned getStageLatency(unsigned ItinClassIndx) const
Return the total stage latency of the given class.
std::optional< unsigned > getOperandLatency(unsigned DefClass, unsigned DefIdx, unsigned UseClass, unsigned UseIdx) const
Compute and return the use operand latency of a given itinerary class and operand index if the value ...
const InstrItinerary * Itineraries
Array of itineraries selected.
bool isEmpty() const
Returns true if there are no itineraries.
bool hasValue() const
static LocationSize precise(uint64_t Value)
bool isScalable() const
TypeSize getValue() const
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition MCAsmInfo.h:69
unsigned getMaxInstLength() const
Returns the maximum possible encoded instruction size in bytes.
Definition MCAsmInfo.h:578
StringRef getCommentString() const
Definition MCAsmInfo.h:587
const char * getSeparatorString() const
Definition MCAsmInfo.h:582
Instances of this class represent a single low-level machine instruction.
Definition MCInst.h:187
Describe properties that are true of each instruction in the target description file.
unsigned getSchedClass() const
Return the scheduling class for this instruction.
const MCInstrDesc & get(unsigned Opcode) const
Return the machine instruction descriptor that corresponds to the specified instruction opcode.
Definition MCInstrInfo.h:89
This holds information about one operand of a machine instruction, indicating the register class for ...
Definition MCInstrDesc.h:88
bool contains(MCRegister Reg) const
contains - Return true if the specified register is included in this register class.
bool hasSubClassEq(const MCRegisterClass *RC) const
Returns true if RC is a sub-class of or equal to this class.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1588
Set of metadata that should be preserved when using BuildMI().
Instructions::const_iterator const_instr_iterator
MachineInstrBundleIterator< MachineInstr > iterator
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool isImmutableObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to an immutable object.
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
const DataLayout & getDataLayout() const
Return the DataLayout attached to the Module associated to this MF.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
const MachineFunctionProperties & getProperties() const
Get the function properties.
MachineMemOperand * getMachineMemOperand(MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LLT MemTy, Align BaseAlignment, const MMOMetadata &Metadata=MMOMetadata(), SyncScope::ID SSID=SyncScope::System, AtomicOrdering Ordering=AtomicOrdering::NotAtomic, AtomicOrdering FailureOrdering=AtomicOrdering::NotAtomic)
getMachineMemOperand - Allocate a new MachineMemOperand.
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addFrameIndex(int Idx) const
const MachineInstrBuilder & copyImplicitOps(const MachineInstr &OtherMI) const
Copy all the implicit operands from OtherMI onto this one.
MachineInstr * getInstr() const
If conversion operators fail, use this method to get the MachineInstr explicitly.
const MachineInstrBuilder & copyMIMetadata(const MIMetadata &MIMD) const
Representation of each machine instruction.
ArrayRef< MachineMemOperand * >::iterator mmo_iterator
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
const MachineBasicBlock * getParent() const
void setFlags(unsigned flags)
bool getFlag(MIFlag Flag) const
Return whether an MI flag is set.
unsigned getNumOperands() const
Retuns the total number of operands.
void setDebugInstrNum(unsigned Num)
Set instruction number of this MachineInstr.
mmo_iterator memoperands_end() const
Access to memory operands of the instruction.
unsigned peekDebugInstrNum() const
Examine the instruction number of this MachineInstr.
LLVM_ABI void setMemRefs(MachineFunction &MF, ArrayRef< MachineMemOperand * > MemRefs)
Assign this MachineInstr's memory reference descriptor list.
bool mayLoad(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly read memory.
LLVM_ABI int findRegisterUseOperandIdx(Register Reg, const TargetRegisterInfo *TRI, bool isKill=false) const
Returns the operand index that is a use of the specific register or -1 if it is not found.
bool isCFIInstruction() const
bool isNotDuplicable(QueryType Type=AnyInBundle) const
Return true if this instruction cannot be safely duplicated.
void clearFlag(MIFlag Flag)
clearFlag - Clear a MI flag.
void untieRegOperand(unsigned OpIdx)
Break any tie involving OpIdx.
LLVM_ABI void setDesc(const MCInstrDesc &TID)
Replace the instruction descriptor (thus opcode) of the current instruction with a new one.
mop_range explicit_operands()
LLVM_ABI void tieOperands(unsigned DefIdx, unsigned UseIdx)
Add a tie between the register operands at DefIdx and UseIdx.
mmo_iterator memoperands_begin() const
Access to memory operands of the instruction.
LLVM_ABI void cloneInstrSymbols(MachineFunction &MF, const MachineInstr &MI)
Clone another MachineInstr's pre- and post- instruction symbols and replace ours with it.
LLVM_ABI bool isIdenticalTo(const MachineInstr &Other, MICheckType Check=CheckDefs) const
Return true if this instruction is identical to Other.
LLVM_ABI const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
ArrayRef< MachineMemOperand * > memoperands() const
Access to memory operands of the instruction.
bool mayStore(QueryType Type=AnyInBundle) const
Return true if this instruction could possibly modify memory.
LLVM_ABI void removeOperand(unsigned OpNo)
Erase an operand from an instruction, leaving it with one fewer operand than it started with.
const MachineOperand & getOperand(unsigned i) const
uint32_t getFlags() const
Return the MI flags bitvector.
LLVM_ABI void clearKillInfo()
Clears kill flags on all operands.
bool canFoldAsLoad(QueryType Type=IgnoreBundle) const
Return true for instructions that can be folded as memory operands in other instructions.
LLVM_ABI const TargetRegisterClass * getRegClassConstraint(unsigned OpIdx, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const
Compute the static register class constraint for operand OpIdx.
LLVM_ABI void addMemOperand(MachineFunction &MF, MachineMemOperand *MO)
Add a MachineMemOperand to the machine instruction.
A description of a memory reference used in the backend.
LocationSize getSize() const
Return the size in bytes of the memory reference.
const PseudoSourceValue * getPseudoValue() const
Flags
Flags values. These may be or'd together.
@ MOLoad
The memory access reads data.
@ MOStore
The memory access writes data.
This class contains meta information specific to a module.
MachineOperand class - Representation of each machine instruction operand.
void setSubReg(unsigned subReg)
unsigned getSubReg() const
void setIsInternalRead(bool Val=true)
void setImm(int64_t immVal)
int64_t getImm() const
LLVM_ABI void setIsRenamable(bool Val=true)
bool isReg() const
isReg - Tests if this is a MO_Register operand.
LLVM_ABI void setReg(Register Reg)
Change the register this operand corresponds to.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
void setIsKill(bool Val=true)
LLVM_ABI bool isRenamable() const
isRenamable - Returns true if this register may be renamed, i.e.
void setMBB(MachineBasicBlock *MBB)
void setIsUndef(bool Val=true)
Register getReg() const
getReg - Returns the register number.
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
bool isMBB() const
isMBB - Tests if this is a MO_MachineBasicBlock operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition Module.h:328
MI-level patchpoint operands.
Definition StackMaps.h:77
Special value supplied for machine level alias analysis.
virtual bool mayAlias(const MachineFrameInfo *) const
Return true if the memory pointed to by this PseudoSourceValue can ever alias an LLVM IR Value.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition Register.h:79
constexpr bool isPhysical() const
Return true if the specified register number is in the physical register namespace.
Definition Register.h:83
Represents one node in the SelectionDAG.
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode.
unsigned getMachineOpcode() const
This may only be called if isMachineOpcode returns true.
ScheduleDAGMI is an implementation of ScheduleDAGInstrs that simply schedules machine instructions ac...
HazardRecognizer - This determines whether or not an instruction can be issued this cycle,...
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
bool contains(const T &V) const
Check if the SmallSet contains the given element.
Definition SmallSet.h:229
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
MI-level stackmap operands.
Definition StackMaps.h:36
MI-level Statepoint operands.
Definition StackMaps.h:159
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
Information about stack frame layout on the target.
StackDirection getStackGrowthDirection() const
getStackGrowthDirection - Return the direction the stack grows
int alignSPAdjust(int SPAdj) const
alignSPAdjust - This method aligns the stack adjustment to the correct alignment.
TargetInstrInfo - Interface to description of machine instruction set.
virtual ScheduleHazardRecognizer * CreateTargetPostRAHazardRecognizer(const InstrItineraryData *, const ScheduleDAG *DAG) const
Allocate and return a hazard recognizer to use for this target when scheduling the machine instructio...
virtual bool hasLowDefLatency(const TargetSchedModel &SchedModel, const MachineInstr &DefMI, unsigned DefIdx) const
Compute operand latency of a def of 'Reg'.
virtual unsigned getInlineAsmLength(const char *Str, const MCAsmInfo &MAI, unsigned MaxInstLength=0) const
Measure the specified inline asm to determine an approximation of its length.
virtual void setSpecialOperandAttr(MachineInstr &OldMI1, MachineInstr &OldMI2, MachineInstr &NewMI1, MachineInstr &NewMI2) const
This is an architecture-specific helper function of reassociateOps.
const TargetRegisterInfo & TRI
virtual unsigned getNumMicroOps(const InstrItineraryData *ItinData, const MachineInstr &MI) const
Return the number of u-operations the given machine instruction will be decoded to on the target cpu.
virtual const TargetRegisterClass * getRegClass(const MCInstrDesc &MCID, unsigned OpNum) const
Given a machine instruction descriptor, returns the register class constraint for OpNum,...
virtual int getSPAdjust(const MachineInstr &MI) const
Returns the actual stack pointer adjustment made by an instruction as part of a call sequence.
virtual void ReplaceTailWithBranchTo(MachineBasicBlock::iterator Tail, MachineBasicBlock *NewDest) const
Delete the instruction OldInst and everything after it, replacing it with an unconditional branch to ...
virtual bool PredicateInstruction(MachineInstr &MI, ArrayRef< MachineOperand > Pred) const
Convert the instruction into a predicated instruction.
int16_t getOpRegClassID(const MCOperandInfo &OpInfo) const
bool areOpcodesEqualOrInverse(unsigned Opcode1, unsigned Opcode2) const
Return true when \P Opcode1 or its inversion is equal to \P Opcode2.
virtual outliner::InstrType getOutliningTypeImpl(const MachineModuleInfo &MMI, MachineBasicBlock::iterator &MIT, unsigned Flags) const
Target-dependent implementation for getOutliningTypeImpl.
virtual bool getInsertSubregLikeInputs(const MachineInstr &MI, unsigned DefIdx, RegSubRegPair &BaseReg, RegSubRegPairAndIdx &InsertedReg) const
Target-dependent implementation of getInsertSubregInputs.
outliner::InstrType getOutliningType(const MachineModuleInfo &MMI, MachineBasicBlock::iterator &MIT, unsigned Flags) const
Returns how or if MIT should be outlined.
virtual bool isThroughputPattern(unsigned Pattern) const
Return true when a code sequence can improve throughput.
bool getAccumulatorReassociationPatterns(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns) const
Find chains of accumulations that can be rewritten as a tree for increased ILP.
virtual std::pair< unsigned, unsigned > getPatchpointUnfoldableRange(const MachineInstr &MI) const
For a patchpoint, stackmap, or statepoint intrinsic, return the range of operands which can't be fold...
virtual bool findCommutedOpIndices(const MachineInstr &MI, unsigned &SrcOpIdx1, unsigned &SrcOpIdx2) const
Returns true iff the routine could find two commutable operands in the given machine instruction.
virtual void mergeOutliningCandidateAttributes(Function &F, std::vector< outliner::Candidate > &Candidates) const
Optional target hook to create the LLVM IR attributes for the outlined function.
bool isUnpredicatedTerminator(const MachineInstr &MI) const
Returns true if the instruction is a terminator instruction that has not been predicated.
virtual void insertNoop(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const
Insert a noop into the instruction stream at the specified point.
void getAccumulatorChain(MachineInstr *CurrentInstr, SmallVectorImpl< Register > &Chain) const
Find the chain of accumulator instructions in \P MBB and return them in \P Chain.
bool isFrameInstr(const MachineInstr &I) const
Returns true if the argument is a frame pseudo instruction.
virtual bool getRegSequenceLikeInputs(const MachineInstr &MI, unsigned DefIdx, SmallVectorImpl< RegSubRegPairAndIdx > &InputRegs) const
Target-dependent implementation of getRegSequenceInputs.
unsigned defaultDefLatency(const TargetSubtargetInfo &STI, const MCSchedModel &SchedModel, const MachineInstr &DefMI) const
Return the default expected latency for a def based on its opcode.
virtual bool getStackSlotRange(const TargetRegisterClass *RC, unsigned SubIdx, unsigned &Size, unsigned &Offset, const MachineFunction &MF) const
Compute the size in bytes and offset within a stack slot of a spilled register or subregister.
virtual ScheduleHazardRecognizer * CreateTargetMIHazardRecognizer(const InstrItineraryData *, const ScheduleDAGMI *DAG) const
Allocate and return a hazard recognizer to use for this target when scheduling the machine instructio...
virtual bool hasStoreToStackSlot(const MachineInstr &MI, SmallVectorImpl< const MachineMemOperand * > &Accesses) const
If the specified machine instruction has a store to a stack slot, return true along with the FrameInd...
virtual bool hasReassociableOperands(const MachineInstr &Inst, const MachineBasicBlock *MBB) const
Return true when \P Inst has reassociable operands in the same \P MBB.
virtual void storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, Register VReg, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const
Store the specified register of the given register class to the specified stack frame index.
virtual void genAlternativeCodeSequence(MachineInstr &Root, unsigned Pattern, SmallVectorImpl< MachineInstr * > &InsInstrs, SmallVectorImpl< MachineInstr * > &DelInstrs, DenseMap< Register, unsigned > &InstIdxForVirtReg) const
When getMachineCombinerPatterns() finds patterns, this function generates the instructions that could...
virtual std::optional< ParamLoadedValue > describeLoadedValue(const MachineInstr &MI, Register Reg) const
Produce the expression describing the MI loading a value into the physical register Reg.
virtual unsigned getReduceOpcodeForAccumulator(unsigned int AccumulatorOpCode) const
Returns the opcode that should be use to reduce accumulation registers.
virtual Register isLoadFromStackSlot(const MachineInstr &MI, int &FrameIndex) const
If the specified machine instruction is a direct load from a stack slot, return the virtual or physic...
virtual ScheduleHazardRecognizer * CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI, const ScheduleDAG *DAG) const
Allocate and return a hazard recognizer to use for this target when scheduling the machine instructio...
virtual MachineInstr * optimizeLoadInstr(MachineInstr &MI, const MachineRegisterInfo *MRI, Register &FoldAsLoadDefReg, MachineInstr *&DefMI, MachineInstr *&CopyMI) const
Try to remove the load by folding it to a register operand at the use.
TargetInstrInfo(const TargetRegisterInfo &TRI, unsigned CFSetupOpcode=~0u, unsigned CFDestroyOpcode=~0u, unsigned CatchRetOpcode=~0u, unsigned ReturnOpcode=~0u, const int16_t *const RegClassByHwModeTable=nullptr)
virtual unsigned insertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB, ArrayRef< MachineOperand > Cond, const DebugLoc &DL, int *BytesAdded=nullptr) const
Insert branch code into the end of the specified MachineBasicBlock.
virtual void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const DebugLoc &DL, Register DestReg, Register SrcReg, bool KillSrc, bool RenamableDest=false, bool RenamableSrc=false) const
Emit instructions to copy a pair of physical registers.
virtual unsigned getAccumulationStartOpcode(unsigned Opcode) const
Returns an opcode which defines the accumulator used by \P Opcode.
unsigned getCallFrameSetupOpcode() const
These methods return the opcode of the frame setup/destroy instructions if they exist (-1 otherwise).
virtual bool getMachineCombinerPatterns(MachineInstr &Root, SmallVectorImpl< unsigned > &Patterns, bool DoRegPressureReduce) const
Return true when there is potentially a faster code sequence for an instruction chain ending in Root.
virtual bool isReMaterializableImpl(const MachineInstr &MI) const
For instructions with opcodes for which the M_REMATERIALIZABLE flag is set, this hook lets the target...
virtual MCInst getNop() const
Return the noop instruction to use for a noop.
unsigned getCallFrameSizeAt(MachineInstr &MI) const
virtual MachineInstr & duplicate(MachineBasicBlock &MBB, MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) const
Clones instruction or the whole instruction bundle Orig and insert into MBB before InsertBefore.
virtual std::string createMIROperandComment(const MachineInstr &MI, const MachineOperand &Op, unsigned OpIdx) const
std::pair< unsigned, unsigned > getReassociationOpcodes(unsigned Pattern, const MachineInstr &Root, const MachineInstr &Prev) const
Reassociation of some instructions requires inverse operations (e.g.
virtual bool isFunctionSafeToOutlineFrom(MachineFunction &MF, bool OutlineFromLinkOnceODRs) const
Return true if the function can safely be outlined from.
unsigned getInstBundleSize(const MachineInstr &MI) const
Sum the sizes of instructions inside of a BUNDLE, by calling getInstSizeInBytes on each.
virtual bool isMBBSafeToOutlineFrom(MachineBasicBlock &MBB, unsigned &Flags) const
Optional target hook that returns true if MBB is safe to outline from, and returns any target-specifi...
virtual void getReassociateOperandIndices(const MachineInstr &Root, unsigned Pattern, std::array< unsigned, 5 > &OperandIndices) const
The returned array encodes the operand index for each parameter because the operands may be commuted;...
virtual bool supportsSectionAwareOutlining() const
Return true if the target supports outlining candidates from multiple input sections in one pass.
virtual bool getMemOperandsWithOffsetWidth(const MachineInstr &MI, SmallVectorImpl< const MachineOperand * > &BaseOps, int64_t &Offset, bool &OffsetIsScalable, LocationSize &Width) const
Get zero or more base operands and the byte offset of an instruction that reads/writes memory.
int64_t getFrameTotalSize(const MachineInstr &I) const
Returns the total frame size, which is made up of the space set up inside the pair of frame start-sto...
MachineInstr * commuteInstruction(MachineInstr &MI, bool NewMI=false, unsigned OpIdx1=CommuteAnyOperandIndex, unsigned OpIdx2=CommuteAnyOperandIndex) const
This method commutes the operands of the given machine instruction MI.
virtual std::optional< unsigned > getOperandLatency(const InstrItineraryData *ItinData, SDNode *DefNode, unsigned DefIdx, SDNode *UseNode, unsigned UseIdx) const
virtual bool isAssociativeAndCommutative(const MachineInstr &Inst, bool Invert=false) const
Return true when \P Inst is both associative and commutative.
virtual void reMaterialize(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register DestReg, unsigned SubIdx, const MachineInstr &Orig, LaneBitmask UsedLanes=LaneBitmask::getAll()) const
Re-issue the specified 'original' instruction at the specific location targeting a new destination re...
void reassociateOps(MachineInstr &Root, MachineInstr &Prev, unsigned Pattern, SmallVectorImpl< MachineInstr * > &InsInstrs, SmallVectorImpl< MachineInstr * > &DelInstrs, ArrayRef< unsigned > OperandIndices, DenseMap< Register, unsigned > &InstrIdxForVirtReg) const
Attempt to reassociate \P Root and \P Prev according to \P Pattern to reduce critical path length.
virtual std::optional< unsigned > getInverseOpcode(unsigned Opcode) const
Return the inverse operation opcode if it exists for \P Opcode (e.g.
virtual void insertNoops(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned Quantity) const
Insert noops into the instruction stream at the specified point.
unsigned getCallFrameDestroyOpcode() const
int64_t getFrameSize(const MachineInstr &I) const
Returns size of the frame associated with the given frame instruction.
virtual bool isPredicated(const MachineInstr &MI) const
Returns true if the instruction is already predicated.
bool getInsertSubregInputs(const MachineInstr &MI, unsigned DefIdx, RegSubRegPair &BaseReg, RegSubRegPairAndIdx &InsertedReg) const
Build the equivalent inputs of a INSERT_SUBREG for the given MI and DefIdx.
virtual ~TargetInstrInfo()
virtual unsigned getInstrLatency(const InstrItineraryData *ItinData, const MachineInstr &MI, unsigned *PredCost=nullptr) const
Compute the instruction latency of a given instruction.
virtual bool produceSameValue(const MachineInstr &MI0, const MachineInstr &MI1, const MachineRegisterInfo *MRI=nullptr) const
Return true if two machine instructions would produce identical values.
virtual bool isAccumulationOpcode(unsigned Opcode) const
Return true when \P OpCode is an instruction which performs accumulation into one of its operand regi...
std::optional< DestSourcePair > isCopyInstr(const MachineInstr &MI) const
If the specific machine instruction is a instruction that moves/copies value from one register to ano...
bool isReassociationCandidate(const MachineInstr &Inst, bool &Commuted) const
Return true if the input \P Inst is part of a chain of dependent ops that are suitable for reassociat...
virtual MachineInstr * foldMemoryOperandImpl(MachineFunction &MF, MachineInstr &MI, ArrayRef< unsigned > Ops, int FrameIndex, MachineInstr *&CopyMI, LiveIntervals *LIS=nullptr, VirtRegMap *VRM=nullptr) const
Target-dependent implementation for foldMemoryOperand.
void reduceAccumulatorTree(SmallVectorImpl< Register > &RegistersToReduce, SmallVectorImpl< MachineInstr * > &InsInstrs, MachineFunction &MF, MachineInstr &Root, MachineRegisterInfo &MRI, DenseMap< Register, unsigned > &InstrIdxForVirtReg, Register ResultReg) const
Reduces branches of the accumulator tree into a single register.
virtual bool isSchedulingBoundary(const MachineInstr &MI, const MachineBasicBlock *MBB, const MachineFunction &MF) const
Test if the given instruction should be considered a scheduling boundary.
virtual unsigned getInstSizeInBytes(const MachineInstr &MI) const
Returns the size in bytes of the specified MachineInstr, or ~0U when this function is not implemented...
virtual unsigned getPredicationCost(const MachineInstr &MI) const
virtual void loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, Register DestReg, int FrameIndex, const TargetRegisterClass *RC, Register VReg, unsigned SubReg=0, MachineInstr::MIFlag Flags=MachineInstr::NoFlags) const
Load the specified register of the given register class from the specified stack frame index.
MachineInstr * foldMemoryOperand(MachineInstr &MI, ArrayRef< unsigned > Ops, int FI, MachineInstr *&CopyMI, LiveIntervals *LIS=nullptr, VirtRegMap *VRM=nullptr) const
Attempt to fold a load or store of the specified stack slot into the specified machine instruction fo...
bool getMemOperandWithOffset(const MachineInstr &MI, const MachineOperand *&BaseOp, int64_t &Offset, bool &OffsetIsScalable) const
Get the base operand and byte offset of an instruction that reads/writes memory.
virtual CombinerObjective getCombinerObjective(unsigned Pattern) const
Return the objective of a combiner pattern.
virtual MachineInstr * commuteInstructionImpl(MachineInstr &MI, bool NewMI, unsigned OpIdx1, unsigned OpIdx2) const
This method commutes the operands of the given machine instruction MI.
virtual bool isFunctionSafeToSplit(const MachineFunction &MF) const
Return true if the function is a viable candidate for machine function splitting.
void lowerCopy(MachineInstr *MI) const
This function defines the logic to lower COPY instruction to target specific instruction(s).
virtual MachineTraceStrategy getMachineCombinerTraceStrategy() const
Return a strategy that MachineCombiner must use when creating traces.
bool getRegSequenceInputs(const MachineInstr &MI, unsigned DefIdx, SmallVectorImpl< RegSubRegPairAndIdx > &InputRegs) const
Build the equivalent inputs of a REG_SEQUENCE for the given MI and DefIdx.
virtual bool hasLoadFromStackSlot(const MachineInstr &MI, SmallVectorImpl< const MachineMemOperand * > &Accesses) const
If the specified machine instruction has a load from a stack slot, return true along with the FrameIn...
virtual bool isGlobalMemoryObject(const MachineInstr *MI) const
Returns true if MI is an instruction we are unable to reason about (like a call or something with unm...
virtual std::optional< RegImmPair > isAddImmediate(const MachineInstr &MI, Register Reg) const
If the specific machine instruction is an instruction that adds an immediate value and a register,...
static const unsigned CommuteAnyOperandIndex
virtual bool hasReassociableSibling(const MachineInstr &Inst, bool &Commuted) const
Return true when \P Inst has reassociable sibling.
virtual bool isHighLatencyDef(int opc) const
Return true if this opcode has high latency to its result.
static bool fixCommutedOpIndices(unsigned &ResultIdx1, unsigned &ResultIdx2, unsigned CommutableOpIdx1, unsigned CommutableOpIdx2)
Assigns the (CommutableOpIdx1, CommutableOpIdx2) pair of commutable operand indices to (ResultIdx1,...
bool getExtractSubregInputs(const MachineInstr &MI, unsigned DefIdx, RegSubRegPairAndIdx &InputReg) const
Build the equivalent inputs of a EXTRACT_SUBREG for the given MI and DefIdx.
virtual bool getExtractSubregLikeInputs(const MachineInstr &MI, unsigned DefIdx, RegSubRegPairAndIdx &InputReg) const
Target-dependent implementation of getExtractSubregInputs.
bool usePreRAHazardRecognizer() const
Provide a global flag for disabling the PreRA hazard recognizer that targets may choose to honor.
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Provide an instruction scheduling machine model to CodeGen passes.
LLVM_ABI void init(const TargetSubtargetInfo *TSInfo, bool EnableSModel=true, bool EnableSItins=true)
Initialize the machine model for instruction scheduling.
LLVM_ABI unsigned computeOperandLatency(const MachineInstr *DefMI, unsigned DefOperIdx, const MachineInstr *UseMI, unsigned UseOperIdx) const
Compute operand latency based on the available machine model.
bool hasInstrSchedModelOrItineraries() const
Return true if this machine model includes an instruction-level scheduling model or cycle-to-cycle it...
const InstrItineraryData * getInstrItineraries() const
TargetSubtargetInfo - Generic base class for all target subtargets.
virtual unsigned getLoadLatency() const
Return the expected latency of load instructions.
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetLowering * getTargetLowering() const
bool isOSDarwin() const
Is this a "Darwin" OS (macOS, iOS, tvOS, watchOS, DriverKit, XROS, or bridgeOS).
Definition Triple.h:727
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
A raw_ostream that writes to an std::string.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
initializer< Ty > init(const Ty &Val)
InstrType
Represents how an instruction should be mapped by the outliner.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
MachineTraceStrategy
Strategies for selecting traces.
@ TS_MinInstrCount
Select the trace through a block that has the fewest instructions.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
@ Define
Register definition.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
InterleavedRange< Range > interleaved(const Range &R, StringRef Separator=", ", StringRef Prefix="", StringRef Suffix="")
Output range R as a sequence of interleaved elements.
constexpr from_range_t from_range
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
MachineInstr * getImm(const MachineOperand &MO, const MachineRegisterInfo *MRI)
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
CombinerObjective
The combiner's goal may differ based on which pattern it is attempting to optimize.
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
LLVM_ABI VirtRegInfo AnalyzeVirtRegInBundle(MachineInstr &MI, Register Reg, SmallVectorImpl< std::pair< MachineInstr *, unsigned > > *Ops=nullptr)
AnalyzeVirtRegInBundle - Analyze how the current instruction or bundle uses a virtual register.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
@ Add
Sum of integers.
DWARFExpression::Operation Op
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
bool isSpace(char C)
Checks whether character C is whitespace in the "C" locale.
std::pair< MachineOperand, DIExpression * > ParamLoadedValue
IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp=true)
Decrement It, then continue decrementing it while it points to a debug instruction.
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
Machine model for scheduling, bundling, and heuristics.
Definition MCSchedule.h:268
static LLVM_ABI MachinePointerInfo getFixedStack(MachineFunction &MF, int FI, int64_t Offset=0)
Return a MachinePointerInfo record that refers to the specified FrameIndex.
Link of an FP accumulation chain, see MachineCombinerPattern::FMA_CHAIN.
A pair composed of a pair of a register and a sub-register index, and another sub-register index.
A pair composed of a register and a sub-register index.
VirtRegInfo - Information about a virtual register used by a set of operands.
bool Reads
Reads - One of the operands read the virtual register.
bool Writes
Writes - One of the operands writes the virtual register.
An individual sequence of instructions to be replaced with a call to an outlined function.
MachineFunction * getMF() const