RegisterBankInfo.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. //===- llvm/CodeGen/GlobalISel/RegisterBankInfo.cpp --------------*- C++ -*-==//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. /// \file
  9. /// This file implements the RegisterBankInfo class.
  10. //===----------------------------------------------------------------------===//
  11. #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
  12. #include "llvm/ADT/SmallString.h"
  13. #include "llvm/ADT/SmallVector.h"
  14. #include "llvm/ADT/Statistic.h"
  15. #include "llvm/ADT/iterator_range.h"
  16. #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
  17. #include "llvm/CodeGen/MachineBasicBlock.h"
  18. #include "llvm/CodeGen/MachineFunction.h"
  19. #include "llvm/CodeGen/MachineRegisterInfo.h"
  20. #include "llvm/CodeGen/TargetOpcodes.h"
  21. #include "llvm/CodeGen/TargetRegisterInfo.h"
  22. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  23. #include "llvm/Config/llvm-config.h"
  24. #include "llvm/IR/Type.h"
  25. #include "llvm/Support/Debug.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include <algorithm> // For std::max.
  28. #define DEBUG_TYPE "registerbankinfo"
  29. using namespace llvm;
  30. STATISTIC(NumPartialMappingsCreated,
  31. "Number of partial mappings dynamically created");
  32. STATISTIC(NumPartialMappingsAccessed,
  33. "Number of partial mappings dynamically accessed");
  34. STATISTIC(NumValueMappingsCreated,
  35. "Number of value mappings dynamically created");
  36. STATISTIC(NumValueMappingsAccessed,
  37. "Number of value mappings dynamically accessed");
  38. STATISTIC(NumOperandsMappingsCreated,
  39. "Number of operands mappings dynamically created");
  40. STATISTIC(NumOperandsMappingsAccessed,
  41. "Number of operands mappings dynamically accessed");
  42. STATISTIC(NumInstructionMappingsCreated,
  43. "Number of instruction mappings dynamically created");
  44. STATISTIC(NumInstructionMappingsAccessed,
  45. "Number of instruction mappings dynamically accessed");
  46. const unsigned RegisterBankInfo::DefaultMappingID = UINT_MAX;
  47. const unsigned RegisterBankInfo::InvalidMappingID = UINT_MAX - 1;
  48. //------------------------------------------------------------------------------
  49. // RegisterBankInfo implementation.
  50. //------------------------------------------------------------------------------
  51. RegisterBankInfo::RegisterBankInfo(RegisterBank **RegBanks,
  52. unsigned NumRegBanks)
  53. : RegBanks(RegBanks), NumRegBanks(NumRegBanks) {
  54. #ifndef NDEBUG
  55. for (unsigned Idx = 0, End = getNumRegBanks(); Idx != End; ++Idx) {
  56. assert(RegBanks[Idx] != nullptr && "Invalid RegisterBank");
  57. assert(RegBanks[Idx]->isValid() && "RegisterBank should be valid");
  58. }
  59. #endif // NDEBUG
  60. }
  61. bool RegisterBankInfo::verify(const TargetRegisterInfo &TRI) const {
  62. #ifndef NDEBUG
  63. for (unsigned Idx = 0, End = getNumRegBanks(); Idx != End; ++Idx) {
  64. const RegisterBank &RegBank = getRegBank(Idx);
  65. assert(Idx == RegBank.getID() &&
  66. "ID does not match the index in the array");
  67. LLVM_DEBUG(dbgs() << "Verify " << RegBank << '\n');
  68. assert(RegBank.verify(TRI) && "RegBank is invalid");
  69. }
  70. #endif // NDEBUG
  71. return true;
  72. }
  73. const RegisterBank *
  74. RegisterBankInfo::getRegBank(Register Reg, const MachineRegisterInfo &MRI,
  75. const TargetRegisterInfo &TRI) const {
  76. if (Register::isPhysicalRegister(Reg)) {
  77. // FIXME: This was probably a copy to a virtual register that does have a
  78. // type we could use.
  79. return &getRegBankFromRegClass(getMinimalPhysRegClass(Reg, TRI), LLT());
  80. }
  81. assert(Reg && "NoRegister does not have a register bank");
  82. const RegClassOrRegBank &RegClassOrBank = MRI.getRegClassOrRegBank(Reg);
  83. if (auto *RB = RegClassOrBank.dyn_cast<const RegisterBank *>())
  84. return RB;
  85. if (auto *RC = RegClassOrBank.dyn_cast<const TargetRegisterClass *>())
  86. return &getRegBankFromRegClass(*RC, MRI.getType(Reg));
  87. return nullptr;
  88. }
  89. const TargetRegisterClass &
  90. RegisterBankInfo::getMinimalPhysRegClass(Register Reg,
  91. const TargetRegisterInfo &TRI) const {
  92. assert(Register::isPhysicalRegister(Reg) && "Reg must be a physreg");
  93. const auto &RegRCIt = PhysRegMinimalRCs.find(Reg);
  94. if (RegRCIt != PhysRegMinimalRCs.end())
  95. return *RegRCIt->second;
  96. const TargetRegisterClass *PhysRC = TRI.getMinimalPhysRegClass(Reg);
  97. PhysRegMinimalRCs[Reg] = PhysRC;
  98. return *PhysRC;
  99. }
  100. const RegisterBank *RegisterBankInfo::getRegBankFromConstraints(
  101. const MachineInstr &MI, unsigned OpIdx, const TargetInstrInfo &TII,
  102. const MachineRegisterInfo &MRI) const {
  103. const TargetRegisterInfo *TRI = MRI.getTargetRegisterInfo();
  104. // The mapping of the registers may be available via the
  105. // register class constraints.
  106. const TargetRegisterClass *RC = MI.getRegClassConstraint(OpIdx, &TII, TRI);
  107. if (!RC)
  108. return nullptr;
  109. Register Reg = MI.getOperand(OpIdx).getReg();
  110. const RegisterBank &RegBank = getRegBankFromRegClass(*RC, MRI.getType(Reg));
  111. // Check that the target properly implemented getRegBankFromRegClass.
  112. assert(RegBank.covers(*RC) &&
  113. "The mapping of the register bank does not make sense");
  114. return &RegBank;
  115. }
  116. const TargetRegisterClass *RegisterBankInfo::constrainGenericRegister(
  117. Register Reg, const TargetRegisterClass &RC, MachineRegisterInfo &MRI) {
  118. // If the register already has a class, fallback to MRI::constrainRegClass.
  119. auto &RegClassOrBank = MRI.getRegClassOrRegBank(Reg);
  120. if (RegClassOrBank.is<const TargetRegisterClass *>())
  121. return MRI.constrainRegClass(Reg, &RC);
  122. const RegisterBank *RB = RegClassOrBank.get<const RegisterBank *>();
  123. // Otherwise, all we can do is ensure the bank covers the class, and set it.
  124. if (RB && !RB->covers(RC))
  125. return nullptr;
  126. // If nothing was set or the class is simply compatible, set it.
  127. MRI.setRegClass(Reg, &RC);
  128. return &RC;
  129. }
  130. /// Check whether or not \p MI should be treated like a copy
  131. /// for the mappings.
  132. /// Copy like instruction are special for mapping because
  133. /// they don't have actual register constraints. Moreover,
  134. /// they sometimes have register classes assigned and we can
  135. /// just use that instead of failing to provide a generic mapping.
  136. static bool isCopyLike(const MachineInstr &MI) {
  137. return MI.isCopy() || MI.isPHI() ||
  138. MI.getOpcode() == TargetOpcode::REG_SEQUENCE;
  139. }
  140. const RegisterBankInfo::InstructionMapping &
  141. RegisterBankInfo::getInstrMappingImpl(const MachineInstr &MI) const {
  142. // For copies we want to walk over the operands and try to find one
  143. // that has a register bank since the instruction itself will not get
  144. // us any constraint.
  145. bool IsCopyLike = isCopyLike(MI);
  146. // For copy like instruction, only the mapping of the definition
  147. // is important. The rest is not constrained.
  148. unsigned NumOperandsForMapping = IsCopyLike ? 1 : MI.getNumOperands();
  149. const MachineFunction &MF = *MI.getMF();
  150. const TargetSubtargetInfo &STI = MF.getSubtarget();
  151. const TargetRegisterInfo &TRI = *STI.getRegisterInfo();
  152. const MachineRegisterInfo &MRI = MF.getRegInfo();
  153. // We may need to query the instruction encoding to guess the mapping.
  154. const TargetInstrInfo &TII = *STI.getInstrInfo();
  155. // Before doing anything complicated check if the mapping is not
  156. // directly available.
  157. bool CompleteMapping = true;
  158. SmallVector<const ValueMapping *, 8> OperandsMapping(NumOperandsForMapping);
  159. for (unsigned OpIdx = 0, EndIdx = MI.getNumOperands(); OpIdx != EndIdx;
  160. ++OpIdx) {
  161. const MachineOperand &MO = MI.getOperand(OpIdx);
  162. if (!MO.isReg())
  163. continue;
  164. Register Reg = MO.getReg();
  165. if (!Reg)
  166. continue;
  167. // The register bank of Reg is just a side effect of the current
  168. // excution and in particular, there is no reason to believe this
  169. // is the best default mapping for the current instruction. Keep
  170. // it as an alternative register bank if we cannot figure out
  171. // something.
  172. const RegisterBank *AltRegBank = getRegBank(Reg, MRI, TRI);
  173. // For copy-like instruction, we want to reuse the register bank
  174. // that is already set on Reg, if any, since those instructions do
  175. // not have any constraints.
  176. const RegisterBank *CurRegBank = IsCopyLike ? AltRegBank : nullptr;
  177. if (!CurRegBank) {
  178. // If this is a target specific instruction, we can deduce
  179. // the register bank from the encoding constraints.
  180. CurRegBank = getRegBankFromConstraints(MI, OpIdx, TII, MRI);
  181. if (!CurRegBank) {
  182. // All our attempts failed, give up.
  183. CompleteMapping = false;
  184. if (!IsCopyLike)
  185. // MI does not carry enough information to guess the mapping.
  186. return getInvalidInstructionMapping();
  187. continue;
  188. }
  189. }
  190. unsigned Size = getSizeInBits(Reg, MRI, TRI);
  191. const ValueMapping *ValMapping = &getValueMapping(0, Size, *CurRegBank);
  192. if (IsCopyLike) {
  193. if (!OperandsMapping[0]) {
  194. if (MI.isRegSequence()) {
  195. // For reg_sequence, the result size does not match the input.
  196. unsigned ResultSize = getSizeInBits(MI.getOperand(0).getReg(),
  197. MRI, TRI);
  198. OperandsMapping[0] = &getValueMapping(0, ResultSize, *CurRegBank);
  199. } else {
  200. OperandsMapping[0] = ValMapping;
  201. }
  202. }
  203. // The default handling assumes any register bank can be copied to any
  204. // other. If this isn't the case, the target should specially deal with
  205. // reg_sequence/phi. There may also be unsatisfiable copies.
  206. for (; OpIdx != EndIdx; ++OpIdx) {
  207. const MachineOperand &MO = MI.getOperand(OpIdx);
  208. if (!MO.isReg())
  209. continue;
  210. Register Reg = MO.getReg();
  211. if (!Reg)
  212. continue;
  213. const RegisterBank *AltRegBank = getRegBank(Reg, MRI, TRI);
  214. if (AltRegBank &&
  215. cannotCopy(*CurRegBank, *AltRegBank, getSizeInBits(Reg, MRI, TRI)))
  216. return getInvalidInstructionMapping();
  217. }
  218. CompleteMapping = true;
  219. break;
  220. }
  221. OperandsMapping[OpIdx] = ValMapping;
  222. }
  223. if (IsCopyLike && !CompleteMapping) {
  224. // No way to deduce the type from what we have.
  225. return getInvalidInstructionMapping();
  226. }
  227. assert(CompleteMapping && "Setting an uncomplete mapping");
  228. return getInstructionMapping(
  229. DefaultMappingID, /*Cost*/ 1,
  230. /*OperandsMapping*/ getOperandsMapping(OperandsMapping),
  231. NumOperandsForMapping);
  232. }
  233. /// Hashing function for PartialMapping.
  234. static hash_code hashPartialMapping(unsigned StartIdx, unsigned Length,
  235. const RegisterBank *RegBank) {
  236. return hash_combine(StartIdx, Length, RegBank ? RegBank->getID() : 0);
  237. }
  238. /// Overloaded version of hash_value for a PartialMapping.
  239. hash_code
  240. llvm::hash_value(const RegisterBankInfo::PartialMapping &PartMapping) {
  241. return hashPartialMapping(PartMapping.StartIdx, PartMapping.Length,
  242. PartMapping.RegBank);
  243. }
  244. const RegisterBankInfo::PartialMapping &
  245. RegisterBankInfo::getPartialMapping(unsigned StartIdx, unsigned Length,
  246. const RegisterBank &RegBank) const {
  247. ++NumPartialMappingsAccessed;
  248. hash_code Hash = hashPartialMapping(StartIdx, Length, &RegBank);
  249. const auto &It = MapOfPartialMappings.find(Hash);
  250. if (It != MapOfPartialMappings.end())
  251. return *It->second;
  252. ++NumPartialMappingsCreated;
  253. auto &PartMapping = MapOfPartialMappings[Hash];
  254. PartMapping = std::make_unique<PartialMapping>(StartIdx, Length, RegBank);
  255. return *PartMapping;
  256. }
  257. const RegisterBankInfo::ValueMapping &
  258. RegisterBankInfo::getValueMapping(unsigned StartIdx, unsigned Length,
  259. const RegisterBank &RegBank) const {
  260. return getValueMapping(&getPartialMapping(StartIdx, Length, RegBank), 1);
  261. }
  262. static hash_code
  263. hashValueMapping(const RegisterBankInfo::PartialMapping *BreakDown,
  264. unsigned NumBreakDowns) {
  265. if (LLVM_LIKELY(NumBreakDowns == 1))
  266. return hash_value(*BreakDown);
  267. SmallVector<size_t, 8> Hashes(NumBreakDowns);
  268. for (unsigned Idx = 0; Idx != NumBreakDowns; ++Idx)
  269. Hashes.push_back(hash_value(BreakDown[Idx]));
  270. return hash_combine_range(Hashes.begin(), Hashes.end());
  271. }
  272. const RegisterBankInfo::ValueMapping &
  273. RegisterBankInfo::getValueMapping(const PartialMapping *BreakDown,
  274. unsigned NumBreakDowns) const {
  275. ++NumValueMappingsAccessed;
  276. hash_code Hash = hashValueMapping(BreakDown, NumBreakDowns);
  277. const auto &It = MapOfValueMappings.find(Hash);
  278. if (It != MapOfValueMappings.end())
  279. return *It->second;
  280. ++NumValueMappingsCreated;
  281. auto &ValMapping = MapOfValueMappings[Hash];
  282. ValMapping = std::make_unique<ValueMapping>(BreakDown, NumBreakDowns);
  283. return *ValMapping;
  284. }
  285. template <typename Iterator>
  286. const RegisterBankInfo::ValueMapping *
  287. RegisterBankInfo::getOperandsMapping(Iterator Begin, Iterator End) const {
  288. ++NumOperandsMappingsAccessed;
  289. // The addresses of the value mapping are unique.
  290. // Therefore, we can use them directly to hash the operand mapping.
  291. hash_code Hash = hash_combine_range(Begin, End);
  292. auto &Res = MapOfOperandsMappings[Hash];
  293. if (Res)
  294. return Res.get();
  295. ++NumOperandsMappingsCreated;
  296. // Create the array of ValueMapping.
  297. // Note: this array will not hash to this instance of operands
  298. // mapping, because we use the pointer of the ValueMapping
  299. // to hash and we expect them to uniquely identify an instance
  300. // of value mapping.
  301. Res = std::make_unique<ValueMapping[]>(std::distance(Begin, End));
  302. unsigned Idx = 0;
  303. for (Iterator It = Begin; It != End; ++It, ++Idx) {
  304. const ValueMapping *ValMap = *It;
  305. if (!ValMap)
  306. continue;
  307. Res[Idx] = *ValMap;
  308. }
  309. return Res.get();
  310. }
  311. const RegisterBankInfo::ValueMapping *RegisterBankInfo::getOperandsMapping(
  312. const SmallVectorImpl<const RegisterBankInfo::ValueMapping *> &OpdsMapping)
  313. const {
  314. return getOperandsMapping(OpdsMapping.begin(), OpdsMapping.end());
  315. }
  316. const RegisterBankInfo::ValueMapping *RegisterBankInfo::getOperandsMapping(
  317. std::initializer_list<const RegisterBankInfo::ValueMapping *> OpdsMapping)
  318. const {
  319. return getOperandsMapping(OpdsMapping.begin(), OpdsMapping.end());
  320. }
  321. static hash_code
  322. hashInstructionMapping(unsigned ID, unsigned Cost,
  323. const RegisterBankInfo::ValueMapping *OperandsMapping,
  324. unsigned NumOperands) {
  325. return hash_combine(ID, Cost, OperandsMapping, NumOperands);
  326. }
  327. const RegisterBankInfo::InstructionMapping &
  328. RegisterBankInfo::getInstructionMappingImpl(
  329. bool IsInvalid, unsigned ID, unsigned Cost,
  330. const RegisterBankInfo::ValueMapping *OperandsMapping,
  331. unsigned NumOperands) const {
  332. assert(((IsInvalid && ID == InvalidMappingID && Cost == 0 &&
  333. OperandsMapping == nullptr && NumOperands == 0) ||
  334. !IsInvalid) &&
  335. "Mismatch argument for invalid input");
  336. ++NumInstructionMappingsAccessed;
  337. hash_code Hash =
  338. hashInstructionMapping(ID, Cost, OperandsMapping, NumOperands);
  339. const auto &It = MapOfInstructionMappings.find(Hash);
  340. if (It != MapOfInstructionMappings.end())
  341. return *It->second;
  342. ++NumInstructionMappingsCreated;
  343. auto &InstrMapping = MapOfInstructionMappings[Hash];
  344. InstrMapping = std::make_unique<InstructionMapping>(
  345. ID, Cost, OperandsMapping, NumOperands);
  346. return *InstrMapping;
  347. }
  348. const RegisterBankInfo::InstructionMapping &
  349. RegisterBankInfo::getInstrMapping(const MachineInstr &MI) const {
  350. const RegisterBankInfo::InstructionMapping &Mapping = getInstrMappingImpl(MI);
  351. if (Mapping.isValid())
  352. return Mapping;
  353. llvm_unreachable("The target must implement this");
  354. }
  355. RegisterBankInfo::InstructionMappings
  356. RegisterBankInfo::getInstrPossibleMappings(const MachineInstr &MI) const {
  357. InstructionMappings PossibleMappings;
  358. const auto &Mapping = getInstrMapping(MI);
  359. if (Mapping.isValid()) {
  360. // Put the default mapping first.
  361. PossibleMappings.push_back(&Mapping);
  362. }
  363. // Then the alternative mapping, if any.
  364. InstructionMappings AltMappings = getInstrAlternativeMappings(MI);
  365. append_range(PossibleMappings, AltMappings);
  366. #ifndef NDEBUG
  367. for (const InstructionMapping *Mapping : PossibleMappings)
  368. assert(Mapping->verify(MI) && "Mapping is invalid");
  369. #endif
  370. return PossibleMappings;
  371. }
  372. RegisterBankInfo::InstructionMappings
  373. RegisterBankInfo::getInstrAlternativeMappings(const MachineInstr &MI) const {
  374. // No alternative for MI.
  375. return InstructionMappings();
  376. }
  377. void RegisterBankInfo::applyDefaultMapping(const OperandsMapper &OpdMapper) {
  378. MachineInstr &MI = OpdMapper.getMI();
  379. MachineRegisterInfo &MRI = OpdMapper.getMRI();
  380. LLVM_DEBUG(dbgs() << "Applying default-like mapping\n");
  381. for (unsigned OpIdx = 0,
  382. EndIdx = OpdMapper.getInstrMapping().getNumOperands();
  383. OpIdx != EndIdx; ++OpIdx) {
  384. LLVM_DEBUG(dbgs() << "OpIdx " << OpIdx);
  385. MachineOperand &MO = MI.getOperand(OpIdx);
  386. if (!MO.isReg()) {
  387. LLVM_DEBUG(dbgs() << " is not a register, nothing to be done\n");
  388. continue;
  389. }
  390. if (!MO.getReg()) {
  391. LLVM_DEBUG(dbgs() << " is $noreg, nothing to be done\n");
  392. continue;
  393. }
  394. assert(OpdMapper.getInstrMapping().getOperandMapping(OpIdx).NumBreakDowns !=
  395. 0 &&
  396. "Invalid mapping");
  397. assert(OpdMapper.getInstrMapping().getOperandMapping(OpIdx).NumBreakDowns ==
  398. 1 &&
  399. "This mapping is too complex for this function");
  400. iterator_range<SmallVectorImpl<Register>::const_iterator> NewRegs =
  401. OpdMapper.getVRegs(OpIdx);
  402. if (NewRegs.empty()) {
  403. LLVM_DEBUG(dbgs() << " has not been repaired, nothing to be done\n");
  404. continue;
  405. }
  406. Register OrigReg = MO.getReg();
  407. Register NewReg = *NewRegs.begin();
  408. LLVM_DEBUG(dbgs() << " changed, replace " << printReg(OrigReg, nullptr));
  409. MO.setReg(NewReg);
  410. LLVM_DEBUG(dbgs() << " with " << printReg(NewReg, nullptr));
  411. // The OperandsMapper creates plain scalar, we may have to fix that.
  412. // Check if the types match and if not, fix that.
  413. LLT OrigTy = MRI.getType(OrigReg);
  414. LLT NewTy = MRI.getType(NewReg);
  415. if (OrigTy != NewTy) {
  416. // The default mapping is not supposed to change the size of
  417. // the storage. However, right now we don't necessarily bump all
  418. // the types to storage size. For instance, we can consider
  419. // s16 G_AND legal whereas the storage size is going to be 32.
  420. assert(OrigTy.getSizeInBits() <= NewTy.getSizeInBits() &&
  421. "Types with difference size cannot be handled by the default "
  422. "mapping");
  423. LLVM_DEBUG(dbgs() << "\nChange type of new opd from " << NewTy << " to "
  424. << OrigTy);
  425. MRI.setType(NewReg, OrigTy);
  426. }
  427. LLVM_DEBUG(dbgs() << '\n');
  428. }
  429. }
  430. unsigned RegisterBankInfo::getSizeInBits(Register Reg,
  431. const MachineRegisterInfo &MRI,
  432. const TargetRegisterInfo &TRI) const {
  433. if (Register::isPhysicalRegister(Reg)) {
  434. // The size is not directly available for physical registers.
  435. // Instead, we need to access a register class that contains Reg and
  436. // get the size of that register class.
  437. // Because this is expensive, we'll cache the register class by calling
  438. auto *RC = &getMinimalPhysRegClass(Reg, TRI);
  439. assert(RC && "Expecting Register class");
  440. return TRI.getRegSizeInBits(*RC);
  441. }
  442. return TRI.getRegSizeInBits(Reg, MRI);
  443. }
  444. //------------------------------------------------------------------------------
  445. // Helper classes implementation.
  446. //------------------------------------------------------------------------------
  447. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  448. LLVM_DUMP_METHOD void RegisterBankInfo::PartialMapping::dump() const {
  449. print(dbgs());
  450. dbgs() << '\n';
  451. }
  452. #endif
  453. bool RegisterBankInfo::PartialMapping::verify() const {
  454. assert(RegBank && "Register bank not set");
  455. assert(Length && "Empty mapping");
  456. assert((StartIdx <= getHighBitIdx()) && "Overflow, switch to APInt?");
  457. // Check if the minimum width fits into RegBank.
  458. assert(RegBank->getSize() >= Length && "Register bank too small for Mask");
  459. return true;
  460. }
  461. void RegisterBankInfo::PartialMapping::print(raw_ostream &OS) const {
  462. OS << "[" << StartIdx << ", " << getHighBitIdx() << "], RegBank = ";
  463. if (RegBank)
  464. OS << *RegBank;
  465. else
  466. OS << "nullptr";
  467. }
  468. bool RegisterBankInfo::ValueMapping::partsAllUniform() const {
  469. if (NumBreakDowns < 2)
  470. return true;
  471. const PartialMapping *First = begin();
  472. for (const PartialMapping *Part = First + 1; Part != end(); ++Part) {
  473. if (Part->Length != First->Length || Part->RegBank != First->RegBank)
  474. return false;
  475. }
  476. return true;
  477. }
  478. bool RegisterBankInfo::ValueMapping::verify(unsigned MeaningfulBitWidth) const {
  479. assert(NumBreakDowns && "Value mapped nowhere?!");
  480. unsigned OrigValueBitWidth = 0;
  481. for (const RegisterBankInfo::PartialMapping &PartMap : *this) {
  482. // Check that each register bank is big enough to hold the partial value:
  483. // this check is done by PartialMapping::verify
  484. assert(PartMap.verify() && "Partial mapping is invalid");
  485. // The original value should completely be mapped.
  486. // Thus the maximum accessed index + 1 is the size of the original value.
  487. OrigValueBitWidth =
  488. std::max(OrigValueBitWidth, PartMap.getHighBitIdx() + 1);
  489. }
  490. assert(OrigValueBitWidth >= MeaningfulBitWidth &&
  491. "Meaningful bits not covered by the mapping");
  492. APInt ValueMask(OrigValueBitWidth, 0);
  493. for (const RegisterBankInfo::PartialMapping &PartMap : *this) {
  494. // Check that the union of the partial mappings covers the whole value,
  495. // without overlaps.
  496. // The high bit is exclusive in the APInt API, thus getHighBitIdx + 1.
  497. APInt PartMapMask = APInt::getBitsSet(OrigValueBitWidth, PartMap.StartIdx,
  498. PartMap.getHighBitIdx() + 1);
  499. ValueMask ^= PartMapMask;
  500. assert((ValueMask & PartMapMask) == PartMapMask &&
  501. "Some partial mappings overlap");
  502. }
  503. assert(ValueMask.isAllOnes() && "Value is not fully mapped");
  504. return true;
  505. }
  506. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  507. LLVM_DUMP_METHOD void RegisterBankInfo::ValueMapping::dump() const {
  508. print(dbgs());
  509. dbgs() << '\n';
  510. }
  511. #endif
  512. void RegisterBankInfo::ValueMapping::print(raw_ostream &OS) const {
  513. OS << "#BreakDown: " << NumBreakDowns << " ";
  514. bool IsFirst = true;
  515. for (const PartialMapping &PartMap : *this) {
  516. if (!IsFirst)
  517. OS << ", ";
  518. OS << '[' << PartMap << ']';
  519. IsFirst = false;
  520. }
  521. }
  522. bool RegisterBankInfo::InstructionMapping::verify(
  523. const MachineInstr &MI) const {
  524. // Check that all the register operands are properly mapped.
  525. // Check the constructor invariant.
  526. // For PHI, we only care about mapping the definition.
  527. assert(NumOperands == (isCopyLike(MI) ? 1 : MI.getNumOperands()) &&
  528. "NumOperands must match, see constructor");
  529. assert(MI.getParent() && MI.getMF() &&
  530. "MI must be connected to a MachineFunction");
  531. const MachineFunction &MF = *MI.getMF();
  532. const RegisterBankInfo *RBI = MF.getSubtarget().getRegBankInfo();
  533. (void)RBI;
  534. for (unsigned Idx = 0; Idx < NumOperands; ++Idx) {
  535. const MachineOperand &MO = MI.getOperand(Idx);
  536. if (!MO.isReg()) {
  537. assert(!getOperandMapping(Idx).isValid() &&
  538. "We should not care about non-reg mapping");
  539. continue;
  540. }
  541. Register Reg = MO.getReg();
  542. if (!Reg)
  543. continue;
  544. assert(getOperandMapping(Idx).isValid() &&
  545. "We must have a mapping for reg operands");
  546. const RegisterBankInfo::ValueMapping &MOMapping = getOperandMapping(Idx);
  547. (void)MOMapping;
  548. // Register size in bits.
  549. // This size must match what the mapping expects.
  550. assert(MOMapping.verify(RBI->getSizeInBits(
  551. Reg, MF.getRegInfo(), *MF.getSubtarget().getRegisterInfo())) &&
  552. "Value mapping is invalid");
  553. }
  554. return true;
  555. }
  556. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  557. LLVM_DUMP_METHOD void RegisterBankInfo::InstructionMapping::dump() const {
  558. print(dbgs());
  559. dbgs() << '\n';
  560. }
  561. #endif
  562. void RegisterBankInfo::InstructionMapping::print(raw_ostream &OS) const {
  563. OS << "ID: " << getID() << " Cost: " << getCost() << " Mapping: ";
  564. for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
  565. const ValueMapping &ValMapping = getOperandMapping(OpIdx);
  566. if (OpIdx)
  567. OS << ", ";
  568. OS << "{ Idx: " << OpIdx << " Map: " << ValMapping << '}';
  569. }
  570. }
  571. const int RegisterBankInfo::OperandsMapper::DontKnowIdx = -1;
  572. RegisterBankInfo::OperandsMapper::OperandsMapper(
  573. MachineInstr &MI, const InstructionMapping &InstrMapping,
  574. MachineRegisterInfo &MRI)
  575. : MRI(MRI), MI(MI), InstrMapping(InstrMapping) {
  576. unsigned NumOpds = InstrMapping.getNumOperands();
  577. OpToNewVRegIdx.resize(NumOpds, OperandsMapper::DontKnowIdx);
  578. assert(InstrMapping.verify(MI) && "Invalid mapping for MI");
  579. }
  580. iterator_range<SmallVectorImpl<Register>::iterator>
  581. RegisterBankInfo::OperandsMapper::getVRegsMem(unsigned OpIdx) {
  582. assert(OpIdx < getInstrMapping().getNumOperands() && "Out-of-bound access");
  583. unsigned NumPartialVal =
  584. getInstrMapping().getOperandMapping(OpIdx).NumBreakDowns;
  585. int StartIdx = OpToNewVRegIdx[OpIdx];
  586. if (StartIdx == OperandsMapper::DontKnowIdx) {
  587. // This is the first time we try to access OpIdx.
  588. // Create the cells that will hold all the partial values at the
  589. // end of the list of NewVReg.
  590. StartIdx = NewVRegs.size();
  591. OpToNewVRegIdx[OpIdx] = StartIdx;
  592. for (unsigned i = 0; i < NumPartialVal; ++i)
  593. NewVRegs.push_back(0);
  594. }
  595. SmallVectorImpl<Register>::iterator End =
  596. getNewVRegsEnd(StartIdx, NumPartialVal);
  597. return make_range(&NewVRegs[StartIdx], End);
  598. }
  599. SmallVectorImpl<Register>::const_iterator
  600. RegisterBankInfo::OperandsMapper::getNewVRegsEnd(unsigned StartIdx,
  601. unsigned NumVal) const {
  602. return const_cast<OperandsMapper *>(this)->getNewVRegsEnd(StartIdx, NumVal);
  603. }
  604. SmallVectorImpl<Register>::iterator
  605. RegisterBankInfo::OperandsMapper::getNewVRegsEnd(unsigned StartIdx,
  606. unsigned NumVal) {
  607. assert((NewVRegs.size() == StartIdx + NumVal ||
  608. NewVRegs.size() > StartIdx + NumVal) &&
  609. "NewVRegs too small to contain all the partial mapping");
  610. return NewVRegs.size() <= StartIdx + NumVal ? NewVRegs.end()
  611. : &NewVRegs[StartIdx + NumVal];
  612. }
  613. void RegisterBankInfo::OperandsMapper::createVRegs(unsigned OpIdx) {
  614. assert(OpIdx < getInstrMapping().getNumOperands() && "Out-of-bound access");
  615. iterator_range<SmallVectorImpl<Register>::iterator> NewVRegsForOpIdx =
  616. getVRegsMem(OpIdx);
  617. const ValueMapping &ValMapping = getInstrMapping().getOperandMapping(OpIdx);
  618. const PartialMapping *PartMap = ValMapping.begin();
  619. for (Register &NewVReg : NewVRegsForOpIdx) {
  620. assert(PartMap != ValMapping.end() && "Out-of-bound access");
  621. assert(NewVReg == 0 && "Register has already been created");
  622. // The new registers are always bound to scalar with the right size.
  623. // The actual type has to be set when the target does the mapping
  624. // of the instruction.
  625. // The rationale is that this generic code cannot guess how the
  626. // target plans to split the input type.
  627. NewVReg = MRI.createGenericVirtualRegister(LLT::scalar(PartMap->Length));
  628. MRI.setRegBank(NewVReg, *PartMap->RegBank);
  629. ++PartMap;
  630. }
  631. }
  632. void RegisterBankInfo::OperandsMapper::setVRegs(unsigned OpIdx,
  633. unsigned PartialMapIdx,
  634. Register NewVReg) {
  635. assert(OpIdx < getInstrMapping().getNumOperands() && "Out-of-bound access");
  636. assert(getInstrMapping().getOperandMapping(OpIdx).NumBreakDowns >
  637. PartialMapIdx &&
  638. "Out-of-bound access for partial mapping");
  639. // Make sure the memory is initialized for that operand.
  640. (void)getVRegsMem(OpIdx);
  641. assert(NewVRegs[OpToNewVRegIdx[OpIdx] + PartialMapIdx] == 0 &&
  642. "This value is already set");
  643. NewVRegs[OpToNewVRegIdx[OpIdx] + PartialMapIdx] = NewVReg;
  644. }
  645. iterator_range<SmallVectorImpl<Register>::const_iterator>
  646. RegisterBankInfo::OperandsMapper::getVRegs(unsigned OpIdx,
  647. bool ForDebug) const {
  648. (void)ForDebug;
  649. assert(OpIdx < getInstrMapping().getNumOperands() && "Out-of-bound access");
  650. int StartIdx = OpToNewVRegIdx[OpIdx];
  651. if (StartIdx == OperandsMapper::DontKnowIdx)
  652. return make_range(NewVRegs.end(), NewVRegs.end());
  653. unsigned PartMapSize =
  654. getInstrMapping().getOperandMapping(OpIdx).NumBreakDowns;
  655. SmallVectorImpl<Register>::const_iterator End =
  656. getNewVRegsEnd(StartIdx, PartMapSize);
  657. iterator_range<SmallVectorImpl<Register>::const_iterator> Res =
  658. make_range(&NewVRegs[StartIdx], End);
  659. #ifndef NDEBUG
  660. for (Register VReg : Res)
  661. assert((VReg || ForDebug) && "Some registers are uninitialized");
  662. #endif
  663. return Res;
  664. }
  665. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  666. LLVM_DUMP_METHOD void RegisterBankInfo::OperandsMapper::dump() const {
  667. print(dbgs(), true);
  668. dbgs() << '\n';
  669. }
  670. #endif
  671. void RegisterBankInfo::OperandsMapper::print(raw_ostream &OS,
  672. bool ForDebug) const {
  673. unsigned NumOpds = getInstrMapping().getNumOperands();
  674. if (ForDebug) {
  675. OS << "Mapping for " << getMI() << "\nwith " << getInstrMapping() << '\n';
  676. // Print out the internal state of the index table.
  677. OS << "Populated indices (CellNumber, IndexInNewVRegs): ";
  678. bool IsFirst = true;
  679. for (unsigned Idx = 0; Idx != NumOpds; ++Idx) {
  680. if (OpToNewVRegIdx[Idx] != DontKnowIdx) {
  681. if (!IsFirst)
  682. OS << ", ";
  683. OS << '(' << Idx << ", " << OpToNewVRegIdx[Idx] << ')';
  684. IsFirst = false;
  685. }
  686. }
  687. OS << '\n';
  688. } else
  689. OS << "Mapping ID: " << getInstrMapping().getID() << ' ';
  690. OS << "Operand Mapping: ";
  691. // If we have a function, we can pretty print the name of the registers.
  692. // Otherwise we will print the raw numbers.
  693. const TargetRegisterInfo *TRI =
  694. getMI().getParent() && getMI().getMF()
  695. ? getMI().getMF()->getSubtarget().getRegisterInfo()
  696. : nullptr;
  697. bool IsFirst = true;
  698. for (unsigned Idx = 0; Idx != NumOpds; ++Idx) {
  699. if (OpToNewVRegIdx[Idx] == DontKnowIdx)
  700. continue;
  701. if (!IsFirst)
  702. OS << ", ";
  703. IsFirst = false;
  704. OS << '(' << printReg(getMI().getOperand(Idx).getReg(), TRI) << ", [";
  705. bool IsFirstNewVReg = true;
  706. for (Register VReg : getVRegs(Idx)) {
  707. if (!IsFirstNewVReg)
  708. OS << ", ";
  709. IsFirstNewVReg = false;
  710. OS << printReg(VReg, TRI);
  711. }
  712. OS << "])";
  713. }
  714. }