1 //===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===// 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 // 9 // This tablegen backend emits an assembly printer for the current target. 10 // Note that this is currently fairly skeletal, but will grow over time. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "AsmWriterInst.h" 15 #include "CodeGenInstruction.h" 16 #include "CodeGenRegisters.h" 17 #include "CodeGenTarget.h" 18 #include "SequenceToOffsetTable.h" 19 #include "Types.h" 20 #include "llvm/ADT/ArrayRef.h" 21 #include "llvm/ADT/DenseMap.h" 22 #include "llvm/ADT/SmallString.h" 23 #include "llvm/ADT/SmallVector.h" 24 #include "llvm/ADT/STLExtras.h" 25 #include "llvm/ADT/StringExtras.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/ADT/Twine.h" 28 #include "llvm/Support/Casting.h" 29 #include "llvm/Support/Debug.h" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/Format.h" 32 #include "llvm/Support/MathExtras.h" 33 #include "llvm/Support/raw_ostream.h" 34 #include "llvm/TableGen/Error.h" 35 #include "llvm/TableGen/Record.h" 36 #include "llvm/TableGen/TableGenBackend.h" 37 #include <algorithm> 38 #include <cassert> 39 #include <cstddef> 40 #include <cstdint> 41 #include <deque> 42 #include <iterator> 43 #include <map> 44 #include <set> 45 #include <string> 46 #include <tuple> 47 #include <utility> 48 #include <vector> 49 50 using namespace llvm; 51 52 #define DEBUG_TYPE "asm-writer-emitter" 53 54 namespace { 55 56 class AsmWriterEmitter { 57 RecordKeeper &Records; 58 CodeGenTarget Target; 59 ArrayRef<const CodeGenInstruction *> NumberedInstructions; 60 std::vector<AsmWriterInst> Instructions; 61 62 public: 63 AsmWriterEmitter(RecordKeeper &R); 64 65 void run(raw_ostream &o); 66 67 private: 68 void EmitPrintInstruction(raw_ostream &o); 69 void EmitGetRegisterName(raw_ostream &o); 70 void EmitPrintAliasInstruction(raw_ostream &O); 71 72 void FindUniqueOperandCommands(std::vector<std::string> &UOC, 73 std::vector<std::vector<unsigned>> &InstIdxs, 74 std::vector<unsigned> &InstOpsUsed, 75 bool PassSubtarget) const; 76 }; 77 78 } // end anonymous namespace 79 80 static void PrintCases(std::vector<std::pair<std::string, 81 AsmWriterOperand>> &OpsToPrint, raw_ostream &O, 82 bool PassSubtarget) { 83 O << " case " << OpsToPrint.back().first << ":"; 84 AsmWriterOperand TheOp = OpsToPrint.back().second; 85 OpsToPrint.pop_back(); 86 87 // Check to see if any other operands are identical in this list, and if so, 88 // emit a case label for them. 89 for (unsigned i = OpsToPrint.size(); i != 0; --i) 90 if (OpsToPrint[i-1].second == TheOp) { 91 O << "\n case " << OpsToPrint[i-1].first << ":"; 92 OpsToPrint.erase(OpsToPrint.begin()+i-1); 93 } 94 95 // Finally, emit the code. 96 O << "\n " << TheOp.getCode(PassSubtarget); 97 O << "\n break;\n"; 98 } 99 100 /// EmitInstructions - Emit the last instruction in the vector and any other 101 /// instructions that are suitably similar to it. 102 static void EmitInstructions(std::vector<AsmWriterInst> &Insts, 103 raw_ostream &O, bool PassSubtarget) { 104 AsmWriterInst FirstInst = Insts.back(); 105 Insts.pop_back(); 106 107 std::vector<AsmWriterInst> SimilarInsts; 108 unsigned DifferingOperand = ~0; 109 for (unsigned i = Insts.size(); i != 0; --i) { 110 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst); 111 if (DiffOp != ~1U) { 112 if (DifferingOperand == ~0U) // First match! 113 DifferingOperand = DiffOp; 114 115 // If this differs in the same operand as the rest of the instructions in 116 // this class, move it to the SimilarInsts list. 117 if (DifferingOperand == DiffOp || DiffOp == ~0U) { 118 SimilarInsts.push_back(Insts[i-1]); 119 Insts.erase(Insts.begin()+i-1); 120 } 121 } 122 } 123 124 O << " case " << FirstInst.CGI->Namespace << "::" 125 << FirstInst.CGI->TheDef->getName() << ":\n"; 126 for (const AsmWriterInst &AWI : SimilarInsts) 127 O << " case " << AWI.CGI->Namespace << "::" 128 << AWI.CGI->TheDef->getName() << ":\n"; 129 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) { 130 if (i != DifferingOperand) { 131 // If the operand is the same for all instructions, just print it. 132 O << " " << FirstInst.Operands[i].getCode(PassSubtarget); 133 } else { 134 // If this is the operand that varies between all of the instructions, 135 // emit a switch for just this operand now. 136 O << " switch (MI->getOpcode()) {\n"; 137 O << " default: llvm_unreachable(\"Unexpected opcode.\");\n"; 138 std::vector<std::pair<std::string, AsmWriterOperand>> OpsToPrint; 139 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace.str() + "::" + 140 FirstInst.CGI->TheDef->getName().str(), 141 FirstInst.Operands[i])); 142 143 for (const AsmWriterInst &AWI : SimilarInsts) { 144 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace.str()+"::" + 145 AWI.CGI->TheDef->getName().str(), 146 AWI.Operands[i])); 147 } 148 std::reverse(OpsToPrint.begin(), OpsToPrint.end()); 149 while (!OpsToPrint.empty()) 150 PrintCases(OpsToPrint, O, PassSubtarget); 151 O << " }"; 152 } 153 O << "\n"; 154 } 155 O << " break;\n"; 156 } 157 158 void AsmWriterEmitter:: 159 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands, 160 std::vector<std::vector<unsigned>> &InstIdxs, 161 std::vector<unsigned> &InstOpsUsed, 162 bool PassSubtarget) const { 163 // This vector parallels UniqueOperandCommands, keeping track of which 164 // instructions each case are used for. It is a comma separated string of 165 // enums. 166 std::vector<std::string> InstrsForCase; 167 InstrsForCase.resize(UniqueOperandCommands.size()); 168 InstOpsUsed.assign(UniqueOperandCommands.size(), 0); 169 170 for (size_t i = 0, e = Instructions.size(); i != e; ++i) { 171 const AsmWriterInst &Inst = Instructions[i]; 172 if (Inst.Operands.empty()) 173 continue; // Instruction already done. 174 175 std::string Command = " "+Inst.Operands[0].getCode(PassSubtarget)+"\n"; 176 177 // Check to see if we already have 'Command' in UniqueOperandCommands. 178 // If not, add it. 179 auto I = llvm::find(UniqueOperandCommands, Command); 180 if (I != UniqueOperandCommands.end()) { 181 size_t idx = I - UniqueOperandCommands.begin(); 182 InstrsForCase[idx] += ", "; 183 InstrsForCase[idx] += Inst.CGI->TheDef->getName(); 184 InstIdxs[idx].push_back(i); 185 } else { 186 UniqueOperandCommands.push_back(std::move(Command)); 187 InstrsForCase.push_back(Inst.CGI->TheDef->getName()); 188 InstIdxs.emplace_back(); 189 InstIdxs.back().push_back(i); 190 191 // This command matches one operand so far. 192 InstOpsUsed.push_back(1); 193 } 194 } 195 196 // For each entry of UniqueOperandCommands, there is a set of instructions 197 // that uses it. If the next command of all instructions in the set are 198 // identical, fold it into the command. 199 for (size_t CommandIdx = 0, e = UniqueOperandCommands.size(); 200 CommandIdx != e; ++CommandIdx) { 201 202 const auto &Idxs = InstIdxs[CommandIdx]; 203 204 for (unsigned Op = 1; ; ++Op) { 205 // Find the first instruction in the set. 206 const AsmWriterInst &FirstInst = Instructions[Idxs.front()]; 207 // If this instruction has no more operands, we isn't anything to merge 208 // into this command. 209 if (FirstInst.Operands.size() == Op) 210 break; 211 212 // Otherwise, scan to see if all of the other instructions in this command 213 // set share the operand. 214 if (std::any_of(Idxs.begin()+1, Idxs.end(), 215 [&](unsigned Idx) { 216 const AsmWriterInst &OtherInst = Instructions[Idx]; 217 return OtherInst.Operands.size() == Op || 218 OtherInst.Operands[Op] != FirstInst.Operands[Op]; 219 })) 220 break; 221 222 // Okay, everything in this command set has the same next operand. Add it 223 // to UniqueOperandCommands and remember that it was consumed. 224 std::string Command = " " + 225 FirstInst.Operands[Op].getCode(PassSubtarget) + "\n"; 226 227 UniqueOperandCommands[CommandIdx] += Command; 228 InstOpsUsed[CommandIdx]++; 229 } 230 } 231 232 // Prepend some of the instructions each case is used for onto the case val. 233 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) { 234 std::string Instrs = InstrsForCase[i]; 235 if (Instrs.size() > 70) { 236 Instrs.erase(Instrs.begin()+70, Instrs.end()); 237 Instrs += "..."; 238 } 239 240 if (!Instrs.empty()) 241 UniqueOperandCommands[i] = " // " + Instrs + "\n" + 242 UniqueOperandCommands[i]; 243 } 244 } 245 246 static void UnescapeString(std::string &Str) { 247 for (unsigned i = 0; i != Str.size(); ++i) { 248 if (Str[i] == '\\' && i != Str.size()-1) { 249 switch (Str[i+1]) { 250 default: continue; // Don't execute the code after the switch. 251 case 'a': Str[i] = '\a'; break; 252 case 'b': Str[i] = '\b'; break; 253 case 'e': Str[i] = 27; break; 254 case 'f': Str[i] = '\f'; break; 255 case 'n': Str[i] = '\n'; break; 256 case 'r': Str[i] = '\r'; break; 257 case 't': Str[i] = '\t'; break; 258 case 'v': Str[i] = '\v'; break; 259 case '"': Str[i] = '\"'; break; 260 case '\'': Str[i] = '\''; break; 261 case '\\': Str[i] = '\\'; break; 262 } 263 // Nuke the second character. 264 Str.erase(Str.begin()+i+1); 265 } 266 } 267 } 268 269 /// EmitPrintInstruction - Generate the code for the "printInstruction" method 270 /// implementation. Destroys all instances of AsmWriterInst information, by 271 /// clearing the Instructions vector. 272 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) { 273 Record *AsmWriter = Target.getAsmWriter(); 274 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName"); 275 bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget"); 276 277 O << 278 "/// printInstruction - This method is automatically generated by tablegen\n" 279 "/// from the instruction set description.\n" 280 "void " << Target.getName() << ClassName 281 << "::printInstruction(const MCInst *MI, " 282 << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "") 283 << "raw_ostream &O) {\n"; 284 285 // Build an aggregate string, and build a table of offsets into it. 286 SequenceToOffsetTable<std::string> StringTable; 287 288 /// OpcodeInfo - This encodes the index of the string to use for the first 289 /// chunk of the output as well as indices used for operand printing. 290 std::vector<uint64_t> OpcodeInfo(NumberedInstructions.size()); 291 const unsigned OpcodeInfoBits = 64; 292 293 // Add all strings to the string table upfront so it can generate an optimized 294 // representation. 295 for (AsmWriterInst &AWI : Instructions) { 296 if (AWI.Operands[0].OperandType == 297 AsmWriterOperand::isLiteralTextOperand && 298 !AWI.Operands[0].Str.empty()) { 299 std::string Str = AWI.Operands[0].Str; 300 UnescapeString(Str); 301 StringTable.add(Str); 302 } 303 } 304 305 StringTable.layout(); 306 307 unsigned MaxStringIdx = 0; 308 for (AsmWriterInst &AWI : Instructions) { 309 unsigned Idx; 310 if (AWI.Operands[0].OperandType != AsmWriterOperand::isLiteralTextOperand || 311 AWI.Operands[0].Str.empty()) { 312 // Something handled by the asmwriter printer, but with no leading string. 313 Idx = StringTable.get(""); 314 } else { 315 std::string Str = AWI.Operands[0].Str; 316 UnescapeString(Str); 317 Idx = StringTable.get(Str); 318 MaxStringIdx = std::max(MaxStringIdx, Idx); 319 320 // Nuke the string from the operand list. It is now handled! 321 AWI.Operands.erase(AWI.Operands.begin()); 322 } 323 324 // Bias offset by one since we want 0 as a sentinel. 325 OpcodeInfo[AWI.CGIIndex] = Idx+1; 326 } 327 328 // Figure out how many bits we used for the string index. 329 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2); 330 331 // To reduce code size, we compactify common instructions into a few bits 332 // in the opcode-indexed table. 333 unsigned BitsLeft = OpcodeInfoBits-AsmStrBits; 334 335 std::vector<std::vector<std::string>> TableDrivenOperandPrinters; 336 337 while (true) { 338 std::vector<std::string> UniqueOperandCommands; 339 std::vector<std::vector<unsigned>> InstIdxs; 340 std::vector<unsigned> NumInstOpsHandled; 341 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs, 342 NumInstOpsHandled, PassSubtarget); 343 344 // If we ran out of operands to print, we're done. 345 if (UniqueOperandCommands.empty()) break; 346 347 // Compute the number of bits we need to represent these cases, this is 348 // ceil(log2(numentries)). 349 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size()); 350 351 // If we don't have enough bits for this operand, don't include it. 352 if (NumBits > BitsLeft) { 353 LLVM_DEBUG(errs() << "Not enough bits to densely encode " << NumBits 354 << " more bits\n"); 355 break; 356 } 357 358 // Otherwise, we can include this in the initial lookup table. Add it in. 359 for (size_t i = 0, e = InstIdxs.size(); i != e; ++i) { 360 unsigned NumOps = NumInstOpsHandled[i]; 361 for (unsigned Idx : InstIdxs[i]) { 362 OpcodeInfo[Instructions[Idx].CGIIndex] |= 363 (uint64_t)i << (OpcodeInfoBits-BitsLeft); 364 // Remove the info about this operand from the instruction. 365 AsmWriterInst &Inst = Instructions[Idx]; 366 if (!Inst.Operands.empty()) { 367 assert(NumOps <= Inst.Operands.size() && 368 "Can't remove this many ops!"); 369 Inst.Operands.erase(Inst.Operands.begin(), 370 Inst.Operands.begin()+NumOps); 371 } 372 } 373 } 374 BitsLeft -= NumBits; 375 376 // Remember the handlers for this set of operands. 377 TableDrivenOperandPrinters.push_back(std::move(UniqueOperandCommands)); 378 } 379 380 // Emit the string table itself. 381 O << " static const char AsmStrs[] = {\n"; 382 StringTable.emit(O, printChar); 383 O << " };\n\n"; 384 385 // Emit the lookup tables in pieces to minimize wasted bytes. 386 unsigned BytesNeeded = ((OpcodeInfoBits - BitsLeft) + 7) / 8; 387 unsigned Table = 0, Shift = 0; 388 SmallString<128> BitsString; 389 raw_svector_ostream BitsOS(BitsString); 390 // If the total bits is more than 32-bits we need to use a 64-bit type. 391 BitsOS << " uint" << ((BitsLeft < (OpcodeInfoBits - 32)) ? 64 : 32) 392 << "_t Bits = 0;\n"; 393 while (BytesNeeded != 0) { 394 // Figure out how big this table section needs to be, but no bigger than 4. 395 unsigned TableSize = std::min(1 << Log2_32(BytesNeeded), 4); 396 BytesNeeded -= TableSize; 397 TableSize *= 8; // Convert to bits; 398 uint64_t Mask = (1ULL << TableSize) - 1; 399 O << " static const uint" << TableSize << "_t OpInfo" << Table 400 << "[] = {\n"; 401 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) { 402 O << " " << ((OpcodeInfo[i] >> Shift) & Mask) << "U,\t// " 403 << NumberedInstructions[i]->TheDef->getName() << "\n"; 404 } 405 O << " };\n\n"; 406 // Emit string to combine the individual table lookups. 407 BitsOS << " Bits |= "; 408 // If the total bits is more than 32-bits we need to use a 64-bit type. 409 if (BitsLeft < (OpcodeInfoBits - 32)) 410 BitsOS << "(uint64_t)"; 411 BitsOS << "OpInfo" << Table << "[MI->getOpcode()] << " << Shift << ";\n"; 412 // Prepare the shift for the next iteration and increment the table count. 413 Shift += TableSize; 414 ++Table; 415 } 416 417 // Emit the initial tab character. 418 O << " O << \"\\t\";\n\n"; 419 420 O << " // Emit the opcode for the instruction.\n"; 421 O << BitsString; 422 423 // Emit the starting string. 424 O << " assert(Bits != 0 && \"Cannot print this instruction.\");\n" 425 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n"; 426 427 // Output the table driven operand information. 428 BitsLeft = OpcodeInfoBits-AsmStrBits; 429 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) { 430 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i]; 431 432 // Compute the number of bits we need to represent these cases, this is 433 // ceil(log2(numentries)). 434 unsigned NumBits = Log2_32_Ceil(Commands.size()); 435 assert(NumBits <= BitsLeft && "consistency error"); 436 437 // Emit code to extract this field from Bits. 438 O << "\n // Fragment " << i << " encoded into " << NumBits 439 << " bits for " << Commands.size() << " unique commands.\n"; 440 441 if (Commands.size() == 2) { 442 // Emit two possibilitys with if/else. 443 O << " if ((Bits >> " 444 << (OpcodeInfoBits-BitsLeft) << ") & " 445 << ((1 << NumBits)-1) << ") {\n" 446 << Commands[1] 447 << " } else {\n" 448 << Commands[0] 449 << " }\n\n"; 450 } else if (Commands.size() == 1) { 451 // Emit a single possibility. 452 O << Commands[0] << "\n\n"; 453 } else { 454 O << " switch ((Bits >> " 455 << (OpcodeInfoBits-BitsLeft) << ") & " 456 << ((1 << NumBits)-1) << ") {\n" 457 << " default: llvm_unreachable(\"Invalid command number.\");\n"; 458 459 // Print out all the cases. 460 for (unsigned j = 0, e = Commands.size(); j != e; ++j) { 461 O << " case " << j << ":\n"; 462 O << Commands[j]; 463 O << " break;\n"; 464 } 465 O << " }\n\n"; 466 } 467 BitsLeft -= NumBits; 468 } 469 470 // Okay, delete instructions with no operand info left. 471 auto I = llvm::remove_if(Instructions, 472 [](AsmWriterInst &Inst) { return Inst.Operands.empty(); }); 473 Instructions.erase(I, Instructions.end()); 474 475 476 // Because this is a vector, we want to emit from the end. Reverse all of the 477 // elements in the vector. 478 std::reverse(Instructions.begin(), Instructions.end()); 479 480 481 // Now that we've emitted all of the operand info that fit into 64 bits, emit 482 // information for those instructions that are left. This is a less dense 483 // encoding, but we expect the main 64-bit table to handle the majority of 484 // instructions. 485 if (!Instructions.empty()) { 486 // Find the opcode # of inline asm. 487 O << " switch (MI->getOpcode()) {\n"; 488 O << " default: llvm_unreachable(\"Unexpected opcode.\");\n"; 489 while (!Instructions.empty()) 490 EmitInstructions(Instructions, O, PassSubtarget); 491 492 O << " }\n"; 493 } 494 495 O << "}\n"; 496 } 497 498 static void 499 emitRegisterNameString(raw_ostream &O, StringRef AltName, 500 const std::deque<CodeGenRegister> &Registers) { 501 SequenceToOffsetTable<std::string> StringTable; 502 SmallVector<std::string, 4> AsmNames(Registers.size()); 503 unsigned i = 0; 504 for (const auto &Reg : Registers) { 505 std::string &AsmName = AsmNames[i++]; 506 507 // "NoRegAltName" is special. We don't need to do a lookup for that, 508 // as it's just a reference to the default register name. 509 if (AltName == "" || AltName == "NoRegAltName") { 510 AsmName = Reg.TheDef->getValueAsString("AsmName"); 511 if (AsmName.empty()) 512 AsmName = Reg.getName(); 513 } else { 514 // Make sure the register has an alternate name for this index. 515 std::vector<Record*> AltNameList = 516 Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices"); 517 unsigned Idx = 0, e; 518 for (e = AltNameList.size(); 519 Idx < e && (AltNameList[Idx]->getName() != AltName); 520 ++Idx) 521 ; 522 // If the register has an alternate name for this index, use it. 523 // Otherwise, leave it empty as an error flag. 524 if (Idx < e) { 525 std::vector<StringRef> AltNames = 526 Reg.TheDef->getValueAsListOfStrings("AltNames"); 527 if (AltNames.size() <= Idx) 528 PrintFatalError(Reg.TheDef->getLoc(), 529 "Register definition missing alt name for '" + 530 AltName + "'."); 531 AsmName = AltNames[Idx]; 532 } 533 } 534 StringTable.add(AsmName); 535 } 536 537 StringTable.layout(); 538 O << " static const char AsmStrs" << AltName << "[] = {\n"; 539 StringTable.emit(O, printChar); 540 O << " };\n\n"; 541 542 O << " static const " << getMinimalTypeForRange(StringTable.size() - 1, 32) 543 << " RegAsmOffset" << AltName << "[] = {"; 544 for (unsigned i = 0, e = Registers.size(); i != e; ++i) { 545 if ((i % 14) == 0) 546 O << "\n "; 547 O << StringTable.get(AsmNames[i]) << ", "; 548 } 549 O << "\n };\n" 550 << "\n"; 551 } 552 553 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) { 554 Record *AsmWriter = Target.getAsmWriter(); 555 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName"); 556 const auto &Registers = Target.getRegBank().getRegisters(); 557 const std::vector<Record*> &AltNameIndices = Target.getRegAltNameIndices(); 558 bool hasAltNames = AltNameIndices.size() > 1; 559 StringRef Namespace = Registers.front().TheDef->getValueAsString("Namespace"); 560 561 O << 562 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n" 563 "/// from the register set description. This returns the assembler name\n" 564 "/// for the specified register.\n" 565 "const char *" << Target.getName() << ClassName << "::"; 566 if (hasAltNames) 567 O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n"; 568 else 569 O << "getRegisterName(unsigned RegNo) {\n"; 570 O << " assert(RegNo && RegNo < " << (Registers.size()+1) 571 << " && \"Invalid register number!\");\n" 572 << "\n"; 573 574 if (hasAltNames) { 575 for (const Record *R : AltNameIndices) 576 emitRegisterNameString(O, R->getName(), Registers); 577 } else 578 emitRegisterNameString(O, "", Registers); 579 580 if (hasAltNames) { 581 O << " switch(AltIdx) {\n" 582 << " default: llvm_unreachable(\"Invalid register alt name index!\");\n"; 583 for (const Record *R : AltNameIndices) { 584 StringRef AltName = R->getName(); 585 O << " case "; 586 if (!Namespace.empty()) 587 O << Namespace << "::"; 588 O << AltName << ":\n" 589 << " assert(*(AsmStrs" << AltName << "+RegAsmOffset" << AltName 590 << "[RegNo-1]) &&\n" 591 << " \"Invalid alt name index for register!\");\n" 592 << " return AsmStrs" << AltName << "+RegAsmOffset" << AltName 593 << "[RegNo-1];\n"; 594 } 595 O << " }\n"; 596 } else { 597 O << " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n" 598 << " \"Invalid alt name index for register!\");\n" 599 << " return AsmStrs+RegAsmOffset[RegNo-1];\n"; 600 } 601 O << "}\n"; 602 } 603 604 namespace { 605 606 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if 607 // they both have the same conditionals. In which case, we cannot print out the 608 // alias for that pattern. 609 class IAPrinter { 610 std::vector<std::string> Conds; 611 std::map<StringRef, std::pair<int, int>> OpMap; 612 613 std::string Result; 614 std::string AsmString; 615 616 public: 617 IAPrinter(std::string R, std::string AS) 618 : Result(std::move(R)), AsmString(std::move(AS)) {} 619 620 void addCond(const std::string &C) { Conds.push_back(C); } 621 622 void addOperand(StringRef Op, int OpIdx, int PrintMethodIdx = -1) { 623 assert(OpIdx >= 0 && OpIdx < 0xFE && "Idx out of range"); 624 assert(PrintMethodIdx >= -1 && PrintMethodIdx < 0xFF && 625 "Idx out of range"); 626 OpMap[Op] = std::make_pair(OpIdx, PrintMethodIdx); 627 } 628 629 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); } 630 int getOpIndex(StringRef Op) { return OpMap[Op].first; } 631 std::pair<int, int> &getOpData(StringRef Op) { return OpMap[Op]; } 632 633 std::pair<StringRef, StringRef::iterator> parseName(StringRef::iterator Start, 634 StringRef::iterator End) { 635 StringRef::iterator I = Start; 636 StringRef::iterator Next; 637 if (*I == '{') { 638 // ${some_name} 639 Start = ++I; 640 while (I != End && *I != '}') 641 ++I; 642 Next = I; 643 // eat the final '}' 644 if (Next != End) 645 ++Next; 646 } else { 647 // $name, just eat the usual suspects. 648 while (I != End && 649 ((*I >= 'a' && *I <= 'z') || (*I >= 'A' && *I <= 'Z') || 650 (*I >= '0' && *I <= '9') || *I == '_')) 651 ++I; 652 Next = I; 653 } 654 655 return std::make_pair(StringRef(Start, I - Start), Next); 656 } 657 658 void print(raw_ostream &O) { 659 if (Conds.empty()) { 660 O.indent(6) << "return true;\n"; 661 return; 662 } 663 664 O << "if ("; 665 666 for (std::vector<std::string>::iterator 667 I = Conds.begin(), E = Conds.end(); I != E; ++I) { 668 if (I != Conds.begin()) { 669 O << " &&\n"; 670 O.indent(8); 671 } 672 673 O << *I; 674 } 675 676 O << ") {\n"; 677 O.indent(6) << "// " << Result << "\n"; 678 679 // Directly mangle mapped operands into the string. Each operand is 680 // identified by a '$' sign followed by a byte identifying the number of the 681 // operand. We add one to the index to avoid zero bytes. 682 StringRef ASM(AsmString); 683 SmallString<128> OutString; 684 raw_svector_ostream OS(OutString); 685 for (StringRef::iterator I = ASM.begin(), E = ASM.end(); I != E;) { 686 OS << *I; 687 if (*I == '$') { 688 StringRef Name; 689 std::tie(Name, I) = parseName(++I, E); 690 assert(isOpMapped(Name) && "Unmapped operand!"); 691 692 int OpIndex, PrintIndex; 693 std::tie(OpIndex, PrintIndex) = getOpData(Name); 694 if (PrintIndex == -1) { 695 // Can use the default printOperand route. 696 OS << format("\\x%02X", (unsigned char)OpIndex + 1); 697 } else 698 // 3 bytes if a PrintMethod is needed: 0xFF, the MCInst operand 699 // number, and which of our pre-detected Methods to call. 700 OS << format("\\xFF\\x%02X\\x%02X", OpIndex + 1, PrintIndex + 1); 701 } else { 702 ++I; 703 } 704 } 705 706 // Emit the string. 707 O.indent(6) << "AsmString = \"" << OutString << "\";\n"; 708 709 O.indent(6) << "break;\n"; 710 O.indent(4) << '}'; 711 } 712 713 bool operator==(const IAPrinter &RHS) const { 714 if (Conds.size() != RHS.Conds.size()) 715 return false; 716 717 unsigned Idx = 0; 718 for (const auto &str : Conds) 719 if (str != RHS.Conds[Idx++]) 720 return false; 721 722 return true; 723 } 724 }; 725 726 } // end anonymous namespace 727 728 static unsigned CountNumOperands(StringRef AsmString, unsigned Variant) { 729 return AsmString.count(' ') + AsmString.count('\t'); 730 } 731 732 namespace { 733 734 struct AliasPriorityComparator { 735 typedef std::pair<CodeGenInstAlias, int> ValueType; 736 bool operator()(const ValueType &LHS, const ValueType &RHS) const { 737 if (LHS.second == RHS.second) { 738 // We don't actually care about the order, but for consistency it 739 // shouldn't depend on pointer comparisons. 740 return LessRecordByID()(LHS.first.TheDef, RHS.first.TheDef); 741 } 742 743 // Aliases with larger priorities should be considered first. 744 return LHS.second > RHS.second; 745 } 746 }; 747 748 } // end anonymous namespace 749 750 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) { 751 Record *AsmWriter = Target.getAsmWriter(); 752 753 O << "\n#ifdef PRINT_ALIAS_INSTR\n"; 754 O << "#undef PRINT_ALIAS_INSTR\n\n"; 755 756 ////////////////////////////// 757 // Gather information about aliases we need to print 758 ////////////////////////////// 759 760 // Emit the method that prints the alias instruction. 761 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName"); 762 unsigned Variant = AsmWriter->getValueAsInt("Variant"); 763 bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget"); 764 765 std::vector<Record*> AllInstAliases = 766 Records.getAllDerivedDefinitions("InstAlias"); 767 768 // Create a map from the qualified name to a list of potential matches. 769 typedef std::set<std::pair<CodeGenInstAlias, int>, AliasPriorityComparator> 770 AliasWithPriority; 771 std::map<std::string, AliasWithPriority> AliasMap; 772 for (Record *R : AllInstAliases) { 773 int Priority = R->getValueAsInt("EmitPriority"); 774 if (Priority < 1) 775 continue; // Aliases with priority 0 are never emitted. 776 777 const DagInit *DI = R->getValueAsDag("ResultInst"); 778 const DefInit *Op = cast<DefInit>(DI->getOperator()); 779 AliasMap[getQualifiedName(Op->getDef())].insert( 780 std::make_pair(CodeGenInstAlias(R, Target), Priority)); 781 } 782 783 // A map of which conditions need to be met for each instruction operand 784 // before it can be matched to the mnemonic. 785 std::map<std::string, std::vector<IAPrinter>> IAPrinterMap; 786 787 std::vector<std::string> PrintMethods; 788 789 // A list of MCOperandPredicates for all operands in use, and the reverse map 790 std::vector<const Record*> MCOpPredicates; 791 DenseMap<const Record*, unsigned> MCOpPredicateMap; 792 793 for (auto &Aliases : AliasMap) { 794 for (auto &Alias : Aliases.second) { 795 const CodeGenInstAlias &CGA = Alias.first; 796 unsigned LastOpNo = CGA.ResultInstOperandIndex.size(); 797 std::string FlatInstAsmString = 798 CodeGenInstruction::FlattenAsmStringVariants(CGA.ResultInst->AsmString, 799 Variant); 800 unsigned NumResultOps = CountNumOperands(FlatInstAsmString, Variant); 801 802 std::string FlatAliasAsmString = 803 CodeGenInstruction::FlattenAsmStringVariants(CGA.AsmString, 804 Variant); 805 806 // Don't emit the alias if it has more operands than what it's aliasing. 807 if (NumResultOps < CountNumOperands(FlatAliasAsmString, Variant)) 808 continue; 809 810 IAPrinter IAP(CGA.Result->getAsString(), FlatAliasAsmString); 811 812 StringRef Namespace = Target.getName(); 813 std::vector<Record *> ReqFeatures; 814 if (PassSubtarget) { 815 // We only consider ReqFeatures predicates if PassSubtarget 816 std::vector<Record *> RF = 817 CGA.TheDef->getValueAsListOfDefs("Predicates"); 818 copy_if(RF, std::back_inserter(ReqFeatures), [](Record *R) { 819 return R->getValueAsBit("AssemblerMatcherPredicate"); 820 }); 821 } 822 823 unsigned NumMIOps = 0; 824 for (auto &ResultInstOpnd : CGA.ResultInst->Operands) 825 NumMIOps += ResultInstOpnd.MINumOperands; 826 827 std::string Cond; 828 Cond = std::string("MI->getNumOperands() == ") + utostr(NumMIOps); 829 IAP.addCond(Cond); 830 831 bool CantHandle = false; 832 833 unsigned MIOpNum = 0; 834 for (unsigned i = 0, e = LastOpNo; i != e; ++i) { 835 // Skip over tied operands as they're not part of an alias declaration. 836 auto &Operands = CGA.ResultInst->Operands; 837 while (true) { 838 unsigned OpNum = Operands.getSubOperandNumber(MIOpNum).first; 839 if (Operands[OpNum].MINumOperands == 1 && 840 Operands[OpNum].getTiedRegister() != -1) { 841 // Tied operands of different RegisterClass should be explicit within 842 // an instruction's syntax and so cannot be skipped. 843 int TiedOpNum = Operands[OpNum].getTiedRegister(); 844 if (Operands[OpNum].Rec->getName() == 845 Operands[TiedOpNum].Rec->getName()) { 846 ++MIOpNum; 847 continue; 848 } 849 } 850 break; 851 } 852 853 std::string Op = "MI->getOperand(" + utostr(MIOpNum) + ")"; 854 855 const CodeGenInstAlias::ResultOperand &RO = CGA.ResultOperands[i]; 856 857 switch (RO.Kind) { 858 case CodeGenInstAlias::ResultOperand::K_Record: { 859 const Record *Rec = RO.getRecord(); 860 StringRef ROName = RO.getName(); 861 int PrintMethodIdx = -1; 862 863 // These two may have a PrintMethod, which we want to record (if it's 864 // the first time we've seen it) and provide an index for the aliasing 865 // code to use. 866 if (Rec->isSubClassOf("RegisterOperand") || 867 Rec->isSubClassOf("Operand")) { 868 StringRef PrintMethod = Rec->getValueAsString("PrintMethod"); 869 if (PrintMethod != "" && PrintMethod != "printOperand") { 870 PrintMethodIdx = 871 llvm::find(PrintMethods, PrintMethod) - PrintMethods.begin(); 872 if (static_cast<unsigned>(PrintMethodIdx) == PrintMethods.size()) 873 PrintMethods.push_back(PrintMethod); 874 } 875 } 876 877 if (Rec->isSubClassOf("RegisterOperand")) 878 Rec = Rec->getValueAsDef("RegClass"); 879 if (Rec->isSubClassOf("RegisterClass")) { 880 IAP.addCond(Op + ".isReg()"); 881 882 if (!IAP.isOpMapped(ROName)) { 883 IAP.addOperand(ROName, MIOpNum, PrintMethodIdx); 884 Record *R = CGA.ResultOperands[i].getRecord(); 885 if (R->isSubClassOf("RegisterOperand")) 886 R = R->getValueAsDef("RegClass"); 887 Cond = std::string("MRI.getRegClass(") + Target.getName().str() + 888 "::" + R->getName().str() + "RegClassID).contains(" + Op + 889 ".getReg())"; 890 } else { 891 Cond = Op + ".getReg() == MI->getOperand(" + 892 utostr(IAP.getOpIndex(ROName)) + ").getReg()"; 893 } 894 } else { 895 // Assume all printable operands are desired for now. This can be 896 // overridden in the InstAlias instantiation if necessary. 897 IAP.addOperand(ROName, MIOpNum, PrintMethodIdx); 898 899 // There might be an additional predicate on the MCOperand 900 unsigned Entry = MCOpPredicateMap[Rec]; 901 if (!Entry) { 902 if (!Rec->isValueUnset("MCOperandPredicate")) { 903 MCOpPredicates.push_back(Rec); 904 Entry = MCOpPredicates.size(); 905 MCOpPredicateMap[Rec] = Entry; 906 } else 907 break; // No conditions on this operand at all 908 } 909 Cond = (Target.getName() + ClassName + "ValidateMCOperand(" + Op + 910 ", STI, " + utostr(Entry) + ")") 911 .str(); 912 } 913 // for all subcases of ResultOperand::K_Record: 914 IAP.addCond(Cond); 915 break; 916 } 917 case CodeGenInstAlias::ResultOperand::K_Imm: { 918 // Just because the alias has an immediate result, doesn't mean the 919 // MCInst will. An MCExpr could be present, for example. 920 IAP.addCond(Op + ".isImm()"); 921 922 Cond = Op + ".getImm() == " + itostr(CGA.ResultOperands[i].getImm()); 923 IAP.addCond(Cond); 924 break; 925 } 926 case CodeGenInstAlias::ResultOperand::K_Reg: 927 // If this is zero_reg, something's playing tricks we're not 928 // equipped to handle. 929 if (!CGA.ResultOperands[i].getRegister()) { 930 CantHandle = true; 931 break; 932 } 933 934 Cond = Op + ".getReg() == " + Target.getName().str() + "::" + 935 CGA.ResultOperands[i].getRegister()->getName().str(); 936 IAP.addCond(Cond); 937 break; 938 } 939 940 MIOpNum += RO.getMINumOperands(); 941 } 942 943 if (CantHandle) continue; 944 945 for (auto I = ReqFeatures.cbegin(); I != ReqFeatures.cend(); I++) { 946 Record *R = *I; 947 StringRef AsmCondString = R->getValueAsString("AssemblerCondString"); 948 949 // AsmCondString has syntax [!]F(,[!]F)* 950 SmallVector<StringRef, 4> Ops; 951 SplitString(AsmCondString, Ops, ","); 952 assert(!Ops.empty() && "AssemblerCondString cannot be empty"); 953 954 for (auto &Op : Ops) { 955 assert(!Op.empty() && "Empty operator"); 956 if (Op[0] == '!') 957 Cond = ("!STI.getFeatureBits()[" + Namespace + "::" + Op.substr(1) + 958 "]") 959 .str(); 960 else 961 Cond = 962 ("STI.getFeatureBits()[" + Namespace + "::" + Op + "]").str(); 963 IAP.addCond(Cond); 964 } 965 } 966 967 IAPrinterMap[Aliases.first].push_back(std::move(IAP)); 968 } 969 } 970 971 ////////////////////////////// 972 // Write out the printAliasInstr function 973 ////////////////////////////// 974 975 std::string Header; 976 raw_string_ostream HeaderO(Header); 977 978 HeaderO << "bool " << Target.getName() << ClassName 979 << "::printAliasInstr(const MCInst" 980 << " *MI, " << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "") 981 << "raw_ostream &OS) {\n"; 982 983 std::string Cases; 984 raw_string_ostream CasesO(Cases); 985 986 for (auto &Entry : IAPrinterMap) { 987 std::vector<IAPrinter> &IAPs = Entry.second; 988 std::vector<IAPrinter*> UniqueIAPs; 989 990 for (auto &LHS : IAPs) { 991 bool IsDup = false; 992 for (const auto &RHS : IAPs) { 993 if (&LHS != &RHS && LHS == RHS) { 994 IsDup = true; 995 break; 996 } 997 } 998 999 if (!IsDup) 1000 UniqueIAPs.push_back(&LHS); 1001 } 1002 1003 if (UniqueIAPs.empty()) continue; 1004 1005 CasesO.indent(2) << "case " << Entry.first << ":\n"; 1006 1007 for (IAPrinter *IAP : UniqueIAPs) { 1008 CasesO.indent(4); 1009 IAP->print(CasesO); 1010 CasesO << '\n'; 1011 } 1012 1013 CasesO.indent(4) << "return false;\n"; 1014 } 1015 1016 if (CasesO.str().empty()) { 1017 O << HeaderO.str(); 1018 O << " return false;\n"; 1019 O << "}\n\n"; 1020 O << "#endif // PRINT_ALIAS_INSTR\n"; 1021 return; 1022 } 1023 1024 if (!MCOpPredicates.empty()) 1025 O << "static bool " << Target.getName() << ClassName 1026 << "ValidateMCOperand(const MCOperand &MCOp,\n" 1027 << " const MCSubtargetInfo &STI,\n" 1028 << " unsigned PredicateIndex);\n"; 1029 1030 O << HeaderO.str(); 1031 O.indent(2) << "const char *AsmString;\n"; 1032 O.indent(2) << "switch (MI->getOpcode()) {\n"; 1033 O.indent(2) << "default: return false;\n"; 1034 O << CasesO.str(); 1035 O.indent(2) << "}\n\n"; 1036 1037 // Code that prints the alias, replacing the operands with the ones from the 1038 // MCInst. 1039 O << " unsigned I = 0;\n"; 1040 O << " while (AsmString[I] != ' ' && AsmString[I] != '\\t' &&\n"; 1041 O << " AsmString[I] != '$' && AsmString[I] != '\\0')\n"; 1042 O << " ++I;\n"; 1043 O << " OS << '\\t' << StringRef(AsmString, I);\n"; 1044 1045 O << " if (AsmString[I] != '\\0') {\n"; 1046 O << " if (AsmString[I] == ' ' || AsmString[I] == '\\t') {\n"; 1047 O << " OS << '\\t';\n"; 1048 O << " ++I;\n"; 1049 O << " }\n"; 1050 O << " do {\n"; 1051 O << " if (AsmString[I] == '$') {\n"; 1052 O << " ++I;\n"; 1053 O << " if (AsmString[I] == (char)0xff) {\n"; 1054 O << " ++I;\n"; 1055 O << " int OpIdx = AsmString[I++] - 1;\n"; 1056 O << " int PrintMethodIdx = AsmString[I++] - 1;\n"; 1057 O << " printCustomAliasOperand(MI, OpIdx, PrintMethodIdx, "; 1058 O << (PassSubtarget ? "STI, " : ""); 1059 O << "OS);\n"; 1060 O << " } else\n"; 1061 O << " printOperand(MI, unsigned(AsmString[I++]) - 1, "; 1062 O << (PassSubtarget ? "STI, " : ""); 1063 O << "OS);\n"; 1064 O << " } else {\n"; 1065 O << " OS << AsmString[I++];\n"; 1066 O << " }\n"; 1067 O << " } while (AsmString[I] != '\\0');\n"; 1068 O << " }\n\n"; 1069 1070 O << " return true;\n"; 1071 O << "}\n\n"; 1072 1073 ////////////////////////////// 1074 // Write out the printCustomAliasOperand function 1075 ////////////////////////////// 1076 1077 O << "void " << Target.getName() << ClassName << "::" 1078 << "printCustomAliasOperand(\n" 1079 << " const MCInst *MI, unsigned OpIdx,\n" 1080 << " unsigned PrintMethodIdx,\n" 1081 << (PassSubtarget ? " const MCSubtargetInfo &STI,\n" : "") 1082 << " raw_ostream &OS) {\n"; 1083 if (PrintMethods.empty()) 1084 O << " llvm_unreachable(\"Unknown PrintMethod kind\");\n"; 1085 else { 1086 O << " switch (PrintMethodIdx) {\n" 1087 << " default:\n" 1088 << " llvm_unreachable(\"Unknown PrintMethod kind\");\n" 1089 << " break;\n"; 1090 1091 for (unsigned i = 0; i < PrintMethods.size(); ++i) { 1092 O << " case " << i << ":\n" 1093 << " " << PrintMethods[i] << "(MI, OpIdx, " 1094 << (PassSubtarget ? "STI, " : "") << "OS);\n" 1095 << " break;\n"; 1096 } 1097 O << " }\n"; 1098 } 1099 O << "}\n\n"; 1100 1101 if (!MCOpPredicates.empty()) { 1102 O << "static bool " << Target.getName() << ClassName 1103 << "ValidateMCOperand(const MCOperand &MCOp,\n" 1104 << " const MCSubtargetInfo &STI,\n" 1105 << " unsigned PredicateIndex) {\n" 1106 << " switch (PredicateIndex) {\n" 1107 << " default:\n" 1108 << " llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n" 1109 << " break;\n"; 1110 1111 for (unsigned i = 0; i < MCOpPredicates.size(); ++i) { 1112 Init *MCOpPred = MCOpPredicates[i]->getValueInit("MCOperandPredicate"); 1113 if (CodeInit *SI = dyn_cast<CodeInit>(MCOpPred)) { 1114 O << " case " << i + 1 << ": {\n" 1115 << SI->getValue() << "\n" 1116 << " }\n"; 1117 } else 1118 llvm_unreachable("Unexpected MCOperandPredicate field!"); 1119 } 1120 O << " }\n" 1121 << "}\n\n"; 1122 } 1123 1124 O << "#endif // PRINT_ALIAS_INSTR\n"; 1125 } 1126 1127 AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) { 1128 Record *AsmWriter = Target.getAsmWriter(); 1129 unsigned Variant = AsmWriter->getValueAsInt("Variant"); 1130 1131 // Get the instruction numbering. 1132 NumberedInstructions = Target.getInstructionsByEnumValue(); 1133 1134 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) { 1135 const CodeGenInstruction *I = NumberedInstructions[i]; 1136 if (!I->AsmString.empty() && I->TheDef->getName() != "PHI") 1137 Instructions.emplace_back(*I, i, Variant); 1138 } 1139 } 1140 1141 void AsmWriterEmitter::run(raw_ostream &O) { 1142 EmitPrintInstruction(O); 1143 EmitGetRegisterName(O); 1144 EmitPrintAliasInstruction(O); 1145 } 1146 1147 namespace llvm { 1148 1149 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) { 1150 emitSourceFileHeader("Assembly Writer Source Fragment", OS); 1151 AsmWriterEmitter(RK).run(OS); 1152 } 1153 1154 } // end namespace llvm 1155