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 "AsmWriterInst.h"
16 #include "CodeGenTarget.h"
17 #include "SequenceToOffsetTable.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/Twine.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Format.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/TableGen/Error.h"
24 #include "llvm/TableGen/Record.h"
25 #include "llvm/TableGen/TableGenBackend.h"
33 class AsmWriterEmitter {
34 RecordKeeper &Records;
36 std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap;
37 std::vector<const CodeGenInstruction*> NumberedInstructions;
38 std::vector<AsmWriterInst> Instructions;
40 AsmWriterEmitter(RecordKeeper &R);
42 void run(raw_ostream &o);
45 void EmitPrintInstruction(raw_ostream &o);
46 void EmitGetRegisterName(raw_ostream &o);
47 void EmitPrintAliasInstruction(raw_ostream &O);
49 AsmWriterInst *getAsmWriterInstByID(unsigned ID) const {
50 assert(ID < NumberedInstructions.size());
51 std::map<const CodeGenInstruction*, AsmWriterInst*>::const_iterator I =
52 CGIAWIMap.find(NumberedInstructions[ID]);
53 assert(I != CGIAWIMap.end() && "Didn't find inst!");
56 void FindUniqueOperandCommands(std::vector<std::string> &UOC,
57 std::vector<unsigned> &InstIdxs,
58 std::vector<unsigned> &InstOpsUsed) const;
60 } // end anonymous namespace
62 static void PrintCases(std::vector<std::pair<std::string,
63 AsmWriterOperand> > &OpsToPrint, raw_ostream &O) {
64 O << " case " << OpsToPrint.back().first << ": ";
65 AsmWriterOperand TheOp = OpsToPrint.back().second;
66 OpsToPrint.pop_back();
68 // Check to see if any other operands are identical in this list, and if so,
69 // emit a case label for them.
70 for (unsigned i = OpsToPrint.size(); i != 0; --i)
71 if (OpsToPrint[i-1].second == TheOp) {
72 O << "\n case " << OpsToPrint[i-1].first << ": ";
73 OpsToPrint.erase(OpsToPrint.begin()+i-1);
76 // Finally, emit the code.
82 /// EmitInstructions - Emit the last instruction in the vector and any other
83 /// instructions that are suitably similar to it.
84 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
86 AsmWriterInst FirstInst = Insts.back();
89 std::vector<AsmWriterInst> SimilarInsts;
90 unsigned DifferingOperand = ~0;
91 for (unsigned i = Insts.size(); i != 0; --i) {
92 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
94 if (DifferingOperand == ~0U) // First match!
95 DifferingOperand = DiffOp;
97 // If this differs in the same operand as the rest of the instructions in
98 // this class, move it to the SimilarInsts list.
99 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
100 SimilarInsts.push_back(Insts[i-1]);
101 Insts.erase(Insts.begin()+i-1);
106 O << " case " << FirstInst.CGI->Namespace << "::"
107 << FirstInst.CGI->TheDef->getName() << ":\n";
108 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
109 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
110 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
111 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
112 if (i != DifferingOperand) {
113 // If the operand is the same for all instructions, just print it.
114 O << " " << FirstInst.Operands[i].getCode();
116 // If this is the operand that varies between all of the instructions,
117 // emit a switch for just this operand now.
118 O << " switch (MI->getOpcode()) {\n";
119 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
120 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
121 FirstInst.CGI->TheDef->getName(),
122 FirstInst.Operands[i]));
124 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
125 AsmWriterInst &AWI = SimilarInsts[si];
126 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
127 AWI.CGI->TheDef->getName(),
130 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
131 while (!OpsToPrint.empty())
132 PrintCases(OpsToPrint, O);
140 void AsmWriterEmitter::
141 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
142 std::vector<unsigned> &InstIdxs,
143 std::vector<unsigned> &InstOpsUsed) const {
144 InstIdxs.assign(NumberedInstructions.size(), ~0U);
146 // This vector parallels UniqueOperandCommands, keeping track of which
147 // instructions each case are used for. It is a comma separated string of
149 std::vector<std::string> InstrsForCase;
150 InstrsForCase.resize(UniqueOperandCommands.size());
151 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
153 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
154 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
155 if (Inst == 0) continue; // PHI, INLINEASM, PROLOG_LABEL, etc.
158 if (Inst->Operands.empty())
159 continue; // Instruction already done.
161 Command = " " + Inst->Operands[0].getCode() + "\n";
163 // Check to see if we already have 'Command' in UniqueOperandCommands.
165 bool FoundIt = false;
166 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
167 if (UniqueOperandCommands[idx] == Command) {
169 InstrsForCase[idx] += ", ";
170 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
175 InstIdxs[i] = UniqueOperandCommands.size();
176 UniqueOperandCommands.push_back(Command);
177 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
179 // This command matches one operand so far.
180 InstOpsUsed.push_back(1);
184 // For each entry of UniqueOperandCommands, there is a set of instructions
185 // that uses it. If the next command of all instructions in the set are
186 // identical, fold it into the command.
187 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
188 CommandIdx != e; ++CommandIdx) {
190 for (unsigned Op = 1; ; ++Op) {
191 // Scan for the first instruction in the set.
192 std::vector<unsigned>::iterator NIT =
193 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
194 if (NIT == InstIdxs.end()) break; // No commonality.
196 // If this instruction has no more operands, we isn't anything to merge
197 // into this command.
198 const AsmWriterInst *FirstInst =
199 getAsmWriterInstByID(NIT-InstIdxs.begin());
200 if (!FirstInst || FirstInst->Operands.size() == Op)
203 // Otherwise, scan to see if all of the other instructions in this command
204 // set share the operand.
206 // Keep track of the maximum, number of operands or any
207 // instruction we see in the group.
208 size_t MaxSize = FirstInst->Operands.size();
210 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
211 NIT != InstIdxs.end();
212 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
213 // Okay, found another instruction in this command set. If the operand
214 // matches, we're ok, otherwise bail out.
215 const AsmWriterInst *OtherInst =
216 getAsmWriterInstByID(NIT-InstIdxs.begin());
219 OtherInst->Operands.size() > FirstInst->Operands.size())
220 MaxSize = std::max(MaxSize, OtherInst->Operands.size());
222 if (!OtherInst || OtherInst->Operands.size() == Op ||
223 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
230 // Okay, everything in this command set has the same next operand. Add it
231 // to UniqueOperandCommands and remember that it was consumed.
232 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
234 UniqueOperandCommands[CommandIdx] += Command;
235 InstOpsUsed[CommandIdx]++;
239 // Prepend some of the instructions each case is used for onto the case val.
240 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
241 std::string Instrs = InstrsForCase[i];
242 if (Instrs.size() > 70) {
243 Instrs.erase(Instrs.begin()+70, Instrs.end());
248 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
249 UniqueOperandCommands[i];
254 static void UnescapeString(std::string &Str) {
255 for (unsigned i = 0; i != Str.size(); ++i) {
256 if (Str[i] == '\\' && i != Str.size()-1) {
258 default: continue; // Don't execute the code after the switch.
259 case 'a': Str[i] = '\a'; break;
260 case 'b': Str[i] = '\b'; break;
261 case 'e': Str[i] = 27; break;
262 case 'f': Str[i] = '\f'; break;
263 case 'n': Str[i] = '\n'; break;
264 case 'r': Str[i] = '\r'; break;
265 case 't': Str[i] = '\t'; break;
266 case 'v': Str[i] = '\v'; break;
267 case '"': Str[i] = '\"'; break;
268 case '\'': Str[i] = '\''; break;
269 case '\\': Str[i] = '\\'; break;
271 // Nuke the second character.
272 Str.erase(Str.begin()+i+1);
277 /// EmitPrintInstruction - Generate the code for the "printInstruction" method
278 /// implementation. Destroys all instances of AsmWriterInst information, by
279 /// clearing the Instructions vector.
280 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) {
281 Record *AsmWriter = Target.getAsmWriter();
282 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
285 "/// printInstruction - This method is automatically generated by tablegen\n"
286 "/// from the instruction set description.\n"
287 "void " << Target.getName() << ClassName
288 << "::printInstruction(const MCInst *MI, raw_ostream &O) {\n";
290 // Build an aggregate string, and build a table of offsets into it.
291 SequenceToOffsetTable<std::string> StringTable;
293 /// OpcodeInfo - This encodes the index of the string to use for the first
294 /// chunk of the output as well as indices used for operand printing.
295 /// To reduce the number of unhandled cases, we expand the size from 32-bit
296 /// to 32+16 = 48-bit.
297 std::vector<uint64_t> OpcodeInfo;
299 // Add all strings to the string table upfront so it can generate an optimized
301 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
302 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
304 AWI->Operands[0].OperandType ==
305 AsmWriterOperand::isLiteralTextOperand &&
306 !AWI->Operands[0].Str.empty()) {
307 std::string Str = AWI->Operands[0].Str;
309 StringTable.add(Str);
313 StringTable.layout();
315 unsigned MaxStringIdx = 0;
316 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
317 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
320 // Something not handled by the asmwriter printer.
322 } else if (AWI->Operands[0].OperandType !=
323 AsmWriterOperand::isLiteralTextOperand ||
324 AWI->Operands[0].Str.empty()) {
325 // Something handled by the asmwriter printer, but with no leading string.
326 Idx = StringTable.get("");
328 std::string Str = AWI->Operands[0].Str;
330 Idx = StringTable.get(Str);
331 MaxStringIdx = std::max(MaxStringIdx, Idx);
333 // Nuke the string from the operand list. It is now handled!
334 AWI->Operands.erase(AWI->Operands.begin());
337 // Bias offset by one since we want 0 as a sentinel.
338 OpcodeInfo.push_back(Idx+1);
341 // Figure out how many bits we used for the string index.
342 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
344 // To reduce code size, we compactify common instructions into a few bits
345 // in the opcode-indexed table.
346 unsigned BitsLeft = 64-AsmStrBits;
348 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
351 std::vector<std::string> UniqueOperandCommands;
352 std::vector<unsigned> InstIdxs;
353 std::vector<unsigned> NumInstOpsHandled;
354 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
357 // If we ran out of operands to print, we're done.
358 if (UniqueOperandCommands.empty()) break;
360 // Compute the number of bits we need to represent these cases, this is
361 // ceil(log2(numentries)).
362 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
364 // If we don't have enough bits for this operand, don't include it.
365 if (NumBits > BitsLeft) {
366 DEBUG(errs() << "Not enough bits to densely encode " << NumBits
371 // Otherwise, we can include this in the initial lookup table. Add it in.
372 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
373 if (InstIdxs[i] != ~0U) {
374 OpcodeInfo[i] |= (uint64_t)InstIdxs[i] << (64-BitsLeft);
378 // Remove the info about this operand.
379 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
380 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
381 if (!Inst->Operands.empty()) {
382 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
383 assert(NumOps <= Inst->Operands.size() &&
384 "Can't remove this many ops!");
385 Inst->Operands.erase(Inst->Operands.begin(),
386 Inst->Operands.begin()+NumOps);
390 // Remember the handlers for this set of operands.
391 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
395 // We always emit at least one 32-bit table. A second table is emitted if
396 // more bits are needed.
397 O<<" static const uint32_t OpInfo[] = {\n";
398 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
399 O << " " << (OpcodeInfo[i] & 0xffffffff) << "U,\t// "
400 << NumberedInstructions[i]->TheDef->getName() << "\n";
402 // Add a dummy entry so the array init doesn't end with a comma.
407 // Add a second OpInfo table only when it is necessary.
408 // Adjust the type of the second table based on the number of bits needed.
409 O << " static const uint"
410 << ((BitsLeft < 16) ? "32" : (BitsLeft < 24) ? "16" : "8")
411 << "_t OpInfo2[] = {\n";
412 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
413 O << " " << (OpcodeInfo[i] >> 32) << "U,\t// "
414 << NumberedInstructions[i]->TheDef->getName() << "\n";
416 // Add a dummy entry so the array init doesn't end with a comma.
421 // Emit the string itself.
422 O << " const char AsmStrs[] = {\n";
423 StringTable.emit(O, printChar);
426 O << " O << \"\\t\";\n\n";
428 O << " // Emit the opcode for the instruction.\n";
430 // If we have two tables then we need to perform two lookups and combine
431 // the results into a single 64-bit value.
432 O << " uint64_t Bits1 = OpInfo[MI->getOpcode()];\n"
433 << " uint64_t Bits2 = OpInfo2[MI->getOpcode()];\n"
434 << " uint64_t Bits = (Bits2 << 32) | Bits1;\n";
436 // If only one table is used we just need to perform a single lookup.
437 O << " uint32_t Bits = OpInfo[MI->getOpcode()];\n";
439 O << " assert(Bits != 0 && \"Cannot print this instruction.\");\n"
440 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
442 // Output the table driven operand information.
443 BitsLeft = 64-AsmStrBits;
444 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
445 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
447 // Compute the number of bits we need to represent these cases, this is
448 // ceil(log2(numentries)).
449 unsigned NumBits = Log2_32_Ceil(Commands.size());
450 assert(NumBits <= BitsLeft && "consistency error");
452 // Emit code to extract this field from Bits.
453 O << "\n // Fragment " << i << " encoded into " << NumBits
454 << " bits for " << Commands.size() << " unique commands.\n";
456 if (Commands.size() == 2) {
457 // Emit two possibilitys with if/else.
458 O << " if ((Bits >> "
459 << (64-BitsLeft) << ") & "
460 << ((1 << NumBits)-1) << ") {\n"
465 } else if (Commands.size() == 1) {
466 // Emit a single possibility.
467 O << Commands[0] << "\n\n";
469 O << " switch ((Bits >> "
470 << (64-BitsLeft) << ") & "
471 << ((1 << NumBits)-1) << ") {\n"
472 << " default: // unreachable.\n";
474 // Print out all the cases.
475 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
476 O << " case " << i << ":\n";
485 // Okay, delete instructions with no operand info left.
486 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
487 // Entire instruction has been emitted?
488 AsmWriterInst &Inst = Instructions[i];
489 if (Inst.Operands.empty()) {
490 Instructions.erase(Instructions.begin()+i);
496 // Because this is a vector, we want to emit from the end. Reverse all of the
497 // elements in the vector.
498 std::reverse(Instructions.begin(), Instructions.end());
501 // Now that we've emitted all of the operand info that fit into 32 bits, emit
502 // information for those instructions that are left. This is a less dense
503 // encoding, but we expect the main 32-bit table to handle the majority of
505 if (!Instructions.empty()) {
506 // Find the opcode # of inline asm.
507 O << " switch (MI->getOpcode()) {\n";
508 while (!Instructions.empty())
509 EmitInstructions(Instructions, O);
519 emitRegisterNameString(raw_ostream &O, StringRef AltName,
520 const std::vector<CodeGenRegister*> &Registers) {
521 SequenceToOffsetTable<std::string> StringTable;
522 SmallVector<std::string, 4> AsmNames(Registers.size());
523 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
524 const CodeGenRegister &Reg = *Registers[i];
525 std::string &AsmName = AsmNames[i];
527 // "NoRegAltName" is special. We don't need to do a lookup for that,
528 // as it's just a reference to the default register name.
529 if (AltName == "" || AltName == "NoRegAltName") {
530 AsmName = Reg.TheDef->getValueAsString("AsmName");
532 AsmName = Reg.getName();
534 // Make sure the register has an alternate name for this index.
535 std::vector<Record*> AltNameList =
536 Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
538 for (e = AltNameList.size();
539 Idx < e && (AltNameList[Idx]->getName() != AltName);
542 // If the register has an alternate name for this index, use it.
543 // Otherwise, leave it empty as an error flag.
545 std::vector<std::string> AltNames =
546 Reg.TheDef->getValueAsListOfStrings("AltNames");
547 if (AltNames.size() <= Idx)
548 PrintFatalError(Reg.TheDef->getLoc(),
549 (Twine("Register definition missing alt name for '") +
550 AltName + "'.").str());
551 AsmName = AltNames[Idx];
554 StringTable.add(AsmName);
557 StringTable.layout();
558 O << " static const char AsmStrs" << AltName << "[] = {\n";
559 StringTable.emit(O, printChar);
562 O << " static const uint32_t RegAsmOffset" << AltName << "[] = {";
563 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
566 O << StringTable.get(AsmNames[i]) << ", ";
572 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
573 Record *AsmWriter = Target.getAsmWriter();
574 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
575 const std::vector<CodeGenRegister*> &Registers =
576 Target.getRegBank().getRegisters();
577 std::vector<Record*> AltNameIndices = Target.getRegAltNameIndices();
578 bool hasAltNames = AltNameIndices.size() > 1;
581 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
582 "/// from the register set description. This returns the assembler name\n"
583 "/// for the specified register.\n"
584 "const char *" << Target.getName() << ClassName << "::";
586 O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
588 O << "getRegisterName(unsigned RegNo) {\n";
589 O << " assert(RegNo && RegNo < " << (Registers.size()+1)
590 << " && \"Invalid register number!\");\n"
594 for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i)
595 emitRegisterNameString(O, AltNameIndices[i]->getName(), Registers);
597 emitRegisterNameString(O, "", Registers);
600 O << " const uint32_t *RegAsmOffset;\n"
601 << " const char *AsmStrs;\n"
602 << " switch(AltIdx) {\n"
603 << " default: llvm_unreachable(\"Invalid register alt name index!\");\n";
604 for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i) {
605 StringRef Namespace = AltNameIndices[1]->getValueAsString("Namespace");
606 StringRef AltName(AltNameIndices[i]->getName());
607 O << " case " << Namespace << "::" << AltName
609 << " AsmStrs = AsmStrs" << AltName << ";\n"
610 << " RegAsmOffset = RegAsmOffset" << AltName << ";\n"
616 O << " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
617 << " \"Invalid alt name index for register!\");\n"
618 << " return AsmStrs+RegAsmOffset[RegNo-1];\n"
623 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if
624 // they both have the same conditionals. In which case, we cannot print out the
625 // alias for that pattern.
627 std::vector<std::string> Conds;
628 std::map<StringRef, unsigned> OpMap;
630 std::string AsmString;
631 SmallVector<Record*, 4> ReqFeatures;
633 IAPrinter(std::string R, std::string AS)
634 : Result(R), AsmString(AS) {}
636 void addCond(const std::string &C) { Conds.push_back(C); }
638 void addOperand(StringRef Op, unsigned Idx) {
639 assert(Idx < 0xFF && "Index too large!");
642 unsigned getOpIndex(StringRef Op) { return OpMap[Op]; }
643 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
645 void print(raw_ostream &O) {
646 if (Conds.empty() && ReqFeatures.empty()) {
647 O.indent(6) << "return true;\n";
653 for (std::vector<std::string>::iterator
654 I = Conds.begin(), E = Conds.end(); I != E; ++I) {
655 if (I != Conds.begin()) {
664 O.indent(6) << "// " << Result << "\n";
666 // Directly mangle mapped operands into the string. Each operand is
667 // identified by a '$' sign followed by a byte identifying the number of the
668 // operand. We add one to the index to avoid zero bytes.
669 std::pair<StringRef, StringRef> ASM = StringRef(AsmString).split(' ');
670 SmallString<128> OutString = ASM.first;
671 if (!ASM.second.empty()) {
672 raw_svector_ostream OS(OutString);
674 for (StringRef::iterator I = ASM.second.begin(), E = ASM.second.end();
678 StringRef::iterator Start = ++I;
680 ((*I >= 'a' && *I <= 'z') || (*I >= 'A' && *I <= 'Z') ||
681 (*I >= '0' && *I <= '9') || *I == '_'))
683 StringRef Name(Start, I - Start);
684 assert(isOpMapped(Name) && "Unmapped operand!");
685 OS << format("\\x%02X", (unsigned char)getOpIndex(Name) + 1);
693 O.indent(6) << "AsmString = \"" << OutString.str() << "\";\n";
695 O.indent(6) << "break;\n";
699 bool operator==(const IAPrinter &RHS) {
700 if (Conds.size() != RHS.Conds.size())
704 for (std::vector<std::string>::iterator
705 I = Conds.begin(), E = Conds.end(); I != E; ++I)
706 if (*I != RHS.Conds[Idx++])
712 bool operator()(const IAPrinter &RHS) {
713 if (Conds.size() < RHS.Conds.size())
717 for (std::vector<std::string>::iterator
718 I = Conds.begin(), E = Conds.end(); I != E; ++I)
719 if (*I != RHS.Conds[Idx++])
720 return *I < RHS.Conds[Idx++];
726 } // end anonymous namespace
728 static unsigned CountNumOperands(StringRef AsmString) {
730 std::pair<StringRef, StringRef> ASM = AsmString.split(' ');
732 while (!ASM.second.empty()) {
734 ASM = ASM.second.split(' ');
740 static unsigned CountResultNumOperands(StringRef AsmString) {
742 std::pair<StringRef, StringRef> ASM = AsmString.split('\t');
744 if (!ASM.second.empty()) {
745 size_t I = ASM.second.find('{');
746 StringRef Str = ASM.second;
747 if (I != StringRef::npos)
748 Str = ASM.second.substr(I, ASM.second.find('|', I));
750 ASM = Str.split(' ');
754 ASM = ASM.second.split(' ');
755 } while (!ASM.second.empty());
761 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
762 Record *AsmWriter = Target.getAsmWriter();
764 O << "\n#ifdef PRINT_ALIAS_INSTR\n";
765 O << "#undef PRINT_ALIAS_INSTR\n\n";
767 // Emit the method that prints the alias instruction.
768 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
770 std::vector<Record*> AllInstAliases =
771 Records.getAllDerivedDefinitions("InstAlias");
773 // Create a map from the qualified name to a list of potential matches.
774 std::map<std::string, std::vector<CodeGenInstAlias*> > AliasMap;
775 for (std::vector<Record*>::iterator
776 I = AllInstAliases.begin(), E = AllInstAliases.end(); I != E; ++I) {
777 CodeGenInstAlias *Alias = new CodeGenInstAlias(*I, Target);
778 const Record *R = *I;
779 if (!R->getValueAsBit("EmitAlias"))
780 continue; // We were told not to emit the alias, but to emit the aliasee.
781 const DagInit *DI = R->getValueAsDag("ResultInst");
782 const DefInit *Op = cast<DefInit>(DI->getOperator());
783 AliasMap[getQualifiedName(Op->getDef())].push_back(Alias);
786 // A map of which conditions need to be met for each instruction operand
787 // before it can be matched to the mnemonic.
788 std::map<std::string, std::vector<IAPrinter*> > IAPrinterMap;
790 for (std::map<std::string, std::vector<CodeGenInstAlias*> >::iterator
791 I = AliasMap.begin(), E = AliasMap.end(); I != E; ++I) {
792 std::vector<CodeGenInstAlias*> &Aliases = I->second;
794 for (std::vector<CodeGenInstAlias*>::iterator
795 II = Aliases.begin(), IE = Aliases.end(); II != IE; ++II) {
796 const CodeGenInstAlias *CGA = *II;
797 unsigned LastOpNo = CGA->ResultInstOperandIndex.size();
798 unsigned NumResultOps =
799 CountResultNumOperands(CGA->ResultInst->AsmString);
801 // Don't emit the alias if it has more operands than what it's aliasing.
802 if (NumResultOps < CountNumOperands(CGA->AsmString))
805 IAPrinter *IAP = new IAPrinter(CGA->Result->getAsString(),
809 Cond = std::string("MI->getNumOperands() == ") + llvm::utostr(LastOpNo);
812 bool CantHandle = false;
814 for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
815 const CodeGenInstAlias::ResultOperand &RO = CGA->ResultOperands[i];
818 case CodeGenInstAlias::ResultOperand::K_Record: {
819 const Record *Rec = RO.getRecord();
820 StringRef ROName = RO.getName();
823 if (Rec->isSubClassOf("RegisterOperand"))
824 Rec = Rec->getValueAsDef("RegClass");
825 if (Rec->isSubClassOf("RegisterClass")) {
826 Cond = std::string("MI->getOperand(")+llvm::utostr(i)+").isReg()";
829 if (!IAP->isOpMapped(ROName)) {
830 IAP->addOperand(ROName, i);
831 Record *R = CGA->ResultOperands[i].getRecord();
832 if (R->isSubClassOf("RegisterOperand"))
833 R = R->getValueAsDef("RegClass");
834 Cond = std::string("MRI.getRegClass(") + Target.getName() + "::" +
835 R->getName() + "RegClassID)"
836 ".contains(MI->getOperand(" + llvm::utostr(i) + ").getReg())";
839 Cond = std::string("MI->getOperand(") +
840 llvm::utostr(i) + ").getReg() == MI->getOperand(" +
841 llvm::utostr(IAP->getOpIndex(ROName)) + ").getReg()";
845 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
846 // FIXME: We may need to handle these situations.
855 case CodeGenInstAlias::ResultOperand::K_Imm: {
856 std::string Op = "MI->getOperand(" + llvm::utostr(i) + ")";
858 // Just because the alias has an immediate result, doesn't mean the
859 // MCInst will. An MCExpr could be present, for example.
860 IAP->addCond(Op + ".isImm()");
862 Cond = Op + ".getImm() == "
863 + llvm::utostr(CGA->ResultOperands[i].getImm());
867 case CodeGenInstAlias::ResultOperand::K_Reg:
868 // If this is zero_reg, something's playing tricks we're not
869 // equipped to handle.
870 if (!CGA->ResultOperands[i].getRegister()) {
875 Cond = std::string("MI->getOperand(") +
876 llvm::utostr(i) + ").getReg() == " + Target.getName() +
877 "::" + CGA->ResultOperands[i].getRegister()->getName();
885 if (CantHandle) continue;
886 IAPrinterMap[I->first].push_back(IAP);
891 raw_string_ostream HeaderO(Header);
893 HeaderO << "bool " << Target.getName() << ClassName
894 << "::printAliasInstr(const MCInst"
895 << " *MI, raw_ostream &OS) {\n";
898 raw_string_ostream CasesO(Cases);
900 for (std::map<std::string, std::vector<IAPrinter*> >::iterator
901 I = IAPrinterMap.begin(), E = IAPrinterMap.end(); I != E; ++I) {
902 std::vector<IAPrinter*> &IAPs = I->second;
903 std::vector<IAPrinter*> UniqueIAPs;
905 for (std::vector<IAPrinter*>::iterator
906 II = IAPs.begin(), IE = IAPs.end(); II != IE; ++II) {
907 IAPrinter *LHS = *II;
909 for (std::vector<IAPrinter*>::iterator
910 III = IAPs.begin(), IIE = IAPs.end(); III != IIE; ++III) {
911 IAPrinter *RHS = *III;
912 if (LHS != RHS && *LHS == *RHS) {
918 if (!IsDup) UniqueIAPs.push_back(LHS);
921 if (UniqueIAPs.empty()) continue;
923 CasesO.indent(2) << "case " << I->first << ":\n";
925 for (std::vector<IAPrinter*>::iterator
926 II = UniqueIAPs.begin(), IE = UniqueIAPs.end(); II != IE; ++II) {
927 IAPrinter *IAP = *II;
933 CasesO.indent(4) << "return false;\n";
936 if (CasesO.str().empty()) {
938 O << " return false;\n";
940 O << "#endif // PRINT_ALIAS_INSTR\n";
945 O.indent(2) << "const char *AsmString;\n";
946 O.indent(2) << "switch (MI->getOpcode()) {\n";
947 O.indent(2) << "default: return false;\n";
949 O.indent(2) << "}\n\n";
951 // Code that prints the alias, replacing the operands with the ones from the
953 O << " unsigned I = 0;\n";
954 O << " while (AsmString[I] != ' ' && AsmString[I] != '\\0')\n";
956 O << " OS << '\\t' << StringRef(AsmString, I);\n";
958 O << " if (AsmString[I] != '\\0') {\n";
959 O << " OS << '\\t';\n";
961 O << " if (AsmString[I] == '$') {\n";
963 O << " printOperand(MI, unsigned(AsmString[I++]) - 1, OS);\n";
965 O << " OS << AsmString[I++];\n";
967 O << " } while (AsmString[I] != '\\0');\n";
970 O << " return true;\n";
973 O << "#endif // PRINT_ALIAS_INSTR\n";
976 AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) {
977 Record *AsmWriter = Target.getAsmWriter();
978 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
979 E = Target.inst_end();
981 if (!(*I)->AsmString.empty() && (*I)->TheDef->getName() != "PHI")
982 Instructions.push_back(
983 AsmWriterInst(**I, AsmWriter->getValueAsInt("Variant"),
984 AsmWriter->getValueAsInt("OperandSpacing")));
986 // Get the instruction numbering.
987 NumberedInstructions = Target.getInstructionsByEnumValue();
989 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
990 // all machine instructions are necessarily being printed, so there may be
991 // target instructions not in this map.
992 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
993 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
996 void AsmWriterEmitter::run(raw_ostream &O) {
997 EmitPrintInstruction(O);
998 EmitGetRegisterName(O);
999 EmitPrintAliasInstruction(O);
1005 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) {
1006 emitSourceFileHeader("Assembly Writer Source Fragment", OS);
1007 AsmWriterEmitter(RK).run(OS);
1010 } // End llvm namespace