MachineInstr.cpp 69 KB

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