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