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