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/FormatVariadic.h" 33 #include "llvm/Support/MathExtras.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/TableGen/Error.h" 36 #include "llvm/TableGen/Record.h" 37 #include "llvm/TableGen/TableGenBackend.h" 38 #include <algorithm> 39 #include <cassert> 40 #include <cstddef> 41 #include <cstdint> 42 #include <deque> 43 #include <iterator> 44 #include <map> 45 #include <set> 46 #include <string> 47 #include <tuple> 48 #include <utility> 49 #include <vector> 50 51 using namespace llvm; 52 53 #define DEBUG_TYPE "asm-writer-emitter" 54 55 namespace { 56 57 class AsmWriterEmitter { 58 RecordKeeper &Records; 59 CodeGenTarget Target; 60 ArrayRef<const CodeGenInstruction *> NumberedInstructions; 61 std::vector<AsmWriterInst> Instructions; 62 63 public: 64 AsmWriterEmitter(RecordKeeper &R); 65 66 void run(raw_ostream &o); 67 68 private: 69 void EmitPrintInstruction(raw_ostream &o); 70 void EmitGetRegisterName(raw_ostream &o); 71 void EmitPrintAliasInstruction(raw_ostream &O); 72 73 void FindUniqueOperandCommands(std::vector<std::string> &UOC, 74 std::vector<std::vector<unsigned>> &InstIdxs, 75 std::vector<unsigned> &InstOpsUsed, 76 bool PassSubtarget) const; 77 }; 78 79 } // end anonymous namespace 80 81 static void PrintCases(std::vector<std::pair<std::string, 82 AsmWriterOperand>> &OpsToPrint, raw_ostream &O, 83 bool PassSubtarget) { 84 O << " case " << OpsToPrint.back().first << ":"; 85 AsmWriterOperand TheOp = OpsToPrint.back().second; 86 OpsToPrint.pop_back(); 87 88 // Check to see if any other operands are identical in this list, and if so, 89 // emit a case label for them. 90 for (unsigned i = OpsToPrint.size(); i != 0; --i) 91 if (OpsToPrint[i-1].second == TheOp) { 92 O << "\n case " << OpsToPrint[i-1].first << ":"; 93 OpsToPrint.erase(OpsToPrint.begin()+i-1); 94 } 95 96 // Finally, emit the code. 97 O << "\n " << TheOp.getCode(PassSubtarget); 98 O << "\n break;\n"; 99 } 100 101 /// EmitInstructions - Emit the last instruction in the vector and any other 102 /// instructions that are suitably similar to it. 103 static void EmitInstructions(std::vector<AsmWriterInst> &Insts, 104 raw_ostream &O, bool PassSubtarget) { 105 AsmWriterInst FirstInst = Insts.back(); 106 Insts.pop_back(); 107 108 std::vector<AsmWriterInst> SimilarInsts; 109 unsigned DifferingOperand = ~0; 110 for (unsigned i = Insts.size(); i != 0; --i) { 111 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst); 112 if (DiffOp != ~1U) { 113 if (DifferingOperand == ~0U) // First match! 114 DifferingOperand = DiffOp; 115 116 // If this differs in the same operand as the rest of the instructions in 117 // this class, move it to the SimilarInsts list. 118 if (DifferingOperand == DiffOp || DiffOp == ~0U) { 119 SimilarInsts.push_back(Insts[i-1]); 120 Insts.erase(Insts.begin()+i-1); 121 } 122 } 123 } 124 125 O << " case " << FirstInst.CGI->Namespace << "::" 126 << FirstInst.CGI->TheDef->getName() << ":\n"; 127 for (const AsmWriterInst &AWI : SimilarInsts) 128 O << " case " << AWI.CGI->Namespace << "::" 129 << AWI.CGI->TheDef->getName() << ":\n"; 130 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) { 131 if (i != DifferingOperand) { 132 // If the operand is the same for all instructions, just print it. 133 O << " " << FirstInst.Operands[i].getCode(PassSubtarget); 134 } else { 135 // If this is the operand that varies between all of the instructions, 136 // emit a switch for just this operand now. 137 O << " switch (MI->getOpcode()) {\n"; 138 O << " default: llvm_unreachable(\"Unexpected opcode.\");\n"; 139 std::vector<std::pair<std::string, AsmWriterOperand>> OpsToPrint; 140 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace.str() + "::" + 141 FirstInst.CGI->TheDef->getName().str(), 142 FirstInst.Operands[i])); 143 144 for (const AsmWriterInst &AWI : SimilarInsts) { 145 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace.str()+"::" + 146 AWI.CGI->TheDef->getName().str(), 147 AWI.Operands[i])); 148 } 149 std::reverse(OpsToPrint.begin(), OpsToPrint.end()); 150 while (!OpsToPrint.empty()) 151 PrintCases(OpsToPrint, O, PassSubtarget); 152 O << " }"; 153 } 154 O << "\n"; 155 } 156 O << " break;\n"; 157 } 158 159 void AsmWriterEmitter:: 160 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands, 161 std::vector<std::vector<unsigned>> &InstIdxs, 162 std::vector<unsigned> &InstOpsUsed, 163 bool PassSubtarget) const { 164 // This vector parallels UniqueOperandCommands, keeping track of which 165 // instructions each case are used for. It is a comma separated string of 166 // enums. 167 std::vector<std::string> InstrsForCase; 168 InstrsForCase.resize(UniqueOperandCommands.size()); 169 InstOpsUsed.assign(UniqueOperandCommands.size(), 0); 170 171 for (size_t i = 0, e = Instructions.size(); i != e; ++i) { 172 const AsmWriterInst &Inst = Instructions[i]; 173 if (Inst.Operands.empty()) 174 continue; // Instruction already done. 175 176 std::string Command = " "+Inst.Operands[0].getCode(PassSubtarget)+"\n"; 177 178 // Check to see if we already have 'Command' in UniqueOperandCommands. 179 // If not, add it. 180 auto I = llvm::find(UniqueOperandCommands, Command); 181 if (I != UniqueOperandCommands.end()) { 182 size_t idx = I - UniqueOperandCommands.begin(); 183 InstrsForCase[idx] += ", "; 184 InstrsForCase[idx] += Inst.CGI->TheDef->getName(); 185 InstIdxs[idx].push_back(i); 186 } else { 187 UniqueOperandCommands.push_back(std::move(Command)); 188 InstrsForCase.push_back(std::string(Inst.CGI->TheDef->getName())); 189 InstIdxs.emplace_back(); 190 InstIdxs.back().push_back(i); 191 192 // This command matches one operand so far. 193 InstOpsUsed.push_back(1); 194 } 195 } 196 197 // For each entry of UniqueOperandCommands, there is a set of instructions 198 // that uses it. If the next command of all instructions in the set are 199 // identical, fold it into the command. 200 for (size_t CommandIdx = 0, e = UniqueOperandCommands.size(); 201 CommandIdx != e; ++CommandIdx) { 202 203 const auto &Idxs = InstIdxs[CommandIdx]; 204 205 for (unsigned Op = 1; ; ++Op) { 206 // Find the first instruction in the set. 207 const AsmWriterInst &FirstInst = Instructions[Idxs.front()]; 208 // If this instruction has no more operands, we isn't anything to merge 209 // into this command. 210 if (FirstInst.Operands.size() == Op) 211 break; 212 213 // Otherwise, scan to see if all of the other instructions in this command 214 // set share the operand. 215 if (std::any_of(Idxs.begin()+1, Idxs.end(), 216 [&](unsigned Idx) { 217 const AsmWriterInst &OtherInst = Instructions[Idx]; 218 return OtherInst.Operands.size() == Op || 219 OtherInst.Operands[Op] != FirstInst.Operands[Op]; 220 })) 221 break; 222 223 // Okay, everything in this command set has the same next operand. Add it 224 // to UniqueOperandCommands and remember that it was consumed. 225 std::string Command = " " + 226 FirstInst.Operands[Op].getCode(PassSubtarget) + "\n"; 227 228 UniqueOperandCommands[CommandIdx] += Command; 229 InstOpsUsed[CommandIdx]++; 230 } 231 } 232 233 // Prepend some of the instructions each case is used for onto the case val. 234 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) { 235 std::string Instrs = InstrsForCase[i]; 236 if (Instrs.size() > 70) { 237 Instrs.erase(Instrs.begin()+70, Instrs.end()); 238 Instrs += "..."; 239 } 240 241 if (!Instrs.empty()) 242 UniqueOperandCommands[i] = " // " + Instrs + "\n" + 243 UniqueOperandCommands[i]; 244 } 245 } 246 247 static void UnescapeString(std::string &Str) { 248 for (unsigned i = 0; i != Str.size(); ++i) { 249 if (Str[i] == '\\' && i != Str.size()-1) { 250 switch (Str[i+1]) { 251 default: continue; // Don't execute the code after the switch. 252 case 'a': Str[i] = '\a'; break; 253 case 'b': Str[i] = '\b'; break; 254 case 'e': Str[i] = 27; break; 255 case 'f': Str[i] = '\f'; break; 256 case 'n': Str[i] = '\n'; break; 257 case 'r': Str[i] = '\r'; break; 258 case 't': Str[i] = '\t'; break; 259 case 'v': Str[i] = '\v'; break; 260 case '"': Str[i] = '\"'; break; 261 case '\'': Str[i] = '\''; break; 262 case '\\': Str[i] = '\\'; break; 263 } 264 // Nuke the second character. 265 Str.erase(Str.begin()+i+1); 266 } 267 } 268 } 269 270 /// EmitPrintInstruction - Generate the code for the "printInstruction" method 271 /// implementation. Destroys all instances of AsmWriterInst information, by 272 /// clearing the Instructions vector. 273 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) { 274 Record *AsmWriter = Target.getAsmWriter(); 275 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName"); 276 bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget"); 277 278 O << "/// printInstruction - This method is automatically generated by " 279 "tablegen\n" 280 "/// from the instruction set description.\n" 281 "void " 282 << Target.getName() << ClassName 283 << "::printInstruction(const MCInst *MI, uint64_t Address, " 284 << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "") 285 << "raw_ostream &O) {\n"; 286 287 // Build an aggregate string, and build a table of offsets into it. 288 SequenceToOffsetTable<std::string> StringTable; 289 290 /// OpcodeInfo - This encodes the index of the string to use for the first 291 /// chunk of the output as well as indices used for operand printing. 292 std::vector<uint64_t> OpcodeInfo(NumberedInstructions.size()); 293 const unsigned OpcodeInfoBits = 64; 294 295 // Add all strings to the string table upfront so it can generate an optimized 296 // representation. 297 for (AsmWriterInst &AWI : Instructions) { 298 if (AWI.Operands[0].OperandType == 299 AsmWriterOperand::isLiteralTextOperand && 300 !AWI.Operands[0].Str.empty()) { 301 std::string Str = AWI.Operands[0].Str; 302 UnescapeString(Str); 303 StringTable.add(Str); 304 } 305 } 306 307 StringTable.layout(); 308 309 unsigned MaxStringIdx = 0; 310 for (AsmWriterInst &AWI : Instructions) { 311 unsigned Idx; 312 if (AWI.Operands[0].OperandType != AsmWriterOperand::isLiteralTextOperand || 313 AWI.Operands[0].Str.empty()) { 314 // Something handled by the asmwriter printer, but with no leading string. 315 Idx = StringTable.get(""); 316 } else { 317 std::string Str = AWI.Operands[0].Str; 318 UnescapeString(Str); 319 Idx = StringTable.get(Str); 320 MaxStringIdx = std::max(MaxStringIdx, Idx); 321 322 // Nuke the string from the operand list. It is now handled! 323 AWI.Operands.erase(AWI.Operands.begin()); 324 } 325 326 // Bias offset by one since we want 0 as a sentinel. 327 OpcodeInfo[AWI.CGIIndex] = Idx+1; 328 } 329 330 // Figure out how many bits we used for the string index. 331 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2); 332 333 // To reduce code size, we compactify common instructions into a few bits 334 // in the opcode-indexed table. 335 unsigned BitsLeft = OpcodeInfoBits-AsmStrBits; 336 337 std::vector<std::vector<std::string>> TableDrivenOperandPrinters; 338 339 while (true) { 340 std::vector<std::string> UniqueOperandCommands; 341 std::vector<std::vector<unsigned>> InstIdxs; 342 std::vector<unsigned> NumInstOpsHandled; 343 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs, 344 NumInstOpsHandled, PassSubtarget); 345 346 // If we ran out of operands to print, we're done. 347 if (UniqueOperandCommands.empty()) break; 348 349 // Compute the number of bits we need to represent these cases, this is 350 // ceil(log2(numentries)). 351 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size()); 352 353 // If we don't have enough bits for this operand, don't include it. 354 if (NumBits > BitsLeft) { 355 LLVM_DEBUG(errs() << "Not enough bits to densely encode " << NumBits 356 << " more bits\n"); 357 break; 358 } 359 360 // Otherwise, we can include this in the initial lookup table. Add it in. 361 for (size_t i = 0, e = InstIdxs.size(); i != e; ++i) { 362 unsigned NumOps = NumInstOpsHandled[i]; 363 for (unsigned Idx : InstIdxs[i]) { 364 OpcodeInfo[Instructions[Idx].CGIIndex] |= 365 (uint64_t)i << (OpcodeInfoBits-BitsLeft); 366 // Remove the info about this operand from the instruction. 367 AsmWriterInst &Inst = Instructions[Idx]; 368 if (!Inst.Operands.empty()) { 369 assert(NumOps <= Inst.Operands.size() && 370 "Can't remove this many ops!"); 371 Inst.Operands.erase(Inst.Operands.begin(), 372 Inst.Operands.begin()+NumOps); 373 } 374 } 375 } 376 BitsLeft -= NumBits; 377 378 // Remember the handlers for this set of operands. 379 TableDrivenOperandPrinters.push_back(std::move(UniqueOperandCommands)); 380 } 381 382 // Emit the string table itself. 383 StringTable.emitStringLiteralDef(O, " static const char AsmStrs[]"); 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 = std::string(Reg.TheDef->getValueAsString("AsmName")); 511 if (AsmName.empty()) 512 AsmName = std::string(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 = std::string(AltNames[Idx]); 532 } 533 } 534 StringTable.add(AsmName); 535 } 536 537 StringTable.layout(); 538 StringTable.emitStringLiteralDef(O, Twine(" static const char AsmStrs") + 539 AltName + "[]"); 540 541 O << " static const " << getMinimalTypeForRange(StringTable.size() - 1, 32) 542 << " RegAsmOffset" << AltName << "[] = {"; 543 for (unsigned i = 0, e = Registers.size(); i != e; ++i) { 544 if ((i % 14) == 0) 545 O << "\n "; 546 O << StringTable.get(AsmNames[i]) << ", "; 547 } 548 O << "\n };\n" 549 << "\n"; 550 } 551 552 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) { 553 Record *AsmWriter = Target.getAsmWriter(); 554 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName"); 555 const auto &Registers = Target.getRegBank().getRegisters(); 556 const std::vector<Record*> &AltNameIndices = Target.getRegAltNameIndices(); 557 bool hasAltNames = AltNameIndices.size() > 1; 558 StringRef Namespace = Registers.front().TheDef->getValueAsString("Namespace"); 559 560 O << 561 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n" 562 "/// from the register set description. This returns the assembler name\n" 563 "/// for the specified register.\n" 564 "const char *" << Target.getName() << ClassName << "::"; 565 if (hasAltNames) 566 O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n"; 567 else 568 O << "getRegisterName(unsigned RegNo) {\n"; 569 O << " assert(RegNo && RegNo < " << (Registers.size()+1) 570 << " && \"Invalid register number!\");\n" 571 << "\n"; 572 573 if (hasAltNames) { 574 for (const Record *R : AltNameIndices) 575 emitRegisterNameString(O, R->getName(), Registers); 576 } else 577 emitRegisterNameString(O, "", Registers); 578 579 if (hasAltNames) { 580 O << " switch(AltIdx) {\n" 581 << " default: llvm_unreachable(\"Invalid register alt name index!\");\n"; 582 for (const Record *R : AltNameIndices) { 583 StringRef AltName = R->getName(); 584 O << " case "; 585 if (!Namespace.empty()) 586 O << Namespace << "::"; 587 O << AltName << ":\n"; 588 if (R->isValueUnset("FallbackRegAltNameIndex")) 589 O << " assert(*(AsmStrs" << AltName << "+RegAsmOffset" << AltName 590 << "[RegNo-1]) &&\n" 591 << " \"Invalid alt name index for register!\");\n"; 592 else { 593 O << " if (!*(AsmStrs" << AltName << "+RegAsmOffset" << AltName 594 << "[RegNo-1]))\n" 595 << " return getRegisterName(RegNo, "; 596 if (!Namespace.empty()) 597 O << Namespace << "::"; 598 O << R->getValueAsDef("FallbackRegAltNameIndex")->getName() << ");\n"; 599 } 600 O << " return AsmStrs" << AltName << "+RegAsmOffset" << AltName 601 << "[RegNo-1];\n"; 602 } 603 O << " }\n"; 604 } else { 605 O << " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n" 606 << " \"Invalid alt name index for register!\");\n" 607 << " return AsmStrs+RegAsmOffset[RegNo-1];\n"; 608 } 609 O << "}\n"; 610 } 611 612 namespace { 613 614 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if 615 // they both have the same conditionals. In which case, we cannot print out the 616 // alias for that pattern. 617 class IAPrinter { 618 std::map<StringRef, std::pair<int, int>> OpMap; 619 620 std::vector<std::string> Conds; 621 622 std::string Result; 623 std::string AsmString; 624 625 unsigned NumMIOps; 626 627 public: 628 IAPrinter(std::string R, std::string AS, unsigned NumMIOps) 629 : Result(std::move(R)), AsmString(std::move(AS)), NumMIOps(NumMIOps) {} 630 631 void addCond(std::string C) { Conds.push_back(std::move(C)); } 632 ArrayRef<std::string> getConds() const { return Conds; } 633 size_t getCondCount() const { return Conds.size(); } 634 635 void addOperand(StringRef Op, int OpIdx, int PrintMethodIdx = -1) { 636 assert(OpIdx >= 0 && OpIdx < 0xFE && "Idx out of range"); 637 assert(PrintMethodIdx >= -1 && PrintMethodIdx < 0xFF && 638 "Idx out of range"); 639 OpMap[Op] = std::make_pair(OpIdx, PrintMethodIdx); 640 } 641 642 unsigned getNumMIOps() { return NumMIOps; } 643 644 StringRef getResult() { return Result; } 645 646 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); } 647 int getOpIndex(StringRef Op) { return OpMap[Op].first; } 648 std::pair<int, int> &getOpData(StringRef Op) { return OpMap[Op]; } 649 650 std::pair<StringRef, StringRef::iterator> parseName(StringRef::iterator Start, 651 StringRef::iterator End) { 652 StringRef::iterator I = Start; 653 StringRef::iterator Next; 654 if (*I == '{') { 655 // ${some_name} 656 Start = ++I; 657 while (I != End && *I != '}') 658 ++I; 659 Next = I; 660 // eat the final '}' 661 if (Next != End) 662 ++Next; 663 } else { 664 // $name, just eat the usual suspects. 665 while (I != End && 666 ((*I >= 'a' && *I <= 'z') || (*I >= 'A' && *I <= 'Z') || 667 (*I >= '0' && *I <= '9') || *I == '_')) 668 ++I; 669 Next = I; 670 } 671 672 return std::make_pair(StringRef(Start, I - Start), Next); 673 } 674 675 std::string formatAliasString(uint32_t &UnescapedSize) { 676 // Directly mangle mapped operands into the string. Each operand is 677 // identified by a '$' sign followed by a byte identifying the number of the 678 // operand. We add one to the index to avoid zero bytes. 679 StringRef ASM(AsmString); 680 std::string OutString; 681 raw_string_ostream OS(OutString); 682 for (StringRef::iterator I = ASM.begin(), E = ASM.end(); I != E;) { 683 OS << *I; 684 ++UnescapedSize; 685 if (*I == '$') { 686 StringRef Name; 687 std::tie(Name, I) = parseName(++I, E); 688 assert(isOpMapped(Name) && "Unmapped operand!"); 689 690 int OpIndex, PrintIndex; 691 std::tie(OpIndex, PrintIndex) = getOpData(Name); 692 if (PrintIndex == -1) { 693 // Can use the default printOperand route. 694 OS << format("\\x%02X", (unsigned char)OpIndex + 1); 695 ++UnescapedSize; 696 } else { 697 // 3 bytes if a PrintMethod is needed: 0xFF, the MCInst operand 698 // number, and which of our pre-detected Methods to call. 699 OS << format("\\xFF\\x%02X\\x%02X", OpIndex + 1, PrintIndex + 1); 700 UnescapedSize += 3; 701 } 702 } else { 703 ++I; 704 } 705 } 706 707 OS.flush(); 708 return OutString; 709 } 710 711 bool operator==(const IAPrinter &RHS) const { 712 if (NumMIOps != RHS.NumMIOps) 713 return false; 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 AliasMap[getQualifiedName(DI->getOperatorAsDef(R->getLoc()))].insert( 779 std::make_pair(CodeGenInstAlias(R, Target), Priority)); 780 } 781 782 // A map of which conditions need to be met for each instruction operand 783 // before it can be matched to the mnemonic. 784 std::map<std::string, std::vector<IAPrinter>> IAPrinterMap; 785 786 std::vector<std::string> PrintMethods; 787 788 // A list of MCOperandPredicates for all operands in use, and the reverse map 789 std::vector<const Record*> MCOpPredicates; 790 DenseMap<const Record*, unsigned> MCOpPredicateMap; 791 792 for (auto &Aliases : AliasMap) { 793 // Collection of instruction alias rules. May contain ambiguous rules. 794 std::vector<IAPrinter> IAPs; 795 796 for (auto &Alias : Aliases.second) { 797 const CodeGenInstAlias &CGA = Alias.first; 798 unsigned LastOpNo = CGA.ResultInstOperandIndex.size(); 799 std::string FlatInstAsmString = 800 CodeGenInstruction::FlattenAsmStringVariants(CGA.ResultInst->AsmString, 801 Variant); 802 unsigned NumResultOps = CountNumOperands(FlatInstAsmString, Variant); 803 804 std::string FlatAliasAsmString = 805 CodeGenInstruction::FlattenAsmStringVariants(CGA.AsmString, Variant); 806 807 // Don't emit the alias if it has more operands than what it's aliasing. 808 if (NumResultOps < CountNumOperands(FlatAliasAsmString, Variant)) 809 continue; 810 811 StringRef Namespace = Target.getName(); 812 unsigned NumMIOps = 0; 813 for (auto &ResultInstOpnd : CGA.ResultInst->Operands) 814 NumMIOps += ResultInstOpnd.MINumOperands; 815 816 IAPrinter IAP(CGA.Result->getAsString(), FlatAliasAsmString, NumMIOps); 817 818 bool CantHandle = false; 819 820 unsigned MIOpNum = 0; 821 for (unsigned i = 0, e = LastOpNo; i != e; ++i) { 822 // Skip over tied operands as they're not part of an alias declaration. 823 auto &Operands = CGA.ResultInst->Operands; 824 while (true) { 825 unsigned OpNum = Operands.getSubOperandNumber(MIOpNum).first; 826 if (Operands[OpNum].MINumOperands == 1 && 827 Operands[OpNum].getTiedRegister() != -1) { 828 // Tied operands of different RegisterClass should be explicit within 829 // an instruction's syntax and so cannot be skipped. 830 int TiedOpNum = Operands[OpNum].getTiedRegister(); 831 if (Operands[OpNum].Rec->getName() == 832 Operands[TiedOpNum].Rec->getName()) { 833 ++MIOpNum; 834 continue; 835 } 836 } 837 break; 838 } 839 840 // Ignore unchecked result operands. 841 while (IAP.getCondCount() < MIOpNum) 842 IAP.addCond("AliasPatternCond::K_Ignore, 0"); 843 844 const CodeGenInstAlias::ResultOperand &RO = CGA.ResultOperands[i]; 845 846 switch (RO.Kind) { 847 case CodeGenInstAlias::ResultOperand::K_Record: { 848 const Record *Rec = RO.getRecord(); 849 StringRef ROName = RO.getName(); 850 int PrintMethodIdx = -1; 851 852 // These two may have a PrintMethod, which we want to record (if it's 853 // the first time we've seen it) and provide an index for the aliasing 854 // code to use. 855 if (Rec->isSubClassOf("RegisterOperand") || 856 Rec->isSubClassOf("Operand")) { 857 StringRef PrintMethod = Rec->getValueAsString("PrintMethod"); 858 if (PrintMethod != "" && PrintMethod != "printOperand") { 859 PrintMethodIdx = 860 llvm::find(PrintMethods, PrintMethod) - PrintMethods.begin(); 861 if (static_cast<unsigned>(PrintMethodIdx) == PrintMethods.size()) 862 PrintMethods.push_back(std::string(PrintMethod)); 863 } 864 } 865 866 if (Rec->isSubClassOf("RegisterOperand")) 867 Rec = Rec->getValueAsDef("RegClass"); 868 if (Rec->isSubClassOf("RegisterClass")) { 869 if (!IAP.isOpMapped(ROName)) { 870 IAP.addOperand(ROName, MIOpNum, PrintMethodIdx); 871 Record *R = CGA.ResultOperands[i].getRecord(); 872 if (R->isSubClassOf("RegisterOperand")) 873 R = R->getValueAsDef("RegClass"); 874 IAP.addCond(std::string( 875 formatv("AliasPatternCond::K_RegClass, {0}::{1}RegClassID", 876 Namespace, R->getName()))); 877 } else { 878 IAP.addCond(std::string(formatv( 879 "AliasPatternCond::K_TiedReg, {0}", IAP.getOpIndex(ROName)))); 880 } 881 } else { 882 // Assume all printable operands are desired for now. This can be 883 // overridden in the InstAlias instantiation if necessary. 884 IAP.addOperand(ROName, MIOpNum, PrintMethodIdx); 885 886 // There might be an additional predicate on the MCOperand 887 unsigned Entry = MCOpPredicateMap[Rec]; 888 if (!Entry) { 889 if (!Rec->isValueUnset("MCOperandPredicate")) { 890 MCOpPredicates.push_back(Rec); 891 Entry = MCOpPredicates.size(); 892 MCOpPredicateMap[Rec] = Entry; 893 } else 894 break; // No conditions on this operand at all 895 } 896 IAP.addCond( 897 std::string(formatv("AliasPatternCond::K_Custom, {0}", Entry))); 898 } 899 break; 900 } 901 case CodeGenInstAlias::ResultOperand::K_Imm: { 902 // Just because the alias has an immediate result, doesn't mean the 903 // MCInst will. An MCExpr could be present, for example. 904 auto Imm = CGA.ResultOperands[i].getImm(); 905 int32_t Imm32 = int32_t(Imm); 906 if (Imm != Imm32) 907 PrintFatalError("Matching an alias with an immediate out of the " 908 "range of int32_t is not supported"); 909 IAP.addCond(std::string( 910 formatv("AliasPatternCond::K_Imm, uint32_t({0})", Imm32))); 911 break; 912 } 913 case CodeGenInstAlias::ResultOperand::K_Reg: 914 // If this is zero_reg, something's playing tricks we're not 915 // equipped to handle. 916 if (!CGA.ResultOperands[i].getRegister()) { 917 CantHandle = true; 918 break; 919 } 920 921 StringRef Reg = CGA.ResultOperands[i].getRegister()->getName(); 922 IAP.addCond(std::string( 923 formatv("AliasPatternCond::K_Reg, {0}::{1}", Namespace, Reg))); 924 break; 925 } 926 927 MIOpNum += RO.getMINumOperands(); 928 } 929 930 if (CantHandle) continue; 931 932 std::vector<Record *> ReqFeatures; 933 if (PassSubtarget) { 934 // We only consider ReqFeatures predicates if PassSubtarget 935 std::vector<Record *> RF = 936 CGA.TheDef->getValueAsListOfDefs("Predicates"); 937 copy_if(RF, std::back_inserter(ReqFeatures), [](Record *R) { 938 return R->getValueAsBit("AssemblerMatcherPredicate"); 939 }); 940 } 941 942 for (auto I = ReqFeatures.cbegin(); I != ReqFeatures.cend(); I++) { 943 Record *R = *I; 944 StringRef AsmCondString = R->getValueAsString("AssemblerCondString"); 945 946 // AsmCondString has syntax [!]F(,[!]F)* 947 SmallVector<StringRef, 4> Ops; 948 SplitString(AsmCondString, Ops, ","); 949 assert(!Ops.empty() && "AssemblerCondString cannot be empty"); 950 951 for (StringRef Op : Ops) { 952 assert(!Op.empty() && "Empty operator"); 953 bool IsNeg = Op[0] == '!'; 954 StringRef Feature = Op.drop_front(IsNeg ? 1 : 0); 955 IAP.addCond( 956 std::string(formatv("AliasPatternCond::K_{0}Feature, {1}::{2}", 957 IsNeg ? "Neg" : "", Namespace, Feature))); 958 } 959 } 960 961 IAPrinterMap[Aliases.first].push_back(std::move(IAP)); 962 } 963 } 964 965 ////////////////////////////// 966 // Write out the printAliasInstr function 967 ////////////////////////////// 968 969 std::string Header; 970 raw_string_ostream HeaderO(Header); 971 972 HeaderO << "bool " << Target.getName() << ClassName 973 << "::printAliasInstr(const MCInst" 974 << " *MI, " << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "") 975 << "raw_ostream &OS) {\n"; 976 977 std::string PatternsForOpcode; 978 raw_string_ostream OpcodeO(PatternsForOpcode); 979 980 unsigned PatternCount = 0; 981 std::string Patterns; 982 raw_string_ostream PatternO(Patterns); 983 984 unsigned CondCount = 0; 985 std::string Conds; 986 raw_string_ostream CondO(Conds); 987 988 // All flattened alias strings. 989 std::map<std::string, uint32_t> AsmStringOffsets; 990 std::vector<std::pair<uint32_t, std::string>> AsmStrings; 991 size_t AsmStringsSize = 0; 992 993 // Iterate over the opcodes in enum order so they are sorted by opcode for 994 // binary search. 995 for (const CodeGenInstruction *Inst : NumberedInstructions) { 996 auto It = IAPrinterMap.find(getQualifiedName(Inst->TheDef)); 997 if (It == IAPrinterMap.end()) 998 continue; 999 std::vector<IAPrinter> &IAPs = It->second; 1000 std::vector<IAPrinter*> UniqueIAPs; 1001 1002 // Remove any ambiguous alias rules. 1003 for (auto &LHS : IAPs) { 1004 bool IsDup = false; 1005 for (const auto &RHS : IAPs) { 1006 if (&LHS != &RHS && LHS == RHS) { 1007 IsDup = true; 1008 break; 1009 } 1010 } 1011 1012 if (!IsDup) 1013 UniqueIAPs.push_back(&LHS); 1014 } 1015 1016 if (UniqueIAPs.empty()) continue; 1017 1018 unsigned PatternStart = PatternCount; 1019 1020 // Insert the pattern start and opcode in the pattern list for debugging. 1021 PatternO << formatv(" // {0} - {1}\n", It->first, PatternStart); 1022 1023 for (IAPrinter *IAP : UniqueIAPs) { 1024 // Start each condition list with a comment of the resulting pattern that 1025 // we're trying to match. 1026 unsigned CondStart = CondCount; 1027 CondO << formatv(" // {0} - {1}\n", IAP->getResult(), CondStart); 1028 for (const auto &Cond : IAP->getConds()) 1029 CondO << " {" << Cond << "},\n"; 1030 CondCount += IAP->getCondCount(); 1031 1032 // After operands have been examined, re-encode the alias string with 1033 // escapes indicating how operands should be printed. 1034 uint32_t UnescapedSize = 0; 1035 std::string EncodedAsmString = IAP->formatAliasString(UnescapedSize); 1036 auto Insertion = 1037 AsmStringOffsets.insert({EncodedAsmString, AsmStringsSize}); 1038 if (Insertion.second) { 1039 // If the string is new, add it to the vector. 1040 AsmStrings.push_back({AsmStringsSize, EncodedAsmString}); 1041 AsmStringsSize += UnescapedSize + 1; 1042 } 1043 unsigned AsmStrOffset = Insertion.first->second; 1044 1045 PatternO << formatv(" {{{0}, {1}, {2}, {3} },\n", AsmStrOffset, 1046 CondStart, IAP->getNumMIOps(), IAP->getCondCount()); 1047 ++PatternCount; 1048 } 1049 1050 OpcodeO << formatv(" {{{0}, {1}, {2} },\n", It->first, PatternStart, 1051 PatternCount - PatternStart); 1052 } 1053 1054 if (OpcodeO.str().empty()) { 1055 O << HeaderO.str(); 1056 O << " return false;\n"; 1057 O << "}\n\n"; 1058 O << "#endif // PRINT_ALIAS_INSTR\n"; 1059 return; 1060 } 1061 1062 // Forward declare the validation method if needed. 1063 if (!MCOpPredicates.empty()) 1064 O << "static bool " << Target.getName() << ClassName 1065 << "ValidateMCOperand(const MCOperand &MCOp,\n" 1066 << " const MCSubtargetInfo &STI,\n" 1067 << " unsigned PredicateIndex);\n"; 1068 1069 O << HeaderO.str(); 1070 O.indent(2) << "static const PatternsForOpcode OpToPatterns[] = {\n"; 1071 O << OpcodeO.str(); 1072 O.indent(2) << "};\n\n"; 1073 O.indent(2) << "static const AliasPattern Patterns[] = {\n"; 1074 O << PatternO.str(); 1075 O.indent(2) << "};\n\n"; 1076 O.indent(2) << "static const AliasPatternCond Conds[] = {\n"; 1077 O << CondO.str(); 1078 O.indent(2) << "};\n\n"; 1079 O.indent(2) << "static const char AsmStrings[] =\n"; 1080 for (const auto &P : AsmStrings) { 1081 O.indent(4) << "/* " << P.first << " */ \"" << P.second << "\\0\"\n"; 1082 } 1083 1084 O.indent(2) << ";\n\n"; 1085 1086 // Assert that the opcode table is sorted. Use a static local constructor to 1087 // ensure that the check only happens once on first run. 1088 O << "#ifndef NDEBUG\n"; 1089 O.indent(2) << "static struct SortCheck {\n"; 1090 O.indent(2) << " SortCheck(ArrayRef<PatternsForOpcode> OpToPatterns) {\n"; 1091 O.indent(2) << " assert(std::is_sorted(\n"; 1092 O.indent(2) << " OpToPatterns.begin(), OpToPatterns.end(),\n"; 1093 O.indent(2) << " [](const PatternsForOpcode &L, const " 1094 "PatternsForOpcode &R) {\n"; 1095 O.indent(2) << " return L.Opcode < R.Opcode;\n"; 1096 O.indent(2) << " }) &&\n"; 1097 O.indent(2) << " \"tablegen failed to sort opcode patterns\");\n"; 1098 O.indent(2) << " }\n"; 1099 O.indent(2) << "} sortCheckVar(OpToPatterns);\n"; 1100 O << "#endif\n\n"; 1101 1102 O.indent(2) << "AliasMatchingData M {\n"; 1103 O.indent(2) << " makeArrayRef(OpToPatterns),\n"; 1104 O.indent(2) << " makeArrayRef(Patterns),\n"; 1105 O.indent(2) << " makeArrayRef(Conds),\n"; 1106 O.indent(2) << " StringRef(AsmStrings, array_lengthof(AsmStrings)),\n"; 1107 if (MCOpPredicates.empty()) 1108 O.indent(2) << " nullptr,\n"; 1109 else 1110 O.indent(2) << " &" << Target.getName() << ClassName << "ValidateMCOperand,\n"; 1111 O.indent(2) << "};\n"; 1112 1113 O.indent(2) << "const char *AsmString = matchAliasPatterns(MI, " 1114 << (PassSubtarget ? "&STI" : "nullptr") << ", M);\n"; 1115 O.indent(2) << "if (!AsmString) return false;\n\n"; 1116 1117 // Code that prints the alias, replacing the operands with the ones from the 1118 // MCInst. 1119 O << " unsigned I = 0;\n"; 1120 O << " while (AsmString[I] != ' ' && AsmString[I] != '\\t' &&\n"; 1121 O << " AsmString[I] != '$' && AsmString[I] != '\\0')\n"; 1122 O << " ++I;\n"; 1123 O << " OS << '\\t' << StringRef(AsmString, I);\n"; 1124 1125 O << " if (AsmString[I] != '\\0') {\n"; 1126 O << " if (AsmString[I] == ' ' || AsmString[I] == '\\t') {\n"; 1127 O << " OS << '\\t';\n"; 1128 O << " ++I;\n"; 1129 O << " }\n"; 1130 O << " do {\n"; 1131 O << " if (AsmString[I] == '$') {\n"; 1132 O << " ++I;\n"; 1133 O << " if (AsmString[I] == (char)0xff) {\n"; 1134 O << " ++I;\n"; 1135 O << " int OpIdx = AsmString[I++] - 1;\n"; 1136 O << " int PrintMethodIdx = AsmString[I++] - 1;\n"; 1137 O << " printCustomAliasOperand(MI, OpIdx, PrintMethodIdx, "; 1138 O << (PassSubtarget ? "STI, " : ""); 1139 O << "OS);\n"; 1140 O << " } else\n"; 1141 O << " printOperand(MI, unsigned(AsmString[I++]) - 1, "; 1142 O << (PassSubtarget ? "STI, " : ""); 1143 O << "OS);\n"; 1144 O << " } else {\n"; 1145 O << " OS << AsmString[I++];\n"; 1146 O << " }\n"; 1147 O << " } while (AsmString[I] != '\\0');\n"; 1148 O << " }\n\n"; 1149 1150 O << " return true;\n"; 1151 O << "}\n\n"; 1152 1153 ////////////////////////////// 1154 // Write out the printCustomAliasOperand function 1155 ////////////////////////////// 1156 1157 O << "void " << Target.getName() << ClassName << "::" 1158 << "printCustomAliasOperand(\n" 1159 << " const MCInst *MI, unsigned OpIdx,\n" 1160 << " unsigned PrintMethodIdx,\n" 1161 << (PassSubtarget ? " const MCSubtargetInfo &STI,\n" : "") 1162 << " raw_ostream &OS) {\n"; 1163 if (PrintMethods.empty()) 1164 O << " llvm_unreachable(\"Unknown PrintMethod kind\");\n"; 1165 else { 1166 O << " switch (PrintMethodIdx) {\n" 1167 << " default:\n" 1168 << " llvm_unreachable(\"Unknown PrintMethod kind\");\n" 1169 << " break;\n"; 1170 1171 for (unsigned i = 0; i < PrintMethods.size(); ++i) { 1172 O << " case " << i << ":\n" 1173 << " " << PrintMethods[i] << "(MI, OpIdx, " 1174 << (PassSubtarget ? "STI, " : "") << "OS);\n" 1175 << " break;\n"; 1176 } 1177 O << " }\n"; 1178 } 1179 O << "}\n\n"; 1180 1181 if (!MCOpPredicates.empty()) { 1182 O << "static bool " << Target.getName() << ClassName 1183 << "ValidateMCOperand(const MCOperand &MCOp,\n" 1184 << " const MCSubtargetInfo &STI,\n" 1185 << " unsigned PredicateIndex) {\n" 1186 << " switch (PredicateIndex) {\n" 1187 << " default:\n" 1188 << " llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n" 1189 << " break;\n"; 1190 1191 for (unsigned i = 0; i < MCOpPredicates.size(); ++i) { 1192 Init *MCOpPred = MCOpPredicates[i]->getValueInit("MCOperandPredicate"); 1193 if (CodeInit *SI = dyn_cast<CodeInit>(MCOpPred)) { 1194 O << " case " << i + 1 << ": {\n" 1195 << SI->getValue() << "\n" 1196 << " }\n"; 1197 } else 1198 llvm_unreachable("Unexpected MCOperandPredicate field!"); 1199 } 1200 O << " }\n" 1201 << "}\n\n"; 1202 } 1203 1204 O << "#endif // PRINT_ALIAS_INSTR\n"; 1205 } 1206 1207 AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) { 1208 Record *AsmWriter = Target.getAsmWriter(); 1209 unsigned Variant = AsmWriter->getValueAsInt("Variant"); 1210 1211 // Get the instruction numbering. 1212 NumberedInstructions = Target.getInstructionsByEnumValue(); 1213 1214 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) { 1215 const CodeGenInstruction *I = NumberedInstructions[i]; 1216 if (!I->AsmString.empty() && I->TheDef->getName() != "PHI") 1217 Instructions.emplace_back(*I, i, Variant); 1218 } 1219 } 1220 1221 void AsmWriterEmitter::run(raw_ostream &O) { 1222 EmitPrintInstruction(O); 1223 EmitGetRegisterName(O); 1224 EmitPrintAliasInstruction(O); 1225 } 1226 1227 namespace llvm { 1228 1229 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) { 1230 emitSourceFileHeader("Assembly Writer Source Fragment", OS); 1231 AsmWriterEmitter(RK).run(OS); 1232 } 1233 1234 } // end namespace llvm 1235