MachineRegisterInfo.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. //===-- lib/Codegen/MachineRegisterInfo.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. // Implementation of the MachineRegisterInfo class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/CodeGen/MachineRegisterInfo.h"
  14. #include "llvm/CodeGen/MachineInstrBuilder.h"
  15. #include "llvm/IR/Function.h"
  16. #include "llvm/Support/raw_os_ostream.h"
  17. #include "llvm/Target/TargetInstrInfo.h"
  18. #include "llvm/Target/TargetMachine.h"
  19. #include "llvm/Target/TargetSubtargetInfo.h"
  20. using namespace llvm;
  21. // Pin the vtable to this file.
  22. void MachineRegisterInfo::Delegate::anchor() {}
  23. MachineRegisterInfo::MachineRegisterInfo(const MachineFunction *MF)
  24. : MF(MF), TheDelegate(nullptr), IsSSA(true), TracksLiveness(true),
  25. TracksSubRegLiveness(false) {
  26. VRegInfo.reserve(256);
  27. RegAllocHints.reserve(256);
  28. UsedPhysRegMask.resize(getTargetRegisterInfo()->getNumRegs());
  29. // Create the physreg use/def lists.
  30. PhysRegUseDefLists.resize(getTargetRegisterInfo()->getNumRegs(), nullptr);
  31. }
  32. /// setRegClass - Set the register class of the specified virtual register.
  33. ///
  34. void
  35. MachineRegisterInfo::setRegClass(unsigned Reg, const TargetRegisterClass *RC) {
  36. assert(RC && RC->isAllocatable() && "Invalid RC for virtual register");
  37. VRegInfo[Reg].first = RC;
  38. }
  39. const TargetRegisterClass *
  40. MachineRegisterInfo::constrainRegClass(unsigned Reg,
  41. const TargetRegisterClass *RC,
  42. unsigned MinNumRegs) {
  43. const TargetRegisterClass *OldRC = getRegClass(Reg);
  44. if (OldRC == RC)
  45. return RC;
  46. const TargetRegisterClass *NewRC =
  47. getTargetRegisterInfo()->getCommonSubClass(OldRC, RC);
  48. if (!NewRC || NewRC == OldRC)
  49. return NewRC;
  50. if (NewRC->getNumRegs() < MinNumRegs)
  51. return nullptr;
  52. setRegClass(Reg, NewRC);
  53. return NewRC;
  54. }
  55. bool
  56. MachineRegisterInfo::recomputeRegClass(unsigned Reg) {
  57. const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
  58. const TargetRegisterClass *OldRC = getRegClass(Reg);
  59. const TargetRegisterClass *NewRC =
  60. getTargetRegisterInfo()->getLargestLegalSuperClass(OldRC, *MF);
  61. // Stop early if there is no room to grow.
  62. if (NewRC == OldRC)
  63. return false;
  64. // Accumulate constraints from all uses.
  65. for (MachineOperand &MO : reg_nodbg_operands(Reg)) {
  66. // Apply the effect of the given operand to NewRC.
  67. MachineInstr *MI = MO.getParent();
  68. unsigned OpNo = &MO - &MI->getOperand(0);
  69. NewRC = MI->getRegClassConstraintEffect(OpNo, NewRC, TII,
  70. getTargetRegisterInfo());
  71. if (!NewRC || NewRC == OldRC)
  72. return false;
  73. }
  74. setRegClass(Reg, NewRC);
  75. return true;
  76. }
  77. /// createVirtualRegister - Create and return a new virtual register in the
  78. /// function with the specified register class.
  79. ///
  80. unsigned
  81. MachineRegisterInfo::createVirtualRegister(const TargetRegisterClass *RegClass){
  82. assert(RegClass && "Cannot create register without RegClass!");
  83. assert(RegClass->isAllocatable() &&
  84. "Virtual register RegClass must be allocatable.");
  85. // New virtual register number.
  86. unsigned Reg = TargetRegisterInfo::index2VirtReg(getNumVirtRegs());
  87. VRegInfo.grow(Reg);
  88. VRegInfo[Reg].first = RegClass;
  89. RegAllocHints.grow(Reg);
  90. if (TheDelegate)
  91. TheDelegate->MRI_NoteNewVirtualRegister(Reg);
  92. return Reg;
  93. }
  94. /// clearVirtRegs - Remove all virtual registers (after physreg assignment).
  95. void MachineRegisterInfo::clearVirtRegs() {
  96. #ifndef NDEBUG
  97. for (unsigned i = 0, e = getNumVirtRegs(); i != e; ++i) {
  98. unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
  99. if (!VRegInfo[Reg].second)
  100. continue;
  101. verifyUseList(Reg);
  102. llvm_unreachable("Remaining virtual register operands");
  103. }
  104. #endif
  105. VRegInfo.clear();
  106. }
  107. void MachineRegisterInfo::verifyUseList(unsigned Reg) const {
  108. #ifndef NDEBUG
  109. bool Valid = true;
  110. for (MachineOperand &M : reg_operands(Reg)) {
  111. MachineOperand *MO = &M;
  112. MachineInstr *MI = MO->getParent();
  113. if (!MI) {
  114. errs() << PrintReg(Reg, getTargetRegisterInfo())
  115. << " use list MachineOperand " << MO
  116. << " has no parent instruction.\n";
  117. Valid = false;
  118. continue;
  119. }
  120. MachineOperand *MO0 = &MI->getOperand(0);
  121. unsigned NumOps = MI->getNumOperands();
  122. if (!(MO >= MO0 && MO < MO0+NumOps)) {
  123. errs() << PrintReg(Reg, getTargetRegisterInfo())
  124. << " use list MachineOperand " << MO
  125. << " doesn't belong to parent MI: " << *MI;
  126. Valid = false;
  127. }
  128. if (!MO->isReg()) {
  129. errs() << PrintReg(Reg, getTargetRegisterInfo())
  130. << " MachineOperand " << MO << ": " << *MO
  131. << " is not a register\n";
  132. Valid = false;
  133. }
  134. if (MO->getReg() != Reg) {
  135. errs() << PrintReg(Reg, getTargetRegisterInfo())
  136. << " use-list MachineOperand " << MO << ": "
  137. << *MO << " is the wrong register\n";
  138. Valid = false;
  139. }
  140. }
  141. assert(Valid && "Invalid use list");
  142. #endif
  143. }
  144. void MachineRegisterInfo::verifyUseLists() const {
  145. #ifndef NDEBUG
  146. for (unsigned i = 0, e = getNumVirtRegs(); i != e; ++i)
  147. verifyUseList(TargetRegisterInfo::index2VirtReg(i));
  148. for (unsigned i = 1, e = getTargetRegisterInfo()->getNumRegs(); i != e; ++i)
  149. verifyUseList(i);
  150. #endif
  151. }
  152. /// Add MO to the linked list of operands for its register.
  153. void MachineRegisterInfo::addRegOperandToUseList(MachineOperand *MO) {
  154. assert(!MO->isOnRegUseList() && "Already on list");
  155. MachineOperand *&HeadRef = getRegUseDefListHead(MO->getReg());
  156. MachineOperand *const Head = HeadRef;
  157. // Head points to the first list element.
  158. // Next is NULL on the last list element.
  159. // Prev pointers are circular, so Head->Prev == Last.
  160. // Head is NULL for an empty list.
  161. if (!Head) {
  162. MO->Contents.Reg.Prev = MO;
  163. MO->Contents.Reg.Next = nullptr;
  164. HeadRef = MO;
  165. return;
  166. }
  167. assert(MO->getReg() == Head->getReg() && "Different regs on the same list!");
  168. // Insert MO between Last and Head in the circular Prev chain.
  169. MachineOperand *Last = Head->Contents.Reg.Prev;
  170. assert(Last && "Inconsistent use list");
  171. assert(MO->getReg() == Last->getReg() && "Different regs on the same list!");
  172. Head->Contents.Reg.Prev = MO;
  173. MO->Contents.Reg.Prev = Last;
  174. // Def operands always precede uses. This allows def_iterator to stop early.
  175. // Insert def operands at the front, and use operands at the back.
  176. if (MO->isDef()) {
  177. // Insert def at the front.
  178. MO->Contents.Reg.Next = Head;
  179. HeadRef = MO;
  180. } else {
  181. // Insert use at the end.
  182. MO->Contents.Reg.Next = nullptr;
  183. Last->Contents.Reg.Next = MO;
  184. }
  185. }
  186. /// Remove MO from its use-def list.
  187. void MachineRegisterInfo::removeRegOperandFromUseList(MachineOperand *MO) {
  188. assert(MO->isOnRegUseList() && "Operand not on use list");
  189. MachineOperand *&HeadRef = getRegUseDefListHead(MO->getReg());
  190. MachineOperand *const Head = HeadRef;
  191. assert(Head && "List already empty");
  192. // Unlink this from the doubly linked list of operands.
  193. MachineOperand *Next = MO->Contents.Reg.Next;
  194. MachineOperand *Prev = MO->Contents.Reg.Prev;
  195. // Prev links are circular, next link is NULL instead of looping back to Head.
  196. if (MO == Head)
  197. HeadRef = Next;
  198. else
  199. Prev->Contents.Reg.Next = Next;
  200. (Next ? Next : Head)->Contents.Reg.Prev = Prev;
  201. MO->Contents.Reg.Prev = nullptr;
  202. MO->Contents.Reg.Next = nullptr;
  203. }
  204. /// Move NumOps operands from Src to Dst, updating use-def lists as needed.
  205. ///
  206. /// The Dst range is assumed to be uninitialized memory. (Or it may contain
  207. /// operands that won't be destroyed, which is OK because the MO destructor is
  208. /// trivial anyway).
  209. ///
  210. /// The Src and Dst ranges may overlap.
  211. void MachineRegisterInfo::moveOperands(MachineOperand *Dst,
  212. MachineOperand *Src,
  213. unsigned NumOps) {
  214. assert(Src != Dst && NumOps && "Noop moveOperands");
  215. // Copy backwards if Dst is within the Src range.
  216. int Stride = 1;
  217. if (Dst >= Src && Dst < Src + NumOps) {
  218. Stride = -1;
  219. Dst += NumOps - 1;
  220. Src += NumOps - 1;
  221. }
  222. // Copy one operand at a time.
  223. do {
  224. new (Dst) MachineOperand(*Src);
  225. // Dst takes Src's place in the use-def chain.
  226. if (Src->isReg()) {
  227. MachineOperand *&Head = getRegUseDefListHead(Src->getReg());
  228. MachineOperand *Prev = Src->Contents.Reg.Prev;
  229. MachineOperand *Next = Src->Contents.Reg.Next;
  230. assert(Head && "List empty, but operand is chained");
  231. assert(Prev && "Operand was not on use-def list");
  232. // Prev links are circular, next link is NULL instead of looping back to
  233. // Head.
  234. if (Src == Head)
  235. Head = Dst;
  236. else
  237. Prev->Contents.Reg.Next = Dst;
  238. // Update Prev pointer. This also works when Src was pointing to itself
  239. // in a 1-element list. In that case Head == Dst.
  240. (Next ? Next : Head)->Contents.Reg.Prev = Dst;
  241. }
  242. Dst += Stride;
  243. Src += Stride;
  244. } while (--NumOps);
  245. }
  246. /// replaceRegWith - Replace all instances of FromReg with ToReg in the
  247. /// machine function. This is like llvm-level X->replaceAllUsesWith(Y),
  248. /// except that it also changes any definitions of the register as well.
  249. /// If ToReg is a physical register we apply the sub register to obtain the
  250. /// final/proper physical register.
  251. void MachineRegisterInfo::replaceRegWith(unsigned FromReg, unsigned ToReg) {
  252. assert(FromReg != ToReg && "Cannot replace a reg with itself");
  253. const TargetRegisterInfo *TRI = getTargetRegisterInfo();
  254. // TODO: This could be more efficient by bulk changing the operands.
  255. for (reg_iterator I = reg_begin(FromReg), E = reg_end(); I != E; ) {
  256. MachineOperand &O = *I;
  257. ++I;
  258. if (TargetRegisterInfo::isPhysicalRegister(ToReg)) {
  259. O.substPhysReg(ToReg, *TRI);
  260. } else {
  261. O.setReg(ToReg);
  262. }
  263. }
  264. }
  265. /// getVRegDef - Return the machine instr that defines the specified virtual
  266. /// register or null if none is found. This assumes that the code is in SSA
  267. /// form, so there should only be one definition.
  268. MachineInstr *MachineRegisterInfo::getVRegDef(unsigned Reg) const {
  269. // Since we are in SSA form, we can use the first definition.
  270. def_instr_iterator I = def_instr_begin(Reg);
  271. assert((I.atEnd() || std::next(I) == def_instr_end()) &&
  272. "getVRegDef assumes a single definition or no definition");
  273. return !I.atEnd() ? &*I : nullptr;
  274. }
  275. /// getUniqueVRegDef - Return the unique machine instr that defines the
  276. /// specified virtual register or null if none is found. If there are
  277. /// multiple definitions or no definition, return null.
  278. MachineInstr *MachineRegisterInfo::getUniqueVRegDef(unsigned Reg) const {
  279. if (def_empty(Reg)) return nullptr;
  280. def_instr_iterator I = def_instr_begin(Reg);
  281. if (std::next(I) != def_instr_end())
  282. return nullptr;
  283. return &*I;
  284. }
  285. bool MachineRegisterInfo::hasOneNonDBGUse(unsigned RegNo) const {
  286. use_nodbg_iterator UI = use_nodbg_begin(RegNo);
  287. if (UI == use_nodbg_end())
  288. return false;
  289. return ++UI == use_nodbg_end();
  290. }
  291. /// clearKillFlags - Iterate over all the uses of the given register and
  292. /// clear the kill flag from the MachineOperand. This function is used by
  293. /// optimization passes which extend register lifetimes and need only
  294. /// preserve conservative kill flag information.
  295. void MachineRegisterInfo::clearKillFlags(unsigned Reg) const {
  296. for (MachineOperand &MO : use_operands(Reg))
  297. MO.setIsKill(false);
  298. }
  299. bool MachineRegisterInfo::isLiveIn(unsigned Reg) const {
  300. for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I)
  301. if (I->first == Reg || I->second == Reg)
  302. return true;
  303. return false;
  304. }
  305. /// getLiveInPhysReg - If VReg is a live-in virtual register, return the
  306. /// corresponding live-in physical register.
  307. unsigned MachineRegisterInfo::getLiveInPhysReg(unsigned VReg) const {
  308. for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I)
  309. if (I->second == VReg)
  310. return I->first;
  311. return 0;
  312. }
  313. /// getLiveInVirtReg - If PReg is a live-in physical register, return the
  314. /// corresponding live-in physical register.
  315. unsigned MachineRegisterInfo::getLiveInVirtReg(unsigned PReg) const {
  316. for (livein_iterator I = livein_begin(), E = livein_end(); I != E; ++I)
  317. if (I->first == PReg)
  318. return I->second;
  319. return 0;
  320. }
  321. /// EmitLiveInCopies - Emit copies to initialize livein virtual registers
  322. /// into the given entry block.
  323. void
  324. MachineRegisterInfo::EmitLiveInCopies(MachineBasicBlock *EntryMBB,
  325. const TargetRegisterInfo &TRI,
  326. const TargetInstrInfo &TII) {
  327. // Emit the copies into the top of the block.
  328. for (unsigned i = 0, e = LiveIns.size(); i != e; ++i)
  329. if (LiveIns[i].second) {
  330. if (use_empty(LiveIns[i].second)) {
  331. // The livein has no uses. Drop it.
  332. //
  333. // It would be preferable to have isel avoid creating live-in
  334. // records for unused arguments in the first place, but it's
  335. // complicated by the debug info code for arguments.
  336. LiveIns.erase(LiveIns.begin() + i);
  337. --i; --e;
  338. } else {
  339. // Emit a copy.
  340. BuildMI(*EntryMBB, EntryMBB->begin(), DebugLoc(),
  341. TII.get(TargetOpcode::COPY), LiveIns[i].second)
  342. .addReg(LiveIns[i].first);
  343. // Add the register to the entry block live-in set.
  344. EntryMBB->addLiveIn(LiveIns[i].first);
  345. }
  346. } else {
  347. // Add the register to the entry block live-in set.
  348. EntryMBB->addLiveIn(LiveIns[i].first);
  349. }
  350. }
  351. unsigned MachineRegisterInfo::getMaxLaneMaskForVReg(unsigned Reg) const
  352. {
  353. // Lane masks are only defined for vregs.
  354. assert(TargetRegisterInfo::isVirtualRegister(Reg));
  355. const TargetRegisterClass &TRC = *getRegClass(Reg);
  356. return TRC.getLaneMask();
  357. }
  358. #ifndef NDEBUG
  359. void MachineRegisterInfo::dumpUses(unsigned Reg) const {
  360. for (MachineInstr &I : use_instructions(Reg))
  361. I.dump();
  362. }
  363. #endif
  364. void MachineRegisterInfo::freezeReservedRegs(const MachineFunction &MF) {
  365. ReservedRegs = getTargetRegisterInfo()->getReservedRegs(MF);
  366. assert(ReservedRegs.size() == getTargetRegisterInfo()->getNumRegs() &&
  367. "Invalid ReservedRegs vector from target");
  368. }
  369. bool MachineRegisterInfo::isConstantPhysReg(unsigned PhysReg,
  370. const MachineFunction &MF) const {
  371. assert(TargetRegisterInfo::isPhysicalRegister(PhysReg));
  372. // Check if any overlapping register is modified, or allocatable so it may be
  373. // used later.
  374. for (MCRegAliasIterator AI(PhysReg, getTargetRegisterInfo(), true);
  375. AI.isValid(); ++AI)
  376. if (!def_empty(*AI) || isAllocatable(*AI))
  377. return false;
  378. return true;
  379. }
  380. /// markUsesInDebugValueAsUndef - Mark every DBG_VALUE referencing the
  381. /// specified register as undefined which causes the DBG_VALUE to be
  382. /// deleted during LiveDebugVariables analysis.
  383. void MachineRegisterInfo::markUsesInDebugValueAsUndef(unsigned Reg) const {
  384. // Mark any DBG_VALUE that uses Reg as undef (but don't delete it.)
  385. MachineRegisterInfo::use_instr_iterator nextI;
  386. for (use_instr_iterator I = use_instr_begin(Reg), E = use_instr_end();
  387. I != E; I = nextI) {
  388. nextI = std::next(I); // I is invalidated by the setReg
  389. MachineInstr *UseMI = &*I;
  390. if (UseMI->isDebugValue())
  391. UseMI->getOperand(0).setReg(0U);
  392. }
  393. }
  394. static const Function *getCalledFunction(const MachineInstr &MI) {
  395. for (const MachineOperand &MO : MI.operands()) {
  396. if (!MO.isGlobal())
  397. continue;
  398. const Function *Func = dyn_cast<Function>(MO.getGlobal());
  399. if (Func != nullptr)
  400. return Func;
  401. }
  402. return nullptr;
  403. }
  404. static bool isNoReturnDef(const MachineOperand &MO) {
  405. // Anything which is not a noreturn function is a real def.
  406. const MachineInstr &MI = *MO.getParent();
  407. if (!MI.isCall())
  408. return false;
  409. const MachineBasicBlock &MBB = *MI.getParent();
  410. if (!MBB.succ_empty())
  411. return false;
  412. const MachineFunction &MF = *MBB.getParent();
  413. // We need to keep correct unwind information even if the function will
  414. // not return, since the runtime may need it.
  415. if (MF.getFunction()->hasFnAttribute(Attribute::UWTable))
  416. return false;
  417. const Function *Called = getCalledFunction(MI);
  418. if (Called == nullptr || !Called->hasFnAttribute(Attribute::NoReturn)
  419. || !Called->hasFnAttribute(Attribute::NoUnwind))
  420. return false;
  421. return true;
  422. }
  423. bool MachineRegisterInfo::isPhysRegModified(unsigned PhysReg) const {
  424. if (UsedPhysRegMask.test(PhysReg))
  425. return true;
  426. const TargetRegisterInfo *TRI = getTargetRegisterInfo();
  427. for (MCRegAliasIterator AI(PhysReg, TRI, true); AI.isValid(); ++AI) {
  428. for (const MachineOperand &MO : make_range(def_begin(*AI), def_end())) {
  429. if (isNoReturnDef(MO))
  430. continue;
  431. return true;
  432. }
  433. }
  434. return false;
  435. }