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/MathExtras.h"
22 #include "llvm/TableGen/Error.h"
23 #include "llvm/TableGen/Record.h"
24 #include "llvm/TableGen/TableGenBackend.h"
32 class AsmWriterEmitter {
33 RecordKeeper &Records;
34 std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap;
35 std::vector<const CodeGenInstruction*> NumberedInstructions;
37 AsmWriterEmitter(RecordKeeper &R) : Records(R) {}
39 void run(raw_ostream &o);
42 void EmitPrintInstruction(raw_ostream &o);
43 void EmitGetRegisterName(raw_ostream &o);
44 void EmitPrintAliasInstruction(raw_ostream &O);
46 AsmWriterInst *getAsmWriterInstByID(unsigned ID) const {
47 assert(ID < NumberedInstructions.size());
48 std::map<const CodeGenInstruction*, AsmWriterInst*>::const_iterator I =
49 CGIAWIMap.find(NumberedInstructions[ID]);
50 assert(I != CGIAWIMap.end() && "Didn't find inst!");
53 void FindUniqueOperandCommands(std::vector<std::string> &UOC,
54 std::vector<unsigned> &InstIdxs,
55 std::vector<unsigned> &InstOpsUsed) const;
57 } // end anonymous namespace
59 static void PrintCases(std::vector<std::pair<std::string,
60 AsmWriterOperand> > &OpsToPrint, raw_ostream &O) {
61 O << " case " << OpsToPrint.back().first << ": ";
62 AsmWriterOperand TheOp = OpsToPrint.back().second;
63 OpsToPrint.pop_back();
65 // Check to see if any other operands are identical in this list, and if so,
66 // emit a case label for them.
67 for (unsigned i = OpsToPrint.size(); i != 0; --i)
68 if (OpsToPrint[i-1].second == TheOp) {
69 O << "\n case " << OpsToPrint[i-1].first << ": ";
70 OpsToPrint.erase(OpsToPrint.begin()+i-1);
73 // Finally, emit the code.
79 /// EmitInstructions - Emit the last instruction in the vector and any other
80 /// instructions that are suitably similar to it.
81 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
83 AsmWriterInst FirstInst = Insts.back();
86 std::vector<AsmWriterInst> SimilarInsts;
87 unsigned DifferingOperand = ~0;
88 for (unsigned i = Insts.size(); i != 0; --i) {
89 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
91 if (DifferingOperand == ~0U) // First match!
92 DifferingOperand = DiffOp;
94 // If this differs in the same operand as the rest of the instructions in
95 // this class, move it to the SimilarInsts list.
96 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
97 SimilarInsts.push_back(Insts[i-1]);
98 Insts.erase(Insts.begin()+i-1);
103 O << " case " << FirstInst.CGI->Namespace << "::"
104 << FirstInst.CGI->TheDef->getName() << ":\n";
105 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
106 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
107 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
108 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
109 if (i != DifferingOperand) {
110 // If the operand is the same for all instructions, just print it.
111 O << " " << FirstInst.Operands[i].getCode();
113 // If this is the operand that varies between all of the instructions,
114 // emit a switch for just this operand now.
115 O << " switch (MI->getOpcode()) {\n";
116 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
117 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
118 FirstInst.CGI->TheDef->getName(),
119 FirstInst.Operands[i]));
121 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
122 AsmWriterInst &AWI = SimilarInsts[si];
123 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
124 AWI.CGI->TheDef->getName(),
127 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
128 while (!OpsToPrint.empty())
129 PrintCases(OpsToPrint, O);
137 void AsmWriterEmitter::
138 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
139 std::vector<unsigned> &InstIdxs,
140 std::vector<unsigned> &InstOpsUsed) const {
141 InstIdxs.assign(NumberedInstructions.size(), ~0U);
143 // This vector parallels UniqueOperandCommands, keeping track of which
144 // instructions each case are used for. It is a comma separated string of
146 std::vector<std::string> InstrsForCase;
147 InstrsForCase.resize(UniqueOperandCommands.size());
148 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
150 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
151 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
152 if (Inst == 0) continue; // PHI, INLINEASM, PROLOG_LABEL, etc.
155 if (Inst->Operands.empty())
156 continue; // Instruction already done.
158 Command = " " + Inst->Operands[0].getCode() + "\n";
160 // Check to see if we already have 'Command' in UniqueOperandCommands.
162 bool FoundIt = false;
163 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
164 if (UniqueOperandCommands[idx] == Command) {
166 InstrsForCase[idx] += ", ";
167 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
172 InstIdxs[i] = UniqueOperandCommands.size();
173 UniqueOperandCommands.push_back(Command);
174 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
176 // This command matches one operand so far.
177 InstOpsUsed.push_back(1);
181 // For each entry of UniqueOperandCommands, there is a set of instructions
182 // that uses it. If the next command of all instructions in the set are
183 // identical, fold it into the command.
184 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
185 CommandIdx != e; ++CommandIdx) {
187 for (unsigned Op = 1; ; ++Op) {
188 // Scan for the first instruction in the set.
189 std::vector<unsigned>::iterator NIT =
190 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
191 if (NIT == InstIdxs.end()) break; // No commonality.
193 // If this instruction has no more operands, we isn't anything to merge
194 // into this command.
195 const AsmWriterInst *FirstInst =
196 getAsmWriterInstByID(NIT-InstIdxs.begin());
197 if (!FirstInst || FirstInst->Operands.size() == Op)
200 // Otherwise, scan to see if all of the other instructions in this command
201 // set share the operand.
203 // Keep track of the maximum, number of operands or any
204 // instruction we see in the group.
205 size_t MaxSize = FirstInst->Operands.size();
207 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
208 NIT != InstIdxs.end();
209 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
210 // Okay, found another instruction in this command set. If the operand
211 // matches, we're ok, otherwise bail out.
212 const AsmWriterInst *OtherInst =
213 getAsmWriterInstByID(NIT-InstIdxs.begin());
216 OtherInst->Operands.size() > FirstInst->Operands.size())
217 MaxSize = std::max(MaxSize, OtherInst->Operands.size());
219 if (!OtherInst || OtherInst->Operands.size() == Op ||
220 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
227 // Okay, everything in this command set has the same next operand. Add it
228 // to UniqueOperandCommands and remember that it was consumed.
229 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
231 UniqueOperandCommands[CommandIdx] += Command;
232 InstOpsUsed[CommandIdx]++;
236 // Prepend some of the instructions each case is used for onto the case val.
237 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
238 std::string Instrs = InstrsForCase[i];
239 if (Instrs.size() > 70) {
240 Instrs.erase(Instrs.begin()+70, Instrs.end());
245 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
246 UniqueOperandCommands[i];
251 static void UnescapeString(std::string &Str) {
252 for (unsigned i = 0; i != Str.size(); ++i) {
253 if (Str[i] == '\\' && i != Str.size()-1) {
255 default: continue; // Don't execute the code after the switch.
256 case 'a': Str[i] = '\a'; break;
257 case 'b': Str[i] = '\b'; break;
258 case 'e': Str[i] = 27; break;
259 case 'f': Str[i] = '\f'; break;
260 case 'n': Str[i] = '\n'; break;
261 case 'r': Str[i] = '\r'; break;
262 case 't': Str[i] = '\t'; break;
263 case 'v': Str[i] = '\v'; break;
264 case '"': Str[i] = '\"'; break;
265 case '\'': Str[i] = '\''; break;
266 case '\\': Str[i] = '\\'; break;
268 // Nuke the second character.
269 Str.erase(Str.begin()+i+1);
274 /// EmitPrintInstruction - Generate the code for the "printInstruction" method
276 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) {
277 CodeGenTarget Target(Records);
278 Record *AsmWriter = Target.getAsmWriter();
279 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
280 bool isMC = AsmWriter->getValueAsBit("isMCAsmWriter");
281 const char *MachineInstrClassName = isMC ? "MCInst" : "MachineInstr";
284 "/// printInstruction - This method is automatically generated by tablegen\n"
285 "/// from the instruction set description.\n"
286 "void " << Target.getName() << ClassName
287 << "::printInstruction(const " << MachineInstrClassName
288 << " *MI, raw_ostream &O) {\n";
290 std::vector<AsmWriterInst> Instructions;
292 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
293 E = Target.inst_end(); I != E; ++I)
294 if (!(*I)->AsmString.empty() &&
295 (*I)->TheDef->getName() != "PHI")
296 Instructions.push_back(
298 AsmWriter->getValueAsInt("Variant"),
299 AsmWriter->getValueAsInt("FirstOperandColumn"),
300 AsmWriter->getValueAsInt("OperandSpacing")));
302 // Get the instruction numbering.
303 NumberedInstructions = Target.getInstructionsByEnumValue();
305 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
306 // all machine instructions are necessarily being printed, so there may be
307 // target instructions not in this map.
308 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
309 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
311 // Build an aggregate string, and build a table of offsets into it.
312 SequenceToOffsetTable<std::string> StringTable;
314 /// OpcodeInfo - This encodes the index of the string to use for the first
315 /// chunk of the output as well as indices used for operand printing.
316 /// To reduce the number of unhandled cases, we expand the size from 32-bit
317 /// to 32+16 = 48-bit.
318 std::vector<std::pair<unsigned, uint16_t> > OpcodeInfo;
320 // Add all strings to the string table upfront so it can generate an optimized
322 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
323 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
325 AWI->Operands[0].OperandType ==
326 AsmWriterOperand::isLiteralTextOperand &&
327 !AWI->Operands[0].Str.empty()) {
328 std::string Str = AWI->Operands[0].Str;
330 StringTable.add(Str);
334 StringTable.layout();
336 unsigned MaxStringIdx = 0;
337 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
338 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
341 // Something not handled by the asmwriter printer.
343 } else if (AWI->Operands[0].OperandType !=
344 AsmWriterOperand::isLiteralTextOperand ||
345 AWI->Operands[0].Str.empty()) {
346 // Something handled by the asmwriter printer, but with no leading string.
347 Idx = StringTable.get("");
349 std::string Str = AWI->Operands[0].Str;
351 Idx = StringTable.get(Str);
352 MaxStringIdx = std::max(MaxStringIdx, Idx);
354 // Nuke the string from the operand list. It is now handled!
355 AWI->Operands.erase(AWI->Operands.begin());
358 // Bias offset by one since we want 0 as a sentinel.
359 OpcodeInfo.push_back(std::make_pair(Idx+1, 0));
362 // Figure out how many bits we used for the string index.
363 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
365 // To reduce code size, we compactify common instructions into a few bits
366 // in the opcode-indexed table.
367 unsigned BitsLeft = 32+16-AsmStrBits;
369 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
372 std::vector<std::string> UniqueOperandCommands;
373 std::vector<unsigned> InstIdxs;
374 std::vector<unsigned> NumInstOpsHandled;
375 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
378 // If we ran out of operands to print, we're done.
379 if (UniqueOperandCommands.empty()) break;
381 // Compute the number of bits we need to represent these cases, this is
382 // ceil(log2(numentries)).
383 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
385 // Check whether these Bits will fit in the first 32 bits.
386 if (BitsLeft > 16 && NumBits > BitsLeft - 16)
387 // We don't have enough bits in the first 32 bits, and we skip the
390 bool UseSecond = (BitsLeft <= 16);
392 // If we don't have enough bits for this operand, don't include it.
393 if (NumBits > BitsLeft) {
394 DEBUG(errs() << "Not enough bits to densely encode " << NumBits
399 // Otherwise, we can include this in the initial lookup table. Add it in.
401 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
402 // Update the first 32 bits or the second 16 bits.
403 if (InstIdxs[i] != ~0U) {
405 OpcodeInfo[i].second |= InstIdxs[i] << BitsLeft;
407 OpcodeInfo[i].first |= InstIdxs[i] << (BitsLeft-16+AsmStrBits);
410 // Remove the info about this operand.
411 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
412 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
413 if (!Inst->Operands.empty()) {
414 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
415 assert(NumOps <= Inst->Operands.size() &&
416 "Can't remove this many ops!");
417 Inst->Operands.erase(Inst->Operands.begin(),
418 Inst->Operands.begin()+NumOps);
422 // Remember the handlers for this set of operands.
423 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
428 O<<" static const unsigned OpInfo[] = {\n";
429 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
430 O << " " << OpcodeInfo[i].first << "U,\t// "
431 << NumberedInstructions[i]->TheDef->getName() << "\n";
433 // Add a dummy entry so the array init doesn't end with a comma.
438 // Add a second OpInfo table only when it is necessary.
439 O<<" static const uint16_t OpInfo2[] = {\n";
440 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
441 O << " " << OpcodeInfo[i].second << "U,\t// "
442 << NumberedInstructions[i]->TheDef->getName() << "\n";
444 // Add a dummy entry so the array init doesn't end with a comma.
449 // Emit the string itself.
450 O << " const char AsmStrs[] = {\n";
451 StringTable.emit(O, printChar);
454 O << " O << \"\\t\";\n\n";
456 O << " // Emit the opcode for the instruction.\n"
457 << " unsigned Bits = OpInfo[MI->getOpcode()];\n";
459 O << " unsigned short Bits2 = OpInfo2[MI->getOpcode()];\n";
460 O << " assert(Bits != 0 && \"Cannot print this instruction.\");\n"
461 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
463 // Output the table driven operand information.
464 BitsLeft = 32+16-AsmStrBits;
465 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
466 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
468 // Compute the number of bits we need to represent these cases, this is
469 // ceil(log2(numentries)).
470 unsigned NumBits = Log2_32_Ceil(Commands.size());
471 assert(NumBits <= BitsLeft && "consistency error");
473 // Check whether these Bits will fit in the first 32 bits.
474 if (BitsLeft > 16 && NumBits > BitsLeft - 16)
476 bool UseSecond = (BitsLeft <= 16);
478 // Emit code to extract this field from Bits.
481 O << "\n // Fragment " << i << " encoded into " << NumBits
482 << " bits for " << Commands.size() << " unique commands.\n";
484 if (Commands.size() == 2) {
485 // Emit two possibilitys with if/else.
486 O << (UseSecond ? " if ((Bits2 >> " : " if ((Bits >> ")
487 << (UseSecond ? BitsLeft : (BitsLeft-16+AsmStrBits)) << ") & "
488 << ((1 << NumBits)-1) << ") {\n"
493 } else if (Commands.size() == 1) {
494 // Emit a single possibility.
495 O << Commands[0] << "\n\n";
497 O << (UseSecond ? " switch ((Bits2 >> " : " switch ((Bits >> ")
498 << (UseSecond ? BitsLeft : (BitsLeft-16+AsmStrBits)) << ") & "
499 << ((1 << NumBits)-1) << ") {\n"
500 << " default: // unreachable.\n";
502 // Print out all the cases.
503 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
504 O << " case " << i << ":\n";
512 // Okay, delete instructions with no operand info left.
513 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
514 // Entire instruction has been emitted?
515 AsmWriterInst &Inst = Instructions[i];
516 if (Inst.Operands.empty()) {
517 Instructions.erase(Instructions.begin()+i);
523 // Because this is a vector, we want to emit from the end. Reverse all of the
524 // elements in the vector.
525 std::reverse(Instructions.begin(), Instructions.end());
528 // Now that we've emitted all of the operand info that fit into 32 bits, emit
529 // information for those instructions that are left. This is a less dense
530 // encoding, but we expect the main 32-bit table to handle the majority of
532 if (!Instructions.empty()) {
533 // Find the opcode # of inline asm.
534 O << " switch (MI->getOpcode()) {\n";
535 while (!Instructions.empty())
536 EmitInstructions(Instructions, O);
546 emitRegisterNameString(raw_ostream &O, StringRef AltName,
547 const std::vector<CodeGenRegister*> &Registers) {
548 SequenceToOffsetTable<std::string> StringTable;
549 SmallVector<std::string, 4> AsmNames(Registers.size());
550 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
551 const CodeGenRegister &Reg = *Registers[i];
552 std::string &AsmName = AsmNames[i];
554 // "NoRegAltName" is special. We don't need to do a lookup for that,
555 // as it's just a reference to the default register name.
556 if (AltName == "" || AltName == "NoRegAltName") {
557 AsmName = Reg.TheDef->getValueAsString("AsmName");
559 AsmName = Reg.getName();
561 // Make sure the register has an alternate name for this index.
562 std::vector<Record*> AltNameList =
563 Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
565 for (e = AltNameList.size();
566 Idx < e && (AltNameList[Idx]->getName() != AltName);
569 // If the register has an alternate name for this index, use it.
570 // Otherwise, leave it empty as an error flag.
572 std::vector<std::string> AltNames =
573 Reg.TheDef->getValueAsListOfStrings("AltNames");
574 if (AltNames.size() <= Idx)
575 throw TGError(Reg.TheDef->getLoc(),
576 (Twine("Register definition missing alt name for '") +
577 AltName + "'.").str());
578 AsmName = AltNames[Idx];
581 StringTable.add(AsmName);
584 unsigned Entries = StringTable.layout();
585 O << " static const char AsmStrs" << AltName << "[] = {\n";
586 StringTable.emit(O, printChar);
589 O << " static const uint" << ((Entries > 0xffff) ? "32" : "16")
590 << "_t RegAsmOffset" << AltName << "[] = {";
591 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
594 O << StringTable.get(AsmNames[i]) << ", ";
600 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
601 CodeGenTarget Target(Records);
602 Record *AsmWriter = Target.getAsmWriter();
603 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
604 const std::vector<CodeGenRegister*> &Registers =
605 Target.getRegBank().getRegisters();
606 std::vector<Record*> AltNameIndices = Target.getRegAltNameIndices();
607 bool hasAltNames = AltNameIndices.size() > 1;
610 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
611 "/// from the register set description. This returns the assembler name\n"
612 "/// for the specified register.\n"
613 "const char *" << Target.getName() << ClassName << "::";
615 O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
617 O << "getRegisterName(unsigned RegNo) {\n";
618 O << " assert(RegNo && RegNo < " << (Registers.size()+1)
619 << " && \"Invalid register number!\");\n"
623 for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i)
624 emitRegisterNameString(O, AltNameIndices[i]->getName(), Registers);
626 emitRegisterNameString(O, "", Registers);
629 O << " const unsigned *RegAsmOffset;\n"
630 << " const char *AsmStrs;\n"
631 << " switch(AltIdx) {\n"
632 << " default: llvm_unreachable(\"Invalid register alt name index!\");\n";
633 for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i) {
634 StringRef Namespace = AltNameIndices[1]->getValueAsString("Namespace");
635 StringRef AltName(AltNameIndices[i]->getName());
636 O << " case " << Namespace << "::" << AltName
638 << " AsmStrs = AsmStrs" << AltName << ";\n"
639 << " RegAsmOffset = RegAsmOffset" << AltName << ";\n"
645 O << " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
646 << " \"Invalid alt name index for register!\");\n"
647 << " return AsmStrs+RegAsmOffset[RegNo-1];\n"
652 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if
653 // they both have the same conditionals. In which case, we cannot print out the
654 // alias for that pattern.
656 std::vector<std::string> Conds;
657 std::map<StringRef, unsigned> OpMap;
659 std::string AsmString;
660 SmallVector<Record*, 4> ReqFeatures;
662 IAPrinter(std::string R, std::string AS)
663 : Result(R), AsmString(AS) {}
665 void addCond(const std::string &C) { Conds.push_back(C); }
667 void addOperand(StringRef Op, unsigned Idx) { OpMap[Op] = Idx; }
668 unsigned getOpIndex(StringRef Op) { return OpMap[Op]; }
669 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
671 void print(raw_ostream &O) {
672 if (Conds.empty() && ReqFeatures.empty()) {
673 O.indent(6) << "return true;\n";
679 for (std::vector<std::string>::iterator
680 I = Conds.begin(), E = Conds.end(); I != E; ++I) {
681 if (I != Conds.begin()) {
690 O.indent(6) << "// " << Result << "\n";
691 O.indent(6) << "AsmString = \"" << AsmString << "\";\n";
693 for (std::map<StringRef, unsigned>::iterator
694 I = OpMap.begin(), E = OpMap.end(); I != E; ++I)
695 O.indent(6) << "OpMap.push_back(std::make_pair(\"" << I->first << "\", "
696 << I->second << "));\n";
698 O.indent(6) << "break;\n";
702 bool operator==(const IAPrinter &RHS) {
703 if (Conds.size() != RHS.Conds.size())
707 for (std::vector<std::string>::iterator
708 I = Conds.begin(), E = Conds.end(); I != E; ++I)
709 if (*I != RHS.Conds[Idx++])
715 bool operator()(const IAPrinter &RHS) {
716 if (Conds.size() < RHS.Conds.size())
720 for (std::vector<std::string>::iterator
721 I = Conds.begin(), E = Conds.end(); I != E; ++I)
722 if (*I != RHS.Conds[Idx++])
723 return *I < RHS.Conds[Idx++];
729 } // end anonymous namespace
731 static void EmitGetMapOperandNumber(raw_ostream &O) {
732 O << "static unsigned getMapOperandNumber("
733 << "const SmallVectorImpl<std::pair<StringRef, unsigned> > &OpMap,\n";
734 O << " StringRef Name) {\n";
735 O << " for (SmallVectorImpl<std::pair<StringRef, unsigned> >::"
736 << "const_iterator\n";
737 O << " I = OpMap.begin(), E = OpMap.end(); I != E; ++I)\n";
738 O << " if (I->first == Name)\n";
739 O << " return I->second;\n";
740 O << " llvm_unreachable(\"Operand not in map!\");\n";
744 static unsigned CountNumOperands(StringRef AsmString) {
746 std::pair<StringRef, StringRef> ASM = AsmString.split(' ');
748 while (!ASM.second.empty()) {
750 ASM = ASM.second.split(' ');
756 static unsigned CountResultNumOperands(StringRef AsmString) {
758 std::pair<StringRef, StringRef> ASM = AsmString.split('\t');
760 if (!ASM.second.empty()) {
761 size_t I = ASM.second.find('{');
762 StringRef Str = ASM.second;
763 if (I != StringRef::npos)
764 Str = ASM.second.substr(I, ASM.second.find('|', I));
766 ASM = Str.split(' ');
770 ASM = ASM.second.split(' ');
771 } while (!ASM.second.empty());
777 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
778 CodeGenTarget Target(Records);
779 Record *AsmWriter = Target.getAsmWriter();
781 if (!AsmWriter->getValueAsBit("isMCAsmWriter"))
784 O << "\n#ifdef PRINT_ALIAS_INSTR\n";
785 O << "#undef PRINT_ALIAS_INSTR\n\n";
787 // Emit the method that prints the alias instruction.
788 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
790 std::vector<Record*> AllInstAliases =
791 Records.getAllDerivedDefinitions("InstAlias");
793 // Create a map from the qualified name to a list of potential matches.
794 std::map<std::string, std::vector<CodeGenInstAlias*> > AliasMap;
795 for (std::vector<Record*>::iterator
796 I = AllInstAliases.begin(), E = AllInstAliases.end(); I != E; ++I) {
797 CodeGenInstAlias *Alias = new CodeGenInstAlias(*I, Target);
798 const Record *R = *I;
799 if (!R->getValueAsBit("EmitAlias"))
800 continue; // We were told not to emit the alias, but to emit the aliasee.
801 const DagInit *DI = R->getValueAsDag("ResultInst");
802 const DefInit *Op = dynamic_cast<const DefInit*>(DI->getOperator());
803 AliasMap[getQualifiedName(Op->getDef())].push_back(Alias);
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 for (std::map<std::string, std::vector<CodeGenInstAlias*> >::iterator
811 I = AliasMap.begin(), E = AliasMap.end(); I != E; ++I) {
812 std::vector<CodeGenInstAlias*> &Aliases = I->second;
814 for (std::vector<CodeGenInstAlias*>::iterator
815 II = Aliases.begin(), IE = Aliases.end(); II != IE; ++II) {
816 const CodeGenInstAlias *CGA = *II;
817 unsigned LastOpNo = CGA->ResultInstOperandIndex.size();
818 unsigned NumResultOps =
819 CountResultNumOperands(CGA->ResultInst->AsmString);
821 // Don't emit the alias if it has more operands than what it's aliasing.
822 if (NumResultOps < CountNumOperands(CGA->AsmString))
825 IAPrinter *IAP = new IAPrinter(CGA->Result->getAsString(),
829 Cond = std::string("MI->getNumOperands() == ") + llvm::utostr(LastOpNo);
832 std::map<StringRef, unsigned> OpMap;
833 bool CantHandle = false;
835 for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
836 const CodeGenInstAlias::ResultOperand &RO = CGA->ResultOperands[i];
839 case CodeGenInstAlias::ResultOperand::K_Record: {
840 const Record *Rec = RO.getRecord();
841 StringRef ROName = RO.getName();
844 if (Rec->isSubClassOf("RegisterOperand"))
845 Rec = Rec->getValueAsDef("RegClass");
846 if (Rec->isSubClassOf("RegisterClass")) {
847 Cond = std::string("MI->getOperand(")+llvm::utostr(i)+").isReg()";
850 if (!IAP->isOpMapped(ROName)) {
851 IAP->addOperand(ROName, i);
852 Cond = std::string("MRI.getRegClass(") + Target.getName() + "::" +
853 CGA->ResultOperands[i].getRecord()->getName() + "RegClassID)"
854 ".contains(MI->getOperand(" + llvm::utostr(i) + ").getReg())";
857 Cond = std::string("MI->getOperand(") +
858 llvm::utostr(i) + ").getReg() == MI->getOperand(" +
859 llvm::utostr(IAP->getOpIndex(ROName)) + ").getReg()";
863 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
864 // FIXME: We may need to handle these situations.
873 case CodeGenInstAlias::ResultOperand::K_Imm:
874 Cond = std::string("MI->getOperand(") +
875 llvm::utostr(i) + ").getImm() == " +
876 llvm::utostr(CGA->ResultOperands[i].getImm());
879 case CodeGenInstAlias::ResultOperand::K_Reg:
880 // If this is zero_reg, something's playing tricks we're not
881 // equipped to handle.
882 if (!CGA->ResultOperands[i].getRegister()) {
887 Cond = std::string("MI->getOperand(") +
888 llvm::utostr(i) + ").getReg() == " + Target.getName() +
889 "::" + CGA->ResultOperands[i].getRegister()->getName();
897 if (CantHandle) continue;
898 IAPrinterMap[I->first].push_back(IAP);
903 raw_string_ostream HeaderO(Header);
905 HeaderO << "bool " << Target.getName() << ClassName
906 << "::printAliasInstr(const MCInst"
907 << " *MI, raw_ostream &OS) {\n";
910 raw_string_ostream CasesO(Cases);
912 for (std::map<std::string, std::vector<IAPrinter*> >::iterator
913 I = IAPrinterMap.begin(), E = IAPrinterMap.end(); I != E; ++I) {
914 std::vector<IAPrinter*> &IAPs = I->second;
915 std::vector<IAPrinter*> UniqueIAPs;
917 for (std::vector<IAPrinter*>::iterator
918 II = IAPs.begin(), IE = IAPs.end(); II != IE; ++II) {
919 IAPrinter *LHS = *II;
921 for (std::vector<IAPrinter*>::iterator
922 III = IAPs.begin(), IIE = IAPs.end(); III != IIE; ++III) {
923 IAPrinter *RHS = *III;
924 if (LHS != RHS && *LHS == *RHS) {
930 if (!IsDup) UniqueIAPs.push_back(LHS);
933 if (UniqueIAPs.empty()) continue;
935 CasesO.indent(2) << "case " << I->first << ":\n";
937 for (std::vector<IAPrinter*>::iterator
938 II = UniqueIAPs.begin(), IE = UniqueIAPs.end(); II != IE; ++II) {
939 IAPrinter *IAP = *II;
945 CasesO.indent(4) << "return false;\n";
948 if (CasesO.str().empty()) {
950 O << " return false;\n";
952 O << "#endif // PRINT_ALIAS_INSTR\n";
956 EmitGetMapOperandNumber(O);
959 O.indent(2) << "StringRef AsmString;\n";
960 O.indent(2) << "SmallVector<std::pair<StringRef, unsigned>, 4> OpMap;\n";
961 O.indent(2) << "switch (MI->getOpcode()) {\n";
962 O.indent(2) << "default: return false;\n";
964 O.indent(2) << "}\n\n";
966 // Code that prints the alias, replacing the operands with the ones from the
968 O << " std::pair<StringRef, StringRef> ASM = AsmString.split(' ');\n";
969 O << " OS << '\\t' << ASM.first;\n";
971 O << " if (!ASM.second.empty()) {\n";
972 O << " OS << '\\t';\n";
973 O << " for (StringRef::iterator\n";
974 O << " I = ASM.second.begin(), E = ASM.second.end(); I != E; ) {\n";
975 O << " if (*I == '$') {\n";
976 O << " StringRef::iterator Start = ++I;\n";
977 O << " while (I != E &&\n";
978 O << " ((*I >= 'a' && *I <= 'z') ||\n";
979 O << " (*I >= 'A' && *I <= 'Z') ||\n";
980 O << " (*I >= '0' && *I <= '9') ||\n";
981 O << " *I == '_'))\n";
983 O << " StringRef Name(Start, I - Start);\n";
984 O << " printOperand(MI, getMapOperandNumber(OpMap, Name), OS);\n";
986 O << " OS << *I++;\n";
991 O << " return true;\n";
994 O << "#endif // PRINT_ALIAS_INSTR\n";
997 void AsmWriterEmitter::run(raw_ostream &O) {
998 EmitPrintInstruction(O);
999 EmitGetRegisterName(O);
1000 EmitPrintAliasInstruction(O);
1006 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) {
1007 emitSourceFileHeader("Assembly Writer Source Fragment", OS);
1008 AsmWriterEmitter(RK).run(OS);
1011 } // End llvm namespace