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::pair<std::string, bool>> 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 bool IsPCRel = 859 Rec->getValueAsString("OperandType") == "OPERAND_PCREL"; 860 if (PrintMethod != "" && PrintMethod != "printOperand") { 861 PrintMethodIdx = llvm::find_if(PrintMethods, 862 [&](auto &X) { 863 return X.first == PrintMethod; 864 }) - 865 PrintMethods.begin(); 866 if (static_cast<unsigned>(PrintMethodIdx) == PrintMethods.size()) 867 PrintMethods.emplace_back(std::string(PrintMethod), IsPCRel); 868 } 869 } 870 871 if (Rec->isSubClassOf("RegisterOperand")) 872 Rec = Rec->getValueAsDef("RegClass"); 873 if (Rec->isSubClassOf("RegisterClass")) { 874 if (!IAP.isOpMapped(ROName)) { 875 IAP.addOperand(ROName, MIOpNum, PrintMethodIdx); 876 Record *R = CGA.ResultOperands[i].getRecord(); 877 if (R->isSubClassOf("RegisterOperand")) 878 R = R->getValueAsDef("RegClass"); 879 IAP.addCond(std::string( 880 formatv("AliasPatternCond::K_RegClass, {0}::{1}RegClassID", 881 Namespace, R->getName()))); 882 } else { 883 IAP.addCond(std::string(formatv( 884 "AliasPatternCond::K_TiedReg, {0}", IAP.getOpIndex(ROName)))); 885 } 886 } else { 887 // Assume all printable operands are desired for now. This can be 888 // overridden in the InstAlias instantiation if necessary. 889 IAP.addOperand(ROName, MIOpNum, PrintMethodIdx); 890 891 // There might be an additional predicate on the MCOperand 892 unsigned Entry = MCOpPredicateMap[Rec]; 893 if (!Entry) { 894 if (!Rec->isValueUnset("MCOperandPredicate")) { 895 MCOpPredicates.push_back(Rec); 896 Entry = MCOpPredicates.size(); 897 MCOpPredicateMap[Rec] = Entry; 898 } else 899 break; // No conditions on this operand at all 900 } 901 IAP.addCond( 902 std::string(formatv("AliasPatternCond::K_Custom, {0}", Entry))); 903 } 904 break; 905 } 906 case CodeGenInstAlias::ResultOperand::K_Imm: { 907 // Just because the alias has an immediate result, doesn't mean the 908 // MCInst will. An MCExpr could be present, for example. 909 auto Imm = CGA.ResultOperands[i].getImm(); 910 int32_t Imm32 = int32_t(Imm); 911 if (Imm != Imm32) 912 PrintFatalError("Matching an alias with an immediate out of the " 913 "range of int32_t is not supported"); 914 IAP.addCond(std::string( 915 formatv("AliasPatternCond::K_Imm, uint32_t({0})", Imm32))); 916 break; 917 } 918 case CodeGenInstAlias::ResultOperand::K_Reg: 919 // If this is zero_reg, something's playing tricks we're not 920 // equipped to handle. 921 if (!CGA.ResultOperands[i].getRegister()) { 922 CantHandle = true; 923 break; 924 } 925 926 StringRef Reg = CGA.ResultOperands[i].getRegister()->getName(); 927 IAP.addCond(std::string( 928 formatv("AliasPatternCond::K_Reg, {0}::{1}", Namespace, Reg))); 929 break; 930 } 931 932 MIOpNum += RO.getMINumOperands(); 933 } 934 935 if (CantHandle) continue; 936 937 std::vector<Record *> ReqFeatures; 938 if (PassSubtarget) { 939 // We only consider ReqFeatures predicates if PassSubtarget 940 std::vector<Record *> RF = 941 CGA.TheDef->getValueAsListOfDefs("Predicates"); 942 copy_if(RF, std::back_inserter(ReqFeatures), [](Record *R) { 943 return R->getValueAsBit("AssemblerMatcherPredicate"); 944 }); 945 } 946 947 for (auto I = ReqFeatures.cbegin(); I != ReqFeatures.cend(); I++) { 948 Record *R = *I; 949 const DagInit *D = R->getValueAsDag("AssemblerCondDag"); 950 std::string CombineType = D->getOperator()->getAsString(); 951 if (CombineType != "any_of" && CombineType != "all_of") 952 PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!"); 953 if (D->getNumArgs() == 0) 954 PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!"); 955 bool IsOr = CombineType == "any_of"; 956 957 for (auto *Arg : D->getArgs()) { 958 bool IsNeg = false; 959 if (auto *NotArg = dyn_cast<DagInit>(Arg)) { 960 if (NotArg->getOperator()->getAsString() != "not" || 961 NotArg->getNumArgs() != 1) 962 PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!"); 963 Arg = NotArg->getArg(0); 964 IsNeg = true; 965 } 966 if (!isa<DefInit>(Arg) || 967 !cast<DefInit>(Arg)->getDef()->isSubClassOf("SubtargetFeature")) 968 PrintFatalError(R->getLoc(), "Invalid AssemblerCondDag!"); 969 970 IAP.addCond(std::string(formatv( 971 "AliasPatternCond::K_{0}{1}Feature, {2}::{3}", IsOr ? "Or" : "", 972 IsNeg ? "Neg" : "", Namespace, Arg->getAsString()))); 973 } 974 // If an AssemblerPredicate with ors is used, note end of list should 975 // these be combined. 976 if (IsOr) 977 IAP.addCond("AliasPatternCond::K_EndOrFeatures, 0"); 978 } 979 980 IAPrinterMap[Aliases.first].push_back(std::move(IAP)); 981 } 982 } 983 984 ////////////////////////////// 985 // Write out the printAliasInstr function 986 ////////////////////////////// 987 988 std::string Header; 989 raw_string_ostream HeaderO(Header); 990 991 HeaderO << "bool " << Target.getName() << ClassName 992 << "::printAliasInstr(const MCInst" 993 << " *MI, uint64_t Address, " 994 << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "") 995 << "raw_ostream &OS) {\n"; 996 997 std::string PatternsForOpcode; 998 raw_string_ostream OpcodeO(PatternsForOpcode); 999 1000 unsigned PatternCount = 0; 1001 std::string Patterns; 1002 raw_string_ostream PatternO(Patterns); 1003 1004 unsigned CondCount = 0; 1005 std::string Conds; 1006 raw_string_ostream CondO(Conds); 1007 1008 // All flattened alias strings. 1009 std::map<std::string, uint32_t> AsmStringOffsets; 1010 std::vector<std::pair<uint32_t, std::string>> AsmStrings; 1011 size_t AsmStringsSize = 0; 1012 1013 // Iterate over the opcodes in enum order so they are sorted by opcode for 1014 // binary search. 1015 for (const CodeGenInstruction *Inst : NumberedInstructions) { 1016 auto It = IAPrinterMap.find(getQualifiedName(Inst->TheDef)); 1017 if (It == IAPrinterMap.end()) 1018 continue; 1019 std::vector<IAPrinter> &IAPs = It->second; 1020 std::vector<IAPrinter*> UniqueIAPs; 1021 1022 // Remove any ambiguous alias rules. 1023 for (auto &LHS : IAPs) { 1024 bool IsDup = false; 1025 for (const auto &RHS : IAPs) { 1026 if (&LHS != &RHS && LHS == RHS) { 1027 IsDup = true; 1028 break; 1029 } 1030 } 1031 1032 if (!IsDup) 1033 UniqueIAPs.push_back(&LHS); 1034 } 1035 1036 if (UniqueIAPs.empty()) continue; 1037 1038 unsigned PatternStart = PatternCount; 1039 1040 // Insert the pattern start and opcode in the pattern list for debugging. 1041 PatternO << formatv(" // {0} - {1}\n", It->first, PatternStart); 1042 1043 for (IAPrinter *IAP : UniqueIAPs) { 1044 // Start each condition list with a comment of the resulting pattern that 1045 // we're trying to match. 1046 unsigned CondStart = CondCount; 1047 CondO << formatv(" // {0} - {1}\n", IAP->getResult(), CondStart); 1048 for (const auto &Cond : IAP->getConds()) 1049 CondO << " {" << Cond << "},\n"; 1050 CondCount += IAP->getCondCount(); 1051 1052 // After operands have been examined, re-encode the alias string with 1053 // escapes indicating how operands should be printed. 1054 uint32_t UnescapedSize = 0; 1055 std::string EncodedAsmString = IAP->formatAliasString(UnescapedSize); 1056 auto Insertion = 1057 AsmStringOffsets.insert({EncodedAsmString, AsmStringsSize}); 1058 if (Insertion.second) { 1059 // If the string is new, add it to the vector. 1060 AsmStrings.push_back({AsmStringsSize, EncodedAsmString}); 1061 AsmStringsSize += UnescapedSize + 1; 1062 } 1063 unsigned AsmStrOffset = Insertion.first->second; 1064 1065 PatternO << formatv(" {{{0}, {1}, {2}, {3} },\n", AsmStrOffset, 1066 CondStart, IAP->getNumMIOps(), IAP->getCondCount()); 1067 ++PatternCount; 1068 } 1069 1070 OpcodeO << formatv(" {{{0}, {1}, {2} },\n", It->first, PatternStart, 1071 PatternCount - PatternStart); 1072 } 1073 1074 if (OpcodeO.str().empty()) { 1075 O << HeaderO.str(); 1076 O << " return false;\n"; 1077 O << "}\n\n"; 1078 O << "#endif // PRINT_ALIAS_INSTR\n"; 1079 return; 1080 } 1081 1082 // Forward declare the validation method if needed. 1083 if (!MCOpPredicates.empty()) 1084 O << "static bool " << Target.getName() << ClassName 1085 << "ValidateMCOperand(const MCOperand &MCOp,\n" 1086 << " const MCSubtargetInfo &STI,\n" 1087 << " unsigned PredicateIndex);\n"; 1088 1089 O << HeaderO.str(); 1090 O.indent(2) << "static const PatternsForOpcode OpToPatterns[] = {\n"; 1091 O << OpcodeO.str(); 1092 O.indent(2) << "};\n\n"; 1093 O.indent(2) << "static const AliasPattern Patterns[] = {\n"; 1094 O << PatternO.str(); 1095 O.indent(2) << "};\n\n"; 1096 O.indent(2) << "static const AliasPatternCond Conds[] = {\n"; 1097 O << CondO.str(); 1098 O.indent(2) << "};\n\n"; 1099 O.indent(2) << "static const char AsmStrings[] =\n"; 1100 for (const auto &P : AsmStrings) { 1101 O.indent(4) << "/* " << P.first << " */ \"" << P.second << "\\0\"\n"; 1102 } 1103 1104 O.indent(2) << ";\n\n"; 1105 1106 // Assert that the opcode table is sorted. Use a static local constructor to 1107 // ensure that the check only happens once on first run. 1108 O << "#ifndef NDEBUG\n"; 1109 O.indent(2) << "static struct SortCheck {\n"; 1110 O.indent(2) << " SortCheck(ArrayRef<PatternsForOpcode> OpToPatterns) {\n"; 1111 O.indent(2) << " assert(std::is_sorted(\n"; 1112 O.indent(2) << " OpToPatterns.begin(), OpToPatterns.end(),\n"; 1113 O.indent(2) << " [](const PatternsForOpcode &L, const " 1114 "PatternsForOpcode &R) {\n"; 1115 O.indent(2) << " return L.Opcode < R.Opcode;\n"; 1116 O.indent(2) << " }) &&\n"; 1117 O.indent(2) << " \"tablegen failed to sort opcode patterns\");\n"; 1118 O.indent(2) << " }\n"; 1119 O.indent(2) << "} sortCheckVar(OpToPatterns);\n"; 1120 O << "#endif\n\n"; 1121 1122 O.indent(2) << "AliasMatchingData M {\n"; 1123 O.indent(2) << " makeArrayRef(OpToPatterns),\n"; 1124 O.indent(2) << " makeArrayRef(Patterns),\n"; 1125 O.indent(2) << " makeArrayRef(Conds),\n"; 1126 O.indent(2) << " StringRef(AsmStrings, array_lengthof(AsmStrings)),\n"; 1127 if (MCOpPredicates.empty()) 1128 O.indent(2) << " nullptr,\n"; 1129 else 1130 O.indent(2) << " &" << Target.getName() << ClassName << "ValidateMCOperand,\n"; 1131 O.indent(2) << "};\n"; 1132 1133 O.indent(2) << "const char *AsmString = matchAliasPatterns(MI, " 1134 << (PassSubtarget ? "&STI" : "nullptr") << ", M);\n"; 1135 O.indent(2) << "if (!AsmString) return false;\n\n"; 1136 1137 // Code that prints the alias, replacing the operands with the ones from the 1138 // MCInst. 1139 O << " unsigned I = 0;\n"; 1140 O << " while (AsmString[I] != ' ' && AsmString[I] != '\\t' &&\n"; 1141 O << " AsmString[I] != '$' && AsmString[I] != '\\0')\n"; 1142 O << " ++I;\n"; 1143 O << " OS << '\\t' << StringRef(AsmString, I);\n"; 1144 1145 O << " if (AsmString[I] != '\\0') {\n"; 1146 O << " if (AsmString[I] == ' ' || AsmString[I] == '\\t') {\n"; 1147 O << " OS << '\\t';\n"; 1148 O << " ++I;\n"; 1149 O << " }\n"; 1150 O << " do {\n"; 1151 O << " if (AsmString[I] == '$') {\n"; 1152 O << " ++I;\n"; 1153 O << " if (AsmString[I] == (char)0xff) {\n"; 1154 O << " ++I;\n"; 1155 O << " int OpIdx = AsmString[I++] - 1;\n"; 1156 O << " int PrintMethodIdx = AsmString[I++] - 1;\n"; 1157 O << " printCustomAliasOperand(MI, Address, OpIdx, PrintMethodIdx, "; 1158 O << (PassSubtarget ? "STI, " : ""); 1159 O << "OS);\n"; 1160 O << " } else\n"; 1161 O << " printOperand(MI, unsigned(AsmString[I++]) - 1, "; 1162 O << (PassSubtarget ? "STI, " : ""); 1163 O << "OS);\n"; 1164 O << " } else {\n"; 1165 O << " OS << AsmString[I++];\n"; 1166 O << " }\n"; 1167 O << " } while (AsmString[I] != '\\0');\n"; 1168 O << " }\n\n"; 1169 1170 O << " return true;\n"; 1171 O << "}\n\n"; 1172 1173 ////////////////////////////// 1174 // Write out the printCustomAliasOperand function 1175 ////////////////////////////// 1176 1177 O << "void " << Target.getName() << ClassName << "::" 1178 << "printCustomAliasOperand(\n" 1179 << " const MCInst *MI, uint64_t Address, unsigned OpIdx,\n" 1180 << " unsigned PrintMethodIdx,\n" 1181 << (PassSubtarget ? " const MCSubtargetInfo &STI,\n" : "") 1182 << " raw_ostream &OS) {\n"; 1183 if (PrintMethods.empty()) 1184 O << " llvm_unreachable(\"Unknown PrintMethod kind\");\n"; 1185 else { 1186 O << " switch (PrintMethodIdx) {\n" 1187 << " default:\n" 1188 << " llvm_unreachable(\"Unknown PrintMethod kind\");\n" 1189 << " break;\n"; 1190 1191 for (unsigned i = 0; i < PrintMethods.size(); ++i) { 1192 O << " case " << i << ":\n" 1193 << " " << PrintMethods[i].first << "(MI, " 1194 << (PrintMethods[i].second ? "Address, " : "") << "OpIdx, " 1195 << (PassSubtarget ? "STI, " : "") << "OS);\n" 1196 << " break;\n"; 1197 } 1198 O << " }\n"; 1199 } 1200 O << "}\n\n"; 1201 1202 if (!MCOpPredicates.empty()) { 1203 O << "static bool " << Target.getName() << ClassName 1204 << "ValidateMCOperand(const MCOperand &MCOp,\n" 1205 << " const MCSubtargetInfo &STI,\n" 1206 << " unsigned PredicateIndex) {\n" 1207 << " switch (PredicateIndex) {\n" 1208 << " default:\n" 1209 << " llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n" 1210 << " break;\n"; 1211 1212 for (unsigned i = 0; i < MCOpPredicates.size(); ++i) { 1213 Init *MCOpPred = MCOpPredicates[i]->getValueInit("MCOperandPredicate"); 1214 if (CodeInit *SI = dyn_cast<CodeInit>(MCOpPred)) { 1215 O << " case " << i + 1 << ": {\n" 1216 << SI->getValue() << "\n" 1217 << " }\n"; 1218 } else 1219 llvm_unreachable("Unexpected MCOperandPredicate field!"); 1220 } 1221 O << " }\n" 1222 << "}\n\n"; 1223 } 1224 1225 O << "#endif // PRINT_ALIAS_INSTR\n"; 1226 } 1227 1228 AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) { 1229 Record *AsmWriter = Target.getAsmWriter(); 1230 unsigned Variant = AsmWriter->getValueAsInt("Variant"); 1231 1232 // Get the instruction numbering. 1233 NumberedInstructions = Target.getInstructionsByEnumValue(); 1234 1235 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) { 1236 const CodeGenInstruction *I = NumberedInstructions[i]; 1237 if (!I->AsmString.empty() && I->TheDef->getName() != "PHI") 1238 Instructions.emplace_back(*I, i, Variant); 1239 } 1240 } 1241 1242 void AsmWriterEmitter::run(raw_ostream &O) { 1243 EmitPrintInstruction(O); 1244 EmitGetRegisterName(O); 1245 EmitPrintAliasInstruction(O); 1246 } 1247 1248 namespace llvm { 1249 1250 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) { 1251 emitSourceFileHeader("Assembly Writer Source Fragment", OS); 1252 AsmWriterEmitter(RK).run(OS); 1253 } 1254 1255 } // end namespace llvm 1256