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