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