]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/llvm/utils/TableGen/AsmWriterEmitter.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm-project / 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/FormatVariadic.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/TableGen/Error.h"
36 #include "llvm/TableGen/Record.h"
37 #include "llvm/TableGen/TableGenBackend.h"
38 #include <algorithm>
39 #include <cassert>
40 #include <cstddef>
41 #include <cstdint>
42 #include <deque>
43 #include <iterator>
44 #include <map>
45 #include <set>
46 #include <string>
47 #include <tuple>
48 #include <utility>
49 #include <vector>
50
51 using namespace llvm;
52
53 #define DEBUG_TYPE "asm-writer-emitter"
54
55 namespace {
56
57 class AsmWriterEmitter {
58   RecordKeeper &Records;
59   CodeGenTarget Target;
60   ArrayRef<const CodeGenInstruction *> NumberedInstructions;
61   std::vector<AsmWriterInst> Instructions;
62
63 public:
64   AsmWriterEmitter(RecordKeeper &R);
65
66   void run(raw_ostream &o);
67
68 private:
69   void EmitPrintInstruction(raw_ostream &o);
70   void EmitGetRegisterName(raw_ostream &o);
71   void EmitPrintAliasInstruction(raw_ostream &O);
72
73   void FindUniqueOperandCommands(std::vector<std::string> &UOC,
74                                  std::vector<std::vector<unsigned>> &InstIdxs,
75                                  std::vector<unsigned> &InstOpsUsed,
76                                  bool PassSubtarget) const;
77 };
78
79 } // end anonymous namespace
80
81 static void PrintCases(std::vector<std::pair<std::string,
82                        AsmWriterOperand>> &OpsToPrint, raw_ostream &O,
83                        bool PassSubtarget) {
84   O << "    case " << OpsToPrint.back().first << ":";
85   AsmWriterOperand TheOp = OpsToPrint.back().second;
86   OpsToPrint.pop_back();
87
88   // Check to see if any other operands are identical in this list, and if so,
89   // emit a case label for them.
90   for (unsigned i = OpsToPrint.size(); i != 0; --i)
91     if (OpsToPrint[i-1].second == TheOp) {
92       O << "\n    case " << OpsToPrint[i-1].first << ":";
93       OpsToPrint.erase(OpsToPrint.begin()+i-1);
94     }
95
96   // Finally, emit the code.
97   O << "\n      " << TheOp.getCode(PassSubtarget);
98   O << "\n      break;\n";
99 }
100
101 /// EmitInstructions - Emit the last instruction in the vector and any other
102 /// instructions that are suitably similar to it.
103 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
104                              raw_ostream &O, bool PassSubtarget) {
105   AsmWriterInst FirstInst = Insts.back();
106   Insts.pop_back();
107
108   std::vector<AsmWriterInst> SimilarInsts;
109   unsigned DifferingOperand = ~0;
110   for (unsigned i = Insts.size(); i != 0; --i) {
111     unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
112     if (DiffOp != ~1U) {
113       if (DifferingOperand == ~0U)  // First match!
114         DifferingOperand = DiffOp;
115
116       // If this differs in the same operand as the rest of the instructions in
117       // this class, move it to the SimilarInsts list.
118       if (DifferingOperand == DiffOp || DiffOp == ~0U) {
119         SimilarInsts.push_back(Insts[i-1]);
120         Insts.erase(Insts.begin()+i-1);
121       }
122     }
123   }
124
125   O << "  case " << FirstInst.CGI->Namespace << "::"
126     << FirstInst.CGI->TheDef->getName() << ":\n";
127   for (const AsmWriterInst &AWI : SimilarInsts)
128     O << "  case " << AWI.CGI->Namespace << "::"
129       << AWI.CGI->TheDef->getName() << ":\n";
130   for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
131     if (i != DifferingOperand) {
132       // If the operand is the same for all instructions, just print it.
133       O << "    " << FirstInst.Operands[i].getCode(PassSubtarget);
134     } else {
135       // If this is the operand that varies between all of the instructions,
136       // emit a switch for just this operand now.
137       O << "    switch (MI->getOpcode()) {\n";
138       O << "    default: llvm_unreachable(\"Unexpected opcode.\");\n";
139       std::vector<std::pair<std::string, AsmWriterOperand>> OpsToPrint;
140       OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace.str() + "::" +
141                                           FirstInst.CGI->TheDef->getName().str(),
142                                           FirstInst.Operands[i]));
143
144       for (const AsmWriterInst &AWI : SimilarInsts) {
145         OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace.str()+"::" +
146                                             AWI.CGI->TheDef->getName().str(),
147                                             AWI.Operands[i]));
148       }
149       std::reverse(OpsToPrint.begin(), OpsToPrint.end());
150       while (!OpsToPrint.empty())
151         PrintCases(OpsToPrint, O, PassSubtarget);
152       O << "    }";
153     }
154     O << "\n";
155   }
156   O << "    break;\n";
157 }
158
159 void AsmWriterEmitter::
160 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
161                           std::vector<std::vector<unsigned>> &InstIdxs,
162                           std::vector<unsigned> &InstOpsUsed,
163                           bool PassSubtarget) const {
164   // This vector parallels UniqueOperandCommands, keeping track of which
165   // instructions each case are used for.  It is a comma separated string of
166   // enums.
167   std::vector<std::string> InstrsForCase;
168   InstrsForCase.resize(UniqueOperandCommands.size());
169   InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
170
171   for (size_t i = 0, e = Instructions.size(); i != e; ++i) {
172     const AsmWriterInst &Inst = Instructions[i];
173     if (Inst.Operands.empty())
174       continue;   // Instruction already done.
175
176     std::string Command = "    "+Inst.Operands[0].getCode(PassSubtarget)+"\n";
177
178     // Check to see if we already have 'Command' in UniqueOperandCommands.
179     // If not, add it.
180     auto I = llvm::find(UniqueOperandCommands, Command);
181     if (I != UniqueOperandCommands.end()) {
182       size_t idx = I - UniqueOperandCommands.begin();
183       InstrsForCase[idx] += ", ";
184       InstrsForCase[idx] += Inst.CGI->TheDef->getName();
185       InstIdxs[idx].push_back(i);
186     } else {
187       UniqueOperandCommands.push_back(std::move(Command));
188       InstrsForCase.push_back(Inst.CGI->TheDef->getName());
189       InstIdxs.emplace_back();
190       InstIdxs.back().push_back(i);
191
192       // This command matches one operand so far.
193       InstOpsUsed.push_back(1);
194     }
195   }
196
197   // For each entry of UniqueOperandCommands, there is a set of instructions
198   // that uses it.  If the next command of all instructions in the set are
199   // identical, fold it into the command.
200   for (size_t CommandIdx = 0, e = UniqueOperandCommands.size();
201        CommandIdx != e; ++CommandIdx) {
202
203     const auto &Idxs = InstIdxs[CommandIdx];
204
205     for (unsigned Op = 1; ; ++Op) {
206       // Find the first instruction in the set.
207       const AsmWriterInst &FirstInst = Instructions[Idxs.front()];
208       // If this instruction has no more operands, we isn't anything to merge
209       // into this command.
210       if (FirstInst.Operands.size() == Op)
211         break;
212
213       // Otherwise, scan to see if all of the other instructions in this command
214       // set share the operand.
215       if (std::any_of(Idxs.begin()+1, Idxs.end(),
216                       [&](unsigned Idx) {
217                         const AsmWriterInst &OtherInst = Instructions[Idx];
218                         return OtherInst.Operands.size() == Op ||
219                           OtherInst.Operands[Op] != FirstInst.Operands[Op];
220                       }))
221         break;
222
223       // Okay, everything in this command set has the same next operand.  Add it
224       // to UniqueOperandCommands and remember that it was consumed.
225       std::string Command = "    " +
226         FirstInst.Operands[Op].getCode(PassSubtarget) + "\n";
227
228       UniqueOperandCommands[CommandIdx] += Command;
229       InstOpsUsed[CommandIdx]++;
230     }
231   }
232
233   // Prepend some of the instructions each case is used for onto the case val.
234   for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
235     std::string Instrs = InstrsForCase[i];
236     if (Instrs.size() > 70) {
237       Instrs.erase(Instrs.begin()+70, Instrs.end());
238       Instrs += "...";
239     }
240
241     if (!Instrs.empty())
242       UniqueOperandCommands[i] = "    // " + Instrs + "\n" +
243         UniqueOperandCommands[i];
244   }
245 }
246
247 static void UnescapeString(std::string &Str) {
248   for (unsigned i = 0; i != Str.size(); ++i) {
249     if (Str[i] == '\\' && i != Str.size()-1) {
250       switch (Str[i+1]) {
251       default: continue;  // Don't execute the code after the switch.
252       case 'a': Str[i] = '\a'; break;
253       case 'b': Str[i] = '\b'; break;
254       case 'e': Str[i] = 27; break;
255       case 'f': Str[i] = '\f'; break;
256       case 'n': Str[i] = '\n'; break;
257       case 'r': Str[i] = '\r'; break;
258       case 't': Str[i] = '\t'; break;
259       case 'v': Str[i] = '\v'; break;
260       case '"': Str[i] = '\"'; break;
261       case '\'': Str[i] = '\''; break;
262       case '\\': Str[i] = '\\'; break;
263       }
264       // Nuke the second character.
265       Str.erase(Str.begin()+i+1);
266     }
267   }
268 }
269
270 /// EmitPrintInstruction - Generate the code for the "printInstruction" method
271 /// implementation. Destroys all instances of AsmWriterInst information, by
272 /// clearing the Instructions vector.
273 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) {
274   Record *AsmWriter = Target.getAsmWriter();
275   StringRef ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
276   bool PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
277
278   O << "/// printInstruction - This method is automatically generated by "
279        "tablegen\n"
280        "/// from the instruction set description.\n"
281        "void "
282     << Target.getName() << ClassName
283     << "::printInstruction(const MCInst *MI, uint64_t Address, "
284     << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "")
285     << "raw_ostream &O) {\n";
286
287   // Build an aggregate string, and build a table of offsets into it.
288   SequenceToOffsetTable<std::string> StringTable;
289
290   /// OpcodeInfo - This encodes the index of the string to use for the first
291   /// chunk of the output as well as indices used for operand printing.
292   std::vector<uint64_t> OpcodeInfo(NumberedInstructions.size());
293   const unsigned OpcodeInfoBits = 64;
294
295   // Add all strings to the string table upfront so it can generate an optimized
296   // representation.
297   for (AsmWriterInst &AWI : Instructions) {
298     if (AWI.Operands[0].OperandType ==
299                  AsmWriterOperand::isLiteralTextOperand &&
300         !AWI.Operands[0].Str.empty()) {
301       std::string Str = AWI.Operands[0].Str;
302       UnescapeString(Str);
303       StringTable.add(Str);
304     }
305   }
306
307   StringTable.layout();
308
309   unsigned MaxStringIdx = 0;
310   for (AsmWriterInst &AWI : Instructions) {
311     unsigned Idx;
312     if (AWI.Operands[0].OperandType != AsmWriterOperand::isLiteralTextOperand ||
313         AWI.Operands[0].Str.empty()) {
314       // Something handled by the asmwriter printer, but with no leading string.
315       Idx = StringTable.get("");
316     } else {
317       std::string Str = AWI.Operands[0].Str;
318       UnescapeString(Str);
319       Idx = StringTable.get(Str);
320       MaxStringIdx = std::max(MaxStringIdx, Idx);
321
322       // Nuke the string from the operand list.  It is now handled!
323       AWI.Operands.erase(AWI.Operands.begin());
324     }
325
326     // Bias offset by one since we want 0 as a sentinel.
327     OpcodeInfo[AWI.CGIIndex] = Idx+1;
328   }
329
330   // Figure out how many bits we used for the string index.
331   unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
332
333   // To reduce code size, we compactify common instructions into a few bits
334   // in the opcode-indexed table.
335   unsigned BitsLeft = OpcodeInfoBits-AsmStrBits;
336
337   std::vector<std::vector<std::string>> TableDrivenOperandPrinters;
338
339   while (true) {
340     std::vector<std::string> UniqueOperandCommands;
341     std::vector<std::vector<unsigned>> InstIdxs;
342     std::vector<unsigned> NumInstOpsHandled;
343     FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
344                               NumInstOpsHandled, PassSubtarget);
345
346     // If we ran out of operands to print, we're done.
347     if (UniqueOperandCommands.empty()) break;
348
349     // Compute the number of bits we need to represent these cases, this is
350     // ceil(log2(numentries)).
351     unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
352
353     // If we don't have enough bits for this operand, don't include it.
354     if (NumBits > BitsLeft) {
355       LLVM_DEBUG(errs() << "Not enough bits to densely encode " << NumBits
356                         << " more bits\n");
357       break;
358     }
359
360     // Otherwise, we can include this in the initial lookup table.  Add it in.
361     for (size_t i = 0, e = InstIdxs.size(); i != e; ++i) {
362       unsigned NumOps = NumInstOpsHandled[i];
363       for (unsigned Idx : InstIdxs[i]) {
364         OpcodeInfo[Instructions[Idx].CGIIndex] |=
365           (uint64_t)i << (OpcodeInfoBits-BitsLeft);
366         // Remove the info about this operand from the instruction.
367         AsmWriterInst &Inst = Instructions[Idx];
368         if (!Inst.Operands.empty()) {
369           assert(NumOps <= Inst.Operands.size() &&
370                  "Can't remove this many ops!");
371           Inst.Operands.erase(Inst.Operands.begin(),
372                               Inst.Operands.begin()+NumOps);
373         }
374       }
375     }
376     BitsLeft -= NumBits;
377
378     // Remember the handlers for this set of operands.
379     TableDrivenOperandPrinters.push_back(std::move(UniqueOperandCommands));
380   }
381
382   // Emit the string table itself.
383   O << "  static const char AsmStrs[] = {\n";
384   StringTable.emit(O, printChar);
385   O << "  };\n\n";
386
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)
394          << "_t Bits = 0;\n";
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
402       << "[] = {\n";
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";
406     }
407     O << "  };\n\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.
415     Shift += TableSize;
416     ++Table;
417   }
418
419   // Emit the initial tab character.
420   O << "  O << \"\\t\";\n\n";
421
422   O << "  // Emit the opcode for the instruction.\n";
423   O << BitsString;
424
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";
428
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];
433
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");
438
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";
442
443     if (Commands.size() == 2) {
444       // Emit two possibilitys with if/else.
445       O << "  if ((Bits >> "
446         << (OpcodeInfoBits-BitsLeft) << ") & "
447         << ((1 << NumBits)-1) << ") {\n"
448         << Commands[1]
449         << "  } else {\n"
450         << Commands[0]
451         << "  }\n\n";
452     } else if (Commands.size() == 1) {
453       // Emit a single possibility.
454       O << Commands[0] << "\n\n";
455     } else {
456       O << "  switch ((Bits >> "
457         << (OpcodeInfoBits-BitsLeft) << ") & "
458         << ((1 << NumBits)-1) << ") {\n"
459         << "  default: llvm_unreachable(\"Invalid command number.\");\n";
460
461       // Print out all the cases.
462       for (unsigned j = 0, e = Commands.size(); j != e; ++j) {
463         O << "  case " << j << ":\n";
464         O << Commands[j];
465         O << "    break;\n";
466       }
467       O << "  }\n\n";
468     }
469     BitsLeft -= NumBits;
470   }
471
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());
476
477
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());
481
482
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
486   // instructions.
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);
493
494     O << "  }\n";
495   }
496
497   O << "}\n";
498 }
499
500 static void
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());
505   unsigned i = 0;
506   for (const auto &Reg : Registers) {
507     std::string &AsmName = AsmNames[i++];
508
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");
513       if (AsmName.empty())
514         AsmName = Reg.getName();
515     } else {
516       // Make sure the register has an alternate name for this index.
517       std::vector<Record*> AltNameList =
518         Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
519       unsigned Idx = 0, e;
520       for (e = AltNameList.size();
521            Idx < e && (AltNameList[Idx]->getName() != AltName);
522            ++Idx)
523         ;
524       // If the register has an alternate name for this index, use it.
525       // Otherwise, leave it empty as an error flag.
526       if (Idx < e) {
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 '" +
532                           AltName + "'.");
533         AsmName = AltNames[Idx];
534       }
535     }
536     StringTable.add(AsmName);
537   }
538
539   StringTable.layout();
540   O << "  static const char AsmStrs" << AltName << "[] = {\n";
541   StringTable.emit(O, printChar);
542   O << "  };\n\n";
543
544   O << "  static const " << getMinimalTypeForRange(StringTable.size() - 1, 32)
545     << " RegAsmOffset" << AltName << "[] = {";
546   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
547     if ((i % 14) == 0)
548       O << "\n    ";
549     O << StringTable.get(AsmNames[i]) << ", ";
550   }
551   O << "\n  };\n"
552     << "\n";
553 }
554
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");
562
563   O <<
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 << "::";
568   if (hasAltNames)
569     O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
570   else
571     O << "getRegisterName(unsigned RegNo) {\n";
572   O << "  assert(RegNo && RegNo < " << (Registers.size()+1)
573     << " && \"Invalid register number!\");\n"
574     << "\n";
575
576   if (hasAltNames) {
577     for (const Record *R : AltNameIndices)
578       emitRegisterNameString(O, R->getName(), Registers);
579   } else
580     emitRegisterNameString(O, "", Registers);
581
582   if (hasAltNames) {
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();
587       O << "  case ";
588       if (!Namespace.empty())
589         O << Namespace << "::";
590       O << AltName << ":\n";
591       if (R->isValueUnset("FallbackRegAltNameIndex"))
592         O << "    assert(*(AsmStrs" << AltName << "+RegAsmOffset" << AltName
593           << "[RegNo-1]) &&\n"
594           << "           \"Invalid alt name index for register!\");\n";
595       else {
596         O << "    if (!*(AsmStrs" << AltName << "+RegAsmOffset" << AltName
597           << "[RegNo-1]))\n"
598           << "      return getRegisterName(RegNo, ";
599         if (!Namespace.empty())
600           O << Namespace << "::";
601         O << R->getValueAsDef("FallbackRegAltNameIndex")->getName() << ");\n";
602       }
603       O << "    return AsmStrs" << AltName << "+RegAsmOffset" << AltName
604         << "[RegNo-1];\n";
605     }
606     O << "  }\n";
607   } else {
608     O << "  assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
609       << "          \"Invalid alt name index for register!\");\n"
610       << "  return AsmStrs+RegAsmOffset[RegNo-1];\n";
611   }
612   O << "}\n";
613 }
614
615 namespace {
616
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.
620 class IAPrinter {
621   std::map<StringRef, std::pair<int, int>> OpMap;
622
623   std::vector<std::string> Conds;
624
625   std::string Result;
626   std::string AsmString;
627
628   unsigned NumMIOps;
629
630 public:
631   IAPrinter(std::string R, std::string AS, unsigned NumMIOps)
632       : Result(std::move(R)), AsmString(std::move(AS)), NumMIOps(NumMIOps) {}
633
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(); }
637
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 &&
641            "Idx out of range");
642     OpMap[Op] = std::make_pair(OpIdx, PrintMethodIdx);
643   }
644
645   unsigned getNumMIOps() { return NumMIOps; }
646
647   StringRef getResult() { return Result; }
648
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]; }
652
653   std::pair<StringRef, StringRef::iterator> parseName(StringRef::iterator Start,
654                                                       StringRef::iterator End) {
655     StringRef::iterator I = Start;
656     StringRef::iterator Next;
657     if (*I == '{') {
658       // ${some_name}
659       Start = ++I;
660       while (I != End && *I != '}')
661         ++I;
662       Next = I;
663       // eat the final '}'
664       if (Next != End)
665         ++Next;
666     } else {
667       // $name, just eat the usual suspects.
668       while (I != End &&
669              ((*I >= 'a' && *I <= 'z') || (*I >= 'A' && *I <= 'Z') ||
670               (*I >= '0' && *I <= '9') || *I == '_'))
671         ++I;
672       Next = I;
673     }
674
675     return std::make_pair(StringRef(Start, I - Start), Next);
676   }
677
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;) {
686       OS << *I;
687       ++UnescapedSize;
688       if (*I == '$') {
689         StringRef Name;
690         std::tie(Name, I) = parseName(++I, E);
691         assert(isOpMapped(Name) && "Unmapped operand!");
692
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);
698           ++UnescapedSize;
699         } else {
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);
703           UnescapedSize += 3;
704         }
705       } else {
706         ++I;
707       }
708     }
709
710     OS.flush();
711     return OutString;
712   }
713
714   bool operator==(const IAPrinter &RHS) const {
715     if (NumMIOps != RHS.NumMIOps)
716       return false;
717     if (Conds.size() != RHS.Conds.size())
718       return false;
719
720     unsigned Idx = 0;
721     for (const auto &str : Conds)
722       if (str != RHS.Conds[Idx++])
723         return false;
724
725     return true;
726   }
727 };
728
729 } // end anonymous namespace
730
731 static unsigned CountNumOperands(StringRef AsmString, unsigned Variant) {
732   return AsmString.count(' ') + AsmString.count('\t');
733 }
734
735 namespace {
736
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);
744     }
745
746     // Aliases with larger priorities should be considered first.
747     return LHS.second > RHS.second;
748   }
749 };
750
751 } // end anonymous namespace
752
753 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
754   Record *AsmWriter = Target.getAsmWriter();
755
756   O << "\n#ifdef PRINT_ALIAS_INSTR\n";
757   O << "#undef PRINT_ALIAS_INSTR\n\n";
758
759   //////////////////////////////
760   // Gather information about aliases we need to print
761   //////////////////////////////
762
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");
767
768   std::vector<Record*> AllInstAliases =
769     Records.getAllDerivedDefinitions("InstAlias");
770
771   // Create a map from the qualified name to a list of potential matches.
772   typedef std::set<std::pair<CodeGenInstAlias, int>, AliasPriorityComparator>
773       AliasWithPriority;
774   std::map<std::string, AliasWithPriority> AliasMap;
775   for (Record *R : AllInstAliases) {
776     int Priority = R->getValueAsInt("EmitPriority");
777     if (Priority < 1)
778       continue; // Aliases with priority 0 are never emitted.
779
780     const DagInit *DI = R->getValueAsDag("ResultInst");
781     AliasMap[getQualifiedName(DI->getOperatorAsDef(R->getLoc()))].insert(
782         std::make_pair(CodeGenInstAlias(R, Target), Priority));
783   }
784
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;
788
789   std::vector<std::string> PrintMethods;
790
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;
794
795   for (auto &Aliases : AliasMap) {
796     // Collection of instruction alias rules. May contain ambiguous rules.
797     std::vector<IAPrinter> IAPs;
798
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,
804                                                       Variant);
805       unsigned NumResultOps = CountNumOperands(FlatInstAsmString, Variant);
806
807       std::string FlatAliasAsmString =
808           CodeGenInstruction::FlattenAsmStringVariants(CGA.AsmString, Variant);
809
810       // Don't emit the alias if it has more operands than what it's aliasing.
811       if (NumResultOps < CountNumOperands(FlatAliasAsmString, Variant))
812         continue;
813
814       StringRef Namespace = Target.getName();
815       unsigned NumMIOps = 0;
816       for (auto &ResultInstOpnd : CGA.ResultInst->Operands)
817         NumMIOps += ResultInstOpnd.MINumOperands;
818
819       IAPrinter IAP(CGA.Result->getAsString(), FlatAliasAsmString, NumMIOps);
820
821       bool CantHandle = false;
822
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;
827         while (true) {
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()) {
836               ++MIOpNum;
837               continue;
838             }
839           }
840           break;
841         }
842
843         // Ignore unchecked result operands.
844         while (IAP.getCondCount() < MIOpNum)
845           IAP.addCond("AliasPatternCond::K_Ignore, 0");
846
847         const CodeGenInstAlias::ResultOperand &RO = CGA.ResultOperands[i];
848
849         switch (RO.Kind) {
850         case CodeGenInstAlias::ResultOperand::K_Record: {
851           const Record *Rec = RO.getRecord();
852           StringRef ROName = RO.getName();
853           int PrintMethodIdx = -1;
854
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
857           // code to use.
858           if (Rec->isSubClassOf("RegisterOperand") ||
859               Rec->isSubClassOf("Operand")) {
860             StringRef PrintMethod = Rec->getValueAsString("PrintMethod");
861             if (PrintMethod != "" && PrintMethod != "printOperand") {
862               PrintMethodIdx =
863                   llvm::find(PrintMethods, PrintMethod) - PrintMethods.begin();
864               if (static_cast<unsigned>(PrintMethodIdx) == PrintMethods.size())
865                 PrintMethods.push_back(PrintMethod);
866             }
867           }
868
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");
877               IAP.addCond(formatv(
878                   "AliasPatternCond::K_RegClass, {0}::{1}RegClassID", Namespace,
879                   R->getName()));
880             } else {
881               IAP.addCond(formatv("AliasPatternCond::K_TiedReg, {0}",
882                                   IAP.getOpIndex(ROName)));
883             }
884           } else {
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);
888
889             // There might be an additional predicate on the MCOperand
890             unsigned Entry = MCOpPredicateMap[Rec];
891             if (!Entry) {
892               if (!Rec->isValueUnset("MCOperandPredicate")) {
893                 MCOpPredicates.push_back(Rec);
894                 Entry = MCOpPredicates.size();
895                 MCOpPredicateMap[Rec] = Entry;
896               } else
897                 break; // No conditions on this operand at all
898             }
899             IAP.addCond(formatv("AliasPatternCond::K_Custom, {0}", Entry));
900           }
901           break;
902         }
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);
908           if (Imm != Imm32)
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));
912           break;
913         }
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()) {
918             CantHandle = true;
919             break;
920           }
921
922           StringRef Reg = CGA.ResultOperands[i].getRegister()->getName();
923           IAP.addCond(
924               formatv("AliasPatternCond::K_Reg, {0}::{1}", Namespace, Reg));
925           break;
926         }
927
928         MIOpNum += RO.getMINumOperands();
929       }
930
931       if (CantHandle) continue;
932
933       std::vector<Record *> ReqFeatures;
934       if (PassSubtarget) {
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");
940         });
941       }
942
943       for (auto I = ReqFeatures.cbegin(); I != ReqFeatures.cend(); I++) {
944         Record *R = *I;
945         StringRef AsmCondString = R->getValueAsString("AssemblerCondString");
946
947         // AsmCondString has syntax [!]F(,[!]F)*
948         SmallVector<StringRef, 4> Ops;
949         SplitString(AsmCondString, Ops, ",");
950         assert(!Ops.empty() && "AssemblerCondString cannot be empty");
951
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));
958         }
959       }
960
961       IAPrinterMap[Aliases.first].push_back(std::move(IAP));
962     }
963   }
964
965   //////////////////////////////
966   // Write out the printAliasInstr function
967   //////////////////////////////
968
969   std::string Header;
970   raw_string_ostream HeaderO(Header);
971
972   HeaderO << "bool " << Target.getName() << ClassName
973           << "::printAliasInstr(const MCInst"
974           << " *MI, " << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "")
975           << "raw_ostream &OS) {\n";
976
977   std::string PatternsForOpcode;
978   raw_string_ostream OpcodeO(PatternsForOpcode);
979
980   unsigned PatternCount = 0;
981   std::string Patterns;
982   raw_string_ostream PatternO(Patterns);
983
984   unsigned CondCount = 0;
985   std::string Conds;
986   raw_string_ostream CondO(Conds);
987
988   // All flattened alias strings.
989   std::map<std::string, uint32_t> AsmStringOffsets;
990   std::vector<std::pair<uint32_t, std::string>> AsmStrings;
991   size_t AsmStringsSize = 0;
992
993   // Iterate over the opcodes in enum order so they are sorted by opcode for
994   // binary search.
995   for (const CodeGenInstruction *Inst : NumberedInstructions) {
996     auto It = IAPrinterMap.find(getQualifiedName(Inst->TheDef));
997     if (It == IAPrinterMap.end())
998       continue;
999     std::vector<IAPrinter> &IAPs = It->second;
1000     std::vector<IAPrinter*> UniqueIAPs;
1001
1002     // Remove any ambiguous alias rules.
1003     for (auto &LHS : IAPs) {
1004       bool IsDup = false;
1005       for (const auto &RHS : IAPs) {
1006         if (&LHS != &RHS && LHS == RHS) {
1007           IsDup = true;
1008           break;
1009         }
1010       }
1011
1012       if (!IsDup)
1013         UniqueIAPs.push_back(&LHS);
1014     }
1015
1016     if (UniqueIAPs.empty()) continue;
1017
1018     unsigned PatternStart = PatternCount;
1019
1020     // Insert the pattern start and opcode in the pattern list for debugging.
1021     PatternO << formatv("    // {0} - {1}\n", It->first, PatternStart);
1022
1023     for (IAPrinter *IAP : UniqueIAPs) {
1024       // Start each condition list with a comment of the resulting pattern that
1025       // we're trying to match.
1026       unsigned CondStart = CondCount;
1027       CondO << formatv("    // {0} - {1}\n", IAP->getResult(), CondStart);
1028       for (const auto &Cond : IAP->getConds())
1029         CondO << "    {" << Cond << "},\n";
1030       CondCount += IAP->getCondCount();
1031
1032       // After operands have been examined, re-encode the alias string with
1033       // escapes indicating how operands should be printed.
1034       uint32_t UnescapedSize = 0;
1035       std::string EncodedAsmString = IAP->formatAliasString(UnescapedSize);
1036       auto Insertion =
1037           AsmStringOffsets.insert({EncodedAsmString, AsmStringsSize});
1038       if (Insertion.second) {
1039         // If the string is new, add it to the vector.
1040         AsmStrings.push_back({AsmStringsSize, EncodedAsmString});
1041         AsmStringsSize += UnescapedSize + 1;
1042       }
1043       unsigned AsmStrOffset = Insertion.first->second;
1044
1045       PatternO << formatv("    {{{0}, {1}, {2}, {3} },\n", AsmStrOffset,
1046                           CondStart, IAP->getNumMIOps(), IAP->getCondCount());
1047       ++PatternCount;
1048     }
1049
1050     OpcodeO << formatv("    {{{0}, {1}, {2} },\n", It->first, PatternStart,
1051                        PatternCount - PatternStart);
1052   }
1053
1054   if (OpcodeO.str().empty()) {
1055     O << HeaderO.str();
1056     O << "  return false;\n";
1057     O << "}\n\n";
1058     O << "#endif // PRINT_ALIAS_INSTR\n";
1059     return;
1060   }
1061
1062   // Forward declare the validation method if needed.
1063   if (!MCOpPredicates.empty())
1064     O << "static bool " << Target.getName() << ClassName
1065       << "ValidateMCOperand(const MCOperand &MCOp,\n"
1066       << "                  const MCSubtargetInfo &STI,\n"
1067       << "                  unsigned PredicateIndex);\n";
1068
1069   O << HeaderO.str();
1070   O.indent(2) << "static const PatternsForOpcode OpToPatterns[] = {\n";
1071   O << OpcodeO.str();
1072   O.indent(2) << "};\n\n";
1073   O.indent(2) << "static const AliasPattern Patterns[] = {\n";
1074   O << PatternO.str();
1075   O.indent(2) << "};\n\n";
1076   O.indent(2) << "static const AliasPatternCond Conds[] = {\n";
1077   O << CondO.str();
1078   O.indent(2) << "};\n\n";
1079   O.indent(2) << "static const char AsmStrings[] =\n";
1080   for (const auto &P : AsmStrings) {
1081     O.indent(4) << "/* " << P.first << " */ \"" << P.second << "\\0\"\n";
1082   }
1083
1084   O.indent(2) << ";\n\n";
1085
1086   // Assert that the opcode table is sorted. Use a static local constructor to
1087   // ensure that the check only happens once on first run.
1088   O << "#ifndef NDEBUG\n";
1089   O.indent(2) << "static struct SortCheck {\n";
1090   O.indent(2) << "  SortCheck(ArrayRef<PatternsForOpcode> OpToPatterns) {\n";
1091   O.indent(2) << "    assert(std::is_sorted(\n";
1092   O.indent(2) << "               OpToPatterns.begin(), OpToPatterns.end(),\n";
1093   O.indent(2) << "               [](const PatternsForOpcode &L, const "
1094                  "PatternsForOpcode &R) {\n";
1095   O.indent(2) << "                 return L.Opcode < R.Opcode;\n";
1096   O.indent(2) << "               }) &&\n";
1097   O.indent(2) << "           \"tablegen failed to sort opcode patterns\");\n";
1098   O.indent(2) << "  }\n";
1099   O.indent(2) << "} sortCheckVar(OpToPatterns);\n";
1100   O << "#endif\n\n";
1101
1102   O.indent(2) << "AliasMatchingData M {\n";
1103   O.indent(2) << "  makeArrayRef(OpToPatterns),\n";
1104   O.indent(2) << "  makeArrayRef(Patterns),\n";
1105   O.indent(2) << "  makeArrayRef(Conds),\n";
1106   O.indent(2) << "  StringRef(AsmStrings, array_lengthof(AsmStrings)),\n";
1107   if (MCOpPredicates.empty())
1108     O.indent(2) << "  nullptr,\n";
1109   else
1110     O.indent(2) << "  &" << Target.getName() << ClassName << "ValidateMCOperand,\n";
1111   O.indent(2) << "};\n";
1112
1113   O.indent(2) << "const char *AsmString = matchAliasPatterns(MI, "
1114               << (PassSubtarget ? "&STI" : "nullptr") << ", M);\n";
1115   O.indent(2) << "if (!AsmString) return false;\n\n";
1116
1117   // Code that prints the alias, replacing the operands with the ones from the
1118   // MCInst.
1119   O << "  unsigned I = 0;\n";
1120   O << "  while (AsmString[I] != ' ' && AsmString[I] != '\\t' &&\n";
1121   O << "         AsmString[I] != '$' && AsmString[I] != '\\0')\n";
1122   O << "    ++I;\n";
1123   O << "  OS << '\\t' << StringRef(AsmString, I);\n";
1124
1125   O << "  if (AsmString[I] != '\\0') {\n";
1126   O << "    if (AsmString[I] == ' ' || AsmString[I] == '\\t') {\n";
1127   O << "      OS << '\\t';\n";
1128   O << "      ++I;\n";
1129   O << "    }\n";
1130   O << "    do {\n";
1131   O << "      if (AsmString[I] == '$') {\n";
1132   O << "        ++I;\n";
1133   O << "        if (AsmString[I] == (char)0xff) {\n";
1134   O << "          ++I;\n";
1135   O << "          int OpIdx = AsmString[I++] - 1;\n";
1136   O << "          int PrintMethodIdx = AsmString[I++] - 1;\n";
1137   O << "          printCustomAliasOperand(MI, OpIdx, PrintMethodIdx, ";
1138   O << (PassSubtarget ? "STI, " : "");
1139   O << "OS);\n";
1140   O << "        } else\n";
1141   O << "          printOperand(MI, unsigned(AsmString[I++]) - 1, ";
1142   O << (PassSubtarget ? "STI, " : "");
1143   O << "OS);\n";
1144   O << "      } else {\n";
1145   O << "        OS << AsmString[I++];\n";
1146   O << "      }\n";
1147   O << "    } while (AsmString[I] != '\\0');\n";
1148   O << "  }\n\n";
1149
1150   O << "  return true;\n";
1151   O << "}\n\n";
1152
1153   //////////////////////////////
1154   // Write out the printCustomAliasOperand function
1155   //////////////////////////////
1156
1157   O << "void " << Target.getName() << ClassName << "::"
1158     << "printCustomAliasOperand(\n"
1159     << "         const MCInst *MI, unsigned OpIdx,\n"
1160     << "         unsigned PrintMethodIdx,\n"
1161     << (PassSubtarget ? "         const MCSubtargetInfo &STI,\n" : "")
1162     << "         raw_ostream &OS) {\n";
1163   if (PrintMethods.empty())
1164     O << "  llvm_unreachable(\"Unknown PrintMethod kind\");\n";
1165   else {
1166     O << "  switch (PrintMethodIdx) {\n"
1167       << "  default:\n"
1168       << "    llvm_unreachable(\"Unknown PrintMethod kind\");\n"
1169       << "    break;\n";
1170
1171     for (unsigned i = 0; i < PrintMethods.size(); ++i) {
1172       O << "  case " << i << ":\n"
1173         << "    " << PrintMethods[i] << "(MI, OpIdx, "
1174         << (PassSubtarget ? "STI, " : "") << "OS);\n"
1175         << "    break;\n";
1176     }
1177     O << "  }\n";
1178   }    
1179   O << "}\n\n";
1180
1181   if (!MCOpPredicates.empty()) {
1182     O << "static bool " << Target.getName() << ClassName
1183       << "ValidateMCOperand(const MCOperand &MCOp,\n"
1184       << "                  const MCSubtargetInfo &STI,\n"
1185       << "                  unsigned PredicateIndex) {\n"      
1186       << "  switch (PredicateIndex) {\n"
1187       << "  default:\n"
1188       << "    llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n"
1189       << "    break;\n";
1190
1191     for (unsigned i = 0; i < MCOpPredicates.size(); ++i) {
1192       Init *MCOpPred = MCOpPredicates[i]->getValueInit("MCOperandPredicate");
1193       if (CodeInit *SI = dyn_cast<CodeInit>(MCOpPred)) {
1194         O << "  case " << i + 1 << ": {\n"
1195           << SI->getValue() << "\n"
1196           << "    }\n";
1197       } else
1198         llvm_unreachable("Unexpected MCOperandPredicate field!");
1199     }
1200     O << "  }\n"
1201       << "}\n\n";
1202   }
1203
1204   O << "#endif // PRINT_ALIAS_INSTR\n";
1205 }
1206
1207 AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) {
1208   Record *AsmWriter = Target.getAsmWriter();
1209   unsigned Variant = AsmWriter->getValueAsInt("Variant");
1210
1211   // Get the instruction numbering.
1212   NumberedInstructions = Target.getInstructionsByEnumValue();
1213
1214   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
1215     const CodeGenInstruction *I = NumberedInstructions[i];
1216     if (!I->AsmString.empty() && I->TheDef->getName() != "PHI")
1217       Instructions.emplace_back(*I, i, Variant);
1218   }
1219 }
1220
1221 void AsmWriterEmitter::run(raw_ostream &O) {
1222   EmitPrintInstruction(O);
1223   EmitGetRegisterName(O);
1224   EmitPrintAliasInstruction(O);
1225 }
1226
1227 namespace llvm {
1228
1229 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) {
1230   emitSourceFileHeader("Assembly Writer Source Fragment", OS);
1231   AsmWriterEmitter(RK).run(OS);
1232 }
1233
1234 } // end namespace llvm