Taints the non-acquire RMW's store address with the load part
[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 << "\n      " << TheOp.getCode();
82   O << "\n      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 (const AsmWriterInst &AWI : SimilarInsts)
113     O << "  case " << AWI.CGI->Namespace << "::"
114       << AWI.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       O << "    default: llvm_unreachable(\"Unexpected opcode.\");\n";
124       std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
125       OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
126                                           FirstInst.CGI->TheDef->getName(),
127                                           FirstInst.Operands[i]));
128
129       for (const AsmWriterInst &AWI : SimilarInsts) {
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   std::vector<uint64_t> OpcodeInfo;
296   const unsigned OpcodeInfoBits = 64;
297
298   // Add all strings to the string table upfront so it can generate an optimized
299   // representation.
300   for (const CodeGenInstruction *Inst : *NumberedInstructions) {
301     AsmWriterInst *AWI = CGIAWIMap[Inst];
302     if (AWI &&
303         AWI->Operands[0].OperandType ==
304                  AsmWriterOperand::isLiteralTextOperand &&
305         !AWI->Operands[0].Str.empty()) {
306       std::string Str = AWI->Operands[0].Str;
307       UnescapeString(Str);
308       StringTable.add(Str);
309     }
310   }
311
312   StringTable.layout();
313
314   unsigned MaxStringIdx = 0;
315   for (const CodeGenInstruction *Inst : *NumberedInstructions) {
316     AsmWriterInst *AWI = CGIAWIMap[Inst];
317     unsigned Idx;
318     if (!AWI) {
319       // Something not handled by the asmwriter printer.
320       Idx = ~0U;
321     } else if (AWI->Operands[0].OperandType !=
322                         AsmWriterOperand::isLiteralTextOperand ||
323                AWI->Operands[0].Str.empty()) {
324       // Something handled by the asmwriter printer, but with no leading string.
325       Idx = StringTable.get("");
326     } else {
327       std::string Str = AWI->Operands[0].Str;
328       UnescapeString(Str);
329       Idx = StringTable.get(Str);
330       MaxStringIdx = std::max(MaxStringIdx, Idx);
331
332       // Nuke the string from the operand list.  It is now handled!
333       AWI->Operands.erase(AWI->Operands.begin());
334     }
335
336     // Bias offset by one since we want 0 as a sentinel.
337     OpcodeInfo.push_back(Idx+1);
338   }
339
340   // Figure out how many bits we used for the string index.
341   unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
342
343   // To reduce code size, we compactify common instructions into a few bits
344   // in the opcode-indexed table.
345   unsigned BitsLeft = OpcodeInfoBits-AsmStrBits;
346
347   std::vector<std::vector<std::string>> TableDrivenOperandPrinters;
348
349   while (1) {
350     std::vector<std::string> UniqueOperandCommands;
351     std::vector<unsigned> InstIdxs;
352     std::vector<unsigned> NumInstOpsHandled;
353     FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
354                               NumInstOpsHandled);
355
356     // If we ran out of operands to print, we're done.
357     if (UniqueOperandCommands.empty()) break;
358
359     // Compute the number of bits we need to represent these cases, this is
360     // ceil(log2(numentries)).
361     unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
362
363     // If we don't have enough bits for this operand, don't include it.
364     if (NumBits > BitsLeft) {
365       DEBUG(errs() << "Not enough bits to densely encode " << NumBits
366                    << " more bits\n");
367       break;
368     }
369
370     // Otherwise, we can include this in the initial lookup table.  Add it in.
371     for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
372       if (InstIdxs[i] != ~0U) {
373         OpcodeInfo[i] |= (uint64_t)InstIdxs[i] << (OpcodeInfoBits-BitsLeft);
374       }
375     BitsLeft -= NumBits;
376
377     // Remove the info about this operand.
378     for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
379       if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
380         if (!Inst->Operands.empty()) {
381           unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
382           assert(NumOps <= Inst->Operands.size() &&
383                  "Can't remove this many ops!");
384           Inst->Operands.erase(Inst->Operands.begin(),
385                                Inst->Operands.begin()+NumOps);
386         }
387     }
388
389     // Remember the handlers for this set of operands.
390     TableDrivenOperandPrinters.push_back(std::move(UniqueOperandCommands));
391   }
392
393   // Emit the string table itself.
394   O << "  static const char AsmStrs[] = {\n";
395   StringTable.emit(O, printChar);
396   O << "  };\n\n";
397
398   // Emit the lookup tables in pieces to minimize wasted bytes.
399   unsigned BytesNeeded = ((OpcodeInfoBits - BitsLeft) + 7) / 8;
400   unsigned Table = 0, Shift = 0;
401   SmallString<128> BitsString;
402   raw_svector_ostream BitsOS(BitsString);
403   // If the total bits is more than 32-bits we need to use a 64-bit type.
404   BitsOS << "  uint" << ((BitsLeft < (OpcodeInfoBits - 32)) ? 64 : 32)
405          << "_t Bits = 0;\n";
406   while (BytesNeeded != 0) {
407     // Figure out how big this table section needs to be, but no bigger than 4.
408     unsigned TableSize = std::min(1 << Log2_32(BytesNeeded), 4);
409     BytesNeeded -= TableSize;
410     TableSize *= 8; // Convert to bits;
411     uint64_t Mask = (1ULL << TableSize) - 1;
412     O << "  static const uint" << TableSize << "_t OpInfo" << Table
413       << "[] = {\n";
414     for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
415       O << "    " << ((OpcodeInfo[i] >> Shift) & Mask) << "U,\t// "
416         << NumberedInstructions->at(i)->TheDef->getName() << "\n";
417     }
418     O << "  };\n\n";
419     // Emit string to combine the individual table lookups.
420     BitsOS << "  Bits |= ";
421     // If the total bits is more than 32-bits we need to use a 64-bit type.
422     if (BitsLeft < (OpcodeInfoBits - 32))
423       BitsOS << "(uint64_t)";
424     BitsOS << "OpInfo" << Table << "[MI->getOpcode()] << " << Shift << ";\n";
425     // Prepare the shift for the next iteration and increment the table count.
426     Shift += TableSize;
427     ++Table;
428   }
429
430   // Emit the initial tab character.
431   O << "  O << \"\\t\";\n\n";
432
433   O << "  // Emit the opcode for the instruction.\n";
434   O << BitsString;
435
436   // Emit the starting string.
437   O << "  assert(Bits != 0 && \"Cannot print this instruction.\");\n"
438     << "  O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
439
440   // Output the table driven operand information.
441   BitsLeft = OpcodeInfoBits-AsmStrBits;
442   for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
443     std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
444
445     // Compute the number of bits we need to represent these cases, this is
446     // ceil(log2(numentries)).
447     unsigned NumBits = Log2_32_Ceil(Commands.size());
448     assert(NumBits <= BitsLeft && "consistency error");
449
450     // Emit code to extract this field from Bits.
451     O << "\n  // Fragment " << i << " encoded into " << NumBits
452       << " bits for " << Commands.size() << " unique commands.\n";
453
454     if (Commands.size() == 2) {
455       // Emit two possibilitys with if/else.
456       O << "  if ((Bits >> "
457         << (OpcodeInfoBits-BitsLeft) << ") & "
458         << ((1 << NumBits)-1) << ") {\n"
459         << Commands[1]
460         << "  } else {\n"
461         << Commands[0]
462         << "  }\n\n";
463     } else if (Commands.size() == 1) {
464       // Emit a single possibility.
465       O << Commands[0] << "\n\n";
466     } else {
467       O << "  switch ((Bits >> "
468         << (OpcodeInfoBits-BitsLeft) << ") & "
469         << ((1 << NumBits)-1) << ") {\n"
470         << "  default: llvm_unreachable(\"Invalid command number.\");\n";
471
472       // Print out all the cases.
473       for (unsigned j = 0, e = Commands.size(); j != e; ++j) {
474         O << "  case " << j << ":\n";
475         O << Commands[j];
476         O << "    break;\n";
477       }
478       O << "  }\n\n";
479     }
480     BitsLeft -= NumBits;
481   }
482
483   // Okay, delete instructions with no operand info left.
484   auto I = std::remove_if(Instructions.begin(), Instructions.end(),
485                           [](AsmWriterInst &Inst) {
486                             return Inst.Operands.empty();
487                           });
488   Instructions.erase(I, Instructions.end());
489
490
491   // Because this is a vector, we want to emit from the end.  Reverse all of the
492   // elements in the vector.
493   std::reverse(Instructions.begin(), Instructions.end());
494
495
496   // Now that we've emitted all of the operand info that fit into 64 bits, emit
497   // information for those instructions that are left.  This is a less dense
498   // encoding, but we expect the main 64-bit table to handle the majority of
499   // instructions.
500   if (!Instructions.empty()) {
501     // Find the opcode # of inline asm.
502     O << "  switch (MI->getOpcode()) {\n";
503     O << "  default: llvm_unreachable(\"Unexpected opcode.\");\n";
504     while (!Instructions.empty())
505       EmitInstructions(Instructions, O);
506
507     O << "  }\n";
508   }
509
510   O << "}\n";
511 }
512
513 static const char *getMinimalTypeForRange(uint64_t Range) {
514   assert(Range < 0xFFFFFFFFULL && "Enum too large");
515   if (Range > 0xFFFF)
516     return "uint32_t";
517   if (Range > 0xFF)
518     return "uint16_t";
519   return "uint8_t";
520 }
521
522 static void
523 emitRegisterNameString(raw_ostream &O, StringRef AltName,
524                        const std::deque<CodeGenRegister> &Registers) {
525   SequenceToOffsetTable<std::string> StringTable;
526   SmallVector<std::string, 4> AsmNames(Registers.size());
527   unsigned i = 0;
528   for (const auto &Reg : Registers) {
529     std::string &AsmName = AsmNames[i++];
530
531     // "NoRegAltName" is special. We don't need to do a lookup for that,
532     // as it's just a reference to the default register name.
533     if (AltName == "" || AltName == "NoRegAltName") {
534       AsmName = Reg.TheDef->getValueAsString("AsmName");
535       if (AsmName.empty())
536         AsmName = Reg.getName();
537     } else {
538       // Make sure the register has an alternate name for this index.
539       std::vector<Record*> AltNameList =
540         Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
541       unsigned Idx = 0, e;
542       for (e = AltNameList.size();
543            Idx < e && (AltNameList[Idx]->getName() != AltName);
544            ++Idx)
545         ;
546       // If the register has an alternate name for this index, use it.
547       // Otherwise, leave it empty as an error flag.
548       if (Idx < e) {
549         std::vector<std::string> AltNames =
550           Reg.TheDef->getValueAsListOfStrings("AltNames");
551         if (AltNames.size() <= Idx)
552           PrintFatalError(Reg.TheDef->getLoc(),
553                           "Register definition missing alt name for '" +
554                           AltName + "'.");
555         AsmName = AltNames[Idx];
556       }
557     }
558     StringTable.add(AsmName);
559   }
560
561   StringTable.layout();
562   O << "  static const char AsmStrs" << AltName << "[] = {\n";
563   StringTable.emit(O, printChar);
564   O << "  };\n\n";
565
566   O << "  static const " << getMinimalTypeForRange(StringTable.size()-1)
567     << " RegAsmOffset" << AltName << "[] = {";
568   for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
569     if ((i % 14) == 0)
570       O << "\n    ";
571     O << StringTable.get(AsmNames[i]) << ", ";
572   }
573   O << "\n  };\n"
574     << "\n";
575 }
576
577 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
578   Record *AsmWriter = Target.getAsmWriter();
579   std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
580   const auto &Registers = Target.getRegBank().getRegisters();
581   std::vector<Record*> AltNameIndices = Target.getRegAltNameIndices();
582   bool hasAltNames = AltNameIndices.size() > 1;
583   std::string Namespace =
584       Registers.front().TheDef->getValueAsString("Namespace");
585
586   O <<
587   "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
588   "/// from the register set description.  This returns the assembler name\n"
589   "/// for the specified register.\n"
590   "const char *" << Target.getName() << ClassName << "::";
591   if (hasAltNames)
592     O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
593   else
594     O << "getRegisterName(unsigned RegNo) {\n";
595   O << "  assert(RegNo && RegNo < " << (Registers.size()+1)
596     << " && \"Invalid register number!\");\n"
597     << "\n";
598
599   if (hasAltNames) {
600     for (const Record *R : AltNameIndices)
601       emitRegisterNameString(O, R->getName(), Registers);
602   } else
603     emitRegisterNameString(O, "", Registers);
604
605   if (hasAltNames) {
606     O << "  switch(AltIdx) {\n"
607       << "  default: llvm_unreachable(\"Invalid register alt name index!\");\n";
608     for (const Record *R : AltNameIndices) {
609       std::string AltName(R->getName());
610       std::string Prefix = !Namespace.empty() ? Namespace + "::" : "";
611       O << "  case " << Prefix << AltName << ":\n"
612         << "    assert(*(AsmStrs" << AltName << "+RegAsmOffset"
613         << AltName << "[RegNo-1]) &&\n"
614         << "           \"Invalid alt name index for register!\");\n"
615         << "    return AsmStrs" << AltName << "+RegAsmOffset"
616         << AltName << "[RegNo-1];\n";
617     }
618     O << "  }\n";
619   } else {
620     O << "  assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
621       << "          \"Invalid alt name index for register!\");\n"
622       << "  return AsmStrs+RegAsmOffset[RegNo-1];\n";
623   }
624   O << "}\n";
625 }
626
627 namespace {
628 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if
629 // they both have the same conditionals. In which case, we cannot print out the
630 // alias for that pattern.
631 class IAPrinter {
632   std::vector<std::string> Conds;
633   std::map<StringRef, std::pair<int, int>> OpMap;
634   SmallVector<Record*, 4> ReqFeatures;
635
636   std::string Result;
637   std::string AsmString;
638 public:
639   IAPrinter(std::string R, std::string AS) : Result(R), AsmString(AS) {}
640
641   void addCond(const std::string &C) { Conds.push_back(C); }
642
643   void addOperand(StringRef Op, int OpIdx, int PrintMethodIdx = -1) {
644     assert(OpIdx >= 0 && OpIdx < 0xFE && "Idx out of range");
645     assert(PrintMethodIdx >= -1 && PrintMethodIdx < 0xFF &&
646            "Idx out of range");
647     OpMap[Op] = std::make_pair(OpIdx, PrintMethodIdx);
648   }
649
650   bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
651   int getOpIndex(StringRef Op) { return OpMap[Op].first; }
652   std::pair<int, int> &getOpData(StringRef Op) { return OpMap[Op]; }
653
654   std::pair<StringRef, StringRef::iterator> parseName(StringRef::iterator Start,
655                                                       StringRef::iterator End) {
656     StringRef::iterator I = Start;
657     StringRef::iterator Next;
658     if (*I == '{') {
659       // ${some_name}
660       Start = ++I;
661       while (I != End && *I != '}')
662         ++I;
663       Next = I;
664       // eat the final '}'
665       if (Next != End)
666         ++Next;
667     } else {
668       // $name, just eat the usual suspects.
669       while (I != End &&
670              ((*I >= 'a' && *I <= 'z') || (*I >= 'A' && *I <= 'Z') ||
671               (*I >= '0' && *I <= '9') || *I == '_'))
672         ++I;
673       Next = I;
674     }
675
676     return std::make_pair(StringRef(Start, I - Start), Next);
677   }
678
679   void print(raw_ostream &O) {
680     if (Conds.empty() && ReqFeatures.empty()) {
681       O.indent(6) << "return true;\n";
682       return;
683     }
684
685     O << "if (";
686
687     for (std::vector<std::string>::iterator
688            I = Conds.begin(), E = Conds.end(); I != E; ++I) {
689       if (I != Conds.begin()) {
690         O << " &&\n";
691         O.indent(8);
692       }
693
694       O << *I;
695     }
696
697     O << ") {\n";
698     O.indent(6) << "// " << Result << "\n";
699
700     // Directly mangle mapped operands into the string. Each operand is
701     // identified by a '$' sign followed by a byte identifying the number of the
702     // operand. We add one to the index to avoid zero bytes.
703     StringRef ASM(AsmString);
704     SmallString<128> OutString;
705     raw_svector_ostream OS(OutString);
706     for (StringRef::iterator I = ASM.begin(), E = ASM.end(); I != E;) {
707       OS << *I;
708       if (*I == '$') {
709         StringRef Name;
710         std::tie(Name, I) = parseName(++I, E);
711         assert(isOpMapped(Name) && "Unmapped operand!");
712
713         int OpIndex, PrintIndex;
714         std::tie(OpIndex, PrintIndex) = getOpData(Name);
715         if (PrintIndex == -1) {
716           // Can use the default printOperand route.
717           OS << format("\\x%02X", (unsigned char)OpIndex + 1);
718         } else
719           // 3 bytes if a PrintMethod is needed: 0xFF, the MCInst operand
720           // number, and which of our pre-detected Methods to call.
721           OS << format("\\xFF\\x%02X\\x%02X", OpIndex + 1, PrintIndex + 1);
722       } else {
723         ++I;
724       }
725     }
726
727     // Emit the string.
728     O.indent(6) << "AsmString = \"" << OutString << "\";\n";
729
730     O.indent(6) << "break;\n";
731     O.indent(4) << '}';
732   }
733
734   bool operator==(const IAPrinter &RHS) const {
735     if (Conds.size() != RHS.Conds.size())
736       return false;
737
738     unsigned Idx = 0;
739     for (const auto &str : Conds)
740       if (str != RHS.Conds[Idx++])
741         return false;
742
743     return true;
744   }
745 };
746
747 } // end anonymous namespace
748
749 static unsigned CountNumOperands(StringRef AsmString, unsigned Variant) {
750   std::string FlatAsmString =
751       CodeGenInstruction::FlattenAsmStringVariants(AsmString, Variant);
752   AsmString = FlatAsmString;
753
754   return AsmString.count(' ') + AsmString.count('\t');
755 }
756
757 namespace {
758 struct AliasPriorityComparator {
759   typedef std::pair<CodeGenInstAlias, int> ValueType;
760   bool operator()(const ValueType &LHS, const ValueType &RHS) {
761     if (LHS.second ==  RHS.second) {
762       // We don't actually care about the order, but for consistency it
763       // shouldn't depend on pointer comparisons.
764       return LHS.first.TheDef->getName() < RHS.first.TheDef->getName();
765     }
766
767     // Aliases with larger priorities should be considered first.
768     return LHS.second > RHS.second;
769   }
770 };
771 }
772
773
774 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
775   Record *AsmWriter = Target.getAsmWriter();
776
777   O << "\n#ifdef PRINT_ALIAS_INSTR\n";
778   O << "#undef PRINT_ALIAS_INSTR\n\n";
779
780   //////////////////////////////
781   // Gather information about aliases we need to print
782   //////////////////////////////
783
784   // Emit the method that prints the alias instruction.
785   std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
786   unsigned Variant = AsmWriter->getValueAsInt("Variant");
787   unsigned PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
788
789   std::vector<Record*> AllInstAliases =
790     Records.getAllDerivedDefinitions("InstAlias");
791
792   // Create a map from the qualified name to a list of potential matches.
793   typedef std::set<std::pair<CodeGenInstAlias, int>, AliasPriorityComparator>
794       AliasWithPriority;
795   std::map<std::string, AliasWithPriority> AliasMap;
796   for (Record *R : AllInstAliases) {
797     int Priority = R->getValueAsInt("EmitPriority");
798     if (Priority < 1)
799       continue; // Aliases with priority 0 are never emitted.
800
801     const DagInit *DI = R->getValueAsDag("ResultInst");
802     const DefInit *Op = cast<DefInit>(DI->getOperator());
803     AliasMap[getQualifiedName(Op->getDef())].insert(
804         std::make_pair(CodeGenInstAlias(R, Variant, Target), Priority));
805   }
806
807   // A map of which conditions need to be met for each instruction operand
808   // before it can be matched to the mnemonic.
809   std::map<std::string, std::vector<IAPrinter>> IAPrinterMap;
810
811   // A list of MCOperandPredicates for all operands in use, and the reverse map
812   std::vector<const Record*> MCOpPredicates;
813   DenseMap<const Record*, unsigned> MCOpPredicateMap;
814
815   for (auto &Aliases : AliasMap) {
816     for (auto &Alias : Aliases.second) {
817       const CodeGenInstAlias &CGA = Alias.first;
818       unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
819       unsigned NumResultOps =
820           CountNumOperands(CGA.ResultInst->AsmString, Variant);
821
822       // Don't emit the alias if it has more operands than what it's aliasing.
823       if (NumResultOps < CountNumOperands(CGA.AsmString, Variant))
824         continue;
825
826       IAPrinter IAP(CGA.Result->getAsString(), CGA.AsmString);
827
828       unsigned NumMIOps = 0;
829       for (auto &Operand : CGA.ResultOperands)
830         NumMIOps += Operand.getMINumOperands();
831
832       std::string Cond;
833       Cond = std::string("MI->getNumOperands() == ") + llvm::utostr(NumMIOps);
834       IAP.addCond(Cond);
835
836       bool CantHandle = false;
837
838       unsigned MIOpNum = 0;
839       for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
840         std::string Op = "MI->getOperand(" + llvm::utostr(MIOpNum) + ")";
841
842         const CodeGenInstAlias::ResultOperand &RO = CGA.ResultOperands[i];
843
844         switch (RO.Kind) {
845         case CodeGenInstAlias::ResultOperand::K_Record: {
846           const Record *Rec = RO.getRecord();
847           StringRef ROName = RO.getName();
848           int PrintMethodIdx = -1;
849
850           // These two may have a PrintMethod, which we want to record (if it's
851           // the first time we've seen it) and provide an index for the aliasing
852           // code to use.
853           if (Rec->isSubClassOf("RegisterOperand") ||
854               Rec->isSubClassOf("Operand")) {
855             std::string PrintMethod = Rec->getValueAsString("PrintMethod");
856             if (PrintMethod != "" && PrintMethod != "printOperand") {
857               PrintMethodIdx = std::find(PrintMethods.begin(),
858                                          PrintMethods.end(), PrintMethod) -
859                                PrintMethods.begin();
860               if (static_cast<unsigned>(PrintMethodIdx) == PrintMethods.size())
861                 PrintMethods.push_back(PrintMethod);
862             }
863           }
864
865           if (Rec->isSubClassOf("RegisterOperand"))
866             Rec = Rec->getValueAsDef("RegClass");
867           if (Rec->isSubClassOf("RegisterClass")) {
868             IAP.addCond(Op + ".isReg()");
869
870             if (!IAP.isOpMapped(ROName)) {
871               IAP.addOperand(ROName, MIOpNum, PrintMethodIdx);
872               Record *R = CGA.ResultOperands[i].getRecord();
873               if (R->isSubClassOf("RegisterOperand"))
874                 R = R->getValueAsDef("RegClass");
875               Cond = std::string("MRI.getRegClass(") + Target.getName() + "::" +
876                      R->getName() + "RegClassID)"
877                                     ".contains(" + Op + ".getReg())";
878             } else {
879               Cond = Op + ".getReg() == MI->getOperand(" +
880                      llvm::utostr(IAP.getOpIndex(ROName)) + ").getReg()";
881             }
882           } else {
883             // Assume all printable operands are desired for now. This can be
884             // overridden in the InstAlias instantiation if necessary.
885             IAP.addOperand(ROName, MIOpNum, PrintMethodIdx);
886
887             // There might be an additional predicate on the MCOperand
888             unsigned Entry = MCOpPredicateMap[Rec];
889             if (!Entry) {
890               if (!Rec->isValueUnset("MCOperandPredicate")) {
891                 MCOpPredicates.push_back(Rec);
892                 Entry = MCOpPredicates.size();
893                 MCOpPredicateMap[Rec] = Entry;
894               } else
895                 break; // No conditions on this operand at all
896             }
897             Cond = Target.getName() + ClassName + "ValidateMCOperand(" +
898                    Op + ", STI, " + llvm::utostr(Entry) + ")";
899           }
900           // for all subcases of ResultOperand::K_Record:
901           IAP.addCond(Cond);
902           break;
903         }
904         case CodeGenInstAlias::ResultOperand::K_Imm: {
905           // Just because the alias has an immediate result, doesn't mean the
906           // MCInst will. An MCExpr could be present, for example.
907           IAP.addCond(Op + ".isImm()");
908
909           Cond = Op + ".getImm() == " +
910                  llvm::utostr(CGA.ResultOperands[i].getImm());
911           IAP.addCond(Cond);
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           Cond = Op + ".getReg() == " + Target.getName() + "::" +
923                  CGA.ResultOperands[i].getRegister()->getName();
924           IAP.addCond(Cond);
925           break;
926         }
927
928         MIOpNum += RO.getMINumOperands();
929       }
930
931       if (CantHandle) continue;
932       IAPrinterMap[Aliases.first].push_back(std::move(IAP));
933     }
934   }
935
936   //////////////////////////////
937   // Write out the printAliasInstr function
938   //////////////////////////////
939
940   std::string Header;
941   raw_string_ostream HeaderO(Header);
942
943   HeaderO << "bool " << Target.getName() << ClassName
944           << "::printAliasInstr(const MCInst"
945           << " *MI, " << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "")
946           << "raw_ostream &OS) {\n";
947
948   std::string Cases;
949   raw_string_ostream CasesO(Cases);
950
951   for (auto &Entry : IAPrinterMap) {
952     std::vector<IAPrinter> &IAPs = Entry.second;
953     std::vector<IAPrinter*> UniqueIAPs;
954
955     for (auto &LHS : IAPs) {
956       bool IsDup = false;
957       for (const auto &RHS : IAPs) {
958         if (&LHS != &RHS && LHS == RHS) {
959           IsDup = true;
960           break;
961         }
962       }
963
964       if (!IsDup)
965         UniqueIAPs.push_back(&LHS);
966     }
967
968     if (UniqueIAPs.empty()) continue;
969
970     CasesO.indent(2) << "case " << Entry.first << ":\n";
971
972     for (IAPrinter *IAP : UniqueIAPs) {
973       CasesO.indent(4);
974       IAP->print(CasesO);
975       CasesO << '\n';
976     }
977
978     CasesO.indent(4) << "return false;\n";
979   }
980
981   if (CasesO.str().empty()) {
982     O << HeaderO.str();
983     O << "  return false;\n";
984     O << "}\n\n";
985     O << "#endif // PRINT_ALIAS_INSTR\n";
986     return;
987   }
988
989   if (!MCOpPredicates.empty())
990     O << "static bool " << Target.getName() << ClassName
991       << "ValidateMCOperand(const MCOperand &MCOp,\n"
992       << "                  const MCSubtargetInfo &STI,\n"
993       << "                  unsigned PredicateIndex);\n";
994
995   O << HeaderO.str();
996   O.indent(2) << "const char *AsmString;\n";
997   O.indent(2) << "switch (MI->getOpcode()) {\n";
998   O.indent(2) << "default: return false;\n";
999   O << CasesO.str();
1000   O.indent(2) << "}\n\n";
1001
1002   // Code that prints the alias, replacing the operands with the ones from the
1003   // MCInst.
1004   O << "  unsigned I = 0;\n";
1005   O << "  while (AsmString[I] != ' ' && AsmString[I] != '\t' &&\n";
1006   O << "         AsmString[I] != '\\0')\n";
1007   O << "    ++I;\n";
1008   O << "  OS << '\\t' << StringRef(AsmString, I);\n";
1009
1010   O << "  if (AsmString[I] != '\\0') {\n";
1011   O << "    OS << '\\t';\n";
1012   O << "    do {\n";
1013   O << "      if (AsmString[I] == '$') {\n";
1014   O << "        ++I;\n";
1015   O << "        if (AsmString[I] == (char)0xff) {\n";
1016   O << "          ++I;\n";
1017   O << "          int OpIdx = AsmString[I++] - 1;\n";
1018   O << "          int PrintMethodIdx = AsmString[I++] - 1;\n";
1019   O << "          printCustomAliasOperand(MI, OpIdx, PrintMethodIdx, ";
1020   O << (PassSubtarget ? "STI, " : "");
1021   O << "OS);\n";
1022   O << "        } else\n";
1023   O << "          printOperand(MI, unsigned(AsmString[I++]) - 1, ";
1024   O << (PassSubtarget ? "STI, " : "");
1025   O << "OS);\n";
1026   O << "      } else {\n";
1027   O << "        OS << AsmString[I++];\n";
1028   O << "      }\n";
1029   O << "    } while (AsmString[I] != '\\0');\n";
1030   O << "  }\n\n";
1031
1032   O << "  return true;\n";
1033   O << "}\n\n";
1034
1035   //////////////////////////////
1036   // Write out the printCustomAliasOperand function
1037   //////////////////////////////
1038
1039   O << "void " << Target.getName() << ClassName << "::"
1040     << "printCustomAliasOperand(\n"
1041     << "         const MCInst *MI, unsigned OpIdx,\n"
1042     << "         unsigned PrintMethodIdx,\n"
1043     << (PassSubtarget ? "         const MCSubtargetInfo &STI,\n" : "")
1044     << "         raw_ostream &OS) {\n";
1045   if (PrintMethods.empty())
1046     O << "  llvm_unreachable(\"Unknown PrintMethod kind\");\n";
1047   else {
1048     O << "  switch (PrintMethodIdx) {\n"
1049       << "  default:\n"
1050       << "    llvm_unreachable(\"Unknown PrintMethod kind\");\n"
1051       << "    break;\n";
1052
1053     for (unsigned i = 0; i < PrintMethods.size(); ++i) {
1054       O << "  case " << i << ":\n"
1055         << "    " << PrintMethods[i] << "(MI, OpIdx, "
1056         << (PassSubtarget ? "STI, " : "") << "OS);\n"
1057         << "    break;\n";
1058     }
1059     O << "  }\n";
1060   }    
1061   O << "}\n\n";
1062
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       << "  switch (PredicateIndex) {\n"
1069       << "  default:\n"
1070       << "    llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n"
1071       << "    break;\n";
1072
1073     for (unsigned i = 0; i < MCOpPredicates.size(); ++i) {
1074       Init *MCOpPred = MCOpPredicates[i]->getValueInit("MCOperandPredicate");
1075       if (StringInit *SI = dyn_cast<StringInit>(MCOpPred)) {
1076         O << "  case " << i + 1 << ": {\n"
1077           << SI->getValue() << "\n"
1078           << "    }\n";
1079       } else
1080         llvm_unreachable("Unexpected MCOperandPredicate field!");
1081     }
1082     O << "  }\n"
1083       << "}\n\n";
1084   }
1085
1086   O << "#endif // PRINT_ALIAS_INSTR\n";
1087 }
1088
1089 AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) {
1090   Record *AsmWriter = Target.getAsmWriter();
1091   unsigned Variant = AsmWriter->getValueAsInt("Variant");
1092   unsigned PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
1093   for (const CodeGenInstruction *I : Target.instructions())
1094     if (!I->AsmString.empty() && I->TheDef->getName() != "PHI")
1095       Instructions.emplace_back(*I, Variant, PassSubtarget);
1096
1097   // Get the instruction numbering.
1098   NumberedInstructions = &Target.getInstructionsByEnumValue();
1099
1100   // Compute the CodeGenInstruction -> AsmWriterInst mapping.  Note that not
1101   // all machine instructions are necessarily being printed, so there may be
1102   // target instructions not in this map.
1103   for (AsmWriterInst &AWI : Instructions)
1104     CGIAWIMap.insert(std::make_pair(AWI.CGI, &AWI));
1105 }
1106
1107 void AsmWriterEmitter::run(raw_ostream &O) {
1108   EmitPrintInstruction(O);
1109   EmitGetRegisterName(O);
1110   EmitPrintAliasInstruction(O);
1111 }
1112
1113
1114 namespace llvm {
1115
1116 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) {
1117   emitSourceFileHeader("Assembly Writer Source Fragment", OS);
1118   AsmWriterEmitter(RK).run(OS);
1119 }
1120
1121 } // End llvm namespace