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/StringExtras.h"
19#include "llvm/ADT/Twine.h"
20#include "llvm/Support/Debug.h"
21#include "llvm/Support/MathExtras.h"
22#include "llvm/TableGen/Error.h"
23#include "llvm/TableGen/Record.h"
24#include "llvm/TableGen/TableGenBackend.h"
25#include <algorithm>
26#include <cassert>
27#include <map>
28#include <vector>
29using namespace llvm;
30
31namespace {
32class AsmWriterEmitter {
33  RecordKeeper &Records;
34  std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap;
35  std::vector<const CodeGenInstruction*> NumberedInstructions;
36public:
37  AsmWriterEmitter(RecordKeeper &R) : Records(R) {}
38
39  void run(raw_ostream &o);
40
41private:
42  void EmitPrintInstruction(raw_ostream &o);
43  void EmitGetRegisterName(raw_ostream &o);
44  void EmitPrintAliasInstruction(raw_ostream &O);
45
46  AsmWriterInst *getAsmWriterInstByID(unsigned ID) const {
47    assert(ID < NumberedInstructions.size());
48    std::map<const CodeGenInstruction*, AsmWriterInst*>::const_iterator I =
49      CGIAWIMap.find(NumberedInstructions[ID]);
50    assert(I != CGIAWIMap.end() && "Didn't find inst!");
51    return I->second;
52  }
53  void FindUniqueOperandCommands(std::vector<std::string> &UOC,
54                                 std::vector<unsigned> &InstIdxs,
55                                 std::vector<unsigned> &InstOpsUsed) const;
56};
57} // end anonymous namespace
58
59static void PrintCases(std::vector<std::pair<std::string,
60                       AsmWriterOperand> > &OpsToPrint, raw_ostream &O) {
61  O << "    case " << OpsToPrint.back().first << ": ";
62  AsmWriterOperand TheOp = OpsToPrint.back().second;
63  OpsToPrint.pop_back();
64
65  // Check to see if any other operands are identical in this list, and if so,
66  // emit a case label for them.
67  for (unsigned i = OpsToPrint.size(); i != 0; --i)
68    if (OpsToPrint[i-1].second == TheOp) {
69      O << "\n    case " << OpsToPrint[i-1].first << ": ";
70      OpsToPrint.erase(OpsToPrint.begin()+i-1);
71    }
72
73  // Finally, emit the code.
74  O << TheOp.getCode();
75  O << "break;\n";
76}
77
78
79/// EmitInstructions - Emit the last instruction in the vector and any other
80/// instructions that are suitably similar to it.
81static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
82                             raw_ostream &O) {
83  AsmWriterInst FirstInst = Insts.back();
84  Insts.pop_back();
85
86  std::vector<AsmWriterInst> SimilarInsts;
87  unsigned DifferingOperand = ~0;
88  for (unsigned i = Insts.size(); i != 0; --i) {
89    unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
90    if (DiffOp != ~1U) {
91      if (DifferingOperand == ~0U)  // First match!
92        DifferingOperand = DiffOp;
93
94      // If this differs in the same operand as the rest of the instructions in
95      // this class, move it to the SimilarInsts list.
96      if (DifferingOperand == DiffOp || DiffOp == ~0U) {
97        SimilarInsts.push_back(Insts[i-1]);
98        Insts.erase(Insts.begin()+i-1);
99      }
100    }
101  }
102
103  O << "  case " << FirstInst.CGI->Namespace << "::"
104    << FirstInst.CGI->TheDef->getName() << ":\n";
105  for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
106    O << "  case " << SimilarInsts[i].CGI->Namespace << "::"
107      << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
108  for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
109    if (i != DifferingOperand) {
110      // If the operand is the same for all instructions, just print it.
111      O << "    " << FirstInst.Operands[i].getCode();
112    } else {
113      // If this is the operand that varies between all of the instructions,
114      // emit a switch for just this operand now.
115      O << "    switch (MI->getOpcode()) {\n";
116      std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
117      OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
118                                          FirstInst.CGI->TheDef->getName(),
119                                          FirstInst.Operands[i]));
120
121      for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
122        AsmWriterInst &AWI = SimilarInsts[si];
123        OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
124                                            AWI.CGI->TheDef->getName(),
125                                            AWI.Operands[i]));
126      }
127      std::reverse(OpsToPrint.begin(), OpsToPrint.end());
128      while (!OpsToPrint.empty())
129        PrintCases(OpsToPrint, O);
130      O << "    }";
131    }
132    O << "\n";
133  }
134  O << "    break;\n";
135}
136
137void AsmWriterEmitter::
138FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
139                          std::vector<unsigned> &InstIdxs,
140                          std::vector<unsigned> &InstOpsUsed) const {
141  InstIdxs.assign(NumberedInstructions.size(), ~0U);
142
143  // This vector parallels UniqueOperandCommands, keeping track of which
144  // instructions each case are used for.  It is a comma separated string of
145  // enums.
146  std::vector<std::string> InstrsForCase;
147  InstrsForCase.resize(UniqueOperandCommands.size());
148  InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
149
150  for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
151    const AsmWriterInst *Inst = getAsmWriterInstByID(i);
152    if (Inst == 0) continue;  // PHI, INLINEASM, PROLOG_LABEL, etc.
153
154    std::string Command;
155    if (Inst->Operands.empty())
156      continue;   // Instruction already done.
157
158    Command = "    " + Inst->Operands[0].getCode() + "\n";
159
160    // Check to see if we already have 'Command' in UniqueOperandCommands.
161    // If not, add it.
162    bool FoundIt = false;
163    for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
164      if (UniqueOperandCommands[idx] == Command) {
165        InstIdxs[i] = idx;
166        InstrsForCase[idx] += ", ";
167        InstrsForCase[idx] += Inst->CGI->TheDef->getName();
168        FoundIt = true;
169        break;
170      }
171    if (!FoundIt) {
172      InstIdxs[i] = UniqueOperandCommands.size();
173      UniqueOperandCommands.push_back(Command);
174      InstrsForCase.push_back(Inst->CGI->TheDef->getName());
175
176      // This command matches one operand so far.
177      InstOpsUsed.push_back(1);
178    }
179  }
180
181  // For each entry of UniqueOperandCommands, there is a set of instructions
182  // that uses it.  If the next command of all instructions in the set are
183  // identical, fold it into the command.
184  for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
185       CommandIdx != e; ++CommandIdx) {
186
187    for (unsigned Op = 1; ; ++Op) {
188      // Scan for the first instruction in the set.
189      std::vector<unsigned>::iterator NIT =
190        std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
191      if (NIT == InstIdxs.end()) break;  // No commonality.
192
193      // If this instruction has no more operands, we isn't anything to merge
194      // into this command.
195      const AsmWriterInst *FirstInst =
196        getAsmWriterInstByID(NIT-InstIdxs.begin());
197      if (!FirstInst || FirstInst->Operands.size() == Op)
198        break;
199
200      // Otherwise, scan to see if all of the other instructions in this command
201      // set share the operand.
202      bool AllSame = true;
203      // Keep track of the maximum, number of operands or any
204      // instruction we see in the group.
205      size_t MaxSize = FirstInst->Operands.size();
206
207      for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
208           NIT != InstIdxs.end();
209           NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
210        // Okay, found another instruction in this command set.  If the operand
211        // matches, we're ok, otherwise bail out.
212        const AsmWriterInst *OtherInst =
213          getAsmWriterInstByID(NIT-InstIdxs.begin());
214
215        if (OtherInst &&
216            OtherInst->Operands.size() > FirstInst->Operands.size())
217          MaxSize = std::max(MaxSize, OtherInst->Operands.size());
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
251static 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.
276void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) {
277  CodeGenTarget Target(Records);
278  Record *AsmWriter = Target.getAsmWriter();
279  std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
280  bool isMC = AsmWriter->getValueAsBit("isMCAsmWriter");
281  const char *MachineInstrClassName = isMC ? "MCInst" : "MachineInstr";
282
283  O <<
284  "/// printInstruction - This method is automatically generated by tablegen\n"
285  "/// from the instruction set description.\n"
286    "void " << Target.getName() << ClassName
287            << "::printInstruction(const " << MachineInstrClassName
288            << " *MI, raw_ostream &O) {\n";
289
290  std::vector<AsmWriterInst> Instructions;
291
292  for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
293         E = Target.inst_end(); I != E; ++I)
294    if (!(*I)->AsmString.empty() &&
295        (*I)->TheDef->getName() != "PHI")
296      Instructions.push_back(
297        AsmWriterInst(**I,
298                      AsmWriter->getValueAsInt("Variant"),
299                      AsmWriter->getValueAsInt("FirstOperandColumn"),
300                      AsmWriter->getValueAsInt("OperandSpacing")));
301
302  // Get the instruction numbering.
303  NumberedInstructions = Target.getInstructionsByEnumValue();
304
305  // Compute the CodeGenInstruction -> AsmWriterInst mapping.  Note that not
306  // all machine instructions are necessarily being printed, so there may be
307  // target instructions not in this map.
308  for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
309    CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
310
311  // Build an aggregate string, and build a table of offsets into it.
312  SequenceToOffsetTable<std::string> StringTable;
313
314  /// OpcodeInfo - This encodes the index of the string to use for the first
315  /// chunk of the output as well as indices used for operand printing.
316  std::vector<unsigned> OpcodeInfo;
317
318  // Add all strings to the string table upfront so it can generate an optimized
319  // representation.
320  for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
321    AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
322    if (AWI != 0 &&
323        AWI->Operands[0].OperandType ==
324                 AsmWriterOperand::isLiteralTextOperand &&
325        !AWI->Operands[0].Str.empty()) {
326      std::string Str = AWI->Operands[0].Str;
327      UnescapeString(Str);
328      StringTable.add(Str);
329    }
330  }
331
332  StringTable.layout();
333
334  unsigned MaxStringIdx = 0;
335  for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
336    AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
337    unsigned Idx;
338    if (AWI == 0) {
339      // Something not handled by the asmwriter printer.
340      Idx = ~0U;
341    } else if (AWI->Operands[0].OperandType !=
342                        AsmWriterOperand::isLiteralTextOperand ||
343               AWI->Operands[0].Str.empty()) {
344      // Something handled by the asmwriter printer, but with no leading string.
345      Idx = StringTable.get("");
346    } else {
347      std::string Str = AWI->Operands[0].Str;
348      UnescapeString(Str);
349      Idx = StringTable.get(Str);
350      MaxStringIdx = std::max(MaxStringIdx, Idx);
351
352      // Nuke the string from the operand list.  It is now handled!
353      AWI->Operands.erase(AWI->Operands.begin());
354    }
355
356    // Bias offset by one since we want 0 as a sentinel.
357    OpcodeInfo.push_back(Idx+1);
358  }
359
360  // Figure out how many bits we used for the string index.
361  unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
362
363  // To reduce code size, we compactify common instructions into a few bits
364  // in the opcode-indexed table.
365  unsigned BitsLeft = 32-AsmStrBits;
366
367  std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
368
369  while (1) {
370    std::vector<std::string> UniqueOperandCommands;
371    std::vector<unsigned> InstIdxs;
372    std::vector<unsigned> NumInstOpsHandled;
373    FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
374                              NumInstOpsHandled);
375
376    // If we ran out of operands to print, we're done.
377    if (UniqueOperandCommands.empty()) break;
378
379    // Compute the number of bits we need to represent these cases, this is
380    // ceil(log2(numentries)).
381    unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
382
383    // If we don't have enough bits for this operand, don't include it.
384    if (NumBits > BitsLeft) {
385      DEBUG(errs() << "Not enough bits to densely encode " << NumBits
386                   << " more bits\n");
387      break;
388    }
389
390    // Otherwise, we can include this in the initial lookup table.  Add it in.
391    BitsLeft -= NumBits;
392    for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
393      if (InstIdxs[i] != ~0U)
394        OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
395
396    // Remove the info about this operand.
397    for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
398      if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
399        if (!Inst->Operands.empty()) {
400          unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
401          assert(NumOps <= Inst->Operands.size() &&
402                 "Can't remove this many ops!");
403          Inst->Operands.erase(Inst->Operands.begin(),
404                               Inst->Operands.begin()+NumOps);
405        }
406    }
407
408    // Remember the handlers for this set of operands.
409    TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
410  }
411
412
413
414  O<<"  static const unsigned OpInfo[] = {\n";
415  for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
416    O << "    " << OpcodeInfo[i] << "U,\t// "
417      << NumberedInstructions[i]->TheDef->getName() << "\n";
418  }
419  // Add a dummy entry so the array init doesn't end with a comma.
420  O << "    0U\n";
421  O << "  };\n\n";
422
423  // Emit the string itself.
424  O << "  const char AsmStrs[] = {\n";
425  StringTable.emit(O, printChar);
426  O << "  };\n\n";
427
428  O << "  O << \"\\t\";\n\n";
429
430  O << "  // Emit the opcode for the instruction.\n"
431    << "  unsigned Bits = OpInfo[MI->getOpcode()];\n"
432    << "  assert(Bits != 0 && \"Cannot print this instruction.\");\n"
433    << "  O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
434
435  // Output the table driven operand information.
436  BitsLeft = 32-AsmStrBits;
437  for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
438    std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
439
440    // Compute the number of bits we need to represent these cases, this is
441    // ceil(log2(numentries)).
442    unsigned NumBits = Log2_32_Ceil(Commands.size());
443    assert(NumBits <= BitsLeft && "consistency error");
444
445    // Emit code to extract this field from Bits.
446    BitsLeft -= NumBits;
447
448    O << "\n  // Fragment " << i << " encoded into " << NumBits
449      << " bits for " << Commands.size() << " unique commands.\n";
450
451    if (Commands.size() == 2) {
452      // Emit two possibilitys with if/else.
453      O << "  if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
454        << ((1 << NumBits)-1) << ") {\n"
455        << Commands[1]
456        << "  } else {\n"
457        << Commands[0]
458        << "  }\n\n";
459    } else if (Commands.size() == 1) {
460      // Emit a single possibility.
461      O << Commands[0] << "\n\n";
462    } else {
463      O << "  switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
464        << ((1 << NumBits)-1) << ") {\n"
465        << "  default:   // unreachable.\n";
466
467      // Print out all the cases.
468      for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
469        O << "  case " << i << ":\n";
470        O << Commands[i];
471        O << "    break;\n";
472      }
473      O << "  }\n\n";
474    }
475  }
476
477  // Okay, delete instructions with no operand info left.
478  for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
479    // Entire instruction has been emitted?
480    AsmWriterInst &Inst = Instructions[i];
481    if (Inst.Operands.empty()) {
482      Instructions.erase(Instructions.begin()+i);
483      --i; --e;
484    }
485  }
486
487
488  // Because this is a vector, we want to emit from the end.  Reverse all of the
489  // elements in the vector.
490  std::reverse(Instructions.begin(), Instructions.end());
491
492
493  // Now that we've emitted all of the operand info that fit into 32 bits, emit
494  // information for those instructions that are left.  This is a less dense
495  // encoding, but we expect the main 32-bit table to handle the majority of
496  // instructions.
497  if (!Instructions.empty()) {
498    // Find the opcode # of inline asm.
499    O << "  switch (MI->getOpcode()) {\n";
500    while (!Instructions.empty())
501      EmitInstructions(Instructions, O);
502
503    O << "  }\n";
504    O << "  return;\n";
505  }
506
507  O << "}\n";
508}
509
510static void
511emitRegisterNameString(raw_ostream &O, StringRef AltName,
512                       const std::vector<CodeGenRegister*> &Registers) {
513  SequenceToOffsetTable<std::string> StringTable;
514  SmallVector<std::string, 4> AsmNames(Registers.size());
515  for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
516    const CodeGenRegister &Reg = *Registers[i];
517    std::string &AsmName = AsmNames[i];
518
519    // "NoRegAltName" is special. We don't need to do a lookup for that,
520    // as it's just a reference to the default register name.
521    if (AltName == "" || AltName == "NoRegAltName") {
522      AsmName = Reg.TheDef->getValueAsString("AsmName");
523      if (AsmName.empty())
524        AsmName = Reg.getName();
525    } else {
526      // Make sure the register has an alternate name for this index.
527      std::vector<Record*> AltNameList =
528        Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
529      unsigned Idx = 0, e;
530      for (e = AltNameList.size();
531           Idx < e && (AltNameList[Idx]->getName() != AltName);
532           ++Idx)
533        ;
534      // If the register has an alternate name for this index, use it.
535      // Otherwise, leave it empty as an error flag.
536      if (Idx < e) {
537        std::vector<std::string> AltNames =
538          Reg.TheDef->getValueAsListOfStrings("AltNames");
539        if (AltNames.size() <= Idx)
540          throw TGError(Reg.TheDef->getLoc(),
541                        (Twine("Register definition missing alt name for '") +
542                        AltName + "'.").str());
543        AsmName = AltNames[Idx];
544      }
545    }
546    StringTable.add(AsmName);
547  }
548
549  StringTable.layout();
550  O << "  static const char AsmStrs" << AltName << "[] = {\n";
551  StringTable.emit(O, printChar);
552  O << "  };\n\n";
553
554  O << "  static const unsigned RegAsmOffset" << AltName << "[] = {";
555  for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
556    if ((i % 14) == 0)
557      O << "\n    ";
558    O << StringTable.get(AsmNames[i]) << ", ";
559  }
560  O << "\n  };\n"
561    << "\n";
562}
563
564void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
565  CodeGenTarget Target(Records);
566  Record *AsmWriter = Target.getAsmWriter();
567  std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
568  const std::vector<CodeGenRegister*> &Registers =
569    Target.getRegBank().getRegisters();
570  std::vector<Record*> AltNameIndices = Target.getRegAltNameIndices();
571  bool hasAltNames = AltNameIndices.size() > 1;
572
573  O <<
574  "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
575  "/// from the register set description.  This returns the assembler name\n"
576  "/// for the specified register.\n"
577  "const char *" << Target.getName() << ClassName << "::";
578  if (hasAltNames)
579    O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
580  else
581    O << "getRegisterName(unsigned RegNo) {\n";
582  O << "  assert(RegNo && RegNo < " << (Registers.size()+1)
583    << " && \"Invalid register number!\");\n"
584    << "\n";
585
586  if (hasAltNames) {
587    for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i)
588      emitRegisterNameString(O, AltNameIndices[i]->getName(), Registers);
589  } else
590    emitRegisterNameString(O, "", Registers);
591
592  if (hasAltNames) {
593    O << "  const unsigned *RegAsmOffset;\n"
594      << "  const char *AsmStrs;\n"
595      << "  switch(AltIdx) {\n"
596      << "  default: llvm_unreachable(\"Invalid register alt name index!\");\n";
597    for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i) {
598      StringRef Namespace = AltNameIndices[1]->getValueAsString("Namespace");
599      StringRef AltName(AltNameIndices[i]->getName());
600      O << "  case " << Namespace << "::" << AltName
601        << ":\n"
602        << "    AsmStrs = AsmStrs" << AltName  << ";\n"
603        << "    RegAsmOffset = RegAsmOffset" << AltName << ";\n"
604        << "    break;\n";
605    }
606    O << "}\n";
607  }
608
609  O << "  assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
610    << "          \"Invalid alt name index for register!\");\n"
611    << "  return AsmStrs+RegAsmOffset[RegNo-1];\n"
612    << "}\n";
613}
614
615namespace {
616// IAPrinter - Holds information about an InstAlias. Two InstAliases match if
617// they both have the same conditionals. In which case, we cannot print out the
618// alias for that pattern.
619class IAPrinter {
620  std::vector<std::string> Conds;
621  std::map<StringRef, unsigned> OpMap;
622  std::string Result;
623  std::string AsmString;
624  SmallVector<Record*, 4> ReqFeatures;
625public:
626  IAPrinter(std::string R, std::string AS)
627    : Result(R), AsmString(AS) {}
628
629  void addCond(const std::string &C) { Conds.push_back(C); }
630
631  void addOperand(StringRef Op, unsigned Idx) { OpMap[Op] = Idx; }
632  unsigned getOpIndex(StringRef Op) { return OpMap[Op]; }
633  bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
634
635  void print(raw_ostream &O) {
636    if (Conds.empty() && ReqFeatures.empty()) {
637      O.indent(6) << "return true;\n";
638      return;
639    }
640
641    O << "if (";
642
643    for (std::vector<std::string>::iterator
644           I = Conds.begin(), E = Conds.end(); I != E; ++I) {
645      if (I != Conds.begin()) {
646        O << " &&\n";
647        O.indent(8);
648      }
649
650      O << *I;
651    }
652
653    O << ") {\n";
654    O.indent(6) << "// " << Result << "\n";
655    O.indent(6) << "AsmString = \"" << AsmString << "\";\n";
656
657    for (std::map<StringRef, unsigned>::iterator
658           I = OpMap.begin(), E = OpMap.end(); I != E; ++I)
659      O.indent(6) << "OpMap.push_back(std::make_pair(\"" << I->first << "\", "
660                  << I->second << "));\n";
661
662    O.indent(6) << "break;\n";
663    O.indent(4) << '}';
664  }
665
666  bool operator==(const IAPrinter &RHS) {
667    if (Conds.size() != RHS.Conds.size())
668      return false;
669
670    unsigned Idx = 0;
671    for (std::vector<std::string>::iterator
672           I = Conds.begin(), E = Conds.end(); I != E; ++I)
673      if (*I != RHS.Conds[Idx++])
674        return false;
675
676    return true;
677  }
678
679  bool operator()(const IAPrinter &RHS) {
680    if (Conds.size() < RHS.Conds.size())
681      return true;
682
683    unsigned Idx = 0;
684    for (std::vector<std::string>::iterator
685           I = Conds.begin(), E = Conds.end(); I != E; ++I)
686      if (*I != RHS.Conds[Idx++])
687        return *I < RHS.Conds[Idx++];
688
689    return false;
690  }
691};
692
693} // end anonymous namespace
694
695static void EmitGetMapOperandNumber(raw_ostream &O) {
696  O << "static unsigned getMapOperandNumber("
697    << "const SmallVectorImpl<std::pair<StringRef, unsigned> > &OpMap,\n";
698  O << "                                    StringRef Name) {\n";
699  O << "  for (SmallVectorImpl<std::pair<StringRef, unsigned> >::"
700    << "const_iterator\n";
701  O << "         I = OpMap.begin(), E = OpMap.end(); I != E; ++I)\n";
702  O << "    if (I->first == Name)\n";
703  O << "      return I->second;\n";
704  O << "  llvm_unreachable(\"Operand not in map!\");\n";
705  O << "}\n\n";
706}
707
708static unsigned CountNumOperands(StringRef AsmString) {
709  unsigned NumOps = 0;
710  std::pair<StringRef, StringRef> ASM = AsmString.split(' ');
711
712  while (!ASM.second.empty()) {
713    ++NumOps;
714    ASM = ASM.second.split(' ');
715  }
716
717  return NumOps;
718}
719
720static unsigned CountResultNumOperands(StringRef AsmString) {
721  unsigned NumOps = 0;
722  std::pair<StringRef, StringRef> ASM = AsmString.split('\t');
723
724  if (!ASM.second.empty()) {
725    size_t I = ASM.second.find('{');
726    StringRef Str = ASM.second;
727    if (I != StringRef::npos)
728      Str = ASM.second.substr(I, ASM.second.find('|', I));
729
730    ASM = Str.split(' ');
731
732    do {
733      ++NumOps;
734      ASM = ASM.second.split(' ');
735    } while (!ASM.second.empty());
736  }
737
738  return NumOps;
739}
740
741void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
742  CodeGenTarget Target(Records);
743  Record *AsmWriter = Target.getAsmWriter();
744
745  if (!AsmWriter->getValueAsBit("isMCAsmWriter"))
746    return;
747
748  O << "\n#ifdef PRINT_ALIAS_INSTR\n";
749  O << "#undef PRINT_ALIAS_INSTR\n\n";
750
751  // Emit the method that prints the alias instruction.
752  std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
753
754  std::vector<Record*> AllInstAliases =
755    Records.getAllDerivedDefinitions("InstAlias");
756
757  // Create a map from the qualified name to a list of potential matches.
758  std::map<std::string, std::vector<CodeGenInstAlias*> > AliasMap;
759  for (std::vector<Record*>::iterator
760         I = AllInstAliases.begin(), E = AllInstAliases.end(); I != E; ++I) {
761    CodeGenInstAlias *Alias = new CodeGenInstAlias(*I, Target);
762    const Record *R = *I;
763    if (!R->getValueAsBit("EmitAlias"))
764      continue; // We were told not to emit the alias, but to emit the aliasee.
765    const DagInit *DI = R->getValueAsDag("ResultInst");
766    const DefInit *Op = dynamic_cast<const DefInit*>(DI->getOperator());
767    AliasMap[getQualifiedName(Op->getDef())].push_back(Alias);
768  }
769
770  // A map of which conditions need to be met for each instruction operand
771  // before it can be matched to the mnemonic.
772  std::map<std::string, std::vector<IAPrinter*> > IAPrinterMap;
773
774  for (std::map<std::string, std::vector<CodeGenInstAlias*> >::iterator
775         I = AliasMap.begin(), E = AliasMap.end(); I != E; ++I) {
776    std::vector<CodeGenInstAlias*> &Aliases = I->second;
777
778    for (std::vector<CodeGenInstAlias*>::iterator
779           II = Aliases.begin(), IE = Aliases.end(); II != IE; ++II) {
780      const CodeGenInstAlias *CGA = *II;
781      unsigned LastOpNo = CGA->ResultInstOperandIndex.size();
782      unsigned NumResultOps =
783        CountResultNumOperands(CGA->ResultInst->AsmString);
784
785      // Don't emit the alias if it has more operands than what it's aliasing.
786      if (NumResultOps < CountNumOperands(CGA->AsmString))
787        continue;
788
789      IAPrinter *IAP = new IAPrinter(CGA->Result->getAsString(),
790                                     CGA->AsmString);
791
792      std::string Cond;
793      Cond = std::string("MI->getNumOperands() == ") + llvm::utostr(LastOpNo);
794      IAP->addCond(Cond);
795
796      std::map<StringRef, unsigned> OpMap;
797      bool CantHandle = false;
798
799      for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
800        const CodeGenInstAlias::ResultOperand &RO = CGA->ResultOperands[i];
801
802        switch (RO.Kind) {
803        case CodeGenInstAlias::ResultOperand::K_Record: {
804          const Record *Rec = RO.getRecord();
805          StringRef ROName = RO.getName();
806
807
808          if (Rec->isSubClassOf("RegisterOperand"))
809            Rec = Rec->getValueAsDef("RegClass");
810          if (Rec->isSubClassOf("RegisterClass")) {
811            Cond = std::string("MI->getOperand(")+llvm::utostr(i)+").isReg()";
812            IAP->addCond(Cond);
813
814            if (!IAP->isOpMapped(ROName)) {
815              IAP->addOperand(ROName, i);
816              Cond = std::string("MRI.getRegClass(") + Target.getName() + "::" +
817                CGA->ResultOperands[i].getRecord()->getName() + "RegClassID)"
818                ".contains(MI->getOperand(" + llvm::utostr(i) + ").getReg())";
819              IAP->addCond(Cond);
820            } else {
821              Cond = std::string("MI->getOperand(") +
822                llvm::utostr(i) + ").getReg() == MI->getOperand(" +
823                llvm::utostr(IAP->getOpIndex(ROName)) + ").getReg()";
824              IAP->addCond(Cond);
825            }
826          } else {
827            assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
828            // FIXME: We may need to handle these situations.
829            delete IAP;
830            IAP = 0;
831            CantHandle = true;
832            break;
833          }
834
835          break;
836        }
837        case CodeGenInstAlias::ResultOperand::K_Imm:
838          Cond = std::string("MI->getOperand(") +
839            llvm::utostr(i) + ").getImm() == " +
840            llvm::utostr(CGA->ResultOperands[i].getImm());
841          IAP->addCond(Cond);
842          break;
843        case CodeGenInstAlias::ResultOperand::K_Reg:
844          // If this is zero_reg, something's playing tricks we're not
845          // equipped to handle.
846          if (!CGA->ResultOperands[i].getRegister()) {
847            CantHandle = true;
848            break;
849          }
850
851          Cond = std::string("MI->getOperand(") +
852            llvm::utostr(i) + ").getReg() == " + Target.getName() +
853            "::" + CGA->ResultOperands[i].getRegister()->getName();
854          IAP->addCond(Cond);
855          break;
856        }
857
858        if (!IAP) break;
859      }
860
861      if (CantHandle) continue;
862      IAPrinterMap[I->first].push_back(IAP);
863    }
864  }
865
866  std::string Header;
867  raw_string_ostream HeaderO(Header);
868
869  HeaderO << "bool " << Target.getName() << ClassName
870          << "::printAliasInstr(const MCInst"
871          << " *MI, raw_ostream &OS) {\n";
872
873  std::string Cases;
874  raw_string_ostream CasesO(Cases);
875
876  for (std::map<std::string, std::vector<IAPrinter*> >::iterator
877         I = IAPrinterMap.begin(), E = IAPrinterMap.end(); I != E; ++I) {
878    std::vector<IAPrinter*> &IAPs = I->second;
879    std::vector<IAPrinter*> UniqueIAPs;
880
881    for (std::vector<IAPrinter*>::iterator
882           II = IAPs.begin(), IE = IAPs.end(); II != IE; ++II) {
883      IAPrinter *LHS = *II;
884      bool IsDup = false;
885      for (std::vector<IAPrinter*>::iterator
886             III = IAPs.begin(), IIE = IAPs.end(); III != IIE; ++III) {
887        IAPrinter *RHS = *III;
888        if (LHS != RHS && *LHS == *RHS) {
889          IsDup = true;
890          break;
891        }
892      }
893
894      if (!IsDup) UniqueIAPs.push_back(LHS);
895    }
896
897    if (UniqueIAPs.empty()) continue;
898
899    CasesO.indent(2) << "case " << I->first << ":\n";
900
901    for (std::vector<IAPrinter*>::iterator
902           II = UniqueIAPs.begin(), IE = UniqueIAPs.end(); II != IE; ++II) {
903      IAPrinter *IAP = *II;
904      CasesO.indent(4);
905      IAP->print(CasesO);
906      CasesO << '\n';
907    }
908
909    CasesO.indent(4) << "return false;\n";
910  }
911
912  if (CasesO.str().empty()) {
913    O << HeaderO.str();
914    O << "  return false;\n";
915    O << "}\n\n";
916    O << "#endif // PRINT_ALIAS_INSTR\n";
917    return;
918  }
919
920  EmitGetMapOperandNumber(O);
921
922  O << HeaderO.str();
923  O.indent(2) << "StringRef AsmString;\n";
924  O.indent(2) << "SmallVector<std::pair<StringRef, unsigned>, 4> OpMap;\n";
925  O.indent(2) << "switch (MI->getOpcode()) {\n";
926  O.indent(2) << "default: return false;\n";
927  O << CasesO.str();
928  O.indent(2) << "}\n\n";
929
930  // Code that prints the alias, replacing the operands with the ones from the
931  // MCInst.
932  O << "  std::pair<StringRef, StringRef> ASM = AsmString.split(' ');\n";
933  O << "  OS << '\\t' << ASM.first;\n";
934
935  O << "  if (!ASM.second.empty()) {\n";
936  O << "    OS << '\\t';\n";
937  O << "    for (StringRef::iterator\n";
938  O << "         I = ASM.second.begin(), E = ASM.second.end(); I != E; ) {\n";
939  O << "      if (*I == '$') {\n";
940  O << "        StringRef::iterator Start = ++I;\n";
941  O << "        while (I != E &&\n";
942  O << "               ((*I >= 'a' && *I <= 'z') ||\n";
943  O << "                (*I >= 'A' && *I <= 'Z') ||\n";
944  O << "                (*I >= '0' && *I <= '9') ||\n";
945  O << "                *I == '_'))\n";
946  O << "          ++I;\n";
947  O << "        StringRef Name(Start, I - Start);\n";
948  O << "        printOperand(MI, getMapOperandNumber(OpMap, Name), OS);\n";
949  O << "      } else {\n";
950  O << "        OS << *I++;\n";
951  O << "      }\n";
952  O << "    }\n";
953  O << "  }\n\n";
954
955  O << "  return true;\n";
956  O << "}\n\n";
957
958  O << "#endif // PRINT_ALIAS_INSTR\n";
959}
960
961void AsmWriterEmitter::run(raw_ostream &O) {
962  EmitPrintInstruction(O);
963  EmitGetRegisterName(O);
964  EmitPrintAliasInstruction(O);
965}
966
967
968namespace llvm {
969
970void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) {
971  emitSourceFileHeader("Assembly Writer Source Fragment", OS);
972  AsmWriterEmitter(RK).run(OS);
973}
974
975} // End llvm namespace
976