[InstCombine] Signed saturation patterns
[llvm-complete.git] / utils / TableGen / AsmWriterEmitter.cpp
blobb5c7f35be0e543d7e1957769b8b87a1c7ad561e2
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.
12 //===----------------------------------------------------------------------===//
14 #include "AsmWriterInst.h"
15 #include "CodeGenInstruction.h"
16 #include "CodeGenRegisters.h"
17 #include "CodeGenTarget.h"
18 #include "SequenceToOffsetTable.h"
19 #include "Types.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/Twine.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/Format.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/TableGen/Error.h"
35 #include "llvm/TableGen/Record.h"
36 #include "llvm/TableGen/TableGenBackend.h"
37 #include <algorithm>
38 #include <cassert>
39 #include <cstddef>
40 #include <cstdint>
41 #include <deque>
42 #include <iterator>
43 #include <map>
44 #include <set>
45 #include <string>
46 #include <tuple>
47 #include <utility>
48 #include <vector>
50 using namespace llvm;
52 #define DEBUG_TYPE "asm-writer-emitter"
54 namespace {
56 class AsmWriterEmitter {
57 RecordKeeper &Records;
58 CodeGenTarget Target;
59 ArrayRef<const CodeGenInstruction *> NumberedInstructions;
60 std::vector<AsmWriterInst> Instructions;
62 public:
63 AsmWriterEmitter(RecordKeeper &R);
65 void run(raw_ostream &o);
67 private:
68 void EmitPrintInstruction(raw_ostream &o);
69 void EmitGetRegisterName(raw_ostream &o);
70 void EmitPrintAliasInstruction(raw_ostream &O);
72 void FindUniqueOperandCommands(std::vector<std::string> &UOC,
73 std::vector<std::vector<unsigned>> &InstIdxs,
74 std::vector<unsigned> &InstOpsUsed,
75 bool PassSubtarget) const;
78 } // end anonymous namespace
80 static void PrintCases(std::vector<std::pair<std::string,
81 AsmWriterOperand>> &OpsToPrint, raw_ostream &O,
82 bool PassSubtarget) {
83 O << " case " << OpsToPrint.back().first << ":";
84 AsmWriterOperand TheOp = OpsToPrint.back().second;
85 OpsToPrint.pop_back();
87 // Check to see if any other operands are identical in this list, and if so,
88 // emit a case label for them.
89 for (unsigned i = OpsToPrint.size(); i != 0; --i)
90 if (OpsToPrint[i-1].second == TheOp) {
91 O << "\n case " << OpsToPrint[i-1].first << ":";
92 OpsToPrint.erase(OpsToPrint.begin()+i-1);
95 // Finally, emit the code.
96 O << "\n " << TheOp.getCode(PassSubtarget);
97 O << "\n break;\n";
100 /// EmitInstructions - Emit the last instruction in the vector and any other
101 /// instructions that are suitably similar to it.
102 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
103 raw_ostream &O, bool PassSubtarget) {
104 AsmWriterInst FirstInst = Insts.back();
105 Insts.pop_back();
107 std::vector<AsmWriterInst> SimilarInsts;
108 unsigned DifferingOperand = ~0;
109 for (unsigned i = Insts.size(); i != 0; --i) {
110 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
111 if (DiffOp != ~1U) {
112 if (DifferingOperand == ~0U) // First match!
113 DifferingOperand = DiffOp;
115 // If this differs in the same operand as the rest of the instructions in
116 // this class, move it to the SimilarInsts list.
117 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
118 SimilarInsts.push_back(Insts[i-1]);
119 Insts.erase(Insts.begin()+i-1);
124 O << " case " << FirstInst.CGI->Namespace << "::"
125 << FirstInst.CGI->TheDef->getName() << ":\n";
126 for (const AsmWriterInst &AWI : SimilarInsts)
127 O << " case " << AWI.CGI->Namespace << "::"
128 << AWI.CGI->TheDef->getName() << ":\n";
129 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
130 if (i != DifferingOperand) {
131 // If the operand is the same for all instructions, just print it.
132 O << " " << FirstInst.Operands[i].getCode(PassSubtarget);
133 } else {
134 // If this is the operand that varies between all of the instructions,
135 // emit a switch for just this operand now.
136 O << " switch (MI->getOpcode()) {\n";
137 O << " default: llvm_unreachable(\"Unexpected opcode.\");\n";
138 std::vector<std::pair<std::string, AsmWriterOperand>> OpsToPrint;
139 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace.str() + "::" +
140 FirstInst.CGI->TheDef->getName().str(),
141 FirstInst.Operands[i]));
143 for (const AsmWriterInst &AWI : SimilarInsts) {
144 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace.str()+"::" +
145 AWI.CGI->TheDef->getName().str(),
146 AWI.Operands[i]));
148 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
149 while (!OpsToPrint.empty())
150 PrintCases(OpsToPrint, O, PassSubtarget);
151 O << " }";
153 O << "\n";
155 O << " break;\n";
158 void AsmWriterEmitter::
159 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
160 std::vector<std::vector<unsigned>> &InstIdxs,
161 std::vector<unsigned> &InstOpsUsed,
162 bool PassSubtarget) const {
163 // This vector parallels UniqueOperandCommands, keeping track of which
164 // instructions each case are used for. It is a comma separated string of
165 // enums.
166 std::vector<std::string> InstrsForCase;
167 InstrsForCase.resize(UniqueOperandCommands.size());
168 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
170 for (size_t i = 0, e = Instructions.size(); i != e; ++i) {
171 const AsmWriterInst &Inst = Instructions[i];
172 if (Inst.Operands.empty())
173 continue; // Instruction already done.
175 std::string Command = " "+Inst.Operands[0].getCode(PassSubtarget)+"\n";
177 // Check to see if we already have 'Command' in UniqueOperandCommands.
178 // If not, add it.
179 auto I = llvm::find(UniqueOperandCommands, Command);
180 if (I != UniqueOperandCommands.end()) {
181 size_t idx = I - UniqueOperandCommands.begin();
182 InstrsForCase[idx] += ", ";
183 InstrsForCase[idx] += Inst.CGI->TheDef->getName();
184 InstIdxs[idx].push_back(i);
185 } else {
186 UniqueOperandCommands.push_back(std::move(Command));
187 InstrsForCase.push_back(Inst.CGI->TheDef->getName());
188 InstIdxs.emplace_back();
189 InstIdxs.back().push_back(i);
191 // This command matches one operand so far.
192 InstOpsUsed.push_back(1);
196 // For each entry of UniqueOperandCommands, there is a set of instructions
197 // that uses it. If the next command of all instructions in the set are
198 // identical, fold it into the command.
199 for (size_t CommandIdx = 0, e = UniqueOperandCommands.size();
200 CommandIdx != e; ++CommandIdx) {
202 const auto &Idxs = InstIdxs[CommandIdx];
204 for (unsigned Op = 1; ; ++Op) {
205 // Find the first instruction in the set.
206 const AsmWriterInst &FirstInst = Instructions[Idxs.front()];
207 // If this instruction has no more operands, we isn't anything to merge
208 // into this command.
209 if (FirstInst.Operands.size() == Op)
210 break;
212 // Otherwise, scan to see if all of the other instructions in this command
213 // set share the operand.
214 if (std::any_of(Idxs.begin()+1, Idxs.end(),
215 [&](unsigned Idx) {
216 const AsmWriterInst &OtherInst = Instructions[Idx];
217 return OtherInst.Operands.size() == Op ||
218 OtherInst.Operands[Op] != FirstInst.Operands[Op];
220 break;
222 // Okay, everything in this command set has the same next operand. Add it
223 // to UniqueOperandCommands and remember that it was consumed.
224 std::string Command = " " +
225 FirstInst.Operands[Op].getCode(PassSubtarget) + "\n";
227 UniqueOperandCommands[CommandIdx] += Command;
228 InstOpsUsed[CommandIdx]++;
232 // Prepend some of the instructions each case is used for onto the case val.
233 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
234 std::string Instrs = InstrsForCase[i];
235 if (Instrs.size() > 70) {
236 Instrs.erase(Instrs.begin()+70, Instrs.end());
237 Instrs += "...";
240 if (!Instrs.empty())
241 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
242 UniqueOperandCommands[i];
246 static void UnescapeString(std::string &Str) {
247 for (unsigned i = 0; i != Str.size(); ++i) {
248 if (Str[i] == '\\' && i != Str.size()-1) {
249 switch (Str[i+1]) {
250 default: continue; // Don't execute the code after the switch.
251 case 'a': Str[i] = '\a'; break;
252 case 'b': Str[i] = '\b'; break;
253 case 'e': Str[i] = 27; break;
254 case 'f': Str[i] = '\f'; break;
255 case 'n': Str[i] = '\n'; break;
256 case 'r': Str[i] = '\r'; break;
257 case 't': Str[i] = '\t'; break;
258 case 'v': Str[i] = '\v'; break;
259 case '"': Str[i] = '\"'; break;
260 case '\'': Str[i] = '\''; break;
261 case '\\': Str[i] = '\\'; break;
263 // Nuke the second character.
264 Str.erase(Str.begin()+i+1);
269 /// EmitPrintInstruction - Generate the code for the "printInstruction" method
270 /// implementation. Destroys all instances of AsmWriterInst information, by
271 /// clearing the Instructions vector.
272 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) {
273 Record *AsmWriter = Target.getAsmWriter();
274 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
275 bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
277 O <<
278 "/// printInstruction - This method is automatically generated by tablegen\n"
279 "/// from the instruction set description.\n"
280 "void " << Target.getName() << ClassName
281 << "::printInstruction(const MCInst *MI, "
282 << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "")
283 << "raw_ostream &O) {\n";
285 // Build an aggregate string, and build a table of offsets into it.
286 SequenceToOffsetTable<std::string> StringTable;
288 /// OpcodeInfo - This encodes the index of the string to use for the first
289 /// chunk of the output as well as indices used for operand printing.
290 std::vector<uint64_t> OpcodeInfo(NumberedInstructions.size());
291 const unsigned OpcodeInfoBits = 64;
293 // Add all strings to the string table upfront so it can generate an optimized
294 // representation.
295 for (AsmWriterInst &AWI : Instructions) {
296 if (AWI.Operands[0].OperandType ==
297 AsmWriterOperand::isLiteralTextOperand &&
298 !AWI.Operands[0].Str.empty()) {
299 std::string Str = AWI.Operands[0].Str;
300 UnescapeString(Str);
301 StringTable.add(Str);
305 StringTable.layout();
307 unsigned MaxStringIdx = 0;
308 for (AsmWriterInst &AWI : Instructions) {
309 unsigned Idx;
310 if (AWI.Operands[0].OperandType != AsmWriterOperand::isLiteralTextOperand ||
311 AWI.Operands[0].Str.empty()) {
312 // Something handled by the asmwriter printer, but with no leading string.
313 Idx = StringTable.get("");
314 } else {
315 std::string Str = AWI.Operands[0].Str;
316 UnescapeString(Str);
317 Idx = StringTable.get(Str);
318 MaxStringIdx = std::max(MaxStringIdx, Idx);
320 // Nuke the string from the operand list. It is now handled!
321 AWI.Operands.erase(AWI.Operands.begin());
324 // Bias offset by one since we want 0 as a sentinel.
325 OpcodeInfo[AWI.CGIIndex] = Idx+1;
328 // Figure out how many bits we used for the string index.
329 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
331 // To reduce code size, we compactify common instructions into a few bits
332 // in the opcode-indexed table.
333 unsigned BitsLeft = OpcodeInfoBits-AsmStrBits;
335 std::vector<std::vector<std::string>> TableDrivenOperandPrinters;
337 while (true) {
338 std::vector<std::string> UniqueOperandCommands;
339 std::vector<std::vector<unsigned>> InstIdxs;
340 std::vector<unsigned> NumInstOpsHandled;
341 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
342 NumInstOpsHandled, PassSubtarget);
344 // If we ran out of operands to print, we're done.
345 if (UniqueOperandCommands.empty()) break;
347 // Compute the number of bits we need to represent these cases, this is
348 // ceil(log2(numentries)).
349 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
351 // If we don't have enough bits for this operand, don't include it.
352 if (NumBits > BitsLeft) {
353 LLVM_DEBUG(errs() << "Not enough bits to densely encode " << NumBits
354 << " more bits\n");
355 break;
358 // Otherwise, we can include this in the initial lookup table. Add it in.
359 for (size_t i = 0, e = InstIdxs.size(); i != e; ++i) {
360 unsigned NumOps = NumInstOpsHandled[i];
361 for (unsigned Idx : InstIdxs[i]) {
362 OpcodeInfo[Instructions[Idx].CGIIndex] |=
363 (uint64_t)i << (OpcodeInfoBits-BitsLeft);
364 // Remove the info about this operand from the instruction.
365 AsmWriterInst &Inst = Instructions[Idx];
366 if (!Inst.Operands.empty()) {
367 assert(NumOps <= Inst.Operands.size() &&
368 "Can't remove this many ops!");
369 Inst.Operands.erase(Inst.Operands.begin(),
370 Inst.Operands.begin()+NumOps);
374 BitsLeft -= NumBits;
376 // Remember the handlers for this set of operands.
377 TableDrivenOperandPrinters.push_back(std::move(UniqueOperandCommands));
380 // Emit the string table itself.
381 O << " static const char AsmStrs[] = {\n";
382 StringTable.emit(O, printChar);
383 O << " };\n\n";
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";
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;
417 // Emit the initial tab character.
418 O << " O << \"\\t\";\n\n";
420 O << " // Emit the opcode for the instruction.\n";
421 O << BitsString;
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";
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];
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");
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";
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";
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";
465 O << " }\n\n";
467 BitsLeft -= NumBits;
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());
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());
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);
492 O << " }\n";
495 O << "}\n";
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++];
507 // "NoRegAltName" is special. We don't need to do a lookup for that,
508 // as it's just a reference to the default register name.
509 if (AltName == "" || AltName == "NoRegAltName") {
510 AsmName = Reg.TheDef->getValueAsString("AsmName");
511 if (AsmName.empty())
512 AsmName = Reg.getName();
513 } else {
514 // Make sure the register has an alternate name for this index.
515 std::vector<Record*> AltNameList =
516 Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
517 unsigned Idx = 0, e;
518 for (e = AltNameList.size();
519 Idx < e && (AltNameList[Idx]->getName() != AltName);
520 ++Idx)
522 // If the register has an alternate name for this index, use it.
523 // Otherwise, leave it empty as an error flag.
524 if (Idx < e) {
525 std::vector<StringRef> AltNames =
526 Reg.TheDef->getValueAsListOfStrings("AltNames");
527 if (AltNames.size() <= Idx)
528 PrintFatalError(Reg.TheDef->getLoc(),
529 "Register definition missing alt name for '" +
530 AltName + "'.");
531 AsmName = AltNames[Idx];
534 StringTable.add(AsmName);
537 StringTable.layout();
538 O << " static const char AsmStrs" << AltName << "[] = {\n";
539 StringTable.emit(O, printChar);
540 O << " };\n\n";
542 O << " static const " << getMinimalTypeForRange(StringTable.size() - 1, 32)
543 << " RegAsmOffset" << AltName << "[] = {";
544 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
545 if ((i % 14) == 0)
546 O << "\n ";
547 O << StringTable.get(AsmNames[i]) << ", ";
549 O << "\n };\n"
550 << "\n";
553 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
554 Record *AsmWriter = Target.getAsmWriter();
555 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
556 const auto &Registers = Target.getRegBank().getRegisters();
557 const std::vector<Record*> &AltNameIndices = Target.getRegAltNameIndices();
558 bool hasAltNames = AltNameIndices.size() > 1;
559 StringRef Namespace = Registers.front().TheDef->getValueAsString("Namespace");
561 O <<
562 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
563 "/// from the register set description. This returns the assembler name\n"
564 "/// for the specified register.\n"
565 "const char *" << Target.getName() << ClassName << "::";
566 if (hasAltNames)
567 O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
568 else
569 O << "getRegisterName(unsigned RegNo) {\n";
570 O << " assert(RegNo && RegNo < " << (Registers.size()+1)
571 << " && \"Invalid register number!\");\n"
572 << "\n";
574 if (hasAltNames) {
575 for (const Record *R : AltNameIndices)
576 emitRegisterNameString(O, R->getName(), Registers);
577 } else
578 emitRegisterNameString(O, "", Registers);
580 if (hasAltNames) {
581 O << " switch(AltIdx) {\n"
582 << " default: llvm_unreachable(\"Invalid register alt name index!\");\n";
583 for (const Record *R : AltNameIndices) {
584 StringRef AltName = R->getName();
585 O << " case ";
586 if (!Namespace.empty())
587 O << Namespace << "::";
588 O << AltName << ":\n";
589 if (R->isValueUnset("FallbackRegAltNameIndex"))
590 O << " assert(*(AsmStrs" << AltName << "+RegAsmOffset" << AltName
591 << "[RegNo-1]) &&\n"
592 << " \"Invalid alt name index for register!\");\n";
593 else {
594 O << " if (!*(AsmStrs" << AltName << "+RegAsmOffset" << AltName
595 << "[RegNo-1]))\n"
596 << " return getRegisterName(RegNo, ";
597 if (!Namespace.empty())
598 O << Namespace << "::";
599 O << R->getValueAsDef("FallbackRegAltNameIndex")->getName() << ");\n";
601 O << " return AsmStrs" << AltName << "+RegAsmOffset" << AltName
602 << "[RegNo-1];\n";
604 O << " }\n";
605 } else {
606 O << " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
607 << " \"Invalid alt name index for register!\");\n"
608 << " return AsmStrs+RegAsmOffset[RegNo-1];\n";
610 O << "}\n";
613 namespace {
615 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if
616 // they both have the same conditionals. In which case, we cannot print out the
617 // alias for that pattern.
618 class IAPrinter {
619 std::vector<std::string> Conds;
620 std::map<StringRef, std::pair<int, int>> OpMap;
622 std::string Result;
623 std::string AsmString;
625 public:
626 IAPrinter(std::string R, std::string AS)
627 : Result(std::move(R)), AsmString(std::move(AS)) {}
629 void addCond(const std::string &C) { Conds.push_back(C); }
631 void addOperand(StringRef Op, int OpIdx, int PrintMethodIdx = -1) {
632 assert(OpIdx >= 0 && OpIdx < 0xFE && "Idx out of range");
633 assert(PrintMethodIdx >= -1 && PrintMethodIdx < 0xFF &&
634 "Idx out of range");
635 OpMap[Op] = std::make_pair(OpIdx, PrintMethodIdx);
638 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
639 int getOpIndex(StringRef Op) { return OpMap[Op].first; }
640 std::pair<int, int> &getOpData(StringRef Op) { return OpMap[Op]; }
642 std::pair<StringRef, StringRef::iterator> parseName(StringRef::iterator Start,
643 StringRef::iterator End) {
644 StringRef::iterator I = Start;
645 StringRef::iterator Next;
646 if (*I == '{') {
647 // ${some_name}
648 Start = ++I;
649 while (I != End && *I != '}')
650 ++I;
651 Next = I;
652 // eat the final '}'
653 if (Next != End)
654 ++Next;
655 } else {
656 // $name, just eat the usual suspects.
657 while (I != End &&
658 ((*I >= 'a' && *I <= 'z') || (*I >= 'A' && *I <= 'Z') ||
659 (*I >= '0' && *I <= '9') || *I == '_'))
660 ++I;
661 Next = I;
664 return std::make_pair(StringRef(Start, I - Start), Next);
667 void print(raw_ostream &O) {
668 if (Conds.empty()) {
669 O.indent(6) << "return true;\n";
670 return;
673 O << "if (";
675 for (std::vector<std::string>::iterator
676 I = Conds.begin(), E = Conds.end(); I != E; ++I) {
677 if (I != Conds.begin()) {
678 O << " &&\n";
679 O.indent(8);
682 O << *I;
685 O << ") {\n";
686 O.indent(6) << "// " << Result << "\n";
688 // Directly mangle mapped operands into the string. Each operand is
689 // identified by a '$' sign followed by a byte identifying the number of the
690 // operand. We add one to the index to avoid zero bytes.
691 StringRef ASM(AsmString);
692 SmallString<128> OutString;
693 raw_svector_ostream OS(OutString);
694 for (StringRef::iterator I = ASM.begin(), E = ASM.end(); I != E;) {
695 OS << *I;
696 if (*I == '$') {
697 StringRef Name;
698 std::tie(Name, I) = parseName(++I, E);
699 assert(isOpMapped(Name) && "Unmapped operand!");
701 int OpIndex, PrintIndex;
702 std::tie(OpIndex, PrintIndex) = getOpData(Name);
703 if (PrintIndex == -1) {
704 // Can use the default printOperand route.
705 OS << format("\\x%02X", (unsigned char)OpIndex + 1);
706 } else
707 // 3 bytes if a PrintMethod is needed: 0xFF, the MCInst operand
708 // number, and which of our pre-detected Methods to call.
709 OS << format("\\xFF\\x%02X\\x%02X", OpIndex + 1, PrintIndex + 1);
710 } else {
711 ++I;
715 // Emit the string.
716 O.indent(6) << "AsmString = \"" << OutString << "\";\n";
718 O.indent(6) << "break;\n";
719 O.indent(4) << '}';
722 bool operator==(const IAPrinter &RHS) const {
723 if (Conds.size() != RHS.Conds.size())
724 return false;
726 unsigned Idx = 0;
727 for (const auto &str : Conds)
728 if (str != RHS.Conds[Idx++])
729 return false;
731 return true;
735 } // end anonymous namespace
737 static unsigned CountNumOperands(StringRef AsmString, unsigned Variant) {
738 return AsmString.count(' ') + AsmString.count('\t');
741 namespace {
743 struct AliasPriorityComparator {
744 typedef std::pair<CodeGenInstAlias, int> ValueType;
745 bool operator()(const ValueType &LHS, const ValueType &RHS) const {
746 if (LHS.second == RHS.second) {
747 // We don't actually care about the order, but for consistency it
748 // shouldn't depend on pointer comparisons.
749 return LessRecordByID()(LHS.first.TheDef, RHS.first.TheDef);
752 // Aliases with larger priorities should be considered first.
753 return LHS.second > RHS.second;
757 } // end anonymous namespace
759 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
760 Record *AsmWriter = Target.getAsmWriter();
762 O << "\n#ifdef PRINT_ALIAS_INSTR\n";
763 O << "#undef PRINT_ALIAS_INSTR\n\n";
765 //////////////////////////////
766 // Gather information about aliases we need to print
767 //////////////////////////////
769 // Emit the method that prints the alias instruction.
770 StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
771 unsigned Variant = AsmWriter->getValueAsInt("Variant");
772 bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
774 std::vector<Record*> AllInstAliases =
775 Records.getAllDerivedDefinitions("InstAlias");
777 // Create a map from the qualified name to a list of potential matches.
778 typedef std::set<std::pair<CodeGenInstAlias, int>, AliasPriorityComparator>
779 AliasWithPriority;
780 std::map<std::string, AliasWithPriority> AliasMap;
781 for (Record *R : AllInstAliases) {
782 int Priority = R->getValueAsInt("EmitPriority");
783 if (Priority < 1)
784 continue; // Aliases with priority 0 are never emitted.
786 const DagInit *DI = R->getValueAsDag("ResultInst");
787 AliasMap[getQualifiedName(DI->getOperatorAsDef(R->getLoc()))].insert(
788 std::make_pair(CodeGenInstAlias(R, Target), Priority));
791 // A map of which conditions need to be met for each instruction operand
792 // before it can be matched to the mnemonic.
793 std::map<std::string, std::vector<IAPrinter>> IAPrinterMap;
795 std::vector<std::string> PrintMethods;
797 // A list of MCOperandPredicates for all operands in use, and the reverse map
798 std::vector<const Record*> MCOpPredicates;
799 DenseMap<const Record*, unsigned> MCOpPredicateMap;
801 for (auto &Aliases : AliasMap) {
802 for (auto &Alias : Aliases.second) {
803 const CodeGenInstAlias &CGA = Alias.first;
804 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
805 std::string FlatInstAsmString =
806 CodeGenInstruction::FlattenAsmStringVariants(CGA.ResultInst->AsmString,
807 Variant);
808 unsigned NumResultOps = CountNumOperands(FlatInstAsmString, Variant);
810 std::string FlatAliasAsmString =
811 CodeGenInstruction::FlattenAsmStringVariants(CGA.AsmString,
812 Variant);
814 // Don't emit the alias if it has more operands than what it's aliasing.
815 if (NumResultOps < CountNumOperands(FlatAliasAsmString, Variant))
816 continue;
818 IAPrinter IAP(CGA.Result->getAsString(), FlatAliasAsmString);
820 StringRef Namespace = Target.getName();
821 std::vector<Record *> ReqFeatures;
822 if (PassSubtarget) {
823 // We only consider ReqFeatures predicates if PassSubtarget
824 std::vector<Record *> RF =
825 CGA.TheDef->getValueAsListOfDefs("Predicates");
826 copy_if(RF, std::back_inserter(ReqFeatures), [](Record *R) {
827 return R->getValueAsBit("AssemblerMatcherPredicate");
831 unsigned NumMIOps = 0;
832 for (auto &ResultInstOpnd : CGA.ResultInst->Operands)
833 NumMIOps += ResultInstOpnd.MINumOperands;
835 std::string Cond;
836 Cond = std::string("MI->getNumOperands() == ") + utostr(NumMIOps);
837 IAP.addCond(Cond);
839 bool CantHandle = false;
841 unsigned MIOpNum = 0;
842 for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
843 // Skip over tied operands as they're not part of an alias declaration.
844 auto &Operands = CGA.ResultInst->Operands;
845 while (true) {
846 unsigned OpNum = Operands.getSubOperandNumber(MIOpNum).first;
847 if (Operands[OpNum].MINumOperands == 1 &&
848 Operands[OpNum].getTiedRegister() != -1) {
849 // Tied operands of different RegisterClass should be explicit within
850 // an instruction's syntax and so cannot be skipped.
851 int TiedOpNum = Operands[OpNum].getTiedRegister();
852 if (Operands[OpNum].Rec->getName() ==
853 Operands[TiedOpNum].Rec->getName()) {
854 ++MIOpNum;
855 continue;
858 break;
861 std::string Op = "MI->getOperand(" + utostr(MIOpNum) + ")";
863 const CodeGenInstAlias::ResultOperand &RO = CGA.ResultOperands[i];
865 switch (RO.Kind) {
866 case CodeGenInstAlias::ResultOperand::K_Record: {
867 const Record *Rec = RO.getRecord();
868 StringRef ROName = RO.getName();
869 int PrintMethodIdx = -1;
871 // These two may have a PrintMethod, which we want to record (if it's
872 // the first time we've seen it) and provide an index for the aliasing
873 // code to use.
874 if (Rec->isSubClassOf("RegisterOperand") ||
875 Rec->isSubClassOf("Operand")) {
876 StringRef PrintMethod = Rec->getValueAsString("PrintMethod");
877 if (PrintMethod != "" && PrintMethod != "printOperand") {
878 PrintMethodIdx =
879 llvm::find(PrintMethods, PrintMethod) - PrintMethods.begin();
880 if (static_cast<unsigned>(PrintMethodIdx) == PrintMethods.size())
881 PrintMethods.push_back(PrintMethod);
885 if (Rec->isSubClassOf("RegisterOperand"))
886 Rec = Rec->getValueAsDef("RegClass");
887 if (Rec->isSubClassOf("RegisterClass")) {
888 IAP.addCond(Op + ".isReg()");
890 if (!IAP.isOpMapped(ROName)) {
891 IAP.addOperand(ROName, MIOpNum, PrintMethodIdx);
892 Record *R = CGA.ResultOperands[i].getRecord();
893 if (R->isSubClassOf("RegisterOperand"))
894 R = R->getValueAsDef("RegClass");
895 Cond = std::string("MRI.getRegClass(") + Target.getName().str() +
896 "::" + R->getName().str() + "RegClassID).contains(" + Op +
897 ".getReg())";
898 } else {
899 Cond = Op + ".getReg() == MI->getOperand(" +
900 utostr(IAP.getOpIndex(ROName)) + ").getReg()";
902 } else {
903 // Assume all printable operands are desired for now. This can be
904 // overridden in the InstAlias instantiation if necessary.
905 IAP.addOperand(ROName, MIOpNum, PrintMethodIdx);
907 // There might be an additional predicate on the MCOperand
908 unsigned Entry = MCOpPredicateMap[Rec];
909 if (!Entry) {
910 if (!Rec->isValueUnset("MCOperandPredicate")) {
911 MCOpPredicates.push_back(Rec);
912 Entry = MCOpPredicates.size();
913 MCOpPredicateMap[Rec] = Entry;
914 } else
915 break; // No conditions on this operand at all
917 Cond = (Target.getName() + ClassName + "ValidateMCOperand(" + Op +
918 ", STI, " + utostr(Entry) + ")")
919 .str();
921 // for all subcases of ResultOperand::K_Record:
922 IAP.addCond(Cond);
923 break;
925 case CodeGenInstAlias::ResultOperand::K_Imm: {
926 // Just because the alias has an immediate result, doesn't mean the
927 // MCInst will. An MCExpr could be present, for example.
928 IAP.addCond(Op + ".isImm()");
930 Cond = Op + ".getImm() == " + itostr(CGA.ResultOperands[i].getImm());
931 IAP.addCond(Cond);
932 break;
934 case CodeGenInstAlias::ResultOperand::K_Reg:
935 // If this is zero_reg, something's playing tricks we're not
936 // equipped to handle.
937 if (!CGA.ResultOperands[i].getRegister()) {
938 CantHandle = true;
939 break;
942 Cond = Op + ".getReg() == " + Target.getName().str() + "::" +
943 CGA.ResultOperands[i].getRegister()->getName().str();
944 IAP.addCond(Cond);
945 break;
948 MIOpNum += RO.getMINumOperands();
951 if (CantHandle) continue;
953 for (auto I = ReqFeatures.cbegin(); I != ReqFeatures.cend(); I++) {
954 Record *R = *I;
955 StringRef AsmCondString = R->getValueAsString("AssemblerCondString");
957 // AsmCondString has syntax [!]F(,[!]F)*
958 SmallVector<StringRef, 4> Ops;
959 SplitString(AsmCondString, Ops, ",");
960 assert(!Ops.empty() && "AssemblerCondString cannot be empty");
962 for (auto &Op : Ops) {
963 assert(!Op.empty() && "Empty operator");
964 if (Op[0] == '!')
965 Cond = ("!STI.getFeatureBits()[" + Namespace + "::" + Op.substr(1) +
966 "]")
967 .str();
968 else
969 Cond =
970 ("STI.getFeatureBits()[" + Namespace + "::" + Op + "]").str();
971 IAP.addCond(Cond);
975 IAPrinterMap[Aliases.first].push_back(std::move(IAP));
979 //////////////////////////////
980 // Write out the printAliasInstr function
981 //////////////////////////////
983 std::string Header;
984 raw_string_ostream HeaderO(Header);
986 HeaderO << "bool " << Target.getName() << ClassName
987 << "::printAliasInstr(const MCInst"
988 << " *MI, " << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "")
989 << "raw_ostream &OS) {\n";
991 std::string Cases;
992 raw_string_ostream CasesO(Cases);
994 for (auto &Entry : IAPrinterMap) {
995 std::vector<IAPrinter> &IAPs = Entry.second;
996 std::vector<IAPrinter*> UniqueIAPs;
998 for (auto &LHS : IAPs) {
999 bool IsDup = false;
1000 for (const auto &RHS : IAPs) {
1001 if (&LHS != &RHS && LHS == RHS) {
1002 IsDup = true;
1003 break;
1007 if (!IsDup)
1008 UniqueIAPs.push_back(&LHS);
1011 if (UniqueIAPs.empty()) continue;
1013 CasesO.indent(2) << "case " << Entry.first << ":\n";
1015 for (IAPrinter *IAP : UniqueIAPs) {
1016 CasesO.indent(4);
1017 IAP->print(CasesO);
1018 CasesO << '\n';
1021 CasesO.indent(4) << "return false;\n";
1024 if (CasesO.str().empty()) {
1025 O << HeaderO.str();
1026 O << " return false;\n";
1027 O << "}\n\n";
1028 O << "#endif // PRINT_ALIAS_INSTR\n";
1029 return;
1032 if (!MCOpPredicates.empty())
1033 O << "static bool " << Target.getName() << ClassName
1034 << "ValidateMCOperand(const MCOperand &MCOp,\n"
1035 << " const MCSubtargetInfo &STI,\n"
1036 << " unsigned PredicateIndex);\n";
1038 O << HeaderO.str();
1039 O.indent(2) << "const char *AsmString;\n";
1040 O.indent(2) << "switch (MI->getOpcode()) {\n";
1041 O.indent(2) << "default: return false;\n";
1042 O << CasesO.str();
1043 O.indent(2) << "}\n\n";
1045 // Code that prints the alias, replacing the operands with the ones from the
1046 // MCInst.
1047 O << " unsigned I = 0;\n";
1048 O << " while (AsmString[I] != ' ' && AsmString[I] != '\\t' &&\n";
1049 O << " AsmString[I] != '$' && AsmString[I] != '\\0')\n";
1050 O << " ++I;\n";
1051 O << " OS << '\\t' << StringRef(AsmString, I);\n";
1053 O << " if (AsmString[I] != '\\0') {\n";
1054 O << " if (AsmString[I] == ' ' || AsmString[I] == '\\t') {\n";
1055 O << " OS << '\\t';\n";
1056 O << " ++I;\n";
1057 O << " }\n";
1058 O << " do {\n";
1059 O << " if (AsmString[I] == '$') {\n";
1060 O << " ++I;\n";
1061 O << " if (AsmString[I] == (char)0xff) {\n";
1062 O << " ++I;\n";
1063 O << " int OpIdx = AsmString[I++] - 1;\n";
1064 O << " int PrintMethodIdx = AsmString[I++] - 1;\n";
1065 O << " printCustomAliasOperand(MI, OpIdx, PrintMethodIdx, ";
1066 O << (PassSubtarget ? "STI, " : "");
1067 O << "OS);\n";
1068 O << " } else\n";
1069 O << " printOperand(MI, unsigned(AsmString[I++]) - 1, ";
1070 O << (PassSubtarget ? "STI, " : "");
1071 O << "OS);\n";
1072 O << " } else {\n";
1073 O << " OS << AsmString[I++];\n";
1074 O << " }\n";
1075 O << " } while (AsmString[I] != '\\0');\n";
1076 O << " }\n\n";
1078 O << " return true;\n";
1079 O << "}\n\n";
1081 //////////////////////////////
1082 // Write out the printCustomAliasOperand function
1083 //////////////////////////////
1085 O << "void " << Target.getName() << ClassName << "::"
1086 << "printCustomAliasOperand(\n"
1087 << " const MCInst *MI, unsigned OpIdx,\n"
1088 << " unsigned PrintMethodIdx,\n"
1089 << (PassSubtarget ? " const MCSubtargetInfo &STI,\n" : "")
1090 << " raw_ostream &OS) {\n";
1091 if (PrintMethods.empty())
1092 O << " llvm_unreachable(\"Unknown PrintMethod kind\");\n";
1093 else {
1094 O << " switch (PrintMethodIdx) {\n"
1095 << " default:\n"
1096 << " llvm_unreachable(\"Unknown PrintMethod kind\");\n"
1097 << " break;\n";
1099 for (unsigned i = 0; i < PrintMethods.size(); ++i) {
1100 O << " case " << i << ":\n"
1101 << " " << PrintMethods[i] << "(MI, OpIdx, "
1102 << (PassSubtarget ? "STI, " : "") << "OS);\n"
1103 << " break;\n";
1105 O << " }\n";
1107 O << "}\n\n";
1109 if (!MCOpPredicates.empty()) {
1110 O << "static bool " << Target.getName() << ClassName
1111 << "ValidateMCOperand(const MCOperand &MCOp,\n"
1112 << " const MCSubtargetInfo &STI,\n"
1113 << " unsigned PredicateIndex) {\n"
1114 << " switch (PredicateIndex) {\n"
1115 << " default:\n"
1116 << " llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n"
1117 << " break;\n";
1119 for (unsigned i = 0; i < MCOpPredicates.size(); ++i) {
1120 Init *MCOpPred = MCOpPredicates[i]->getValueInit("MCOperandPredicate");
1121 if (CodeInit *SI = dyn_cast<CodeInit>(MCOpPred)) {
1122 O << " case " << i + 1 << ": {\n"
1123 << SI->getValue() << "\n"
1124 << " }\n";
1125 } else
1126 llvm_unreachable("Unexpected MCOperandPredicate field!");
1128 O << " }\n"
1129 << "}\n\n";
1132 O << "#endif // PRINT_ALIAS_INSTR\n";
1135 AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) {
1136 Record *AsmWriter = Target.getAsmWriter();
1137 unsigned Variant = AsmWriter->getValueAsInt("Variant");
1139 // Get the instruction numbering.
1140 NumberedInstructions = Target.getInstructionsByEnumValue();
1142 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
1143 const CodeGenInstruction *I = NumberedInstructions[i];
1144 if (!I->AsmString.empty() && I->TheDef->getName() != "PHI")
1145 Instructions.emplace_back(*I, i, Variant);
1149 void AsmWriterEmitter::run(raw_ostream &O) {
1150 EmitPrintInstruction(O);
1151 EmitGetRegisterName(O);
1152 EmitPrintAliasInstruction(O);
1155 namespace llvm {
1157 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) {
1158 emitSourceFileHeader("Assembly Writer Source Fragment", OS);
1159 AsmWriterEmitter(RK).run(OS);
1162 } // end namespace llvm