MachineInstr.cpp 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867
  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. // OpNo now points as the desired insertion point. Unless this is a variadic
  591. // instruction, only implicit regs are allowed beyond MCID->getNumOperands().
  592. // RegMask operands go between the explicit and implicit operands.
  593. assert((isImpReg || Op.isRegMask() || MCID->isVariadic() ||
  594. OpNo < MCID->getNumOperands()) &&
  595. "Trying to add an operand to a machine instr that is already done!");
  596. MachineRegisterInfo *MRI = getRegInfo();
  597. // Determine if the Operands array needs to be reallocated.
  598. // Save the old capacity and operand array.
  599. OperandCapacity OldCap = CapOperands;
  600. MachineOperand *OldOperands = Operands;
  601. if (!OldOperands || OldCap.getSize() == getNumOperands()) {
  602. CapOperands = OldOperands ? OldCap.getNext() : OldCap.get(1);
  603. Operands = MF.allocateOperandArray(CapOperands);
  604. // Move the operands before the insertion point.
  605. if (OpNo)
  606. moveOperands(Operands, OldOperands, OpNo, MRI);
  607. }
  608. // Move the operands following the insertion point.
  609. if (OpNo != NumOperands)
  610. moveOperands(Operands + OpNo + 1, OldOperands + OpNo, NumOperands - OpNo,
  611. MRI);
  612. ++NumOperands;
  613. // Deallocate the old operand array.
  614. if (OldOperands != Operands && OldOperands)
  615. MF.deallocateOperandArray(OldCap, OldOperands);
  616. // Copy Op into place. It still needs to be inserted into the MRI use lists.
  617. MachineOperand *NewMO = new (Operands + OpNo) MachineOperand(Op);
  618. NewMO->ParentMI = this;
  619. // When adding a register operand, tell MRI about it.
  620. if (NewMO->isReg()) {
  621. // Ensure isOnRegUseList() returns false, regardless of Op's status.
  622. NewMO->Contents.Reg.Prev = 0;
  623. // Ignore existing ties. This is not a property that can be copied.
  624. NewMO->TiedTo = 0;
  625. // Add the new operand to MRI, but only for instructions in an MBB.
  626. if (MRI)
  627. MRI->addRegOperandToUseList(NewMO);
  628. // The MCID operand information isn't accurate until we start adding
  629. // explicit operands. The implicit operands are added first, then the
  630. // explicits are inserted before them.
  631. if (!isImpReg) {
  632. // Tie uses to defs as indicated in MCInstrDesc.
  633. if (NewMO->isUse()) {
  634. int DefIdx = MCID->getOperandConstraint(OpNo, MCOI::TIED_TO);
  635. if (DefIdx != -1)
  636. tieOperands(DefIdx, OpNo);
  637. }
  638. // If the register operand is flagged as early, mark the operand as such.
  639. if (MCID->getOperandConstraint(OpNo, MCOI::EARLY_CLOBBER) != -1)
  640. NewMO->setIsEarlyClobber(true);
  641. }
  642. }
  643. }
  644. /// RemoveOperand - Erase an operand from an instruction, leaving it with one
  645. /// fewer operand than it started with.
  646. ///
  647. void MachineInstr::RemoveOperand(unsigned OpNo) {
  648. assert(OpNo < getNumOperands() && "Invalid operand number");
  649. untieRegOperand(OpNo);
  650. #ifndef NDEBUG
  651. // Moving tied operands would break the ties.
  652. for (unsigned i = OpNo + 1, e = getNumOperands(); i != e; ++i)
  653. if (Operands[i].isReg())
  654. assert(!Operands[i].isTied() && "Cannot move tied operands");
  655. #endif
  656. MachineRegisterInfo *MRI = getRegInfo();
  657. if (MRI && Operands[OpNo].isReg())
  658. MRI->removeRegOperandFromUseList(Operands + OpNo);
  659. // Don't call the MachineOperand destructor. A lot of this code depends on
  660. // MachineOperand having a trivial destructor anyway, and adding a call here
  661. // wouldn't make it 'destructor-correct'.
  662. if (unsigned N = NumOperands - 1 - OpNo)
  663. moveOperands(Operands + OpNo, Operands + OpNo + 1, N, MRI);
  664. --NumOperands;
  665. }
  666. /// addMemOperand - Add a MachineMemOperand to the machine instruction.
  667. /// This function should be used only occasionally. The setMemRefs function
  668. /// is the primary method for setting up a MachineInstr's MemRefs list.
  669. void MachineInstr::addMemOperand(MachineFunction &MF,
  670. MachineMemOperand *MO) {
  671. mmo_iterator OldMemRefs = MemRefs;
  672. unsigned OldNumMemRefs = NumMemRefs;
  673. unsigned NewNum = NumMemRefs + 1;
  674. mmo_iterator NewMemRefs = MF.allocateMemRefsArray(NewNum);
  675. std::copy(OldMemRefs, OldMemRefs + OldNumMemRefs, NewMemRefs);
  676. NewMemRefs[NewNum - 1] = MO;
  677. setMemRefs(NewMemRefs, NewMemRefs + NewNum);
  678. }
  679. bool MachineInstr::hasPropertyInBundle(unsigned Mask, QueryType Type) const {
  680. assert(!isBundledWithPred() && "Must be called on bundle header");
  681. for (MachineBasicBlock::const_instr_iterator MII = this;; ++MII) {
  682. if (MII->getDesc().getFlags() & Mask) {
  683. if (Type == AnyInBundle)
  684. return true;
  685. } else {
  686. if (Type == AllInBundle && !MII->isBundle())
  687. return false;
  688. }
  689. // This was the last instruction in the bundle.
  690. if (!MII->isBundledWithSucc())
  691. return Type == AllInBundle;
  692. }
  693. }
  694. bool MachineInstr::isIdenticalTo(const MachineInstr *Other,
  695. MICheckType Check) const {
  696. // If opcodes or number of operands are not the same then the two
  697. // instructions are obviously not identical.
  698. if (Other->getOpcode() != getOpcode() ||
  699. Other->getNumOperands() != getNumOperands())
  700. return false;
  701. if (isBundle()) {
  702. // Both instructions are bundles, compare MIs inside the bundle.
  703. MachineBasicBlock::const_instr_iterator I1 = *this;
  704. MachineBasicBlock::const_instr_iterator E1 = getParent()->instr_end();
  705. MachineBasicBlock::const_instr_iterator I2 = *Other;
  706. MachineBasicBlock::const_instr_iterator E2= Other->getParent()->instr_end();
  707. while (++I1 != E1 && I1->isInsideBundle()) {
  708. ++I2;
  709. if (I2 == E2 || !I2->isInsideBundle() || !I1->isIdenticalTo(I2, Check))
  710. return false;
  711. }
  712. }
  713. // Check operands to make sure they match.
  714. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  715. const MachineOperand &MO = getOperand(i);
  716. const MachineOperand &OMO = Other->getOperand(i);
  717. if (!MO.isReg()) {
  718. if (!MO.isIdenticalTo(OMO))
  719. return false;
  720. continue;
  721. }
  722. // Clients may or may not want to ignore defs when testing for equality.
  723. // For example, machine CSE pass only cares about finding common
  724. // subexpressions, so it's safe to ignore virtual register defs.
  725. if (MO.isDef()) {
  726. if (Check == IgnoreDefs)
  727. continue;
  728. else if (Check == IgnoreVRegDefs) {
  729. if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) ||
  730. TargetRegisterInfo::isPhysicalRegister(OMO.getReg()))
  731. if (MO.getReg() != OMO.getReg())
  732. return false;
  733. } else {
  734. if (!MO.isIdenticalTo(OMO))
  735. return false;
  736. if (Check == CheckKillDead && MO.isDead() != OMO.isDead())
  737. return false;
  738. }
  739. } else {
  740. if (!MO.isIdenticalTo(OMO))
  741. return false;
  742. if (Check == CheckKillDead && MO.isKill() != OMO.isKill())
  743. return false;
  744. }
  745. }
  746. // If DebugLoc does not match then two dbg.values are not identical.
  747. if (isDebugValue())
  748. if (!getDebugLoc().isUnknown() && !Other->getDebugLoc().isUnknown()
  749. && getDebugLoc() != Other->getDebugLoc())
  750. return false;
  751. return true;
  752. }
  753. MachineInstr *MachineInstr::removeFromParent() {
  754. assert(getParent() && "Not embedded in a basic block!");
  755. return getParent()->remove(this);
  756. }
  757. MachineInstr *MachineInstr::removeFromBundle() {
  758. assert(getParent() && "Not embedded in a basic block!");
  759. return getParent()->remove_instr(this);
  760. }
  761. void MachineInstr::eraseFromParent() {
  762. assert(getParent() && "Not embedded in a basic block!");
  763. getParent()->erase(this);
  764. }
  765. void MachineInstr::eraseFromBundle() {
  766. assert(getParent() && "Not embedded in a basic block!");
  767. getParent()->erase_instr(this);
  768. }
  769. /// getNumExplicitOperands - Returns the number of non-implicit operands.
  770. ///
  771. unsigned MachineInstr::getNumExplicitOperands() const {
  772. unsigned NumOperands = MCID->getNumOperands();
  773. if (!MCID->isVariadic())
  774. return NumOperands;
  775. for (unsigned i = NumOperands, e = getNumOperands(); i != e; ++i) {
  776. const MachineOperand &MO = getOperand(i);
  777. if (!MO.isReg() || !MO.isImplicit())
  778. NumOperands++;
  779. }
  780. return NumOperands;
  781. }
  782. void MachineInstr::bundleWithPred() {
  783. assert(!isBundledWithPred() && "MI is already bundled with its predecessor");
  784. setFlag(BundledPred);
  785. MachineBasicBlock::instr_iterator Pred = this;
  786. --Pred;
  787. assert(!Pred->isBundledWithSucc() && "Inconsistent bundle flags");
  788. Pred->setFlag(BundledSucc);
  789. }
  790. void MachineInstr::bundleWithSucc() {
  791. assert(!isBundledWithSucc() && "MI is already bundled with its successor");
  792. setFlag(BundledSucc);
  793. MachineBasicBlock::instr_iterator Succ = this;
  794. ++Succ;
  795. assert(!Succ->isBundledWithPred() && "Inconsistent bundle flags");
  796. Succ->setFlag(BundledPred);
  797. }
  798. void MachineInstr::unbundleFromPred() {
  799. assert(isBundledWithPred() && "MI isn't bundled with its predecessor");
  800. clearFlag(BundledPred);
  801. MachineBasicBlock::instr_iterator Pred = this;
  802. --Pred;
  803. assert(Pred->isBundledWithSucc() && "Inconsistent bundle flags");
  804. Pred->clearFlag(BundledSucc);
  805. }
  806. void MachineInstr::unbundleFromSucc() {
  807. assert(isBundledWithSucc() && "MI isn't bundled with its successor");
  808. clearFlag(BundledSucc);
  809. MachineBasicBlock::instr_iterator Succ = this;
  810. ++Succ;
  811. assert(Succ->isBundledWithPred() && "Inconsistent bundle flags");
  812. Succ->clearFlag(BundledPred);
  813. }
  814. bool MachineInstr::isStackAligningInlineAsm() const {
  815. if (isInlineAsm()) {
  816. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  817. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  818. return true;
  819. }
  820. return false;
  821. }
  822. InlineAsm::AsmDialect MachineInstr::getInlineAsmDialect() const {
  823. assert(isInlineAsm() && "getInlineAsmDialect() only works for inline asms!");
  824. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  825. return InlineAsm::AsmDialect((ExtraInfo & InlineAsm::Extra_AsmDialect) != 0);
  826. }
  827. int MachineInstr::findInlineAsmFlagIdx(unsigned OpIdx,
  828. unsigned *GroupNo) const {
  829. assert(isInlineAsm() && "Expected an inline asm instruction");
  830. assert(OpIdx < getNumOperands() && "OpIdx out of range");
  831. // Ignore queries about the initial operands.
  832. if (OpIdx < InlineAsm::MIOp_FirstOperand)
  833. return -1;
  834. unsigned Group = 0;
  835. unsigned NumOps;
  836. for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
  837. i += NumOps) {
  838. const MachineOperand &FlagMO = getOperand(i);
  839. // If we reach the implicit register operands, stop looking.
  840. if (!FlagMO.isImm())
  841. return -1;
  842. NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
  843. if (i + NumOps > OpIdx) {
  844. if (GroupNo)
  845. *GroupNo = Group;
  846. return i;
  847. }
  848. ++Group;
  849. }
  850. return -1;
  851. }
  852. const TargetRegisterClass*
  853. MachineInstr::getRegClassConstraint(unsigned OpIdx,
  854. const TargetInstrInfo *TII,
  855. const TargetRegisterInfo *TRI) const {
  856. assert(getParent() && "Can't have an MBB reference here!");
  857. assert(getParent()->getParent() && "Can't have an MF reference here!");
  858. const MachineFunction &MF = *getParent()->getParent();
  859. // Most opcodes have fixed constraints in their MCInstrDesc.
  860. if (!isInlineAsm())
  861. return TII->getRegClass(getDesc(), OpIdx, TRI, MF);
  862. if (!getOperand(OpIdx).isReg())
  863. return NULL;
  864. // For tied uses on inline asm, get the constraint from the def.
  865. unsigned DefIdx;
  866. if (getOperand(OpIdx).isUse() && isRegTiedToDefOperand(OpIdx, &DefIdx))
  867. OpIdx = DefIdx;
  868. // Inline asm stores register class constraints in the flag word.
  869. int FlagIdx = findInlineAsmFlagIdx(OpIdx);
  870. if (FlagIdx < 0)
  871. return NULL;
  872. unsigned Flag = getOperand(FlagIdx).getImm();
  873. unsigned RCID;
  874. if (InlineAsm::hasRegClassConstraint(Flag, RCID))
  875. return TRI->getRegClass(RCID);
  876. // Assume that all registers in a memory operand are pointers.
  877. if (InlineAsm::getKind(Flag) == InlineAsm::Kind_Mem)
  878. return TRI->getPointerRegClass(MF);
  879. return NULL;
  880. }
  881. /// Return the number of instructions inside the MI bundle, not counting the
  882. /// header instruction.
  883. unsigned MachineInstr::getBundleSize() const {
  884. MachineBasicBlock::const_instr_iterator I = this;
  885. unsigned Size = 0;
  886. while (I->isBundledWithSucc())
  887. ++Size, ++I;
  888. return Size;
  889. }
  890. /// findRegisterUseOperandIdx() - Returns the MachineOperand that is a use of
  891. /// the specific register or -1 if it is not found. It further tightens
  892. /// the search criteria to a use that kills the register if isKill is true.
  893. int MachineInstr::findRegisterUseOperandIdx(unsigned Reg, bool isKill,
  894. const TargetRegisterInfo *TRI) const {
  895. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  896. const MachineOperand &MO = getOperand(i);
  897. if (!MO.isReg() || !MO.isUse())
  898. continue;
  899. unsigned MOReg = MO.getReg();
  900. if (!MOReg)
  901. continue;
  902. if (MOReg == Reg ||
  903. (TRI &&
  904. TargetRegisterInfo::isPhysicalRegister(MOReg) &&
  905. TargetRegisterInfo::isPhysicalRegister(Reg) &&
  906. TRI->isSubRegister(MOReg, Reg)))
  907. if (!isKill || MO.isKill())
  908. return i;
  909. }
  910. return -1;
  911. }
  912. /// readsWritesVirtualRegister - Return a pair of bools (reads, writes)
  913. /// indicating if this instruction reads or writes Reg. This also considers
  914. /// partial defines.
  915. std::pair<bool,bool>
  916. MachineInstr::readsWritesVirtualRegister(unsigned Reg,
  917. SmallVectorImpl<unsigned> *Ops) const {
  918. bool PartDef = false; // Partial redefine.
  919. bool FullDef = false; // Full define.
  920. bool Use = false;
  921. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  922. const MachineOperand &MO = getOperand(i);
  923. if (!MO.isReg() || MO.getReg() != Reg)
  924. continue;
  925. if (Ops)
  926. Ops->push_back(i);
  927. if (MO.isUse())
  928. Use |= !MO.isUndef();
  929. else if (MO.getSubReg() && !MO.isUndef())
  930. // A partial <def,undef> doesn't count as reading the register.
  931. PartDef = true;
  932. else
  933. FullDef = true;
  934. }
  935. // A partial redefine uses Reg unless there is also a full define.
  936. return std::make_pair(Use || (PartDef && !FullDef), PartDef || FullDef);
  937. }
  938. /// findRegisterDefOperandIdx() - Returns the operand index that is a def of
  939. /// the specified register or -1 if it is not found. If isDead is true, defs
  940. /// that are not dead are skipped. If TargetRegisterInfo is non-null, then it
  941. /// also checks if there is a def of a super-register.
  942. int
  943. MachineInstr::findRegisterDefOperandIdx(unsigned Reg, bool isDead, bool Overlap,
  944. const TargetRegisterInfo *TRI) const {
  945. bool isPhys = TargetRegisterInfo::isPhysicalRegister(Reg);
  946. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  947. const MachineOperand &MO = getOperand(i);
  948. // Accept regmask operands when Overlap is set.
  949. // Ignore them when looking for a specific def operand (Overlap == false).
  950. if (isPhys && Overlap && MO.isRegMask() && MO.clobbersPhysReg(Reg))
  951. return i;
  952. if (!MO.isReg() || !MO.isDef())
  953. continue;
  954. unsigned MOReg = MO.getReg();
  955. bool Found = (MOReg == Reg);
  956. if (!Found && TRI && isPhys &&
  957. TargetRegisterInfo::isPhysicalRegister(MOReg)) {
  958. if (Overlap)
  959. Found = TRI->regsOverlap(MOReg, Reg);
  960. else
  961. Found = TRI->isSubRegister(MOReg, Reg);
  962. }
  963. if (Found && (!isDead || MO.isDead()))
  964. return i;
  965. }
  966. return -1;
  967. }
  968. /// findFirstPredOperandIdx() - Find the index of the first operand in the
  969. /// operand list that is used to represent the predicate. It returns -1 if
  970. /// none is found.
  971. int MachineInstr::findFirstPredOperandIdx() const {
  972. // Don't call MCID.findFirstPredOperandIdx() because this variant
  973. // is sometimes called on an instruction that's not yet complete, and
  974. // so the number of operands is less than the MCID indicates. In
  975. // particular, the PTX target does this.
  976. const MCInstrDesc &MCID = getDesc();
  977. if (MCID.isPredicable()) {
  978. for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
  979. if (MCID.OpInfo[i].isPredicate())
  980. return i;
  981. }
  982. return -1;
  983. }
  984. // MachineOperand::TiedTo is 4 bits wide.
  985. const unsigned TiedMax = 15;
  986. /// tieOperands - Mark operands at DefIdx and UseIdx as tied to each other.
  987. ///
  988. /// Use and def operands can be tied together, indicated by a non-zero TiedTo
  989. /// field. TiedTo can have these values:
  990. ///
  991. /// 0: Operand is not tied to anything.
  992. /// 1 to TiedMax-1: Tied to getOperand(TiedTo-1).
  993. /// TiedMax: Tied to an operand >= TiedMax-1.
  994. ///
  995. /// The tied def must be one of the first TiedMax operands on a normal
  996. /// instruction. INLINEASM instructions allow more tied defs.
  997. ///
  998. void MachineInstr::tieOperands(unsigned DefIdx, unsigned UseIdx) {
  999. MachineOperand &DefMO = getOperand(DefIdx);
  1000. MachineOperand &UseMO = getOperand(UseIdx);
  1001. assert(DefMO.isDef() && "DefIdx must be a def operand");
  1002. assert(UseMO.isUse() && "UseIdx must be a use operand");
  1003. assert(!DefMO.isTied() && "Def is already tied to another use");
  1004. assert(!UseMO.isTied() && "Use is already tied to another def");
  1005. if (DefIdx < TiedMax)
  1006. UseMO.TiedTo = DefIdx + 1;
  1007. else {
  1008. // Inline asm can use the group descriptors to find tied operands, but on
  1009. // normal instruction, the tied def must be within the first TiedMax
  1010. // operands.
  1011. assert(isInlineAsm() && "DefIdx out of range");
  1012. UseMO.TiedTo = TiedMax;
  1013. }
  1014. // UseIdx can be out of range, we'll search for it in findTiedOperandIdx().
  1015. DefMO.TiedTo = std::min(UseIdx + 1, TiedMax);
  1016. }
  1017. /// Given the index of a tied register operand, find the operand it is tied to.
  1018. /// Defs are tied to uses and vice versa. Returns the index of the tied operand
  1019. /// which must exist.
  1020. unsigned MachineInstr::findTiedOperandIdx(unsigned OpIdx) const {
  1021. const MachineOperand &MO = getOperand(OpIdx);
  1022. assert(MO.isTied() && "Operand isn't tied");
  1023. // Normally TiedTo is in range.
  1024. if (MO.TiedTo < TiedMax)
  1025. return MO.TiedTo - 1;
  1026. // Uses on normal instructions can be out of range.
  1027. if (!isInlineAsm()) {
  1028. // Normal tied defs must be in the 0..TiedMax-1 range.
  1029. if (MO.isUse())
  1030. return TiedMax - 1;
  1031. // MO is a def. Search for the tied use.
  1032. for (unsigned i = TiedMax - 1, e = getNumOperands(); i != e; ++i) {
  1033. const MachineOperand &UseMO = getOperand(i);
  1034. if (UseMO.isReg() && UseMO.isUse() && UseMO.TiedTo == OpIdx + 1)
  1035. return i;
  1036. }
  1037. llvm_unreachable("Can't find tied use");
  1038. }
  1039. // Now deal with inline asm by parsing the operand group descriptor flags.
  1040. // Find the beginning of each operand group.
  1041. SmallVector<unsigned, 8> GroupIdx;
  1042. unsigned OpIdxGroup = ~0u;
  1043. unsigned NumOps;
  1044. for (unsigned i = InlineAsm::MIOp_FirstOperand, e = getNumOperands(); i < e;
  1045. i += NumOps) {
  1046. const MachineOperand &FlagMO = getOperand(i);
  1047. assert(FlagMO.isImm() && "Invalid tied operand on inline asm");
  1048. unsigned CurGroup = GroupIdx.size();
  1049. GroupIdx.push_back(i);
  1050. NumOps = 1 + InlineAsm::getNumOperandRegisters(FlagMO.getImm());
  1051. // OpIdx belongs to this operand group.
  1052. if (OpIdx > i && OpIdx < i + NumOps)
  1053. OpIdxGroup = CurGroup;
  1054. unsigned TiedGroup;
  1055. if (!InlineAsm::isUseOperandTiedToDef(FlagMO.getImm(), TiedGroup))
  1056. continue;
  1057. // Operands in this group are tied to operands in TiedGroup which must be
  1058. // earlier. Find the number of operands between the two groups.
  1059. unsigned Delta = i - GroupIdx[TiedGroup];
  1060. // OpIdx is a use tied to TiedGroup.
  1061. if (OpIdxGroup == CurGroup)
  1062. return OpIdx - Delta;
  1063. // OpIdx is a def tied to this use group.
  1064. if (OpIdxGroup == TiedGroup)
  1065. return OpIdx + Delta;
  1066. }
  1067. llvm_unreachable("Invalid tied operand on inline asm");
  1068. }
  1069. /// clearKillInfo - Clears kill flags on all operands.
  1070. ///
  1071. void MachineInstr::clearKillInfo() {
  1072. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1073. MachineOperand &MO = getOperand(i);
  1074. if (MO.isReg() && MO.isUse())
  1075. MO.setIsKill(false);
  1076. }
  1077. }
  1078. void MachineInstr::substituteRegister(unsigned FromReg,
  1079. unsigned ToReg,
  1080. unsigned SubIdx,
  1081. const TargetRegisterInfo &RegInfo) {
  1082. if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
  1083. if (SubIdx)
  1084. ToReg = RegInfo.getSubReg(ToReg, SubIdx);
  1085. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1086. MachineOperand &MO = getOperand(i);
  1087. if (!MO.isReg() || MO.getReg() != FromReg)
  1088. continue;
  1089. MO.substPhysReg(ToReg, RegInfo);
  1090. }
  1091. } else {
  1092. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1093. MachineOperand &MO = getOperand(i);
  1094. if (!MO.isReg() || MO.getReg() != FromReg)
  1095. continue;
  1096. MO.substVirtReg(ToReg, SubIdx, RegInfo);
  1097. }
  1098. }
  1099. }
  1100. /// isSafeToMove - Return true if it is safe to move this instruction. If
  1101. /// SawStore is set to true, it means that there is a store (or call) between
  1102. /// the instruction's location and its intended destination.
  1103. bool MachineInstr::isSafeToMove(const TargetInstrInfo *TII,
  1104. AliasAnalysis *AA,
  1105. bool &SawStore) const {
  1106. // Ignore stuff that we obviously can't move.
  1107. //
  1108. // Treat volatile loads as stores. This is not strictly necessary for
  1109. // volatiles, but it is required for atomic loads. It is not allowed to move
  1110. // a load across an atomic load with Ordering > Monotonic.
  1111. if (mayStore() || isCall() ||
  1112. (mayLoad() && hasOrderedMemoryRef())) {
  1113. SawStore = true;
  1114. return false;
  1115. }
  1116. if (isLabel() || isDebugValue() ||
  1117. isTerminator() || hasUnmodeledSideEffects())
  1118. return false;
  1119. // See if this instruction does a load. If so, we have to guarantee that the
  1120. // loaded value doesn't change between the load and the its intended
  1121. // destination. The check for isInvariantLoad gives the targe the chance to
  1122. // classify the load as always returning a constant, e.g. a constant pool
  1123. // load.
  1124. if (mayLoad() && !isInvariantLoad(AA))
  1125. // Otherwise, this is a real load. If there is a store between the load and
  1126. // end of block, we can't move it.
  1127. return !SawStore;
  1128. return true;
  1129. }
  1130. /// isSafeToReMat - Return true if it's safe to rematerialize the specified
  1131. /// instruction which defined the specified register instead of copying it.
  1132. bool MachineInstr::isSafeToReMat(const TargetInstrInfo *TII,
  1133. AliasAnalysis *AA,
  1134. unsigned DstReg) const {
  1135. bool SawStore = false;
  1136. if (!TII->isTriviallyReMaterializable(this, AA) ||
  1137. !isSafeToMove(TII, AA, SawStore))
  1138. return false;
  1139. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1140. const MachineOperand &MO = getOperand(i);
  1141. if (!MO.isReg())
  1142. continue;
  1143. // FIXME: For now, do not remat any instruction with register operands.
  1144. // Later on, we can loosen the restriction is the register operands have
  1145. // not been modified between the def and use. Note, this is different from
  1146. // MachineSink because the code is no longer in two-address form (at least
  1147. // partially).
  1148. if (MO.isUse())
  1149. return false;
  1150. else if (!MO.isDead() && MO.getReg() != DstReg)
  1151. return false;
  1152. }
  1153. return true;
  1154. }
  1155. /// hasOrderedMemoryRef - Return true if this instruction may have an ordered
  1156. /// or volatile memory reference, or if the information describing the memory
  1157. /// reference is not available. Return false if it is known to have no ordered
  1158. /// memory references.
  1159. bool MachineInstr::hasOrderedMemoryRef() const {
  1160. // An instruction known never to access memory won't have a volatile access.
  1161. if (!mayStore() &&
  1162. !mayLoad() &&
  1163. !isCall() &&
  1164. !hasUnmodeledSideEffects())
  1165. return false;
  1166. // Otherwise, if the instruction has no memory reference information,
  1167. // conservatively assume it wasn't preserved.
  1168. if (memoperands_empty())
  1169. return true;
  1170. // Check the memory reference information for ordered references.
  1171. for (mmo_iterator I = memoperands_begin(), E = memoperands_end(); I != E; ++I)
  1172. if (!(*I)->isUnordered())
  1173. return true;
  1174. return false;
  1175. }
  1176. /// isInvariantLoad - Return true if this instruction is loading from a
  1177. /// location whose value is invariant across the function. For example,
  1178. /// loading a value from the constant pool or from the argument area
  1179. /// of a function if it does not change. This should only return true of
  1180. /// *all* loads the instruction does are invariant (if it does multiple loads).
  1181. bool MachineInstr::isInvariantLoad(AliasAnalysis *AA) const {
  1182. // If the instruction doesn't load at all, it isn't an invariant load.
  1183. if (!mayLoad())
  1184. return false;
  1185. // If the instruction has lost its memoperands, conservatively assume that
  1186. // it may not be an invariant load.
  1187. if (memoperands_empty())
  1188. return false;
  1189. const MachineFrameInfo *MFI = getParent()->getParent()->getFrameInfo();
  1190. for (mmo_iterator I = memoperands_begin(),
  1191. E = memoperands_end(); I != E; ++I) {
  1192. if ((*I)->isVolatile()) return false;
  1193. if ((*I)->isStore()) return false;
  1194. if ((*I)->isInvariant()) return true;
  1195. if (const Value *V = (*I)->getValue()) {
  1196. // A load from a constant PseudoSourceValue is invariant.
  1197. if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V))
  1198. if (PSV->isConstant(MFI))
  1199. continue;
  1200. // If we have an AliasAnalysis, ask it whether the memory is constant.
  1201. if (AA && AA->pointsToConstantMemory(
  1202. AliasAnalysis::Location(V, (*I)->getSize(),
  1203. (*I)->getTBAAInfo())))
  1204. continue;
  1205. }
  1206. // Otherwise assume conservatively.
  1207. return false;
  1208. }
  1209. // Everything checks out.
  1210. return true;
  1211. }
  1212. /// isConstantValuePHI - If the specified instruction is a PHI that always
  1213. /// merges together the same virtual register, return the register, otherwise
  1214. /// return 0.
  1215. unsigned MachineInstr::isConstantValuePHI() const {
  1216. if (!isPHI())
  1217. return 0;
  1218. assert(getNumOperands() >= 3 &&
  1219. "It's illegal to have a PHI without source operands");
  1220. unsigned Reg = getOperand(1).getReg();
  1221. for (unsigned i = 3, e = getNumOperands(); i < e; i += 2)
  1222. if (getOperand(i).getReg() != Reg)
  1223. return 0;
  1224. return Reg;
  1225. }
  1226. bool MachineInstr::hasUnmodeledSideEffects() const {
  1227. if (hasProperty(MCID::UnmodeledSideEffects))
  1228. return true;
  1229. if (isInlineAsm()) {
  1230. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1231. if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
  1232. return true;
  1233. }
  1234. return false;
  1235. }
  1236. /// allDefsAreDead - Return true if all the defs of this instruction are dead.
  1237. ///
  1238. bool MachineInstr::allDefsAreDead() const {
  1239. for (unsigned i = 0, e = getNumOperands(); i < e; ++i) {
  1240. const MachineOperand &MO = getOperand(i);
  1241. if (!MO.isReg() || MO.isUse())
  1242. continue;
  1243. if (!MO.isDead())
  1244. return false;
  1245. }
  1246. return true;
  1247. }
  1248. /// copyImplicitOps - Copy implicit register operands from specified
  1249. /// instruction to this instruction.
  1250. void MachineInstr::copyImplicitOps(MachineFunction &MF,
  1251. const MachineInstr *MI) {
  1252. for (unsigned i = MI->getDesc().getNumOperands(), e = MI->getNumOperands();
  1253. i != e; ++i) {
  1254. const MachineOperand &MO = MI->getOperand(i);
  1255. if (MO.isReg() && MO.isImplicit())
  1256. addOperand(MF, MO);
  1257. }
  1258. }
  1259. void MachineInstr::dump() const {
  1260. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1261. dbgs() << " " << *this;
  1262. #endif
  1263. }
  1264. static void printDebugLoc(DebugLoc DL, const MachineFunction *MF,
  1265. raw_ostream &CommentOS) {
  1266. const LLVMContext &Ctx = MF->getFunction()->getContext();
  1267. if (!DL.isUnknown()) { // Print source line info.
  1268. DIScope Scope(DL.getScope(Ctx));
  1269. // Omit the directory, because it's likely to be long and uninteresting.
  1270. if (Scope.Verify())
  1271. CommentOS << Scope.getFilename();
  1272. else
  1273. CommentOS << "<unknown>";
  1274. CommentOS << ':' << DL.getLine();
  1275. if (DL.getCol() != 0)
  1276. CommentOS << ':' << DL.getCol();
  1277. DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(DL.getInlinedAt(Ctx));
  1278. if (!InlinedAtDL.isUnknown()) {
  1279. CommentOS << " @[ ";
  1280. printDebugLoc(InlinedAtDL, MF, CommentOS);
  1281. CommentOS << " ]";
  1282. }
  1283. }
  1284. }
  1285. void MachineInstr::print(raw_ostream &OS, const TargetMachine *TM,
  1286. bool SkipOpers) const {
  1287. // We can be a bit tidier if we know the TargetMachine and/or MachineFunction.
  1288. const MachineFunction *MF = 0;
  1289. const MachineRegisterInfo *MRI = 0;
  1290. if (const MachineBasicBlock *MBB = getParent()) {
  1291. MF = MBB->getParent();
  1292. if (!TM && MF)
  1293. TM = &MF->getTarget();
  1294. if (MF)
  1295. MRI = &MF->getRegInfo();
  1296. }
  1297. // Save a list of virtual registers.
  1298. SmallVector<unsigned, 8> VirtRegs;
  1299. // Print explicitly defined operands on the left of an assignment syntax.
  1300. unsigned StartOp = 0, e = getNumOperands();
  1301. for (; StartOp < e && getOperand(StartOp).isReg() &&
  1302. getOperand(StartOp).isDef() &&
  1303. !getOperand(StartOp).isImplicit();
  1304. ++StartOp) {
  1305. if (StartOp != 0) OS << ", ";
  1306. getOperand(StartOp).print(OS, TM);
  1307. unsigned Reg = getOperand(StartOp).getReg();
  1308. if (TargetRegisterInfo::isVirtualRegister(Reg))
  1309. VirtRegs.push_back(Reg);
  1310. }
  1311. if (StartOp != 0)
  1312. OS << " = ";
  1313. // Print the opcode name.
  1314. if (TM && TM->getInstrInfo())
  1315. OS << TM->getInstrInfo()->getName(getOpcode());
  1316. else
  1317. OS << "UNKNOWN";
  1318. if (SkipOpers)
  1319. return;
  1320. // Print the rest of the operands.
  1321. bool OmittedAnyCallClobbers = false;
  1322. bool FirstOp = true;
  1323. unsigned AsmDescOp = ~0u;
  1324. unsigned AsmOpCount = 0;
  1325. if (isInlineAsm() && e >= InlineAsm::MIOp_FirstOperand) {
  1326. // Print asm string.
  1327. OS << " ";
  1328. getOperand(InlineAsm::MIOp_AsmString).print(OS, TM);
  1329. // Print HasSideEffects, MayLoad, MayStore, IsAlignStack
  1330. unsigned ExtraInfo = getOperand(InlineAsm::MIOp_ExtraInfo).getImm();
  1331. if (ExtraInfo & InlineAsm::Extra_HasSideEffects)
  1332. OS << " [sideeffect]";
  1333. if (ExtraInfo & InlineAsm::Extra_MayLoad)
  1334. OS << " [mayload]";
  1335. if (ExtraInfo & InlineAsm::Extra_MayStore)
  1336. OS << " [maystore]";
  1337. if (ExtraInfo & InlineAsm::Extra_IsAlignStack)
  1338. OS << " [alignstack]";
  1339. if (getInlineAsmDialect() == InlineAsm::AD_ATT)
  1340. OS << " [attdialect]";
  1341. if (getInlineAsmDialect() == InlineAsm::AD_Intel)
  1342. OS << " [inteldialect]";
  1343. StartOp = AsmDescOp = InlineAsm::MIOp_FirstOperand;
  1344. FirstOp = false;
  1345. }
  1346. for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) {
  1347. const MachineOperand &MO = getOperand(i);
  1348. if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  1349. VirtRegs.push_back(MO.getReg());
  1350. // Omit call-clobbered registers which aren't used anywhere. This makes
  1351. // call instructions much less noisy on targets where calls clobber lots
  1352. // of registers. Don't rely on MO.isDead() because we may be called before
  1353. // LiveVariables is run, or we may be looking at a non-allocatable reg.
  1354. if (MF && isCall() &&
  1355. MO.isReg() && MO.isImplicit() && MO.isDef()) {
  1356. unsigned Reg = MO.getReg();
  1357. if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
  1358. const MachineRegisterInfo &MRI = MF->getRegInfo();
  1359. if (MRI.use_empty(Reg)) {
  1360. bool HasAliasLive = false;
  1361. for (MCRegAliasIterator AI(Reg, TM->getRegisterInfo(), true);
  1362. AI.isValid(); ++AI) {
  1363. unsigned AliasReg = *AI;
  1364. if (!MRI.use_empty(AliasReg)) {
  1365. HasAliasLive = true;
  1366. break;
  1367. }
  1368. }
  1369. if (!HasAliasLive) {
  1370. OmittedAnyCallClobbers = true;
  1371. continue;
  1372. }
  1373. }
  1374. }
  1375. }
  1376. if (FirstOp) FirstOp = false; else OS << ",";
  1377. OS << " ";
  1378. if (i < getDesc().NumOperands) {
  1379. const MCOperandInfo &MCOI = getDesc().OpInfo[i];
  1380. if (MCOI.isPredicate())
  1381. OS << "pred:";
  1382. if (MCOI.isOptionalDef())
  1383. OS << "opt:";
  1384. }
  1385. if (isDebugValue() && MO.isMetadata()) {
  1386. // Pretty print DBG_VALUE instructions.
  1387. const MDNode *MD = MO.getMetadata();
  1388. if (const MDString *MDS = dyn_cast<MDString>(MD->getOperand(2)))
  1389. OS << "!\"" << MDS->getString() << '\"';
  1390. else
  1391. MO.print(OS, TM);
  1392. } else if (TM && (isInsertSubreg() || isRegSequence()) && MO.isImm()) {
  1393. OS << TM->getRegisterInfo()->getSubRegIndexName(MO.getImm());
  1394. } else if (i == AsmDescOp && MO.isImm()) {
  1395. // Pretty print the inline asm operand descriptor.
  1396. OS << '$' << AsmOpCount++;
  1397. unsigned Flag = MO.getImm();
  1398. switch (InlineAsm::getKind(Flag)) {
  1399. case InlineAsm::Kind_RegUse: OS << ":[reguse"; break;
  1400. case InlineAsm::Kind_RegDef: OS << ":[regdef"; break;
  1401. case InlineAsm::Kind_RegDefEarlyClobber: OS << ":[regdef-ec"; break;
  1402. case InlineAsm::Kind_Clobber: OS << ":[clobber"; break;
  1403. case InlineAsm::Kind_Imm: OS << ":[imm"; break;
  1404. case InlineAsm::Kind_Mem: OS << ":[mem"; break;
  1405. default: OS << ":[??" << InlineAsm::getKind(Flag); break;
  1406. }
  1407. unsigned RCID = 0;
  1408. if (InlineAsm::hasRegClassConstraint(Flag, RCID)) {
  1409. if (TM)
  1410. OS << ':' << TM->getRegisterInfo()->getRegClass(RCID)->getName();
  1411. else
  1412. OS << ":RC" << RCID;
  1413. }
  1414. unsigned TiedTo = 0;
  1415. if (InlineAsm::isUseOperandTiedToDef(Flag, TiedTo))
  1416. OS << " tiedto:$" << TiedTo;
  1417. OS << ']';
  1418. // Compute the index of the next operand descriptor.
  1419. AsmDescOp += 1 + InlineAsm::getNumOperandRegisters(Flag);
  1420. } else
  1421. MO.print(OS, TM);
  1422. }
  1423. // Briefly indicate whether any call clobbers were omitted.
  1424. if (OmittedAnyCallClobbers) {
  1425. if (!FirstOp) OS << ",";
  1426. OS << " ...";
  1427. }
  1428. bool HaveSemi = false;
  1429. const unsigned PrintableFlags = FrameSetup;
  1430. if (Flags & PrintableFlags) {
  1431. if (!HaveSemi) OS << ";"; HaveSemi = true;
  1432. OS << " flags: ";
  1433. if (Flags & FrameSetup)
  1434. OS << "FrameSetup";
  1435. }
  1436. if (!memoperands_empty()) {
  1437. if (!HaveSemi) OS << ";"; HaveSemi = true;
  1438. OS << " mem:";
  1439. for (mmo_iterator i = memoperands_begin(), e = memoperands_end();
  1440. i != e; ++i) {
  1441. OS << **i;
  1442. if (llvm::next(i) != e)
  1443. OS << " ";
  1444. }
  1445. }
  1446. // Print the regclass of any virtual registers encountered.
  1447. if (MRI && !VirtRegs.empty()) {
  1448. if (!HaveSemi) OS << ";"; HaveSemi = true;
  1449. for (unsigned i = 0; i != VirtRegs.size(); ++i) {
  1450. const TargetRegisterClass *RC = MRI->getRegClass(VirtRegs[i]);
  1451. OS << " " << RC->getName() << ':' << PrintReg(VirtRegs[i]);
  1452. for (unsigned j = i+1; j != VirtRegs.size();) {
  1453. if (MRI->getRegClass(VirtRegs[j]) != RC) {
  1454. ++j;
  1455. continue;
  1456. }
  1457. if (VirtRegs[i] != VirtRegs[j])
  1458. OS << "," << PrintReg(VirtRegs[j]);
  1459. VirtRegs.erase(VirtRegs.begin()+j);
  1460. }
  1461. }
  1462. }
  1463. // Print debug location information.
  1464. if (isDebugValue() && getOperand(e - 1).isMetadata()) {
  1465. if (!HaveSemi) OS << ";"; HaveSemi = true;
  1466. DIVariable DV(getOperand(e - 1).getMetadata());
  1467. OS << " line no:" << DV.getLineNumber();
  1468. if (MDNode *InlinedAt = DV.getInlinedAt()) {
  1469. DebugLoc InlinedAtDL = DebugLoc::getFromDILocation(InlinedAt);
  1470. if (!InlinedAtDL.isUnknown()) {
  1471. OS << " inlined @[ ";
  1472. printDebugLoc(InlinedAtDL, MF, OS);
  1473. OS << " ]";
  1474. }
  1475. }
  1476. } else if (!debugLoc.isUnknown() && MF) {
  1477. if (!HaveSemi) OS << ";"; HaveSemi = true;
  1478. OS << " dbg:";
  1479. printDebugLoc(debugLoc, MF, OS);
  1480. }
  1481. OS << '\n';
  1482. }
  1483. bool MachineInstr::addRegisterKilled(unsigned IncomingReg,
  1484. const TargetRegisterInfo *RegInfo,
  1485. bool AddIfNotFound) {
  1486. bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
  1487. bool hasAliases = isPhysReg &&
  1488. MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
  1489. bool Found = false;
  1490. SmallVector<unsigned,4> DeadOps;
  1491. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1492. MachineOperand &MO = getOperand(i);
  1493. if (!MO.isReg() || !MO.isUse() || MO.isUndef())
  1494. continue;
  1495. unsigned Reg = MO.getReg();
  1496. if (!Reg)
  1497. continue;
  1498. if (Reg == IncomingReg) {
  1499. if (!Found) {
  1500. if (MO.isKill())
  1501. // The register is already marked kill.
  1502. return true;
  1503. if (isPhysReg && isRegTiedToDefOperand(i))
  1504. // Two-address uses of physregs must not be marked kill.
  1505. return true;
  1506. MO.setIsKill();
  1507. Found = true;
  1508. }
  1509. } else if (hasAliases && MO.isKill() &&
  1510. TargetRegisterInfo::isPhysicalRegister(Reg)) {
  1511. // A super-register kill already exists.
  1512. if (RegInfo->isSuperRegister(IncomingReg, Reg))
  1513. return true;
  1514. if (RegInfo->isSubRegister(IncomingReg, Reg))
  1515. DeadOps.push_back(i);
  1516. }
  1517. }
  1518. // Trim unneeded kill operands.
  1519. while (!DeadOps.empty()) {
  1520. unsigned OpIdx = DeadOps.back();
  1521. if (getOperand(OpIdx).isImplicit())
  1522. RemoveOperand(OpIdx);
  1523. else
  1524. getOperand(OpIdx).setIsKill(false);
  1525. DeadOps.pop_back();
  1526. }
  1527. // If not found, this means an alias of one of the operands is killed. Add a
  1528. // new implicit operand if required.
  1529. if (!Found && AddIfNotFound) {
  1530. addOperand(MachineOperand::CreateReg(IncomingReg,
  1531. false /*IsDef*/,
  1532. true /*IsImp*/,
  1533. true /*IsKill*/));
  1534. return true;
  1535. }
  1536. return Found;
  1537. }
  1538. void MachineInstr::clearRegisterKills(unsigned Reg,
  1539. const TargetRegisterInfo *RegInfo) {
  1540. if (!TargetRegisterInfo::isPhysicalRegister(Reg))
  1541. RegInfo = 0;
  1542. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1543. MachineOperand &MO = getOperand(i);
  1544. if (!MO.isReg() || !MO.isUse() || !MO.isKill())
  1545. continue;
  1546. unsigned OpReg = MO.getReg();
  1547. if (OpReg == Reg || (RegInfo && RegInfo->isSuperRegister(Reg, OpReg)))
  1548. MO.setIsKill(false);
  1549. }
  1550. }
  1551. bool MachineInstr::addRegisterDead(unsigned IncomingReg,
  1552. const TargetRegisterInfo *RegInfo,
  1553. bool AddIfNotFound) {
  1554. bool isPhysReg = TargetRegisterInfo::isPhysicalRegister(IncomingReg);
  1555. bool hasAliases = isPhysReg &&
  1556. MCRegAliasIterator(IncomingReg, RegInfo, false).isValid();
  1557. bool Found = false;
  1558. SmallVector<unsigned,4> DeadOps;
  1559. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1560. MachineOperand &MO = getOperand(i);
  1561. if (!MO.isReg() || !MO.isDef())
  1562. continue;
  1563. unsigned Reg = MO.getReg();
  1564. if (!Reg)
  1565. continue;
  1566. if (Reg == IncomingReg) {
  1567. MO.setIsDead();
  1568. Found = true;
  1569. } else if (hasAliases && MO.isDead() &&
  1570. TargetRegisterInfo::isPhysicalRegister(Reg)) {
  1571. // There exists a super-register that's marked dead.
  1572. if (RegInfo->isSuperRegister(IncomingReg, Reg))
  1573. return true;
  1574. if (RegInfo->isSubRegister(IncomingReg, Reg))
  1575. DeadOps.push_back(i);
  1576. }
  1577. }
  1578. // Trim unneeded dead operands.
  1579. while (!DeadOps.empty()) {
  1580. unsigned OpIdx = DeadOps.back();
  1581. if (getOperand(OpIdx).isImplicit())
  1582. RemoveOperand(OpIdx);
  1583. else
  1584. getOperand(OpIdx).setIsDead(false);
  1585. DeadOps.pop_back();
  1586. }
  1587. // If not found, this means an alias of one of the operands is dead. Add a
  1588. // new implicit operand if required.
  1589. if (Found || !AddIfNotFound)
  1590. return Found;
  1591. addOperand(MachineOperand::CreateReg(IncomingReg,
  1592. true /*IsDef*/,
  1593. true /*IsImp*/,
  1594. false /*IsKill*/,
  1595. true /*IsDead*/));
  1596. return true;
  1597. }
  1598. void MachineInstr::addRegisterDefined(unsigned IncomingReg,
  1599. const TargetRegisterInfo *RegInfo) {
  1600. if (TargetRegisterInfo::isPhysicalRegister(IncomingReg)) {
  1601. MachineOperand *MO = findRegisterDefOperand(IncomingReg, false, RegInfo);
  1602. if (MO)
  1603. return;
  1604. } else {
  1605. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1606. const MachineOperand &MO = getOperand(i);
  1607. if (MO.isReg() && MO.getReg() == IncomingReg && MO.isDef() &&
  1608. MO.getSubReg() == 0)
  1609. return;
  1610. }
  1611. }
  1612. addOperand(MachineOperand::CreateReg(IncomingReg,
  1613. true /*IsDef*/,
  1614. true /*IsImp*/));
  1615. }
  1616. void MachineInstr::setPhysRegsDeadExcept(ArrayRef<unsigned> UsedRegs,
  1617. const TargetRegisterInfo &TRI) {
  1618. bool HasRegMask = false;
  1619. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  1620. MachineOperand &MO = getOperand(i);
  1621. if (MO.isRegMask()) {
  1622. HasRegMask = true;
  1623. continue;
  1624. }
  1625. if (!MO.isReg() || !MO.isDef()) continue;
  1626. unsigned Reg = MO.getReg();
  1627. if (!TargetRegisterInfo::isPhysicalRegister(Reg)) continue;
  1628. bool Dead = true;
  1629. for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
  1630. I != E; ++I)
  1631. if (TRI.regsOverlap(*I, Reg)) {
  1632. Dead = false;
  1633. break;
  1634. }
  1635. // If there are no uses, including partial uses, the def is dead.
  1636. if (Dead) MO.setIsDead();
  1637. }
  1638. // This is a call with a register mask operand.
  1639. // Mask clobbers are always dead, so add defs for the non-dead defines.
  1640. if (HasRegMask)
  1641. for (ArrayRef<unsigned>::iterator I = UsedRegs.begin(), E = UsedRegs.end();
  1642. I != E; ++I)
  1643. addRegisterDefined(*I, &TRI);
  1644. }
  1645. unsigned
  1646. MachineInstrExpressionTrait::getHashValue(const MachineInstr* const &MI) {
  1647. // Build up a buffer of hash code components.
  1648. SmallVector<size_t, 8> HashComponents;
  1649. HashComponents.reserve(MI->getNumOperands() + 1);
  1650. HashComponents.push_back(MI->getOpcode());
  1651. for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
  1652. const MachineOperand &MO = MI->getOperand(i);
  1653. if (MO.isReg() && MO.isDef() &&
  1654. TargetRegisterInfo::isVirtualRegister(MO.getReg()))
  1655. continue; // Skip virtual register defs.
  1656. HashComponents.push_back(hash_value(MO));
  1657. }
  1658. return hash_combine_range(HashComponents.begin(), HashComponents.end());
  1659. }
  1660. void MachineInstr::emitError(StringRef Msg) const {
  1661. // Find the source location cookie.
  1662. unsigned LocCookie = 0;
  1663. const MDNode *LocMD = 0;
  1664. for (unsigned i = getNumOperands(); i != 0; --i) {
  1665. if (getOperand(i-1).isMetadata() &&
  1666. (LocMD = getOperand(i-1).getMetadata()) &&
  1667. LocMD->getNumOperands() != 0) {
  1668. if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
  1669. LocCookie = CI->getZExtValue();
  1670. break;
  1671. }
  1672. }
  1673. }
  1674. if (const MachineBasicBlock *MBB = getParent())
  1675. if (const MachineFunction *MF = MBB->getParent())
  1676. return MF->getMMI().getModule()->getContext().emitError(LocCookie, Msg);
  1677. report_fatal_error(Msg);
  1678. }