PageRenderTime 55ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/3rd_party/llvm/lib/CodeGen/MachineInstr.cpp

https://code.google.com/p/softart/
C++ | 1846 lines | 1369 code | 188 blank | 289 comment | 580 complexity | dc9c3a7d27180eb4e2e2d44d7f7c2e3e MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, JSON, MPL-2.0-no-copyleft-exception, GPL-2.0, GPL-3.0, LGPL-3.0, BSD-2-Clause
  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.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/MachineInstr.h"
  14. #include "llvm/ADT/FoldingSet.h"
  15. #include "llvm/ADT/Hashing.h"
  16. #include "llvm/Analysis/AliasAnalysis.h"
  17. #include "llvm/Assembly/Writer.h"
  18. #include "llvm/CodeGen/MachineConstantPool.h"
  19. #include "llvm/CodeGen/MachineFunction.h"
  20. #include "llvm/CodeGen/MachineMemOperand.h"
  21. #include "llvm/CodeGen/MachineModuleInfo.h"
  22. #include "llvm/CodeGen/MachineRegisterInfo.h"
  23. #include "llvm/CodeGen/PseudoSourceValue.h"
  24. #include "llvm/DebugInfo.h"
  25. #include "llvm/IR/Constants.h"
  26. #include "llvm/IR/Function.h"
  27. #include "llvm/IR/InlineAsm.h"
  28. #include "llvm/IR/LLVMContext.h"
  29. #include "llvm/IR/Metadata.h"
  30. #include "llvm/IR/Module.h"
  31. #include "llvm/IR/Type.h"
  32. #include "llvm/IR/Value.h"
  33. #include "llvm/MC/MCInstrDesc.h"
  34. #include "llvm/MC/MCSymbol.h"
  35. #include "llvm/Support/Debug.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. #include "llvm/Support/MathExtras.h"
  38. #include "llvm/Support/raw_ostream.h"
  39. #include "llvm/Target/TargetInstrInfo.h"
  40. #include "llvm/Target/TargetMachine.h"
  41. #include "llvm/Target/TargetRegisterInfo.h"
  42. using namespace llvm;
  43. //===----------------------------------------------------------------------===//
  44. // MachineOperand Implementation
  45. //===----------------------------------------------------------------------===//
  46. void MachineOperand::setReg(unsigned Reg) {
  47. if (getReg() == Reg) return; // No change.
  48. // Otherwise, we have to change the register. If this operand is embedded
  49. // into a machine function, we need to update the old and new register's
  50. // use/def lists.
  51. if (MachineInstr *MI = getParent())
  52. if (MachineBasicBlock *MBB = MI->getParent())
  53. if (MachineFunction *MF = MBB->getParent()) {
  54. MachineRegisterInfo &MRI = MF->getRegInfo();
  55. MRI.removeRegOperandFromUseList(this);
  56. SmallContents.RegNo = Reg;
  57. MRI.addRegOperandToUseList(this);
  58. return;
  59. }
  60. // Otherwise, just change the register, no problem. :)
  61. SmallContents.RegNo = Reg;
  62. }
  63. void MachineOperand::substVirtReg(unsigned Reg, unsigned SubIdx,
  64. const TargetRegisterInfo &TRI) {
  65. assert(TargetRegisterInfo::isVirtualRegister(Reg));
  66. if (SubIdx && getSubReg())
  67. SubIdx = TRI.composeSubRegIndices(SubIdx, getSubReg());
  68. setReg(Reg);
  69. if (SubIdx)
  70. setSubReg(SubIdx);
  71. }
  72. void MachineOperand::substPhysReg(unsigned Reg, const TargetRegisterInfo &TRI) {
  73. assert(TargetRegisterInfo::isPhysicalRegister(Reg));
  74. if (getSubReg()) {
  75. Reg = TRI.getSubReg(Reg, getSubReg());
  76. // Note that getSubReg() may return 0 if the sub-register doesn't exist.
  77. // That won't happen in legal code.
  78. setSubReg(0);
  79. }
  80. setReg(Reg);
  81. }
  82. /// Change a def to a use, or a use to a def.
  83. void MachineOperand::setIsDef(bool Val) {
  84. assert(isReg() && "Wrong MachineOperand accessor");
  85. assert((!Val || !isDebug()) && "Marking a debug operation as def");
  86. if (IsDef == Val)
  87. return;
  88. // MRI may keep uses and defs in different list positions.
  89. if (MachineInstr *MI = getParent())
  90. if (MachineBasicBlock *MBB = MI->getParent())
  91. if (MachineFunction *MF = MBB->getParent()) {
  92. MachineRegisterInfo &MRI = MF->getRegInfo();
  93. MRI.removeRegOperandFromUseList(this);
  94. IsDef = Val;
  95. MRI.addRegOperandToUseList(this);
  96. return;
  97. }
  98. IsDef = Val;
  99. }
  100. /// ChangeToImmediate - Replace this operand with a new immediate operand of
  101. /// the specified value. If an operand is known to be an immediate already,
  102. /// the setImm method should be used.
  103. void MachineOperand::ChangeToImmediate(int64_t ImmVal) {
  104. assert((!isReg() || !isTied()) && "Cannot change a tied operand into an imm");
  105. // If this operand is currently a register operand, and if this is in a
  106. // function, deregister the operand from the register's use/def list.
  107. if (isReg() && isOnRegUseList())
  108. if (MachineInstr *MI = getParent())
  109. if (MachineBasicBlock *MBB = MI->getParent())
  110. if (MachineFunction *MF = MBB->getParent())
  111. MF->getRegInfo().removeRegOperandFromUseList(this);
  112. OpKind = MO_Immediate;
  113. Contents.ImmVal = ImmVal;
  114. }
  115. /// ChangeToRegister - Replace this operand with a new register operand of
  116. /// the specified value. If an operand is known to be an register already,
  117. /// the setReg method should be used.
  118. void MachineOperand::ChangeToRegister(unsigned Reg, bool isDef, bool isImp,
  119. bool isKill, bool isDead, bool isUndef,
  120. bool isDebug) {
  121. MachineRegisterInfo *RegInfo = 0;
  122. if (MachineInstr *MI = getParent())
  123. if (MachineBasicBlock *MBB = MI->getParent())
  124. if (MachineFunction *MF = MBB->getParent())
  125. RegInfo = &MF->getRegInfo();
  126. // If this operand is already a register operand, remove it from the
  127. // register's use/def lists.
  128. bool WasReg = isReg();
  129. if (RegInfo && WasReg)
  130. RegInfo->removeRegOperandFromUseList(this);
  131. // Change this to a register and set the reg#.
  132. OpKind = MO_Register;
  133. SmallContents.RegNo = Reg;
  134. SubReg_TargetFlags = 0;
  135. IsDef = isDef;
  136. IsImp = isImp;
  137. IsKill = isKill;
  138. IsDead = isDead;
  139. IsUndef = isUndef;
  140. IsInternalRead = false;
  141. IsEarlyClobber = false;
  142. IsDebug = isDebug;
  143. // Ensure isOnRegUseList() returns false.
  144. Contents.Reg.Prev = 0;
  145. // Preserve the tie when the operand was already a register.
  146. if (!WasReg)
  147. TiedTo = 0;
  148. // If this operand is embedded in a function, add the operand to the
  149. // register's use/def list.
  150. if (RegInfo)
  151. RegInfo->addRegOperandToUseList(this);
  152. }
  153. /// isIdenticalTo - Return true if this operand is identical to the specified
  154. /// operand. Note that this should stay in sync with the hash_value overload
  155. /// below.
  156. bool MachineOperand::isIdenticalTo(const MachineOperand &Other) const {
  157. if (getType() != Other.getType() ||
  158. getTargetFlags() != Other.getTargetFlags())
  159. return false;
  160. switch (getType()) {
  161. case MachineOperand::MO_Register:
  162. return getReg() == Other.getReg() && isDef() == Other.isDef() &&
  163. getSubReg() == Other.getSubReg();
  164. case MachineOperand::MO_Immediate:
  165. return getImm() == Other.getImm();
  166. case MachineOperand::MO_CImmediate:
  167. return getCImm() == Other.getCImm();
  168. case MachineOperand::MO_FPImmediate:
  169. return getFPImm() == Other.getFPImm();
  170. case MachineOperand::MO_MachineBasicBlock:
  171. return getMBB() == Other.getMBB();
  172. case MachineOperand::MO_FrameIndex:
  173. return getIndex() == Other.getIndex();
  174. case MachineOperand::MO_ConstantPoolIndex:
  175. case MachineOperand::MO_TargetIndex:
  176. return getIndex() == Other.getIndex() && getOffset() == Other.getOffset();
  177. case MachineOperand::MO_JumpTableIndex:
  178. return getIndex() == Other.getIndex();
  179. case MachineOperand::MO_GlobalAddress:
  180. return getGlobal() == Other.getGlobal() && getOffset() == Other.getOffset();
  181. case MachineOperand::MO_ExternalSymbol:
  182. return !strcmp(getSymbolName(), Other.getSymbolName()) &&
  183. getOffset() == Other.getOffset();
  184. case MachineOperand::MO_BlockAddress:
  185. return getBlockAddress() == Other.getBlockAddress() &&
  186. getOffset() == Other.getOffset();
  187. case MO_RegisterMask:
  188. return getRegMask() == Other.getRegMask();
  189. case MachineOperand::MO_MCSymbol:
  190. return getMCSymbol() == Other.getMCSymbol();
  191. case MachineOperand::MO_Metadata:
  192. return getMetadata() == Other.getMetadata();
  193. }
  194. llvm_unreachable("Invalid machine operand type");
  195. }
  196. // Note: this must stay exactly in sync with isIdenticalTo above.
  197. hash_code llvm::hash_value(const MachineOperand &MO) {
  198. switch (MO.getType()) {
  199. case MachineOperand::MO_Register:
  200. // Register operands don't have target flags.
  201. return hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(), MO.isDef());
  202. case MachineOperand::MO_Immediate:
  203. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
  204. case MachineOperand::MO_CImmediate:
  205. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getCImm());
  206. case MachineOperand::MO_FPImmediate:
  207. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getFPImm());
  208. case MachineOperand::MO_MachineBasicBlock:
  209. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMBB());
  210. case MachineOperand::MO_FrameIndex:
  211. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
  212. case MachineOperand::MO_ConstantPoolIndex:
  213. case MachineOperand::MO_TargetIndex:
  214. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex(),
  215. MO.getOffset());
  216. case MachineOperand::MO_JumpTableIndex:
  217. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getIndex());
  218. case MachineOperand::MO_ExternalSymbol:
  219. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getOffset(),
  220. MO.getSymbolName());
  221. case MachineOperand::MO_GlobalAddress:
  222. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getGlobal(),
  223. MO.getOffset());
  224. case MachineOperand::MO_BlockAddress:
  225. return hash_combine(MO.getType(), MO.getTargetFlags(),
  226. MO.getBlockAddress(), MO.getOffset());
  227. case MachineOperand::MO_RegisterMask:
  228. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getRegMask());
  229. case MachineOperand::MO_Metadata:
  230. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMetadata());
  231. case MachineOperand::MO_MCSymbol:
  232. return hash_combine(MO.getType(), MO.getTargetFlags(), MO.getMCSymbol());
  233. }
  234. llvm_unreachable("Invalid machine operand type");
  235. }
  236. /// print - Print the specified machine operand.
  237. ///
  238. void MachineOperand::print(raw_ostream &OS, const TargetMachine *TM) const {
  239. // If the instruction is embedded into a basic block, we can find the
  240. // target info for the instruction.
  241. if (!TM)
  242. if (const MachineInstr *MI = getParent())
  243. if (const MachineBasicBlock *MBB = MI->getParent())
  244. if (const MachineFunction *MF = MBB->getParent())
  245. TM = &MF->getTarget();
  246. const TargetRegisterInfo *TRI = TM ? TM->getRegisterInfo() : 0;
  247. switch (getType()) {
  248. case MachineOperand::MO_Register:
  249. OS << PrintReg(getReg(), TRI, getSubReg());
  250. if (isDef() || isKill() || isDead() || isImplicit() || isUndef() ||
  251. isInternalRead() || isEarlyClobber() || isTied()) {
  252. OS << '<';
  253. bool NeedComma = false;
  254. if (isDef()) {
  255. if (NeedComma) OS << ',';
  256. if (isEarlyClobber())
  257. OS << "earlyclobber,";
  258. if (isImplicit())
  259. OS << "imp-";
  260. OS << "def";
  261. NeedComma = true;
  262. // <def,read-undef> only makes sense when getSubReg() is set.
  263. // Don't clutter the output otherwise.
  264. if (isUndef() && getSubReg())
  265. OS << ",read-undef";
  266. } else if (isImplicit()) {
  267. OS << "imp-use";
  268. NeedComma = true;
  269. }
  270. if (isKill()) {
  271. if (NeedComma) OS << ',';
  272. OS << "kill";
  273. NeedComma = true;
  274. }
  275. if (isDead()) {
  276. if (NeedComma) OS << ',';
  277. OS << "dead";
  278. NeedComma = true;
  279. }
  280. if (isUndef() && isUse()) {
  281. if (NeedComma) OS << ',';
  282. OS << "undef";
  283. NeedComma = true;
  284. }
  285. if (isInternalRead()) {
  286. if (NeedComma) OS << ',';
  287. OS << "internal";
  288. NeedComma = true;
  289. }
  290. if (isTied()) {
  291. if (NeedComma) OS << ',';
  292. OS << "tied";
  293. if (TiedTo != 15)
  294. OS << unsigned(TiedTo - 1);
  295. NeedComma = true;
  296. }
  297. OS << '>';
  298. }
  299. break;
  300. case MachineOperand::MO_Immediate:
  301. OS << getImm();
  302. break;
  303. case MachineOperand::MO_CImmediate:
  304. getCImm()->getValue().print(OS, false);
  305. break;
  306. case MachineOperand::MO_FPImmediate:
  307. if (getFPImm()->getType()->isFloatTy())
  308. OS << getFPImm()->getValueAPF().convertToFloat();
  309. else
  310. OS << getFPImm()->getValueAPF().convertToDouble();
  311. break;
  312. case MachineOperand::MO_MachineBasicBlock:
  313. OS << "<BB#" << getMBB()->getNumber() << ">";
  314. break;
  315. case MachineOperand::MO_FrameIndex:
  316. OS << "<fi#" << getIndex() << '>';
  317. break;
  318. case MachineOperand::MO_ConstantPoolIndex:
  319. OS << "<cp#" << getIndex();
  320. if (getOffset()) OS << "+" << getOffset();
  321. OS << '>';
  322. break;
  323. case MachineOperand::MO_TargetIndex:
  324. OS << "<ti#" << getIndex();
  325. if (getOffset()) OS << "+" << getOffset();
  326. OS << '>';
  327. break;
  328. case MachineOperand::MO_JumpTableIndex:
  329. OS << "<jt#" << getIndex() << '>';
  330. break;
  331. case MachineOperand::MO_GlobalAddress:
  332. OS << "<ga:";
  333. WriteAsOperand(OS, getGlobal(), /*PrintType=*/false);
  334. if (getOffset()) OS << "+" << getOffset();
  335. OS << '>';
  336. break;
  337. case MachineOperand::MO_ExternalSymbol:
  338. OS << "<es:" << getSymbolName();
  339. if (getOffset()) OS << "+" << getOffset();
  340. OS << '>';
  341. break;
  342. case MachineOperand::MO_BlockAddress:
  343. OS << '<';
  344. WriteAsOperand(OS, getBlockAddress(), /*PrintType=*/false);
  345. if (getOffset()) OS << "+" << getOffset();
  346. OS << '>';
  347. break;
  348. case MachineOperand::MO_RegisterMask:
  349. OS << "<regmask>";
  350. break;
  351. case MachineOperand::MO_Metadata:
  352. OS << '<';
  353. WriteAsOperand(OS, getMetadata(), /*PrintType=*/false);
  354. OS << '>';
  355. break;
  356. case MachineOperand::MO_MCSymbol:
  357. OS << "<MCSym=" << *getMCSymbol() << '>';
  358. break;
  359. }
  360. if (unsigned TF = getTargetFlags())
  361. OS << "[TF=" << TF << ']';
  362. }
  363. //===----------------------------------------------------------------------===//
  364. // MachineMemOperand Implementation
  365. //===----------------------------------------------------------------------===//
  366. /// getAddrSpace - Return the LLVM IR address space number that this pointer
  367. /// points into.
  368. unsigned MachinePointerInfo::getAddrSpace() const {
  369. if (V == 0) return 0;
  370. return cast<PointerType>(V->getType())->getAddressSpace();
  371. }
  372. /// getConstantPool - Return a MachinePointerInfo record that refers to the
  373. /// constant pool.
  374. MachinePointerInfo MachinePointerInfo::getConstantPool() {
  375. return MachinePointerInfo(PseudoSourceValue::getConstantPool());
  376. }
  377. /// getFixedStack - Return a MachinePointerInfo record that refers to the
  378. /// the specified FrameIndex.
  379. MachinePointerInfo MachinePointerInfo::getFixedStack(int FI, int64_t offset) {
  380. return MachinePointerInfo(PseudoSourceValue::getFixedStack(FI), offset);
  381. }
  382. MachinePointerInfo MachinePointerInfo::getJumpTable() {
  383. return MachinePointerInfo(PseudoSourceValue::getJumpTable());
  384. }
  385. MachinePointerInfo MachinePointerInfo::getGOT() {
  386. return MachinePointerInfo(PseudoSourceValue::getGOT());
  387. }
  388. MachinePointerInfo MachinePointerInfo::getStack(int64_t Offset) {
  389. return MachinePointerInfo(PseudoSourceValue::getStack(), Offset);
  390. }
  391. MachineMemOperand::MachineMemOperand(MachinePointerInfo ptrinfo, unsigned f,
  392. uint64_t s, unsigned int a,
  393. const MDNode *TBAAInfo,
  394. const MDNode *Ranges)
  395. : PtrInfo(ptrinfo), Size(s),
  396. Flags((f & ((1 << MOMaxBits) - 1)) | ((Log2_32(a) + 1) << MOMaxBits)),
  397. TBAAInfo(TBAAInfo), Ranges(Ranges) {
  398. assert((PtrInfo.V == 0 || isa<PointerType>(PtrInfo.V->getType())) &&
  399. "invalid pointer value");
  400. assert(getBaseAlignment() == a && "Alignment is not a power of 2!");
  401. assert((isLoad() || isStore()) && "Not a load/store!");
  402. }
  403. /// Profile - Gather unique data for the object.
  404. ///
  405. void MachineMemOperand::Profile(FoldingSetNodeID &ID) const {
  406. ID.AddInteger(getOffset());
  407. ID.AddInteger(Size);
  408. ID.AddPointer(getValue());
  409. ID.AddInteger(Flags);
  410. }
  411. void MachineMemOperand::refineAlignment(const MachineMemOperand *MMO) {
  412. // The Value and Offset may differ due to CSE. But the flags and size
  413. // should be the same.
  414. assert(MMO->getFlags() == getFlags() && "Flags mismatch!");
  415. assert(MMO->getSize() == getSize() && "Size mismatch!");
  416. if (MMO->getBaseAlignment() >= getBaseAlignment()) {
  417. // Update the alignment value.
  418. Flags = (Flags & ((1 << MOMaxBits) - 1)) |
  419. ((Log2_32(MMO->getBaseAlignment()) + 1) << MOMaxBits);
  420. // Also update the base and offset, because the new alignment may
  421. // not be applicable with the old ones.
  422. PtrInfo = MMO->PtrInfo;
  423. }
  424. }
  425. /// getAlignment - Return the minimum known alignment in bytes of the
  426. /// actual memory reference.
  427. uint64_t MachineMemOperand::getAlignment() const {
  428. return MinAlign(getBaseAlignment(), getOffset());
  429. }
  430. raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineMemOperand &MMO) {
  431. assert((MMO.isLoad() || MMO.isStore()) &&
  432. "SV has to be a load, store or both.");
  433. if (MMO.isVolatile())
  434. OS << "Volatile ";
  435. if (MMO.isLoad())
  436. OS << "LD";
  437. if (MMO.isStore())
  438. OS << "ST";
  439. OS << MMO.getSize();
  440. // Print the address information.
  441. OS << "[";
  442. if (!MMO.getValue())
  443. OS << "<unknown>";
  444. else
  445. WriteAsOperand(OS, MMO.getValue(), /*PrintType=*/false);
  446. // If the alignment of the memory reference itself differs from the alignment
  447. // of the base pointer, print the base alignment explicitly, next to the base
  448. // pointer.
  449. if (MMO.getBaseAlignment() != MMO.getAlignment())
  450. OS << "(align=" << MMO.getBaseAlignment() << ")";
  451. if (MMO.getOffset() != 0)
  452. OS << "+" << MMO.getOffset();
  453. OS << "]";
  454. // Print the alignment of the reference.
  455. if (MMO.getBaseAlignment() != MMO.getAlignment() ||
  456. MMO.getBaseAlignment() != MMO.getSize())
  457. OS << "(align=" << MMO.getAlignment() << ")";
  458. // Print TBAA info.
  459. if (const MDNode *TBAAInfo = MMO.getTBAAInfo()) {
  460. OS << "(tbaa=";
  461. if (TBAAInfo->getNumOperands() > 0)
  462. WriteAsOperand(OS, TBAAInfo->getOperand(0), /*PrintType=*/false);
  463. else
  464. OS << "<unknown>";
  465. OS << ")";
  466. }
  467. // Print nontemporal info.
  468. if (MMO.isNonTemporal())
  469. OS << "(nontemporal)";
  470. return OS;
  471. }
  472. //===----------------------------------------------------------------------===//
  473. // MachineInstr Implementation
  474. //===----------------------------------------------------------------------===//
  475. void MachineInstr::addImplicitDefUseOperands(MachineFunction &MF) {
  476. if (MCID->ImplicitDefs)
  477. for (const uint16_t *ImpDefs = MCID->getImplicitDefs(); *ImpDefs; ++ImpDefs)
  478. addOperand(MF, MachineOperand::CreateReg(*ImpDefs, true, true));
  479. if (MCID->ImplicitUses)
  480. for (const uint16_t *ImpUses = MCID->getImplicitUses(); *ImpUses; ++ImpUses)
  481. addOperand(MF, MachineOperand::CreateReg(*ImpUses, false, true));
  482. }
  483. /// MachineInstr ctor - This constructor creates a MachineInstr and adds the
  484. /// implicit operands. It reserves space for the number of operands specified by
  485. /// the MCInstrDesc.
  486. MachineInstr::MachineInstr(MachineFunction &MF, const MCInstrDesc &tid,
  487. const DebugLoc dl, bool NoImp)
  488. : MCID(&tid), Parent(0), Operands(0), NumOperands(0),
  489. Flags(0), AsmPrinterFlags(0),
  490. NumMemRefs(0), MemRefs(0), debugLoc(dl) {
  491. // Reserve space for the expected number of operands.
  492. if (unsigned NumOps = MCID->getNumOperands() +
  493. MCID->getNumImplicitDefs() + MCID->getNumImplicitUses()) {
  494. CapOperands = OperandCapacity::get(NumOps);
  495. Operands = MF.allocateOperandArray(CapOperands);
  496. }
  497. if (!NoImp)
  498. addImplicitDefUseOperands(MF);
  499. }
  500. /// MachineInstr ctor - Copies MachineInstr arg exactly
  501. ///
  502. MachineInstr::MachineInstr(MachineFunction &MF, const MachineInstr &MI)
  503. : MCID(&MI.getDesc()), Parent(0), Operands(0), NumOperands(0),
  504. Flags(0), AsmPrinterFlags(0),
  505. NumMemRefs(MI.NumMemRefs), MemRefs(MI.MemRefs),
  506. debugLoc(MI.getDebugLoc()) {
  507. CapOperands = OperandCapacity::get(MI.getNumOperands());
  508. Operands = MF.allocateOperandArray(CapOperands);
  509. // Copy operands.
  510. for (unsigned i = 0; i != MI.getNumOperands(); ++i)
  511. addOperand(MF, MI.getOperand(i));
  512. // Copy all the sensible flags.
  513. setFlags(MI.Flags);
  514. }
  515. /// getRegInfo - If this instruction is embedded into a MachineFunction,
  516. /// return the MachineRegisterInfo object for the current function, otherwise
  517. /// return null.
  518. MachineRegisterInfo *MachineInstr::getRegInfo() {
  519. if (MachineBasicBlock *MBB = getParent())
  520. return &MBB->getParent()->getRegInfo();
  521. return 0;
  522. }
  523. /// RemoveRegOperandsFromUseLists - Unlink all of the register operands in
  524. /// this instruction from their respective use lists. This requires that the
  525. /// operands already be on their use lists.
  526. void MachineInstr::RemoveRegOperandsFromUseLists(MachineRegisterInfo &MRI) {
  527. for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
  528. if (Operands[i].isReg())
  529. MRI.removeRegOperandFromUseList(&Operands[i]);
  530. }
  531. /// AddRegOperandsToUseLists - Add all of the register operands in
  532. /// this instruction from their respective use lists. This requires that the
  533. /// operands not be on their use lists yet.
  534. void MachineInstr::AddRegOperandsToUseLists(MachineRegisterInfo &MRI) {
  535. for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
  536. if (Operands[i].isReg())
  537. MRI.addRegOperandToUseList(&Operands[i]);
  538. }
  539. void MachineInstr::addOperand(const MachineOperand &Op) {
  540. MachineBasicBlock *MBB = getParent();
  541. assert(MBB && "Use MachineInstrBuilder to add operands to dangling instrs");
  542. MachineFunction *MF = MBB->getParent();
  543. assert(MF && "Use MachineInstrBuilder to add operands to dangling instrs");
  544. addOperand(*MF, Op);
  545. }
  546. /// Move NumOps MachineOperands from Src to Dst, with support for overlapping
  547. /// ranges. If MRI is non-null also update use-def chains.
  548. static void moveOperands(MachineOperand *Dst, MachineOperand *Src,
  549. unsigned NumOps, MachineRegisterInfo *MRI) {
  550. if (MRI)
  551. return MRI->moveOperands(Dst, Src, NumOps);
  552. // Here it would be convenient to call memmove, so that isn't allowed because
  553. // MachineOperand has a constructor and so isn't a POD type.
  554. if (Dst < Src)
  555. for (unsigned i = 0; i != NumOps; ++i)
  556. new (Dst + i) MachineOperand(Src[i]);
  557. else
  558. for (unsigned i = NumOps; i ; --i)
  559. new (Dst + i - 1) MachineOperand(Src[i - 1]);
  560. }
  561. /// addOperand - Add the specified operand to the instruction. If it is an
  562. /// implicit operand, it is added to the end of the operand list. If it is
  563. /// an explicit operand it is added at the end of the explicit operand list
  564. /// (before the first implicit operand).
  565. void MachineInstr::addOperand(MachineFunction &MF, const MachineOperand &Op) {
  566. assert(MCID && "Cannot add operands before providing an instr descriptor");
  567. // Check if we're adding one of our existing operands.
  568. if (&Op >= Operands && &Op < Operands + NumOperands) {
  569. // This is unusual: MI->addOperand(MI->getOperand(i)).
  570. // If adding Op requires reallocating or moving existing operands around,
  571. // the Op reference could go stale. Support it by copying Op.
  572. MachineOperand CopyOp(Op);
  573. return addOperand(MF, CopyOp);
  574. }
  575. // Find the insert location for the new operand. Implicit registers go at
  576. // the end, everything else goes before the implicit regs.
  577. //
  578. // FIXME: Allow mixed explicit and implicit operands on inline asm.
  579. // InstrEmitter::EmitSpecialNode() is marking inline asm clobbers as
  580. // implicit-defs, but they must not be moved around. See the FIXME in
  581. // InstrEmitter.cpp.
  582. unsigned OpNo = getNumOperands();
  583. bool isImpReg = Op.isReg() && Op.isImplicit();
  584. if (!isImpReg && !isInlineAsm()) {
  585. while (OpNo && Operands[OpNo-1].isReg() && Operands[OpNo-1].isImplicit()) {
  586. --OpNo;
  587. assert(!Operands[OpNo].isTied() && "Cannot move tied operands");
  588. }
  589. }
  590. #ifndef NDEBUG
  591. bool isMetaDataOp = Op.getType() == MachineOperand::MO_Metadata;
  592. // OpNo now points as the desired insertion point. Unless this is a variadic
  593. // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
  594. // RegMask operands go between the explicit and implicit operands.
  595. assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
  596. OpNo < MCID->getNumOperands() || isMetaDataOp) &&
  597. "Trying to add an operand to a machine instr that is already done!");
  598. #endif
  599. MachineRegisterInfo *MRI = getRegInfo();
  600. // Determine if the Operands array needs to be reallocated.
  601. // Save the old capacity and operand array.
  602. OperandCapacity OldCap = CapOperands;
  603. MachineOperand *OldOperands = Operands;
  604. if (!OldOperands || OldCap.getSize() == getNumOperands()) {
  605. CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
  606. Operands = MF.allocateOperandArray(CapOperands);
  607. // Move the operands before the insertion point.
  608. if (OpNo)
  609. moveOperands(Operands, OldOperands, OpNo, MRI);
  610. }
  611. // Move the operands following the insertion point.
  612. if (OpNo != NumOperands)
  613. moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
  614. MRI);
  615. ++NumOperands;
  616. // Deallocate the old operand array.
  617. if (OldOperands != Operands && OldOperands)
  618. MF.deallocateOperandArray(OldCap, OldOperands);
  619. // Copy Op into place. It still needs to be inserted into the MRI use lists.
  620. MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
  621. NewMO->ParentMI = this;
  622. // When adding a register operand, tell MRI about it.
  623. if (NewMO->isReg()) {
  624. // Ensure isOnRegUseList() returns false, regardless of Op's status.
  625. NewMO->Contents.Reg.Prev = 0;
  626. // Ignore existing ties. This is not a property that can be copied.
  627. NewMO->TiedTo = 0;
  628. // Add the new operand to MRI, but only for instructions in an MBB.
  629. if (MRI)
  630. MRI->addRegOperandToUseList(NewMO);
  631. // The MCID operand information isn't accurate until we start adding
  632. // explicit operands. The implicit operands are added first, then the
  633. // explicits are inserted before them.
  634. if (!isImpReg) {
  635. // Tie uses to defs as indicated in MCInstrDesc.
  636. if (NewMO->isUse()) {
  637. int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
  638. if (DefIdx != -1)
  639. tieOperands(DefIdx, OpNo);
  640. }
  641. // If the register operand is flagged as early, mark the operand as such.
  642. if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
  643. NewMO->setIsEarlyClobber(true);
  644. }
  645. }
  646. }
  647. /// RemoveOperand - Erase an operand from an instruction, leaving it with one
  648. /// fewer operand than it started with.
  649. ///
  650. void MachineInstr::RemoveOperand(unsigned OpNo) {
  651. assert(OpNo < getNumOperands() && "Invalid operand number");
  652. untieRegOperand(OpNo);
  653. #ifndef NDEBUG
  654. // Moving tied operands would break the ties.
  655. for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
  656. if (Operands[i].isReg())
  657. assert(!Operands[i].isTied() && "Cannot move tied operands");
  658. #endif
  659. MachineRegisterInfo *MRI = getRegInfo();
  660. if (MRI && Operands[OpNo].isReg())
  661. MRI->removeRegOperandFromUseList(Operands + OpNo);
  662. // Don't call the MachineOperand destructor. A lot of this code depends on
  663. // MachineOperand having a trivial destructor anyway, and adding a call here
  664. // wouldn't make it 'destructor-correct'.
  665. if (unsigned N = NumOperands - 1 - OpNo)
  666. moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
  667. --NumOperands;
  668. }
  669. /// addMemOperand - Add a MachineMemOperand to the machine instruction.
  670. /// This function should be used only occasionally. The setMemRefs function
  671. /// is the primary method for setting up a MachineInstr's MemRefs list.
  672. void MachineInstr::addMemOperand(MachineFunction &MF,
  673. MachineMemOperand *MO) {
  674. mmo_iterator OldMemRefs = MemRefs;
  675. unsigned OldNumMemRefs = NumMemRefs;
  676. unsigned NewNum = NumMemRefs + 1;
  677. mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
  678. std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
  679. NewMemRefs[NewNum - 1] = MO;
  680. setMemRefs(NewMemRefs, NewMemRefs + NewNum);
  681. }
  682. bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
  683. assert(!isBundledWithPred() && "Must be called on bundle header");
  684. for (MachineBasicBlock::const_instr_iterator MII = this;; ++MII) {
  685. if (MII->getDesc().getFlags() & Mask) {
  686. if (Type == AnyInBundle)
  687. return true;
  688. } else {
  689. if (Type == AllInBundle && !MII->isBundle())
  690. return false;
  691. }
  692. // This was the last instruction in the bundle.
  693. if (!MII->isBundledWithSucc())
  694. return Type == AllInBundle;
  695. }
  696. }
  697. bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
  698. MICheckType Check) const {
  699. // If opcodes or number of operands are not the same then the two
  700. // instructions are obviously not identical.
  701. if (Other->getOpcode() != getOpcode() ||
  702. Other->getNumOperands() != getNumOperands())
  703. return false;
  704. if (isBundle()) {
  705. // Both instructions are bundles, compare MIs inside the bundle.
  706. MachineBasicBlock::const_instr_iterator I1 = *this;
  707. MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end();
  708. MachineBasicBlock::const_instr_iterator I2 = *Other;
  709. MachineBasicBlock::const_instr_iterator E2= Other->getParent()->instr_end();
  710. while (++I1 != E1 && I1->isInsideBundle()) {
  711. ++I2;
  712. if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(I2, Check))
  713. return false;
  714. }
  715. }
  716. // Check operands to make sure they match.
  717. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  718. const MachineOperand &MO = getOperand(i);
  719. const MachineOperand &OMO = Other->getOperand(i);
  720. if (!MO.isReg()) {
  721. if (!MO.isIdenticalTo(OMO))
  722. return false;
  723. continue;
  724. }
  725. // Clients may or may not want to ignore defs when testing for equality.
  726. // For example, machine CSE pass only cares about finding common
  727. // subexpressions, so it's safe to ignore virtual register defs.
  728. if (MO.isDef()) {
  729. if (Check == IgnoreDefs)
  730. continue;
  731. else if (Check == IgnoreVRegDefs) {
  732. if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
  733. TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
  734. if (MO.getReg() != OMO.getReg())
  735. return false;
  736. } else {
  737. if (!MO.isIdenticalTo(OMO))
  738. return false;
  739. if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
  740. return false;
  741. }
  742. } else {
  743. if (!MO.isIdenticalTo(OMO))
  744. return false;
  745. if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
  746. return false;
  747. }
  748. }
  749. // If DebugLoc does not match then two dbg.values are not identical.
  750. if (isDebugValue())
  751. if (!getDebugLoc().isUnknown() && !Other->getDebugLoc().isUnknown()
  752. && getDebugLoc() != Other->getDebugLoc())
  753. return false;
  754. return true;
  755. }
  756. MachineInstr *MachineInstr::removeFromParent() {
  757. assert(getParent() && "Not embedded in a basic block!");
  758. return getParent()->remove(this);
  759. }
  760. MachineInstr *MachineInstr::removeFromBundle() {
  761. assert(getParent() && "Not embedded in a basic block!");
  762. return getParent()->remove_instr(this);
  763. }
  764. void MachineInstr::eraseFromParent() {
  765. assert(getParent() && "Not embedded in a basic block!");
  766. getParent()->erase(this);
  767. }
  768. void MachineInstr::eraseFromBundle() {
  769. assert(getParent() && "Not embedded in a basic block!");
  770. getParent()->erase_instr(this);
  771. }
  772. /// getNumExplicitOperands - Returns the number of non-implicit operands.
  773. ///
  774. unsigned MachineInstr::getNumExplicitOperands() const {
  775. unsigned NumOperands = MCID->getNumOperands();
  776. if (!MCID->isVariadic())
  777. return NumOperands;
  778. for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
  779. const MachineOperand &MO = getOperand(i);
  780. if (!MO.isReg() || !MO.isImplicit())
  781. NumOperands++;
  782. }
  783. return NumOperands;
  784. }
  785. void MachineInstr::bundleWithPred() {
  786. assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
  787. setFlag(BundledPred);
  788. MachineBasicBlock::instr_iterator Pred = this;
  789. --Pred;
  790. assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
  791. Pred->setFlag(BundledSucc);
  792. }
  793. void MachineInstr::bundleWithSucc() {
  794. assert(!isBundledWithSucc() && "MI is already bundled with its successor");
  795. setFlag(BundledSucc);
  796. MachineBasicBlock::instr_iterator Succ = this;
  797. ++Succ;
  798. assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
  799. Succ->setFlag(BundledPred);
  800. }
  801. void MachineInstr::unbundleFromPred() {
  802. assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
  803. clearFlag(BundledPred);
  804. MachineBasicBlock::instr_iterator Pred = this;
  805. --Pred;
  806. assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
  807. Pred->clearFlag(BundledSucc);
  808. }
  809. void MachineInstr::unbundleFromSucc() {
  810. assert(isBundledWithSucc() && "MI isn't bundled with its successor");
  811. clearFlag(BundledSucc);
  812. MachineBasicBlock::instr_iterator Succ = this;
  813. ++Succ;
  814. assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
  815. Succ->clearFlag(BundledPred);
  816. }
  817. bool MachineInstr::isStackAligningInlineAsm() const {
  818. if (isInlineAsm()) {
  819. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  820. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  821. return true;
  822. }
  823. return false;
  824. }
  825. InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
  826. assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
  827. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  828. return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
  829. }
  830. int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
  831. unsigned *GroupNo) const {
  832. assert(isInlineAsm() && "Expected an inline asm instruction");
  833. assert(OpIdx < getNumOperands() && "OpIdx out of range");
  834. // Ignore queries about the initial operands.
  835. if (OpIdx < InlineAsm::MIOp_FirstOperand)
  836. return -1;
  837. unsigned Group = 0;
  838. unsigned NumOps;
  839. for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
  840. i += NumOps) {
  841. const MachineOperand &FlagMO = getOperand(i);
  842. // If we reach the implicit register operands, stop looking.
  843. if (!FlagMO.isImm())
  844. return -1;
  845. NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
  846. if (i + NumOps > OpIdx) {
  847. if (GroupNo)
  848. *GroupNo = Group;
  849. return i;
  850. }
  851. ++Group;
  852. }
  853. return -1;
  854. }
  855. const TargetRegisterClass*
  856. MachineInstr::getRegClassConstraint(unsigned OpIdx,
  857. const TargetInstrInfo *TII,
  858. const TargetRegisterInfo *TRI) const {
  859. assert(getParent() && "Can't have an MBB reference here!");
  860. assert(getParent()->getParent() && "Can't have an MF reference here!");
  861. const MachineFunction &MF = *getParent()->getParent();
  862. // Most opcodes have fixed constraints in their MCInstrDesc.
  863. if (!isInlineAsm())
  864. return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
  865. if (!getOperand(OpIdx).isReg())
  866. return NULL;
  867. // For tied uses on inline asm, get the constraint from the def.
  868. unsigned DefIdx;
  869. if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
  870. OpIdx = DefIdx;
  871. // Inline asm stores register class constraints in the flag word.
  872. int FlagIdx = findInlineAsmFlagIdx(OpIdx);
  873. if (FlagIdx < 0)
  874. return NULL;
  875. unsigned Flag = getOperand(FlagIdx).getImm();
  876. unsigned RCID;
  877. if (InlineAsm::hasRegClassConstraint(Flag, RCID))
  878. return TRI->getRegClass(RCID);
  879. // Assume that all registers in a memory operand are pointers.
  880. if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
  881. return TRI->getPointerRegClass(MF);
  882. return NULL;
  883. }
  884. /// Return the number of instructions inside the MI bundle, not counting the
  885. /// header instruction.
  886. unsigned MachineInstr::getBundleSize() const {
  887. MachineBasicBlock::const_instr_iterator I = this;
  888. unsigned Size = 0;
  889. while (I->isBundledWithSucc())
  890. ++Size, ++I;
  891. return Size;
  892. }
  893. /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
  894. /// the specific register or -1 if it is not found. It further tightens
  895. /// the search criteria to a use that kills the register if isKill is true.
  896. int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
  897. const TargetRegisterInfo *TRI) const {
  898. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  899. const MachineOperand &MO = getOperand(i);
  900. if (!MO.isReg() || !MO.isUse())
  901. continue;
  902. unsigned MOReg = MO.getReg();
  903. if (!MOReg)
  904. continue;
  905. if (MOReg == Reg ||
  906. (TRI &&
  907. TargetRegisterInfo::isPhysicalRegister(MOReg) &&
  908. TargetRegisterInfo::isPhysicalRegister(Reg) &&
  909. TRI->isSubRegister(MOReg, Reg)))
  910. if (!isKill || MO.isKill())
  911. return i;
  912. }
  913. return -1;
  914. }
  915. /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
  916. /// indicating if this instruction reads or writes Reg. This also considers
  917. /// partial defines.
  918. std::pair<bool,bool>
  919. MachineInstr::readsWritesVirtualRegister(unsigned Reg,
  920. SmallVectorImpl<unsigned> *Ops) const {
  921. bool PartDef = false; // Partial redefine.
  922. bool FullDef = false; // Full define.
  923. bool Use = false;
  924. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  925. const MachineOperand &MO = getOperand(i);
  926. if (!MO.isReg() || MO.getReg() != Reg)
  927. continue;
  928. if (Ops)
  929. Ops->push_back(i);
  930. if (MO.isUse())
  931. Use |= !MO.isUndef();
  932. else if (MO.getSubReg() && !MO.isUndef())
  933. // A partial <def,undef> doesn't count as reading the register.
  934. PartDef = true;
  935. else
  936. FullDef = true;
  937. }
  938. // A partial redefine uses Reg unless there is also a full define.
  939. return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
  940. }
  941. /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
  942. /// the specified register or -1 if it is not found. If isDead is true, defs
  943. /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
  944. /// also checks if there is a def of a super-register.
  945. int
  946. MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
  947. const TargetRegisterInfo *TRI) const {
  948. bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
  949. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  950. const MachineOperand &MO = getOperand(i);
  951. // Accept regmask operands when Overlap is set.
  952. // Ignore them when looking for a specific def operand (Overlap == false).
  953. if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
  954. return i;
  955. if (!MO.isReg() || !MO.isDef())
  956. continue;
  957. unsigned MOReg = MO.getReg();
  958. bool Found = (MOReg == Reg);
  959. if (!Found && TRI && isPhys &&
  960. TargetRegisterInfo::isPhysicalRegister(MOReg)) {
  961. if (Overlap)
  962. Found = TRI->regsOverlap(MOReg, Reg);
  963. else
  964. Found = TRI->isSubRegister(MOReg, Reg);
  965. }
  966. if (Found && (!isDead || MO.isDead()))
  967. return i;
  968. }
  969. return -1;
  970. }
  971. /// findFirstPredOperandIdx() - Find the index of the first operand in the
  972. /// operand list that is used to represent the predicate. It returns -1 if
  973. /// none is found.
  974. int MachineInstr::findFirstPredOperandIdx() const {
  975. // Don't call MCID.findFirstPredOperandIdx() because this variant
  976. // is sometimes called on an instruction that's not yet complete, and
  977. // so the number of operands is less than the MCID indicates. In
  978. // particular, the PTX target does this.
  979. const MCInstrDesc &MCID = getDesc();
  980. if (MCID.isPredicable()) {
  981. for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
  982. if (MCID.OpInfo[i].isPredicate())
  983. return i;
  984. }
  985. return -1;
  986. }
  987. // MachineOperand::TiedTo is 4 bits wide.
  988. const unsigned TiedMax = 15;
  989. /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
  990. ///
  991. /// Use and def operands can be tied together, indicated by a non-zero TiedTo
  992. /// field. TiedTo can have these values:
  993. ///
  994. /// 0: Operand is not tied to anything.
  995. /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
  996. /// TiedMax: Tied to an operand >= TiedMax-1.
  997. ///
  998. /// The tied def must be one of the first TiedMax operands on a normal
  999. /// instruction. INLINEASM instructions allow more tied defs.
  1000. ///
  1001. void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
  1002. MachineOperand &DefMO = getOperand(DefIdx);
  1003. MachineOperand &UseMO = getOperand(UseIdx);
  1004. assert(DefMO.isDef() && "DefIdx must be a def operand");
  1005. assert(UseMO.isUse() && "UseIdx must be a use operand");
  1006. assert(!DefMO.isTied() && "Def is already tied to another use");
  1007. assert(!UseMO.isTied() && "Use is already tied to another def");
  1008. if (DefIdx < TiedMax)
  1009. UseMO.TiedTo = DefIdx + 1;
  1010. else {
  1011. // Inline asm can use the group descriptors to find tied operands, but on
  1012. // normal instruction, the tied def must be within the first TiedMax
  1013. // operands.
  1014. assert(isInlineAsm() && "DefIdx out of range");
  1015. UseMO.TiedTo = TiedMax;
  1016. }
  1017. // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
  1018. DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
  1019. }
  1020. /// Given the index of a tied register operand, find the operand it is tied to.
  1021. /// Defs are tied to uses and vice versa. Returns the index of the tied operand
  1022. /// which must exist.
  1023. unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
  1024. const MachineOperand &MO = getOperand(OpIdx);
  1025. assert(MO.isTied() && "Operand isn't tied");
  1026. // Normally TiedTo is in range.
  1027. if (MO.TiedTo < TiedMax)
  1028. return MO.TiedTo - 1;
  1029. // Uses on normal instructions can be out of range.
  1030. if (!isInlineAsm()) {
  1031. // Normal tied defs must be in the 0..TiedMax-1 range.
  1032. if (MO.isUse())
  1033. return TiedMax - 1;
  1034. // MO is a def. Search for the tied use.
  1035. for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
  1036. const MachineOperand &UseMO = getOperand(i);
  1037. if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
  1038. return i;
  1039. }
  1040. llvm_unreachable("Can't find tied use");
  1041. }
  1042. // Now deal with inline asm by parsing the operand group descriptor flags.
  1043. // Find the beginning of each operand group.
  1044. SmallVector<unsigned, 8> GroupIdx;
  1045. unsigned OpIdxGroup = ~0u;
  1046. unsigned NumOps;
  1047. for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
  1048. i += NumOps) {
  1049. const MachineOperand &FlagMO = getOperand(i);
  1050. assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
  1051. unsigned CurGroup = GroupIdx.size();
  1052. GroupIdx.push_back(i);
  1053. NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
  1054. // OpIdx belongs to this operand group.
  1055. if (OpIdx > i && OpIdx < i + NumOps)
  1056. OpIdxGroup = CurGroup;
  1057. unsigned TiedGroup;
  1058. if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
  1059. continue;
  1060. // Operands in this group are tied to operands in TiedGroup which must be
  1061. // earlier. Find the number of operands between the two groups.
  1062. unsigned Delta = i - GroupIdx[TiedGroup];
  1063. // OpIdx is a use tied to TiedGroup.
  1064. if (OpIdxGroup == CurGroup)
  1065. return OpIdx - Delta;
  1066. // OpIdx is a def tied to this use group.
  1067. if (OpIdxGroup == TiedGroup)
  1068. return OpIdx + Delta;
  1069. }
  1070. llvm_unreachable("Invalid tied operand on inline asm");
  1071. }
  1072. /// clearKillInfo - Clears kill flags on all operands.
  1073. ///
  1074. void MachineInstr::clearKillInfo() {
  1075. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1076. MachineOperand &MO = getOperand(i);
  1077. if (MO.isReg() && MO.isUse())
  1078. MO.setIsKill(false);
  1079. }
  1080. }
  1081. void MachineInstr::substituteRegister(unsigned FromReg,
  1082. unsigned ToReg,
  1083. unsigned SubIdx,
  1084. const TargetRegisterInfo &RegInfo) {
  1085. if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
  1086. if (SubIdx)
  1087. ToReg = RegInfo.getSubReg(ToReg, SubIdx);
  1088. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1089. MachineOperand &MO = getOperand(i);
  1090. if (!MO.isReg() || MO.getReg() != FromReg)
  1091. continue;
  1092. MO.substPhysReg(ToReg, RegInfo);
  1093. }
  1094. } else {
  1095. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1096. MachineOperand &MO = getOperand(i);
  1097. if (!MO.isReg() || MO.getReg() != FromReg)
  1098. continue;
  1099. MO.substVirtReg(ToReg, SubIdx, RegInfo);
  1100. }
  1101. }
  1102. }
  1103. /// isSafeToMove - Return true if it is safe to move this instruction. If
  1104. /// SawStore is set to true, it means that there is a store (or call) between
  1105. /// the instruction's location and its intended destination.
  1106. bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
  1107. AliasAnalysis *AA,
  1108. bool &SawStore) const {
  1109. // Ignore stuff that we obviously can't move.
  1110. //
  1111. // Treat volatile loads as stores. This is not strictly necessary for
  1112. // volatiles, but it is required for atomic loads. It is not allowed to move
  1113. // a load across an atomic load with Ordering > Monotonic.
  1114. if (mayStore() || isCall() ||
  1115. (mayLoad() && hasOrderedMemoryRef())) {
  1116. SawStore = true;
  1117. return false;
  1118. }
  1119. if (isLabel() || isDebugValue() ||
  1120. isTerminator() || hasUnmodeledSideEffects())
  1121. return false;
  1122. // See if this instruction does a load. If so, we have to guarantee that the
  1123. // loaded value doesn't change between the load and the its intended
  1124. // destination. The check for isInvariantLoad gives the targe the chance to
  1125. // classify the load as always returning a constant, e.g. a constant pool
  1126. // load.
  1127. if (mayLoad() && !isInvariantLoad(AA))
  1128. // Otherwise, this is a real load. If there is a store between the load and
  1129. // end of block, we can't move it.
  1130. return !SawStore;
  1131. return true;
  1132. }
  1133. /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
  1134. /// or volatile memory reference, or if the information describing the memory
  1135. /// reference is not available. Return false if it is known to have no ordered
  1136. /// memory references.
  1137. bool MachineInstr::hasOrderedMemoryRef() const {
  1138. // An instruction known never to access memory won't have a volatile access.
  1139. if (!mayStore() &&
  1140. !mayLoad() &&
  1141. !isCall() &&
  1142. !hasUnmodeledSideEffects())
  1143. return false;
  1144. // Otherwise, if the instruction has no memory reference information,
  1145. // conservatively assume it wasn't preserved.
  1146. if (memoperands_empty())
  1147. return true;
  1148. // Check the memory reference information for ordered references.
  1149. for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
  1150. if (!(*I)->isUnordered())
  1151. return true;
  1152. return false;
  1153. }
  1154. /// isInvariantLoad - Return true if this instruction is loading from a
  1155. /// location whose value is invariant across the function. For example,
  1156. /// loading a value from the constant pool or from the argument area
  1157. /// of a function if it does not change. This should only return true of
  1158. /// *all* loads the instruction does are invariant (if it does multiple loads).
  1159. bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
  1160. // If the instruction doesn't load at all, it isn't an invariant load.
  1161. if (!mayLoad())
  1162. return false;
  1163. // If the instruction has lost its memoperands, conservatively assume that
  1164. // it may not be an invariant load.
  1165. if (memoperands_empty())
  1166. return false;
  1167. const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
  1168. for (mmo_iterator I = memoperands_begin(),
  1169. E = memoperands_end(); I != E; ++I) {
  1170. if ((*I)->isVolatile()) return false;
  1171. if ((*I)->isStore()) return false;
  1172. if ((*I)->isInvariant()) return true;
  1173. if (const Value *V = (*I)->getValue()) {
  1174. // A load from a constant PseudoSourceValue is invariant.
  1175. if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
  1176. if (PSV->isConstant(MFI))
  1177. continue;
  1178. // If we have an AliasAnalysis, ask it whether the memory is constant.
  1179. if (AA && AA->pointsToConstantMemory(
  1180. AliasAnalysis::Location(V, (*I)->getSize(),
  1181. (*I)->getTBAAInfo())))
  1182. continue;
  1183. }
  1184. // Otherwise assume conservatively.
  1185. return false;
  1186. }
  1187. // Everything checks out.
  1188. return true;
  1189. }
  1190. /// isConstantValuePHI - If the specified instruction is a PHI that always
  1191. /// merges together the same virtual register, return the register, otherwise
  1192. /// return 0.
  1193. unsigned MachineInstr::isConstantValuePHI() const {
  1194. if (!isPHI())
  1195. return 0;
  1196. assert(getNumOperands() >= 3 &&
  1197. "It's illegal to have a PHI without source operands");
  1198. unsigned Reg = getOperand(1).getReg();
  1199. for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
  1200. if (getOperand(i).getReg() != Reg)
  1201. return 0;
  1202. return Reg;
  1203. }
  1204. bool MachineInstr::hasUnmodeledSideEffects() const {
  1205. if (hasProperty(MCID::UnmodeledSideEffects))
  1206. return true;
  1207. if (isInlineAsm()) {
  1208. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1209. if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
  1210. return true;
  1211. }
  1212. return false;
  1213. }
  1214. /// allDefsAreDead - Return true if all the defs of this instruction are dead.
  1215. ///
  1216. bool MachineInstr::allDefsAreDead() const {
  1217. for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
  1218. const MachineOperand &MO = getOperand(i);
  1219. if (!MO.isReg() || MO.isUse())
  1220. continue;
  1221. if (!MO.isDead())
  1222. return false;
  1223. }
  1224. return true;
  1225. }
  1226. /// copyImplicitOps - Copy implicit register operands from specified
  1227. /// instruction to this instruction.
  1228. void MachineInstr::copyImplicitOps(MachineFunction &MF,
  1229. const MachineInstr *MI) {
  1230. for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
  1231. i != e; ++i) {
  1232. const MachineOperand &MO = MI->getOperand(i);
  1233. if (MO.isReg() && MO.isImplicit())
  1234. addOperand(MF, MO);
  1235. }
  1236. }
  1237. void MachineInstr::dump() const {
  1238. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1239. dbgs() << " " << *this;
  1240. #endif
  1241. }
  1242. static void printDebugLoc(DebugLoc DL, const MachineFunction *MF,
  1243. raw_ostream &CommentOS) {
  1244. const LLVMContext &Ctx = MF->getFunction()->getContext();
  1245. if (!DL.isUnknown()) { // Print source line info.
  1246. DIScope Scope(DL.getScope(Ctx));
  1247. assert((!Scope || Scope.isScope()) &&
  1248. "Scope of a DebugLoc should be null or a DIScope.");
  1249. // Omit the directory, because it's likely to be long and uninteresting.
  1250. if (Scope)
  1251. CommentOS << Scope.getFilename();
  1252. else
  1253. CommentOS << "<unknown>";
  1254. CommentOS << ':' << DL.getLine();
  1255. if (DL.getCol() != 0)
  1256. CommentOS << ':' << DL.getCol();
  1257. DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
  1258. if (!InlinedAtDL.isUnknown()) {
  1259. CommentOS << " @[ ";
  1260. printDebugLoc(InlinedAtDL, MF, CommentOS);
  1261. CommentOS << " ]";
  1262. }
  1263. }
  1264. }
  1265. void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM,
  1266. bool SkipOpers) const {
  1267. // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
  1268. const MachineFunction *MF = 0;
  1269. const MachineRegisterInfo *MRI = 0;
  1270. if (const MachineBasicBlock *MBB = getParent()) {
  1271. MF = MBB->getParent();
  1272. if (!TM && MF)
  1273. TM = &MF->getTarget();
  1274. if (MF)
  1275. MRI = &MF->getRegInfo();
  1276. }
  1277. // Save a list of virtual registers.
  1278. SmallVector<unsigned, 8> VirtRegs;
  1279. // Print explicitly defined operands on the left of an assignment syntax.
  1280. unsigned StartOp = 0, e = getNumOperands();
  1281. for (; StartOp < e && getOperand(StartOp).isReg() &&
  1282. getOperand(StartOp).isDef() &&
  1283. !getOperand(StartOp).isImplicit();
  1284. ++StartOp) {
  1285. if (StartOp != 0) OS << ", ";
  1286. getOperand(StartOp).print(OS, TM);
  1287. unsigned Reg = getOperand(StartOp).getReg();
  1288. if (TargetRegisterInfo::isVirtualRegister(Reg))
  1289. VirtRegs.push_back(Reg);
  1290. }
  1291. if (StartOp != 0)
  1292. OS << " = ";
  1293. // Print the opcode name.
  1294. if (TM && TM->getInstrInfo())
  1295. OS << TM->getInstrInfo()->getName(getOpcode());
  1296. else
  1297. OS << "UNKNOWN";
  1298. if (SkipOpers)
  1299. return;
  1300. // Print the rest of the operands.
  1301. bool OmittedAnyCallClobbers = false;
  1302. bool FirstOp = true;
  1303. unsigned AsmDescOp = ~0u;
  1304. unsigned AsmOpCount = 0;
  1305. if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
  1306. // Print asm string.
  1307. OS << " ";
  1308. getOperand(InlineAsm::MIOp_AsmString).print(OS, TM);
  1309. // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
  1310. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1311. if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
  1312. OS << " [sideeffect]";
  1313. if (ExtraInfo & InlineAsm::Extra_MayLoad)
  1314. OS << " [mayload]";
  1315. if (ExtraInfo & InlineAsm::Extra_MayStore)
  1316. OS << " [maystore]";
  1317. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  1318. OS << " [alignstack]";
  1319. if (getInlineAsmDialect() == InlineAsm::AD_ATT)
  1320. OS << " [attdialect]";
  1321. if (getInlineAsmDialect() == InlineAsm::AD_Intel)
  1322. OS << " [inteldialect]";
  1323. StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
  1324. FirstOp = false;
  1325. }
  1326. for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
  1327. const MachineOperand &MO = getOperand(i);
  1328. if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  1329. VirtRegs.push_back(MO.getReg());
  1330. // Omit call-clobbered registers which aren't used anywhere. This makes
  1331. // call instructions much less noisy on targets where calls clobber lots
  1332. // of registers. Don't rely on MO.isDead() because we may be called before
  1333. // LiveVariables is run, or we may be looking at a non-allocatable reg.
  1334. if (MF && isCall() &&
  1335. MO.isReg() && MO.isImplicit() && MO.isDef()) {
  1336. unsigned Reg = MO.getReg();
  1337. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  1338. const MachineRegisterInfo &MRI = MF->getRegInfo();
  1339. if (MRI.use_empty(Reg)) {
  1340. bool HasAliasLive = false;
  1341. for (MCRegAliasIterator AI(Reg, TM->getRegisterInfo(), true);
  1342. AI.isValid(); ++AI) {
  1343. unsigned AliasReg = *AI;
  1344. if (!MRI.use_empty(AliasReg)) {
  1345. HasAliasLive = true;
  1346. break;
  1347. }
  1348. }
  1349. if (!HasAliasLive) {
  1350. OmittedAnyCallClobbers = true;
  1351. continue;
  1352. }
  1353. }
  1354. }
  1355. }
  1356. if (FirstOp) FirstOp = false; else OS << ",";
  1357. OS << " ";
  1358. if (i < getDesc().NumOperands) {
  1359. const MCOperandInfo &MCOI = getDesc().OpInfo[i];
  1360. if (MCOI.isPredicate())
  1361. OS << "pred:";
  1362. if (MCOI.isOptionalDef())
  1363. OS << "opt:";
  1364. }
  1365. if (isDebugValue() && MO.isMetadata()) {
  1366. // Pretty print DBG_VALUE instructions.
  1367. const MDNode *MD = MO.getMetadata();
  1368. if (const MDString *MDS = dyn_cast<MDString>(MD->getOperand(2)))
  1369. OS << "!\"" << MDS->getString() << '\"';
  1370. else
  1371. MO.print(OS, TM);
  1372. } else if (TM && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
  1373. OS << TM->getRegisterInfo()->getSubRegIndexName(MO.getImm());
  1374. } else if (i == AsmDescOp && MO.isImm()) {
  1375. // Pretty print the inline asm operand descriptor.
  1376. OS << '$' << AsmOpCount++;
  1377. unsigned Flag = MO.getImm();
  1378. switch (InlineAsm::getKind(Flag)) {
  1379. case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
  1380. case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
  1381. case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
  1382. case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
  1383. case InlineAsm::Kind_Imm: OS << ":[imm"; break;
  1384. case InlineAsm::Kind_Mem: OS << ":[mem"; break;
  1385. default: OS << ":[??" << InlineAsm::getKind(Flag); break;
  1386. }
  1387. unsigned RCID = 0;
  1388. if (InlineAsm::hasRegClassConstraint(Flag, RCID)) {
  1389. if (TM)
  1390. OS << ':' << TM->getRegisterInfo()->getRegClass(RCID)->getName();
  1391. else
  1392. OS << ":RC" << RCID;
  1393. }
  1394. unsigned TiedTo = 0;
  1395. if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
  1396. OS << " tiedto:$" << TiedTo;
  1397. OS << ']';
  1398. // Compute the index of the next operand descriptor.
  1399. AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
  1400. } else
  1401. MO.print(OS, TM);
  1402. }
  1403. // Briefly indicate whether any call clobbers were omitted.
  1404. if (OmittedAnyCallClobbers) {
  1405. if (!FirstOp) OS << ",";
  1406. OS << " ...";
  1407. }
  1408. bool HaveSemi = false;
  1409. const unsigned PrintableFlags = FrameSetup;
  1410. if (Flags & PrintableFlags) {
  1411. if (!HaveSemi) OS << ";"; HaveSemi = true;
  1412. OS << " flags: ";
  1413. if (Flags & FrameSetup)
  1414. OS << "FrameSetup";
  1415. }
  1416. if (!memoperands_empty()) {
  1417. if (!HaveSemi) OS << ";"; HaveSemi = true;
  1418. OS << " mem:";
  1419. for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
  1420. i != e; ++i) {
  1421. OS << **i;
  1422. if (llvm::next(i) != e)
  1423. OS << " ";
  1424. }
  1425. }
  1426. // Print the regclass of any virtual registers encountered.
  1427. if (MRI && !VirtRegs.empty()) {
  1428. if (!HaveSemi) OS << ";"; HaveSemi = true;
  1429. for (unsigned i = 0; i != VirtRegs.size(); ++i) {
  1430. const TargetRegisterClass *RC = MRI->getRegClass(VirtRegs[i]);
  1431. OS << " " << RC->getName() << ':' << PrintReg(VirtRegs[i]);
  1432. for (unsigned j = i+1; j != VirtRegs.size();) {
  1433. if (MRI->getRegClass(VirtRegs[j]) != RC) {
  1434. ++j;
  1435. continue;
  1436. }
  1437. if (VirtRegs[i] != VirtRegs[j])
  1438. OS << "," << PrintReg(VirtRegs[j]);
  1439. VirtRegs.erase(VirtRegs.begin()+j);
  1440. }
  1441. }
  1442. }
  1443. // Print debug location information.
  1444. if (isDebugValue() && getOperand(e - 1).isMetadata()) {
  1445. if (!HaveSemi) OS << ";"; HaveSemi = true;
  1446. DIVariable DV(getOperand(e - 1).getMetadata());
  1447. OS << " line no:" << DV.getLineNumber();
  1448. if (MDNode *InlinedAt = DV.getInlinedAt()) {
  1449. DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
  1450. if (!InlinedAtDL.isUnknown()) {
  1451. OS << " inlined @[ ";
  1452. printDebugLoc(InlinedAtDL, MF, OS);
  1453. OS << " ]";
  1454. }
  1455. }
  1456. } else if (!debugLoc.isUnknown() && MF) {
  1457. if (!HaveSemi) OS << ";"; HaveSemi = true;
  1458. OS << " dbg:";
  1459. printDebugLoc(debugLoc, MF, OS);
  1460. }
  1461. OS << '\n';
  1462. }
  1463. bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
  1464. const TargetRegisterInfo *RegInfo,
  1465. bool AddIfNotFound) {
  1466. bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
  1467. bool hasAliases = isPhysReg &&
  1468. MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
  1469. bool Found = false;
  1470. SmallVector<unsigned,4> DeadOps;
  1471. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1472. MachineOperand &MO = getOperand(i);
  1473. if (!MO.isReg() || !MO.isUse() || MO.isUndef())
  1474. continue;
  1475. unsigned Reg = MO.getReg();
  1476. if (!Reg)
  1477. continue;
  1478. if (Reg == IncomingReg) {
  1479. if (!Found) {
  1480. if (MO.isKill())
  1481. // The register is already marked kill.
  1482. return true;
  1483. if (isPhysReg && isRegTiedToDefOperand(i))
  1484. // Two-address uses of physregs must not be marked kill.
  1485. return true;
  1486. MO.setIsKill();
  1487. Found = true;
  1488. }
  1489. } else if (hasAliases && MO.isKill() &&
  1490. TargetRegisterInfo::isPhysicalRegister(Reg)) {
  1491. // A super-register kill already exists.
  1492. if (RegInfo->isSuperRegister(IncomingReg, Reg))
  1493. return true;
  1494. if (RegInfo->isSubRegister(IncomingReg, Reg))
  1495. DeadOps.push_back(i);
  1496. }
  1497. }
  1498. // Trim unneeded kill operands.
  1499. while (!DeadOps.empty()) {
  1500. unsigned OpIdx = DeadOps.back();
  1501. if (getOperand(OpIdx).isImplicit())
  1502. RemoveOperand(OpIdx);
  1503. else
  1504. getOperand(OpIdx).setIsKill(false);
  1505. DeadOps.pop_back();
  1506. }
  1507. // If not found, this means an alias of one of the operands is killed. Add a
  1508. // new implicit operand if required.
  1509. if (!Found && AddIfNotFound) {
  1510. addOperand(MachineOperand::CreateReg(IncomingReg,
  1511. false /*IsDef*/,
  1512. true /*IsImp*/,
  1513. true /*IsKill*/));
  1514. return true;
  1515. }
  1516. return Found;
  1517. }
  1518. void MachineInstr::clearRegisterKills(unsigned Reg,
  1519. const TargetRegisterInfo *RegInfo) {
  1520. if (!TargetRegisterInfo::isPhysicalRegister(Reg))
  1521. RegInfo = 0;
  1522. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1523. MachineOperand &MO = getOperand(i);
  1524. if (!MO.isReg() || !MO.isUse() || !MO.isKill())
  1525. continue;
  1526. unsigned OpReg = MO.getReg();
  1527. if (OpReg == Reg || (RegInfo && RegInfo->isSuperRegister(Reg, OpReg)))
  1528. MO.setIsKill(false);
  1529. }
  1530. }
  1531. bool MachineInstr::addRegisterDead(unsigned Reg,
  1532. const TargetRegisterInfo *RegInfo,
  1533. bool AddIfNotFound) {
  1534. bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(Reg);
  1535. bool hasAliases = isPhysReg &&
  1536. MCRegAliasIterator(Reg, RegInfo, false).isValid();
  1537. bool Found = false;
  1538. SmallVector<unsigned,4> DeadOps;
  1539. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1540. MachineOperand &MO = getOperand(i);
  1541. if (!MO.isReg() || !MO.isDef())
  1542. continue;
  1543. unsigned MOReg = MO.getReg();
  1544. if (!MOReg)
  1545. continue;
  1546. if (MOReg == Reg) {
  1547. MO.setIsDead();
  1548. Found = true;
  1549. } else if (hasAliases && MO.isDead() &&
  1550. TargetRegisterInfo::isPhysicalRegister(MOReg)) {
  1551. // There exists a super-register that's marked dead.
  1552. if (RegInfo->isSuperRegister(Reg, MOReg))
  1553. return true;
  1554. if (RegInfo->isSubRegister(Reg, MOReg))
  1555. DeadOps.push_back(i);
  1556. }
  1557. }
  1558. // Trim unneeded dead operands.
  1559. while (!DeadOps.empty()) {
  1560. unsigned OpIdx = DeadOps.back();
  1561. if (getOperand(OpIdx).isImplicit())
  1562. RemoveOperand(OpIdx);
  1563. else
  1564. getOperand(OpIdx).setIsDead(false);
  1565. DeadOps.pop_back();
  1566. }
  1567. // If not found, this means an alias of one of the operands is dead. Add a
  1568. // new implicit operand if required.
  1569. if (Found || !AddIfNotFound)
  1570. return Found;
  1571. addOperand(MachineOperand::CreateReg(Reg,
  1572. true /*IsDef*/,
  1573. true /*IsImp*/,
  1574. false /*IsKill*/,
  1575. true /*IsDead*/));
  1576. return true;
  1577. }
  1578. void MachineInstr::addRegisterDefined(unsigned Reg,
  1579. const TargetRegisterInfo *RegInfo) {
  1580. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  1581. MachineOperand *MO = findRegisterDefOperand(Reg, false, RegInfo);
  1582. if (MO)
  1583. return;
  1584. } else {
  1585. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1586. const MachineOperand &MO = getOperand(i);
  1587. if (MO.isReg() && MO.getReg() == Reg && MO.isDef() &&
  1588. MO.getSubReg() == 0)
  1589. return;
  1590. }
  1591. }
  1592. addOperand(MachineOperand::CreateReg(Reg,
  1593. true /*IsDef*/,
  1594. true /*IsImp*/));
  1595. }
  1596. void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
  1597. const TargetRegisterInfo &TRI) {
  1598. bool HasRegMask = false;
  1599. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1600. MachineOperand &MO = getOperand(i);
  1601. if (MO.isRegMask()) {
  1602. HasRegMask = true;
  1603. continue;
  1604. }
  1605. if (!MO.isReg() || !MO.isDef()) continue;
  1606. unsigned Reg = MO.getReg();
  1607. if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
  1608. bool Dead = true;
  1609. for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
  1610. I != E; ++I)
  1611. if (TRI.regsOverlap(*I, Reg)) {
  1612. Dead = false;
  1613. break;
  1614. }
  1615. // If there are no uses, including partial uses, the def is dead.
  1616. if (Dead) MO.setIsDead();
  1617. }
  1618. // This is a call with a register mask operand.
  1619. // Mask clobbers are always dead, so add defs for the non-dead defines.
  1620. if (HasRegMask)
  1621. for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
  1622. I != E; ++I)
  1623. addRegisterDefined(*I, &TRI);
  1624. }
  1625. unsigned
  1626. MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
  1627. // Build up a buffer of hash code components.
  1628. SmallVector<size_t, 8> HashComponents;
  1629. HashComponents.reserve(MI->getNumOperands() + 1);
  1630. HashComponents.push_back(MI->getOpcode());
  1631. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  1632. const MachineOperand &MO = MI->getOperand(i);
  1633. if (MO.isReg() && MO.isDef() &&
  1634. TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  1635. continue; // Skip virtual register defs.
  1636. HashComponents.push_back(hash_value(MO));
  1637. }
  1638. return hash_combine_range(HashComponents.begin(), HashComponents.end());
  1639. }
  1640. void MachineInstr::emitError(StringRef Msg) const {
  1641. // Find the source location cookie.
  1642. unsigned LocCookie = 0;
  1643. const MDNode *LocMD = 0;
  1644. for (unsigned i = getNumOperands(); i != 0; --i) {
  1645. if (getOperand(i-1).isMetadata() &&
  1646. (LocMD = getOperand(i-1).getMetadata()) &&
  1647. LocMD->getNumOperands() != 0) {
  1648. if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
  1649. LocCookie = CI->getZExtValue();
  1650. break;
  1651. }
  1652. }
  1653. }
  1654. if (const MachineBasicBlock *MBB = getParent())
  1655. if (const MachineFunction *MF = MBB->getParent())
  1656. return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
  1657. report_fatal_error(Msg);
  1658. }