MachineInstr.cpp 64 KB

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