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 std::vector<unsigned> OpcodeInfo;
318 // Add all strings to the string table upfront so it can generate an optimized
320 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
321 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
323 AWI->Operands[0].OperandType ==
324 AsmWriterOperand::isLiteralTextOperand &&
325 !AWI->Operands[0].Str.empty()) {
326 std::string Str = AWI->Operands[0].Str;
328 StringTable.add(Str);
332 StringTable.layout();
334 unsigned MaxStringIdx = 0;
335 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
336 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
339 // Something not handled by the asmwriter printer.
341 } else if (AWI->Operands[0].OperandType !=
342 AsmWriterOperand::isLiteralTextOperand ||
343 AWI->Operands[0].Str.empty()) {
344 // Something handled by the asmwriter printer, but with no leading string.
345 Idx = StringTable.get("");
347 std::string Str = AWI->Operands[0].Str;
349 Idx = StringTable.get(Str);
350 MaxStringIdx = std::max(MaxStringIdx, Idx);
352 // Nuke the string from the operand list. It is now handled!
353 AWI->Operands.erase(AWI->Operands.begin());
356 // Bias offset by one since we want 0 as a sentinel.
357 OpcodeInfo.push_back(Idx+1);
360 // Figure out how many bits we used for the string index.
361 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
363 // To reduce code size, we compactify common instructions into a few bits
364 // in the opcode-indexed table.
365 unsigned BitsLeft = 32-AsmStrBits;
367 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
370 std::vector<std::string> UniqueOperandCommands;
371 std::vector<unsigned> InstIdxs;
372 std::vector<unsigned> NumInstOpsHandled;
373 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
376 // If we ran out of operands to print, we're done.
377 if (UniqueOperandCommands.empty()) break;
379 // Compute the number of bits we need to represent these cases, this is
380 // ceil(log2(numentries)).
381 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
383 // If we don't have enough bits for this operand, don't include it.
384 if (NumBits > BitsLeft) {
385 DEBUG(errs() << "Not enough bits to densely encode " << NumBits
390 // Otherwise, we can include this in the initial lookup table. Add it in.
392 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
393 if (InstIdxs[i] != ~0U)
394 OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
396 // Remove the info about this operand.
397 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
398 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
399 if (!Inst->Operands.empty()) {
400 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
401 assert(NumOps <= Inst->Operands.size() &&
402 "Can't remove this many ops!");
403 Inst->Operands.erase(Inst->Operands.begin(),
404 Inst->Operands.begin()+NumOps);
408 // Remember the handlers for this set of operands.
409 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
414 O<<" static const unsigned OpInfo[] = {\n";
415 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
416 O << " " << OpcodeInfo[i] << "U,\t// "
417 << NumberedInstructions[i]->TheDef->getName() << "\n";
419 // Add a dummy entry so the array init doesn't end with a comma.
423 // Emit the string itself.
424 O << " const char AsmStrs[] = {\n";
425 StringTable.emit(O, printChar);
428 O << " O << \"\\t\";\n\n";
430 O << " // Emit the opcode for the instruction.\n"
431 << " unsigned Bits = OpInfo[MI->getOpcode()];\n"
432 << " assert(Bits != 0 && \"Cannot print this instruction.\");\n"
433 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
435 // Output the table driven operand information.
436 BitsLeft = 32-AsmStrBits;
437 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
438 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
440 // Compute the number of bits we need to represent these cases, this is
441 // ceil(log2(numentries)).
442 unsigned NumBits = Log2_32_Ceil(Commands.size());
443 assert(NumBits <= BitsLeft && "consistency error");
445 // Emit code to extract this field from Bits.
448 O << "\n // Fragment " << i << " encoded into " << NumBits
449 << " bits for " << Commands.size() << " unique commands.\n";
451 if (Commands.size() == 2) {
452 // Emit two possibilitys with if/else.
453 O << " if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
454 << ((1 << NumBits)-1) << ") {\n"
459 } else if (Commands.size() == 1) {
460 // Emit a single possibility.
461 O << Commands[0] << "\n\n";
463 O << " switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
464 << ((1 << NumBits)-1) << ") {\n"
465 << " default: // unreachable.\n";
467 // Print out all the cases.
468 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
469 O << " case " << i << ":\n";
477 // Okay, delete instructions with no operand info left.
478 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
479 // Entire instruction has been emitted?
480 AsmWriterInst &Inst = Instructions[i];
481 if (Inst.Operands.empty()) {
482 Instructions.erase(Instructions.begin()+i);
488 // Because this is a vector, we want to emit from the end. Reverse all of the
489 // elements in the vector.
490 std::reverse(Instructions.begin(), Instructions.end());
493 // Now that we've emitted all of the operand info that fit into 32 bits, emit
494 // information for those instructions that are left. This is a less dense
495 // encoding, but we expect the main 32-bit table to handle the majority of
497 if (!Instructions.empty()) {
498 // Find the opcode # of inline asm.
499 O << " switch (MI->getOpcode()) {\n";
500 while (!Instructions.empty())
501 EmitInstructions(Instructions, O);
511 emitRegisterNameString(raw_ostream &O, StringRef AltName,
512 const std::vector<CodeGenRegister*> &Registers) {
513 SequenceToOffsetTable<std::string> StringTable;
514 SmallVector<std::string, 4> AsmNames(Registers.size());
515 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
516 const CodeGenRegister &Reg = *Registers[i];
517 std::string &AsmName = AsmNames[i];
519 // "NoRegAltName" is special. We don't need to do a lookup for that,
520 // as it's just a reference to the default register name.
521 if (AltName == "" || AltName == "NoRegAltName") {
522 AsmName = Reg.TheDef->getValueAsString("AsmName");
524 AsmName = Reg.getName();
526 // Make sure the register has an alternate name for this index.
527 std::vector<Record*> AltNameList =
528 Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
530 for (e = AltNameList.size();
531 Idx < e && (AltNameList[Idx]->getName() != AltName);
534 // If the register has an alternate name for this index, use it.
535 // Otherwise, leave it empty as an error flag.
537 std::vector<std::string> AltNames =
538 Reg.TheDef->getValueAsListOfStrings("AltNames");
539 if (AltNames.size() <= Idx)
540 throw TGError(Reg.TheDef->getLoc(),
541 (Twine("Register definition missing alt name for '") +
542 AltName + "'.").str());
543 AsmName = AltNames[Idx];
546 StringTable.add(AsmName);
549 StringTable.layout();
550 O << " static const char AsmStrs" << AltName << "[] = {\n";
551 StringTable.emit(O, printChar);
554 O << " static const unsigned RegAsmOffset" << AltName << "[] = {";
555 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
558 O << StringTable.get(AsmNames[i]) << ", ";
564 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
565 CodeGenTarget Target(Records);
566 Record *AsmWriter = Target.getAsmWriter();
567 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
568 const std::vector<CodeGenRegister*> &Registers =
569 Target.getRegBank().getRegisters();
570 std::vector<Record*> AltNameIndices = Target.getRegAltNameIndices();
571 bool hasAltNames = AltNameIndices.size() > 1;
574 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
575 "/// from the register set description. This returns the assembler name\n"
576 "/// for the specified register.\n"
577 "const char *" << Target.getName() << ClassName << "::";
579 O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
581 O << "getRegisterName(unsigned RegNo) {\n";
582 O << " assert(RegNo && RegNo < " << (Registers.size()+1)
583 << " && \"Invalid register number!\");\n"
587 for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i)
588 emitRegisterNameString(O, AltNameIndices[i]->getName(), Registers);
590 emitRegisterNameString(O, "", Registers);
593 O << " const unsigned *RegAsmOffset;\n"
594 << " const char *AsmStrs;\n"
595 << " switch(AltIdx) {\n"
596 << " default: llvm_unreachable(\"Invalid register alt name index!\");\n";
597 for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i) {
598 StringRef Namespace = AltNameIndices[1]->getValueAsString("Namespace");
599 StringRef AltName(AltNameIndices[i]->getName());
600 O << " case " << Namespace << "::" << AltName
602 << " AsmStrs = AsmStrs" << AltName << ";\n"
603 << " RegAsmOffset = RegAsmOffset" << AltName << ";\n"
609 O << " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
610 << " \"Invalid alt name index for register!\");\n"
611 << " return AsmStrs+RegAsmOffset[RegNo-1];\n"
616 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if
617 // they both have the same conditionals. In which case, we cannot print out the
618 // alias for that pattern.
620 std::vector<std::string> Conds;
621 std::map<StringRef, unsigned> OpMap;
623 std::string AsmString;
624 SmallVector<Record*, 4> ReqFeatures;
626 IAPrinter(std::string R, std::string AS)
627 : Result(R), AsmString(AS) {}
629 void addCond(const std::string &C) { Conds.push_back(C); }
631 void addOperand(StringRef Op, unsigned Idx) { OpMap[Op] = Idx; }
632 unsigned getOpIndex(StringRef Op) { return OpMap[Op]; }
633 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
635 void print(raw_ostream &O) {
636 if (Conds.empty() && ReqFeatures.empty()) {
637 O.indent(6) << "return true;\n";
643 for (std::vector<std::string>::iterator
644 I = Conds.begin(), E = Conds.end(); I != E; ++I) {
645 if (I != Conds.begin()) {
654 O.indent(6) << "// " << Result << "\n";
655 O.indent(6) << "AsmString = \"" << AsmString << "\";\n";
657 for (std::map<StringRef, unsigned>::iterator
658 I = OpMap.begin(), E = OpMap.end(); I != E; ++I)
659 O.indent(6) << "OpMap.push_back(std::make_pair(\"" << I->first << "\", "
660 << I->second << "));\n";
662 O.indent(6) << "break;\n";
666 bool operator==(const IAPrinter &RHS) {
667 if (Conds.size() != RHS.Conds.size())
671 for (std::vector<std::string>::iterator
672 I = Conds.begin(), E = Conds.end(); I != E; ++I)
673 if (*I != RHS.Conds[Idx++])
679 bool operator()(const IAPrinter &RHS) {
680 if (Conds.size() < RHS.Conds.size())
684 for (std::vector<std::string>::iterator
685 I = Conds.begin(), E = Conds.end(); I != E; ++I)
686 if (*I != RHS.Conds[Idx++])
687 return *I < RHS.Conds[Idx++];
693 } // end anonymous namespace
695 static void EmitGetMapOperandNumber(raw_ostream &O) {
696 O << "static unsigned getMapOperandNumber("
697 << "const SmallVectorImpl<std::pair<StringRef, unsigned> > &OpMap,\n";
698 O << " StringRef Name) {\n";
699 O << " for (SmallVectorImpl<std::pair<StringRef, unsigned> >::"
700 << "const_iterator\n";
701 O << " I = OpMap.begin(), E = OpMap.end(); I != E; ++I)\n";
702 O << " if (I->first == Name)\n";
703 O << " return I->second;\n";
704 O << " llvm_unreachable(\"Operand not in map!\");\n";
708 static unsigned CountNumOperands(StringRef AsmString) {
710 std::pair<StringRef, StringRef> ASM = AsmString.split(' ');
712 while (!ASM.second.empty()) {
714 ASM = ASM.second.split(' ');
720 static unsigned CountResultNumOperands(StringRef AsmString) {
722 std::pair<StringRef, StringRef> ASM = AsmString.split('\t');
724 if (!ASM.second.empty()) {
725 size_t I = ASM.second.find('{');
726 StringRef Str = ASM.second;
727 if (I != StringRef::npos)
728 Str = ASM.second.substr(I, ASM.second.find('|', I));
730 ASM = Str.split(' ');
734 ASM = ASM.second.split(' ');
735 } while (!ASM.second.empty());
741 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
742 CodeGenTarget Target(Records);
743 Record *AsmWriter = Target.getAsmWriter();
745 if (!AsmWriter->getValueAsBit("isMCAsmWriter"))
748 O << "\n#ifdef PRINT_ALIAS_INSTR\n";
749 O << "#undef PRINT_ALIAS_INSTR\n\n";
751 // Emit the method that prints the alias instruction.
752 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
754 std::vector<Record*> AllInstAliases =
755 Records.getAllDerivedDefinitions("InstAlias");
757 // Create a map from the qualified name to a list of potential matches.
758 std::map<std::string, std::vector<CodeGenInstAlias*> > AliasMap;
759 for (std::vector<Record*>::iterator
760 I = AllInstAliases.begin(), E = AllInstAliases.end(); I != E; ++I) {
761 CodeGenInstAlias *Alias = new CodeGenInstAlias(*I, Target);
762 const Record *R = *I;
763 if (!R->getValueAsBit("EmitAlias"))
764 continue; // We were told not to emit the alias, but to emit the aliasee.
765 const DagInit *DI = R->getValueAsDag("ResultInst");
766 const DefInit *Op = dynamic_cast<const DefInit*>(DI->getOperator());
767 AliasMap[getQualifiedName(Op->getDef())].push_back(Alias);
770 // A map of which conditions need to be met for each instruction operand
771 // before it can be matched to the mnemonic.
772 std::map<std::string, std::vector<IAPrinter*> > IAPrinterMap;
774 for (std::map<std::string, std::vector<CodeGenInstAlias*> >::iterator
775 I = AliasMap.begin(), E = AliasMap.end(); I != E; ++I) {
776 std::vector<CodeGenInstAlias*> &Aliases = I->second;
778 for (std::vector<CodeGenInstAlias*>::iterator
779 II = Aliases.begin(), IE = Aliases.end(); II != IE; ++II) {
780 const CodeGenInstAlias *CGA = *II;
781 unsigned LastOpNo = CGA->ResultInstOperandIndex.size();
782 unsigned NumResultOps =
783 CountResultNumOperands(CGA->ResultInst->AsmString);
785 // Don't emit the alias if it has more operands than what it's aliasing.
786 if (NumResultOps < CountNumOperands(CGA->AsmString))
789 IAPrinter *IAP = new IAPrinter(CGA->Result->getAsString(),
793 Cond = std::string("MI->getNumOperands() == ") + llvm::utostr(LastOpNo);
796 std::map<StringRef, unsigned> OpMap;
797 bool CantHandle = false;
799 for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
800 const CodeGenInstAlias::ResultOperand &RO = CGA->ResultOperands[i];
803 case CodeGenInstAlias::ResultOperand::K_Record: {
804 const Record *Rec = RO.getRecord();
805 StringRef ROName = RO.getName();
808 if (Rec->isSubClassOf("RegisterOperand"))
809 Rec = Rec->getValueAsDef("RegClass");
810 if (Rec->isSubClassOf("RegisterClass")) {
811 Cond = std::string("MI->getOperand(")+llvm::utostr(i)+").isReg()";
814 if (!IAP->isOpMapped(ROName)) {
815 IAP->addOperand(ROName, i);
816 Cond = std::string("MRI.getRegClass(") + Target.getName() + "::" +
817 CGA->ResultOperands[i].getRecord()->getName() + "RegClassID)"
818 ".contains(MI->getOperand(" + llvm::utostr(i) + ").getReg())";
821 Cond = std::string("MI->getOperand(") +
822 llvm::utostr(i) + ").getReg() == MI->getOperand(" +
823 llvm::utostr(IAP->getOpIndex(ROName)) + ").getReg()";
827 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
828 // FIXME: We may need to handle these situations.
837 case CodeGenInstAlias::ResultOperand::K_Imm:
838 Cond = std::string("MI->getOperand(") +
839 llvm::utostr(i) + ").getImm() == " +
840 llvm::utostr(CGA->ResultOperands[i].getImm());
843 case CodeGenInstAlias::ResultOperand::K_Reg:
844 // If this is zero_reg, something's playing tricks we're not
845 // equipped to handle.
846 if (!CGA->ResultOperands[i].getRegister()) {
851 Cond = std::string("MI->getOperand(") +
852 llvm::utostr(i) + ").getReg() == " + Target.getName() +
853 "::" + CGA->ResultOperands[i].getRegister()->getName();
861 if (CantHandle) continue;
862 IAPrinterMap[I->first].push_back(IAP);
867 raw_string_ostream HeaderO(Header);
869 HeaderO << "bool " << Target.getName() << ClassName
870 << "::printAliasInstr(const MCInst"
871 << " *MI, raw_ostream &OS) {\n";
874 raw_string_ostream CasesO(Cases);
876 for (std::map<std::string, std::vector<IAPrinter*> >::iterator
877 I = IAPrinterMap.begin(), E = IAPrinterMap.end(); I != E; ++I) {
878 std::vector<IAPrinter*> &IAPs = I->second;
879 std::vector<IAPrinter*> UniqueIAPs;
881 for (std::vector<IAPrinter*>::iterator
882 II = IAPs.begin(), IE = IAPs.end(); II != IE; ++II) {
883 IAPrinter *LHS = *II;
885 for (std::vector<IAPrinter*>::iterator
886 III = IAPs.begin(), IIE = IAPs.end(); III != IIE; ++III) {
887 IAPrinter *RHS = *III;
888 if (LHS != RHS && *LHS == *RHS) {
894 if (!IsDup) UniqueIAPs.push_back(LHS);
897 if (UniqueIAPs.empty()) continue;
899 CasesO.indent(2) << "case " << I->first << ":\n";
901 for (std::vector<IAPrinter*>::iterator
902 II = UniqueIAPs.begin(), IE = UniqueIAPs.end(); II != IE; ++II) {
903 IAPrinter *IAP = *II;
909 CasesO.indent(4) << "return false;\n";
912 if (CasesO.str().empty()) {
914 O << " return false;\n";
916 O << "#endif // PRINT_ALIAS_INSTR\n";
920 EmitGetMapOperandNumber(O);
923 O.indent(2) << "StringRef AsmString;\n";
924 O.indent(2) << "SmallVector<std::pair<StringRef, unsigned>, 4> OpMap;\n";
925 O.indent(2) << "switch (MI->getOpcode()) {\n";
926 O.indent(2) << "default: return false;\n";
928 O.indent(2) << "}\n\n";
930 // Code that prints the alias, replacing the operands with the ones from the
932 O << " std::pair<StringRef, StringRef> ASM = AsmString.split(' ');\n";
933 O << " OS << '\\t' << ASM.first;\n";
935 O << " if (!ASM.second.empty()) {\n";
936 O << " OS << '\\t';\n";
937 O << " for (StringRef::iterator\n";
938 O << " I = ASM.second.begin(), E = ASM.second.end(); I != E; ) {\n";
939 O << " if (*I == '$') {\n";
940 O << " StringRef::iterator Start = ++I;\n";
941 O << " while (I != E &&\n";
942 O << " ((*I >= 'a' && *I <= 'z') ||\n";
943 O << " (*I >= 'A' && *I <= 'Z') ||\n";
944 O << " (*I >= '0' && *I <= '9') ||\n";
945 O << " *I == '_'))\n";
947 O << " StringRef Name(Start, I - Start);\n";
948 O << " printOperand(MI, getMapOperandNumber(OpMap, Name), OS);\n";
950 O << " OS << *I++;\n";
955 O << " return true;\n";
958 O << "#endif // PRINT_ALIAS_INSTR\n";
961 void AsmWriterEmitter::run(raw_ostream &O) {
962 EmitPrintInstruction(O);
963 EmitGetRegisterName(O);
964 EmitPrintAliasInstruction(O);
970 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) {
971 emitSourceFileHeader("Assembly Writer Source Fragment", OS);
972 AsmWriterEmitter(RK).run(OS);
975 } // End llvm namespace