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 "AsmWriterEmitter.h"
16 #include "AsmWriterInst.h"
17 #include "CodeGenTarget.h"
18 #include "StringToOffsetTable.h"
19 #include "SequenceToOffsetTable.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/TableGen/Error.h"
24 #include "llvm/TableGen/Record.h"
28 static void PrintCases(std::vector<std::pair<std::string,
29 AsmWriterOperand> > &OpsToPrint, raw_ostream &O) {
30 O << " case " << OpsToPrint.back().first << ": ";
31 AsmWriterOperand TheOp = OpsToPrint.back().second;
32 OpsToPrint.pop_back();
34 // Check to see if any other operands are identical in this list, and if so,
35 // emit a case label for them.
36 for (unsigned i = OpsToPrint.size(); i != 0; --i)
37 if (OpsToPrint[i-1].second == TheOp) {
38 O << "\n case " << OpsToPrint[i-1].first << ": ";
39 OpsToPrint.erase(OpsToPrint.begin()+i-1);
42 // Finally, emit the code.
48 /// EmitInstructions - Emit the last instruction in the vector and any other
49 /// instructions that are suitably similar to it.
50 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
52 AsmWriterInst FirstInst = Insts.back();
55 std::vector<AsmWriterInst> SimilarInsts;
56 unsigned DifferingOperand = ~0;
57 for (unsigned i = Insts.size(); i != 0; --i) {
58 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
60 if (DifferingOperand == ~0U) // First match!
61 DifferingOperand = DiffOp;
63 // If this differs in the same operand as the rest of the instructions in
64 // this class, move it to the SimilarInsts list.
65 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
66 SimilarInsts.push_back(Insts[i-1]);
67 Insts.erase(Insts.begin()+i-1);
72 O << " case " << FirstInst.CGI->Namespace << "::"
73 << FirstInst.CGI->TheDef->getName() << ":\n";
74 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
75 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
76 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
77 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
78 if (i != DifferingOperand) {
79 // If the operand is the same for all instructions, just print it.
80 O << " " << FirstInst.Operands[i].getCode();
82 // If this is the operand that varies between all of the instructions,
83 // emit a switch for just this operand now.
84 O << " switch (MI->getOpcode()) {\n";
85 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
86 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
87 FirstInst.CGI->TheDef->getName(),
88 FirstInst.Operands[i]));
90 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
91 AsmWriterInst &AWI = SimilarInsts[si];
92 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
93 AWI.CGI->TheDef->getName(),
96 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
97 while (!OpsToPrint.empty())
98 PrintCases(OpsToPrint, O);
106 void AsmWriterEmitter::
107 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
108 std::vector<unsigned> &InstIdxs,
109 std::vector<unsigned> &InstOpsUsed) const {
110 InstIdxs.assign(NumberedInstructions.size(), ~0U);
112 // This vector parallels UniqueOperandCommands, keeping track of which
113 // instructions each case are used for. It is a comma separated string of
115 std::vector<std::string> InstrsForCase;
116 InstrsForCase.resize(UniqueOperandCommands.size());
117 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
119 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
120 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
121 if (Inst == 0) continue; // PHI, INLINEASM, PROLOG_LABEL, etc.
124 if (Inst->Operands.empty())
125 continue; // Instruction already done.
127 Command = " " + Inst->Operands[0].getCode() + "\n";
129 // Check to see if we already have 'Command' in UniqueOperandCommands.
131 bool FoundIt = false;
132 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
133 if (UniqueOperandCommands[idx] == Command) {
135 InstrsForCase[idx] += ", ";
136 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
141 InstIdxs[i] = UniqueOperandCommands.size();
142 UniqueOperandCommands.push_back(Command);
143 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
145 // This command matches one operand so far.
146 InstOpsUsed.push_back(1);
150 // For each entry of UniqueOperandCommands, there is a set of instructions
151 // that uses it. If the next command of all instructions in the set are
152 // identical, fold it into the command.
153 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
154 CommandIdx != e; ++CommandIdx) {
156 for (unsigned Op = 1; ; ++Op) {
157 // Scan for the first instruction in the set.
158 std::vector<unsigned>::iterator NIT =
159 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
160 if (NIT == InstIdxs.end()) break; // No commonality.
162 // If this instruction has no more operands, we isn't anything to merge
163 // into this command.
164 const AsmWriterInst *FirstInst =
165 getAsmWriterInstByID(NIT-InstIdxs.begin());
166 if (!FirstInst || FirstInst->Operands.size() == Op)
169 // Otherwise, scan to see if all of the other instructions in this command
170 // set share the operand.
172 // Keep track of the maximum, number of operands or any
173 // instruction we see in the group.
174 size_t MaxSize = FirstInst->Operands.size();
176 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
177 NIT != InstIdxs.end();
178 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
179 // Okay, found another instruction in this command set. If the operand
180 // matches, we're ok, otherwise bail out.
181 const AsmWriterInst *OtherInst =
182 getAsmWriterInstByID(NIT-InstIdxs.begin());
185 OtherInst->Operands.size() > FirstInst->Operands.size())
186 MaxSize = std::max(MaxSize, OtherInst->Operands.size());
188 if (!OtherInst || OtherInst->Operands.size() == Op ||
189 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
196 // Okay, everything in this command set has the same next operand. Add it
197 // to UniqueOperandCommands and remember that it was consumed.
198 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
200 UniqueOperandCommands[CommandIdx] += Command;
201 InstOpsUsed[CommandIdx]++;
205 // Prepend some of the instructions each case is used for onto the case val.
206 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
207 std::string Instrs = InstrsForCase[i];
208 if (Instrs.size() > 70) {
209 Instrs.erase(Instrs.begin()+70, Instrs.end());
214 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
215 UniqueOperandCommands[i];
220 static void UnescapeString(std::string &Str) {
221 for (unsigned i = 0; i != Str.size(); ++i) {
222 if (Str[i] == '\\' && i != Str.size()-1) {
224 default: continue; // Don't execute the code after the switch.
225 case 'a': Str[i] = '\a'; break;
226 case 'b': Str[i] = '\b'; break;
227 case 'e': Str[i] = 27; break;
228 case 'f': Str[i] = '\f'; break;
229 case 'n': Str[i] = '\n'; break;
230 case 'r': Str[i] = '\r'; break;
231 case 't': Str[i] = '\t'; break;
232 case 'v': Str[i] = '\v'; break;
233 case '"': Str[i] = '\"'; break;
234 case '\'': Str[i] = '\''; break;
235 case '\\': Str[i] = '\\'; break;
237 // Nuke the second character.
238 Str.erase(Str.begin()+i+1);
243 /// EmitPrintInstruction - Generate the code for the "printInstruction" method
245 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) {
246 CodeGenTarget Target(Records);
247 Record *AsmWriter = Target.getAsmWriter();
248 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
249 bool isMC = AsmWriter->getValueAsBit("isMCAsmWriter");
250 const char *MachineInstrClassName = isMC ? "MCInst" : "MachineInstr";
253 "/// printInstruction - This method is automatically generated by tablegen\n"
254 "/// from the instruction set description.\n"
255 "void " << Target.getName() << ClassName
256 << "::printInstruction(const " << MachineInstrClassName
257 << " *MI, raw_ostream &O) {\n";
259 std::vector<AsmWriterInst> Instructions;
261 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
262 E = Target.inst_end(); I != E; ++I)
263 if (!(*I)->AsmString.empty() &&
264 (*I)->TheDef->getName() != "PHI")
265 Instructions.push_back(
267 AsmWriter->getValueAsInt("Variant"),
268 AsmWriter->getValueAsInt("FirstOperandColumn"),
269 AsmWriter->getValueAsInt("OperandSpacing")));
271 // Get the instruction numbering.
272 NumberedInstructions = Target.getInstructionsByEnumValue();
274 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
275 // all machine instructions are necessarily being printed, so there may be
276 // target instructions not in this map.
277 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
278 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
280 // Build an aggregate string, and build a table of offsets into it.
281 StringToOffsetTable StringTable;
283 /// OpcodeInfo - This encodes the index of the string to use for the first
284 /// chunk of the output as well as indices used for operand printing.
285 std::vector<unsigned> OpcodeInfo;
287 unsigned MaxStringIdx = 0;
288 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
289 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
292 // Something not handled by the asmwriter printer.
294 } else if (AWI->Operands[0].OperandType !=
295 AsmWriterOperand::isLiteralTextOperand ||
296 AWI->Operands[0].Str.empty()) {
297 // Something handled by the asmwriter printer, but with no leading string.
298 Idx = StringTable.GetOrAddStringOffset("");
300 std::string Str = AWI->Operands[0].Str;
302 Idx = StringTable.GetOrAddStringOffset(Str);
303 MaxStringIdx = std::max(MaxStringIdx, Idx);
305 // Nuke the string from the operand list. It is now handled!
306 AWI->Operands.erase(AWI->Operands.begin());
309 // Bias offset by one since we want 0 as a sentinel.
310 OpcodeInfo.push_back(Idx+1);
313 // Figure out how many bits we used for the string index.
314 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
316 // To reduce code size, we compactify common instructions into a few bits
317 // in the opcode-indexed table.
318 unsigned BitsLeft = 32-AsmStrBits;
320 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
323 std::vector<std::string> UniqueOperandCommands;
324 std::vector<unsigned> InstIdxs;
325 std::vector<unsigned> NumInstOpsHandled;
326 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
329 // If we ran out of operands to print, we're done.
330 if (UniqueOperandCommands.empty()) break;
332 // Compute the number of bits we need to represent these cases, this is
333 // ceil(log2(numentries)).
334 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
336 // If we don't have enough bits for this operand, don't include it.
337 if (NumBits > BitsLeft) {
338 DEBUG(errs() << "Not enough bits to densely encode " << NumBits
343 // Otherwise, we can include this in the initial lookup table. Add it in.
345 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
346 if (InstIdxs[i] != ~0U)
347 OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
349 // Remove the info about this operand.
350 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
351 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
352 if (!Inst->Operands.empty()) {
353 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
354 assert(NumOps <= Inst->Operands.size() &&
355 "Can't remove this many ops!");
356 Inst->Operands.erase(Inst->Operands.begin(),
357 Inst->Operands.begin()+NumOps);
361 // Remember the handlers for this set of operands.
362 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
367 O<<" static const unsigned OpInfo[] = {\n";
368 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
369 O << " " << OpcodeInfo[i] << "U,\t// "
370 << NumberedInstructions[i]->TheDef->getName() << "\n";
372 // Add a dummy entry so the array init doesn't end with a comma.
376 // Emit the string itself.
377 O << " const char *const AsmStrs = \n";
378 StringTable.EmitString(O);
381 O << " O << \"\\t\";\n\n";
383 O << " // Emit the opcode for the instruction.\n"
384 << " unsigned Bits = OpInfo[MI->getOpcode()];\n"
385 << " assert(Bits != 0 && \"Cannot print this instruction.\");\n"
386 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
388 // Output the table driven operand information.
389 BitsLeft = 32-AsmStrBits;
390 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
391 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
393 // Compute the number of bits we need to represent these cases, this is
394 // ceil(log2(numentries)).
395 unsigned NumBits = Log2_32_Ceil(Commands.size());
396 assert(NumBits <= BitsLeft && "consistency error");
398 // Emit code to extract this field from Bits.
401 O << "\n // Fragment " << i << " encoded into " << NumBits
402 << " bits for " << Commands.size() << " unique commands.\n";
404 if (Commands.size() == 2) {
405 // Emit two possibilitys with if/else.
406 O << " if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
407 << ((1 << NumBits)-1) << ") {\n"
412 } else if (Commands.size() == 1) {
413 // Emit a single possibility.
414 O << Commands[0] << "\n\n";
416 O << " switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
417 << ((1 << NumBits)-1) << ") {\n"
418 << " default: // unreachable.\n";
420 // Print out all the cases.
421 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
422 O << " case " << i << ":\n";
430 // Okay, delete instructions with no operand info left.
431 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
432 // Entire instruction has been emitted?
433 AsmWriterInst &Inst = Instructions[i];
434 if (Inst.Operands.empty()) {
435 Instructions.erase(Instructions.begin()+i);
441 // Because this is a vector, we want to emit from the end. Reverse all of the
442 // elements in the vector.
443 std::reverse(Instructions.begin(), Instructions.end());
446 // Now that we've emitted all of the operand info that fit into 32 bits, emit
447 // information for those instructions that are left. This is a less dense
448 // encoding, but we expect the main 32-bit table to handle the majority of
450 if (!Instructions.empty()) {
451 // Find the opcode # of inline asm.
452 O << " switch (MI->getOpcode()) {\n";
453 while (!Instructions.empty())
454 EmitInstructions(Instructions, O);
464 emitRegisterNameString(raw_ostream &O, StringRef AltName,
465 const std::vector<CodeGenRegister*> &Registers) {
466 SequenceToOffsetTable<std::string> StringTable;
467 SmallVector<std::string, 4> AsmNames(Registers.size());
468 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
469 const CodeGenRegister &Reg = *Registers[i];
470 std::string &AsmName = AsmNames[i];
472 // "NoRegAltName" is special. We don't need to do a lookup for that,
473 // as it's just a reference to the default register name.
474 if (AltName == "" || AltName == "NoRegAltName") {
475 AsmName = Reg.TheDef->getValueAsString("AsmName");
477 AsmName = Reg.getName();
479 // Make sure the register has an alternate name for this index.
480 std::vector<Record*> AltNameList =
481 Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
483 for (e = AltNameList.size();
484 Idx < e && (AltNameList[Idx]->getName() != AltName);
487 // If the register has an alternate name for this index, use it.
488 // Otherwise, leave it empty as an error flag.
490 std::vector<std::string> AltNames =
491 Reg.TheDef->getValueAsListOfStrings("AltNames");
492 if (AltNames.size() <= Idx)
493 throw TGError(Reg.TheDef->getLoc(),
494 (Twine("Register definition missing alt name for '") +
495 AltName + "'.").str());
496 AsmName = AltNames[Idx];
499 StringTable.add(AsmName);
502 StringTable.layout();
503 O << " static const char AsmStrs" << AltName << "[] = {\n";
504 StringTable.emit(O, printChar);
507 O << " static const unsigned RegAsmOffset" << AltName << "[] = {";
508 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
511 O << StringTable.get(AsmNames[i]) << ", ";
517 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
518 CodeGenTarget Target(Records);
519 Record *AsmWriter = Target.getAsmWriter();
520 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
521 const std::vector<CodeGenRegister*> &Registers =
522 Target.getRegBank().getRegisters();
523 std::vector<Record*> AltNameIndices = Target.getRegAltNameIndices();
524 bool hasAltNames = AltNameIndices.size() > 1;
527 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
528 "/// from the register set description. This returns the assembler name\n"
529 "/// for the specified register.\n"
530 "const char *" << Target.getName() << ClassName << "::";
532 O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
534 O << "getRegisterName(unsigned RegNo) {\n";
535 O << " assert(RegNo && RegNo < " << (Registers.size()+1)
536 << " && \"Invalid register number!\");\n"
540 for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i)
541 emitRegisterNameString(O, AltNameIndices[i]->getName(), Registers);
543 emitRegisterNameString(O, "", Registers);
546 O << " const unsigned *RegAsmOffset;\n"
547 << " const char *AsmStrs;\n"
548 << " switch(AltIdx) {\n"
549 << " default: llvm_unreachable(\"Invalid register alt name index!\");\n";
550 for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i) {
551 StringRef Namespace = AltNameIndices[1]->getValueAsString("Namespace");
552 StringRef AltName(AltNameIndices[i]->getName());
553 O << " case " << Namespace << "::" << AltName
555 << " AsmStrs = AsmStrs" << AltName << ";\n"
556 << " RegAsmOffset = RegAsmOffset" << AltName << ";\n"
562 O << " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
563 << " \"Invalid alt name index for register!\");\n"
564 << " return AsmStrs+RegAsmOffset[RegNo-1];\n"
569 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if
570 // they both have the same conditionals. In which case, we cannot print out the
571 // alias for that pattern.
573 std::vector<std::string> Conds;
574 std::map<StringRef, unsigned> OpMap;
576 std::string AsmString;
577 std::vector<Record*> ReqFeatures;
579 IAPrinter(std::string R, std::string AS)
580 : Result(R), AsmString(AS) {}
582 void addCond(const std::string &C) { Conds.push_back(C); }
584 void addOperand(StringRef Op, unsigned Idx) { OpMap[Op] = Idx; }
585 unsigned getOpIndex(StringRef Op) { return OpMap[Op]; }
586 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
588 void print(raw_ostream &O) {
589 if (Conds.empty() && ReqFeatures.empty()) {
590 O.indent(6) << "return true;\n";
596 for (std::vector<std::string>::iterator
597 I = Conds.begin(), E = Conds.end(); I != E; ++I) {
598 if (I != Conds.begin()) {
607 O.indent(6) << "// " << Result << "\n";
608 O.indent(6) << "AsmString = \"" << AsmString << "\";\n";
610 for (std::map<StringRef, unsigned>::iterator
611 I = OpMap.begin(), E = OpMap.end(); I != E; ++I)
612 O.indent(6) << "OpMap.push_back(std::make_pair(\"" << I->first << "\", "
613 << I->second << "));\n";
615 O.indent(6) << "break;\n";
619 bool operator==(const IAPrinter &RHS) {
620 if (Conds.size() != RHS.Conds.size())
624 for (std::vector<std::string>::iterator
625 I = Conds.begin(), E = Conds.end(); I != E; ++I)
626 if (*I != RHS.Conds[Idx++])
632 bool operator()(const IAPrinter &RHS) {
633 if (Conds.size() < RHS.Conds.size())
637 for (std::vector<std::string>::iterator
638 I = Conds.begin(), E = Conds.end(); I != E; ++I)
639 if (*I != RHS.Conds[Idx++])
640 return *I < RHS.Conds[Idx++];
646 } // end anonymous namespace
648 static void EmitGetMapOperandNumber(raw_ostream &O) {
649 O << "static unsigned getMapOperandNumber("
650 << "const SmallVectorImpl<std::pair<StringRef, unsigned> > &OpMap,\n";
651 O << " StringRef Name) {\n";
652 O << " for (SmallVectorImpl<std::pair<StringRef, unsigned> >::"
653 << "const_iterator\n";
654 O << " I = OpMap.begin(), E = OpMap.end(); I != E; ++I)\n";
655 O << " if (I->first == Name)\n";
656 O << " return I->second;\n";
657 O << " assert(false && \"Operand not in map!\");\n";
662 static unsigned CountNumOperands(StringRef AsmString) {
664 std::pair<StringRef, StringRef> ASM = AsmString.split(' ');
666 while (!ASM.second.empty()) {
668 ASM = ASM.second.split(' ');
674 static unsigned CountResultNumOperands(StringRef AsmString) {
676 std::pair<StringRef, StringRef> ASM = AsmString.split('\t');
678 if (!ASM.second.empty()) {
679 size_t I = ASM.second.find('{');
680 StringRef Str = ASM.second;
681 if (I != StringRef::npos)
682 Str = ASM.second.substr(I, ASM.second.find('|', I));
684 ASM = Str.split(' ');
688 ASM = ASM.second.split(' ');
689 } while (!ASM.second.empty());
695 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
696 CodeGenTarget Target(Records);
697 Record *AsmWriter = Target.getAsmWriter();
699 if (!AsmWriter->getValueAsBit("isMCAsmWriter"))
702 O << "\n#ifdef PRINT_ALIAS_INSTR\n";
703 O << "#undef PRINT_ALIAS_INSTR\n\n";
705 // Emit the method that prints the alias instruction.
706 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
708 std::vector<Record*> AllInstAliases =
709 Records.getAllDerivedDefinitions("InstAlias");
711 // Create a map from the qualified name to a list of potential matches.
712 std::map<std::string, std::vector<CodeGenInstAlias*> > AliasMap;
713 for (std::vector<Record*>::iterator
714 I = AllInstAliases.begin(), E = AllInstAliases.end(); I != E; ++I) {
715 CodeGenInstAlias *Alias = new CodeGenInstAlias(*I, Target);
716 const Record *R = *I;
717 if (!R->getValueAsBit("EmitAlias"))
718 continue; // We were told not to emit the alias, but to emit the aliasee.
719 const DagInit *DI = R->getValueAsDag("ResultInst");
720 const DefInit *Op = dynamic_cast<const DefInit*>(DI->getOperator());
721 AliasMap[getQualifiedName(Op->getDef())].push_back(Alias);
724 // A map of which conditions need to be met for each instruction operand
725 // before it can be matched to the mnemonic.
726 std::map<std::string, std::vector<IAPrinter*> > IAPrinterMap;
728 for (std::map<std::string, std::vector<CodeGenInstAlias*> >::iterator
729 I = AliasMap.begin(), E = AliasMap.end(); I != E; ++I) {
730 std::vector<CodeGenInstAlias*> &Aliases = I->second;
732 for (std::vector<CodeGenInstAlias*>::iterator
733 II = Aliases.begin(), IE = Aliases.end(); II != IE; ++II) {
734 const CodeGenInstAlias *CGA = *II;
735 unsigned LastOpNo = CGA->ResultInstOperandIndex.size();
736 unsigned NumResultOps =
737 CountResultNumOperands(CGA->ResultInst->AsmString);
739 // Don't emit the alias if it has more operands than what it's aliasing.
740 if (NumResultOps < CountNumOperands(CGA->AsmString))
743 IAPrinter *IAP = new IAPrinter(CGA->Result->getAsString(),
747 Cond = std::string("MI->getNumOperands() == ") + llvm::utostr(LastOpNo);
750 std::map<StringRef, unsigned> OpMap;
751 bool CantHandle = false;
753 for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
754 const CodeGenInstAlias::ResultOperand &RO = CGA->ResultOperands[i];
757 case CodeGenInstAlias::ResultOperand::K_Record: {
758 const Record *Rec = RO.getRecord();
759 StringRef ROName = RO.getName();
762 if (Rec->isSubClassOf("RegisterOperand"))
763 Rec = Rec->getValueAsDef("RegClass");
764 if (Rec->isSubClassOf("RegisterClass")) {
765 Cond = std::string("MI->getOperand(")+llvm::utostr(i)+").isReg()";
768 if (!IAP->isOpMapped(ROName)) {
769 IAP->addOperand(ROName, i);
770 Cond = std::string("MRI.getRegClass(") + Target.getName() + "::" +
771 CGA->ResultOperands[i].getRecord()->getName() + "RegClassID)"
772 ".contains(MI->getOperand(" + llvm::utostr(i) + ").getReg())";
775 Cond = std::string("MI->getOperand(") +
776 llvm::utostr(i) + ").getReg() == MI->getOperand(" +
777 llvm::utostr(IAP->getOpIndex(ROName)) + ").getReg()";
781 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
782 // FIXME: We may need to handle these situations.
791 case CodeGenInstAlias::ResultOperand::K_Imm:
792 Cond = std::string("MI->getOperand(") +
793 llvm::utostr(i) + ").getImm() == " +
794 llvm::utostr(CGA->ResultOperands[i].getImm());
797 case CodeGenInstAlias::ResultOperand::K_Reg:
798 // If this is zero_reg, something's playing tricks we're not
799 // equipped to handle.
800 if (!CGA->ResultOperands[i].getRegister()) {
805 Cond = std::string("MI->getOperand(") +
806 llvm::utostr(i) + ").getReg() == " + Target.getName() +
807 "::" + CGA->ResultOperands[i].getRegister()->getName();
815 if (CantHandle) continue;
816 IAPrinterMap[I->first].push_back(IAP);
821 raw_string_ostream HeaderO(Header);
823 HeaderO << "bool " << Target.getName() << ClassName
824 << "::printAliasInstr(const MCInst"
825 << " *MI, raw_ostream &OS) {\n";
828 raw_string_ostream CasesO(Cases);
830 for (std::map<std::string, std::vector<IAPrinter*> >::iterator
831 I = IAPrinterMap.begin(), E = IAPrinterMap.end(); I != E; ++I) {
832 std::vector<IAPrinter*> &IAPs = I->second;
833 std::vector<IAPrinter*> UniqueIAPs;
835 for (std::vector<IAPrinter*>::iterator
836 II = IAPs.begin(), IE = IAPs.end(); II != IE; ++II) {
837 IAPrinter *LHS = *II;
839 for (std::vector<IAPrinter*>::iterator
840 III = IAPs.begin(), IIE = IAPs.end(); III != IIE; ++III) {
841 IAPrinter *RHS = *III;
842 if (LHS != RHS && *LHS == *RHS) {
848 if (!IsDup) UniqueIAPs.push_back(LHS);
851 if (UniqueIAPs.empty()) continue;
853 CasesO.indent(2) << "case " << I->first << ":\n";
855 for (std::vector<IAPrinter*>::iterator
856 II = UniqueIAPs.begin(), IE = UniqueIAPs.end(); II != IE; ++II) {
857 IAPrinter *IAP = *II;
863 CasesO.indent(4) << "return false;\n";
866 if (CasesO.str().empty()) {
868 O << " return false;\n";
870 O << "#endif // PRINT_ALIAS_INSTR\n";
874 EmitGetMapOperandNumber(O);
877 O.indent(2) << "StringRef AsmString;\n";
878 O.indent(2) << "SmallVector<std::pair<StringRef, unsigned>, 4> OpMap;\n";
879 O.indent(2) << "switch (MI->getOpcode()) {\n";
880 O.indent(2) << "default: return false;\n";
882 O.indent(2) << "}\n\n";
884 // Code that prints the alias, replacing the operands with the ones from the
886 O << " std::pair<StringRef, StringRef> ASM = AsmString.split(' ');\n";
887 O << " OS << '\\t' << ASM.first;\n";
889 O << " if (!ASM.second.empty()) {\n";
890 O << " OS << '\\t';\n";
891 O << " for (StringRef::iterator\n";
892 O << " I = ASM.second.begin(), E = ASM.second.end(); I != E; ) {\n";
893 O << " if (*I == '$') {\n";
894 O << " StringRef::iterator Start = ++I;\n";
895 O << " while (I != E &&\n";
896 O << " ((*I >= 'a' && *I <= 'z') ||\n";
897 O << " (*I >= 'A' && *I <= 'Z') ||\n";
898 O << " (*I >= '0' && *I <= '9') ||\n";
899 O << " *I == '_'))\n";
901 O << " StringRef Name(Start, I - Start);\n";
902 O << " printOperand(MI, getMapOperandNumber(OpMap, Name), OS);\n";
904 O << " OS << *I++;\n";
909 O << " return true;\n";
912 O << "#endif // PRINT_ALIAS_INSTR\n";
915 void AsmWriterEmitter::run(raw_ostream &O) {
916 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
918 EmitPrintInstruction(O);
919 EmitGetRegisterName(O);
920 EmitPrintAliasInstruction(O);