933f9210f82e4819dc26e228eee8a3c6e0e6f232
[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 "CodeGenTarget.h"
17 #include "Record.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/MathExtras.h"
21 #include <algorithm>
22 #include <sstream>
23 #include <iostream>
24 using namespace llvm;
25
26 static bool isIdentChar(char C) {
27   return (C >= 'a' && C <= 'z') ||
28          (C >= 'A' && C <= 'Z') ||
29          (C >= '0' && C <= '9') ||
30          C == '_';
31 }
32
33 // This should be an anon namespace, this works around a GCC warning.
34 namespace llvm {  
35   struct AsmWriterOperand {
36     enum OpType { 
37       isLiteralTextOperand, 
38       isMachineInstrOperand,
39       isLiteralStatementOperand
40     } OperandType;
41
42     /// Str - For isLiteralTextOperand, this IS the literal text.  For
43     /// isMachineInstrOperand, this is the PrinterMethodName for the operand.
44     std::string Str;
45
46     /// MiOpNo - For isMachineInstrOperand, this is the operand number of the
47     /// machine instruction.
48     unsigned MIOpNo;
49     
50     /// MiModifier - For isMachineInstrOperand, this is the modifier string for
51     /// an operand, specified with syntax like ${opname:modifier}.
52     std::string MiModifier;
53
54     // To make VS STL happy
55     AsmWriterOperand(OpType op = isLiteralTextOperand):OperandType(op) {}
56
57     AsmWriterOperand(const std::string &LitStr,
58                      OpType op = isLiteralTextOperand)
59       : OperandType(op), Str(LitStr) {}
60
61     AsmWriterOperand(const std::string &Printer, unsigned OpNo, 
62                      const std::string &Modifier,
63                      OpType op = isMachineInstrOperand) 
64       : OperandType(op), Str(Printer), MIOpNo(OpNo),
65       MiModifier(Modifier) {}
66
67     bool operator!=(const AsmWriterOperand &Other) const {
68       if (OperandType != Other.OperandType || Str != Other.Str) return true;
69       if (OperandType == isMachineInstrOperand)
70         return MIOpNo != Other.MIOpNo || MiModifier != Other.MiModifier;
71       return false;
72     }
73     bool operator==(const AsmWriterOperand &Other) const {
74       return !operator!=(Other);
75     }
76     
77     /// getCode - Return the code that prints this operand.
78     std::string getCode() const;
79   };
80 }
81
82 namespace llvm {
83   class AsmWriterInst {
84   public:
85     std::vector<AsmWriterOperand> Operands;
86     const CodeGenInstruction *CGI;
87
88     /// MAX_GROUP_NESTING_LEVEL - The maximum number of group nesting
89     /// levels we ever expect to see in an asm operand.
90     static const int MAX_GROUP_NESTING_LEVEL = 10;
91
92     /// GroupLevel - The level of nesting of the current operand
93     /// group, such as [reg + (reg + offset)].  -1 means we are not in
94     /// a group.
95     int GroupLevel;
96
97     /// GroupDelim - Remember the delimeter for a group operand.
98     char GroupDelim[MAX_GROUP_NESTING_LEVEL];
99
100     /// InGroup - Determine whether we are in the middle of an
101     /// operand group.
102     bool InGroup() const { return GroupLevel != -1; }
103
104     AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
105
106     /// MatchesAllButOneOp - If this instruction is exactly identical to the
107     /// specified instruction except for one differing operand, return the
108     /// differing operand number.  Otherwise return ~0.
109     unsigned MatchesAllButOneOp(const AsmWriterInst &Other) const;
110
111   private:
112     void AddLiteralString(const std::string &Str) {
113       // If the last operand was already a literal text string, append this to
114       // it, otherwise add a new operand.
115
116       std::string::size_type SearchStart = 0;
117       std::string::size_type SpaceStartPos = std::string::npos;
118       do {
119         // Search for whitespace and replace with calls to set the
120         // output column.
121         SpaceStartPos = Str.find_first_of(" \t", SearchStart);
122         // Assume grouped text is one operand.
123         std::string::size_type StartDelimPos = Str.find_first_of("[{(", SearchStart);
124
125         SearchStart = std::string::npos;
126
127         if (StartDelimPos != std::string::npos) {
128           ++GroupLevel;
129           assert(GroupLevel < MAX_GROUP_NESTING_LEVEL
130                  && "Exceeded maximum operand group nesting level");
131           GroupDelim[GroupLevel] = Str[StartDelimPos];
132           if (SpaceStartPos != std::string::npos &&
133               SpaceStartPos > StartDelimPos) {
134             // This space doesn't count.
135             SpaceStartPos = std::string::npos;
136           }
137         }
138
139         if (InGroup()) {
140           // Find the end delimiter.
141           char EndDelim = (GroupDelim[GroupLevel] == '{' ? '}' : 
142                            (GroupDelim[GroupLevel] == '(' ? ')' : ']'));
143           std::string::size_type EndDelimSearchStart =
144             StartDelimPos == std::string::npos ? 0 : StartDelimPos+1;
145           std::string::size_type EndDelimPos = Str.find(EndDelim,
146                                                         EndDelimSearchStart);
147           SearchStart = EndDelimPos;
148           if (EndDelimPos != std::string::npos) {
149             // Iterate.
150             SearchStart = EndDelimPos + 1;
151             --GroupLevel;
152             assert(GroupLevel > -2 && "Too many end delimeters!");
153           }
154           if (InGroup())
155             SpaceStartPos = std::string::npos;
156         }
157       } while (SearchStart != std::string::npos);
158
159
160       if (SpaceStartPos != std::string::npos) {
161         std::string::size_type SpaceEndPos = 
162           Str.find_first_not_of(" \t", SpaceStartPos+1);
163         if (SpaceStartPos != 0) {
164           // Emit the first part of the string.
165           AddLiteralString(Str.substr(0, SpaceStartPos));
166         }
167         Operands.push_back(
168           AsmWriterOperand(
169             "O.PadToColumn(TAI->getOperandColumn(OperandColumn++), 1);\n",
170             AsmWriterOperand::isLiteralStatementOperand));
171         if (SpaceEndPos != std::string::npos) {
172           // Emit the last part of the string.
173           AddLiteralString(Str.substr(SpaceEndPos));
174         }
175         // We've emitted the whole string.
176         return;
177       }
178       
179       if (!Operands.empty() &&
180           Operands.back().OperandType == AsmWriterOperand::isLiteralTextOperand)
181         Operands.back().Str.append(Str);
182       else
183         Operands.push_back(AsmWriterOperand(Str));
184     }
185   };
186 }
187
188
189 std::string AsmWriterOperand::getCode() const {
190   if (OperandType == isLiteralTextOperand)
191     return "O << \"" + Str + "\"; ";
192
193   if (OperandType == isLiteralStatementOperand) {
194     return Str;
195   }
196
197   if (OperandType == isLiteralStatementOperand) {
198     return Str;
199   }
200
201   if (OperandType == isLiteralStatementOperand) {
202     return Str;
203   }
204
205   std::string Result = Str + "(MI";
206   if (MIOpNo != ~0U)
207     Result += ", " + utostr(MIOpNo);
208   if (!MiModifier.empty())
209     Result += ", \"" + MiModifier + '"';
210   return Result + "); ";
211 }
212
213
214 /// ParseAsmString - Parse the specified Instruction's AsmString into this
215 /// AsmWriterInst.
216 ///
217 AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant)
218     : GroupLevel(-1) {
219   this->CGI = &CGI;
220   unsigned CurVariant = ~0U;  // ~0 if we are outside a {.|.|.} region, other #.
221
222   // NOTE: Any extensions to this code need to be mirrored in the 
223   // AsmPrinter::printInlineAsm code that executes as compile time (assuming
224   // that inline asm strings should also get the new feature)!
225   const std::string &AsmString = CGI.AsmString;
226   std::string::size_type LastEmitted = 0;
227   while (LastEmitted != AsmString.size()) {
228     std::string::size_type DollarPos =
229       AsmString.find_first_of("${|}\\", LastEmitted);
230     if (DollarPos == std::string::npos) DollarPos = AsmString.size();
231
232     // Emit a constant string fragment.
233     if (DollarPos != LastEmitted) {
234       if (CurVariant == Variant || CurVariant == ~0U) {
235         for (; LastEmitted != DollarPos; ++LastEmitted)
236           switch (AsmString[LastEmitted]) {
237           case '\n': AddLiteralString("\\n"); break;
238           case '\t': AddLiteralString("\\t"); break;
239           case '"': AddLiteralString("\\\""); break;
240           case '\\': AddLiteralString("\\\\"); break;
241           default:
242             AddLiteralString(std::string(1, AsmString[LastEmitted]));
243             break;
244           }
245       } else {
246         LastEmitted = DollarPos;
247       }
248     } else if (AsmString[DollarPos] == '\\') {
249       if (DollarPos+1 != AsmString.size() &&
250           (CurVariant == Variant || CurVariant == ~0U)) {
251         if (AsmString[DollarPos+1] == 'n') {
252           AddLiteralString("\\n");
253         } else if (AsmString[DollarPos+1] == 't') {
254           AddLiteralString("\\t");
255         } else if (std::string("${|}\\").find(AsmString[DollarPos+1]) 
256                    != std::string::npos) {
257           AddLiteralString(std::string(1, AsmString[DollarPos+1]));
258         } else {
259           throw "Non-supported escaped character found in instruction '" +
260             CGI.TheDef->getName() + "'!";
261         }
262         LastEmitted = DollarPos+2;
263         continue;
264       }
265     } else if (AsmString[DollarPos] == '{') {
266       if (CurVariant != ~0U)
267         throw "Nested variants found for instruction '" +
268               CGI.TheDef->getName() + "'!";
269       LastEmitted = DollarPos+1;
270       CurVariant = 0;   // We are now inside of the variant!
271     } else if (AsmString[DollarPos] == '|') {
272       if (CurVariant == ~0U)
273         throw "'|' character found outside of a variant in instruction '"
274           + CGI.TheDef->getName() + "'!";
275       ++CurVariant;
276       ++LastEmitted;
277     } else if (AsmString[DollarPos] == '}') {
278       if (CurVariant == ~0U)
279         throw "'}' character found outside of a variant in instruction '"
280           + CGI.TheDef->getName() + "'!";
281       ++LastEmitted;
282       CurVariant = ~0U;
283     } else if (DollarPos+1 != AsmString.size() &&
284                AsmString[DollarPos+1] == '$') {
285       if (CurVariant == Variant || CurVariant == ~0U) 
286         AddLiteralString("$");  // "$$" -> $
287       LastEmitted = DollarPos+2;
288     } else {
289       // Get the name of the variable.
290       std::string::size_type VarEnd = DollarPos+1;
291
292       // handle ${foo}bar as $foo by detecting whether the character following
293       // the dollar sign is a curly brace.  If so, advance VarEnd and DollarPos
294       // so the variable name does not contain the leading curly brace.
295       bool hasCurlyBraces = false;
296       if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {
297         hasCurlyBraces = true;
298         ++DollarPos;
299         ++VarEnd;
300       }
301
302       while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
303         ++VarEnd;
304       std::string VarName(AsmString.begin()+DollarPos+1,
305                           AsmString.begin()+VarEnd);
306
307       // Modifier - Support ${foo:modifier} syntax, where "modifier" is passed
308       // into printOperand.  Also support ${:feature}, which is passed into
309       // PrintSpecial.
310       std::string Modifier;
311       
312       // In order to avoid starting the next string at the terminating curly
313       // brace, advance the end position past it if we found an opening curly
314       // brace.
315       if (hasCurlyBraces) {
316         if (VarEnd >= AsmString.size())
317           throw "Reached end of string before terminating curly brace in '"
318                 + CGI.TheDef->getName() + "'";
319         
320         // Look for a modifier string.
321         if (AsmString[VarEnd] == ':') {
322           ++VarEnd;
323           if (VarEnd >= AsmString.size())
324             throw "Reached end of string before terminating curly brace in '"
325               + CGI.TheDef->getName() + "'";
326           
327           unsigned ModifierStart = VarEnd;
328           while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
329             ++VarEnd;
330           Modifier = std::string(AsmString.begin()+ModifierStart,
331                                  AsmString.begin()+VarEnd);
332           if (Modifier.empty())
333             throw "Bad operand modifier name in '"+ CGI.TheDef->getName() + "'";
334         }
335         
336         if (AsmString[VarEnd] != '}')
337           throw "Variable name beginning with '{' did not end with '}' in '"
338                 + CGI.TheDef->getName() + "'";
339         ++VarEnd;
340       }
341       if (VarName.empty() && Modifier.empty())
342         throw "Stray '$' in '" + CGI.TheDef->getName() +
343               "' asm string, maybe you want $$?";
344
345       if (VarName.empty()) {
346         // Just a modifier, pass this into PrintSpecial.
347         Operands.push_back(AsmWriterOperand("PrintSpecial", ~0U, Modifier));
348       } else {
349         // Otherwise, normal operand.
350         unsigned OpNo = CGI.getOperandNamed(VarName);
351         CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
352
353         if (CurVariant == Variant || CurVariant == ~0U) {
354           unsigned MIOp = OpInfo.MIOperandNo;
355           Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp,
356                                               Modifier));
357         }
358       }
359       LastEmitted = VarEnd;
360     }
361   }
362 }
363
364 /// MatchesAllButOneOp - If this instruction is exactly identical to the
365 /// specified instruction except for one differing operand, return the differing
366 /// operand number.  If more than one operand mismatches, return ~1, otherwise
367 /// if the instructions are identical return ~0.
368 unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
369   if (Operands.size() != Other.Operands.size()) return ~1;
370
371   unsigned MismatchOperand = ~0U;
372   for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
373     if (Operands[i] != Other.Operands[i]) {
374       if (MismatchOperand != ~0U)  // Already have one mismatch?
375         return ~1U;
376       else
377         MismatchOperand = i;
378     }
379   }
380   return MismatchOperand;
381 }
382
383 static void PrintCases(std::vector<std::pair<std::string,
384                        AsmWriterOperand> > &OpsToPrint, raw_ostream &O) {
385   O << "    case " << OpsToPrint.back().first << ": ";
386   AsmWriterOperand TheOp = OpsToPrint.back().second;
387   OpsToPrint.pop_back();
388
389   // Check to see if any other operands are identical in this list, and if so,
390   // emit a case label for them.
391   for (unsigned i = OpsToPrint.size(); i != 0; --i)
392     if (OpsToPrint[i-1].second == TheOp) {
393       O << "\n    case " << OpsToPrint[i-1].first << ": ";
394       OpsToPrint.erase(OpsToPrint.begin()+i-1);
395     }
396
397   // Finally, emit the code.
398   O << TheOp.getCode();
399   O << "break;\n";
400 }
401
402
403 /// EmitInstructions - Emit the last instruction in the vector and any other
404 /// instructions that are suitably similar to it.
405 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
406                              raw_ostream &O) {
407   AsmWriterInst FirstInst = Insts.back();
408   Insts.pop_back();
409
410   std::vector<AsmWriterInst> SimilarInsts;
411   unsigned DifferingOperand = ~0;
412   for (unsigned i = Insts.size(); i != 0; --i) {
413     unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
414     if (DiffOp != ~1U) {
415       if (DifferingOperand == ~0U)  // First match!
416         DifferingOperand = DiffOp;
417
418       // If this differs in the same operand as the rest of the instructions in
419       // this class, move it to the SimilarInsts list.
420       if (DifferingOperand == DiffOp || DiffOp == ~0U) {
421         SimilarInsts.push_back(Insts[i-1]);
422         Insts.erase(Insts.begin()+i-1);
423       }
424     }
425   }
426
427   O << "  case " << FirstInst.CGI->Namespace << "::"
428     << FirstInst.CGI->TheDef->getName() << ":\n";
429   for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
430     O << "  case " << SimilarInsts[i].CGI->Namespace << "::"
431       << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
432   for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
433     if (i != DifferingOperand) {
434       // If the operand is the same for all instructions, just print it.
435       O << "    " << FirstInst.Operands[i].getCode();
436     } else {
437       // If this is the operand that varies between all of the instructions,
438       // emit a switch for just this operand now.
439       O << "    switch (MI->getOpcode()) {\n";
440       std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
441       OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
442                                           FirstInst.CGI->TheDef->getName(),
443                                           FirstInst.Operands[i]));
444
445       for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
446         AsmWriterInst &AWI = SimilarInsts[si];
447         OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
448                                             AWI.CGI->TheDef->getName(),
449                                             AWI.Operands[i]));
450       }
451       std::reverse(OpsToPrint.begin(), OpsToPrint.end());
452       while (!OpsToPrint.empty())
453         PrintCases(OpsToPrint, O);
454       O << "    }";
455     }
456     O << "\n";
457   }
458   O << "    EmitComments(*MI);\n";
459   // Print the final newline
460   O << "    O << \"\\n\";\n";
461   O << "    break;\n";
462 }
463
464 void AsmWriterEmitter::
465 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands, 
466                           std::vector<unsigned> &InstIdxs,
467                           std::vector<unsigned> &InstOpsUsed) const {
468   InstIdxs.assign(NumberedInstructions.size(), ~0U);
469   
470   // This vector parallels UniqueOperandCommands, keeping track of which
471   // instructions each case are used for.  It is a comma separated string of
472   // enums.
473   std::vector<std::string> InstrsForCase;
474   InstrsForCase.resize(UniqueOperandCommands.size());
475   InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
476   
477   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
478     const AsmWriterInst *Inst = getAsmWriterInstByID(i);
479     if (Inst == 0) continue;  // PHI, INLINEASM, DBG_LABEL, etc.
480     
481     std::string Command;
482     if (Inst->Operands.empty())
483       continue;   // Instruction already done.
484
485     Command = "    " + Inst->Operands[0].getCode() + "\n";
486
487     // If this is the last operand, emit a return.
488     if (Inst->Operands.size() == 1) {
489       Command += "    EmitComments(*MI);\n";
490       // Print the final newline
491       Command += "    O << \"\\n\";\n";
492       Command += "    return true;\n";
493     }
494     
495     // Check to see if we already have 'Command' in UniqueOperandCommands.
496     // If not, add it.
497     bool FoundIt = false;
498     for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
499       if (UniqueOperandCommands[idx] == Command) {
500         InstIdxs[i] = idx;
501         InstrsForCase[idx] += ", ";
502         InstrsForCase[idx] += Inst->CGI->TheDef->getName();
503         FoundIt = true;
504         break;
505       }
506     if (!FoundIt) {
507       InstIdxs[i] = UniqueOperandCommands.size();
508       UniqueOperandCommands.push_back(Command);
509       InstrsForCase.push_back(Inst->CGI->TheDef->getName());
510
511       // This command matches one operand so far.
512       InstOpsUsed.push_back(1);
513     }
514   }
515   
516   // For each entry of UniqueOperandCommands, there is a set of instructions
517   // that uses it.  If the next command of all instructions in the set are
518   // identical, fold it into the command.
519   for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
520        CommandIdx != e; ++CommandIdx) {
521     
522     for (unsigned Op = 1; ; ++Op) {
523       // Scan for the first instruction in the set.
524       std::vector<unsigned>::iterator NIT =
525         std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
526       if (NIT == InstIdxs.end()) break;  // No commonality.
527
528       // If this instruction has no more operands, we isn't anything to merge
529       // into this command.
530       const AsmWriterInst *FirstInst = 
531         getAsmWriterInstByID(NIT-InstIdxs.begin());
532       if (!FirstInst || FirstInst->Operands.size() == Op)
533         break;
534
535       // Otherwise, scan to see if all of the other instructions in this command
536       // set share the operand.
537       bool AllSame = true;
538       
539       for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
540            NIT != InstIdxs.end();
541            NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
542         // Okay, found another instruction in this command set.  If the operand
543         // matches, we're ok, otherwise bail out.
544         const AsmWriterInst *OtherInst = 
545           getAsmWriterInstByID(NIT-InstIdxs.begin());
546         if (!OtherInst || OtherInst->Operands.size() == Op ||
547             OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
548           AllSame = false;
549           break;
550         }
551       }
552       if (!AllSame) break;
553       
554       // Okay, everything in this command set has the same next operand.  Add it
555       // to UniqueOperandCommands and remember that it was consumed.
556       std::string Command = "    " + FirstInst->Operands[Op].getCode() + "\n";
557       
558       // If this is the last operand, emit a return after the code.
559       if (FirstInst->Operands.size() == Op+1) {
560         Command += "    EmitComments(*MI);\n";
561         // Print the final newline
562         Command += "    O << \"\\n\";\n";
563         Command += "    return true;\n";
564       }
565       
566       UniqueOperandCommands[CommandIdx] += Command;
567       InstOpsUsed[CommandIdx]++;
568     }
569   }
570   
571   // Prepend some of the instructions each case is used for onto the case val.
572   for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
573     std::string Instrs = InstrsForCase[i];
574     if (Instrs.size() > 70) {
575       Instrs.erase(Instrs.begin()+70, Instrs.end());
576       Instrs += "...";
577     }
578     
579     if (!Instrs.empty())
580       UniqueOperandCommands[i] = "    // " + Instrs + "\n" + 
581         UniqueOperandCommands[i];
582   }
583 }
584
585
586
587 void AsmWriterEmitter::run(raw_ostream &O) {
588   EmitSourceFileHeader("Assembly Writer Source Fragment", O);
589
590   CodeGenTarget Target;
591   Record *AsmWriter = Target.getAsmWriter();
592   std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
593   unsigned Variant = AsmWriter->getValueAsInt("Variant");
594
595   O <<
596   "/// printInstruction - This method is automatically generated by tablegen\n"
597   "/// from the instruction set description.  This method returns true if the\n"
598   "/// machine instruction was sufficiently described to print it, otherwise\n"
599   "/// it returns false.\n"
600     "bool " << Target.getName() << ClassName
601             << "::printInstruction(const MachineInstr *MI) {\n";
602
603   std::vector<AsmWriterInst> Instructions;
604
605   for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
606          E = Target.inst_end(); I != E; ++I)
607     if (!I->second.AsmString.empty())
608       Instructions.push_back(AsmWriterInst(I->second, Variant));
609
610   // Get the instruction numbering.
611   Target.getInstructionsByEnumValue(NumberedInstructions);
612   
613   // Compute the CodeGenInstruction -> AsmWriterInst mapping.  Note that not
614   // all machine instructions are necessarily being printed, so there may be
615   // target instructions not in this map.
616   for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
617     CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
618
619   // Build an aggregate string, and build a table of offsets into it.
620   std::map<std::string, unsigned> StringOffset;
621   std::string AggregateString;
622   AggregateString.push_back(0);  // "\0"
623   AggregateString.push_back(0);  // "\0"
624   
625   /// OpcodeInfo - This encodes the index of the string to use for the first
626   /// chunk of the output as well as indices used for operand printing.
627   std::vector<unsigned> OpcodeInfo;
628   
629   unsigned MaxStringIdx = 0;
630   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
631     AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
632     unsigned Idx;
633     if (AWI == 0) {
634       // Something not handled by the asmwriter printer.
635       Idx = 0;
636     } else if (AWI->Operands[0].OperandType != 
637                         AsmWriterOperand::isLiteralTextOperand ||
638                AWI->Operands[0].Str.empty()) {
639       // Something handled by the asmwriter printer, but with no leading string.
640       Idx = 1;
641     } else {
642       unsigned &Entry = StringOffset[AWI->Operands[0].Str];
643       if (Entry == 0) {
644         // Add the string to the aggregate if this is the first time found.
645         MaxStringIdx = Entry = AggregateString.size();
646         std::string Str = AWI->Operands[0].Str;
647         UnescapeString(Str);
648         AggregateString += Str;
649         AggregateString += '\0';
650       }
651       Idx = Entry;
652
653       // Nuke the string from the operand list.  It is now handled!
654       AWI->Operands.erase(AWI->Operands.begin());
655     }
656     OpcodeInfo.push_back(Idx);
657   }
658   
659   // Figure out how many bits we used for the string index.
660   unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+1);
661   
662   // To reduce code size, we compactify common instructions into a few bits
663   // in the opcode-indexed table.
664   unsigned BitsLeft = 32-AsmStrBits;
665
666   std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
667   
668   bool isFirst = true;
669   while (1) {
670     std::vector<std::string> UniqueOperandCommands;
671
672     // For the first operand check, add a default value for instructions with
673     // just opcode strings to use.
674     if (isFirst) {
675       // Do the post instruction processing and print the final newline
676       UniqueOperandCommands.push_back("    EmitComments(*MI);\n    O << \"\\n\";\n    return true;\n");
677       isFirst = false;
678     }
679
680     std::vector<unsigned> InstIdxs;
681     std::vector<unsigned> NumInstOpsHandled;
682     FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
683                               NumInstOpsHandled);
684     
685     // If we ran out of operands to print, we're done.
686     if (UniqueOperandCommands.empty()) break;
687     
688     // Compute the number of bits we need to represent these cases, this is
689     // ceil(log2(numentries)).
690     unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
691     
692     // If we don't have enough bits for this operand, don't include it.
693     if (NumBits > BitsLeft) {
694       DOUT << "Not enough bits to densely encode " << NumBits
695            << " more bits\n";
696       break;
697     }
698     
699     // Otherwise, we can include this in the initial lookup table.  Add it in.
700     BitsLeft -= NumBits;
701     for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
702       if (InstIdxs[i] != ~0U)
703         OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
704     
705     // Remove the info about this operand.
706     for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
707       if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
708         if (!Inst->Operands.empty()) {
709           unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
710           assert(NumOps <= Inst->Operands.size() &&
711                  "Can't remove this many ops!");
712           Inst->Operands.erase(Inst->Operands.begin(),
713                                Inst->Operands.begin()+NumOps);
714         }
715     }
716     
717     // Remember the handlers for this set of operands.
718     TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
719   }
720   
721   
722   
723   O<<"  static const unsigned OpInfo[] = {\n";
724   for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
725     O << "    " << OpcodeInfo[i] << "U,\t// "
726       << NumberedInstructions[i]->TheDef->getName() << "\n";
727   }
728   // Add a dummy entry so the array init doesn't end with a comma.
729   O << "    0U\n";
730   O << "  };\n\n";
731   
732   // Emit the string itself.
733   O << "  const char *AsmStrs = \n    \"";
734   unsigned CharsPrinted = 0;
735   EscapeString(AggregateString);
736   for (unsigned i = 0, e = AggregateString.size(); i != e; ++i) {
737     if (CharsPrinted > 70) {
738       O << "\"\n    \"";
739       CharsPrinted = 0;
740     }
741     O << AggregateString[i];
742     ++CharsPrinted;
743     
744     // Print escape sequences all together.
745     if (AggregateString[i] == '\\') {
746       assert(i+1 < AggregateString.size() && "Incomplete escape sequence!");
747       if (isdigit(AggregateString[i+1])) {
748         assert(isdigit(AggregateString[i+2]) && isdigit(AggregateString[i+3]) &&
749                "Expected 3 digit octal escape!");
750         O << AggregateString[++i];
751         O << AggregateString[++i];
752         O << AggregateString[++i];
753         CharsPrinted += 3;
754       } else {
755         O << AggregateString[++i];
756         ++CharsPrinted;
757       }
758     }
759   }
760   O << "\";\n\n";
761
762   O << "  processDebugLoc(MI->getDebugLoc());\n\n";
763
764   O << "\n#ifndef NO_ASM_WRITER_BOILERPLATE\n";
765   
766   O << "  if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {\n"
767     << "    O << \"\\t\";\n"
768     << "    printInlineAsm(MI);\n"
769     << "    return true;\n"
770     << "  } else if (MI->isLabel()) {\n"
771     << "    printLabel(MI);\n"
772     << "    return true;\n"
773     << "  } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {\n"
774     << "    printDeclare(MI);\n"
775     << "    return true;\n"
776     << "  } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {\n"
777     << "    printImplicitDef(MI);\n"
778     << "    return true;\n"
779     << "  }\n\n";
780
781   O << "\n#endif\n";
782
783   O << "  O << \"\\t\";\n\n";
784
785   O << "  // Emit the opcode for the instruction.\n"
786     << "  unsigned Bits = OpInfo[MI->getOpcode()];\n"
787     << "  if (Bits == 0) return false;\n\n";
788
789   O << "  std::string OpStr(AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << "));\n"
790     << "  unsigned OperandColumn = 1;\n"
791     << "  O << OpStr;\n\n";
792
793   O << "  if (OpStr.find_last_of(\" \\t\") == OpStr.size()-1) {\n"
794     << "    O.PadToColumn(TAI->getOperandColumn(1));\n"
795     << "    OperandColumn = 2;\n"
796     << "  }\n\n";
797
798   // Output the table driven operand information.
799   BitsLeft = 32-AsmStrBits;
800   for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
801     std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
802
803     // Compute the number of bits we need to represent these cases, this is
804     // ceil(log2(numentries)).
805     unsigned NumBits = Log2_32_Ceil(Commands.size());
806     assert(NumBits <= BitsLeft && "consistency error");
807     
808     // Emit code to extract this field from Bits.
809     BitsLeft -= NumBits;
810     
811     O << "\n  // Fragment " << i << " encoded into " << NumBits
812       << " bits for " << Commands.size() << " unique commands.\n";
813     
814     if (Commands.size() == 2) {
815       // Emit two possibilitys with if/else.
816       O << "  if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
817         << ((1 << NumBits)-1) << ") {\n"
818         << Commands[1]
819         << "  } else {\n"
820         << Commands[0]
821         << "  }\n\n";
822     } else {
823       O << "  switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
824         << ((1 << NumBits)-1) << ") {\n"
825         << "  default:   // unreachable.\n";
826       
827       // Print out all the cases.
828       for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
829         O << "  case " << i << ":\n";
830         O << Commands[i];
831         O << "    break;\n";
832       }
833       O << "  }\n\n";
834     }
835   }
836   
837   // Okay, delete instructions with no operand info left.
838   for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
839     // Entire instruction has been emitted?
840     AsmWriterInst &Inst = Instructions[i];
841     if (Inst.Operands.empty()) {
842       Instructions.erase(Instructions.begin()+i);
843       --i; --e;
844     }
845   }
846
847     
848   // Because this is a vector, we want to emit from the end.  Reverse all of the
849   // elements in the vector.
850   std::reverse(Instructions.begin(), Instructions.end());
851   
852   if (!Instructions.empty()) {
853     // Find the opcode # of inline asm.
854     O << "  switch (MI->getOpcode()) {\n";
855     while (!Instructions.empty())
856       EmitInstructions(Instructions, O);
857
858     O << "  }\n";
859     O << "  EmitComments(*MI);\n";
860   }
861   // Print the final newline
862   O << "  O << \"\\n\";\n";
863   O << "  return true;\n";
864   
865   O << "}\n";
866 }