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