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