[AArch64] Crypto requires FP.
[llvm-core.git] / lib / CodeGen / MachineInstr.cpp
blobc0a8b95ed8a06dfccdb908b9d52fa1e9064caca2
1 //===-- lib/CodeGen/MachineInstr.cpp --------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Methods common to all machine instructions.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/ADT/FoldingSet.h"
16 #include "llvm/ADT/Hashing.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/CodeGen/MachineConstantPool.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineMemOperand.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/PseudoSourceValue.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/InlineAsm.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Metadata.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ModuleSlotTracker.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/IR/Value.h"
36 #include "llvm/MC/MCInstrDesc.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetIntrinsicInfo.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetRegisterInfo.h"
47 #include "llvm/Target/TargetSubtargetInfo.h"
48 using namespace llvm;
50 static cl::opt<bool> PrintWholeRegMask(
51 "print-whole-regmask",
52 cl::desc("Print the full contents of regmask operands in IR dumps"),
53 cl::init(true), cl::Hidden);
55 //===----------------------------------------------------------------------===//
56 // MachineOperand Implementation
57 //===----------------------------------------------------------------------===//
59 void MachineOperand::setReg(unsigned Reg) {
60 if (getReg() == Reg) return; // No change.
62 // Otherwise, we have to change the register. If this operand is embedded
63 // into a machine function, we need to update the old and new register's
64 // use/def lists.
65 if (MachineInstr *MI = getParent())
66 if (MachineBasicBlock *MBB = MI->getParent())
67 if (MachineFunction *MF = MBB->getParent()) {
68 MachineRegisterInfo &MRI = MF->getRegInfo();
69 MRI.removeRegOperandFromUseList(this);
70 SmallContents.RegNo = Reg;
71 MRI.addRegOperandToUseList(this);
72 return;
75 // Otherwise, just change the register, no problem. :)
76 SmallContents.RegNo = Reg;
79 void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
80 const TargetRegisterInfo &TRI) {
81 assert(TargetRegisterInfo::isVirtualRegister(Reg));
82 if (SubIdx && getSubReg())
83 SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
84 setReg(Reg);
85 if (SubIdx)
86 setSubReg(SubIdx);
89 void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
90 assert(TargetRegisterInfo::isPhysicalRegister(Reg));
91 if (getSubReg()) {
92 Reg = TRI.getSubReg(Reg, getSubReg());
93 // Note that getSubReg() may return 0 if the sub-register doesn't exist.
94 // That won't happen in legal code.
95 setSubReg(0);
96 if (isDef())
97 setIsUndef(false);
99 setReg(Reg);
102 /// Change a def to a use, or a use to a def.
103 void MachineOperand::setIsDef(bool Val) {
104 assert(isReg() && "Wrong MachineOperand accessor");
105 assert((!Val || !isDebug()) && "Marking a debug operation as def");
106 if (IsDef == Val)
107 return;
108 // MRI may keep uses and defs in different list positions.
109 if (MachineInstr *MI = getParent())
110 if (MachineBasicBlock *MBB = MI->getParent())
111 if (MachineFunction *MF = MBB->getParent()) {
112 MachineRegisterInfo &MRI = MF->getRegInfo();
113 MRI.removeRegOperandFromUseList(this);
114 IsDef = Val;
115 MRI.addRegOperandToUseList(this);
116 return;
118 IsDef = Val;
121 // If this operand is currently a register operand, and if this is in a
122 // function, deregister the operand from the register's use/def list.
123 void MachineOperand::removeRegFromUses() {
124 if (!isReg() || !isOnRegUseList())
125 return;
127 if (MachineInstr *MI = getParent()) {
128 if (MachineBasicBlock *MBB = MI->getParent()) {
129 if (MachineFunction *MF = MBB->getParent())
130 MF->getRegInfo().removeRegOperandFromUseList(this);
135 /// ChangeToImmediate - Replace this operand with a new immediate operand of
136 /// the specified value. If an operand is known to be an immediate already,
137 /// the setImm method should be used.
138 void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
139 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
141 removeRegFromUses();
143 OpKind = MO_Immediate;
144 Contents.ImmVal = ImmVal;
147 void MachineOperand::ChangeToFPImmediate(const ConstantFP *FPImm) {
148 assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
150 removeRegFromUses();
152 OpKind = MO_FPImmediate;
153 Contents.CFP = FPImm;
156 void MachineOperand::ChangeToES(const char *SymName, unsigned char TargetFlags) {
157 assert((!isReg() || !isTied()) &&
158 "Cannot change a tied operand into an external symbol");
160 removeRegFromUses();
162 OpKind = MO_ExternalSymbol;
163 Contents.OffsetedInfo.Val.SymbolName = SymName;
164 setOffset(0); // Offset is always 0.
165 setTargetFlags(TargetFlags);
168 void MachineOperand::ChangeToMCSymbol(MCSymbol *Sym) {
169 assert((!isReg() || !isTied()) &&
170 "Cannot change a tied operand into an MCSymbol");
172 removeRegFromUses();
174 OpKind = MO_MCSymbol;
175 Contents.Sym = Sym;
178 void MachineOperand::ChangeToFrameIndex(int Idx) {
179 assert((!isReg() || !isTied()) &&
180 "Cannot change a tied operand into a FrameIndex");
182 removeRegFromUses();
184 OpKind = MO_FrameIndex;
185 setIndex(Idx);
188 /// ChangeToRegister - Replace this operand with a new register operand of
189 /// the specified value. If an operand is known to be an register already,
190 /// the setReg method should be used.
191 void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
192 bool isKill, bool isDead, bool isUndef,
193 bool isDebug) {
194 MachineRegisterInfo *RegInfo = nullptr;
195 if (MachineInstr *MI = getParent())
196 if (MachineBasicBlock *MBB = MI->getParent())
197 if (MachineFunction *MF = MBB->getParent())
198 RegInfo = &MF->getRegInfo();
199 // If this operand is already a register operand, remove it from the
200 // register's use/def lists.
201 bool WasReg = isReg();
202 if (RegInfo && WasReg)
203 RegInfo->removeRegOperandFromUseList(this);
205 // Change this to a register and set the reg#.
206 OpKind = MO_Register;
207 SmallContents.RegNo = Reg;
208 SubReg_TargetFlags = 0;
209 IsDef = isDef;
210 IsImp = isImp;
211 IsKill = isKill;
212 IsDead = isDead;
213 IsUndef = isUndef;
214 IsInternalRead = false;
215 IsEarlyClobber = false;
216 IsDebug = isDebug;
217 // Ensure isOnRegUseList() returns false.
218 Contents.Reg.Prev = nullptr;
219 // Preserve the tie when the operand was already a register.
220 if (!WasReg)
221 TiedTo = 0;
223 // If this operand is embedded in a function, add the operand to the
224 // register's use/def list.
225 if (RegInfo)
226 RegInfo->addRegOperandToUseList(this);
229 /// isIdenticalTo - Return true if this operand is identical to the specified
230 /// operand. Note that this should stay in sync with the hash_value overload
231 /// below.
232 bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
233 if (getType() != Other.getType() ||
234 getTargetFlags() != Other.getTargetFlags())
235 return false;
237 switch (getType()) {
238 case MachineOperand::MO_Register:
239 return getReg() == Other.getReg() && isDef() == Other.isDef() &&
240 getSubReg() == Other.getSubReg();
241 case MachineOperand::MO_Immediate:
242 return getImm() == Other.getImm();
243 case MachineOperand::MO_CImmediate:
244 return getCImm() == Other.getCImm();
245 case MachineOperand::MO_FPImmediate:
246 return getFPImm() == Other.getFPImm();
247 case MachineOperand::MO_MachineBasicBlock:
248 return getMBB() == Other.getMBB();
249 case MachineOperand::MO_FrameIndex:
250 return getIndex() == Other.getIndex();
251 case MachineOperand::MO_ConstantPoolIndex:
252 case MachineOperand::MO_TargetIndex:
253 return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
254 case MachineOperand::MO_JumpTableIndex:
255 return getIndex() == Other.getIndex();
256 case MachineOperand::MO_GlobalAddress:
257 return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
258 case MachineOperand::MO_ExternalSymbol:
259 return !strcmp(getSymbolName(), Other.getSymbolName()) &&
260 getOffset() == Other.getOffset();
261 case MachineOperand::MO_BlockAddress:
262 return getBlockAddress() == Other.getBlockAddress() &&
263 getOffset() == Other.getOffset();
264 case MachineOperand::MO_RegisterMask:
265 case MachineOperand::MO_RegisterLiveOut: {
266 // Shallow compare of the two RegMasks
267 const uint32_t *RegMask = getRegMask();
268 const uint32_t *OtherRegMask = Other.getRegMask();
269 if (RegMask == OtherRegMask)
270 return true;
272 // Calculate the size of the RegMask
273 const MachineFunction *MF = getParent()->getParent()->getParent();
274 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
275 unsigned RegMaskSize = (TRI->getNumRegs() + 31) / 32;
277 // Deep compare of the two RegMasks
278 return std::equal(RegMask, RegMask + RegMaskSize, OtherRegMask);
280 case MachineOperand::MO_MCSymbol:
281 return getMCSymbol() == Other.getMCSymbol();
282 case MachineOperand::MO_CFIIndex:
283 return getCFIIndex() == Other.getCFIIndex();
284 case MachineOperand::MO_Metadata:
285 return getMetadata() == Other.getMetadata();
286 case MachineOperand::MO_IntrinsicID:
287 return getIntrinsicID() == Other.getIntrinsicID();
288 case MachineOperand::MO_Predicate:
289 return getPredicate() == Other.getPredicate();
290 case MachineOperand::MO_Placeholder:
291 return true;
293 llvm_unreachable("Invalid machine operand type");
296 // Note: this must stay exactly in sync with isIdenticalTo above.
297 hash_code llvm::hash_value(const MachineOperand &MO) {
298 switch (MO.getType()) {
299 case MachineOperand::MO_Register:
300 // Register operands don't have target flags.
301 return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
302 case MachineOperand::MO_Immediate:
303 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
304 case MachineOperand::MO_CImmediate:
305 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
306 case MachineOperand::MO_FPImmediate:
307 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
308 case MachineOperand::MO_MachineBasicBlock:
309 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
310 case MachineOperand::MO_FrameIndex:
311 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
312 case MachineOperand::MO_ConstantPoolIndex:
313 case MachineOperand::MO_TargetIndex:
314 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
315 MO.getOffset());
316 case MachineOperand::MO_JumpTableIndex:
317 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
318 case MachineOperand::MO_ExternalSymbol:
319 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
320 MO.getSymbolName());
321 case MachineOperand::MO_GlobalAddress:
322 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
323 MO.getOffset());
324 case MachineOperand::MO_BlockAddress:
325 return hash_combine(MO.getType(), MO.getTargetFlags(),
326 MO.getBlockAddress(), MO.getOffset());
327 case MachineOperand::MO_RegisterMask:
328 case MachineOperand::MO_RegisterLiveOut:
329 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
330 case MachineOperand::MO_Metadata:
331 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
332 case MachineOperand::MO_MCSymbol:
333 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
334 case MachineOperand::MO_CFIIndex:
335 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCFIIndex());
336 case MachineOperand::MO_IntrinsicID:
337 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIntrinsicID());
338 case MachineOperand::MO_Predicate:
339 return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getPredicate());
340 case MachineOperand::MO_Placeholder:
341 return hash_combine();
343 llvm_unreachable("Invalid machine operand type");
346 void MachineOperand::print(raw_ostream &OS, const TargetRegisterInfo *TRI,
347 const TargetIntrinsicInfo *IntrinsicInfo) const {
348 ModuleSlotTracker DummyMST(nullptr);
349 print(OS, DummyMST, TRI, IntrinsicInfo);
352 void MachineOperand::print(raw_ostream &OS, ModuleSlotTracker &MST,
353 const TargetRegisterInfo *TRI,
354 const TargetIntrinsicInfo *IntrinsicInfo) const {
355 switch (getType()) {
356 case MachineOperand::MO_Register:
357 OS << PrintReg(getReg(), TRI, getSubReg());
359 if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
360 isInternalRead() || isEarlyClobber() || isTied()) {
361 OS << '<';
362 bool NeedComma = false;
363 if (isDef()) {
364 if (NeedComma) OS << ',';
365 if (isEarlyClobber())
366 OS << "earlyclobber,";
367 if (isImplicit())
368 OS << "imp-";
369 OS << "def";
370 NeedComma = true;
371 // <def,read-undef> only makes sense when getSubReg() is set.
372 // Don't clutter the output otherwise.
373 if (isUndef() && getSubReg())
374 OS << ",read-undef";
375 } else if (isImplicit()) {
376 OS << "imp-use";
377 NeedComma = true;
380 if (isKill()) {
381 if (NeedComma) OS << ',';
382 OS << "kill";
383 NeedComma = true;
385 if (isDead()) {
386 if (NeedComma) OS << ',';
387 OS << "dead";
388 NeedComma = true;
390 if (isUndef() && isUse()) {
391 if (NeedComma) OS << ',';
392 OS << "undef";
393 NeedComma = true;
395 if (isInternalRead()) {
396 if (NeedComma) OS << ',';
397 OS << "internal";
398 NeedComma = true;
400 if (isTied()) {
401 if (NeedComma) OS << ',';
402 OS << "tied";
403 if (TiedTo != 15)
404 OS << unsigned(TiedTo - 1);
406 OS << '>';
408 break;
409 case MachineOperand::MO_Immediate:
410 OS << getImm();
411 break;
412 case MachineOperand::MO_CImmediate:
413 getCImm()->getValue().print(OS, false);
414 break;
415 case MachineOperand::MO_FPImmediate:
416 if (getFPImm()->getType()->isFloatTy()) {
417 OS << getFPImm()->getValueAPF().convertToFloat();
418 } else if (getFPImm()->getType()->isHalfTy()) {
419 APFloat APF = getFPImm()->getValueAPF();
420 bool Unused;
421 APF.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &Unused);
422 OS << "half " << APF.convertToFloat();
423 } else if (getFPImm()->getType()->isFP128Ty()) {
424 APFloat APF = getFPImm()->getValueAPF();
425 SmallString<16> Str;
426 getFPImm()->getValueAPF().toString(Str);
427 OS << "quad " << Str;
428 } else {
429 OS << getFPImm()->getValueAPF().convertToDouble();
431 break;
432 case MachineOperand::MO_MachineBasicBlock:
433 OS << "<BB#" << getMBB()->getNumber() << ">";
434 break;
435 case MachineOperand::MO_FrameIndex:
436 OS << "<fi#" << getIndex() << '>';
437 break;
438 case MachineOperand::MO_ConstantPoolIndex:
439 OS << "<cp#" << getIndex();
440 if (getOffset()) OS << "+" << getOffset();
441 OS << '>';
442 break;
443 case MachineOperand::MO_TargetIndex:
444 OS << "<ti#" << getIndex();
445 if (getOffset()) OS << "+" << getOffset();
446 OS << '>';
447 break;
448 case MachineOperand::MO_JumpTableIndex:
449 OS << "<jt#" << getIndex() << '>';
450 break;
451 case MachineOperand::MO_GlobalAddress:
452 OS << "<ga:";
453 getGlobal()->printAsOperand(OS, /*PrintType=*/false, MST);
454 if (getOffset()) OS << "+" << getOffset();
455 OS << '>';
456 break;
457 case MachineOperand::MO_ExternalSymbol:
458 OS << "<es:" << getSymbolName();
459 if (getOffset()) OS << "+" << getOffset();
460 OS << '>';
461 break;
462 case MachineOperand::MO_BlockAddress:
463 OS << '<';
464 getBlockAddress()->printAsOperand(OS, /*PrintType=*/false, MST);
465 if (getOffset()) OS << "+" << getOffset();
466 OS << '>';
467 break;
468 case MachineOperand::MO_RegisterMask: {
469 unsigned NumRegsInMask = 0;
470 unsigned NumRegsEmitted = 0;
471 OS << "<regmask";
472 for (unsigned i = 0; i < TRI->getNumRegs(); ++i) {
473 unsigned MaskWord = i / 32;
474 unsigned MaskBit = i % 32;
475 if (getRegMask()[MaskWord] & (1 << MaskBit)) {
476 if (PrintWholeRegMask || NumRegsEmitted <= 10) {
477 OS << " " << PrintReg(i, TRI);
478 NumRegsEmitted++;
480 NumRegsInMask++;
483 if (NumRegsEmitted != NumRegsInMask)
484 OS << " and " << (NumRegsInMask - NumRegsEmitted) << " more...";
485 OS << ">";
486 break;
488 case MachineOperand::MO_RegisterLiveOut:
489 OS << "<regliveout>";
490 break;
491 case MachineOperand::MO_Metadata:
492 OS << '<';
493 getMetadata()->printAsOperand(OS, MST);
494 OS << '>';
495 break;
496 case MachineOperand::MO_MCSymbol:
497 OS << "<MCSym=" << *getMCSymbol() << '>';
498 break;
499 case MachineOperand::MO_CFIIndex:
500 OS << "<call frame instruction>";
501 break;
502 case MachineOperand::MO_IntrinsicID: {
503 Intrinsic::ID ID = getIntrinsicID();
504 if (ID < Intrinsic::num_intrinsics)
505 OS << "<intrinsic:@" << Intrinsic::getName(ID, None) << '>';
506 else if (IntrinsicInfo)
507 OS << "<intrinsic:@" << IntrinsicInfo->getName(ID) << '>';
508 else
509 OS << "<intrinsic:" << ID << '>';
510 break;
512 case MachineOperand::MO_Predicate: {
513 auto Pred = static_cast<CmpInst::Predicate>(getPredicate());
514 OS << '<' << (CmpInst::isIntPredicate(Pred) ? "intpred" : "floatpred")
515 << CmpInst::getPredicateName(Pred) << '>';
516 break;
518 case MachineOperand::MO_Placeholder:
519 OS << "<placeholder>";
520 break;
522 if (unsigned TF = getTargetFlags())
523 OS << "[TF=" << TF << ']';
526 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
527 LLVM_DUMP_METHOD void MachineOperand::dump() const {
528 dbgs() << *this << '\n';
530 #endif
532 //===----------------------------------------------------------------------===//
533 // MachineMemOperand Implementation
534 //===----------------------------------------------------------------------===//
536 /// getAddrSpace - Return the LLVM IR address space number that this pointer
537 /// points into.
538 unsigned MachinePointerInfo::getAddrSpace() const {
539 if (V.isNull() || V.is<const PseudoSourceValue*>()) return 0;
540 return cast<PointerType>(V.get<const Value*>()->getType())->getAddressSpace();
543 /// getConstantPool - Return a MachinePointerInfo record that refers to the
544 /// constant pool.
545 MachinePointerInfo MachinePointerInfo::getConstantPool(MachineFunction &MF) {
546 return MachinePointerInfo(MF.getPSVManager().getConstantPool());
549 /// getFixedStack - Return a MachinePointerInfo record that refers to the
550 /// the specified FrameIndex.
551 MachinePointerInfo MachinePointerInfo::getFixedStack(MachineFunction &MF,
552 int FI, int64_t Offset) {
553 return MachinePointerInfo(MF.getPSVManager().getFixedStack(FI), Offset);
556 MachinePointerInfo MachinePointerInfo::getJumpTable(MachineFunction &MF) {
557 return MachinePointerInfo(MF.getPSVManager().getJumpTable());
560 MachinePointerInfo MachinePointerInfo::getGOT(MachineFunction &MF) {
561 return MachinePointerInfo(MF.getPSVManager().getGOT());
564 MachinePointerInfo MachinePointerInfo::getStack(MachineFunction &MF,
565 int64_t Offset) {
566 return MachinePointerInfo(MF.getPSVManager().getStack(), Offset);
569 MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, Flags f,
570 uint64_t s, unsigned int a,
571 const AAMDNodes &AAInfo,
572 const MDNode *Ranges,
573 SynchronizationScope SynchScope,
574 AtomicOrdering Ordering,
575 AtomicOrdering FailureOrdering)
576 : PtrInfo(ptrinfo), Size(s), FlagVals(f), BaseAlignLog2(Log2_32(a) + 1),
577 AAInfo(AAInfo), Ranges(Ranges) {
578 assert((PtrInfo.V.isNull() || PtrInfo.V.is<const PseudoSourceValue*>() ||
579 isa<PointerType>(PtrInfo.V.get<const Value*>()->getType())) &&
580 "invalid pointer value");
581 assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
582 assert((isLoad() || isStore()) && "Not a load/store!");
584 AtomicInfo.SynchScope = static_cast<unsigned>(SynchScope);
585 assert(getSynchScope() == SynchScope && "Value truncated");
586 AtomicInfo.Ordering = static_cast<unsigned>(Ordering);
587 assert(getOrdering() == Ordering && "Value truncated");
588 AtomicInfo.FailureOrdering = static_cast<unsigned>(FailureOrdering);
589 assert(getFailureOrdering() == FailureOrdering && "Value truncated");
592 /// Profile - Gather unique data for the object.
594 void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
595 ID.AddInteger(getOffset());
596 ID.AddInteger(Size);
597 ID.AddPointer(getOpaqueValue());
598 ID.AddInteger(getFlags());
599 ID.AddInteger(getBaseAlignment());
602 void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
603 // The Value and Offset may differ due to CSE. But the flags and size
604 // should be the same.
605 assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
606 assert(MMO->getSize() == getSize() && "Size mismatch!");
608 if (MMO->getBaseAlignment() >= getBaseAlignment()) {
609 // Update the alignment value.
610 BaseAlignLog2 = Log2_32(MMO->getBaseAlignment()) + 1;
611 // Also update the base and offset, because the new alignment may
612 // not be applicable with the old ones.
613 PtrInfo = MMO->PtrInfo;
617 /// getAlignment - Return the minimum known alignment in bytes of the
618 /// actual memory reference.
619 uint64_t MachineMemOperand::getAlignment() const {
620 return MinAlign(getBaseAlignment(), getOffset());
623 void MachineMemOperand::print(raw_ostream &OS) const {
624 ModuleSlotTracker DummyMST(nullptr);
625 print(OS, DummyMST);
627 void MachineMemOperand::print(raw_ostream &OS, ModuleSlotTracker &MST) const {
628 assert((isLoad() || isStore()) &&
629 "SV has to be a load, store or both.");
631 if (isVolatile())
632 OS << "Volatile ";
634 if (isLoad())
635 OS << "LD";
636 if (isStore())
637 OS << "ST";
638 OS << getSize();
640 // Print the address information.
641 OS << "[";
642 if (const Value *V = getValue())
643 V->printAsOperand(OS, /*PrintType=*/false, MST);
644 else if (const PseudoSourceValue *PSV = getPseudoValue())
645 PSV->printCustom(OS);
646 else
647 OS << "<unknown>";
649 unsigned AS = getAddrSpace();
650 if (AS != 0)
651 OS << "(addrspace=" << AS << ')';
653 // If the alignment of the memory reference itself differs from the alignment
654 // of the base pointer, print the base alignment explicitly, next to the base
655 // pointer.
656 if (getBaseAlignment() != getAlignment())
657 OS << "(align=" << getBaseAlignment() << ")";
659 if (getOffset() != 0)
660 OS << "+" << getOffset();
661 OS << "]";
663 // Print the alignment of the reference.
664 if (getBaseAlignment() != getAlignment() || getBaseAlignment() != getSize())
665 OS << "(align=" << getAlignment() << ")";
667 // Print TBAA info.
668 if (const MDNode *TBAAInfo = getAAInfo().TBAA) {
669 OS << "(tbaa=";
670 if (TBAAInfo->getNumOperands() > 0)
671 TBAAInfo->getOperand(0)->printAsOperand(OS, MST);
672 else
673 OS << "<unknown>";
674 OS << ")";
677 // Print AA scope info.
678 if (const MDNode *ScopeInfo = getAAInfo().Scope) {
679 OS << "(alias.scope=";
680 if (ScopeInfo->getNumOperands() > 0)
681 for (unsigned i = 0, ie = ScopeInfo->getNumOperands(); i != ie; ++i) {
682 ScopeInfo->getOperand(i)->printAsOperand(OS, MST);
683 if (i != ie-1)
684 OS << ",";
686 else
687 OS << "<unknown>";
688 OS << ")";
691 // Print AA noalias scope info.
692 if (const MDNode *NoAliasInfo = getAAInfo().NoAlias) {
693 OS << "(noalias=";
694 if (NoAliasInfo->getNumOperands() > 0)
695 for (unsigned i = 0, ie = NoAliasInfo->getNumOperands(); i != ie; ++i) {
696 NoAliasInfo->getOperand(i)->printAsOperand(OS, MST);
697 if (i != ie-1)
698 OS << ",";
700 else
701 OS << "<unknown>";
702 OS << ")";
705 if (isNonTemporal())
706 OS << "(nontemporal)";
707 if (isDereferenceable())
708 OS << "(dereferenceable)";
709 if (isInvariant())
710 OS << "(invariant)";
713 //===----------------------------------------------------------------------===//
714 // MachineInstr Implementation
715 //===----------------------------------------------------------------------===//
717 void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
718 if (MCID->ImplicitDefs)
719 for (const MCPhysReg *ImpDefs = MCID->getImplicitDefs(); *ImpDefs;
720 ++ImpDefs)
721 addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
722 if (MCID->ImplicitUses)
723 for (const MCPhysReg *ImpUses = MCID->getImplicitUses(); *ImpUses;
724 ++ImpUses)
725 addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
728 /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
729 /// implicit operands. It reserves space for the number of operands specified by
730 /// the MCInstrDesc.
731 MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
732 DebugLoc dl, bool NoImp)
733 : MCID(&tid), Parent(nullptr), Operands(nullptr), NumOperands(0), Flags(0),
734 AsmPrinterFlags(0), NumMemRefs(0), MemRefs(nullptr),
735 debugLoc(std::move(dl)) {
736 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
738 // Reserve space for the expected number of operands.
739 if (unsigned NumOps = MCID->getNumOperands() +
740 MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
741 CapOperands = OperandCapacity::get(NumOps);
742 Operands = MF.allocateOperandArray(CapOperands);
745 if (!NoImp)
746 addImplicitDefUseOperands(MF);
749 /// MachineInstr ctor - Copies MachineInstr arg exactly
751 MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
752 : MCID(&MI.getDesc()), Parent(nullptr), Operands(nullptr), NumOperands(0),
753 Flags(0), AsmPrinterFlags(0), NumMemRefs(MI.NumMemRefs),
754 MemRefs(MI.MemRefs), debugLoc(MI.getDebugLoc()) {
755 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor");
757 CapOperands = OperandCapacity::get(MI.getNumOperands());
758 Operands = MF.allocateOperandArray(CapOperands);
760 // Copy operands.
761 for (const MachineOperand &MO : MI.operands())
762 addOperand(MF, MO);
764 // Copy all the sensible flags.
765 setFlags(MI.Flags);
768 /// getRegInfo - If this instruction is embedded into a MachineFunction,
769 /// return the MachineRegisterInfo object for the current function, otherwise
770 /// return null.
771 MachineRegisterInfo *MachineInstr::getRegInfo() {
772 if (MachineBasicBlock *MBB = getParent())
773 return &MBB->getParent()->getRegInfo();
774 return nullptr;
777 /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
778 /// this instruction from their respective use lists. This requires that the
779 /// operands already be on their use lists.
780 void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
781 for (MachineOperand &MO : operands())
782 if (MO.isReg())
783 MRI.removeRegOperandFromUseList(&MO);
786 /// AddRegOperandsToUseLists - Add all of the register operands in
787 /// this instruction from their respective use lists. This requires that the
788 /// operands not be on their use lists yet.
789 void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
790 for (MachineOperand &MO : operands())
791 if (MO.isReg())
792 MRI.addRegOperandToUseList(&MO);
795 void MachineInstr::addOperand(const MachineOperand &Op) {
796 MachineBasicBlock *MBB = getParent();
797 assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
798 MachineFunction *MF = MBB->getParent();
799 assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
800 addOperand(*MF, Op);
803 /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
804 /// ranges. If MRI is non-null also update use-def chains.
805 static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
806 unsigned NumOps, MachineRegisterInfo *MRI) {
807 if (MRI)
808 return MRI->moveOperands(Dst, Src, NumOps);
810 // MachineOperand is a trivially copyable type so we can just use memmove.
811 std::memmove(Dst, Src, NumOps * sizeof(MachineOperand));
814 /// addOperand - Add the specified operand to the instruction. If it is an
815 /// implicit operand, it is added to the end of the operand list. If it is
816 /// an explicit operand it is added at the end of the explicit operand list
817 /// (before the first implicit operand).
818 void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
819 assert(MCID && "Cannot add operands before providing an instr descriptor");
821 // Check if we're adding one of our existing operands.
822 if (&Op >= Operands && &Op < Operands + NumOperands) {
823 // This is unusual: MI->addOperand(MI->getOperand(i)).
824 // If adding Op requires reallocating or moving existing operands around,
825 // the Op reference could go stale. Support it by copying Op.
826 MachineOperand CopyOp(Op);
827 return addOperand(MF, CopyOp);
830 // Find the insert location for the new operand. Implicit registers go at
831 // the end, everything else goes before the implicit regs.
833 // FIXME: Allow mixed explicit and implicit operands on inline asm.
834 // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
835 // implicit-defs, but they must not be moved around. See the FIXME in
836 // InstrEmitter.cpp.
837 unsigned OpNo = getNumOperands();
838 bool isImpReg = Op.isReg() && Op.isImplicit();
839 if (!isImpReg && !isInlineAsm()) {
840 while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
841 --OpNo;
842 assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
846 #ifndef NDEBUG
847 bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata;
848 // OpNo now points as the desired insertion point. Unless this is a variadic
849 // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
850 // RegMask operands go between the explicit and implicit operands.
851 assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
852 OpNo < MCID->getNumOperands() || isMetaDataOp) &&
853 "Trying to add an operand to a machine instr that is already done!");
854 #endif
856 MachineRegisterInfo *MRI = getRegInfo();
858 // Determine if the Operands array needs to be reallocated.
859 // Save the old capacity and operand array.
860 OperandCapacity OldCap = CapOperands;
861 MachineOperand *OldOperands = Operands;
862 if (!OldOperands || OldCap.getSize() == getNumOperands()) {
863 CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
864 Operands = MF.allocateOperandArray(CapOperands);
865 // Move the operands before the insertion point.
866 if (OpNo)
867 moveOperands(Operands, OldOperands, OpNo, MRI);
870 // Move the operands following the insertion point.
871 if (OpNo != NumOperands)
872 moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
873 MRI);
874 ++NumOperands;
876 // Deallocate the old operand array.
877 if (OldOperands != Operands && OldOperands)
878 MF.deallocateOperandArray(OldCap, OldOperands);
880 // Copy Op into place. It still needs to be inserted into the MRI use lists.
881 MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
882 NewMO->ParentMI = this;
884 // When adding a register operand, tell MRI about it.
885 if (NewMO->isReg()) {
886 // Ensure isOnRegUseList() returns false, regardless of Op's status.
887 NewMO->Contents.Reg.Prev = nullptr;
888 // Ignore existing ties. This is not a property that can be copied.
889 NewMO->TiedTo = 0;
890 // Add the new operand to MRI, but only for instructions in an MBB.
891 if (MRI)
892 MRI->addRegOperandToUseList(NewMO);
893 // The MCID operand information isn't accurate until we start adding
894 // explicit operands. The implicit operands are added first, then the
895 // explicits are inserted before them.
896 if (!isImpReg) {
897 // Tie uses to defs as indicated in MCInstrDesc.
898 if (NewMO->isUse()) {
899 int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
900 if (DefIdx != -1)
901 tieOperands(DefIdx, OpNo);
903 // If the register operand is flagged as early, mark the operand as such.
904 if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
905 NewMO->setIsEarlyClobber(true);
910 /// RemoveOperand - Erase an operand from an instruction, leaving it with one
911 /// fewer operand than it started with.
913 void MachineInstr::RemoveOperand(unsigned OpNo) {
914 assert(OpNo < getNumOperands() && "Invalid operand number");
915 untieRegOperand(OpNo);
917 #ifndef NDEBUG
918 // Moving tied operands would break the ties.
919 for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
920 if (Operands[i].isReg())
921 assert(!Operands[i].isTied() && "Cannot move tied operands");
922 #endif
924 MachineRegisterInfo *MRI = getRegInfo();
925 if (MRI && Operands[OpNo].isReg())
926 MRI->removeRegOperandFromUseList(Operands + OpNo);
928 // Don't call the MachineOperand destructor. A lot of this code depends on
929 // MachineOperand having a trivial destructor anyway, and adding a call here
930 // wouldn't make it 'destructor-correct'.
932 if (unsigned N = NumOperands - 1 - OpNo)
933 moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
934 --NumOperands;
937 /// addMemOperand - Add a MachineMemOperand to the machine instruction.
938 /// This function should be used only occasionally. The setMemRefs function
939 /// is the primary method for setting up a MachineInstr's MemRefs list.
940 void MachineInstr::addMemOperand(MachineFunction &MF,
941 MachineMemOperand *MO) {
942 mmo_iterator OldMemRefs = MemRefs;
943 unsigned OldNumMemRefs = NumMemRefs;
945 unsigned NewNum = NumMemRefs + 1;
946 mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
948 std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
949 NewMemRefs[NewNum - 1] = MO;
950 setMemRefs(NewMemRefs, NewMemRefs + NewNum);
953 /// Check to see if the MMOs pointed to by the two MemRefs arrays are
954 /// identical.
955 static bool hasIdenticalMMOs(const MachineInstr &MI1, const MachineInstr &MI2) {
956 auto I1 = MI1.memoperands_begin(), E1 = MI1.memoperands_end();
957 auto I2 = MI2.memoperands_begin(), E2 = MI2.memoperands_end();
958 if ((E1 - I1) != (E2 - I2))
959 return false;
960 for (; I1 != E1; ++I1, ++I2) {
961 if (**I1 != **I2)
962 return false;
964 return true;
967 std::pair<MachineInstr::mmo_iterator, unsigned>
968 MachineInstr::mergeMemRefsWith(const MachineInstr& Other) {
970 // If either of the incoming memrefs are empty, we must be conservative and
971 // treat this as if we've exhausted our space for memrefs and dropped them.
972 if (memoperands_empty() || Other.memoperands_empty())
973 return std::make_pair(nullptr, 0);
975 // If both instructions have identical memrefs, we don't need to merge them.
976 // Since many instructions have a single memref, and we tend to merge things
977 // like pairs of loads from the same location, this catches a large number of
978 // cases in practice.
979 if (hasIdenticalMMOs(*this, Other))
980 return std::make_pair(MemRefs, NumMemRefs);
982 // TODO: consider uniquing elements within the operand lists to reduce
983 // space usage and fall back to conservative information less often.
984 size_t CombinedNumMemRefs = NumMemRefs + Other.NumMemRefs;
986 // If we don't have enough room to store this many memrefs, be conservative
987 // and drop them. Otherwise, we'd fail asserts when trying to add them to
988 // the new instruction.
989 if (CombinedNumMemRefs != uint8_t(CombinedNumMemRefs))
990 return std::make_pair(nullptr, 0);
992 MachineFunction *MF = getParent()->getParent();
993 mmo_iterator MemBegin = MF->allocateMemRefsArray(CombinedNumMemRefs);
994 mmo_iterator MemEnd = std::copy(memoperands_begin(), memoperands_end(),
995 MemBegin);
996 MemEnd = std::copy(Other.memoperands_begin(), Other.memoperands_end(),
997 MemEnd);
998 assert(MemEnd - MemBegin == (ptrdiff_t)CombinedNumMemRefs &&
999 "missing memrefs");
1001 return std::make_pair(MemBegin, CombinedNumMemRefs);
1004 bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
1005 assert(!isBundledWithPred() && "Must be called on bundle header");
1006 for (MachineBasicBlock::const_instr_iterator MII = getIterator();; ++MII) {
1007 if (MII->getDesc().getFlags() & Mask) {
1008 if (Type == AnyInBundle)
1009 return true;
1010 } else {
1011 if (Type == AllInBundle && !MII->isBundle())
1012 return false;
1014 // This was the last instruction in the bundle.
1015 if (!MII->isBundledWithSucc())
1016 return Type == AllInBundle;
1020 bool MachineInstr::isIdenticalTo(const MachineInstr &Other,
1021 MICheckType Check) const {
1022 // If opcodes or number of operands are not the same then the two
1023 // instructions are obviously not identical.
1024 if (Other.getOpcode() != getOpcode() ||
1025 Other.getNumOperands() != getNumOperands())
1026 return false;
1028 if (isBundle()) {
1029 // We have passed the test above that both instructions have the same
1030 // opcode, so we know that both instructions are bundles here. Let's compare
1031 // MIs inside the bundle.
1032 assert(Other.isBundle() && "Expected that both instructions are bundles.");
1033 MachineBasicBlock::const_instr_iterator I1 = getIterator();
1034 MachineBasicBlock::const_instr_iterator I2 = Other.getIterator();
1035 // Loop until we analysed the last intruction inside at least one of the
1036 // bundles.
1037 while (I1->isBundledWithSucc() && I2->isBundledWithSucc()) {
1038 ++I1;
1039 ++I2;
1040 if (!I1->isIdenticalTo(*I2, Check))
1041 return false;
1043 // If we've reached the end of just one of the two bundles, but not both,
1044 // the instructions are not identical.
1045 if (I1->isBundledWithSucc() || I2->isBundledWithSucc())
1046 return false;
1049 // Check operands to make sure they match.
1050 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1051 const MachineOperand &MO = getOperand(i);
1052 const MachineOperand &OMO = Other.getOperand(i);
1053 if (!MO.isReg()) {
1054 if (!MO.isIdenticalTo(OMO))
1055 return false;
1056 continue;
1059 // Clients may or may not want to ignore defs when testing for equality.
1060 // For example, machine CSE pass only cares about finding common
1061 // subexpressions, so it's safe to ignore virtual register defs.
1062 if (MO.isDef()) {
1063 if (Check == IgnoreDefs)
1064 continue;
1065 else if (Check == IgnoreVRegDefs) {
1066 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
1067 TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
1068 if (MO.getReg() != OMO.getReg())
1069 return false;
1070 } else {
1071 if (!MO.isIdenticalTo(OMO))
1072 return false;
1073 if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
1074 return false;
1076 } else {
1077 if (!MO.isIdenticalTo(OMO))
1078 return false;
1079 if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
1080 return false;
1083 // If DebugLoc does not match then two dbg.values are not identical.
1084 if (isDebugValue())
1085 if (getDebugLoc() && Other.getDebugLoc() &&
1086 getDebugLoc() != Other.getDebugLoc())
1087 return false;
1088 return true;
1091 MachineInstr *MachineInstr::removeFromParent() {
1092 assert(getParent() && "Not embedded in a basic block!");
1093 return getParent()->remove(this);
1096 MachineInstr *MachineInstr::removeFromBundle() {
1097 assert(getParent() && "Not embedded in a basic block!");
1098 return getParent()->remove_instr(this);
1101 void MachineInstr::eraseFromParent() {
1102 assert(getParent() && "Not embedded in a basic block!");
1103 getParent()->erase(this);
1106 void MachineInstr::eraseFromParentAndMarkDBGValuesForRemoval() {
1107 assert(getParent() && "Not embedded in a basic block!");
1108 MachineBasicBlock *MBB = getParent();
1109 MachineFunction *MF = MBB->getParent();
1110 assert(MF && "Not embedded in a function!");
1112 MachineInstr *MI = (MachineInstr *)this;
1113 MachineRegisterInfo &MRI = MF->getRegInfo();
1115 for (const MachineOperand &MO : MI->operands()) {
1116 if (!MO.isReg() || !MO.isDef())
1117 continue;
1118 unsigned Reg = MO.getReg();
1119 if (!TargetRegisterInfo::isVirtualRegister(Reg))
1120 continue;
1121 MRI.markUsesInDebugValueAsUndef(Reg);
1123 MI->eraseFromParent();
1126 void MachineInstr::eraseFromBundle() {
1127 assert(getParent() && "Not embedded in a basic block!");
1128 getParent()->erase_instr(this);
1131 /// getNumExplicitOperands - Returns the number of non-implicit operands.
1133 unsigned MachineInstr::getNumExplicitOperands() const {
1134 unsigned NumOperands = MCID->getNumOperands();
1135 if (!MCID->isVariadic())
1136 return NumOperands;
1138 for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
1139 const MachineOperand &MO = getOperand(i);
1140 if (!MO.isReg() || !MO.isImplicit())
1141 NumOperands++;
1143 return NumOperands;
1146 void MachineInstr::bundleWithPred() {
1147 assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
1148 setFlag(BundledPred);
1149 MachineBasicBlock::instr_iterator Pred = getIterator();
1150 --Pred;
1151 assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
1152 Pred->setFlag(BundledSucc);
1155 void MachineInstr::bundleWithSucc() {
1156 assert(!isBundledWithSucc() && "MI is already bundled with its successor");
1157 setFlag(BundledSucc);
1158 MachineBasicBlock::instr_iterator Succ = getIterator();
1159 ++Succ;
1160 assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
1161 Succ->setFlag(BundledPred);
1164 void MachineInstr::unbundleFromPred() {
1165 assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
1166 clearFlag(BundledPred);
1167 MachineBasicBlock::instr_iterator Pred = getIterator();
1168 --Pred;
1169 assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
1170 Pred->clearFlag(BundledSucc);
1173 void MachineInstr::unbundleFromSucc() {
1174 assert(isBundledWithSucc() && "MI isn't bundled with its successor");
1175 clearFlag(BundledSucc);
1176 MachineBasicBlock::instr_iterator Succ = getIterator();
1177 ++Succ;
1178 assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
1179 Succ->clearFlag(BundledPred);
1182 bool MachineInstr::isStackAligningInlineAsm() const {
1183 if (isInlineAsm()) {
1184 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1185 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1186 return true;
1188 return false;
1191 InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
1192 assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
1193 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1194 return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
1197 int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
1198 unsigned *GroupNo) const {
1199 assert(isInlineAsm() && "Expected an inline asm instruction");
1200 assert(OpIdx < getNumOperands() && "OpIdx out of range");
1202 // Ignore queries about the initial operands.
1203 if (OpIdx < InlineAsm::MIOp_FirstOperand)
1204 return -1;
1206 unsigned Group = 0;
1207 unsigned NumOps;
1208 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1209 i += NumOps) {
1210 const MachineOperand &FlagMO = getOperand(i);
1211 // If we reach the implicit register operands, stop looking.
1212 if (!FlagMO.isImm())
1213 return -1;
1214 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1215 if (i + NumOps > OpIdx) {
1216 if (GroupNo)
1217 *GroupNo = Group;
1218 return i;
1220 ++Group;
1222 return -1;
1225 const DILocalVariable *MachineInstr::getDebugVariable() const {
1226 assert(isDebugValue() && "not a DBG_VALUE");
1227 return cast<DILocalVariable>(getOperand(2).getMetadata());
1230 const DIExpression *MachineInstr::getDebugExpression() const {
1231 assert(isDebugValue() && "not a DBG_VALUE");
1232 return cast<DIExpression>(getOperand(3).getMetadata());
1235 const TargetRegisterClass*
1236 MachineInstr::getRegClassConstraint(unsigned OpIdx,
1237 const TargetInstrInfo *TII,
1238 const TargetRegisterInfo *TRI) const {
1239 assert(getParent() && "Can't have an MBB reference here!");
1240 assert(getParent()->getParent() && "Can't have an MF reference here!");
1241 const MachineFunction &MF = *getParent()->getParent();
1243 // Most opcodes have fixed constraints in their MCInstrDesc.
1244 if (!isInlineAsm())
1245 return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
1247 if (!getOperand(OpIdx).isReg())
1248 return nullptr;
1250 // For tied uses on inline asm, get the constraint from the def.
1251 unsigned DefIdx;
1252 if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
1253 OpIdx = DefIdx;
1255 // Inline asm stores register class constraints in the flag word.
1256 int FlagIdx = findInlineAsmFlagIdx(OpIdx);
1257 if (FlagIdx < 0)
1258 return nullptr;
1260 unsigned Flag = getOperand(FlagIdx).getImm();
1261 unsigned RCID;
1262 if ((InlineAsm::getKind(Flag) == InlineAsm::Kind_RegUse ||
1263 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDef ||
1264 InlineAsm::getKind(Flag) == InlineAsm::Kind_RegDefEarlyClobber) &&
1265 InlineAsm::hasRegClassConstraint(Flag, RCID))
1266 return TRI->getRegClass(RCID);
1268 // Assume that all registers in a memory operand are pointers.
1269 if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
1270 return TRI->getPointerRegClass(MF);
1272 return nullptr;
1275 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVReg(
1276 unsigned Reg, const TargetRegisterClass *CurRC, const TargetInstrInfo *TII,
1277 const TargetRegisterInfo *TRI, bool ExploreBundle) const {
1278 // Check every operands inside the bundle if we have
1279 // been asked to.
1280 if (ExploreBundle)
1281 for (ConstMIBundleOperands OpndIt(*this); OpndIt.isValid() && CurRC;
1282 ++OpndIt)
1283 CurRC = OpndIt->getParent()->getRegClassConstraintEffectForVRegImpl(
1284 OpndIt.getOperandNo(), Reg, CurRC, TII, TRI);
1285 else
1286 // Otherwise, just check the current operands.
1287 for (unsigned i = 0, e = NumOperands; i < e && CurRC; ++i)
1288 CurRC = getRegClassConstraintEffectForVRegImpl(i, Reg, CurRC, TII, TRI);
1289 return CurRC;
1292 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffectForVRegImpl(
1293 unsigned OpIdx, unsigned Reg, const TargetRegisterClass *CurRC,
1294 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1295 assert(CurRC && "Invalid initial register class");
1296 // Check if Reg is constrained by some of its use/def from MI.
1297 const MachineOperand &MO = getOperand(OpIdx);
1298 if (!MO.isReg() || MO.getReg() != Reg)
1299 return CurRC;
1300 // If yes, accumulate the constraints through the operand.
1301 return getRegClassConstraintEffect(OpIdx, CurRC, TII, TRI);
1304 const TargetRegisterClass *MachineInstr::getRegClassConstraintEffect(
1305 unsigned OpIdx, const TargetRegisterClass *CurRC,
1306 const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const {
1307 const TargetRegisterClass *OpRC = getRegClassConstraint(OpIdx, TII, TRI);
1308 const MachineOperand &MO = getOperand(OpIdx);
1309 assert(MO.isReg() &&
1310 "Cannot get register constraints for non-register operand");
1311 assert(CurRC && "Invalid initial register class");
1312 if (unsigned SubIdx = MO.getSubReg()) {
1313 if (OpRC)
1314 CurRC = TRI->getMatchingSuperRegClass(CurRC, OpRC, SubIdx);
1315 else
1316 CurRC = TRI->getSubClassWithSubReg(CurRC, SubIdx);
1317 } else if (OpRC)
1318 CurRC = TRI->getCommonSubClass(CurRC, OpRC);
1319 return CurRC;
1322 /// Return the number of instructions inside the MI bundle, not counting the
1323 /// header instruction.
1324 unsigned MachineInstr::getBundleSize() const {
1325 MachineBasicBlock::const_instr_iterator I = getIterator();
1326 unsigned Size = 0;
1327 while (I->isBundledWithSucc()) {
1328 ++Size;
1329 ++I;
1331 return Size;
1334 /// Returns true if the MachineInstr has an implicit-use operand of exactly
1335 /// the given register (not considering sub/super-registers).
1336 bool MachineInstr::hasRegisterImplicitUseOperand(unsigned Reg) const {
1337 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1338 const MachineOperand &MO = getOperand(i);
1339 if (MO.isReg() && MO.isUse() && MO.isImplicit() && MO.getReg() == Reg)
1340 return true;
1342 return false;
1345 /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
1346 /// the specific register or -1 if it is not found. It further tightens
1347 /// the search criteria to a use that kills the register if isKill is true.
1348 int MachineInstr::findRegisterUseOperandIdx(
1349 unsigned Reg, bool isKill, const TargetRegisterInfo *TRI) const {
1350 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1351 const MachineOperand &MO = getOperand(i);
1352 if (!MO.isReg() || !MO.isUse())
1353 continue;
1354 unsigned MOReg = MO.getReg();
1355 if (!MOReg)
1356 continue;
1357 if (MOReg == Reg || (TRI && TargetRegisterInfo::isPhysicalRegister(MOReg) &&
1358 TargetRegisterInfo::isPhysicalRegister(Reg) &&
1359 TRI->isSubRegister(MOReg, Reg)))
1360 if (!isKill || MO.isKill())
1361 return i;
1363 return -1;
1366 /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
1367 /// indicating if this instruction reads or writes Reg. This also considers
1368 /// partial defines.
1369 std::pair<bool,bool>
1370 MachineInstr::readsWritesVirtualRegister(unsigned Reg,
1371 SmallVectorImpl<unsigned> *Ops) const {
1372 bool PartDef = false; // Partial redefine.
1373 bool FullDef = false; // Full define.
1374 bool Use = false;
1376 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1377 const MachineOperand &MO = getOperand(i);
1378 if (!MO.isReg() || MO.getReg() != Reg)
1379 continue;
1380 if (Ops)
1381 Ops->push_back(i);
1382 if (MO.isUse())
1383 Use |= !MO.isUndef();
1384 else if (MO.getSubReg() && !MO.isUndef())
1385 // A partial <def,undef> doesn't count as reading the register.
1386 PartDef = true;
1387 else
1388 FullDef = true;
1390 // A partial redefine uses Reg unless there is also a full define.
1391 return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
1394 /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
1395 /// the specified register or -1 if it is not found. If isDead is true, defs
1396 /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
1397 /// also checks if there is a def of a super-register.
1399 MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
1400 const TargetRegisterInfo *TRI) const {
1401 bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
1402 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1403 const MachineOperand &MO = getOperand(i);
1404 // Accept regmask operands when Overlap is set.
1405 // Ignore them when looking for a specific def operand (Overlap == false).
1406 if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
1407 return i;
1408 if (!MO.isReg() || !MO.isDef())
1409 continue;
1410 unsigned MOReg = MO.getReg();
1411 bool Found = (MOReg == Reg);
1412 if (!Found && TRI && isPhys &&
1413 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
1414 if (Overlap)
1415 Found = TRI->regsOverlap(MOReg, Reg);
1416 else
1417 Found = TRI->isSubRegister(MOReg, Reg);
1419 if (Found && (!isDead || MO.isDead()))
1420 return i;
1422 return -1;
1425 /// findFirstPredOperandIdx() - Find the index of the first operand in the
1426 /// operand list that is used to represent the predicate. It returns -1 if
1427 /// none is found.
1428 int MachineInstr::findFirstPredOperandIdx() const {
1429 // Don't call MCID.findFirstPredOperandIdx() because this variant
1430 // is sometimes called on an instruction that's not yet complete, and
1431 // so the number of operands is less than the MCID indicates. In
1432 // particular, the PTX target does this.
1433 const MCInstrDesc &MCID = getDesc();
1434 if (MCID.isPredicable()) {
1435 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
1436 if (MCID.OpInfo[i].isPredicate())
1437 return i;
1440 return -1;
1443 // MachineOperand::TiedTo is 4 bits wide.
1444 const unsigned TiedMax = 15;
1446 /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
1448 /// Use and def operands can be tied together, indicated by a non-zero TiedTo
1449 /// field. TiedTo can have these values:
1451 /// 0: Operand is not tied to anything.
1452 /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
1453 /// TiedMax: Tied to an operand >= TiedMax-1.
1455 /// The tied def must be one of the first TiedMax operands on a normal
1456 /// instruction. INLINEASM instructions allow more tied defs.
1458 void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
1459 MachineOperand &DefMO = getOperand(DefIdx);
1460 MachineOperand &UseMO = getOperand(UseIdx);
1461 assert(DefMO.isDef() && "DefIdx must be a def operand");
1462 assert(UseMO.isUse() && "UseIdx must be a use operand");
1463 assert(!DefMO.isTied() && "Def is already tied to another use");
1464 assert(!UseMO.isTied() && "Use is already tied to another def");
1466 if (DefIdx < TiedMax)
1467 UseMO.TiedTo = DefIdx + 1;
1468 else {
1469 // Inline asm can use the group descriptors to find tied operands, but on
1470 // normal instruction, the tied def must be within the first TiedMax
1471 // operands.
1472 assert(isInlineAsm() && "DefIdx out of range");
1473 UseMO.TiedTo = TiedMax;
1476 // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
1477 DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
1480 /// Given the index of a tied register operand, find the operand it is tied to.
1481 /// Defs are tied to uses and vice versa. Returns the index of the tied operand
1482 /// which must exist.
1483 unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
1484 const MachineOperand &MO = getOperand(OpIdx);
1485 assert(MO.isTied() && "Operand isn't tied");
1487 // Normally TiedTo is in range.
1488 if (MO.TiedTo < TiedMax)
1489 return MO.TiedTo - 1;
1491 // Uses on normal instructions can be out of range.
1492 if (!isInlineAsm()) {
1493 // Normal tied defs must be in the 0..TiedMax-1 range.
1494 if (MO.isUse())
1495 return TiedMax - 1;
1496 // MO is a def. Search for the tied use.
1497 for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
1498 const MachineOperand &UseMO = getOperand(i);
1499 if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
1500 return i;
1502 llvm_unreachable("Can't find tied use");
1505 // Now deal with inline asm by parsing the operand group descriptor flags.
1506 // Find the beginning of each operand group.
1507 SmallVector<unsigned, 8> GroupIdx;
1508 unsigned OpIdxGroup = ~0u;
1509 unsigned NumOps;
1510 for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
1511 i += NumOps) {
1512 const MachineOperand &FlagMO = getOperand(i);
1513 assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
1514 unsigned CurGroup = GroupIdx.size();
1515 GroupIdx.push_back(i);
1516 NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
1517 // OpIdx belongs to this operand group.
1518 if (OpIdx > i && OpIdx < i + NumOps)
1519 OpIdxGroup = CurGroup;
1520 unsigned TiedGroup;
1521 if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
1522 continue;
1523 // Operands in this group are tied to operands in TiedGroup which must be
1524 // earlier. Find the number of operands between the two groups.
1525 unsigned Delta = i - GroupIdx[TiedGroup];
1527 // OpIdx is a use tied to TiedGroup.
1528 if (OpIdxGroup == CurGroup)
1529 return OpIdx - Delta;
1531 // OpIdx is a def tied to this use group.
1532 if (OpIdxGroup == TiedGroup)
1533 return OpIdx + Delta;
1535 llvm_unreachable("Invalid tied operand on inline asm");
1538 /// clearKillInfo - Clears kill flags on all operands.
1540 void MachineInstr::clearKillInfo() {
1541 for (MachineOperand &MO : operands()) {
1542 if (MO.isReg() && MO.isUse())
1543 MO.setIsKill(false);
1547 void MachineInstr::substituteRegister(unsigned FromReg,
1548 unsigned ToReg,
1549 unsigned SubIdx,
1550 const TargetRegisterInfo &RegInfo) {
1551 if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
1552 if (SubIdx)
1553 ToReg = RegInfo.getSubReg(ToReg, SubIdx);
1554 for (MachineOperand &MO : operands()) {
1555 if (!MO.isReg() || MO.getReg() != FromReg)
1556 continue;
1557 MO.substPhysReg(ToReg, RegInfo);
1559 } else {
1560 for (MachineOperand &MO : operands()) {
1561 if (!MO.isReg() || MO.getReg() != FromReg)
1562 continue;
1563 MO.substVirtReg(ToReg, SubIdx, RegInfo);
1568 /// isSafeToMove - Return true if it is safe to move this instruction. If
1569 /// SawStore is set to true, it means that there is a store (or call) between
1570 /// the instruction's location and its intended destination.
1571 bool MachineInstr::isSafeToMove(AliasAnalysis *AA, bool &SawStore) const {
1572 // Ignore stuff that we obviously can't move.
1574 // Treat volatile loads as stores. This is not strictly necessary for
1575 // volatiles, but it is required for atomic loads. It is not allowed to move
1576 // a load across an atomic load with Ordering > Monotonic.
1577 if (mayStore() || isCall() ||
1578 (mayLoad() && hasOrderedMemoryRef())) {
1579 SawStore = true;
1580 return false;
1583 if (isPosition() || isDebugValue() || isTerminator() ||
1584 hasUnmodeledSideEffects())
1585 return false;
1587 // See if this instruction does a load. If so, we have to guarantee that the
1588 // loaded value doesn't change between the load and the its intended
1589 // destination. The check for isInvariantLoad gives the targe the chance to
1590 // classify the load as always returning a constant, e.g. a constant pool
1591 // load.
1592 if (mayLoad() && !isDereferenceableInvariantLoad(AA))
1593 // Otherwise, this is a real load. If there is a store between the load and
1594 // end of block, we can't move it.
1595 return !SawStore;
1597 return true;
1600 bool MachineInstr::mayAlias(AliasAnalysis *AA, MachineInstr &Other,
1601 bool UseTBAA) {
1602 const MachineFunction *MF = getParent()->getParent();
1603 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1605 // If neither instruction stores to memory, they can't alias in any
1606 // meaningful way, even if they read from the same address.
1607 if (!mayStore() && !Other.mayStore())
1608 return false;
1610 // Let the target decide if memory accesses cannot possibly overlap.
1611 if (TII->areMemAccessesTriviallyDisjoint(*this, Other, AA))
1612 return false;
1614 if (!AA)
1615 return true;
1617 // FIXME: Need to handle multiple memory operands to support all targets.
1618 if (!hasOneMemOperand() || !Other.hasOneMemOperand())
1619 return true;
1621 MachineMemOperand *MMOa = *memoperands_begin();
1622 MachineMemOperand *MMOb = *Other.memoperands_begin();
1624 if (!MMOa->getValue() || !MMOb->getValue())
1625 return true;
1627 // The following interface to AA is fashioned after DAGCombiner::isAlias
1628 // and operates with MachineMemOperand offset with some important
1629 // assumptions:
1630 // - LLVM fundamentally assumes flat address spaces.
1631 // - MachineOperand offset can *only* result from legalization and
1632 // cannot affect queries other than the trivial case of overlap
1633 // checking.
1634 // - These offsets never wrap and never step outside
1635 // of allocated objects.
1636 // - There should never be any negative offsets here.
1638 // FIXME: Modify API to hide this math from "user"
1639 // FIXME: Even before we go to AA we can reason locally about some
1640 // memory objects. It can save compile time, and possibly catch some
1641 // corner cases not currently covered.
1643 assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
1644 assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
1646 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
1647 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
1648 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
1650 AliasResult AAResult =
1651 AA->alias(MemoryLocation(MMOa->getValue(), Overlapa,
1652 UseTBAA ? MMOa->getAAInfo() : AAMDNodes()),
1653 MemoryLocation(MMOb->getValue(), Overlapb,
1654 UseTBAA ? MMOb->getAAInfo() : AAMDNodes()));
1656 return (AAResult != NoAlias);
1659 /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
1660 /// or volatile memory reference, or if the information describing the memory
1661 /// reference is not available. Return false if it is known to have no ordered
1662 /// memory references.
1663 bool MachineInstr::hasOrderedMemoryRef() const {
1664 // An instruction known never to access memory won't have a volatile access.
1665 if (!mayStore() &&
1666 !mayLoad() &&
1667 !isCall() &&
1668 !hasUnmodeledSideEffects())
1669 return false;
1671 // Otherwise, if the instruction has no memory reference information,
1672 // conservatively assume it wasn't preserved.
1673 if (memoperands_empty())
1674 return true;
1676 // Check if any of our memory operands are ordered.
1677 return any_of(memoperands(), [](const MachineMemOperand *MMO) {
1678 return !MMO->isUnordered();
1682 /// isDereferenceableInvariantLoad - Return true if this instruction will never
1683 /// trap and is loading from a location whose value is invariant across a run of
1684 /// this function.
1685 bool MachineInstr::isDereferenceableInvariantLoad(AliasAnalysis *AA) const {
1686 // If the instruction doesn't load at all, it isn't an invariant load.
1687 if (!mayLoad())
1688 return false;
1690 // If the instruction has lost its memoperands, conservatively assume that
1691 // it may not be an invariant load.
1692 if (memoperands_empty())
1693 return false;
1695 const MachineFrameInfo &MFI = getParent()->getParent()->getFrameInfo();
1697 for (MachineMemOperand *MMO : memoperands()) {
1698 if (MMO->isVolatile()) return false;
1699 if (MMO->isStore()) return false;
1700 if (MMO->isInvariant() && MMO->isDereferenceable())
1701 continue;
1703 // A load from a constant PseudoSourceValue is invariant.
1704 if (const PseudoSourceValue *PSV = MMO->getPseudoValue())
1705 if (PSV->isConstant(&MFI))
1706 continue;
1708 if (const Value *V = MMO->getValue()) {
1709 // If we have an AliasAnalysis, ask it whether the memory is constant.
1710 if (AA &&
1711 AA->pointsToConstantMemory(
1712 MemoryLocation(V, MMO->getSize(), MMO->getAAInfo())))
1713 continue;
1716 // Otherwise assume conservatively.
1717 return false;
1720 // Everything checks out.
1721 return true;
1724 /// isConstantValuePHI - If the specified instruction is a PHI that always
1725 /// merges together the same virtual register, return the register, otherwise
1726 /// return 0.
1727 unsigned MachineInstr::isConstantValuePHI() const {
1728 if (!isPHI())
1729 return 0;
1730 assert(getNumOperands() >= 3 &&
1731 "It's illegal to have a PHI without source operands");
1733 unsigned Reg = getOperand(1).getReg();
1734 for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
1735 if (getOperand(i).getReg() != Reg)
1736 return 0;
1737 return Reg;
1740 bool MachineInstr::hasUnmodeledSideEffects() const {
1741 if (hasProperty(MCID::UnmodeledSideEffects))
1742 return true;
1743 if (isInlineAsm()) {
1744 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1745 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1746 return true;
1749 return false;
1752 bool MachineInstr::isLoadFoldBarrier() const {
1753 return mayStore() || isCall() || hasUnmodeledSideEffects();
1756 /// allDefsAreDead - Return true if all the defs of this instruction are dead.
1758 bool MachineInstr::allDefsAreDead() const {
1759 for (const MachineOperand &MO : operands()) {
1760 if (!MO.isReg() || MO.isUse())
1761 continue;
1762 if (!MO.isDead())
1763 return false;
1765 return true;
1768 /// copyImplicitOps - Copy implicit register operands from specified
1769 /// instruction to this instruction.
1770 void MachineInstr::copyImplicitOps(MachineFunction &MF,
1771 const MachineInstr &MI) {
1772 for (unsigned i = MI.getDesc().getNumOperands(), e = MI.getNumOperands();
1773 i != e; ++i) {
1774 const MachineOperand &MO = MI.getOperand(i);
1775 if ((MO.isReg() && MO.isImplicit()) || MO.isRegMask())
1776 addOperand(MF, MO);
1780 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1781 LLVM_DUMP_METHOD void MachineInstr::dump() const {
1782 dbgs() << " ";
1783 print(dbgs());
1785 #endif
1787 void MachineInstr::print(raw_ostream &OS, bool SkipOpers, bool SkipDebugLoc,
1788 const TargetInstrInfo *TII) const {
1789 const Module *M = nullptr;
1790 if (const MachineBasicBlock *MBB = getParent())
1791 if (const MachineFunction *MF = MBB->getParent())
1792 M = MF->getFunction()->getParent();
1794 ModuleSlotTracker MST(M);
1795 print(OS, MST, SkipOpers, SkipDebugLoc, TII);
1798 void MachineInstr::print(raw_ostream &OS, ModuleSlotTracker &MST,
1799 bool SkipOpers, bool SkipDebugLoc,
1800 const TargetInstrInfo *TII) const {
1801 // We can be a bit tidier if we know the MachineFunction.
1802 const MachineFunction *MF = nullptr;
1803 const TargetRegisterInfo *TRI = nullptr;
1804 const MachineRegisterInfo *MRI = nullptr;
1805 const TargetIntrinsicInfo *IntrinsicInfo = nullptr;
1807 if (const MachineBasicBlock *MBB = getParent()) {
1808 MF = MBB->getParent();
1809 if (MF) {
1810 MRI = &MF->getRegInfo();
1811 TRI = MF->getSubtarget().getRegisterInfo();
1812 if (!TII)
1813 TII = MF->getSubtarget().getInstrInfo();
1814 IntrinsicInfo = MF->getTarget().getIntrinsicInfo();
1818 // Save a list of virtual registers.
1819 SmallVector<unsigned, 8> VirtRegs;
1821 // Print explicitly defined operands on the left of an assignment syntax.
1822 unsigned StartOp = 0, e = getNumOperands();
1823 for (; StartOp < e && getOperand(StartOp).isReg() &&
1824 getOperand(StartOp).isDef() &&
1825 !getOperand(StartOp).isImplicit();
1826 ++StartOp) {
1827 if (StartOp != 0) OS << ", ";
1828 getOperand(StartOp).print(OS, MST, TRI, IntrinsicInfo);
1829 unsigned Reg = getOperand(StartOp).getReg();
1830 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1831 VirtRegs.push_back(Reg);
1832 LLT Ty = MRI ? MRI->getType(Reg) : LLT{};
1833 if (Ty.isValid())
1834 OS << '(' << Ty << ')';
1838 if (StartOp != 0)
1839 OS << " = ";
1841 // Print the opcode name.
1842 if (TII)
1843 OS << TII->getName(getOpcode());
1844 else
1845 OS << "UNKNOWN";
1847 if (SkipOpers)
1848 return;
1850 // Print the rest of the operands.
1851 bool OmittedAnyCallClobbers = false;
1852 bool FirstOp = true;
1853 unsigned AsmDescOp = ~0u;
1854 unsigned AsmOpCount = 0;
1856 if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
1857 // Print asm string.
1858 OS << " ";
1859 getOperand(InlineAsm::MIOp_AsmString).print(OS, MST, TRI);
1861 // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
1862 unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
1863 if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
1864 OS << " [sideeffect]";
1865 if (ExtraInfo & InlineAsm::Extra_MayLoad)
1866 OS << " [mayload]";
1867 if (ExtraInfo & InlineAsm::Extra_MayStore)
1868 OS << " [maystore]";
1869 if (ExtraInfo & InlineAsm::Extra_IsConvergent)
1870 OS << " [isconvergent]";
1871 if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
1872 OS << " [alignstack]";
1873 if (getInlineAsmDialect() == InlineAsm::AD_ATT)
1874 OS << " [attdialect]";
1875 if (getInlineAsmDialect() == InlineAsm::AD_Intel)
1876 OS << " [inteldialect]";
1878 StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
1879 FirstOp = false;
1882 for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
1883 const MachineOperand &MO = getOperand(i);
1885 if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
1886 VirtRegs.push_back(MO.getReg());
1888 // Omit call-clobbered registers which aren't used anywhere. This makes
1889 // call instructions much less noisy on targets where calls clobber lots
1890 // of registers. Don't rely on MO.isDead() because we may be called before
1891 // LiveVariables is run, or we may be looking at a non-allocatable reg.
1892 if (MRI && isCall() &&
1893 MO.isReg() && MO.isImplicit() && MO.isDef()) {
1894 unsigned Reg = MO.getReg();
1895 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
1896 if (MRI->use_empty(Reg)) {
1897 bool HasAliasLive = false;
1898 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
1899 unsigned AliasReg = *AI;
1900 if (!MRI->use_empty(AliasReg)) {
1901 HasAliasLive = true;
1902 break;
1905 if (!HasAliasLive) {
1906 OmittedAnyCallClobbers = true;
1907 continue;
1913 if (FirstOp) FirstOp = false; else OS << ",";
1914 OS << " ";
1915 if (i < getDesc().NumOperands) {
1916 const MCOperandInfo &MCOI = getDesc().OpInfo[i];
1917 if (MCOI.isPredicate())
1918 OS << "pred:";
1919 if (MCOI.isOptionalDef())
1920 OS << "opt:";
1922 if (isDebugValue() && MO.isMetadata()) {
1923 // Pretty print DBG_VALUE instructions.
1924 auto *DIV = dyn_cast<DILocalVariable>(MO.getMetadata());
1925 if (DIV && !DIV->getName().empty())
1926 OS << "!\"" << DIV->getName() << '\"';
1927 else
1928 MO.print(OS, MST, TRI);
1929 } else if (TRI && (isInsertSubreg() || isRegSequence() ||
1930 (isSubregToReg() && i == 3)) && MO.isImm()) {
1931 OS << TRI->getSubRegIndexName(MO.getImm());
1932 } else if (i == AsmDescOp && MO.isImm()) {
1933 // Pretty print the inline asm operand descriptor.
1934 OS << '$' << AsmOpCount++;
1935 unsigned Flag = MO.getImm();
1936 switch (InlineAsm::getKind(Flag)) {
1937 case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
1938 case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
1939 case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
1940 case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
1941 case InlineAsm::Kind_Imm: OS << ":[imm"; break;
1942 case InlineAsm::Kind_Mem: OS << ":[mem"; break;
1943 default: OS << ":[??" << InlineAsm::getKind(Flag); break;
1946 unsigned RCID = 0;
1947 if (!InlineAsm::isImmKind(Flag) && !InlineAsm::isMemKind(Flag) &&
1948 InlineAsm::hasRegClassConstraint(Flag, RCID)) {
1949 if (TRI) {
1950 OS << ':' << TRI->getRegClassName(TRI->getRegClass(RCID));
1951 } else
1952 OS << ":RC" << RCID;
1955 if (InlineAsm::isMemKind(Flag)) {
1956 unsigned MCID = InlineAsm::getMemoryConstraintID(Flag);
1957 switch (MCID) {
1958 case InlineAsm::Constraint_es: OS << ":es"; break;
1959 case InlineAsm::Constraint_i: OS << ":i"; break;
1960 case InlineAsm::Constraint_m: OS << ":m"; break;
1961 case InlineAsm::Constraint_o: OS << ":o"; break;
1962 case InlineAsm::Constraint_v: OS << ":v"; break;
1963 case InlineAsm::Constraint_Q: OS << ":Q"; break;
1964 case InlineAsm::Constraint_R: OS << ":R"; break;
1965 case InlineAsm::Constraint_S: OS << ":S"; break;
1966 case InlineAsm::Constraint_T: OS << ":T"; break;
1967 case InlineAsm::Constraint_Um: OS << ":Um"; break;
1968 case InlineAsm::Constraint_Un: OS << ":Un"; break;
1969 case InlineAsm::Constraint_Uq: OS << ":Uq"; break;
1970 case InlineAsm::Constraint_Us: OS << ":Us"; break;
1971 case InlineAsm::Constraint_Ut: OS << ":Ut"; break;
1972 case InlineAsm::Constraint_Uv: OS << ":Uv"; break;
1973 case InlineAsm::Constraint_Uy: OS << ":Uy"; break;
1974 case InlineAsm::Constraint_X: OS << ":X"; break;
1975 case InlineAsm::Constraint_Z: OS << ":Z"; break;
1976 case InlineAsm::Constraint_ZC: OS << ":ZC"; break;
1977 case InlineAsm::Constraint_Zy: OS << ":Zy"; break;
1978 default: OS << ":?"; break;
1982 unsigned TiedTo = 0;
1983 if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
1984 OS << " tiedto:$" << TiedTo;
1986 OS << ']';
1988 // Compute the index of the next operand descriptor.
1989 AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
1990 } else
1991 MO.print(OS, MST, TRI);
1994 // Briefly indicate whether any call clobbers were omitted.
1995 if (OmittedAnyCallClobbers) {
1996 if (!FirstOp) OS << ",";
1997 OS << " ...";
2000 bool HaveSemi = false;
2001 const unsigned PrintableFlags = FrameSetup | FrameDestroy;
2002 if (Flags & PrintableFlags) {
2003 if (!HaveSemi) {
2004 OS << ";";
2005 HaveSemi = true;
2007 OS << " flags: ";
2009 if (Flags & FrameSetup)
2010 OS << "FrameSetup";
2012 if (Flags & FrameDestroy)
2013 OS << "FrameDestroy";
2016 if (!memoperands_empty()) {
2017 if (!HaveSemi) {
2018 OS << ";";
2019 HaveSemi = true;
2022 OS << " mem:";
2023 for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
2024 i != e; ++i) {
2025 (*i)->print(OS, MST);
2026 if (std::next(i) != e)
2027 OS << " ";
2031 // Print the regclass of any virtual registers encountered.
2032 if (MRI && !VirtRegs.empty()) {
2033 if (!HaveSemi) {
2034 OS << ";";
2035 HaveSemi = true;
2037 for (unsigned i = 0; i != VirtRegs.size(); ++i) {
2038 const RegClassOrRegBank &RC = MRI->getRegClassOrRegBank(VirtRegs[i]);
2039 if (!RC)
2040 continue;
2041 // Generic virtual registers do not have register classes.
2042 if (RC.is<const RegisterBank *>())
2043 OS << " " << RC.get<const RegisterBank *>()->getName();
2044 else
2045 OS << " "
2046 << TRI->getRegClassName(RC.get<const TargetRegisterClass *>());
2047 OS << ':' << PrintReg(VirtRegs[i]);
2048 for (unsigned j = i+1; j != VirtRegs.size();) {
2049 if (MRI->getRegClassOrRegBank(VirtRegs[j]) != RC) {
2050 ++j;
2051 continue;
2053 if (VirtRegs[i] != VirtRegs[j])
2054 OS << "," << PrintReg(VirtRegs[j]);
2055 VirtRegs.erase(VirtRegs.begin()+j);
2060 // Print debug location information.
2061 if (isDebugValue() && getOperand(e - 2).isMetadata()) {
2062 if (!HaveSemi)
2063 OS << ";";
2064 auto *DV = cast<DILocalVariable>(getOperand(e - 2).getMetadata());
2065 OS << " line no:" << DV->getLine();
2066 if (auto *InlinedAt = debugLoc->getInlinedAt()) {
2067 DebugLoc InlinedAtDL(InlinedAt);
2068 if (InlinedAtDL && MF) {
2069 OS << " inlined @[ ";
2070 InlinedAtDL.print(OS);
2071 OS << " ]";
2074 if (isIndirectDebugValue())
2075 OS << " indirect";
2076 } else if (SkipDebugLoc) {
2077 return;
2078 } else if (debugLoc && MF) {
2079 if (!HaveSemi)
2080 OS << ";";
2081 OS << " dbg:";
2082 debugLoc.print(OS);
2085 OS << '\n';
2088 bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
2089 const TargetRegisterInfo *RegInfo,
2090 bool AddIfNotFound) {
2091 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
2092 bool hasAliases = isPhysReg &&
2093 MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
2094 bool Found = false;
2095 SmallVector<unsigned,4> DeadOps;
2096 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2097 MachineOperand &MO = getOperand(i);
2098 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
2099 continue;
2101 // DEBUG_VALUE nodes do not contribute to code generation and should
2102 // always be ignored. Failure to do so may result in trying to modify
2103 // KILL flags on DEBUG_VALUE nodes.
2104 if (MO.isDebug())
2105 continue;
2107 unsigned Reg = MO.getReg();
2108 if (!Reg)
2109 continue;
2111 if (Reg == IncomingReg) {
2112 if (!Found) {
2113 if (MO.isKill())
2114 // The register is already marked kill.
2115 return true;
2116 if (isPhysReg && isRegTiedToDefOperand(i))
2117 // Two-address uses of physregs must not be marked kill.
2118 return true;
2119 MO.setIsKill();
2120 Found = true;
2122 } else if (hasAliases && MO.isKill() &&
2123 TargetRegisterInfo::isPhysicalRegister(Reg)) {
2124 // A super-register kill already exists.
2125 if (RegInfo->isSuperRegister(IncomingReg, Reg))
2126 return true;
2127 if (RegInfo->isSubRegister(IncomingReg, Reg))
2128 DeadOps.push_back(i);
2132 // Trim unneeded kill operands.
2133 while (!DeadOps.empty()) {
2134 unsigned OpIdx = DeadOps.back();
2135 if (getOperand(OpIdx).isImplicit())
2136 RemoveOperand(OpIdx);
2137 else
2138 getOperand(OpIdx).setIsKill(false);
2139 DeadOps.pop_back();
2142 // If not found, this means an alias of one of the operands is killed. Add a
2143 // new implicit operand if required.
2144 if (!Found && AddIfNotFound) {
2145 addOperand(MachineOperand::CreateReg(IncomingReg,
2146 false /*IsDef*/,
2147 true /*IsImp*/,
2148 true /*IsKill*/));
2149 return true;
2151 return Found;
2154 void MachineInstr::clearRegisterKills(unsigned Reg,
2155 const TargetRegisterInfo *RegInfo) {
2156 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
2157 RegInfo = nullptr;
2158 for (MachineOperand &MO : operands()) {
2159 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
2160 continue;
2161 unsigned OpReg = MO.getReg();
2162 if ((RegInfo && RegInfo->regsOverlap(Reg, OpReg)) || Reg == OpReg)
2163 MO.setIsKill(false);
2167 bool MachineInstr::addRegisterDead(unsigned Reg,
2168 const TargetRegisterInfo *RegInfo,
2169 bool AddIfNotFound) {
2170 bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
2171 bool hasAliases = isPhysReg &&
2172 MCRegAliasIterator(Reg, RegInfo, false).isValid();
2173 bool Found = false;
2174 SmallVector<unsigned,4> DeadOps;
2175 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2176 MachineOperand &MO = getOperand(i);
2177 if (!MO.isReg() || !MO.isDef())
2178 continue;
2179 unsigned MOReg = MO.getReg();
2180 if (!MOReg)
2181 continue;
2183 if (MOReg == Reg) {
2184 MO.setIsDead();
2185 Found = true;
2186 } else if (hasAliases && MO.isDead() &&
2187 TargetRegisterInfo::isPhysicalRegister(MOReg)) {
2188 // There exists a super-register that's marked dead.
2189 if (RegInfo->isSuperRegister(Reg, MOReg))
2190 return true;
2191 if (RegInfo->isSubRegister(Reg, MOReg))
2192 DeadOps.push_back(i);
2196 // Trim unneeded dead operands.
2197 while (!DeadOps.empty()) {
2198 unsigned OpIdx = DeadOps.back();
2199 if (getOperand(OpIdx).isImplicit())
2200 RemoveOperand(OpIdx);
2201 else
2202 getOperand(OpIdx).setIsDead(false);
2203 DeadOps.pop_back();
2206 // If not found, this means an alias of one of the operands is dead. Add a
2207 // new implicit operand if required.
2208 if (Found || !AddIfNotFound)
2209 return Found;
2211 addOperand(MachineOperand::CreateReg(Reg,
2212 true /*IsDef*/,
2213 true /*IsImp*/,
2214 false /*IsKill*/,
2215 true /*IsDead*/));
2216 return true;
2219 void MachineInstr::clearRegisterDeads(unsigned Reg) {
2220 for (MachineOperand &MO : operands()) {
2221 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg)
2222 continue;
2223 MO.setIsDead(false);
2227 void MachineInstr::setRegisterDefReadUndef(unsigned Reg, bool IsUndef) {
2228 for (MachineOperand &MO : operands()) {
2229 if (!MO.isReg() || !MO.isDef() || MO.getReg() != Reg || MO.getSubReg() == 0)
2230 continue;
2231 MO.setIsUndef(IsUndef);
2235 void MachineInstr::addRegisterDefined(unsigned Reg,
2236 const TargetRegisterInfo *RegInfo) {
2237 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
2238 MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
2239 if (MO)
2240 return;
2241 } else {
2242 for (const MachineOperand &MO : operands()) {
2243 if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
2244 MO.getSubReg() == 0)
2245 return;
2248 addOperand(MachineOperand::CreateReg(Reg,
2249 true /*IsDef*/,
2250 true /*IsImp*/));
2253 void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
2254 const TargetRegisterInfo &TRI) {
2255 bool HasRegMask = false;
2256 for (MachineOperand &MO : operands()) {
2257 if (MO.isRegMask()) {
2258 HasRegMask = true;
2259 continue;
2261 if (!MO.isReg() || !MO.isDef()) continue;
2262 unsigned Reg = MO.getReg();
2263 if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
2264 // If there are no uses, including partial uses, the def is dead.
2265 if (none_of(UsedRegs,
2266 [&](unsigned Use) { return TRI.regsOverlap(Use, Reg); }))
2267 MO.setIsDead();
2270 // This is a call with a register mask operand.
2271 // Mask clobbers are always dead, so add defs for the non-dead defines.
2272 if (HasRegMask)
2273 for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
2274 I != E; ++I)
2275 addRegisterDefined(*I, &TRI);
2278 unsigned
2279 MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
2280 // Build up a buffer of hash code components.
2281 SmallVector<size_t, 8> HashComponents;
2282 HashComponents.reserve(MI->getNumOperands() + 1);
2283 HashComponents.push_back(MI->getOpcode());
2284 for (const MachineOperand &MO : MI->operands()) {
2285 if (MO.isReg() && MO.isDef() &&
2286 TargetRegisterInfo::isVirtualRegister(MO.getReg()))
2287 continue; // Skip virtual register defs.
2289 HashComponents.push_back(hash_value(MO));
2291 return hash_combine_range(HashComponents.begin(), HashComponents.end());
2294 void MachineInstr::emitError(StringRef Msg) const {
2295 // Find the source location cookie.
2296 unsigned LocCookie = 0;
2297 const MDNode *LocMD = nullptr;
2298 for (unsigned i = getNumOperands(); i != 0; --i) {
2299 if (getOperand(i-1).isMetadata() &&
2300 (LocMD = getOperand(i-1).getMetadata()) &&
2301 LocMD->getNumOperands() != 0) {
2302 if (const ConstantInt *CI =
2303 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
2304 LocCookie = CI->getZExtValue();
2305 break;
2310 if (const MachineBasicBlock *MBB = getParent())
2311 if (const MachineFunction *MF = MBB->getParent())
2312 return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
2313 report_fatal_error(Msg);
2316 MachineInstrBuilder llvm::BuildMI(MachineFunction &MF, const DebugLoc &DL,
2317 const MCInstrDesc &MCID, bool IsIndirect,
2318 unsigned Reg, unsigned Offset,
2319 const MDNode *Variable, const MDNode *Expr) {
2320 assert(isa<DILocalVariable>(Variable) && "not a variable");
2321 assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2322 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
2323 "Expected inlined-at fields to agree");
2324 if (IsIndirect)
2325 return BuildMI(MF, DL, MCID)
2326 .addReg(Reg, RegState::Debug)
2327 .addImm(Offset)
2328 .addMetadata(Variable)
2329 .addMetadata(Expr);
2330 else {
2331 assert(Offset == 0 && "A direct address cannot have an offset.");
2332 return BuildMI(MF, DL, MCID)
2333 .addReg(Reg, RegState::Debug)
2334 .addReg(0U, RegState::Debug)
2335 .addMetadata(Variable)
2336 .addMetadata(Expr);
2340 MachineInstrBuilder llvm::BuildMI(MachineBasicBlock &BB,
2341 MachineBasicBlock::iterator I,
2342 const DebugLoc &DL, const MCInstrDesc &MCID,
2343 bool IsIndirect, unsigned Reg,
2344 unsigned Offset, const MDNode *Variable,
2345 const MDNode *Expr) {
2346 assert(isa<DILocalVariable>(Variable) && "not a variable");
2347 assert(cast<DIExpression>(Expr)->isValid() && "not an expression");
2348 MachineFunction &MF = *BB.getParent();
2349 MachineInstr *MI =
2350 BuildMI(MF, DL, MCID, IsIndirect, Reg, Offset, Variable, Expr);
2351 BB.insert(I, MI);
2352 return MachineInstrBuilder(MF, MI);