Recommit r373598 "[yaml2obj/obj2yaml] - Add support for SHT_LLVM_ADDRSIG sections."
[llvm-complete.git] / lib / CodeGen / MachineOperand.cpp
blob8eccfb85a9461869fcd808a7294f0e1fb5c1ed60
1 //===- lib/CodeGen/MachineOperand.cpp -------------------------------------===//
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 /// \file Methods common to all machine operands.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/CodeGen/MachineOperand.h"
14 #include "llvm/ADT/StringExtras.h"
15 #include "llvm/Analysis/Loads.h"
16 #include "llvm/Analysis/MemoryLocation.h"
17 #include "llvm/CodeGen/MIRPrinter.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineJumpTableInfo.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/TargetInstrInfo.h"
22 #include "llvm/CodeGen/TargetRegisterInfo.h"
23 #include "llvm/Config/llvm-config.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/IRPrintingPasses.h"
26 #include "llvm/IR/ModuleSlotTracker.h"
27 #include "llvm/MC/MCDwarf.h"
28 #include "llvm/Target/TargetIntrinsicInfo.h"
29 #include "llvm/Target/TargetMachine.h"
31 using namespace llvm;
33 static cl::opt<int>
34 PrintRegMaskNumRegs("print-regmask-num-regs",
35 cl::desc("Number of registers to limit to when "
36 "printing regmask operands in IR dumps. "
37 "unlimited = -1"),
38 cl::init(32), cl::Hidden);
40 static const MachineFunction *getMFIfAvailable(const MachineOperand &MO) {
41 if (const MachineInstr *MI = MO.getParent())
42 if (const MachineBasicBlock *MBB = MI->getParent())
43 if (const MachineFunction *MF = MBB->getParent())
44 return MF;
45 return nullptr;
47 static MachineFunction *getMFIfAvailable(MachineOperand &MO) {
48 return const_cast<MachineFunction *>(
49 getMFIfAvailable(const_cast<const MachineOperand &>(MO)));
52 void MachineOperand::setReg(Register Reg) {
53 if (getReg() == Reg)
54 return; // No change.
56 // Clear the IsRenamable bit to keep it conservatively correct.
57 IsRenamable = false;
59 // Otherwise, we have to change the register. If this operand is embedded
60 // into a machine function, we need to update the old and new register's
61 // use/def lists.
62 if (MachineFunction *MF = getMFIfAvailable(*this)) {
63 MachineRegisterInfo &MRI = MF->getRegInfo();
64 MRI.removeRegOperandFromUseList(this);
65 SmallContents.RegNo = Reg;
66 MRI.addRegOperandToUseList(this);
67 return;
70 // Otherwise, just change the register, no problem. :)
71 SmallContents.RegNo = Reg;
74 void MachineOperand::substVirtReg(Register Reg, unsigned SubIdx,
75 const TargetRegisterInfo &TRI) {
76 assert(Reg.isVirtual());
77 if (SubIdx && getSubReg())
78 SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
79 setReg(Reg);
80 if (SubIdx)
81 setSubReg(SubIdx);
84 void MachineOperand::substPhysReg(MCRegister Reg, const TargetRegisterInfo &TRI) {
85 assert(Reg.isPhysical());
86 if (getSubReg()) {
87 Reg = TRI.getSubReg(Reg, getSubReg());
88 // Note that getSubReg() may return 0 if the sub-register doesn't exist.
89 // That won't happen in legal code.
90 setSubReg(0);
91 if (isDef())
92 setIsUndef(false);
94 setReg(Reg);
97 /// Change a def to a use, or a use to a def.
98 void MachineOperand::setIsDef(bool Val) {
99 assert(isReg() && "Wrong MachineOperand accessor");
100 assert((!Val || !isDebug()) && "Marking a debug operation as def");
101 if (IsDef == Val)
102 return;
103 assert(!IsDeadOrKill && "Changing def/use with dead/kill set not supported");
104 // MRI may keep uses and defs in different list positions.
105 if (MachineFunction *MF = getMFIfAvailable(*this)) {
106 MachineRegisterInfo &MRI = MF->getRegInfo();
107 MRI.removeRegOperandFromUseList(this);
108 IsDef = Val;
109 MRI.addRegOperandToUseList(this);
110 return;
112 IsDef = Val;
115 bool MachineOperand::isRenamable() const {
116 assert(isReg() && "Wrong MachineOperand accessor");
117 assert(Register::isPhysicalRegister(getReg()) &&
118 "isRenamable should only be checked on physical registers");
119 if (!IsRenamable)
120 return false;
122 const MachineInstr *MI = getParent();
123 if (!MI)
124 return true;
126 if (isDef())
127 return !MI->hasExtraDefRegAllocReq(MachineInstr::IgnoreBundle);
129 assert(isUse() && "Reg is not def or use");
130 return !MI->hasExtraSrcRegAllocReq(MachineInstr::IgnoreBundle);
133 void MachineOperand::setIsRenamable(bool Val) {
134 assert(isReg() && "Wrong MachineOperand accessor");
135 assert(Register::isPhysicalRegister(getReg()) &&
136 "setIsRenamable should only be called on physical registers");
137 IsRenamable = Val;
140 // If this operand is currently a register operand, and if this is in a
141 // function, deregister the operand from the register's use/def list.
142 void MachineOperand::removeRegFromUses() {
143 if (!isReg() || !isOnRegUseList())
144 return;
146 if (MachineFunction *MF = getMFIfAvailable(*this))
147 MF->getRegInfo().removeRegOperandFromUseList(this);
150 /// ChangeToImmediate - Replace this operand with a new immediate operand of
151 /// the specified value. If an operand is known to be an immediate already,
152 /// the setImm method should be used.
153 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
154 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
156 removeRegFromUses();
158 OpKind = MO_Immediate;
159 Contents.ImmVal = ImmVal;
162 void MachineOperand::ChangeToFPImmediate(const ConstantFP *FPImm) {
163 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
165 removeRegFromUses();
167 OpKind = MO_FPImmediate;
168 Contents.CFP = FPImm;
171 void MachineOperand::ChangeToES(const char *SymName,
172 unsigned TargetFlags) {
173 assert((!isReg() || !isTied()) &&
174 "Cannot change a tied operand into an external symbol");
176 removeRegFromUses();
178 OpKind = MO_ExternalSymbol;
179 Contents.OffsetedInfo.Val.SymbolName = SymName;
180 setOffset(0); // Offset is always 0.
181 setTargetFlags(TargetFlags);
184 void MachineOperand::ChangeToGA(const GlobalValue *GV, int64_t Offset,
185 unsigned TargetFlags) {
186 assert((!isReg() || !isTied()) &&
187 "Cannot change a tied operand into a global address");
189 removeRegFromUses();
191 OpKind = MO_GlobalAddress;
192 Contents.OffsetedInfo.Val.GV = GV;
193 setOffset(Offset);
194 setTargetFlags(TargetFlags);
197 void MachineOperand::ChangeToMCSymbol(MCSymbol *Sym) {
198 assert((!isReg() || !isTied()) &&
199 "Cannot change a tied operand into an MCSymbol");
201 removeRegFromUses();
203 OpKind = MO_MCSymbol;
204 Contents.Sym = Sym;
207 void MachineOperand::ChangeToFrameIndex(int Idx) {
208 assert((!isReg() || !isTied()) &&
209 "Cannot change a tied operand into a FrameIndex");
211 removeRegFromUses();
213 OpKind = MO_FrameIndex;
214 setIndex(Idx);
217 void MachineOperand::ChangeToTargetIndex(unsigned Idx, int64_t Offset,
218 unsigned TargetFlags) {
219 assert((!isReg() || !isTied()) &&
220 "Cannot change a tied operand into a FrameIndex");
222 removeRegFromUses();
224 OpKind = MO_TargetIndex;
225 setIndex(Idx);
226 setOffset(Offset);
227 setTargetFlags(TargetFlags);
230 /// ChangeToRegister - Replace this operand with a new register operand of
231 /// the specified value. If an operand is known to be an register already,
232 /// the setReg method should be used.
233 void MachineOperand::ChangeToRegister(Register Reg, bool isDef, bool isImp,
234 bool isKill, bool isDead, bool isUndef,
235 bool isDebug) {
236 MachineRegisterInfo *RegInfo = nullptr;
237 if (MachineFunction *MF = getMFIfAvailable(*this))
238 RegInfo = &MF->getRegInfo();
239 // If this operand is already a register operand, remove it from the
240 // register's use/def lists.
241 bool WasReg = isReg();
242 if (RegInfo && WasReg)
243 RegInfo->removeRegOperandFromUseList(this);
245 // Change this to a register and set the reg#.
246 assert(!(isDead && !isDef) && "Dead flag on non-def");
247 assert(!(isKill && isDef) && "Kill flag on def");
248 OpKind = MO_Register;
249 SmallContents.RegNo = Reg;
250 SubReg_TargetFlags = 0;
251 IsDef = isDef;
252 IsImp = isImp;
253 IsDeadOrKill = isKill | isDead;
254 IsRenamable = false;
255 IsUndef = isUndef;
256 IsInternalRead = false;
257 IsEarlyClobber = false;
258 IsDebug = isDebug;
259 // Ensure isOnRegUseList() returns false.
260 Contents.Reg.Prev = nullptr;
261 // Preserve the tie when the operand was already a register.
262 if (!WasReg)
263 TiedTo = 0;
265 // If this operand is embedded in a function, add the operand to the
266 // register's use/def list.
267 if (RegInfo)
268 RegInfo->addRegOperandToUseList(this);
271 /// isIdenticalTo - Return true if this operand is identical to the specified
272 /// operand. Note that this should stay in sync with the hash_value overload
273 /// below.
274 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
275 if (getType() != Other.getType() ||
276 getTargetFlags() != Other.getTargetFlags())
277 return false;
279 switch (getType()) {
280 case MachineOperand::MO_Register:
281 return getReg() == Other.getReg() && isDef() == Other.isDef() &&
282 getSubReg() == Other.getSubReg();
283 case MachineOperand::MO_Immediate:
284 return getImm() == Other.getImm();
285 case MachineOperand::MO_CImmediate:
286 return getCImm() == Other.getCImm();
287 case MachineOperand::MO_FPImmediate:
288 return getFPImm() == Other.getFPImm();
289 case MachineOperand::MO_MachineBasicBlock:
290 return getMBB() == Other.getMBB();
291 case MachineOperand::MO_FrameIndex:
292 return getIndex() == Other.getIndex();
293 case MachineOperand::MO_ConstantPoolIndex:
294 case MachineOperand::MO_TargetIndex:
295 return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
296 case MachineOperand::MO_JumpTableIndex:
297 return getIndex() == Other.getIndex();
298 case MachineOperand::MO_GlobalAddress:
299 return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
300 case MachineOperand::MO_ExternalSymbol:
301 return strcmp(getSymbolName(), Other.getSymbolName()) == 0 &&
302 getOffset() == Other.getOffset();
303 case MachineOperand::MO_BlockAddress:
304 return getBlockAddress() == Other.getBlockAddress() &&
305 getOffset() == Other.getOffset();
306 case MachineOperand::MO_RegisterMask:
307 case MachineOperand::MO_RegisterLiveOut: {
308 // Shallow compare of the two RegMasks
309 const uint32_t *RegMask = getRegMask();
310 const uint32_t *OtherRegMask = Other.getRegMask();
311 if (RegMask == OtherRegMask)
312 return true;
314 if (const MachineFunction *MF = getMFIfAvailable(*this)) {
315 // Calculate the size of the RegMask
316 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
317 unsigned RegMaskSize = (TRI->getNumRegs() + 31) / 32;
319 // Deep compare of the two RegMasks
320 return std::equal(RegMask, RegMask + RegMaskSize, OtherRegMask);
322 // We don't know the size of the RegMask, so we can't deep compare the two
323 // reg masks.
324 return false;
326 case MachineOperand::MO_MCSymbol:
327 return getMCSymbol() == Other.getMCSymbol();
328 case MachineOperand::MO_CFIIndex:
329 return getCFIIndex() == Other.getCFIIndex();
330 case MachineOperand::MO_Metadata:
331 return getMetadata() == Other.getMetadata();
332 case MachineOperand::MO_IntrinsicID:
333 return getIntrinsicID() == Other.getIntrinsicID();
334 case MachineOperand::MO_Predicate:
335 return getPredicate() == Other.getPredicate();
336 case MachineOperand::MO_ShuffleMask:
337 return getShuffleMask() == Other.getShuffleMask();
339 llvm_unreachable("Invalid machine operand type");
342 // Note: this must stay exactly in sync with isIdenticalTo above.
343 hash_code llvm::hash_value(const MachineOperand &MO) {
344 switch (MO.getType()) {
345 case MachineOperand::MO_Register:
346 // Register operands don't have target flags.
347 return hash_combine(MO.getType(), (unsigned)MO.getReg(), MO.getSubReg(), MO.isDef());
348 case MachineOperand::MO_Immediate:
349 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
350 case MachineOperand::MO_CImmediate:
351 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
352 case MachineOperand::MO_FPImmediate:
353 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
354 case MachineOperand::MO_MachineBasicBlock:
355 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
356 case MachineOperand::MO_FrameIndex:
357 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
358 case MachineOperand::MO_ConstantPoolIndex:
359 case MachineOperand::MO_TargetIndex:
360 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
361 MO.getOffset());
362 case MachineOperand::MO_JumpTableIndex:
363 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
364 case MachineOperand::MO_ExternalSymbol:
365 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
366 StringRef(MO.getSymbolName()));
367 case MachineOperand::MO_GlobalAddress:
368 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
369 MO.getOffset());
370 case MachineOperand::MO_BlockAddress:
371 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getBlockAddress(),
372 MO.getOffset());
373 case MachineOperand::MO_RegisterMask:
374 case MachineOperand::MO_RegisterLiveOut:
375 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
376 case MachineOperand::MO_Metadata:
377 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
378 case MachineOperand::MO_MCSymbol:
379 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
380 case MachineOperand::MO_CFIIndex:
381 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCFIIndex());
382 case MachineOperand::MO_IntrinsicID:
383 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIntrinsicID());
384 case MachineOperand::MO_Predicate:
385 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getPredicate());
386 case MachineOperand::MO_ShuffleMask:
387 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getShuffleMask());
389 llvm_unreachable("Invalid machine operand type");
392 // Try to crawl up to the machine function and get TRI and IntrinsicInfo from
393 // it.
394 static void tryToGetTargetInfo(const MachineOperand &MO,
395 const TargetRegisterInfo *&TRI,
396 const TargetIntrinsicInfo *&IntrinsicInfo) {
397 if (const MachineFunction *MF = getMFIfAvailable(MO)) {
398 TRI = MF->getSubtarget().getRegisterInfo();
399 IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
403 static const char *getTargetIndexName(const MachineFunction &MF, int Index) {
404 const auto *TII = MF.getSubtarget().getInstrInfo();
405 assert(TII && "expected instruction info");
406 auto Indices = TII->getSerializableTargetIndices();
407 auto Found = find_if(Indices, [&](const std::pair<int, const char *> &I) {
408 return I.first == Index;
410 if (Found != Indices.end())
411 return Found->second;
412 return nullptr;
415 static const char *getTargetFlagName(const TargetInstrInfo *TII, unsigned TF) {
416 auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
417 for (const auto &I : Flags) {
418 if (I.first == TF) {
419 return I.second;
422 return nullptr;
425 static void printCFIRegister(unsigned DwarfReg, raw_ostream &OS,
426 const TargetRegisterInfo *TRI) {
427 if (!TRI) {
428 OS << "%dwarfreg." << DwarfReg;
429 return;
432 if (Optional<unsigned> Reg = TRI->getLLVMRegNum(DwarfReg, true))
433 OS << printReg(*Reg, TRI);
434 else
435 OS << "<badreg>";
438 static void printIRBlockReference(raw_ostream &OS, const BasicBlock &BB,
439 ModuleSlotTracker &MST) {
440 OS << "%ir-block.";
441 if (BB.hasName()) {
442 printLLVMNameWithoutPrefix(OS, BB.getName());
443 return;
445 Optional<int> Slot;
446 if (const Function *F = BB.getParent()) {
447 if (F == MST.getCurrentFunction()) {
448 Slot = MST.getLocalSlot(&BB);
449 } else if (const Module *M = F->getParent()) {
450 ModuleSlotTracker CustomMST(M, /*ShouldInitializeAllMetadata=*/false);
451 CustomMST.incorporateFunction(*F);
452 Slot = CustomMST.getLocalSlot(&BB);
455 if (Slot)
456 MachineOperand::printIRSlotNumber(OS, *Slot);
457 else
458 OS << "<unknown>";
461 static void printIRValueReference(raw_ostream &OS, const Value &V,
462 ModuleSlotTracker &MST) {
463 if (isa<GlobalValue>(V)) {
464 V.printAsOperand(OS, /*PrintType=*/false, MST);
465 return;
467 if (isa<Constant>(V)) {
468 // Machine memory operands can load/store to/from constant value pointers.
469 OS << '`';
470 V.printAsOperand(OS, /*PrintType=*/true, MST);
471 OS << '`';
472 return;
474 OS << "%ir.";
475 if (V.hasName()) {
476 printLLVMNameWithoutPrefix(OS, V.getName());
477 return;
479 int Slot = MST.getCurrentFunction() ? MST.getLocalSlot(&V) : -1;
480 MachineOperand::printIRSlotNumber(OS, Slot);
483 static void printSyncScope(raw_ostream &OS, const LLVMContext &Context,
484 SyncScope::ID SSID,
485 SmallVectorImpl<StringRef> &SSNs) {
486 switch (SSID) {
487 case SyncScope::System:
488 break;
489 default:
490 if (SSNs.empty())
491 Context.getSyncScopeNames(SSNs);
493 OS << "syncscope(\"";
494 printEscapedString(SSNs[SSID], OS);
495 OS << "\") ";
496 break;
500 static const char *getTargetMMOFlagName(const TargetInstrInfo &TII,
501 unsigned TMMOFlag) {
502 auto Flags = TII.getSerializableMachineMemOperandTargetFlags();
503 for (const auto &I : Flags) {
504 if (I.first == TMMOFlag) {
505 return I.second;
508 return nullptr;
511 static void printFrameIndex(raw_ostream& OS, int FrameIndex, bool IsFixed,
512 const MachineFrameInfo *MFI) {
513 StringRef Name;
514 if (MFI) {
515 IsFixed = MFI->isFixedObjectIndex(FrameIndex);
516 if (const AllocaInst *Alloca = MFI->getObjectAllocation(FrameIndex))
517 if (Alloca->hasName())
518 Name = Alloca->getName();
519 if (IsFixed)
520 FrameIndex -= MFI->getObjectIndexBegin();
522 MachineOperand::printStackObjectReference(OS, FrameIndex, IsFixed, Name);
525 void MachineOperand::printSubRegIdx(raw_ostream &OS, uint64_t Index,
526 const TargetRegisterInfo *TRI) {
527 OS << "%subreg.";
528 if (TRI)
529 OS << TRI->getSubRegIndexName(Index);
530 else
531 OS << Index;
534 void MachineOperand::printTargetFlags(raw_ostream &OS,
535 const MachineOperand &Op) {
536 if (!Op.getTargetFlags())
537 return;
538 const MachineFunction *MF = getMFIfAvailable(Op);
539 if (!MF)
540 return;
542 const auto *TII = MF->getSubtarget().getInstrInfo();
543 assert(TII && "expected instruction info");
544 auto Flags = TII->decomposeMachineOperandsTargetFlags(Op.getTargetFlags());
545 OS << "target-flags(";
546 const bool HasDirectFlags = Flags.first;
547 const bool HasBitmaskFlags = Flags.second;
548 if (!HasDirectFlags && !HasBitmaskFlags) {
549 OS << "<unknown>) ";
550 return;
552 if (HasDirectFlags) {
553 if (const auto *Name = getTargetFlagName(TII, Flags.first))
554 OS << Name;
555 else
556 OS << "<unknown target flag>";
558 if (!HasBitmaskFlags) {
559 OS << ") ";
560 return;
562 bool IsCommaNeeded = HasDirectFlags;
563 unsigned BitMask = Flags.second;
564 auto BitMasks = TII->getSerializableBitmaskMachineOperandTargetFlags();
565 for (const auto &Mask : BitMasks) {
566 // Check if the flag's bitmask has the bits of the current mask set.
567 if ((BitMask & Mask.first) == Mask.first) {
568 if (IsCommaNeeded)
569 OS << ", ";
570 IsCommaNeeded = true;
571 OS << Mask.second;
572 // Clear the bits which were serialized from the flag's bitmask.
573 BitMask &= ~(Mask.first);
576 if (BitMask) {
577 // When the resulting flag's bitmask isn't zero, we know that we didn't
578 // serialize all of the bit flags.
579 if (IsCommaNeeded)
580 OS << ", ";
581 OS << "<unknown bitmask target flag>";
583 OS << ") ";
586 void MachineOperand::printSymbol(raw_ostream &OS, MCSymbol &Sym) {
587 OS << "<mcsymbol " << Sym << ">";
590 void MachineOperand::printStackObjectReference(raw_ostream &OS,
591 unsigned FrameIndex,
592 bool IsFixed, StringRef Name) {
593 if (IsFixed) {
594 OS << "%fixed-stack." << FrameIndex;
595 return;
598 OS << "%stack." << FrameIndex;
599 if (!Name.empty())
600 OS << '.' << Name;
603 void MachineOperand::printOperandOffset(raw_ostream &OS, int64_t Offset) {
604 if (Offset == 0)
605 return;
606 if (Offset < 0) {
607 OS << " - " << -Offset;
608 return;
610 OS << " + " << Offset;
613 void MachineOperand::printIRSlotNumber(raw_ostream &OS, int Slot) {
614 if (Slot == -1)
615 OS << "<badref>";
616 else
617 OS << Slot;
620 static void printCFI(raw_ostream &OS, const MCCFIInstruction &CFI,
621 const TargetRegisterInfo *TRI) {
622 switch (CFI.getOperation()) {
623 case MCCFIInstruction::OpSameValue:
624 OS << "same_value ";
625 if (MCSymbol *Label = CFI.getLabel())
626 MachineOperand::printSymbol(OS, *Label);
627 printCFIRegister(CFI.getRegister(), OS, TRI);
628 break;
629 case MCCFIInstruction::OpRememberState:
630 OS << "remember_state ";
631 if (MCSymbol *Label = CFI.getLabel())
632 MachineOperand::printSymbol(OS, *Label);
633 break;
634 case MCCFIInstruction::OpRestoreState:
635 OS << "restore_state ";
636 if (MCSymbol *Label = CFI.getLabel())
637 MachineOperand::printSymbol(OS, *Label);
638 break;
639 case MCCFIInstruction::OpOffset:
640 OS << "offset ";
641 if (MCSymbol *Label = CFI.getLabel())
642 MachineOperand::printSymbol(OS, *Label);
643 printCFIRegister(CFI.getRegister(), OS, TRI);
644 OS << ", " << CFI.getOffset();
645 break;
646 case MCCFIInstruction::OpDefCfaRegister:
647 OS << "def_cfa_register ";
648 if (MCSymbol *Label = CFI.getLabel())
649 MachineOperand::printSymbol(OS, *Label);
650 printCFIRegister(CFI.getRegister(), OS, TRI);
651 break;
652 case MCCFIInstruction::OpDefCfaOffset:
653 OS << "def_cfa_offset ";
654 if (MCSymbol *Label = CFI.getLabel())
655 MachineOperand::printSymbol(OS, *Label);
656 OS << CFI.getOffset();
657 break;
658 case MCCFIInstruction::OpDefCfa:
659 OS << "def_cfa ";
660 if (MCSymbol *Label = CFI.getLabel())
661 MachineOperand::printSymbol(OS, *Label);
662 printCFIRegister(CFI.getRegister(), OS, TRI);
663 OS << ", " << CFI.getOffset();
664 break;
665 case MCCFIInstruction::OpRelOffset:
666 OS << "rel_offset ";
667 if (MCSymbol *Label = CFI.getLabel())
668 MachineOperand::printSymbol(OS, *Label);
669 printCFIRegister(CFI.getRegister(), OS, TRI);
670 OS << ", " << CFI.getOffset();
671 break;
672 case MCCFIInstruction::OpAdjustCfaOffset:
673 OS << "adjust_cfa_offset ";
674 if (MCSymbol *Label = CFI.getLabel())
675 MachineOperand::printSymbol(OS, *Label);
676 OS << CFI.getOffset();
677 break;
678 case MCCFIInstruction::OpRestore:
679 OS << "restore ";
680 if (MCSymbol *Label = CFI.getLabel())
681 MachineOperand::printSymbol(OS, *Label);
682 printCFIRegister(CFI.getRegister(), OS, TRI);
683 break;
684 case MCCFIInstruction::OpEscape: {
685 OS << "escape ";
686 if (MCSymbol *Label = CFI.getLabel())
687 MachineOperand::printSymbol(OS, *Label);
688 if (!CFI.getValues().empty()) {
689 size_t e = CFI.getValues().size() - 1;
690 for (size_t i = 0; i < e; ++i)
691 OS << format("0x%02x", uint8_t(CFI.getValues()[i])) << ", ";
692 OS << format("0x%02x", uint8_t(CFI.getValues()[e])) << ", ";
694 break;
696 case MCCFIInstruction::OpUndefined:
697 OS << "undefined ";
698 if (MCSymbol *Label = CFI.getLabel())
699 MachineOperand::printSymbol(OS, *Label);
700 printCFIRegister(CFI.getRegister(), OS, TRI);
701 break;
702 case MCCFIInstruction::OpRegister:
703 OS << "register ";
704 if (MCSymbol *Label = CFI.getLabel())
705 MachineOperand::printSymbol(OS, *Label);
706 printCFIRegister(CFI.getRegister(), OS, TRI);
707 OS << ", ";
708 printCFIRegister(CFI.getRegister2(), OS, TRI);
709 break;
710 case MCCFIInstruction::OpWindowSave:
711 OS << "window_save ";
712 if (MCSymbol *Label = CFI.getLabel())
713 MachineOperand::printSymbol(OS, *Label);
714 break;
715 case MCCFIInstruction::OpNegateRAState:
716 OS << "negate_ra_sign_state ";
717 if (MCSymbol *Label = CFI.getLabel())
718 MachineOperand::printSymbol(OS, *Label);
719 break;
720 default:
721 // TODO: Print the other CFI Operations.
722 OS << "<unserializable cfi directive>";
723 break;
727 void MachineOperand::print(raw_ostream &OS, const TargetRegisterInfo *TRI,
728 const TargetIntrinsicInfo *IntrinsicInfo) const {
729 print(OS, LLT{}, TRI, IntrinsicInfo);
732 void MachineOperand::print(raw_ostream &OS, LLT TypeToPrint,
733 const TargetRegisterInfo *TRI,
734 const TargetIntrinsicInfo *IntrinsicInfo) const {
735 tryToGetTargetInfo(*this, TRI, IntrinsicInfo);
736 ModuleSlotTracker DummyMST(nullptr);
737 print(OS, DummyMST, TypeToPrint, /*PrintDef=*/false, /*IsStandalone=*/true,
738 /*ShouldPrintRegisterTies=*/true,
739 /*TiedOperandIdx=*/0, TRI, IntrinsicInfo);
742 void MachineOperand::print(raw_ostream &OS, ModuleSlotTracker &MST,
743 LLT TypeToPrint, bool PrintDef, bool IsStandalone,
744 bool ShouldPrintRegisterTies,
745 unsigned TiedOperandIdx,
746 const TargetRegisterInfo *TRI,
747 const TargetIntrinsicInfo *IntrinsicInfo) const {
748 printTargetFlags(OS, *this);
749 switch (getType()) {
750 case MachineOperand::MO_Register: {
751 Register Reg = getReg();
752 if (isImplicit())
753 OS << (isDef() ? "implicit-def " : "implicit ");
754 else if (PrintDef && isDef())
755 // Print the 'def' flag only when the operand is defined after '='.
756 OS << "def ";
757 if (isInternalRead())
758 OS << "internal ";
759 if (isDead())
760 OS << "dead ";
761 if (isKill())
762 OS << "killed ";
763 if (isUndef())
764 OS << "undef ";
765 if (isEarlyClobber())
766 OS << "early-clobber ";
767 if (Register::isPhysicalRegister(getReg()) && isRenamable())
768 OS << "renamable ";
769 // isDebug() is exactly true for register operands of a DBG_VALUE. So we
770 // simply infer it when parsing and do not need to print it.
772 const MachineRegisterInfo *MRI = nullptr;
773 if (Register::isVirtualRegister(Reg)) {
774 if (const MachineFunction *MF = getMFIfAvailable(*this)) {
775 MRI = &MF->getRegInfo();
779 OS << printReg(Reg, TRI, 0, MRI);
780 // Print the sub register.
781 if (unsigned SubReg = getSubReg()) {
782 if (TRI)
783 OS << '.' << TRI->getSubRegIndexName(SubReg);
784 else
785 OS << ".subreg" << SubReg;
787 // Print the register class / bank.
788 if (Register::isVirtualRegister(Reg)) {
789 if (const MachineFunction *MF = getMFIfAvailable(*this)) {
790 const MachineRegisterInfo &MRI = MF->getRegInfo();
791 if (IsStandalone || !PrintDef || MRI.def_empty(Reg)) {
792 OS << ':';
793 OS << printRegClassOrBank(Reg, MRI, TRI);
797 // Print ties.
798 if (ShouldPrintRegisterTies && isTied() && !isDef())
799 OS << "(tied-def " << TiedOperandIdx << ")";
800 // Print types.
801 if (TypeToPrint.isValid())
802 OS << '(' << TypeToPrint << ')';
803 break;
805 case MachineOperand::MO_Immediate:
806 OS << getImm();
807 break;
808 case MachineOperand::MO_CImmediate:
809 getCImm()->printAsOperand(OS, /*PrintType=*/true, MST);
810 break;
811 case MachineOperand::MO_FPImmediate:
812 getFPImm()->printAsOperand(OS, /*PrintType=*/true, MST);
813 break;
814 case MachineOperand::MO_MachineBasicBlock:
815 OS << printMBBReference(*getMBB());
816 break;
817 case MachineOperand::MO_FrameIndex: {
818 int FrameIndex = getIndex();
819 bool IsFixed = false;
820 const MachineFrameInfo *MFI = nullptr;
821 if (const MachineFunction *MF = getMFIfAvailable(*this))
822 MFI = &MF->getFrameInfo();
823 printFrameIndex(OS, FrameIndex, IsFixed, MFI);
824 break;
826 case MachineOperand::MO_ConstantPoolIndex:
827 OS << "%const." << getIndex();
828 printOperandOffset(OS, getOffset());
829 break;
830 case MachineOperand::MO_TargetIndex: {
831 OS << "target-index(";
832 const char *Name = "<unknown>";
833 if (const MachineFunction *MF = getMFIfAvailable(*this))
834 if (const auto *TargetIndexName = getTargetIndexName(*MF, getIndex()))
835 Name = TargetIndexName;
836 OS << Name << ')';
837 printOperandOffset(OS, getOffset());
838 break;
840 case MachineOperand::MO_JumpTableIndex:
841 OS << printJumpTableEntryReference(getIndex());
842 break;
843 case MachineOperand::MO_GlobalAddress:
844 getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
845 printOperandOffset(OS, getOffset());
846 break;
847 case MachineOperand::MO_ExternalSymbol: {
848 StringRef Name = getSymbolName();
849 OS << '&';
850 if (Name.empty()) {
851 OS << "\"\"";
852 } else {
853 printLLVMNameWithoutPrefix(OS, Name);
855 printOperandOffset(OS, getOffset());
856 break;
858 case MachineOperand::MO_BlockAddress: {
859 OS << "blockaddress(";
860 getBlockAddress()->getFunction()->printAsOperand(OS, /*PrintType=*/false,
861 MST);
862 OS << ", ";
863 printIRBlockReference(OS, *getBlockAddress()->getBasicBlock(), MST);
864 OS << ')';
865 MachineOperand::printOperandOffset(OS, getOffset());
866 break;
868 case MachineOperand::MO_RegisterMask: {
869 OS << "<regmask";
870 if (TRI) {
871 unsigned NumRegsInMask = 0;
872 unsigned NumRegsEmitted = 0;
873 for (unsigned i = 0; i < TRI->getNumRegs(); ++i) {
874 unsigned MaskWord = i / 32;
875 unsigned MaskBit = i % 32;
876 if (getRegMask()[MaskWord] & (1 << MaskBit)) {
877 if (PrintRegMaskNumRegs < 0 ||
878 NumRegsEmitted <= static_cast<unsigned>(PrintRegMaskNumRegs)) {
879 OS << " " << printReg(i, TRI);
880 NumRegsEmitted++;
882 NumRegsInMask++;
885 if (NumRegsEmitted != NumRegsInMask)
886 OS << " and " << (NumRegsInMask - NumRegsEmitted) << " more...";
887 } else {
888 OS << " ...";
890 OS << ">";
891 break;
893 case MachineOperand::MO_RegisterLiveOut: {
894 const uint32_t *RegMask = getRegLiveOut();
895 OS << "liveout(";
896 if (!TRI) {
897 OS << "<unknown>";
898 } else {
899 bool IsCommaNeeded = false;
900 for (unsigned Reg = 0, E = TRI->getNumRegs(); Reg < E; ++Reg) {
901 if (RegMask[Reg / 32] & (1U << (Reg % 32))) {
902 if (IsCommaNeeded)
903 OS << ", ";
904 OS << printReg(Reg, TRI);
905 IsCommaNeeded = true;
909 OS << ")";
910 break;
912 case MachineOperand::MO_Metadata:
913 getMetadata()->printAsOperand(OS, MST);
914 break;
915 case MachineOperand::MO_MCSymbol:
916 printSymbol(OS, *getMCSymbol());
917 break;
918 case MachineOperand::MO_CFIIndex: {
919 if (const MachineFunction *MF = getMFIfAvailable(*this))
920 printCFI(OS, MF->getFrameInstructions()[getCFIIndex()], TRI);
921 else
922 OS << "<cfi directive>";
923 break;
925 case MachineOperand::MO_IntrinsicID: {
926 Intrinsic::ID ID = getIntrinsicID();
927 if (ID < Intrinsic::num_intrinsics)
928 OS << "intrinsic(@" << Intrinsic::getName(ID, None) << ')';
929 else if (IntrinsicInfo)
930 OS << "intrinsic(@" << IntrinsicInfo->getName(ID) << ')';
931 else
932 OS << "intrinsic(" << ID << ')';
933 break;
935 case MachineOperand::MO_Predicate: {
936 auto Pred = static_cast<CmpInst::Predicate>(getPredicate());
937 OS << (CmpInst::isIntPredicate(Pred) ? "int" : "float") << "pred("
938 << CmpInst::getPredicateName(Pred) << ')';
939 break;
941 case MachineOperand::MO_ShuffleMask:
942 OS << "shufflemask(";
943 const Constant* C = getShuffleMask();
944 const int NumElts = C->getType()->getVectorNumElements();
946 StringRef Separator;
947 for (int I = 0; I != NumElts; ++I) {
948 OS << Separator;
949 C->getAggregateElement(I)->printAsOperand(OS, false, MST);
950 Separator = ", ";
953 OS << ')';
954 break;
958 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
959 LLVM_DUMP_METHOD void MachineOperand::dump() const { dbgs() << *this << '\n'; }
960 #endif
962 //===----------------------------------------------------------------------===//
963 // MachineMemOperand Implementation
964 //===----------------------------------------------------------------------===//
966 /// getAddrSpace - Return the LLVM IR address space number that this pointer
967 /// points into.
968 unsigned MachinePointerInfo::getAddrSpace() const { return AddrSpace; }
970 /// isDereferenceable - Return true if V is always dereferenceable for
971 /// Offset + Size byte.
972 bool MachinePointerInfo::isDereferenceable(unsigned Size, LLVMContext &C,
973 const DataLayout &DL) const {
974 if (!V.is<const Value *>())
975 return false;
977 const Value *BasePtr = V.get<const Value *>();
978 if (BasePtr == nullptr)
979 return false;
981 return isDereferenceableAndAlignedPointer(
982 BasePtr, 1, APInt(DL.getPointerSizeInBits(), Offset + Size), DL);
985 /// getConstantPool - Return a MachinePointerInfo record that refers to the
986 /// constant pool.
987 MachinePointerInfo MachinePointerInfo::getConstantPool(MachineFunction &MF) {
988 return MachinePointerInfo(MF.getPSVManager().getConstantPool());
991 /// getFixedStack - Return a MachinePointerInfo record that refers to the
992 /// the specified FrameIndex.
993 MachinePointerInfo MachinePointerInfo::getFixedStack(MachineFunction &MF,
994 int FI, int64_t Offset) {
995 return MachinePointerInfo(MF.getPSVManager().getFixedStack(FI), Offset);
998 MachinePointerInfo MachinePointerInfo::getJumpTable(MachineFunction &MF) {
999 return MachinePointerInfo(MF.getPSVManager().getJumpTable());
1002 MachinePointerInfo MachinePointerInfo::getGOT(MachineFunction &MF) {
1003 return MachinePointerInfo(MF.getPSVManager().getGOT());
1006 MachinePointerInfo MachinePointerInfo::getStack(MachineFunction &MF,
1007 int64_t Offset, uint8_t ID) {
1008 return MachinePointerInfo(MF.getPSVManager().getStack(), Offset, ID);
1011 MachinePointerInfo MachinePointerInfo::getUnknownStack(MachineFunction &MF) {
1012 return MachinePointerInfo(MF.getDataLayout().getAllocaAddrSpace());
1015 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, Flags f,
1016 uint64_t s, uint64_t a,
1017 const AAMDNodes &AAInfo,
1018 const MDNode *Ranges, SyncScope::ID SSID,
1019 AtomicOrdering Ordering,
1020 AtomicOrdering FailureOrdering)
1021 : PtrInfo(ptrinfo), Size(s), FlagVals(f), BaseAlignLog2(Log2_32(a) + 1),
1022 AAInfo(AAInfo), Ranges(Ranges) {
1023 assert((PtrInfo.V.isNull() || PtrInfo.V.is<const PseudoSourceValue *>() ||
1024 isa<PointerType>(PtrInfo.V.get<const Value *>()->getType())) &&
1025 "invalid pointer value");
1026 assert(getBaseAlignment() == a && a != 0 && "Alignment is not a power of 2!");
1027 assert((isLoad() || isStore()) && "Not a load/store!");
1029 AtomicInfo.SSID = static_cast<unsigned>(SSID);
1030 assert(getSyncScopeID() == SSID && "Value truncated");
1031 AtomicInfo.Ordering = static_cast<unsigned>(Ordering);
1032 assert(getOrdering() == Ordering && "Value truncated");
1033 AtomicInfo.FailureOrdering = static_cast<unsigned>(FailureOrdering);
1034 assert(getFailureOrdering() == FailureOrdering && "Value truncated");
1037 /// Profile - Gather unique data for the object.
1039 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
1040 ID.AddInteger(getOffset());
1041 ID.AddInteger(Size);
1042 ID.AddPointer(getOpaqueValue());
1043 ID.AddInteger(getFlags());
1044 ID.AddInteger(getBaseAlignment());
1047 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
1048 // The Value and Offset may differ due to CSE. But the flags and size
1049 // should be the same.
1050 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
1051 assert(MMO->getSize() == getSize() && "Size mismatch!");
1053 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
1054 // Update the alignment value.
1055 BaseAlignLog2 = Log2_32(MMO->getBaseAlignment()) + 1;
1056 // Also update the base and offset, because the new alignment may
1057 // not be applicable with the old ones.
1058 PtrInfo = MMO->PtrInfo;
1062 /// getAlignment - Return the minimum known alignment in bytes of the
1063 /// actual memory reference.
1064 uint64_t MachineMemOperand::getAlignment() const {
1065 return MinAlign(getBaseAlignment(), getOffset());
1068 void MachineMemOperand::print(raw_ostream &OS, ModuleSlotTracker &MST,
1069 SmallVectorImpl<StringRef> &SSNs,
1070 const LLVMContext &Context,
1071 const MachineFrameInfo *MFI,
1072 const TargetInstrInfo *TII) const {
1073 OS << '(';
1074 if (isVolatile())
1075 OS << "volatile ";
1076 if (isNonTemporal())
1077 OS << "non-temporal ";
1078 if (isDereferenceable())
1079 OS << "dereferenceable ";
1080 if (isInvariant())
1081 OS << "invariant ";
1082 if (getFlags() & MachineMemOperand::MOTargetFlag1)
1083 OS << '"' << getTargetMMOFlagName(*TII, MachineMemOperand::MOTargetFlag1)
1084 << "\" ";
1085 if (getFlags() & MachineMemOperand::MOTargetFlag2)
1086 OS << '"' << getTargetMMOFlagName(*TII, MachineMemOperand::MOTargetFlag2)
1087 << "\" ";
1088 if (getFlags() & MachineMemOperand::MOTargetFlag3)
1089 OS << '"' << getTargetMMOFlagName(*TII, MachineMemOperand::MOTargetFlag3)
1090 << "\" ";
1092 assert((isLoad() || isStore()) &&
1093 "machine memory operand must be a load or store (or both)");
1094 if (isLoad())
1095 OS << "load ";
1096 if (isStore())
1097 OS << "store ";
1099 printSyncScope(OS, Context, getSyncScopeID(), SSNs);
1101 if (getOrdering() != AtomicOrdering::NotAtomic)
1102 OS << toIRString(getOrdering()) << ' ';
1103 if (getFailureOrdering() != AtomicOrdering::NotAtomic)
1104 OS << toIRString(getFailureOrdering()) << ' ';
1106 if (getSize() == MemoryLocation::UnknownSize)
1107 OS << "unknown-size";
1108 else
1109 OS << getSize();
1111 if (const Value *Val = getValue()) {
1112 OS << ((isLoad() && isStore()) ? " on " : isLoad() ? " from " : " into ");
1113 printIRValueReference(OS, *Val, MST);
1114 } else if (const PseudoSourceValue *PVal = getPseudoValue()) {
1115 OS << ((isLoad() && isStore()) ? " on " : isLoad() ? " from " : " into ");
1116 assert(PVal && "Expected a pseudo source value");
1117 switch (PVal->kind()) {
1118 case PseudoSourceValue::Stack:
1119 OS << "stack";
1120 break;
1121 case PseudoSourceValue::GOT:
1122 OS << "got";
1123 break;
1124 case PseudoSourceValue::JumpTable:
1125 OS << "jump-table";
1126 break;
1127 case PseudoSourceValue::ConstantPool:
1128 OS << "constant-pool";
1129 break;
1130 case PseudoSourceValue::FixedStack: {
1131 int FrameIndex = cast<FixedStackPseudoSourceValue>(PVal)->getFrameIndex();
1132 bool IsFixed = true;
1133 printFrameIndex(OS, FrameIndex, IsFixed, MFI);
1134 break;
1136 case PseudoSourceValue::GlobalValueCallEntry:
1137 OS << "call-entry ";
1138 cast<GlobalValuePseudoSourceValue>(PVal)->getValue()->printAsOperand(
1139 OS, /*PrintType=*/false, MST);
1140 break;
1141 case PseudoSourceValue::ExternalSymbolCallEntry:
1142 OS << "call-entry &";
1143 printLLVMNameWithoutPrefix(
1144 OS, cast<ExternalSymbolPseudoSourceValue>(PVal)->getSymbol());
1145 break;
1146 default:
1147 // FIXME: This is not necessarily the correct MIR serialization format for
1148 // a custom pseudo source value, but at least it allows
1149 // -print-machineinstrs to work on a target with custom pseudo source
1150 // values.
1151 OS << "custom ";
1152 PVal->printCustom(OS);
1153 break;
1156 MachineOperand::printOperandOffset(OS, getOffset());
1157 if (getBaseAlignment() != getSize())
1158 OS << ", align " << getBaseAlignment();
1159 auto AAInfo = getAAInfo();
1160 if (AAInfo.TBAA) {
1161 OS << ", !tbaa ";
1162 AAInfo.TBAA->printAsOperand(OS, MST);
1164 if (AAInfo.Scope) {
1165 OS << ", !alias.scope ";
1166 AAInfo.Scope->printAsOperand(OS, MST);
1168 if (AAInfo.NoAlias) {
1169 OS << ", !noalias ";
1170 AAInfo.NoAlias->printAsOperand(OS, MST);
1172 if (getRanges()) {
1173 OS << ", !range ";
1174 getRanges()->printAsOperand(OS, MST);
1176 // FIXME: Implement addrspace printing/parsing in MIR.
1177 // For now, print this even though parsing it is not available in MIR.
1178 if (unsigned AS = getAddrSpace())
1179 OS << ", addrspace " << AS;
1181 OS << ')';