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