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