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