1 //===- AsmWriterEmitter.cpp - Generate an assembly writer -----------------===//
3 // The LLVM Compiler Infrastructure
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.
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"
25 static bool isIdentChar(char C) {
26 return (C >= 'a' && C <= 'z') ||
27 (C >= 'A' && C <= 'Z') ||
28 (C >= '0' && C <= '9') ||
33 struct AsmWriterOperand {
34 enum { isLiteralTextOperand, isMachineInstrOperand } OperandType;
36 /// Str - For isLiteralTextOperand, this IS the literal text. For
37 /// isMachineInstrOperand, this is the PrinterMethodName for the operand.
40 /// MiOpNo - For isMachineInstrOperand, this is the operand number of the
41 /// machine instruction.
44 /// MiModifier - For isMachineInstrOperand, this is the modifier string for
45 /// an operand, specified with syntax like ${opname:modifier}.
46 std::string MiModifier;
48 AsmWriterOperand(const std::string &LitStr)
49 : OperandType(isLiteralTextOperand), Str(LitStr) {}
51 AsmWriterOperand(const std::string &Printer, unsigned OpNo,
52 const std::string &Modifier)
53 : OperandType(isMachineInstrOperand), Str(Printer), MIOpNo(OpNo),
54 MiModifier(Modifier) {}
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;
62 bool operator==(const AsmWriterOperand &Other) const {
63 return !operator!=(Other);
66 /// getCode - Return the code that prints this operand.
67 std::string getCode() const;
72 struct AsmWriterInst {
73 std::vector<AsmWriterOperand> Operands;
74 const CodeGenInstruction *CGI;
76 AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant);
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;
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);
91 Operands.push_back(AsmWriterOperand(Str));
97 std::string AsmWriterOperand::getCode() const {
98 if (OperandType == isLiteralTextOperand)
99 return "O << \"" + Str + "\"; ";
101 std::string Result = Str + "(MI, " + utostr(MIOpNo);
102 if (!MiModifier.empty())
103 Result += ", \"" + MiModifier + '"';
104 return Result + "); ";
108 /// ParseAsmString - Parse the specified Instruction's AsmString into this
111 AsmWriterInst::AsmWriterInst(const CodeGenInstruction &CGI, unsigned Variant) {
113 unsigned CurVariant = ~0U; // ~0 if we are outside a {.|.|.} region, other #.
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();
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() + "'!";
144 } else if (AsmString[DollarPos] == '}') {
145 if (CurVariant == ~0U)
146 throw "'}' character found outside of a variant in instruction '"
147 + CGI.TheDef->getName() + "'!";
150 } else if (DollarPos+1 != AsmString.size() &&
151 AsmString[DollarPos+1] == '$') {
152 if (CurVariant == Variant || CurVariant == ~0U)
153 AddLiteralString("$"); // "$$" -> $
154 LastEmitted = DollarPos+2;
156 // Get the name of the variable.
157 std::string::size_type VarEnd = DollarPos+1;
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;
169 while (VarEnd < AsmString.size() && isIdentChar(AsmString[VarEnd]))
171 std::string VarName(AsmString.begin()+DollarPos+1,
172 AsmString.begin()+VarEnd);
174 // Modifier - Support ${foo:modifier} syntax, where "modifier" is passed
175 // into printOperand.
176 std::string Modifier;
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
181 if (hasCurlyBraces) {
182 if (VarEnd >= AsmString.size())
183 throw "Reached end of string before terminating curly brace in '"
184 + CGI.TheDef->getName() + "'";
186 // Look for a modifier string.
187 if (AsmString[VarEnd] == ':') {
189 if (VarEnd >= AsmString.size())
190 throw "Reached end of string before terminating curly brace in '"
191 + CGI.TheDef->getName() + "'";
193 unsigned ModifierStart = VarEnd;
194 while (VarEnd < AsmString.size() && isIdentChar(AsmString[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() + "'";
202 if (AsmString[VarEnd] != '}')
203 throw "Variable name beginning with '{' did not end with '}' in '"
204 + CGI.TheDef->getName() + "'";
208 throw "Stray '$' in '" + CGI.TheDef->getName() +
209 "' asm string, maybe you want $$?";
211 unsigned OpNo = CGI.getOperandNamed(VarName);
212 CodeGenInstruction::OperandInfo OpInfo = CGI.OperandList[OpNo];
214 // If this is a two-address instruction and we are not accessing the
215 // 0th operand, remove an operand.
216 unsigned MIOp = OpInfo.MIOperandNo;
217 if (CGI.isTwoAddress && MIOp != 0) {
219 throw "Should refer to operand #0 instead of #1 for two-address"
220 " instruction '" + CGI.TheDef->getName() + "'!";
224 if (CurVariant == Variant || CurVariant == ~0U)
225 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp,
227 LastEmitted = VarEnd;
231 AddLiteralString("\\n");
234 /// MatchesAllButOneOp - If this instruction is exactly identical to the
235 /// specified instruction except for one differing operand, return the differing
236 /// operand number. If more than one operand mismatches, return ~1, otherwise
237 /// if the instructions are identical return ~0.
238 unsigned AsmWriterInst::MatchesAllButOneOp(const AsmWriterInst &Other)const{
239 if (Operands.size() != Other.Operands.size()) return ~1;
241 unsigned MismatchOperand = ~0U;
242 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
243 if (Operands[i] != Other.Operands[i])
244 if (MismatchOperand != ~0U) // Already have one mismatch?
249 return MismatchOperand;
252 static void PrintCases(std::vector<std::pair<std::string,
253 AsmWriterOperand> > &OpsToPrint, std::ostream &O) {
254 O << " case " << OpsToPrint.back().first << ": ";
255 AsmWriterOperand TheOp = OpsToPrint.back().second;
256 OpsToPrint.pop_back();
258 // Check to see if any other operands are identical in this list, and if so,
259 // emit a case label for them.
260 for (unsigned i = OpsToPrint.size(); i != 0; --i)
261 if (OpsToPrint[i-1].second == TheOp) {
262 O << "\n case " << OpsToPrint[i-1].first << ": ";
263 OpsToPrint.erase(OpsToPrint.begin()+i-1);
266 // Finally, emit the code.
267 O << TheOp.getCode();
272 /// EmitInstructions - Emit the last instruction in the vector and any other
273 /// instructions that are suitably similar to it.
274 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
276 AsmWriterInst FirstInst = Insts.back();
279 std::vector<AsmWriterInst> SimilarInsts;
280 unsigned DifferingOperand = ~0;
281 for (unsigned i = Insts.size(); i != 0; --i) {
282 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
284 if (DifferingOperand == ~0U) // First match!
285 DifferingOperand = DiffOp;
287 // If this differs in the same operand as the rest of the instructions in
288 // this class, move it to the SimilarInsts list.
289 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
290 SimilarInsts.push_back(Insts[i-1]);
291 Insts.erase(Insts.begin()+i-1);
296 O << " case " << FirstInst.CGI->Namespace << "::"
297 << FirstInst.CGI->TheDef->getName() << ":\n";
298 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
299 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
300 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
301 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
302 if (i != DifferingOperand) {
303 // If the operand is the same for all instructions, just print it.
304 O << " " << FirstInst.Operands[i].getCode();
306 // If this is the operand that varies between all of the instructions,
307 // emit a switch for just this operand now.
308 O << " switch (MI->getOpcode()) {\n";
309 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
310 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
311 FirstInst.CGI->TheDef->getName(),
312 FirstInst.Operands[i]));
314 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
315 AsmWriterInst &AWI = SimilarInsts[si];
316 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
317 AWI.CGI->TheDef->getName(),
320 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
321 while (!OpsToPrint.empty())
322 PrintCases(OpsToPrint, O);
331 void AsmWriterEmitter::
332 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
333 std::vector<unsigned> &InstIdxs,
334 std::vector<unsigned> &InstOpsUsed) const {
335 InstIdxs.assign(NumberedInstructions.size(), ~0U);
337 // This vector parallels UniqueOperandCommands, keeping track of which
338 // instructions each case are used for. It is a comma separated string of
340 std::vector<std::string> InstrsForCase;
341 InstrsForCase.resize(UniqueOperandCommands.size());
342 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
344 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
345 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
346 if (Inst == 0) continue; // PHI, INLINEASM, etc.
349 if (Inst->Operands.empty())
350 continue; // Instruction already done.
352 Command = " " + Inst->Operands[0].getCode() + "\n";
354 // If this is the last operand, emit a return.
355 if (Inst->Operands.size() == 1)
356 Command += " return true;\n";
358 // Check to see if we already have 'Command' in UniqueOperandCommands.
360 bool FoundIt = false;
361 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
362 if (UniqueOperandCommands[idx] == Command) {
364 InstrsForCase[idx] += ", ";
365 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
370 InstIdxs[i] = UniqueOperandCommands.size();
371 UniqueOperandCommands.push_back(Command);
372 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
374 // This command matches one operand so far.
375 InstOpsUsed.push_back(1);
379 // For each entry of UniqueOperandCommands, there is a set of instructions
380 // that uses it. If the next command of all instructions in the set are
381 // identical, fold it into the command.
382 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
383 CommandIdx != e; ++CommandIdx) {
385 for (unsigned Op = 1; ; ++Op) {
386 // Scan for the first instruction in the set.
387 std::vector<unsigned>::iterator NIT =
388 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
389 if (NIT == InstIdxs.end()) break; // No commonality.
391 // If this instruction has no more operands, we isn't anything to merge
392 // into this command.
393 const AsmWriterInst *FirstInst =
394 getAsmWriterInstByID(NIT-InstIdxs.begin());
395 if (!FirstInst || FirstInst->Operands.size() == Op)
398 // Otherwise, scan to see if all of the other instructions in this command
399 // set share the operand.
402 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
403 NIT != InstIdxs.end();
404 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
405 // Okay, found another instruction in this command set. If the operand
406 // matches, we're ok, otherwise bail out.
407 const AsmWriterInst *OtherInst =
408 getAsmWriterInstByID(NIT-InstIdxs.begin());
409 if (!OtherInst || OtherInst->Operands.size() == Op ||
410 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
417 // Okay, everything in this command set has the same next operand. Add it
418 // to UniqueOperandCommands and remember that it was consumed.
419 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
421 // If this is the last operand, emit a return after the code.
422 if (FirstInst->Operands.size() == Op+1)
423 Command += " return true;\n";
425 UniqueOperandCommands[CommandIdx] += Command;
426 InstOpsUsed[CommandIdx]++;
430 // Prepend some of the instructions each case is used for onto the case val.
431 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
432 std::string Instrs = InstrsForCase[i];
433 if (Instrs.size() > 70) {
434 Instrs.erase(Instrs.begin()+70, Instrs.end());
439 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
440 UniqueOperandCommands[i];
446 void AsmWriterEmitter::run(std::ostream &O) {
447 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
449 CodeGenTarget Target;
450 Record *AsmWriter = Target.getAsmWriter();
451 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
452 unsigned Variant = AsmWriter->getValueAsInt("Variant");
455 "/// printInstruction - This method is automatically generated by tablegen\n"
456 "/// from the instruction set description. This method returns true if the\n"
457 "/// machine instruction was sufficiently described to print it, otherwise\n"
458 "/// it returns false.\n"
459 "bool " << Target.getName() << ClassName
460 << "::printInstruction(const MachineInstr *MI) {\n";
462 std::vector<AsmWriterInst> Instructions;
464 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
465 E = Target.inst_end(); I != E; ++I)
466 if (!I->second.AsmString.empty())
467 Instructions.push_back(AsmWriterInst(I->second, Variant));
469 // Get the instruction numbering.
470 Target.getInstructionsByEnumValue(NumberedInstructions);
472 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
473 // all machine instructions are necessarily being printed, so there may be
474 // target instructions not in this map.
475 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
476 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
478 // Build an aggregate string, and build a table of offsets into it.
479 std::map<std::string, unsigned> StringOffset;
480 std::string AggregateString;
481 AggregateString += "\0\0";
483 /// OpcodeInfo - Theis encodes the index of the string to use for the first
484 /// chunk of the output as well as indices used for operand printing.
485 std::vector<unsigned> OpcodeInfo;
487 unsigned MaxStringIdx = 0;
488 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
489 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
492 // Something not handled by the asmwriter printer.
494 } else if (AWI->Operands[0].OperandType !=
495 AsmWriterOperand::isLiteralTextOperand ||
496 AWI->Operands[0].Str.empty()) {
497 // Something handled by the asmwriter printer, but with no leading string.
500 unsigned &Entry = StringOffset[AWI->Operands[0].Str];
502 // Add the string to the aggregate if this is the first time found.
503 MaxStringIdx = Entry = AggregateString.size();
504 std::string Str = AWI->Operands[0].Str;
506 AggregateString += Str;
507 AggregateString += '\0';
511 // Nuke the string from the operand list. It is now handled!
512 AWI->Operands.erase(AWI->Operands.begin());
514 OpcodeInfo.push_back(Idx);
517 // Figure out how many bits we used for the string index.
518 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx);
520 // To reduce code size, we compactify common instructions into a few bits
521 // in the opcode-indexed table.
522 unsigned BitsLeft = 32-AsmStrBits;
524 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
528 std::vector<std::string> UniqueOperandCommands;
530 // For the first operand check, add a default value for instructions with
531 // just opcode strings to use.
533 UniqueOperandCommands.push_back(" return true;\n");
537 std::vector<unsigned> InstIdxs;
538 std::vector<unsigned> NumInstOpsHandled;
539 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
542 // If we ran out of operands to print, we're done.
543 if (UniqueOperandCommands.empty()) break;
545 // Compute the number of bits we need to represent these cases, this is
546 // ceil(log2(numentries)).
547 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
549 // If we don't have enough bits for this operand, don't include it.
550 if (NumBits > BitsLeft) {
551 DEBUG(std::cerr << "Not enough bits to densely encode " << NumBits
556 // Otherwise, we can include this in the initial lookup table. Add it in.
558 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
559 if (InstIdxs[i] != ~0U)
560 OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
562 // Remove the info about this operand.
563 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
564 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
565 if (!Inst->Operands.empty()) {
566 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
567 assert(NumOps <= Inst->Operands.size() &&
568 "Can't remove this many ops!");
569 Inst->Operands.erase(Inst->Operands.begin(),
570 Inst->Operands.begin()+NumOps);
574 // Remember the handlers for this set of operands.
575 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
580 O<<" static const unsigned OpInfo[] = {\n";
581 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
582 O << " " << OpcodeInfo[i] << "U,\t// "
583 << NumberedInstructions[i]->TheDef->getName() << "\n";
585 // Add a dummy entry so the array init doesn't end with a comma.
589 // Emit the string itself.
590 O << " const char *AsmStrs = \n \"";
591 unsigned CharsPrinted = 0;
592 EscapeString(AggregateString);
593 for (unsigned i = 0, e = AggregateString.size(); i != e; ++i) {
594 if (CharsPrinted > 70) {
598 O << AggregateString[i];
601 // Print escape sequences all together.
602 if (AggregateString[i] == '\\') {
603 assert(i+1 < AggregateString.size() && "Incomplete escape sequence!");
604 if (isdigit(AggregateString[i+1])) {
605 assert(isdigit(AggregateString[i+2]) && isdigit(AggregateString[i+3]) &&
606 "Expected 3 digit octal escape!");
607 O << AggregateString[++i];
608 O << AggregateString[++i];
609 O << AggregateString[++i];
612 O << AggregateString[++i];
619 O << " if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {\n"
620 << " printInlineAsm(MI);\n"
624 O << " // Emit the opcode for the instruction.\n"
625 << " unsigned Bits = OpInfo[MI->getOpcode()];\n"
626 << " if (Bits == 0) return false;\n"
627 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ");\n\n";
629 // Output the table driven operand information.
630 BitsLeft = 32-AsmStrBits;
631 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
632 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
634 // Compute the number of bits we need to represent these cases, this is
635 // ceil(log2(numentries)).
636 unsigned NumBits = Log2_32_Ceil(Commands.size());
637 assert(NumBits <= BitsLeft && "consistency error");
639 // Emit code to extract this field from Bits.
642 O << "\n // Fragment " << i << " encoded into " << NumBits
643 << " bits for " << Commands.size() << " unique commands.\n";
645 if (Commands.size() == 2) {
646 // Emit two possibilitys with if/else.
647 O << " if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
648 << ((1 << NumBits)-1) << ") {\n"
654 O << " switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
655 << ((1 << NumBits)-1) << ") {\n"
656 << " default: // unreachable.\n";
658 // Print out all the cases.
659 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
660 O << " case " << i << ":\n";
668 // Okay, delete instructions with no operand info left.
669 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
670 // Entire instruction has been emitted?
671 AsmWriterInst &Inst = Instructions[i];
672 if (Inst.Operands.empty()) {
673 Instructions.erase(Instructions.begin()+i);
679 // Because this is a vector, we want to emit from the end. Reverse all of the
680 // elements in the vector.
681 std::reverse(Instructions.begin(), Instructions.end());
683 if (!Instructions.empty()) {
684 // Find the opcode # of inline asm.
685 O << " switch (MI->getOpcode()) {\n";
686 while (!Instructions.empty())
687 EmitInstructions(Instructions, O);
690 O << " return true;\n";