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