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 /// ReadingWhitespace - Tell whether we just read some whitespace.
101 bool ReadingWhitespace;
103 /// InGroup - Determine whether we are in the middle of an
105 bool InGroup() const { return GroupLevel != -1; }
107 /// InWhitespace - Determine whether we are in the middle of
108 /// emitting whitespace.
109 bool InWhitespace() const { return ReadingWhitespace; }
111 AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
113 /// MatchesAllButOneOp - If this instruction is exactly identical to the
114 /// specified instruction except for one differing operand, return the
115 /// differing operand number. Otherwise return ~0.
116 unsigned MatchesAllButOneOp(const AsmWriterInst &Other) const;
119 void AddLiteralString(const std::string &Str) {
120 // If the last operand was already a literal text string, append this to
121 // it, otherwise add a new operand.
122 if (!Operands.empty() &&
123 Operands.back().OperandType == AsmWriterOperand::isLiteralTextOperand)
124 Operands.back().Str.append(Str);
126 Operands.push_back(AsmWriterOperand(Str));
132 std::string AsmWriterOperand::getCode() const {
133 if (OperandType == isLiteralTextOperand)
134 return "O << \"" + Str + "\"; ";
136 if (OperandType == isLiteralStatementOperand) {
140 if (OperandType == isLiteralStatementOperand) {
144 if (OperandType == isLiteralStatementOperand) {
148 std::string Result = Str + "(MI";
150 Result += ", " + utostr(MIOpNo);
151 if (!MiModifier.empty())
152 Result += ", \"" + MiModifier + '"';
153 return Result + "); ";
157 /// ParseAsmString - Parse the specified Instruction's AsmString into this
160 AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant)
161 : GroupLevel(-1), ReadingWhitespace(false) {
163 unsigned CurVariant = ~0U; // ~0 if we are outside a {.|.|.} region, other #.
165 // NOTE: Any extensions to this code need to be mirrored in the
166 // AsmPrinter::printInlineAsm code that executes as compile time (assuming
167 // that inline asm strings should also get the new feature)!
168 const std::string &AsmString = CGI.AsmString;
169 std::string::size_type LastEmitted = 0;
170 while (LastEmitted != AsmString.size()) {
171 std::string::size_type DollarPos =
172 AsmString.find_first_of("${|}\\", LastEmitted);
173 if (DollarPos == std::string::npos) DollarPos = AsmString.size();
175 // Emit a constant string fragment.
177 // TODO: Recognize an operand separator to determine when to pad
178 // to the next operator.
179 if (DollarPos != LastEmitted) {
180 if (CurVariant == Variant || CurVariant == ~0U) {
181 for (; LastEmitted != DollarPos; ++LastEmitted)
182 switch (AsmString[LastEmitted]) {
184 assert(!InGroup() && "Missing matching group delimeter");
185 ReadingWhitespace = false;
186 AddLiteralString("\\n");
190 ReadingWhitespace = true;
192 AddLiteralString("\\t");
195 if (InWhitespace() && !InGroup())
198 "O.PadToColumn(TAI->getOperandColumn(OperandColumn++));\n",
199 AsmWriterOperand::isLiteralStatementOperand));
200 ReadingWhitespace = false;
201 AddLiteralString("\\\"");
204 if (InWhitespace() && !InGroup())
207 "O.PadToColumn(TAI->getOperandColumn(OperandColumn++));\n",
208 AsmWriterOperand::isLiteralStatementOperand));
209 ReadingWhitespace = false;
210 AddLiteralString("\\\\");
213 case '(': // Fallthrough
215 if (InWhitespace() && !InGroup())
218 "O.PadToColumn(TAI->getOperandColumn(OperandColumn++));\n",
219 AsmWriterOperand::isLiteralStatementOperand));
220 ReadingWhitespace = false;
223 assert(GroupLevel < MAX_GROUP_NESTING_LEVEL
224 && "Exceeded maximum operand group nesting level");
225 GroupDelim[GroupLevel] = AsmString[LastEmitted];
226 AddLiteralString(std::string(1, AsmString[LastEmitted]));
229 case ')': // Fallthrough
231 if (InWhitespace() && !InGroup())
234 "O.PadToColumn(TAI->getOperandColumn(OperandColumn++));\n",
235 AsmWriterOperand::isLiteralStatementOperand));
236 ReadingWhitespace = false;
238 if (AsmString[LastEmitted] == ')')
239 assert(GroupDelim[GroupLevel] == '(' && "Mismatched delimeters");
241 assert(GroupDelim[GroupLevel] == '[' && "Mismatched delimeters");
244 assert(GroupLevel > -2 && "Too many end delimeters!");
245 AddLiteralString(std::string(1, AsmString[LastEmitted]));
249 if (AsmString[LastEmitted] != ' ' &&
250 AsmString[LastEmitted] != '\t') {
251 if (!InGroup() && InWhitespace())
254 "O.PadToColumn(TAI->getOperandColumn(OperandColumn++));\n",
255 AsmWriterOperand::isLiteralStatementOperand));
256 ReadingWhitespace = false;
260 ReadingWhitespace = true;
262 AddLiteralString(std::string(1, AsmString[LastEmitted]));
266 LastEmitted = DollarPos;
268 } else if (AsmString[DollarPos] == '\\') {
269 if (DollarPos+1 != AsmString.size() &&
270 (CurVariant == Variant || CurVariant == ~0U)) {
271 if (AsmString[DollarPos+1] == 'n') {
272 assert(!InGroup() && "Missing matching group delimeter");
273 ReadingWhitespace = false;
274 AddLiteralString("\\n");
275 } else if (AsmString[DollarPos+1] == 't') {
277 ReadingWhitespace = true;
279 AddLiteralString("\\t");
280 } else if (std::string("${|}\\").find(AsmString[DollarPos+1])
281 != std::string::npos) {
282 if (InWhitespace() && !InGroup())
285 "O.PadToColumn(TAI->getOperandColumn(OperandColumn++));\n",
286 AsmWriterOperand::isLiteralStatementOperand));
287 ReadingWhitespace = false;
289 if (AsmString[DollarPos+1] == '{') {
291 assert(GroupLevel < MAX_GROUP_NESTING_LEVEL
292 && "Exceeded maximum operand group nesting level");
293 GroupDelim[GroupLevel] = AsmString[DollarPos+1];
294 } else if (AsmString[DollarPos+1] == '}') {
295 assert(GroupDelim[GroupLevel] == '{' && "Mismatched delimeters");
297 assert(GroupLevel > -2 && "Too many end delimeters!");
299 AddLiteralString(std::string(1, AsmString[DollarPos+1]));
301 throw "Non-supported escaped character found in instruction '" +
302 CGI.TheDef->getName() + "'!";
304 LastEmitted = DollarPos+2;
307 } else if (AsmString[DollarPos] == '{') {
308 if (CurVariant != ~0U)
309 throw "Nested variants found for instruction '" +
310 CGI.TheDef->getName() + "'!";
311 LastEmitted = DollarPos+1;
312 CurVariant = 0; // We are now inside of the variant!
313 } else if (AsmString[DollarPos] == '|') {
314 if (CurVariant == ~0U)
315 throw "'|' character found outside of a variant in instruction '"
316 + CGI.TheDef->getName() + "'!";
319 } else if (AsmString[DollarPos] == '}') {
320 if (CurVariant == ~0U)
321 throw "'}' character found outside of a variant in instruction '"
322 + CGI.TheDef->getName() + "'!";
325 } else if (DollarPos+1 != AsmString.size() &&
326 AsmString[DollarPos+1] == '$') {
327 if (CurVariant == Variant || CurVariant == ~0U) {
328 if (InWhitespace() && !InGroup())
331 "O.PadToColumn(TAI->getOperandColumn(OperandColumn++));\n",
332 AsmWriterOperand::isLiteralStatementOperand));
333 ReadingWhitespace = false;
334 AddLiteralString("$"); // "$$" -> $
336 LastEmitted = DollarPos+2;
338 if (InWhitespace() && !InGroup())
341 "O.PadToColumn(TAI->getOperandColumn(OperandColumn++));\n",
342 AsmWriterOperand::isLiteralStatementOperand));
343 ReadingWhitespace = false;
345 // Get the name of the variable.
346 std::string::size_type VarEnd = DollarPos+1;
348 // handle ${foo}bar as $foo by detecting whether the character following
349 // the dollar sign is a curly brace. If so, advance VarEnd and DollarPos
350 // so the variable name does not contain the leading curly brace.
351 bool hasCurlyBraces = false;
352 if (VarEnd < AsmString.size() && '{' == AsmString[VarEnd]) {
353 hasCurlyBraces = true;
358 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
360 std::string VarName(AsmString.begin()+DollarPos+1,
361 AsmString.begin()+VarEnd);
363 // Modifier - Support ${foo:modifier} syntax, where "modifier" is passed
364 // into printOperand. Also support ${:feature}, which is passed into
366 std::string Modifier;
368 // In order to avoid starting the next string at the terminating curly
369 // brace, advance the end position past it if we found an opening curly
371 if (hasCurlyBraces) {
372 if (VarEnd >= AsmString.size())
373 throw "Reached end of string before terminating curly brace in '"
374 + CGI.TheDef->getName() + "'";
376 // Look for a modifier string.
377 if (AsmString[VarEnd] == ':') {
379 if (VarEnd >= AsmString.size())
380 throw "Reached end of string before terminating curly brace in '"
381 + CGI.TheDef->getName() + "'";
383 unsigned ModifierStart = VarEnd;
384 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
386 Modifier = std::string(AsmString.begin()+ModifierStart,
387 AsmString.begin()+VarEnd);
388 if (Modifier.empty())
389 throw "Bad operand modifier name in '"+ CGI.TheDef->getName() + "'";
392 if (AsmString[VarEnd] != '}')
393 throw "Variable name beginning with '{' did not end with '}' in '"
394 + CGI.TheDef->getName() + "'";
397 if (VarName.empty() && Modifier.empty())
398 throw "Stray '$' in '" + CGI.TheDef->getName() +
399 "' asm string, maybe you want $$?";
401 if (VarName.empty()) {
402 // Just a modifier, pass this into PrintSpecial.
403 Operands.push_back(AsmWriterOperand("PrintSpecial", ~0U, Modifier));
405 // Otherwise, normal operand.
406 unsigned OpNo = CGI.getOperandNamed(VarName);
407 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
409 if (CurVariant == Variant || CurVariant == ~0U) {
410 unsigned MIOp = OpInfo.MIOperandNo;
411 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp,
415 LastEmitted = VarEnd;
420 AsmWriterOperand("EmitComments(*MI);\n",
421 AsmWriterOperand::isLiteralStatementOperand));
422 AddLiteralString("\\n");
425 /// MatchesAllButOneOp - If this instruction is exactly identical to the
426 /// specified instruction except for one differing operand, return the differing
427 /// operand number. If more than one operand mismatches, return ~1, otherwise
428 /// if the instructions are identical return ~0.
429 unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
430 if (Operands.size() != Other.Operands.size()) return ~1;
432 unsigned MismatchOperand = ~0U;
433 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
434 if (Operands[i] != Other.Operands[i]) {
435 if (MismatchOperand != ~0U) // Already have one mismatch?
441 return MismatchOperand;
444 static void PrintCases(std::vector<std::pair<std::string,
445 AsmWriterOperand> > &OpsToPrint, raw_ostream &O) {
446 O << " case " << OpsToPrint.back().first << ": ";
447 AsmWriterOperand TheOp = OpsToPrint.back().second;
448 OpsToPrint.pop_back();
450 // Check to see if any other operands are identical in this list, and if so,
451 // emit a case label for them.
452 for (unsigned i = OpsToPrint.size(); i != 0; --i)
453 if (OpsToPrint[i-1].second == TheOp) {
454 O << "\n case " << OpsToPrint[i-1].first << ": ";
455 OpsToPrint.erase(OpsToPrint.begin()+i-1);
458 // Finally, emit the code.
459 O << TheOp.getCode();
464 /// EmitInstructions - Emit the last instruction in the vector and any other
465 /// instructions that are suitably similar to it.
466 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
468 AsmWriterInst FirstInst = Insts.back();
471 std::vector<AsmWriterInst> SimilarInsts;
472 unsigned DifferingOperand = ~0;
473 for (unsigned i = Insts.size(); i != 0; --i) {
474 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
476 if (DifferingOperand == ~0U) // First match!
477 DifferingOperand = DiffOp;
479 // If this differs in the same operand as the rest of the instructions in
480 // this class, move it to the SimilarInsts list.
481 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
482 SimilarInsts.push_back(Insts[i-1]);
483 Insts.erase(Insts.begin()+i-1);
488 O << " case " << FirstInst.CGI->Namespace << "::"
489 << FirstInst.CGI->TheDef->getName() << ":\n";
490 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
491 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
492 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
493 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
494 if (i != DifferingOperand) {
495 // If the operand is the same for all instructions, just print it.
496 O << " " << FirstInst.Operands[i].getCode();
498 // If this is the operand that varies between all of the instructions,
499 // emit a switch for just this operand now.
500 O << " switch (MI->getOpcode()) {\n";
501 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
502 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
503 FirstInst.CGI->TheDef->getName(),
504 FirstInst.Operands[i]));
506 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
507 AsmWriterInst &AWI = SimilarInsts[si];
508 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
509 AWI.CGI->TheDef->getName(),
512 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
513 while (!OpsToPrint.empty())
514 PrintCases(OpsToPrint, O);
522 void AsmWriterEmitter::
523 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
524 std::vector<unsigned> &InstIdxs,
525 std::vector<unsigned> &InstOpsUsed) const {
526 InstIdxs.assign(NumberedInstructions.size(), ~0U);
528 // This vector parallels UniqueOperandCommands, keeping track of which
529 // instructions each case are used for. It is a comma separated string of
531 std::vector<std::string> InstrsForCase;
532 InstrsForCase.resize(UniqueOperandCommands.size());
533 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
535 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
536 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
537 if (Inst == 0) continue; // PHI, INLINEASM, DBG_LABEL, etc.
540 if (Inst->Operands.empty())
541 continue; // Instruction already done.
543 Command = " " + Inst->Operands[0].getCode() + "\n";
545 // If this is the last operand, emit a return.
546 if (Inst->Operands.size() == 1) {
547 Command += " return true;\n";
550 // Check to see if we already have 'Command' in UniqueOperandCommands.
552 bool FoundIt = false;
553 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
554 if (UniqueOperandCommands[idx] == Command) {
556 InstrsForCase[idx] += ", ";
557 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
562 InstIdxs[i] = UniqueOperandCommands.size();
563 UniqueOperandCommands.push_back(Command);
564 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
566 // This command matches one operand so far.
567 InstOpsUsed.push_back(1);
571 // For each entry of UniqueOperandCommands, there is a set of instructions
572 // that uses it. If the next command of all instructions in the set are
573 // identical, fold it into the command.
574 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
575 CommandIdx != e; ++CommandIdx) {
577 for (unsigned Op = 1; ; ++Op) {
578 // Scan for the first instruction in the set.
579 std::vector<unsigned>::iterator NIT =
580 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
581 if (NIT == InstIdxs.end()) break; // No commonality.
583 // If this instruction has no more operands, we isn't anything to merge
584 // into this command.
585 const AsmWriterInst *FirstInst =
586 getAsmWriterInstByID(NIT-InstIdxs.begin());
587 if (!FirstInst || FirstInst->Operands.size() == Op)
590 // Otherwise, scan to see if all of the other instructions in this command
591 // set share the operand.
593 // Keep track of the maximum, number of operands or any
594 // instruction we see in the group.
595 size_t MaxSize = FirstInst->Operands.size();
597 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
598 NIT != InstIdxs.end();
599 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
600 // Okay, found another instruction in this command set. If the operand
601 // matches, we're ok, otherwise bail out.
602 const AsmWriterInst *OtherInst =
603 getAsmWriterInstByID(NIT-InstIdxs.begin());
606 OtherInst->Operands.size() > FirstInst->Operands.size())
607 MaxSize = std::max(MaxSize, OtherInst->Operands.size());
609 if (!OtherInst || OtherInst->Operands.size() == Op ||
610 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
617 // Okay, everything in this command set has the same next operand. Add it
618 // to UniqueOperandCommands and remember that it was consumed.
619 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
621 // If this is the last operand, emit a return after the code.
622 if (FirstInst->Operands.size() == Op+1 &&
623 // Don't early-out too soon. Other instructions in this
624 // group may have more operands.
625 FirstInst->Operands.size() == MaxSize) {
626 Command += " return true;\n";
629 UniqueOperandCommands[CommandIdx] += Command;
630 InstOpsUsed[CommandIdx]++;
634 // Prepend some of the instructions each case is used for onto the case val.
635 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
636 std::string Instrs = InstrsForCase[i];
637 if (Instrs.size() > 70) {
638 Instrs.erase(Instrs.begin()+70, Instrs.end());
643 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
644 UniqueOperandCommands[i];
650 void AsmWriterEmitter::run(raw_ostream &O) {
651 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
653 CodeGenTarget Target;
654 Record *AsmWriter = Target.getAsmWriter();
655 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
656 unsigned Variant = AsmWriter->getValueAsInt("Variant");
659 "/// printInstruction - This method is automatically generated by tablegen\n"
660 "/// from the instruction set description. This method returns true if the\n"
661 "/// machine instruction was sufficiently described to print it, otherwise\n"
662 "/// it returns false.\n"
663 "bool " << Target.getName() << ClassName
664 << "::printInstruction(const MachineInstr *MI) {\n";
666 std::vector<AsmWriterInst> Instructions;
668 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
669 E = Target.inst_end(); I != E; ++I)
670 if (!I->second.AsmString.empty())
671 Instructions.push_back(AsmWriterInst(I->second, Variant));
673 // Get the instruction numbering.
674 Target.getInstructionsByEnumValue(NumberedInstructions);
676 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
677 // all machine instructions are necessarily being printed, so there may be
678 // target instructions not in this map.
679 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
680 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
682 // Build an aggregate string, and build a table of offsets into it.
683 std::map<std::string, unsigned> StringOffset;
684 std::string AggregateString;
685 AggregateString.push_back(0); // "\0"
686 AggregateString.push_back(0); // "\0"
688 /// OpcodeInfo - This encodes the index of the string to use for the first
689 /// chunk of the output as well as indices used for operand printing.
690 std::vector<unsigned> OpcodeInfo;
692 unsigned MaxStringIdx = 0;
693 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
694 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
697 // Something not handled by the asmwriter printer.
699 } else if (AWI->Operands[0].OperandType !=
700 AsmWriterOperand::isLiteralTextOperand ||
701 AWI->Operands[0].Str.empty()) {
702 // Something handled by the asmwriter printer, but with no leading string.
705 unsigned &Entry = StringOffset[AWI->Operands[0].Str];
707 // Add the string to the aggregate if this is the first time found.
708 MaxStringIdx = Entry = AggregateString.size();
709 std::string Str = AWI->Operands[0].Str;
711 AggregateString += Str;
712 AggregateString += '\0';
716 // Nuke the string from the operand list. It is now handled!
717 AWI->Operands.erase(AWI->Operands.begin());
719 OpcodeInfo.push_back(Idx);
722 // Figure out how many bits we used for the string index.
723 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+1);
725 // To reduce code size, we compactify common instructions into a few bits
726 // in the opcode-indexed table.
727 unsigned BitsLeft = 32-AsmStrBits;
729 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
733 std::vector<std::string> UniqueOperandCommands;
735 // For the first operand check, add a default value for instructions with
736 // just opcode strings to use.
738 UniqueOperandCommands.push_back(" return true;\n");
742 std::vector<unsigned> InstIdxs;
743 std::vector<unsigned> NumInstOpsHandled;
744 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
747 // If we ran out of operands to print, we're done.
748 if (UniqueOperandCommands.empty()) break;
750 // Compute the number of bits we need to represent these cases, this is
751 // ceil(log2(numentries)).
752 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
754 // If we don't have enough bits for this operand, don't include it.
755 if (NumBits > BitsLeft) {
756 DOUT << "Not enough bits to densely encode " << NumBits
761 // Otherwise, we can include this in the initial lookup table. Add it in.
763 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
764 if (InstIdxs[i] != ~0U)
765 OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
767 // Remove the info about this operand.
768 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
769 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
770 if (!Inst->Operands.empty()) {
771 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
772 assert(NumOps <= Inst->Operands.size() &&
773 "Can't remove this many ops!");
774 Inst->Operands.erase(Inst->Operands.begin(),
775 Inst->Operands.begin()+NumOps);
779 // Remember the handlers for this set of operands.
780 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
785 O<<" static const unsigned OpInfo[] = {\n";
786 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
787 O << " " << OpcodeInfo[i] << "U,\t// "
788 << NumberedInstructions[i]->TheDef->getName() << "\n";
790 // Add a dummy entry so the array init doesn't end with a comma.
794 // Emit the string itself.
795 O << " const char *AsmStrs = \n \"";
796 unsigned CharsPrinted = 0;
797 EscapeString(AggregateString);
798 for (unsigned i = 0, e = AggregateString.size(); i != e; ++i) {
799 if (CharsPrinted > 70) {
803 O << AggregateString[i];
806 // Print escape sequences all together.
807 if (AggregateString[i] == '\\') {
808 assert(i+1 < AggregateString.size() && "Incomplete escape sequence!");
809 if (isdigit(AggregateString[i+1])) {
810 assert(isdigit(AggregateString[i+2]) && isdigit(AggregateString[i+3]) &&
811 "Expected 3 digit octal escape!");
812 O << AggregateString[++i];
813 O << AggregateString[++i];
814 O << AggregateString[++i];
817 O << AggregateString[++i];
824 O << " processDebugLoc(MI->getDebugLoc());\n\n";
826 O << "\n#ifndef NO_ASM_WRITER_BOILERPLATE\n";
828 O << " if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {\n"
829 << " O << \"\\t\";\n"
830 << " printInlineAsm(MI);\n"
832 << " } else if (MI->isLabel()) {\n"
833 << " printLabel(MI);\n"
835 << " } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {\n"
836 << " printDeclare(MI);\n"
838 << " } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {\n"
839 << " printImplicitDef(MI);\n"
845 O << " O << \"\\t\";\n\n";
847 O << " // Emit the opcode for the instruction.\n"
848 << " unsigned Bits = OpInfo[MI->getOpcode()];\n"
849 << " if (Bits == 0) return false;\n\n";
851 O << " unsigned OperandColumn = 1;\n\n"
852 << " if (TAI->getOperandColumn(1) > 0) {\n"
853 << " // Don't emit trailing whitespace, let the column padding do it. This\n"
854 << " // guarantees that a stray long opcode + tab won't upset the alignment.\n"
855 << " unsigned OpLength = std::strlen(AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << "));\n"
856 << " if (OpLength > 0 &&\n"
857 << " ((AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << "))[OpLength-1] == ' ' ||\n"
858 << " (AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << "))[OpLength-1] == '\\t')) {\n"
861 << " } while ((AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << "))[OpLength-1] == ' ' ||\n"
862 << " (AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << "))[OpLength-1] == '\\t');\n"
863 << " for (unsigned Idx = 0; Idx < OpLength; ++Idx)\n"
864 << " O << (AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << "))[Idx];\n"
865 << " O.PadToColumn(TAI->getOperandColumn(OperandColumn++), 1);\n"
868 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ");\n"
872 // Output the table driven operand information.
873 BitsLeft = 32-AsmStrBits;
874 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
875 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
877 // Compute the number of bits we need to represent these cases, this is
878 // ceil(log2(numentries)).
879 unsigned NumBits = Log2_32_Ceil(Commands.size());
880 assert(NumBits <= BitsLeft && "consistency error");
882 // Emit code to extract this field from Bits.
885 O << "\n // Fragment " << i << " encoded into " << NumBits
886 << " bits for " << Commands.size() << " unique commands.\n";
888 if (Commands.size() == 2) {
889 // Emit two possibilitys with if/else.
890 O << " if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
891 << ((1 << NumBits)-1) << ") {\n"
897 O << " switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
898 << ((1 << NumBits)-1) << ") {\n"
899 << " default: // unreachable.\n";
901 // Print out all the cases.
902 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
903 O << " case " << i << ":\n";
911 // Okay, delete instructions with no operand info left.
912 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
913 // Entire instruction has been emitted?
914 AsmWriterInst &Inst = Instructions[i];
915 if (Inst.Operands.empty()) {
916 Instructions.erase(Instructions.begin()+i);
922 // Because this is a vector, we want to emit from the end. Reverse all of the
923 // elements in the vector.
924 std::reverse(Instructions.begin(), Instructions.end());
926 if (!Instructions.empty()) {
927 // Find the opcode # of inline asm.
928 O << " switch (MI->getOpcode()) {\n";
929 while (!Instructions.empty())
930 EmitInstructions(Instructions, O);
933 O << " return true;\n";
936 O << " return true;\n";