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;
43 AsmWriterEmitter(RecordKeeper &R);
45 void run(raw_ostream &o);
48 void EmitPrintInstruction(raw_ostream &o);
49 void EmitGetRegisterName(raw_ostream &o);
50 void EmitPrintAliasInstruction(raw_ostream &O);
52 AsmWriterInst *getAsmWriterInstByID(unsigned ID) const {
53 assert(ID < NumberedInstructions->size());
54 std::map<const CodeGenInstruction*, AsmWriterInst*>::const_iterator I =
55 CGIAWIMap.find(NumberedInstructions->at(ID));
56 assert(I != CGIAWIMap.end() && "Didn't find inst!");
59 void FindUniqueOperandCommands(std::vector<std::string> &UOC,
60 std::vector<unsigned> &InstIdxs,
61 std::vector<unsigned> &InstOpsUsed) const;
63 } // end anonymous namespace
65 static void PrintCases(std::vector<std::pair<std::string,
66 AsmWriterOperand> > &OpsToPrint, raw_ostream &O) {
67 O << " case " << OpsToPrint.back().first << ": ";
68 AsmWriterOperand TheOp = OpsToPrint.back().second;
69 OpsToPrint.pop_back();
71 // Check to see if any other operands are identical in this list, and if so,
72 // emit a case label for them.
73 for (unsigned i = OpsToPrint.size(); i != 0; --i)
74 if (OpsToPrint[i-1].second == TheOp) {
75 O << "\n case " << OpsToPrint[i-1].first << ": ";
76 OpsToPrint.erase(OpsToPrint.begin()+i-1);
79 // Finally, emit the code.
85 /// EmitInstructions - Emit the last instruction in the vector and any other
86 /// instructions that are suitably similar to it.
87 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
89 AsmWriterInst FirstInst = Insts.back();
92 std::vector<AsmWriterInst> SimilarInsts;
93 unsigned DifferingOperand = ~0;
94 for (unsigned i = Insts.size(); i != 0; --i) {
95 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
97 if (DifferingOperand == ~0U) // First match!
98 DifferingOperand = DiffOp;
100 // If this differs in the same operand as the rest of the instructions in
101 // this class, move it to the SimilarInsts list.
102 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
103 SimilarInsts.push_back(Insts[i-1]);
104 Insts.erase(Insts.begin()+i-1);
109 O << " case " << FirstInst.CGI->Namespace << "::"
110 << FirstInst.CGI->TheDef->getName() << ":\n";
111 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
112 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
113 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
114 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
115 if (i != DifferingOperand) {
116 // If the operand is the same for all instructions, just print it.
117 O << " " << FirstInst.Operands[i].getCode();
119 // If this is the operand that varies between all of the instructions,
120 // emit a switch for just this operand now.
121 O << " switch (MI->getOpcode()) {\n";
122 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
123 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
124 FirstInst.CGI->TheDef->getName(),
125 FirstInst.Operands[i]));
127 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
128 AsmWriterInst &AWI = SimilarInsts[si];
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.
162 if (Inst->Operands.empty())
163 continue; // Instruction already done.
165 Command = " " + Inst->Operands[0].getCode() + "\n";
167 // Check to see if we already have 'Command' in UniqueOperandCommands.
169 bool FoundIt = false;
170 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
171 if (UniqueOperandCommands[idx] == Command) {
173 InstrsForCase[idx] += ", ";
174 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
179 InstIdxs[i] = UniqueOperandCommands.size();
180 UniqueOperandCommands.push_back(Command);
181 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
183 // This command matches one operand so far.
184 InstOpsUsed.push_back(1);
188 // For each entry of UniqueOperandCommands, there is a set of instructions
189 // that uses it. If the next command of all instructions in the set are
190 // identical, fold it into the command.
191 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
192 CommandIdx != e; ++CommandIdx) {
194 for (unsigned Op = 1; ; ++Op) {
195 // Scan for the first instruction in the set.
196 std::vector<unsigned>::iterator NIT =
197 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
198 if (NIT == InstIdxs.end()) break; // No commonality.
200 // If this instruction has no more operands, we isn't anything to merge
201 // into this command.
202 const AsmWriterInst *FirstInst =
203 getAsmWriterInstByID(NIT-InstIdxs.begin());
204 if (!FirstInst || FirstInst->Operands.size() == Op)
207 // Otherwise, scan to see if all of the other instructions in this command
208 // set share the operand.
210 // Keep track of the maximum, number of operands or any
211 // instruction we see in the group.
212 size_t MaxSize = FirstInst->Operands.size();
214 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
215 NIT != InstIdxs.end();
216 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
217 // Okay, found another instruction in this command set. If the operand
218 // matches, we're ok, otherwise bail out.
219 const AsmWriterInst *OtherInst =
220 getAsmWriterInstByID(NIT-InstIdxs.begin());
223 OtherInst->Operands.size() > FirstInst->Operands.size())
224 MaxSize = std::max(MaxSize, OtherInst->Operands.size());
226 if (!OtherInst || OtherInst->Operands.size() == Op ||
227 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
234 // Okay, everything in this command set has the same next operand. Add it
235 // to UniqueOperandCommands and remember that it was consumed.
236 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
238 UniqueOperandCommands[CommandIdx] += Command;
239 InstOpsUsed[CommandIdx]++;
243 // Prepend some of the instructions each case is used for onto the case val.
244 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
245 std::string Instrs = InstrsForCase[i];
246 if (Instrs.size() > 70) {
247 Instrs.erase(Instrs.begin()+70, Instrs.end());
252 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
253 UniqueOperandCommands[i];
258 static void UnescapeString(std::string &Str) {
259 for (unsigned i = 0; i != Str.size(); ++i) {
260 if (Str[i] == '\\' && i != Str.size()-1) {
262 default: continue; // Don't execute the code after the switch.
263 case 'a': Str[i] = '\a'; break;
264 case 'b': Str[i] = '\b'; break;
265 case 'e': Str[i] = 27; break;
266 case 'f': Str[i] = '\f'; break;
267 case 'n': Str[i] = '\n'; break;
268 case 'r': Str[i] = '\r'; break;
269 case 't': Str[i] = '\t'; break;
270 case 'v': Str[i] = '\v'; break;
271 case '"': Str[i] = '\"'; break;
272 case '\'': Str[i] = '\''; break;
273 case '\\': Str[i] = '\\'; break;
275 // Nuke the second character.
276 Str.erase(Str.begin()+i+1);
281 /// EmitPrintInstruction - Generate the code for the "printInstruction" method
282 /// implementation. Destroys all instances of AsmWriterInst information, by
283 /// clearing the Instructions vector.
284 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) {
285 Record *AsmWriter = Target.getAsmWriter();
286 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
289 "/// printInstruction - This method is automatically generated by tablegen\n"
290 "/// from the instruction set description.\n"
291 "void " << Target.getName() << ClassName
292 << "::printInstruction(const MCInst *MI, raw_ostream &O) {\n";
294 // Build an aggregate string, and build a table of offsets into it.
295 SequenceToOffsetTable<std::string> StringTable;
297 /// OpcodeInfo - This encodes the index of the string to use for the first
298 /// chunk of the output as well as indices used for operand printing.
299 /// To reduce the number of unhandled cases, we expand the size from 32-bit
300 /// to 32+16 = 48-bit.
301 std::vector<uint64_t> OpcodeInfo;
303 // Add all strings to the string table upfront so it can generate an optimized
305 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
306 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions->at(i)];
308 AWI->Operands[0].OperandType ==
309 AsmWriterOperand::isLiteralTextOperand &&
310 !AWI->Operands[0].Str.empty()) {
311 std::string Str = AWI->Operands[0].Str;
313 StringTable.add(Str);
317 StringTable.layout();
319 unsigned MaxStringIdx = 0;
320 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
321 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions->at(i)];
324 // Something not handled by the asmwriter printer.
326 } else if (AWI->Operands[0].OperandType !=
327 AsmWriterOperand::isLiteralTextOperand ||
328 AWI->Operands[0].Str.empty()) {
329 // Something handled by the asmwriter printer, but with no leading string.
330 Idx = StringTable.get("");
332 std::string Str = AWI->Operands[0].Str;
334 Idx = StringTable.get(Str);
335 MaxStringIdx = std::max(MaxStringIdx, Idx);
337 // Nuke the string from the operand list. It is now handled!
338 AWI->Operands.erase(AWI->Operands.begin());
341 // Bias offset by one since we want 0 as a sentinel.
342 OpcodeInfo.push_back(Idx+1);
345 // Figure out how many bits we used for the string index.
346 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
348 // To reduce code size, we compactify common instructions into a few bits
349 // in the opcode-indexed table.
350 unsigned BitsLeft = 64-AsmStrBits;
352 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
355 std::vector<std::string> UniqueOperandCommands;
356 std::vector<unsigned> InstIdxs;
357 std::vector<unsigned> NumInstOpsHandled;
358 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
361 // If we ran out of operands to print, we're done.
362 if (UniqueOperandCommands.empty()) break;
364 // Compute the number of bits we need to represent these cases, this is
365 // ceil(log2(numentries)).
366 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
368 // If we don't have enough bits for this operand, don't include it.
369 if (NumBits > BitsLeft) {
370 DEBUG(errs() << "Not enough bits to densely encode " << NumBits
375 // Otherwise, we can include this in the initial lookup table. Add it in.
376 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
377 if (InstIdxs[i] != ~0U) {
378 OpcodeInfo[i] |= (uint64_t)InstIdxs[i] << (64-BitsLeft);
382 // Remove the info about this operand.
383 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
384 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
385 if (!Inst->Operands.empty()) {
386 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
387 assert(NumOps <= Inst->Operands.size() &&
388 "Can't remove this many ops!");
389 Inst->Operands.erase(Inst->Operands.begin(),
390 Inst->Operands.begin()+NumOps);
394 // Remember the handlers for this set of operands.
395 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
399 // We always emit at least one 32-bit table. A second table is emitted if
400 // more bits are needed.
401 O<<" static const uint32_t OpInfo[] = {\n";
402 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
403 O << " " << (OpcodeInfo[i] & 0xffffffff) << "U,\t// "
404 << NumberedInstructions->at(i)->TheDef->getName() << "\n";
406 // Add a dummy entry so the array init doesn't end with a comma.
411 // Add a second OpInfo table only when it is necessary.
412 // Adjust the type of the second table based on the number of bits needed.
413 O << " static const uint"
414 << ((BitsLeft < 16) ? "32" : (BitsLeft < 24) ? "16" : "8")
415 << "_t OpInfo2[] = {\n";
416 for (unsigned i = 0, e = NumberedInstructions->size(); i != e; ++i) {
417 O << " " << (OpcodeInfo[i] >> 32) << "U,\t// "
418 << NumberedInstructions->at(i)->TheDef->getName() << "\n";
420 // Add a dummy entry so the array init doesn't end with a comma.
425 // Emit the string itself.
426 O << " const char AsmStrs[] = {\n";
427 StringTable.emit(O, printChar);
430 O << " O << \"\\t\";\n\n";
432 O << " // Emit the opcode for the instruction.\n";
434 // If we have two tables then we need to perform two lookups and combine
435 // the results into a single 64-bit value.
436 O << " uint64_t Bits1 = OpInfo[MI->getOpcode()];\n"
437 << " uint64_t Bits2 = OpInfo2[MI->getOpcode()];\n"
438 << " uint64_t Bits = (Bits2 << 32) | Bits1;\n";
440 // If only one table is used we just need to perform a single lookup.
441 O << " uint32_t Bits = OpInfo[MI->getOpcode()];\n";
443 O << " assert(Bits != 0 && \"Cannot print this instruction.\");\n"
444 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
446 // Output the table driven operand information.
447 BitsLeft = 64-AsmStrBits;
448 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
449 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
451 // Compute the number of bits we need to represent these cases, this is
452 // ceil(log2(numentries)).
453 unsigned NumBits = Log2_32_Ceil(Commands.size());
454 assert(NumBits <= BitsLeft && "consistency error");
456 // Emit code to extract this field from Bits.
457 O << "\n // Fragment " << i << " encoded into " << NumBits
458 << " bits for " << Commands.size() << " unique commands.\n";
460 if (Commands.size() == 2) {
461 // Emit two possibilitys with if/else.
462 O << " if ((Bits >> "
463 << (64-BitsLeft) << ") & "
464 << ((1 << NumBits)-1) << ") {\n"
469 } else if (Commands.size() == 1) {
470 // Emit a single possibility.
471 O << Commands[0] << "\n\n";
473 O << " switch ((Bits >> "
474 << (64-BitsLeft) << ") & "
475 << ((1 << NumBits)-1) << ") {\n"
476 << " default: // unreachable.\n";
478 // Print out all the cases.
479 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
480 O << " case " << i << ":\n";
489 // Okay, delete instructions with no operand info left.
490 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
491 // Entire instruction has been emitted?
492 AsmWriterInst &Inst = Instructions[i];
493 if (Inst.Operands.empty()) {
494 Instructions.erase(Instructions.begin()+i);
500 // Because this is a vector, we want to emit from the end. Reverse all of the
501 // elements in the vector.
502 std::reverse(Instructions.begin(), Instructions.end());
505 // Now that we've emitted all of the operand info that fit into 32 bits, emit
506 // information for those instructions that are left. This is a less dense
507 // encoding, but we expect the main 32-bit table to handle the majority of
509 if (!Instructions.empty()) {
510 // Find the opcode # of inline asm.
511 O << " switch (MI->getOpcode()) {\n";
512 while (!Instructions.empty())
513 EmitInstructions(Instructions, O);
523 emitRegisterNameString(raw_ostream &O, StringRef AltName,
524 const std::vector<CodeGenRegister*> &Registers) {
525 SequenceToOffsetTable<std::string> StringTable;
526 SmallVector<std::string, 4> AsmNames(Registers.size());
527 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
528 const CodeGenRegister &Reg = *Registers[i];
529 std::string &AsmName = AsmNames[i];
531 // "NoRegAltName" is special. We don't need to do a lookup for that,
532 // as it's just a reference to the default register name.
533 if (AltName == "" || AltName == "NoRegAltName") {
534 AsmName = Reg.TheDef->getValueAsString("AsmName");
536 AsmName = Reg.getName();
538 // Make sure the register has an alternate name for this index.
539 std::vector<Record*> AltNameList =
540 Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
542 for (e = AltNameList.size();
543 Idx < e && (AltNameList[Idx]->getName() != AltName);
546 // If the register has an alternate name for this index, use it.
547 // Otherwise, leave it empty as an error flag.
549 std::vector<std::string> AltNames =
550 Reg.TheDef->getValueAsListOfStrings("AltNames");
551 if (AltNames.size() <= Idx)
552 PrintFatalError(Reg.TheDef->getLoc(),
553 "Register definition missing alt name for '" +
555 AsmName = AltNames[Idx];
558 StringTable.add(AsmName);
561 StringTable.layout();
562 O << " static const char AsmStrs" << AltName << "[] = {\n";
563 StringTable.emit(O, printChar);
566 O << " static const uint32_t 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 std::vector<CodeGenRegister*> &Registers =
580 Target.getRegBank().getRegisters();
581 std::vector<Record*> AltNameIndices = Target.getRegAltNameIndices();
582 bool hasAltNames = AltNameIndices.size() > 1;
585 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
586 "/// from the register set description. This returns the assembler name\n"
587 "/// for the specified register.\n"
588 "const char *" << Target.getName() << ClassName << "::";
590 O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
592 O << "getRegisterName(unsigned RegNo) {\n";
593 O << " assert(RegNo && RegNo < " << (Registers.size()+1)
594 << " && \"Invalid register number!\");\n"
598 for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i)
599 emitRegisterNameString(O, AltNameIndices[i]->getName(), Registers);
601 emitRegisterNameString(O, "", Registers);
604 O << " const uint32_t *RegAsmOffset;\n"
605 << " const char *AsmStrs;\n"
606 << " switch(AltIdx) {\n"
607 << " default: llvm_unreachable(\"Invalid register alt name index!\");\n";
608 for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i) {
609 std::string Namespace = AltNameIndices[1]->getValueAsString("Namespace");
610 std::string AltName(AltNameIndices[i]->getName());
611 O << " case " << Namespace << "::" << AltName
613 << " AsmStrs = AsmStrs" << AltName << ";\n"
614 << " RegAsmOffset = RegAsmOffset" << AltName << ";\n"
620 O << " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
621 << " \"Invalid alt name index for register!\");\n"
622 << " 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, unsigned> OpMap;
634 std::string AsmString;
635 SmallVector<Record*, 4> ReqFeatures;
637 IAPrinter(std::string R, std::string AS)
638 : Result(R), AsmString(AS) {}
640 void addCond(const std::string &C) { Conds.push_back(C); }
642 void addOperand(StringRef Op, unsigned Idx) {
643 assert(Idx < 0xFF && "Index too large!");
646 unsigned getOpIndex(StringRef Op) { return OpMap[Op]; }
647 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
649 void print(raw_ostream &O) {
650 if (Conds.empty() && ReqFeatures.empty()) {
651 O.indent(6) << "return true;\n";
657 for (std::vector<std::string>::iterator
658 I = Conds.begin(), E = Conds.end(); I != E; ++I) {
659 if (I != Conds.begin()) {
668 O.indent(6) << "// " << Result << "\n";
670 // Directly mangle mapped operands into the string. Each operand is
671 // identified by a '$' sign followed by a byte identifying the number of the
672 // operand. We add one to the index to avoid zero bytes.
673 std::pair<StringRef, StringRef> ASM = StringRef(AsmString).split(' ');
674 SmallString<128> OutString = ASM.first;
675 if (!ASM.second.empty()) {
676 raw_svector_ostream OS(OutString);
678 for (StringRef::iterator I = ASM.second.begin(), E = ASM.second.end();
682 StringRef::iterator Start = ++I;
684 ((*I >= 'a' && *I <= 'z') || (*I >= 'A' && *I <= 'Z') ||
685 (*I >= '0' && *I <= '9') || *I == '_'))
687 StringRef Name(Start, I - Start);
688 assert(isOpMapped(Name) && "Unmapped operand!");
689 OS << format("\\x%02X", (unsigned char)getOpIndex(Name) + 1);
697 O.indent(6) << "AsmString = \"" << OutString.str() << "\";\n";
699 O.indent(6) << "break;\n";
703 bool operator==(const IAPrinter &RHS) {
704 if (Conds.size() != RHS.Conds.size())
708 for (std::vector<std::string>::iterator
709 I = Conds.begin(), E = Conds.end(); I != E; ++I)
710 if (*I != RHS.Conds[Idx++])
717 } // end anonymous namespace
719 static unsigned CountNumOperands(StringRef AsmString) {
721 std::pair<StringRef, StringRef> ASM = AsmString.split(' ');
723 while (!ASM.second.empty()) {
725 ASM = ASM.second.split(' ');
731 static unsigned CountResultNumOperands(StringRef AsmString) {
733 std::pair<StringRef, StringRef> ASM = AsmString.split('\t');
735 if (!ASM.second.empty()) {
736 size_t I = ASM.second.find('{');
737 StringRef Str = ASM.second;
738 if (I != StringRef::npos)
739 Str = ASM.second.substr(I, ASM.second.find('|', I));
741 ASM = Str.split(' ');
745 ASM = ASM.second.split(' ');
746 } while (!ASM.second.empty());
752 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
753 Record *AsmWriter = Target.getAsmWriter();
755 O << "\n#ifdef PRINT_ALIAS_INSTR\n";
756 O << "#undef PRINT_ALIAS_INSTR\n\n";
758 // Emit the method that prints the alias instruction.
759 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
761 std::vector<Record*> AllInstAliases =
762 Records.getAllDerivedDefinitions("InstAlias");
764 // Create a map from the qualified name to a list of potential matches.
765 std::map<std::string, std::vector<CodeGenInstAlias*> > AliasMap;
766 for (std::vector<Record*>::iterator
767 I = AllInstAliases.begin(), E = AllInstAliases.end(); I != E; ++I) {
768 CodeGenInstAlias *Alias = new CodeGenInstAlias(*I, Target);
769 const Record *R = *I;
770 if (!R->getValueAsBit("EmitAlias"))
771 continue; // We were told not to emit the alias, but to emit the aliasee.
772 const DagInit *DI = R->getValueAsDag("ResultInst");
773 const DefInit *Op = cast<DefInit>(DI->getOperator());
774 AliasMap[getQualifiedName(Op->getDef())].push_back(Alias);
777 // A map of which conditions need to be met for each instruction operand
778 // before it can be matched to the mnemonic.
779 std::map<std::string, std::vector<IAPrinter*> > IAPrinterMap;
781 for (std::map<std::string, std::vector<CodeGenInstAlias*> >::iterator
782 I = AliasMap.begin(), E = AliasMap.end(); I != E; ++I) {
783 std::vector<CodeGenInstAlias*> &Aliases = I->second;
785 for (std::vector<CodeGenInstAlias*>::iterator
786 II = Aliases.begin(), IE = Aliases.end(); II != IE; ++II) {
787 const CodeGenInstAlias *CGA = *II;
788 unsigned LastOpNo = CGA->ResultInstOperandIndex.size();
789 unsigned NumResultOps =
790 CountResultNumOperands(CGA->ResultInst->AsmString);
792 // Don't emit the alias if it has more operands than what it's aliasing.
793 if (NumResultOps < CountNumOperands(CGA->AsmString))
796 IAPrinter *IAP = new IAPrinter(CGA->Result->getAsString(),
800 Cond = std::string("MI->getNumOperands() == ") + llvm::utostr(LastOpNo);
803 bool CantHandle = false;
805 for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
806 const CodeGenInstAlias::ResultOperand &RO = CGA->ResultOperands[i];
809 case CodeGenInstAlias::ResultOperand::K_Record: {
810 const Record *Rec = RO.getRecord();
811 StringRef ROName = RO.getName();
814 if (Rec->isSubClassOf("RegisterOperand"))
815 Rec = Rec->getValueAsDef("RegClass");
816 if (Rec->isSubClassOf("RegisterClass")) {
817 Cond = std::string("MI->getOperand(")+llvm::utostr(i)+").isReg()";
820 if (!IAP->isOpMapped(ROName)) {
821 IAP->addOperand(ROName, i);
822 Record *R = CGA->ResultOperands[i].getRecord();
823 if (R->isSubClassOf("RegisterOperand"))
824 R = R->getValueAsDef("RegClass");
825 Cond = std::string("MRI.getRegClass(") + Target.getName() + "::" +
826 R->getName() + "RegClassID)"
827 ".contains(MI->getOperand(" + llvm::utostr(i) + ").getReg())";
830 Cond = std::string("MI->getOperand(") +
831 llvm::utostr(i) + ").getReg() == MI->getOperand(" +
832 llvm::utostr(IAP->getOpIndex(ROName)) + ").getReg()";
836 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
837 // FIXME: We may need to handle these situations.
846 case CodeGenInstAlias::ResultOperand::K_Imm: {
847 std::string Op = "MI->getOperand(" + llvm::utostr(i) + ")";
849 // Just because the alias has an immediate result, doesn't mean the
850 // MCInst will. An MCExpr could be present, for example.
851 IAP->addCond(Op + ".isImm()");
853 Cond = Op + ".getImm() == "
854 + llvm::utostr(CGA->ResultOperands[i].getImm());
858 case CodeGenInstAlias::ResultOperand::K_Reg:
859 // If this is zero_reg, something's playing tricks we're not
860 // equipped to handle.
861 if (!CGA->ResultOperands[i].getRegister()) {
866 Cond = std::string("MI->getOperand(") +
867 llvm::utostr(i) + ").getReg() == " + Target.getName() +
868 "::" + CGA->ResultOperands[i].getRegister()->getName();
876 if (CantHandle) continue;
877 IAPrinterMap[I->first].push_back(IAP);
882 raw_string_ostream HeaderO(Header);
884 HeaderO << "bool " << Target.getName() << ClassName
885 << "::printAliasInstr(const MCInst"
886 << " *MI, raw_ostream &OS) {\n";
889 raw_string_ostream CasesO(Cases);
891 for (std::map<std::string, std::vector<IAPrinter*> >::iterator
892 I = IAPrinterMap.begin(), E = IAPrinterMap.end(); I != E; ++I) {
893 std::vector<IAPrinter*> &IAPs = I->second;
894 std::vector<IAPrinter*> UniqueIAPs;
896 for (std::vector<IAPrinter*>::iterator
897 II = IAPs.begin(), IE = IAPs.end(); II != IE; ++II) {
898 IAPrinter *LHS = *II;
900 for (std::vector<IAPrinter*>::iterator
901 III = IAPs.begin(), IIE = IAPs.end(); III != IIE; ++III) {
902 IAPrinter *RHS = *III;
903 if (LHS != RHS && *LHS == *RHS) {
909 if (!IsDup) UniqueIAPs.push_back(LHS);
912 if (UniqueIAPs.empty()) continue;
914 CasesO.indent(2) << "case " << I->first << ":\n";
916 for (std::vector<IAPrinter*>::iterator
917 II = UniqueIAPs.begin(), IE = UniqueIAPs.end(); II != IE; ++II) {
918 IAPrinter *IAP = *II;
924 CasesO.indent(4) << "return false;\n";
927 if (CasesO.str().empty()) {
929 O << " return false;\n";
931 O << "#endif // PRINT_ALIAS_INSTR\n";
936 O.indent(2) << "const char *AsmString;\n";
937 O.indent(2) << "switch (MI->getOpcode()) {\n";
938 O.indent(2) << "default: return false;\n";
940 O.indent(2) << "}\n\n";
942 // Code that prints the alias, replacing the operands with the ones from the
944 O << " unsigned I = 0;\n";
945 O << " while (AsmString[I] != ' ' && AsmString[I] != '\\0')\n";
947 O << " OS << '\\t' << StringRef(AsmString, I);\n";
949 O << " if (AsmString[I] != '\\0') {\n";
950 O << " OS << '\\t';\n";
952 O << " if (AsmString[I] == '$') {\n";
954 O << " printOperand(MI, unsigned(AsmString[I++]) - 1, OS);\n";
956 O << " OS << AsmString[I++];\n";
958 O << " } while (AsmString[I] != '\\0');\n";
961 O << " return true;\n";
964 O << "#endif // PRINT_ALIAS_INSTR\n";
967 AsmWriterEmitter::AsmWriterEmitter(RecordKeeper &R) : Records(R), Target(R) {
968 Record *AsmWriter = Target.getAsmWriter();
969 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
970 E = Target.inst_end();
972 if (!(*I)->AsmString.empty() && (*I)->TheDef->getName() != "PHI")
973 Instructions.push_back(
974 AsmWriterInst(**I, AsmWriter->getValueAsInt("Variant"),
975 AsmWriter->getValueAsInt("OperandSpacing")));
977 // Get the instruction numbering.
978 NumberedInstructions = &Target.getInstructionsByEnumValue();
980 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
981 // all machine instructions are necessarily being printed, so there may be
982 // target instructions not in this map.
983 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
984 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
987 void AsmWriterEmitter::run(raw_ostream &O) {
988 EmitPrintInstruction(O);
989 EmitGetRegisterName(O);
990 EmitPrintAliasInstruction(O);
996 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) {
997 emitSourceFileHeader("Assembly Writer Source Fragment", OS);
998 AsmWriterEmitter(RK).run(OS);
1001 } // End llvm namespace