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/SmallString.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/TableGen/Error.h"
25 #include "llvm/TableGen/Record.h"
26 #include "llvm/TableGen/TableGenBackend.h"
33 #define DEBUG_TYPE "asm-writer-emitter"
36 class AsmWriterEmitter {
37 RecordKeeper &Records;
39 std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap;
40 const std::vector<const CodeGenInstruction*> *NumberedInstructions;
41 std::vector<AsmWriterInst> Instructions;
42 std::vector<std::string> PrintMethods;
44 AsmWriterEmitter(RecordKeeper &R);
46 void run(raw_ostream &o);
49 void EmitPrintInstruction(raw_ostream &o);
50 void EmitGetRegisterName(raw_ostream &o);
51 void EmitPrintAliasInstruction(raw_ostream &O);
53 AsmWriterInst *getAsmWriterInstByID(unsigned ID) const {
54 assert(ID < NumberedInstructions->size());
55 std::map<const CodeGenInstruction*, AsmWriterInst*>::const_iterator I =
56 CGIAWIMap.find(NumberedInstructions->at(ID));
57 assert(I != CGIAWIMap.end() && "Didn't find inst!");
60 void FindUniqueOperandCommands(std::vector<std::string> &UOC,
61 std::vector<unsigned> &InstIdxs,
62 std::vector<unsigned> &InstOpsUsed) const;
64 } // end anonymous namespace
66 static void PrintCases(std::vector<std::pair<std::string,
67 AsmWriterOperand> > &OpsToPrint, raw_ostream &O) {
68 O << " case " << OpsToPrint.back().first << ": ";
69 AsmWriterOperand TheOp = OpsToPrint.back().second;
70 OpsToPrint.pop_back();
72 // Check to see if any other operands are identical in this list, and if so,
73 // emit a case label for them.
74 for (unsigned i = OpsToPrint.size(); i != 0; --i)
75 if (OpsToPrint[i-1].second == TheOp) {
76 O << "\n case " << OpsToPrint[i-1].first << ": ";
77 OpsToPrint.erase(OpsToPrint.begin()+i-1);
80 // Finally, emit the code.
86 /// EmitInstructions - Emit the last instruction in the vector and any other
87 /// instructions that are suitably similar to it.
88 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
90 AsmWriterInst FirstInst = Insts.back();
93 std::vector<AsmWriterInst> SimilarInsts;
94 unsigned DifferingOperand = ~0;
95 for (unsigned i = Insts.size(); i != 0; --i) {
96 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
98 if (DifferingOperand == ~0U) // First match!
99 DifferingOperand = DiffOp;
101 // If this differs in the same operand as the rest of the instructions in
102 // this class, move it to the SimilarInsts list.
103 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
104 SimilarInsts.push_back(Insts[i-1]);
105 Insts.erase(Insts.begin()+i-1);
110 O << " case " << FirstInst.CGI->Namespace << "::"
111 << FirstInst.CGI->TheDef->getName() << ":\n";
112 for (const AsmWriterInst &AWI : SimilarInsts)
113 O << " case " << AWI.CGI->Namespace << "::"
114 << AWI.CGI->TheDef->getName() << ":\n";
115 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
116 if (i != DifferingOperand) {
117 // If the operand is the same for all instructions, just print it.
118 O << " " << FirstInst.Operands[i].getCode();
120 // If this is the operand that varies between all of the instructions,
121 // emit a switch for just this operand now.
122 O << " switch (MI->getOpcode()) {\n";
123 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
124 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
125 FirstInst.CGI->TheDef->getName(),
126 FirstInst.Operands[i]));
128 for (const AsmWriterInst &AWI : SimilarInsts) {
129 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
130 AWI.CGI->TheDef->getName(),
133 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
134 while (!OpsToPrint.empty())
135 PrintCases(OpsToPrint, O);
143 void AsmWriterEmitter::
144 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
145 std::vector<unsigned> &InstIdxs,
146 std::vector<unsigned> &InstOpsUsed) const {
147 InstIdxs.assign(NumberedInstructions->size(), ~0U);
149 // This vector parallels UniqueOperandCommands, keeping track of which
150 // instructions each case are used for. It is a comma separated string of
152 std::vector<std::string> InstrsForCase;
153 InstrsForCase.resize(UniqueOperandCommands.size());
154 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
156 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
157 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
159 continue; // PHI, INLINEASM, CFI_INSTRUCTION, etc.
161 if (Inst->Operands.empty())
162 continue; // Instruction already done.
164 std::string Command = " " + Inst->Operands[0].getCode() + "\n";
166 // Check to see if we already have 'Command' in UniqueOperandCommands.
168 bool FoundIt = false;
169 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
170 if (UniqueOperandCommands[idx] == Command) {
172 InstrsForCase[idx] += ", ";
173 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
178 InstIdxs[i] = UniqueOperandCommands.size();
179 UniqueOperandCommands.push_back(std::move(Command));
180 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
182 // This command matches one operand so far.
183 InstOpsUsed.push_back(1);
187 // For each entry of UniqueOperandCommands, there is a set of instructions
188 // that uses it. If the next command of all instructions in the set are
189 // identical, fold it into the command.
190 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
191 CommandIdx != e; ++CommandIdx) {
193 for (unsigned Op = 1; ; ++Op) {
194 // Scan for the first instruction in the set.
195 std::vector<unsigned>::iterator NIT =
196 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
197 if (NIT == InstIdxs.end()) break; // No commonality.
199 // If this instruction has no more operands, we isn't anything to merge
200 // into this command.
201 const AsmWriterInst *FirstInst =
202 getAsmWriterInstByID(NIT-InstIdxs.begin());
203 if (!FirstInst || FirstInst->Operands.size() == Op)
206 // Otherwise, scan to see if all of the other instructions in this command
207 // set share the operand.
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());
218 if (!OtherInst || OtherInst->Operands.size() == Op ||
219 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
226 // Okay, everything in this command set has the same next operand. Add it
227 // to UniqueOperandCommands and remember that it was consumed.
228 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
230 UniqueOperandCommands[CommandIdx] += Command;
231 InstOpsUsed[CommandIdx]++;
235 // Prepend some of the instructions each case is used for onto the case val.
236 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
237 std::string Instrs = InstrsForCase[i];
238 if (Instrs.size() > 70) {
239 Instrs.erase(Instrs.begin()+70, Instrs.end());
244 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
245 UniqueOperandCommands[i];
250 static void UnescapeString(std::string &Str) {
251 for (unsigned i = 0; i != Str.size(); ++i) {
252 if (Str[i] == '\\' && i != Str.size()-1) {
254 default: continue; // Don't execute the code after the switch.
255 case 'a': Str[i] = '\a'; break;
256 case 'b': Str[i] = '\b'; break;
257 case 'e': Str[i] = 27; break;
258 case 'f': Str[i] = '\f'; break;
259 case 'n': Str[i] = '\n'; break;
260 case 'r': Str[i] = '\r'; break;
261 case 't': Str[i] = '\t'; break;
262 case 'v': Str[i] = '\v'; break;
263 case '"': Str[i] = '\"'; break;
264 case '\'': Str[i] = '\''; break;
265 case '\\': Str[i] = '\\'; break;
267 // Nuke the second character.
268 Str.erase(Str.begin()+i+1);
273 /// EmitPrintInstruction - Generate the code for the "printInstruction" method
274 /// implementation. Destroys all instances of AsmWriterInst information, by
275 /// clearing the Instructions vector.
276 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) {
277 Record *AsmWriter = Target.getAsmWriter();
278 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
279 unsigned PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
282 "/// printInstruction - This method is automatically generated by tablegen\n"
283 "/// from the instruction set description.\n"
284 "void " << Target.getName() << ClassName
285 << "::printInstruction(const MCInst *MI, "
286 << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "")
287 << "raw_ostream &O) {\n";
289 // Build an aggregate string, and build a table of offsets into it.
290 SequenceToOffsetTable<std::string> StringTable;
292 /// OpcodeInfo - This encodes the index of the string to use for the first
293 /// chunk of the output as well as indices used for operand printing.
294 std::vector<uint64_t> OpcodeInfo;
295 const unsigned OpcodeInfoBits = 64;
297 // Add all strings to the string table upfront so it can generate an optimized
299 for (const CodeGenInstruction *Inst : *NumberedInstructions) {
300 AsmWriterInst *AWI = CGIAWIMap[Inst];
302 AWI->Operands[0].OperandType ==
303 AsmWriterOperand::isLiteralTextOperand &&
304 !AWI->Operands[0].Str.empty()) {
305 std::string Str = AWI->Operands[0].Str;
307 StringTable.add(Str);
311 StringTable.layout();
313 unsigned MaxStringIdx = 0;
314 for (const CodeGenInstruction *Inst : *NumberedInstructions) {
315 AsmWriterInst *AWI = CGIAWIMap[Inst];
318 // Something not handled by the asmwriter printer.
320 } else if (AWI->Operands[0].OperandType !=
321 AsmWriterOperand::isLiteralTextOperand ||
322 AWI->Operands[0].Str.empty()) {
323 // Something handled by the asmwriter printer, but with no leading string.
324 Idx = StringTable.get("");
326 std::string Str = AWI->Operands[0].Str;
328 Idx = StringTable.get(Str);
329 MaxStringIdx = std::max(MaxStringIdx, Idx);
331 // Nuke the string from the operand list. It is now handled!
332 AWI->Operands.erase(AWI->Operands.begin());
335 // Bias offset by one since we want 0 as a sentinel.
336 OpcodeInfo.push_back(Idx+1);
339 // Figure out how many bits we used for the string index.
340 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
342 // To reduce code size, we compactify common instructions into a few bits
343 // in the opcode-indexed table.
344 unsigned BitsLeft = OpcodeInfoBits-AsmStrBits;
346 std::vector<std::vector<std::string>> TableDrivenOperandPrinters;
349 std::vector<std::string> UniqueOperandCommands;
350 std::vector<unsigned> InstIdxs;
351 std::vector<unsigned> NumInstOpsHandled;
352 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
355 // If we ran out of operands to print, we're done.
356 if (UniqueOperandCommands.empty()) break;
358 // Compute the number of bits we need to represent these cases, this is
359 // ceil(log2(numentries)).
360 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
362 // If we don't have enough bits for this operand, don't include it.
363 if (NumBits > BitsLeft) {
364 DEBUG(errs() << "Not enough bits to densely encode " << NumBits
369 // Otherwise, we can include this in the initial lookup table. Add it in.
370 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
371 if (InstIdxs[i] != ~0U) {
372 OpcodeInfo[i] |= (uint64_t)InstIdxs[i] << (OpcodeInfoBits-BitsLeft);
376 // Remove the info about this operand.
377 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
378 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
379 if (!Inst->Operands.empty()) {
380 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
381 assert(NumOps <= Inst->Operands.size() &&
382 "Can't remove this many ops!");
383 Inst->Operands.erase(Inst->Operands.begin(),
384 Inst->Operands.begin()+NumOps);
388 // Remember the handlers for this set of operands.
389 TableDrivenOperandPrinters.push_back(std::move(UniqueOperandCommands));
392 // Emit the string table itself.
393 O << " static const char AsmStrs[] = {\n";
394 StringTable.emit(O, printChar);
397 // Emit the lookup tables in pieces to minimize wasted bytes.
398 unsigned BytesNeeded = ((OpcodeInfoBits - BitsLeft) + 7) / 8;
399 unsigned Table = 0, Shift = 0;
400 SmallString<128> BitsString;
401 raw_svector_ostream BitsOS(BitsString);
402 // If the total bits is more than 32-bits we need to use a 64-bit type.
403 BitsOS << " uint" << ((BitsLeft < (OpcodeInfoBits - 32)) ? 64 : 32)
405 while (BytesNeeded != 0) {
406 // Figure out how big this table section needs to be, but no bigger than 4.
407 unsigned TableSize = std::min(1 << Log2_32(BytesNeeded), 4);
408 BytesNeeded -= TableSize;
409 TableSize *= 8; // Convert to bits;
410 uint64_t Mask = (1ULL << TableSize) - 1;
411 O << " static const uint" << TableSize << "_t OpInfo" << Table
413 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
414 O << " " << ((OpcodeInfo[i] >> Shift) & Mask) << "U,\t// "
415 << NumberedInstructions->at(i)->TheDef->getName() << "\n";
418 // Emit string to combine the individual table lookups.
419 BitsOS << " Bits |= ";
420 // If the total bits is more than 32-bits we need to use a 64-bit type.
421 if (BitsLeft < (OpcodeInfoBits - 32))
422 BitsOS << "(uint64_t)";
423 BitsOS << "OpInfo" << Table << "[MI->getOpcode()] << " << Shift << ";\n";
424 // Prepare the shift for the next iteration and increment the table count.
429 // Emit the initial tab character.
430 O << " O << \"\\t\";\n\n";
432 O << " // Emit the opcode for the instruction.\n";
435 // Emit the starting string.
436 O << " assert(Bits != 0 && \"Cannot print this instruction.\");\n"
437 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
439 // Output the table driven operand information.
440 BitsLeft = OpcodeInfoBits-AsmStrBits;
441 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
442 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
444 // Compute the number of bits we need to represent these cases, this is
445 // ceil(log2(numentries)).
446 unsigned NumBits = Log2_32_Ceil(Commands.size());
447 assert(NumBits <= BitsLeft && "consistency error");
449 // Emit code to extract this field from Bits.
450 O << "\n // Fragment " << i << " encoded into " << NumBits
451 << " bits for " << Commands.size() << " unique commands.\n";
453 if (Commands.size() == 2) {
454 // Emit two possibilitys with if/else.
455 O << " if ((Bits >> "
456 << (OpcodeInfoBits-BitsLeft) << ") & "
457 << ((1 << NumBits)-1) << ") {\n"
462 } else if (Commands.size() == 1) {
463 // Emit a single possibility.
464 O << Commands[0] << "\n\n";
466 O << " switch ((Bits >> "
467 << (OpcodeInfoBits-BitsLeft) << ") & "
468 << ((1 << NumBits)-1) << ") {\n"
469 << " default: llvm_unreachable(\"Invalid command number.\");\n";
471 // Print out all the cases.
472 for (unsigned j = 0, e = Commands.size(); j != e; ++j) {
473 O << " case " << j << ":\n";
482 // Okay, delete instructions with no operand info left.
483 auto I = std::remove_if(Instructions.begin(), Instructions.end(),
484 [](AsmWriterInst &Inst) {
485 return Inst.Operands.empty();
487 Instructions.erase(I, Instructions.end());
490 // Because this is a vector, we want to emit from the end. Reverse all of the
491 // elements in the vector.
492 std::reverse(Instructions.begin(), Instructions.end());
495 // Now that we've emitted all of the operand info that fit into 64 bits, emit
496 // information for those instructions that are left. This is a less dense
497 // encoding, but we expect the main 64-bit table to handle the majority of
499 if (!Instructions.empty()) {
500 // Find the opcode # of inline asm.
501 O << " switch (MI->getOpcode()) {\n";
502 while (!Instructions.empty())
503 EmitInstructions(Instructions, O);
512 static const char *getMinimalTypeForRange(uint64_t Range) {
513 assert(Range < 0xFFFFFFFFULL && "Enum too large");
522 emitRegisterNameString(raw_ostream &O, StringRef AltName,
523 const std::deque<CodeGenRegister> &Registers) {
524 SequenceToOffsetTable<std::string> StringTable;
525 SmallVector<std::string, 4> AsmNames(Registers.size());
527 for (const auto &Reg : Registers) {
528 std::string &AsmName = AsmNames[i++];
530 // "NoRegAltName" is special. We don't need to do a lookup for that,
531 // as it's just a reference to the default register name.
532 if (AltName == "" || AltName == "NoRegAltName") {
533 AsmName = Reg.TheDef->getValueAsString("AsmName");
535 AsmName = Reg.getName();
537 // Make sure the register has an alternate name for this index.
538 std::vector<Record*> AltNameList =
539 Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
541 for (e = AltNameList.size();
542 Idx < e && (AltNameList[Idx]->getName() != AltName);
545 // If the register has an alternate name for this index, use it.
546 // Otherwise, leave it empty as an error flag.
548 std::vector<std::string> AltNames =
549 Reg.TheDef->getValueAsListOfStrings("AltNames");
550 if (AltNames.size() <= Idx)
551 PrintFatalError(Reg.TheDef->getLoc(),
552 "Register definition missing alt name for '" +
554 AsmName = AltNames[Idx];
557 StringTable.add(AsmName);
560 StringTable.layout();
561 O << " static const char AsmStrs" << AltName << "[] = {\n";
562 StringTable.emit(O, printChar);
565 O << " static const " << getMinimalTypeForRange(StringTable.size()-1)
566 << " RegAsmOffset" << AltName << "[] = {";
567 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
570 O << StringTable.get(AsmNames[i]) << ", ";
576 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
577 Record *AsmWriter = Target.getAsmWriter();
578 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
579 const auto &Registers = Target.getRegBank().getRegisters();
580 std::vector<Record*> AltNameIndices = Target.getRegAltNameIndices();
581 bool hasAltNames = AltNameIndices.size() > 1;
582 std::string Namespace =
583 Registers.front().TheDef->getValueAsString("Namespace");
586 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
587 "/// from the register set description. This returns the assembler name\n"
588 "/// for the specified register.\n"
589 "const char *" << Target.getName() << ClassName << "::";
591 O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
593 O << "getRegisterName(unsigned RegNo) {\n";
594 O << " assert(RegNo && RegNo < " << (Registers.size()+1)
595 << " && \"Invalid register number!\");\n"
599 for (const Record *R : AltNameIndices)
600 emitRegisterNameString(O, R->getName(), Registers);
602 emitRegisterNameString(O, "", Registers);
605 O << " switch(AltIdx) {\n"
606 << " default: llvm_unreachable(\"Invalid register alt name index!\");\n";
607 for (const Record *R : AltNameIndices) {
608 std::string AltName(R->getName());
609 std::string Prefix = !Namespace.empty() ? Namespace + "::" : "";
610 O << " case " << Prefix << AltName << ":\n"
611 << " assert(*(AsmStrs" << AltName << "+RegAsmOffset"
612 << AltName << "[RegNo-1]) &&\n"
613 << " \"Invalid alt name index for register!\");\n"
614 << " return AsmStrs" << AltName << "+RegAsmOffset"
615 << AltName << "[RegNo-1];\n";
619 O << " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
620 << " \"Invalid alt name index for register!\");\n"
621 << " return AsmStrs+RegAsmOffset[RegNo-1];\n";
627 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if
628 // they both have the same conditionals. In which case, we cannot print out the
629 // alias for that pattern.
631 std::vector<std::string> Conds;
632 std::map<StringRef, std::pair<int, int>> OpMap;
633 SmallVector<Record*, 4> ReqFeatures;
636 std::string AsmString;
638 IAPrinter(std::string R, std::string AS) : Result(R), AsmString(AS) {}
640 void addCond(const std::string &C) { Conds.push_back(C); }
642 void addOperand(StringRef Op, int OpIdx, int PrintMethodIdx = -1) {
643 assert(OpIdx >= 0 && OpIdx < 0xFE && "Idx out of range");
644 assert(PrintMethodIdx >= -1 && PrintMethodIdx < 0xFF &&
646 OpMap[Op] = std::make_pair(OpIdx, PrintMethodIdx);
649 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
650 int getOpIndex(StringRef Op) { return OpMap[Op].first; }
651 std::pair<int, int> &getOpData(StringRef Op) { return OpMap[Op]; }
653 std::pair<StringRef, StringRef::iterator> parseName(StringRef::iterator Start,
654 StringRef::iterator End) {
655 StringRef::iterator I = Start;
656 StringRef::iterator Next;
660 while (I != End && *I != '}')
667 // $name, just eat the usual suspects.
669 ((*I >= 'a' && *I <= 'z') || (*I >= 'A' && *I <= 'Z') ||
670 (*I >= '0' && *I <= '9') || *I == '_'))
675 return std::make_pair(StringRef(Start, I - Start), Next);
678 void print(raw_ostream &O) {
679 if (Conds.empty() && ReqFeatures.empty()) {
680 O.indent(6) << "return true;\n";
686 for (std::vector<std::string>::iterator
687 I = Conds.begin(), E = Conds.end(); I != E; ++I) {
688 if (I != Conds.begin()) {
697 O.indent(6) << "// " << Result << "\n";
699 // Directly mangle mapped operands into the string. Each operand is
700 // identified by a '$' sign followed by a byte identifying the number of the
701 // operand. We add one to the index to avoid zero bytes.
702 StringRef ASM(AsmString);
703 SmallString<128> OutString;
704 raw_svector_ostream OS(OutString);
705 for (StringRef::iterator I = ASM.begin(), E = ASM.end(); I != E;) {
709 std::tie(Name, I) = parseName(++I, E);
710 assert(isOpMapped(Name) && "Unmapped operand!");
712 int OpIndex, PrintIndex;
713 std::tie(OpIndex, PrintIndex) = getOpData(Name);
714 if (PrintIndex == -1) {
715 // Can use the default printOperand route.
716 OS << format("\\x%02X", (unsigned char)OpIndex + 1);
718 // 3 bytes if a PrintMethod is needed: 0xFF, the MCInst operand
719 // number, and which of our pre-detected Methods to call.
720 OS << format("\\xFF\\x%02X\\x%02X", OpIndex + 1, PrintIndex + 1);
727 O.indent(6) << "AsmString = \"" << OutString << "\";\n";
729 O.indent(6) << "break;\n";
733 bool operator==(const IAPrinter &RHS) const {
734 if (Conds.size() != RHS.Conds.size())
738 for (const auto &str : Conds)
739 if (str != RHS.Conds[Idx++])
746 } // end anonymous namespace
748 static unsigned CountNumOperands(StringRef AsmString, unsigned Variant) {
749 std::string FlatAsmString =
750 CodeGenInstruction::FlattenAsmStringVariants(AsmString, Variant);
751 AsmString = FlatAsmString;
753 return AsmString.count(' ') + AsmString.count('\t');
757 struct AliasPriorityComparator {
758 typedef std::pair<CodeGenInstAlias, int> ValueType;
759 bool operator()(const ValueType &LHS, const ValueType &RHS) {
760 if (LHS.second == RHS.second) {
761 // We don't actually care about the order, but for consistency it
762 // shouldn't depend on pointer comparisons.
763 return LHS.first.TheDef->getName() < RHS.first.TheDef->getName();
766 // Aliases with larger priorities should be considered first.
767 return LHS.second > RHS.second;
773 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
774 Record *AsmWriter = Target.getAsmWriter();
776 O << "\n#ifdef PRINT_ALIAS_INSTR\n";
777 O << "#undef PRINT_ALIAS_INSTR\n\n";
779 //////////////////////////////
780 // Gather information about aliases we need to print
781 //////////////////////////////
783 // Emit the method that prints the alias instruction.
784 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
785 unsigned Variant = AsmWriter->getValueAsInt("Variant");
786 unsigned PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
788 std::vector<Record*> AllInstAliases =
789 Records.getAllDerivedDefinitions("InstAlias");
791 // Create a map from the qualified name to a list of potential matches.
792 typedef std::set<std::pair<CodeGenInstAlias, int>, AliasPriorityComparator>
794 std::map<std::string, AliasWithPriority> AliasMap;
795 for (Record *R : AllInstAliases) {
796 int Priority = R->getValueAsInt("EmitPriority");
798 continue; // Aliases with priority 0 are never emitted.
800 const DagInit *DI = R->getValueAsDag("ResultInst");
801 const DefInit *Op = cast<DefInit>(DI->getOperator());
802 AliasMap[getQualifiedName(Op->getDef())].insert(
803 std::make_pair(CodeGenInstAlias(R, Variant, Target), Priority));
806 // A map of which conditions need to be met for each instruction operand
807 // before it can be matched to the mnemonic.
808 std::map<std::string, std::vector<IAPrinter>> IAPrinterMap;
810 // A list of MCOperandPredicates for all operands in use, and the reverse map
811 std::vector<const Record*> MCOpPredicates;
812 DenseMap<const Record*, unsigned> MCOpPredicateMap;
814 for (auto &Aliases : AliasMap) {
815 for (auto &Alias : Aliases.second) {
816 const CodeGenInstAlias &CGA = Alias.first;
817 unsigned LastOpNo = CGA.ResultInstOperandIndex.size();
818 unsigned NumResultOps =
819 CountNumOperands(CGA.ResultInst->AsmString, Variant);
821 // Don't emit the alias if it has more operands than what it's aliasing.
822 if (NumResultOps < CountNumOperands(CGA.AsmString, Variant))
825 IAPrinter IAP(CGA.Result->getAsString(), CGA.AsmString);
827 unsigned NumMIOps = 0;
828 for (auto &Operand : CGA.ResultOperands)
829 NumMIOps += Operand.getMINumOperands();
832 Cond = std::string("MI->getNumOperands() == ") + llvm::utostr(NumMIOps);
835 bool CantHandle = false;
837 unsigned MIOpNum = 0;
838 for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
839 std::string Op = "MI->getOperand(" + llvm::utostr(MIOpNum) + ")";
841 const CodeGenInstAlias::ResultOperand &RO = CGA.ResultOperands[i];
844 case CodeGenInstAlias::ResultOperand::K_Record: {
845 const Record *Rec = RO.getRecord();
846 StringRef ROName = RO.getName();
847 int PrintMethodIdx = -1;
849 // These two may have a PrintMethod, which we want to record (if it's
850 // the first time we've seen it) and provide an index for the aliasing
852 if (Rec->isSubClassOf("RegisterOperand") ||
853 Rec->isSubClassOf("Operand")) {
854 std::string PrintMethod = Rec->getValueAsString("PrintMethod");
855 if (PrintMethod != "" && PrintMethod != "printOperand") {
856 PrintMethodIdx = std::find(PrintMethods.begin(),
857 PrintMethods.end(), PrintMethod) -
858 PrintMethods.begin();
859 if (static_cast<unsigned>(PrintMethodIdx) == PrintMethods.size())
860 PrintMethods.push_back(PrintMethod);
864 if (Rec->isSubClassOf("RegisterOperand"))
865 Rec = Rec->getValueAsDef("RegClass");
866 if (Rec->isSubClassOf("RegisterClass")) {
867 IAP.addCond(Op + ".isReg()");
869 if (!IAP.isOpMapped(ROName)) {
870 IAP.addOperand(ROName, MIOpNum, PrintMethodIdx);
871 Record *R = CGA.ResultOperands[i].getRecord();
872 if (R->isSubClassOf("RegisterOperand"))
873 R = R->getValueAsDef("RegClass");
874 Cond = std::string("MRI.getRegClass(") + Target.getName() + "::" +
875 R->getName() + "RegClassID)"
876 ".contains(" + Op + ".getReg())";
878 Cond = Op + ".getReg() == MI->getOperand(" +
879 llvm::utostr(IAP.getOpIndex(ROName)) + ").getReg()";
882 // Assume all printable operands are desired for now. This can be
883 // overridden in the InstAlias instantiation if necessary.
884 IAP.addOperand(ROName, MIOpNum, PrintMethodIdx);
886 // There might be an additional predicate on the MCOperand
887 unsigned Entry = MCOpPredicateMap[Rec];
889 if (!Rec->isValueUnset("MCOperandPredicate")) {
890 MCOpPredicates.push_back(Rec);
891 Entry = MCOpPredicates.size();
892 MCOpPredicateMap[Rec] = Entry;
894 break; // No conditions on this operand at all
896 Cond = Target.getName() + ClassName + "ValidateMCOperand(" +
897 Op + ", STI, " + llvm::utostr(Entry) + ")";
899 // for all subcases of ResultOperand::K_Record:
903 case CodeGenInstAlias::ResultOperand::K_Imm: {
904 // Just because the alias has an immediate result, doesn't mean the
905 // MCInst will. An MCExpr could be present, for example.
906 IAP.addCond(Op + ".isImm()");
908 Cond = Op + ".getImm() == " +
909 llvm::utostr(CGA.ResultOperands[i].getImm());
913 case CodeGenInstAlias::ResultOperand::K_Reg:
914 // If this is zero_reg, something's playing tricks we're not
915 // equipped to handle.
916 if (!CGA.ResultOperands[i].getRegister()) {
921 Cond = Op + ".getReg() == " + Target.getName() + "::" +
922 CGA.ResultOperands[i].getRegister()->getName();
927 MIOpNum += RO.getMINumOperands();
930 if (CantHandle) continue;
931 IAPrinterMap[Aliases.first].push_back(std::move(IAP));
935 //////////////////////////////
936 // Write out the printAliasInstr function
937 //////////////////////////////
940 raw_string_ostream HeaderO(Header);
942 HeaderO << "bool " << Target.getName() << ClassName
943 << "::printAliasInstr(const MCInst"
944 << " *MI, " << (PassSubtarget ? "const MCSubtargetInfo &STI, " : "")
945 << "raw_ostream &OS) {\n";
948 raw_string_ostream CasesO(Cases);
950 for (auto &Entry : IAPrinterMap) {
951 std::vector<IAPrinter> &IAPs = Entry.second;
952 std::vector<IAPrinter*> UniqueIAPs;
954 for (auto &LHS : IAPs) {
956 for (const auto &RHS : IAPs) {
957 if (&LHS != &RHS && LHS == RHS) {
964 UniqueIAPs.push_back(&LHS);
967 if (UniqueIAPs.empty()) continue;
969 CasesO.indent(2) << "case " << Entry.first << ":\n";
971 for (IAPrinter *IAP : UniqueIAPs) {
977 CasesO.indent(4) << "return false;\n";
980 if (CasesO.str().empty()) {
982 O << " return false;\n";
984 O << "#endif // PRINT_ALIAS_INSTR\n";
988 if (!MCOpPredicates.empty())
989 O << "static bool " << Target.getName() << ClassName
990 << "ValidateMCOperand(const MCOperand &MCOp,\n"
991 << " const MCSubtargetInfo &STI,\n"
992 << " unsigned PredicateIndex);\n";
995 O.indent(2) << "const char *AsmString;\n";
996 O.indent(2) << "switch (MI->getOpcode()) {\n";
997 O.indent(2) << "default: return false;\n";
999 O.indent(2) << "}\n\n";
1001 // Code that prints the alias, replacing the operands with the ones from the
1003 O << " unsigned I = 0;\n";
1004 O << " while (AsmString[I] != ' ' && AsmString[I] != '\t' &&\n";
1005 O << " AsmString[I] != '\\0')\n";
1007 O << " OS << '\\t' << StringRef(AsmString, I);\n";
1009 O << " if (AsmString[I] != '\\0') {\n";
1010 O << " OS << '\\t';\n";
1012 O << " if (AsmString[I] == '$') {\n";
1014 O << " if (AsmString[I] == (char)0xff) {\n";
1016 O << " int OpIdx = AsmString[I++] - 1;\n";
1017 O << " int PrintMethodIdx = AsmString[I++] - 1;\n";
1018 O << " printCustomAliasOperand(MI, OpIdx, PrintMethodIdx, ";
1019 O << (PassSubtarget ? "STI, " : "");
1022 O << " printOperand(MI, unsigned(AsmString[I++]) - 1, ";
1023 O << (PassSubtarget ? "STI, " : "");
1026 O << " OS << AsmString[I++];\n";
1028 O << " } while (AsmString[I] != '\\0');\n";
1031 O << " return true;\n";
1034 //////////////////////////////
1035 // Write out the printCustomAliasOperand function
1036 //////////////////////////////
1038 O << "void " << Target.getName() << ClassName << "::"
1039 << "printCustomAliasOperand(\n"
1040 << " const MCInst *MI, unsigned OpIdx,\n"
1041 << " unsigned PrintMethodIdx,\n"
1042 << (PassSubtarget ? " const MCSubtargetInfo &STI,\n" : "")
1043 << " raw_ostream &OS) {\n";
1044 if (PrintMethods.empty())
1045 O << " llvm_unreachable(\"Unknown PrintMethod kind\");\n";
1047 O << " switch (PrintMethodIdx) {\n"
1049 << " llvm_unreachable(\"Unknown PrintMethod kind\");\n"
1052 for (unsigned i = 0; i < PrintMethods.size(); ++i) {
1053 O << " case " << i << ":\n"
1054 << " " << PrintMethods[i] << "(MI, OpIdx, "
1055 << (PassSubtarget ? "STI, " : "") << "OS);\n"
1062 if (!MCOpPredicates.empty()) {
1063 O << "static bool " << Target.getName() << ClassName
1064 << "ValidateMCOperand(const MCOperand &MCOp,\n"
1065 << " const MCSubtargetInfo &STI,\n"
1066 << " unsigned PredicateIndex) {\n"
1067 << " switch (PredicateIndex) {\n"
1069 << " llvm_unreachable(\"Unknown MCOperandPredicate kind\");\n"
1072 for (unsigned i = 0; i < MCOpPredicates.size(); ++i) {
1073 Init *MCOpPred = MCOpPredicates[i]->getValueInit("MCOperandPredicate");
1074 if (StringInit *SI = dyn_cast<StringInit>(MCOpPred)) {
1075 O << " case " << i + 1 << ": {\n"
1076 << SI->getValue() << "\n"
1079 llvm_unreachable("Unexpected MCOperandPredicate field!");
1085 O << "#endif // PRINT_ALIAS_INSTR\n";
1088 AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) {
1089 Record *AsmWriter = Target.getAsmWriter();
1090 unsigned Variant = AsmWriter->getValueAsInt("Variant");
1091 unsigned PassSubtarget = AsmWriter->getValueAsInt("PassSubtarget");
1092 for (const CodeGenInstruction *I : Target.instructions())
1093 if (!I->AsmString.empty() && I->TheDef->getName() != "PHI")
1094 Instructions.emplace_back(*I, Variant, PassSubtarget);
1096 // Get the instruction numbering.
1097 NumberedInstructions = &Target.getInstructionsByEnumValue();
1099 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
1100 // all machine instructions are necessarily being printed, so there may be
1101 // target instructions not in this map.
1102 for (AsmWriterInst &AWI : Instructions)
1103 CGIAWIMap.insert(std::make_pair(AWI.CGI, &AWI));
1106 void AsmWriterEmitter::run(raw_ostream &O) {
1107 EmitPrintInstruction(O);
1108 EmitGetRegisterName(O);
1109 EmitPrintAliasInstruction(O);
1115 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) {
1116 emitSourceFileHeader("Assembly Writer Source Fragment", OS);
1117 AsmWriterEmitter(RK).run(OS);
1120 } // End llvm namespace