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