MachineInstr.cpp 65 KB

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