1 //===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #include "AsmWriterEmitter.h"
16 #include "CodeGenTarget.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/MathExtras.h"
26 static bool isIdentChar(char C) {
27 return (C >= 'a' && C <= 'z') ||
28 (C >= 'A' && C <= 'Z') ||
29 (C >= '0' && C <= '9') ||
33 // This should be an anon namespace, this works around a GCC warning.
35 struct AsmWriterOperand {
38 isMachineInstrOperand,
39 isLiteralStatementOperand
42 /// Str - For isLiteralTextOperand, this IS the literal text. For
43 /// isMachineInstrOperand, this is the PrinterMethodName for the operand.
46 /// MiOpNo - For isMachineInstrOperand, this is the operand number of the
47 /// machine instruction.
50 /// MiModifier - For isMachineInstrOperand, this is the modifier string for
51 /// an operand, specified with syntax like ${opname:modifier}.
52 std::string MiModifier;
54 // To make VS STL happy
55 AsmWriterOperand(OpType op = isLiteralTextOperand):OperandType(op) {}
57 AsmWriterOperand(const std::string &LitStr,
58 OpType op = isLiteralTextOperand)
59 : OperandType(op), Str(LitStr) {}
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) {}
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;
73 bool operator==(const AsmWriterOperand &Other) const {
74 return !operator!=(Other);
77 /// getCode - Return the code that prints this operand.
78 std::string getCode() const;
85 std::vector<AsmWriterOperand> Operands;
86 const CodeGenInstruction *CGI;
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;
92 /// GroupLevel - The level of nesting of the current operand
93 /// group, such as [reg + (reg + offset)]. -1 means we are not in
97 /// GroupDelim - Remember the delimeter for a group operand.
98 char GroupDelim[MAX_GROUP_NESTING_LEVEL];
100 /// InGroup - Determine whether we are in the middle of an
102 bool InGroup() const { return GroupLevel != -1; }
104 AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
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;
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.
116 std::string::size_type SearchStart = 0;
117 std::string::size_type SpaceStartPos = std::string::npos;
119 // Search for whitespace and replace with calls to set the
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);
125 SearchStart = std::string::npos;
127 if (StartDelimPos != std::string::npos) {
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;
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) {
150 SearchStart = EndDelimPos + 1;
152 assert(GroupLevel > -2 && "Too many end delimeters!");
155 SpaceStartPos = std::string::npos;
157 } while (SearchStart != std::string::npos);
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));
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));
175 // We've emitted the whole string.
179 if (!Operands.empty() &&
180 Operands.back().OperandType == AsmWriterOperand::isLiteralTextOperand)
181 Operands.back().Str.append(Str);
183 Operands.push_back(AsmWriterOperand(Str));
189 std::string AsmWriterOperand::getCode() const {
190 if (OperandType == isLiteralTextOperand)
191 return "O << \"" + Str + "\"; ";
193 if (OperandType == isLiteralStatementOperand) {
197 if (OperandType == isLiteralStatementOperand) {
201 if (OperandType == isLiteralStatementOperand) {
205 std::string Result = Str + "(MI";
207 Result += ", " + utostr(MIOpNo);
208 if (!MiModifier.empty())
209 Result += ", \"" + MiModifier + '"';
210 return Result + "); ";
214 /// ParseAsmString - Parse the specified Instruction's AsmString into this
217 AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant)
220 unsigned CurVariant = ~0U; // ~0 if we are outside a {.|.|.} region, other #.
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();
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;
242 AddLiteralString(std::string(1, AsmString[LastEmitted]));
246 LastEmitted = DollarPos;
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]));
259 throw "Non-supported escaped character found in instruction '" +
260 CGI.TheDef->getName() + "'!";
262 LastEmitted = DollarPos+2;
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() + "'!";
277 } else if (AsmString[DollarPos] == '}') {
278 if (CurVariant == ~0U)
279 throw "'}' character found outside of a variant in instruction '"
280 + CGI.TheDef->getName() + "'!";
283 } else if (DollarPos+1 != AsmString.size() &&
284 AsmString[DollarPos+1] == '$') {
285 if (CurVariant == Variant || CurVariant == ~0U)
286 AddLiteralString("$"); // "$$" -> $
287 LastEmitted = DollarPos+2;
289 // Get the name of the variable.
290 std::string::size_type VarEnd = DollarPos+1;
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;
302 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
304 std::string VarName(AsmString.begin()+DollarPos+1,
305 AsmString.begin()+VarEnd);
307 // Modifier - Support ${foo:modifier} syntax, where "modifier" is passed
308 // into printOperand. Also support ${:feature}, which is passed into
310 std::string Modifier;
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
315 if (hasCurlyBraces) {
316 if (VarEnd >= AsmString.size())
317 throw "Reached end of string before terminating curly brace in '"
318 + CGI.TheDef->getName() + "'";
320 // Look for a modifier string.
321 if (AsmString[VarEnd] == ':') {
323 if (VarEnd >= AsmString.size())
324 throw "Reached end of string before terminating curly brace in '"
325 + CGI.TheDef->getName() + "'";
327 unsigned ModifierStart = VarEnd;
328 while (VarEnd < AsmString.size() && isIdentChar(AsmString[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() + "'";
336 if (AsmString[VarEnd] != '}')
337 throw "Variable name beginning with '{' did not end with '}' in '"
338 + CGI.TheDef->getName() + "'";
341 if (VarName.empty() && Modifier.empty())
342 throw "Stray '$' in '" + CGI.TheDef->getName() +
343 "' asm string, maybe you want $$?";
345 if (VarName.empty()) {
346 // Just a modifier, pass this into PrintSpecial.
347 Operands.push_back(AsmWriterOperand("PrintSpecial", ~0U, Modifier));
349 // Otherwise, normal operand.
350 unsigned OpNo = CGI.getOperandNamed(VarName);
351 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
353 if (CurVariant == Variant || CurVariant == ~0U) {
354 unsigned MIOp = OpInfo.MIOperandNo;
355 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp,
359 LastEmitted = VarEnd;
364 AsmWriterOperand("EmitComments(*MI);\n",
365 AsmWriterOperand::isLiteralStatementOperand));
366 AddLiteralString("\\n");
369 /// MatchesAllButOneOp - If this instruction is exactly identical to the
370 /// specified instruction except for one differing operand, return the differing
371 /// operand number. If more than one operand mismatches, return ~1, otherwise
372 /// if the instructions are identical return ~0.
373 unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
374 if (Operands.size() != Other.Operands.size()) return ~1;
376 unsigned MismatchOperand = ~0U;
377 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
378 if (Operands[i] != Other.Operands[i]) {
379 if (MismatchOperand != ~0U) // Already have one mismatch?
385 return MismatchOperand;
388 static void PrintCases(std::vector<std::pair<std::string,
389 AsmWriterOperand> > &OpsToPrint, raw_ostream &O) {
390 O << " case " << OpsToPrint.back().first << ": ";
391 AsmWriterOperand TheOp = OpsToPrint.back().second;
392 OpsToPrint.pop_back();
394 // Check to see if any other operands are identical in this list, and if so,
395 // emit a case label for them.
396 for (unsigned i = OpsToPrint.size(); i != 0; --i)
397 if (OpsToPrint[i-1].second == TheOp) {
398 O << "\n case " << OpsToPrint[i-1].first << ": ";
399 OpsToPrint.erase(OpsToPrint.begin()+i-1);
402 // Finally, emit the code.
403 O << TheOp.getCode();
408 /// EmitInstructions - Emit the last instruction in the vector and any other
409 /// instructions that are suitably similar to it.
410 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
412 AsmWriterInst FirstInst = Insts.back();
415 std::vector<AsmWriterInst> SimilarInsts;
416 unsigned DifferingOperand = ~0;
417 for (unsigned i = Insts.size(); i != 0; --i) {
418 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
420 if (DifferingOperand == ~0U) // First match!
421 DifferingOperand = DiffOp;
423 // If this differs in the same operand as the rest of the instructions in
424 // this class, move it to the SimilarInsts list.
425 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
426 SimilarInsts.push_back(Insts[i-1]);
427 Insts.erase(Insts.begin()+i-1);
432 O << " case " << FirstInst.CGI->Namespace << "::"
433 << FirstInst.CGI->TheDef->getName() << ":\n";
434 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
435 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
436 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
437 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
438 if (i != DifferingOperand) {
439 // If the operand is the same for all instructions, just print it.
440 O << " " << FirstInst.Operands[i].getCode();
442 // If this is the operand that varies between all of the instructions,
443 // emit a switch for just this operand now.
444 O << " switch (MI->getOpcode()) {\n";
445 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
446 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
447 FirstInst.CGI->TheDef->getName(),
448 FirstInst.Operands[i]));
450 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
451 AsmWriterInst &AWI = SimilarInsts[si];
452 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
453 AWI.CGI->TheDef->getName(),
456 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
457 while (!OpsToPrint.empty())
458 PrintCases(OpsToPrint, O);
466 void AsmWriterEmitter::
467 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
468 std::vector<unsigned> &InstIdxs,
469 std::vector<unsigned> &InstOpsUsed) const {
470 InstIdxs.assign(NumberedInstructions.size(), ~0U);
472 // This vector parallels UniqueOperandCommands, keeping track of which
473 // instructions each case are used for. It is a comma separated string of
475 std::vector<std::string> InstrsForCase;
476 InstrsForCase.resize(UniqueOperandCommands.size());
477 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
479 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
480 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
481 if (Inst == 0) continue; // PHI, INLINEASM, DBG_LABEL, etc.
484 if (Inst->Operands.empty())
485 continue; // Instruction already done.
487 Command = " " + Inst->Operands[0].getCode() + "\n";
489 // If this is the last operand, emit a return.
490 if (Inst->Operands.size() == 1) {
491 Command += " return true;\n";
494 // Check to see if we already have 'Command' in UniqueOperandCommands.
496 bool FoundIt = false;
497 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
498 if (UniqueOperandCommands[idx] == Command) {
500 InstrsForCase[idx] += ", ";
501 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
506 InstIdxs[i] = UniqueOperandCommands.size();
507 UniqueOperandCommands.push_back(Command);
508 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
510 // This command matches one operand so far.
511 InstOpsUsed.push_back(1);
515 // For each entry of UniqueOperandCommands, there is a set of instructions
516 // that uses it. If the next command of all instructions in the set are
517 // identical, fold it into the command.
518 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
519 CommandIdx != e; ++CommandIdx) {
521 for (unsigned Op = 1; ; ++Op) {
522 // Scan for the first instruction in the set.
523 std::vector<unsigned>::iterator NIT =
524 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
525 if (NIT == InstIdxs.end()) break; // No commonality.
527 // If this instruction has no more operands, we isn't anything to merge
528 // into this command.
529 const AsmWriterInst *FirstInst =
530 getAsmWriterInstByID(NIT-InstIdxs.begin());
531 if (!FirstInst || FirstInst->Operands.size() == Op)
534 // Otherwise, scan to see if all of the other instructions in this command
535 // set share the operand.
537 // Keep track of the maximum, number of operands or any
538 // instruction we see in the group.
539 size_t MaxSize = FirstInst->Operands.size();
541 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
542 NIT != InstIdxs.end();
543 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
544 // Okay, found another instruction in this command set. If the operand
545 // matches, we're ok, otherwise bail out.
546 const AsmWriterInst *OtherInst =
547 getAsmWriterInstByID(NIT-InstIdxs.begin());
550 OtherInst->Operands.size() > FirstInst->Operands.size())
551 MaxSize = std::max(MaxSize, OtherInst->Operands.size());
553 if (!OtherInst || OtherInst->Operands.size() == Op ||
554 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
561 // Okay, everything in this command set has the same next operand. Add it
562 // to UniqueOperandCommands and remember that it was consumed.
563 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
565 // If this is the last operand, emit a return after the code.
566 if (FirstInst->Operands.size() == Op+1 &&
567 // Don't early-out too soon. Other instructions in this
568 // group may have more operands.
569 FirstInst->Operands.size() == MaxSize) {
570 Command += " return true;\n";
573 UniqueOperandCommands[CommandIdx] += Command;
574 InstOpsUsed[CommandIdx]++;
578 // Prepend some of the instructions each case is used for onto the case val.
579 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
580 std::string Instrs = InstrsForCase[i];
581 if (Instrs.size() > 70) {
582 Instrs.erase(Instrs.begin()+70, Instrs.end());
587 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
588 UniqueOperandCommands[i];
594 void AsmWriterEmitter::run(raw_ostream &O) {
595 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
597 CodeGenTarget Target;
598 Record *AsmWriter = Target.getAsmWriter();
599 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
600 unsigned Variant = AsmWriter->getValueAsInt("Variant");
603 "/// printInstruction - This method is automatically generated by tablegen\n"
604 "/// from the instruction set description. This method returns true if the\n"
605 "/// machine instruction was sufficiently described to print it, otherwise\n"
606 "/// it returns false.\n"
607 "bool " << Target.getName() << ClassName
608 << "::printInstruction(const MachineInstr *MI) {\n";
610 std::vector<AsmWriterInst> Instructions;
612 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
613 E = Target.inst_end(); I != E; ++I)
614 if (!I->second.AsmString.empty())
615 Instructions.push_back(AsmWriterInst(I->second, Variant));
617 // Get the instruction numbering.
618 Target.getInstructionsByEnumValue(NumberedInstructions);
620 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
621 // all machine instructions are necessarily being printed, so there may be
622 // target instructions not in this map.
623 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
624 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
626 // Build an aggregate string, and build a table of offsets into it.
627 std::map<std::string, unsigned> StringOffset;
628 std::string AggregateString;
629 AggregateString.push_back(0); // "\0"
630 AggregateString.push_back(0); // "\0"
632 /// OpcodeInfo - This encodes the index of the string to use for the first
633 /// chunk of the output as well as indices used for operand printing.
634 std::vector<unsigned> OpcodeInfo;
636 unsigned MaxStringIdx = 0;
637 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
638 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
641 // Something not handled by the asmwriter printer.
643 } else if (AWI->Operands[0].OperandType !=
644 AsmWriterOperand::isLiteralTextOperand ||
645 AWI->Operands[0].Str.empty()) {
646 // Something handled by the asmwriter printer, but with no leading string.
649 unsigned &Entry = StringOffset[AWI->Operands[0].Str];
651 // Add the string to the aggregate if this is the first time found.
652 MaxStringIdx = Entry = AggregateString.size();
653 std::string Str = AWI->Operands[0].Str;
655 AggregateString += Str;
656 AggregateString += '\0';
660 // Nuke the string from the operand list. It is now handled!
661 AWI->Operands.erase(AWI->Operands.begin());
663 OpcodeInfo.push_back(Idx);
666 // Figure out how many bits we used for the string index.
667 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+1);
669 // To reduce code size, we compactify common instructions into a few bits
670 // in the opcode-indexed table.
671 unsigned BitsLeft = 32-AsmStrBits;
673 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
677 std::vector<std::string> UniqueOperandCommands;
679 // For the first operand check, add a default value for instructions with
680 // just opcode strings to use.
682 UniqueOperandCommands.push_back(" return true;\n");
686 std::vector<unsigned> InstIdxs;
687 std::vector<unsigned> NumInstOpsHandled;
688 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
691 // If we ran out of operands to print, we're done.
692 if (UniqueOperandCommands.empty()) break;
694 // Compute the number of bits we need to represent these cases, this is
695 // ceil(log2(numentries)).
696 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
698 // If we don't have enough bits for this operand, don't include it.
699 if (NumBits > BitsLeft) {
700 DOUT << "Not enough bits to densely encode " << NumBits
705 // Otherwise, we can include this in the initial lookup table. Add it in.
707 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
708 if (InstIdxs[i] != ~0U)
709 OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
711 // Remove the info about this operand.
712 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
713 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
714 if (!Inst->Operands.empty()) {
715 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
716 assert(NumOps <= Inst->Operands.size() &&
717 "Can't remove this many ops!");
718 Inst->Operands.erase(Inst->Operands.begin(),
719 Inst->Operands.begin()+NumOps);
723 // Remember the handlers for this set of operands.
724 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
729 O<<" static const unsigned OpInfo[] = {\n";
730 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
731 O << " " << OpcodeInfo[i] << "U,\t// "
732 << NumberedInstructions[i]->TheDef->getName() << "\n";
734 // Add a dummy entry so the array init doesn't end with a comma.
738 // Emit the string itself.
739 O << " const char *AsmStrs = \n \"";
740 unsigned CharsPrinted = 0;
741 EscapeString(AggregateString);
742 for (unsigned i = 0, e = AggregateString.size(); i != e; ++i) {
743 if (CharsPrinted > 70) {
747 O << AggregateString[i];
750 // Print escape sequences all together.
751 if (AggregateString[i] == '\\') {
752 assert(i+1 < AggregateString.size() && "Incomplete escape sequence!");
753 if (isdigit(AggregateString[i+1])) {
754 assert(isdigit(AggregateString[i+2]) && isdigit(AggregateString[i+3]) &&
755 "Expected 3 digit octal escape!");
756 O << AggregateString[++i];
757 O << AggregateString[++i];
758 O << AggregateString[++i];
761 O << AggregateString[++i];
768 O << " processDebugLoc(MI->getDebugLoc());\n\n";
770 O << "\n#ifndef NO_ASM_WRITER_BOILERPLATE\n";
772 O << " if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {\n"
773 << " O << \"\\t\";\n"
774 << " printInlineAsm(MI);\n"
776 << " } else if (MI->isLabel()) {\n"
777 << " printLabel(MI);\n"
779 << " } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {\n"
780 << " printDeclare(MI);\n"
782 << " } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {\n"
783 << " printImplicitDef(MI);\n"
789 O << " O << \"\\t\";\n\n";
791 O << " // Emit the opcode for the instruction.\n"
792 << " unsigned Bits = OpInfo[MI->getOpcode()];\n"
793 << " if (Bits == 0) return false;\n\n";
795 O << " std::string OpStr(AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << "));\n"
796 << " unsigned OperandColumn = 1;\n"
797 << " O << OpStr;\n\n";
799 O << " if (OpStr.find_last_of(\" \\t\") == OpStr.size()-1) {\n"
800 << " O.PadToColumn(TAI->getOperandColumn(1));\n"
801 << " OperandColumn = 2;\n"
804 // Output the table driven operand information.
805 BitsLeft = 32-AsmStrBits;
806 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
807 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
809 // Compute the number of bits we need to represent these cases, this is
810 // ceil(log2(numentries)).
811 unsigned NumBits = Log2_32_Ceil(Commands.size());
812 assert(NumBits <= BitsLeft && "consistency error");
814 // Emit code to extract this field from Bits.
817 O << "\n // Fragment " << i << " encoded into " << NumBits
818 << " bits for " << Commands.size() << " unique commands.\n";
820 if (Commands.size() == 2) {
821 // Emit two possibilitys with if/else.
822 O << " if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
823 << ((1 << NumBits)-1) << ") {\n"
829 O << " switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
830 << ((1 << NumBits)-1) << ") {\n"
831 << " default: // unreachable.\n";
833 // Print out all the cases.
834 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
835 O << " case " << i << ":\n";
843 // Okay, delete instructions with no operand info left.
844 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
845 // Entire instruction has been emitted?
846 AsmWriterInst &Inst = Instructions[i];
847 if (Inst.Operands.empty()) {
848 Instructions.erase(Instructions.begin()+i);
854 // Because this is a vector, we want to emit from the end. Reverse all of the
855 // elements in the vector.
856 std::reverse(Instructions.begin(), Instructions.end());
858 if (!Instructions.empty()) {
859 // Find the opcode # of inline asm.
860 O << " switch (MI->getOpcode()) {\n";
861 while (!Instructions.empty())
862 EmitInstructions(Instructions, O);
865 O << " return true;\n";
868 O << " return true;\n";