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, verify the second operand isn't
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() + "'!";
221 if (CurVariant == Variant || CurVariant == ~0U)
222 Operands.push_back(AsmWriterOperand(OpInfo.PrinterMethodName, MIOp,
224 LastEmitted = VarEnd;
228 AddLiteralString("\\n");
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;
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?
246 return MismatchOperand;
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();
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);
263 // Finally, emit the code.
264 O << TheOp.getCode();
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,
273 AsmWriterInst FirstInst = Insts.back();
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);
281 if (DifferingOperand == ~0U) // First match!
282 DifferingOperand = DiffOp;
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);
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();
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]));
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(),
317 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
318 while (!OpsToPrint.empty())
319 PrintCases(OpsToPrint, O);
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);
334 // This vector parallels UniqueOperandCommands, keeping track of which
335 // instructions each case are used for. It is a comma separated string of
337 std::vector<std::string> InstrsForCase;
338 InstrsForCase.resize(UniqueOperandCommands.size());
339 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
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.
346 if (Inst->Operands.empty())
347 continue; // Instruction already done.
349 Command = " " + Inst->Operands[0].getCode() + "\n";
351 // If this is the last operand, emit a return.
352 if (Inst->Operands.size() == 1)
353 Command += " return true;\n";
355 // Check to see if we already have 'Command' in UniqueOperandCommands.
357 bool FoundIt = false;
358 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
359 if (UniqueOperandCommands[idx] == Command) {
361 InstrsForCase[idx] += ", ";
362 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
367 InstIdxs[i] = UniqueOperandCommands.size();
368 UniqueOperandCommands.push_back(Command);
369 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
371 // This command matches one operand so far.
372 InstOpsUsed.push_back(1);
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) {
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.
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)
395 // Otherwise, scan to see if all of the other instructions in this command
396 // set share the operand.
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]) {
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";
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";
422 UniqueOperandCommands[CommandIdx] += Command;
423 InstOpsUsed[CommandIdx]++;
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());
436 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
437 UniqueOperandCommands[i];
443 void AsmWriterEmitter::run(std::ostream &O) {
444 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
446 CodeGenTarget Target;
447 Record *AsmWriter = Target.getAsmWriter();
448 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
449 unsigned Variant = AsmWriter->getValueAsInt("Variant");
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";
459 std::vector<AsmWriterInst> Instructions;
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));
466 // Get the instruction numbering.
467 Target.getInstructionsByEnumValue(NumberedInstructions);
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]));
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";
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;
484 unsigned MaxStringIdx = 0;
485 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
486 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
489 // Something not handled by the asmwriter printer.
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.
497 unsigned &Entry = StringOffset[AWI->Operands[0].Str];
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;
503 AggregateString += Str;
504 AggregateString += '\0';
508 // Nuke the string from the operand list. It is now handled!
509 AWI->Operands.erase(AWI->Operands.begin());
511 OpcodeInfo.push_back(Idx);
514 // Figure out how many bits we used for the string index.
515 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx);
517 // To reduce code size, we compactify common instructions into a few bits
518 // in the opcode-indexed table.
519 unsigned BitsLeft = 32-AsmStrBits;
521 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
525 std::vector<std::string> UniqueOperandCommands;
527 // For the first operand check, add a default value for instructions with
528 // just opcode strings to use.
530 UniqueOperandCommands.push_back(" return true;\n");
534 std::vector<unsigned> InstIdxs;
535 std::vector<unsigned> NumInstOpsHandled;
536 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
539 // If we ran out of operands to print, we're done.
540 if (UniqueOperandCommands.empty()) break;
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());
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
553 // Otherwise, we can include this in the initial lookup table. Add it in.
555 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
556 if (InstIdxs[i] != ~0U)
557 OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
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);
571 // Remember the handlers for this set of operands.
572 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
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";
582 // Add a dummy entry so the array init doesn't end with a comma.
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) {
595 O << AggregateString[i];
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];
609 O << AggregateString[++i];
616 O << " if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {\n"
617 << " printInlineAsm(MI);\n"
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";
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];
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");
636 // Emit code to extract this field from Bits.
639 O << "\n // Fragment " << i << " encoded into " << NumBits
640 << " bits for " << Commands.size() << " unique commands.\n";
642 if (Commands.size() == 2) {
643 // Emit two possibilitys with if/else.
644 O << " if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
645 << ((1 << NumBits)-1) << ") {\n"
651 O << " switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
652 << ((1 << NumBits)-1) << ") {\n"
653 << " default: // unreachable.\n";
655 // Print out all the cases.
656 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
657 O << " case " << i << ":\n";
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);
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());
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);
687 O << " return true;\n";