1 //===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
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
7 //===----------------------------------------------------------------------===//
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.
12 //===----------------------------------------------------------------------===//
14 #include "AsmWriterInst.h"
15 #include "CodeGenInstruction.h"
16 #include "CodeGenRegisters.h"
17 #include "CodeGenTarget.h"
18 #include "SequenceToOffsetTable.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"
53 #define DEBUG_TYPE "asm-writer-emitter"
57 class AsmWriterEmitter {
58 RecordKeeper &Records;
60 ArrayRef<const CodeGenInstruction *> NumberedInstructions;
61 std::vector<AsmWriterInst> Instructions;
64 AsmWriterEmitter(RecordKeeper &R);
66 void run(raw_ostream &o);
69 void EmitPrintInstruction(raw_ostream &o);
70 void EmitGetRegisterName(raw_ostream &o);
71 void EmitPrintAliasInstruction(raw_ostream &O);
73 void FindUniqueOperandCommands(std::vector<std::string> &UOC,
74 std::vector<std::vector<unsigned>> &InstIdxs,
75 std::vector<unsigned> &InstOpsUsed,
76 bool PassSubtarget) const;
79 } // end anonymous namespace
81 static void PrintCases(std::vector<std::pair<std::string,
82 AsmWriterOperand>> &OpsToPrint, raw_ostream &O,
84 O << " case " << OpsToPrint.back().first << ":";
85 AsmWriterOperand TheOp = OpsToPrint.back().second;
86 OpsToPrint.pop_back();
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);
96 // Finally, emit the code.
97 O << "\n " << TheOp.getCode(PassSubtarget);
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();
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);
113 if (DifferingOperand == ~0U) // First match!
114 DifferingOperand = DiffOp;
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);
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);
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]));
144 for (const AsmWriterInst &AWI : SimilarInsts) {
145 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace.str()+"::" +
146 AWI.CGI->TheDef->getName().str(),
149 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
150 while (!OpsToPrint.empty())
151 PrintCases(OpsToPrint, O, PassSubtarget);
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
167 std::vector<std::string> InstrsForCase;
168 InstrsForCase.resize(UniqueOperandCommands.size());
169 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
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.
176 std::string Command = " "+Inst.Operands[0].getCode(PassSubtarget)+"\n";
178 // Check to see if we already have 'Command' in UniqueOperandCommands.
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);
187 UniqueOperandCommands.push_back(std::move(Command));
188 InstrsForCase.push_back(Inst.CGI->TheDef->getName());
189 InstIdxs.emplace_back();
190 InstIdxs.back().push_back(i);
192 // This command matches one operand so far.
193 InstOpsUsed.push_back(1);
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) {
203 const auto &Idxs = InstIdxs[CommandIdx];
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)
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(),
217 const AsmWriterInst &OtherInst = Instructions[Idx];
218 return OtherInst.Operands.size() == Op ||
219 OtherInst.Operands[Op] != FirstInst.Operands[Op];
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";
228 UniqueOperandCommands[CommandIdx] += Command;
229 InstOpsUsed[CommandIdx]++;
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());
242 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
243 UniqueOperandCommands[i];
247 static void UnescapeString(std::string &Str) {
248 for (unsigned i = 0; i != Str.size(); ++i) {
249 if (Str[i] == '\\' && i != Str.size()-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;
264 // Nuke the second character.
265 Str.erase(Str.begin()+i+1);
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");
278 O << "/// printInstruction - This method is automatically generated by "
280 "/// from the instruction set description.\n"
282 << Target.getName() << ClassName
283 << "::printInstruction(const MCInst *MI, uint64_t Address, "
284 << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "")
285 << "raw_ostream &O) {\n";
287 // Build an aggregate string, and build a table of offsets into it.
288 SequenceToOffsetTable<std::string> StringTable;
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;
295 // Add all strings to the string table upfront so it can generate an optimized
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;
303 StringTable.add(Str);
307 StringTable.layout();
309 unsigned MaxStringIdx = 0;
310 for (AsmWriterInst &AWI : Instructions) {
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("");
317 std::string Str = AWI.Operands[0].Str;
319 Idx = StringTable.get(Str);
320 MaxStringIdx = std::max(MaxStringIdx, Idx);
322 // Nuke the string from the operand list. It is now handled!
323 AWI.Operands.erase(AWI.Operands.begin());
326 // Bias offset by one since we want 0 as a sentinel.
327 OpcodeInfo[AWI.CGIIndex] = Idx+1;
330 // Figure out how many bits we used for the string index.
331 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
333 // To reduce code size, we compactify common instructions into a few bits
334 // in the opcode-indexed table.
335 unsigned BitsLeft = OpcodeInfoBits-AsmStrBits;
337 std::vector<std::vector<std::string>> TableDrivenOperandPrinters;
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);
346 // If we ran out of operands to print, we're done.
347 if (UniqueOperandCommands.empty()) break;
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());
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
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);
378 // Remember the handlers for this set of operands.
379 TableDrivenOperandPrinters.push_back(std::move(UniqueOperandCommands));
382 // Emit the string table itself.
383 O << " static const char AsmStrs[] = {\n";
384 StringTable.emit(O, printChar);
387 // Emit the lookup tables in pieces to minimize wasted bytes.
388 unsigned BytesNeeded = ((OpcodeInfoBits - BitsLeft) + 7) / 8;
389 unsigned Table = 0, Shift = 0;
390 SmallString<128> BitsString;
391 raw_svector_ostream BitsOS(BitsString);
392 // If the total bits is more than 32-bits we need to use a 64-bit type.
393 BitsOS << " uint" << ((BitsLeft < (OpcodeInfoBits - 32)) ? 64 : 32)
395 while (BytesNeeded != 0) {
396 // Figure out how big this table section needs to be, but no bigger than 4.
397 unsigned TableSize = std::min(1 << Log2_32(BytesNeeded), 4);
398 BytesNeeded -= TableSize;
399 TableSize *= 8; // Convert to bits;
400 uint64_t Mask = (1ULL << TableSize) - 1;
401 O << " static const uint" << TableSize << "_t OpInfo" << Table
403 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
404 O << " " << ((OpcodeInfo[i] >> Shift) & Mask) << "U,\t// "
405 << NumberedInstructions[i]->TheDef->getName() << "\n";
408 // Emit string to combine the individual table lookups.
409 BitsOS << " Bits |= ";
410 // If the total bits is more than 32-bits we need to use a 64-bit type.
411 if (BitsLeft < (OpcodeInfoBits - 32))
412 BitsOS << "(uint64_t)";
413 BitsOS << "OpInfo" << Table << "[MI->getOpcode()] << " << Shift << ";\n";
414 // Prepare the shift for the next iteration and increment the table count.
419 // Emit the initial tab character.
420 O << " O << \"\\t\";\n\n";
422 O << " // Emit the opcode for the instruction.\n";
425 // Emit the starting string.
426 O << " assert(Bits != 0 && \"Cannot print this instruction.\");\n"
427 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
429 // Output the table driven operand information.
430 BitsLeft = OpcodeInfoBits-AsmStrBits;
431 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
432 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
434 // Compute the number of bits we need to represent these cases, this is
435 // ceil(log2(numentries)).
436 unsigned NumBits = Log2_32_Ceil(Commands.size());
437 assert(NumBits <= BitsLeft && "consistency error");
439 // Emit code to extract this field from Bits.
440 O << "\n // Fragment " << i << " encoded into " << NumBits
441 << " bits for " << Commands.size() << " unique commands.\n";
443 if (Commands.size() == 2) {
444 // Emit two possibilitys with if/else.
445 O << " if ((Bits >> "
446 << (OpcodeInfoBits-BitsLeft) << ") & "
447 << ((1 << NumBits)-1) << ") {\n"
452 } else if (Commands.size() == 1) {
453 // Emit a single possibility.
454 O << Commands[0] << "\n\n";
456 O << " switch ((Bits >> "
457 << (OpcodeInfoBits-BitsLeft) << ") & "
458 << ((1 << NumBits)-1) << ") {\n"
459 << " default: llvm_unreachable(\"Invalid command number.\");\n";
461 // Print out all the cases.
462 for (unsigned j = 0, e = Commands.size(); j != e; ++j) {
463 O << " case " << j << ":\n";
472 // Okay, delete instructions with no operand info left.
473 auto I = llvm::remove_if(Instructions,
474 [](AsmWriterInst &Inst) { return Inst.Operands.empty(); });
475 Instructions.erase(I, Instructions.end());
478 // Because this is a vector, we want to emit from the end. Reverse all of the
479 // elements in the vector.
480 std::reverse(Instructions.begin(), Instructions.end());
483 // Now that we've emitted all of the operand info that fit into 64 bits, emit
484 // information for those instructions that are left. This is a less dense
485 // encoding, but we expect the main 64-bit table to handle the majority of
487 if (!Instructions.empty()) {
488 // Find the opcode # of inline asm.
489 O << " switch (MI->getOpcode()) {\n";
490 O << " default: llvm_unreachable(\"Unexpected opcode.\");\n";
491 while (!Instructions.empty())
492 EmitInstructions(Instructions, O, PassSubtarget);
501 emitRegisterNameString(raw_ostream &O, StringRef AltName,
502 const std::deque<CodeGenRegister> &Registers) {
503 SequenceToOffsetTable<std::string> StringTable;
504 SmallVector<std::string, 4> AsmNames(Registers.size());
506 for (const auto &Reg : Registers) {
507 std::string &AsmName = AsmNames[i++];
509 // "NoRegAltName" is special. We don't need to do a lookup for that,
510 // as it's just a reference to the default register name.
511 if (AltName == "" || AltName == "NoRegAltName") {
512 AsmName = Reg.TheDef->getValueAsString("AsmName");
514 AsmName = Reg.getName();
516 // Make sure the register has an alternate name for this index.
517 std::vector<Record*> AltNameList =
518 Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
520 for (e = AltNameList.size();
521 Idx < e && (AltNameList[Idx]->getName() != AltName);
524 // If the register has an alternate name for this index, use it.
525 // Otherwise, leave it empty as an error flag.
527 std::vector<StringRef> AltNames =
528 Reg.TheDef->getValueAsListOfStrings("AltNames");
529 if (AltNames.size() <= Idx)
530 PrintFatalError(Reg.TheDef->getLoc(),
531 "Register definition missing alt name for '" +
533 AsmName = AltNames[Idx];
536 StringTable.add(AsmName);
539 StringTable.layout();
540 O << " static const char AsmStrs" << AltName << "[] = {\n";
541 StringTable.emit(O, printChar);
544 O << " static const " << getMinimalTypeForRange(StringTable.size() - 1, 32)
545 << " RegAsmOffset" << AltName << "[] = {";
546 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
549 O << StringTable.get(AsmNames[i]) << ", ";
555 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
556 Record *AsmWriter = Target.getAsmWriter();
557 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
558 const auto &Registers = Target.getRegBank().getRegisters();
559 const std::vector<Record*> &AltNameIndices = Target.getRegAltNameIndices();
560 bool hasAltNames = AltNameIndices.size() > 1;
561 StringRef Namespace = Registers.front().TheDef->getValueAsString("Namespace");
564 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
565 "/// from the register set description. This returns the assembler name\n"
566 "/// for the specified register.\n"
567 "const char *" << Target.getName() << ClassName << "::";
569 O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
571 O << "getRegisterName(unsigned RegNo) {\n";
572 O << " assert(RegNo && RegNo < " << (Registers.size()+1)
573 << " && \"Invalid register number!\");\n"
577 for (const Record *R : AltNameIndices)
578 emitRegisterNameString(O, R->getName(), Registers);
580 emitRegisterNameString(O, "", Registers);
583 O << " switch(AltIdx) {\n"
584 << " default: llvm_unreachable(\"Invalid register alt name index!\");\n";
585 for (const Record *R : AltNameIndices) {
586 StringRef AltName = R->getName();
588 if (!Namespace.empty())
589 O << Namespace << "::";
590 O << AltName << ":\n";
591 if (R->isValueUnset("FallbackRegAltNameIndex"))
592 O << " assert(*(AsmStrs" << AltName << "+RegAsmOffset" << AltName
594 << " \"Invalid alt name index for register!\");\n";
596 O << " if (!*(AsmStrs" << AltName << "+RegAsmOffset" << AltName
598 << " return getRegisterName(RegNo, ";
599 if (!Namespace.empty())
600 O << Namespace << "::";
601 O << R->getValueAsDef("FallbackRegAltNameIndex")->getName() << ");\n";
603 O << " return AsmStrs" << AltName << "+RegAsmOffset" << AltName
608 O << " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
609 << " \"Invalid alt name index for register!\");\n"
610 << " return AsmStrs+RegAsmOffset[RegNo-1];\n";
617 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if
618 // they both have the same conditionals. In which case, we cannot print out the
619 // alias for that pattern.
621 std::map<StringRef, std::pair<int, int>> OpMap;
623 std::vector<std::string> Conds;
626 std::string AsmString;
631 IAPrinter(std::string R, std::string AS, unsigned NumMIOps)
632 : Result(std::move(R)), AsmString(std::move(AS)), NumMIOps(NumMIOps) {}
634 void addCond(std::string C) { Conds.push_back(std::move(C)); }
635 ArrayRef<std::string> getConds() const { return Conds; }
636 size_t getCondCount() const { return Conds.size(); }
638 void addOperand(StringRef Op, int OpIdx, int PrintMethodIdx = -1) {
639 assert(OpIdx >= 0 && OpIdx < 0xFE && "Idx out of range");
640 assert(PrintMethodIdx >= -1 && PrintMethodIdx < 0xFF &&
642 OpMap[Op] = std::make_pair(OpIdx, PrintMethodIdx);
645 unsigned getNumMIOps() { return NumMIOps; }
647 StringRef getResult() { return Result; }
649 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
650 int getOpIndex(StringRef Op) { return OpMap[Op].first; }
651 std::pair<int, int> &getOpData(StringRef Op) { return OpMap[Op]; }
653 std::pair<StringRef, StringRef::iterator> parseName(StringRef::iterator Start,
654 StringRef::iterator End) {
655 StringRef::iterator I = Start;
656 StringRef::iterator Next;
660 while (I != End && *I != '}')
667 // $name, just eat the usual suspects.
669 ((*I >= 'a' && *I <= 'z') || (*I >= 'A' && *I <= 'Z') ||
670 (*I >= '0' && *I <= '9') || *I == '_'))
675 return std::make_pair(StringRef(Start, I - Start), Next);
678 std::string formatAliasString(uint32_t &UnescapedSize) {
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 std::string OutString;
684 raw_string_ostream OS(OutString);
685 for (StringRef::iterator I = ASM.begin(), E = ASM.end(); I != E;) {
690 std::tie(Name, I) = parseName(++I, E);
691 assert(isOpMapped(Name) && "Unmapped operand!");
693 int OpIndex, PrintIndex;
694 std::tie(OpIndex, PrintIndex) = getOpData(Name);
695 if (PrintIndex == -1) {
696 // Can use the default printOperand route.
697 OS << format("\\x%02X", (unsigned char)OpIndex + 1);
700 // 3 bytes if a PrintMethod is needed: 0xFF, the MCInst operand
701 // number, and which of our pre-detected Methods to call.
702 OS << format("\\xFF\\x%02X\\x%02X", OpIndex + 1, PrintIndex + 1);
714 bool operator==(const IAPrinter &RHS) const {
715 if (NumMIOps != RHS.NumMIOps)
717 if (Conds.size() != RHS.Conds.size())
721 for (const auto &str : Conds)
722 if (str != RHS.Conds[Idx++])
729 } // end anonymous namespace
731 static unsigned CountNumOperands(StringRef AsmString, unsigned Variant) {
732 return AsmString.count(' ') + AsmString.count('\t');
737 struct AliasPriorityComparator {
738 typedef std::pair<CodeGenInstAlias, int> ValueType;
739 bool operator()(const ValueType &LHS, const ValueType &RHS) const {
740 if (LHS.second == RHS.second) {
741 // We don't actually care about the order, but for consistency it
742 // shouldn't depend on pointer comparisons.
743 return LessRecordByID()(LHS.first.TheDef, RHS.first.TheDef);
746 // Aliases with larger priorities should be considered first.
747 return LHS.second > RHS.second;
751 } // end anonymous namespace
753 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
754 Record *AsmWriter = Target.getAsmWriter();
756 O << "\n#ifdef PRINT_ALIAS_INSTR\n";
757 O << "#undef PRINT_ALIAS_INSTR\n\n";
759 //////////////////////////////
760 // Gather information about aliases we need to print
761 //////////////////////////////
763 // Emit the method that prints the alias instruction.
764 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
765 unsigned Variant = AsmWriter->getValueAsInt("Variant");
766 bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
768 std::vector<Record*> AllInstAliases =
769 Records.getAllDerivedDefinitions("InstAlias");
771 // Create a map from the qualified name to a list of potential matches.
772 typedef std::set<std::pair<CodeGenInstAlias, int>, AliasPriorityComparator>
774 std::map<std::string, AliasWithPriority> AliasMap;
775 for (Record *R : AllInstAliases) {
776 int Priority = R->getValueAsInt("EmitPriority");
778 continue; // Aliases with priority 0 are never emitted.
780 const DagInit *DI = R->getValueAsDag("ResultInst");
781 AliasMap[getQualifiedName(DI->getOperatorAsDef(R->getLoc()))].insert(
782 std::make_pair(CodeGenInstAlias(R, Target), Priority));
785 // A map of which conditions need to be met for each instruction operand
786 // before it can be matched to the mnemonic.
787 std::map<std::string, std::vector<IAPrinter>> IAPrinterMap;
789 std::vector<std::string> PrintMethods;
791 // A list of MCOperandPredicates for all operands in use, and the reverse map
792 std::vector<const Record*> MCOpPredicates;
793 DenseMap<const Record*, unsigned> MCOpPredicateMap;
795 for (auto &Aliases : AliasMap) {
796 // Collection of instruction alias rules. May contain ambiguous rules.
797 std::vector<IAPrinter> IAPs;
799 for (auto &Alias : Aliases.second) {
800 const CodeGenInstAlias &CGA = Alias.first;
801 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
802 std::string FlatInstAsmString =
803 CodeGenInstruction::FlattenAsmStringVariants(CGA.ResultInst->AsmString,
805 unsigned NumResultOps = CountNumOperands(FlatInstAsmString, Variant);
807 std::string FlatAliasAsmString =
808 CodeGenInstruction::FlattenAsmStringVariants(CGA.AsmString, Variant);
810 // Don't emit the alias if it has more operands than what it's aliasing.
811 if (NumResultOps < CountNumOperands(FlatAliasAsmString, Variant))
814 StringRef Namespace = Target.getName();
815 unsigned NumMIOps = 0;
816 for (auto &ResultInstOpnd : CGA.ResultInst->Operands)
817 NumMIOps += ResultInstOpnd.MINumOperands;
819 IAPrinter IAP(CGA.Result->getAsString(), FlatAliasAsmString, NumMIOps);
821 bool CantHandle = false;
823 unsigned MIOpNum = 0;
824 for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
825 // Skip over tied operands as they're not part of an alias declaration.
826 auto &Operands = CGA.ResultInst->Operands;
828 unsigned OpNum = Operands.getSubOperandNumber(MIOpNum).first;
829 if (Operands[OpNum].MINumOperands == 1 &&
830 Operands[OpNum].getTiedRegister() != -1) {
831 // Tied operands of different RegisterClass should be explicit within
832 // an instruction's syntax and so cannot be skipped.
833 int TiedOpNum = Operands[OpNum].getTiedRegister();
834 if (Operands[OpNum].Rec->getName() ==
835 Operands[TiedOpNum].Rec->getName()) {
843 // Ignore unchecked result operands.
844 while (IAP.getCondCount() < MIOpNum)
845 IAP.addCond("AliasPatternCond::K_Ignore, 0");
847 const CodeGenInstAlias::ResultOperand &RO = CGA.ResultOperands[i];
850 case CodeGenInstAlias::ResultOperand::K_Record: {
851 const Record *Rec = RO.getRecord();
852 StringRef ROName = RO.getName();
853 int PrintMethodIdx = -1;
855 // These two may have a PrintMethod, which we want to record (if it's
856 // the first time we've seen it) and provide an index for the aliasing
858 if (Rec->isSubClassOf("RegisterOperand") ||
859 Rec->isSubClassOf("Operand")) {
860 StringRef PrintMethod = Rec->getValueAsString("PrintMethod");
861 if (PrintMethod != "" && PrintMethod != "printOperand") {
863 llvm::find(PrintMethods, PrintMethod) - PrintMethods.begin();
864 if (static_cast<unsigned>(PrintMethodIdx) == PrintMethods.size())
865 PrintMethods.push_back(PrintMethod);
869 if (Rec->isSubClassOf("RegisterOperand"))
870 Rec = Rec->getValueAsDef("RegClass");
871 if (Rec->isSubClassOf("RegisterClass")) {
872 if (!IAP.isOpMapped(ROName)) {
873 IAP.addOperand(ROName, MIOpNum, PrintMethodIdx);
874 Record *R = CGA.ResultOperands[i].getRecord();
875 if (R->isSubClassOf("RegisterOperand"))
876 R = R->getValueAsDef("RegClass");
878 "AliasPatternCond::K_RegClass, {0}::{1}RegClassID", Namespace,
881 IAP.addCond(formatv("AliasPatternCond::K_TiedReg, {0}",
882 IAP.getOpIndex(ROName)));
885 // Assume all printable operands are desired for now. This can be
886 // overridden in the InstAlias instantiation if necessary.
887 IAP.addOperand(ROName, MIOpNum, PrintMethodIdx);
889 // There might be an additional predicate on the MCOperand
890 unsigned Entry = MCOpPredicateMap[Rec];
892 if (!Rec->isValueUnset("MCOperandPredicate")) {
893 MCOpPredicates.push_back(Rec);
894 Entry = MCOpPredicates.size();
895 MCOpPredicateMap[Rec] = Entry;
897 break; // No conditions on this operand at all
899 IAP.addCond(formatv("AliasPatternCond::K_Custom, {0}", Entry));
903 case CodeGenInstAlias::ResultOperand::K_Imm: {
904 // Just because the alias has an immediate result, doesn't mean the
905 // MCInst will. An MCExpr could be present, for example.
906 auto Imm = CGA.ResultOperands[i].getImm();
907 int32_t Imm32 = int32_t(Imm);
909 PrintFatalError("Matching an alias with an immediate out of the "
910 "range of int32_t is not supported");
911 IAP.addCond(formatv("AliasPatternCond::K_Imm, uint32_t({0})", Imm32));
914 case CodeGenInstAlias::ResultOperand::K_Reg:
915 // If this is zero_reg, something's playing tricks we're not
916 // equipped to handle.
917 if (!CGA.ResultOperands[i].getRegister()) {
922 StringRef Reg = CGA.ResultOperands[i].getRegister()->getName();
924 formatv("AliasPatternCond::K_Reg, {0}::{1}", Namespace, Reg));
928 MIOpNum += RO.getMINumOperands();
931 if (CantHandle) continue;
933 std::vector<Record *> ReqFeatures;
935 // We only consider ReqFeatures predicates if PassSubtarget
936 std::vector<Record *> RF =
937 CGA.TheDef->getValueAsListOfDefs("Predicates");
938 copy_if(RF, std::back_inserter(ReqFeatures), [](Record *R) {
939 return R->getValueAsBit("AssemblerMatcherPredicate");
943 for (auto I = ReqFeatures.cbegin(); I != ReqFeatures.cend(); I++) {
945 StringRef AsmCondString = R->getValueAsString("AssemblerCondString");
947 // AsmCondString has syntax [!]F(,[!]F)*
948 SmallVector<StringRef, 4> Ops;
949 SplitString(AsmCondString, Ops, ",");
950 assert(!Ops.empty() && "AssemblerCondString cannot be empty");
952 for (StringRef Op : Ops) {
953 assert(!Op.empty() && "Empty operator");
954 bool IsNeg = Op[0] == '!';
955 StringRef Feature = Op.drop_front(IsNeg ? 1 : 0);
956 IAP.addCond(formatv("AliasPatternCond::K_{0}Feature, {1}::{2}",
957 IsNeg ? "Neg" : "", Namespace, Feature));
961 IAPrinterMap[Aliases.first].push_back(std::move(IAP));
965 //////////////////////////////
966 // Write out the printAliasInstr function
967 //////////////////////////////
970 raw_string_ostream HeaderO(Header);
972 HeaderO << "bool " << Target.getName() << ClassName
973 << "::printAliasInstr(const MCInst"
974 << " *MI, " << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "")
975 << "raw_ostream &OS) {\n";
977 std::string PatternsForOpcode;
978 raw_string_ostream OpcodeO(PatternsForOpcode);
980 unsigned PatternCount = 0;
981 std::string Patterns;
982 raw_string_ostream PatternO(Patterns);
984 unsigned CondCount = 0;
986 raw_string_ostream CondO(Conds);
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;
993 // Iterate over the opcodes in enum order so they are sorted by opcode for
995 for (const CodeGenInstruction *Inst : NumberedInstructions) {
996 auto It = IAPrinterMap.find(getQualifiedName(Inst->TheDef));
997 if (It == IAPrinterMap.end())
999 std::vector<IAPrinter> &IAPs = It->second;
1000 std::vector<IAPrinter*> UniqueIAPs;
1002 // Remove any ambiguous alias rules.
1003 for (auto &LHS : IAPs) {
1005 for (const auto &RHS : IAPs) {
1006 if (&LHS != &RHS && LHS == RHS) {
1013 UniqueIAPs.push_back(&LHS);
1016 if (UniqueIAPs.empty()) continue;
1018 unsigned PatternStart = PatternCount;
1020 // Insert the pattern start and opcode in the pattern list for debugging.
1021 PatternO << formatv(" // {0} - {1}\n", It->first, PatternStart);
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();
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);
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;
1043 unsigned AsmStrOffset = Insertion.first->second;
1045 PatternO << formatv(" {{{0}, {1}, {2}, {3} },\n", AsmStrOffset,
1046 CondStart, IAP->getNumMIOps(), IAP->getCondCount());
1050 OpcodeO << formatv(" {{{0}, {1}, {2} },\n", It->first, PatternStart,
1051 PatternCount - PatternStart);
1054 if (OpcodeO.str().empty()) {
1056 O << " return false;\n";
1058 O << "#endif // PRINT_ALIAS_INSTR\n";
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";
1070 O.indent(2) << "static const PatternsForOpcode OpToPatterns[] = {\n";
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";
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";
1084 O.indent(2) << ";\n\n";
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";
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";
1110 O.indent(2) << " &" << Target.getName() << ClassName << "ValidateMCOperand,\n";
1111 O.indent(2) << "};\n";
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";
1117 // Code that prints the alias, replacing the operands with the ones from the
1119 O << " unsigned I = 0;\n";
1120 O << " while (AsmString[I] != ' ' && AsmString[I] != '\\t' &&\n";
1121 O << " AsmString[I] != '$' && AsmString[I] != '\\0')\n";
1123 O << " OS << '\\t' << StringRef(AsmString, I);\n";
1125 O << " if (AsmString[I] != '\\0') {\n";
1126 O << " if (AsmString[I] == ' ' || AsmString[I] == '\\t') {\n";
1127 O << " OS << '\\t';\n";
1131 O << " if (AsmString[I] == '$') {\n";
1133 O << " if (AsmString[I] == (char)0xff) {\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, " : "");
1141 O << " printOperand(MI, unsigned(AsmString[I++]) - 1, ";
1142 O << (PassSubtarget ? "STI, " : "");
1145 O << " OS << AsmString[I++];\n";
1147 O << " } while (AsmString[I] != '\\0');\n";
1150 O << " return true;\n";
1153 //////////////////////////////
1154 // Write out the printCustomAliasOperand function
1155 //////////////////////////////
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";
1166 O << " switch (PrintMethodIdx) {\n"
1168 << " llvm_unreachable(\"Unknown PrintMethod kind\");\n"
1171 for (unsigned i = 0; i < PrintMethods.size(); ++i) {
1172 O << " case " << i << ":\n"
1173 << " " << PrintMethods[i] << "(MI, OpIdx, "
1174 << (PassSubtarget ? "STI, " : "") << "OS);\n"
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"
1188 << " llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n"
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"
1198 llvm_unreachable("Unexpected MCOperandPredicate field!");
1204 O << "#endif // PRINT_ALIAS_INSTR\n";
1207 AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) {
1208 Record *AsmWriter = Target.getAsmWriter();
1209 unsigned Variant = AsmWriter->getValueAsInt("Variant");
1211 // Get the instruction numbering.
1212 NumberedInstructions = Target.getInstructionsByEnumValue();
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);
1221 void AsmWriterEmitter::run(raw_ostream &O) {
1222 EmitPrintInstruction(O);
1223 EmitGetRegisterName(O);
1224 EmitPrintAliasInstruction(O);
1229 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) {
1230 emitSourceFileHeader("Assembly Writer Source Fragment", OS);
1231 AsmWriterEmitter(RK).run(OS);
1234 } // end namespace llvm