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/Format.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/TableGen/Error.h"
24 #include "llvm/TableGen/Record.h"
25 #include "llvm/TableGen/TableGenBackend.h"
33 class AsmWriterEmitter {
34 RecordKeeper &Records;
35 std::map<const CodeGenInstruction*, AsmWriterInst*> CGIAWIMap;
36 std::vector<const CodeGenInstruction*> NumberedInstructions;
38 AsmWriterEmitter(RecordKeeper &R) : Records(R) {}
40 void run(raw_ostream &o);
43 void EmitPrintInstruction(raw_ostream &o);
44 void EmitGetRegisterName(raw_ostream &o);
45 void EmitPrintAliasInstruction(raw_ostream &O);
47 AsmWriterInst *getAsmWriterInstByID(unsigned ID) const {
48 assert(ID < NumberedInstructions.size());
49 std::map<const CodeGenInstruction*, AsmWriterInst*>::const_iterator I =
50 CGIAWIMap.find(NumberedInstructions[ID]);
51 assert(I != CGIAWIMap.end() && "Didn't find inst!");
54 void FindUniqueOperandCommands(std::vector<std::string> &UOC,
55 std::vector<unsigned> &InstIdxs,
56 std::vector<unsigned> &InstOpsUsed) const;
58 } // end anonymous namespace
60 static void PrintCases(std::vector<std::pair<std::string,
61 AsmWriterOperand> > &OpsToPrint, raw_ostream &O) {
62 O << " case " << OpsToPrint.back().first << ": ";
63 AsmWriterOperand TheOp = OpsToPrint.back().second;
64 OpsToPrint.pop_back();
66 // Check to see if any other operands are identical in this list, and if so,
67 // emit a case label for them.
68 for (unsigned i = OpsToPrint.size(); i != 0; --i)
69 if (OpsToPrint[i-1].second == TheOp) {
70 O << "\n case " << OpsToPrint[i-1].first << ": ";
71 OpsToPrint.erase(OpsToPrint.begin()+i-1);
74 // Finally, emit the code.
80 /// EmitInstructions - Emit the last instruction in the vector and any other
81 /// instructions that are suitably similar to it.
82 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
84 AsmWriterInst FirstInst = Insts.back();
87 std::vector<AsmWriterInst> SimilarInsts;
88 unsigned DifferingOperand = ~0;
89 for (unsigned i = Insts.size(); i != 0; --i) {
90 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
92 if (DifferingOperand == ~0U) // First match!
93 DifferingOperand = DiffOp;
95 // If this differs in the same operand as the rest of the instructions in
96 // this class, move it to the SimilarInsts list.
97 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
98 SimilarInsts.push_back(Insts[i-1]);
99 Insts.erase(Insts.begin()+i-1);
104 O << " case " << FirstInst.CGI->Namespace << "::"
105 << FirstInst.CGI->TheDef->getName() << ":\n";
106 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
107 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
108 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
109 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
110 if (i != DifferingOperand) {
111 // If the operand is the same for all instructions, just print it.
112 O << " " << FirstInst.Operands[i].getCode();
114 // If this is the operand that varies between all of the instructions,
115 // emit a switch for just this operand now.
116 O << " switch (MI->getOpcode()) {\n";
117 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
118 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
119 FirstInst.CGI->TheDef->getName(),
120 FirstInst.Operands[i]));
122 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
123 AsmWriterInst &AWI = SimilarInsts[si];
124 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
125 AWI.CGI->TheDef->getName(),
128 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
129 while (!OpsToPrint.empty())
130 PrintCases(OpsToPrint, O);
138 void AsmWriterEmitter::
139 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
140 std::vector<unsigned> &InstIdxs,
141 std::vector<unsigned> &InstOpsUsed) const {
142 InstIdxs.assign(NumberedInstructions.size(), ~0U);
144 // This vector parallels UniqueOperandCommands, keeping track of which
145 // instructions each case are used for. It is a comma separated string of
147 std::vector<std::string> InstrsForCase;
148 InstrsForCase.resize(UniqueOperandCommands.size());
149 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
151 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
152 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
153 if (Inst == 0) continue; // PHI, INLINEASM, PROLOG_LABEL, etc.
156 if (Inst->Operands.empty())
157 continue; // Instruction already done.
159 Command = " " + Inst->Operands[0].getCode() + "\n";
161 // Check to see if we already have 'Command' in UniqueOperandCommands.
163 bool FoundIt = false;
164 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
165 if (UniqueOperandCommands[idx] == Command) {
167 InstrsForCase[idx] += ", ";
168 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
173 InstIdxs[i] = UniqueOperandCommands.size();
174 UniqueOperandCommands.push_back(Command);
175 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
177 // This command matches one operand so far.
178 InstOpsUsed.push_back(1);
182 // For each entry of UniqueOperandCommands, there is a set of instructions
183 // that uses it. If the next command of all instructions in the set are
184 // identical, fold it into the command.
185 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
186 CommandIdx != e; ++CommandIdx) {
188 for (unsigned Op = 1; ; ++Op) {
189 // Scan for the first instruction in the set.
190 std::vector<unsigned>::iterator NIT =
191 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
192 if (NIT == InstIdxs.end()) break; // No commonality.
194 // If this instruction has no more operands, we isn't anything to merge
195 // into this command.
196 const AsmWriterInst *FirstInst =
197 getAsmWriterInstByID(NIT-InstIdxs.begin());
198 if (!FirstInst || FirstInst->Operands.size() == Op)
201 // Otherwise, scan to see if all of the other instructions in this command
202 // set share the operand.
204 // Keep track of the maximum, number of operands or any
205 // instruction we see in the group.
206 size_t MaxSize = FirstInst->Operands.size();
208 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
209 NIT != InstIdxs.end();
210 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
211 // Okay, found another instruction in this command set. If the operand
212 // matches, we're ok, otherwise bail out.
213 const AsmWriterInst *OtherInst =
214 getAsmWriterInstByID(NIT-InstIdxs.begin());
217 OtherInst->Operands.size() > FirstInst->Operands.size())
218 MaxSize = std::max(MaxSize, OtherInst->Operands.size());
220 if (!OtherInst || OtherInst->Operands.size() == Op ||
221 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
228 // Okay, everything in this command set has the same next operand. Add it
229 // to UniqueOperandCommands and remember that it was consumed.
230 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
232 UniqueOperandCommands[CommandIdx] += Command;
233 InstOpsUsed[CommandIdx]++;
237 // Prepend some of the instructions each case is used for onto the case val.
238 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
239 std::string Instrs = InstrsForCase[i];
240 if (Instrs.size() > 70) {
241 Instrs.erase(Instrs.begin()+70, Instrs.end());
246 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
247 UniqueOperandCommands[i];
252 static void UnescapeString(std::string &Str) {
253 for (unsigned i = 0; i != Str.size(); ++i) {
254 if (Str[i] == '\\' && i != Str.size()-1) {
256 default: continue; // Don't execute the code after the switch.
257 case 'a': Str[i] = '\a'; break;
258 case 'b': Str[i] = '\b'; break;
259 case 'e': Str[i] = 27; break;
260 case 'f': Str[i] = '\f'; break;
261 case 'n': Str[i] = '\n'; break;
262 case 'r': Str[i] = '\r'; break;
263 case 't': Str[i] = '\t'; break;
264 case 'v': Str[i] = '\v'; break;
265 case '"': Str[i] = '\"'; break;
266 case '\'': Str[i] = '\''; break;
267 case '\\': Str[i] = '\\'; break;
269 // Nuke the second character.
270 Str.erase(Str.begin()+i+1);
275 /// EmitPrintInstruction - Generate the code for the "printInstruction" method
277 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) {
278 CodeGenTarget Target(Records);
279 Record *AsmWriter = Target.getAsmWriter();
280 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
281 bool isMC = AsmWriter->getValueAsBit("isMCAsmWriter");
282 const char *MachineInstrClassName = isMC ? "MCInst" : "MachineInstr";
285 "/// printInstruction - This method is automatically generated by tablegen\n"
286 "/// from the instruction set description.\n"
287 "void " << Target.getName() << ClassName
288 << "::printInstruction(const " << MachineInstrClassName
289 << " *MI, raw_ostream &O) {\n";
291 std::vector<AsmWriterInst> Instructions;
293 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
294 E = Target.inst_end(); I != E; ++I)
295 if (!(*I)->AsmString.empty() &&
296 (*I)->TheDef->getName() != "PHI")
297 Instructions.push_back(
299 AsmWriter->getValueAsInt("Variant"),
300 AsmWriter->getValueAsInt("FirstOperandColumn"),
301 AsmWriter->getValueAsInt("OperandSpacing")));
303 // Get the instruction numbering.
304 NumberedInstructions = Target.getInstructionsByEnumValue();
306 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
307 // all machine instructions are necessarily being printed, so there may be
308 // target instructions not in this map.
309 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
310 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
312 // Build an aggregate string, and build a table of offsets into it.
313 SequenceToOffsetTable<std::string> StringTable;
315 /// OpcodeInfo - This encodes the index of the string to use for the first
316 /// chunk of the output as well as indices used for operand printing.
317 /// To reduce the number of unhandled cases, we expand the size from 32-bit
318 /// to 32+16 = 48-bit.
319 std::vector<uint64_t> OpcodeInfo;
321 // Add all strings to the string table upfront so it can generate an optimized
323 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
324 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
326 AWI->Operands[0].OperandType ==
327 AsmWriterOperand::isLiteralTextOperand &&
328 !AWI->Operands[0].Str.empty()) {
329 std::string Str = AWI->Operands[0].Str;
331 StringTable.add(Str);
335 StringTable.layout();
337 unsigned MaxStringIdx = 0;
338 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
339 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
342 // Something not handled by the asmwriter printer.
344 } else if (AWI->Operands[0].OperandType !=
345 AsmWriterOperand::isLiteralTextOperand ||
346 AWI->Operands[0].Str.empty()) {
347 // Something handled by the asmwriter printer, but with no leading string.
348 Idx = StringTable.get("");
350 std::string Str = AWI->Operands[0].Str;
352 Idx = StringTable.get(Str);
353 MaxStringIdx = std::max(MaxStringIdx, Idx);
355 // Nuke the string from the operand list. It is now handled!
356 AWI->Operands.erase(AWI->Operands.begin());
359 // Bias offset by one since we want 0 as a sentinel.
360 OpcodeInfo.push_back(Idx+1);
363 // Figure out how many bits we used for the string index.
364 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
366 // To reduce code size, we compactify common instructions into a few bits
367 // in the opcode-indexed table.
368 unsigned BitsLeft = 64-AsmStrBits;
370 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
373 std::vector<std::string> UniqueOperandCommands;
374 std::vector<unsigned> InstIdxs;
375 std::vector<unsigned> NumInstOpsHandled;
376 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
379 // If we ran out of operands to print, we're done.
380 if (UniqueOperandCommands.empty()) break;
382 // Compute the number of bits we need to represent these cases, this is
383 // ceil(log2(numentries)).
384 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
386 // If we don't have enough bits for this operand, don't include it.
387 if (NumBits > BitsLeft) {
388 DEBUG(errs() << "Not enough bits to densely encode " << NumBits
393 // Otherwise, we can include this in the initial lookup table. Add it in.
394 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
395 if (InstIdxs[i] != ~0U) {
396 OpcodeInfo[i] |= (uint64_t)InstIdxs[i] << (64-BitsLeft);
400 // Remove the info about this operand.
401 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
402 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
403 if (!Inst->Operands.empty()) {
404 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
405 assert(NumOps <= Inst->Operands.size() &&
406 "Can't remove this many ops!");
407 Inst->Operands.erase(Inst->Operands.begin(),
408 Inst->Operands.begin()+NumOps);
412 // Remember the handlers for this set of operands.
413 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
417 // We always emit at least one 32-bit table. A second table is emitted if
418 // more bits are needed.
419 O<<" static const uint32_t OpInfo[] = {\n";
420 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
421 O << " " << (OpcodeInfo[i] & 0xffffffff) << "U,\t// "
422 << NumberedInstructions[i]->TheDef->getName() << "\n";
424 // Add a dummy entry so the array init doesn't end with a comma.
429 // Add a second OpInfo table only when it is necessary.
430 // Adjust the type of the second table based on the number of bits needed.
431 O << " static const uint"
432 << ((BitsLeft < 16) ? "32" : (BitsLeft < 24) ? "16" : "8")
433 << "_t OpInfo2[] = {\n";
434 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
435 O << " " << (OpcodeInfo[i] >> 32) << "U,\t// "
436 << NumberedInstructions[i]->TheDef->getName() << "\n";
438 // Add a dummy entry so the array init doesn't end with a comma.
443 // Emit the string itself.
444 O << " const char AsmStrs[] = {\n";
445 StringTable.emit(O, printChar);
448 O << " O << \"\\t\";\n\n";
450 O << " // Emit the opcode for the instruction.\n";
452 // If we have two tables then we need to perform two lookups and combine
453 // the results into a single 64-bit value.
454 O << " uint64_t Bits1 = OpInfo[MI->getOpcode()];\n"
455 << " uint64_t Bits2 = OpInfo2[MI->getOpcode()];\n"
456 << " uint64_t Bits = (Bits2 << 32) | Bits1;\n";
458 // If only one table is used we just need to perform a single lookup.
459 O << " uint32_t Bits = OpInfo[MI->getOpcode()];\n";
461 O << " assert(Bits != 0 && \"Cannot print this instruction.\");\n"
462 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
464 // Output the table driven operand information.
465 BitsLeft = 64-AsmStrBits;
466 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
467 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
469 // Compute the number of bits we need to represent these cases, this is
470 // ceil(log2(numentries)).
471 unsigned NumBits = Log2_32_Ceil(Commands.size());
472 assert(NumBits <= BitsLeft && "consistency error");
474 // Emit code to extract this field from Bits.
475 O << "\n // Fragment " << i << " encoded into " << NumBits
476 << " bits for " << Commands.size() << " unique commands.\n";
478 if (Commands.size() == 2) {
479 // Emit two possibilitys with if/else.
480 O << " if ((Bits >> "
481 << (64-BitsLeft) << ") & "
482 << ((1 << NumBits)-1) << ") {\n"
487 } else if (Commands.size() == 1) {
488 // Emit a single possibility.
489 O << Commands[0] << "\n\n";
491 O << " switch ((Bits >> "
492 << (64-BitsLeft) << ") & "
493 << ((1 << NumBits)-1) << ") {\n"
494 << " default: // unreachable.\n";
496 // Print out all the cases.
497 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
498 O << " case " << i << ":\n";
507 // Okay, delete instructions with no operand info left.
508 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
509 // Entire instruction has been emitted?
510 AsmWriterInst &Inst = Instructions[i];
511 if (Inst.Operands.empty()) {
512 Instructions.erase(Instructions.begin()+i);
518 // Because this is a vector, we want to emit from the end. Reverse all of the
519 // elements in the vector.
520 std::reverse(Instructions.begin(), Instructions.end());
523 // Now that we've emitted all of the operand info that fit into 32 bits, emit
524 // information for those instructions that are left. This is a less dense
525 // encoding, but we expect the main 32-bit table to handle the majority of
527 if (!Instructions.empty()) {
528 // Find the opcode # of inline asm.
529 O << " switch (MI->getOpcode()) {\n";
530 while (!Instructions.empty())
531 EmitInstructions(Instructions, O);
541 emitRegisterNameString(raw_ostream &O, StringRef AltName,
542 const std::vector<CodeGenRegister*> &Registers) {
543 SequenceToOffsetTable<std::string> StringTable;
544 SmallVector<std::string, 4> AsmNames(Registers.size());
545 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
546 const CodeGenRegister &Reg = *Registers[i];
547 std::string &AsmName = AsmNames[i];
549 // "NoRegAltName" is special. We don't need to do a lookup for that,
550 // as it's just a reference to the default register name.
551 if (AltName == "" || AltName == "NoRegAltName") {
552 AsmName = Reg.TheDef->getValueAsString("AsmName");
554 AsmName = Reg.getName();
556 // Make sure the register has an alternate name for this index.
557 std::vector<Record*> AltNameList =
558 Reg.TheDef->getValueAsListOfDefs("RegAltNameIndices");
560 for (e = AltNameList.size();
561 Idx < e && (AltNameList[Idx]->getName() != AltName);
564 // If the register has an alternate name for this index, use it.
565 // Otherwise, leave it empty as an error flag.
567 std::vector<std::string> AltNames =
568 Reg.TheDef->getValueAsListOfStrings("AltNames");
569 if (AltNames.size() <= Idx)
570 PrintFatalError(Reg.TheDef->getLoc(),
571 (Twine("Register definition missing alt name for '") +
572 AltName + "'.").str());
573 AsmName = AltNames[Idx];
576 StringTable.add(AsmName);
579 StringTable.layout();
580 O << " static const char AsmStrs" << AltName << "[] = {\n";
581 StringTable.emit(O, printChar);
584 O << " static const uint32_t RegAsmOffset" << AltName << "[] = {";
585 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
588 O << StringTable.get(AsmNames[i]) << ", ";
594 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
595 CodeGenTarget Target(Records);
596 Record *AsmWriter = Target.getAsmWriter();
597 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
598 const std::vector<CodeGenRegister*> &Registers =
599 Target.getRegBank().getRegisters();
600 std::vector<Record*> AltNameIndices = Target.getRegAltNameIndices();
601 bool hasAltNames = AltNameIndices.size() > 1;
604 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
605 "/// from the register set description. This returns the assembler name\n"
606 "/// for the specified register.\n"
607 "const char *" << Target.getName() << ClassName << "::";
609 O << "\ngetRegisterName(unsigned RegNo, unsigned AltIdx) {\n";
611 O << "getRegisterName(unsigned RegNo) {\n";
612 O << " assert(RegNo && RegNo < " << (Registers.size()+1)
613 << " && \"Invalid register number!\");\n"
617 for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i)
618 emitRegisterNameString(O, AltNameIndices[i]->getName(), Registers);
620 emitRegisterNameString(O, "", Registers);
623 O << " const uint32_t *RegAsmOffset;\n"
624 << " const char *AsmStrs;\n"
625 << " switch(AltIdx) {\n"
626 << " default: llvm_unreachable(\"Invalid register alt name index!\");\n";
627 for (unsigned i = 0, e = AltNameIndices.size(); i < e; ++i) {
628 StringRef Namespace = AltNameIndices[1]->getValueAsString("Namespace");
629 StringRef AltName(AltNameIndices[i]->getName());
630 O << " case " << Namespace << "::" << AltName
632 << " AsmStrs = AsmStrs" << AltName << ";\n"
633 << " RegAsmOffset = RegAsmOffset" << AltName << ";\n"
639 O << " assert (*(AsmStrs+RegAsmOffset[RegNo-1]) &&\n"
640 << " \"Invalid alt name index for register!\");\n"
641 << " return AsmStrs+RegAsmOffset[RegNo-1];\n"
646 // IAPrinter - Holds information about an InstAlias. Two InstAliases match if
647 // they both have the same conditionals. In which case, we cannot print out the
648 // alias for that pattern.
650 std::vector<std::string> Conds;
651 std::map<StringRef, unsigned> OpMap;
653 std::string AsmString;
654 SmallVector<Record*, 4> ReqFeatures;
656 IAPrinter(std::string R, std::string AS)
657 : Result(R), AsmString(AS) {}
659 void addCond(const std::string &C) { Conds.push_back(C); }
661 void addOperand(StringRef Op, unsigned Idx) {
662 assert(Idx < 0xFF && "Index too large!");
665 unsigned getOpIndex(StringRef Op) { return OpMap[Op]; }
666 bool isOpMapped(StringRef Op) { return OpMap.find(Op) != OpMap.end(); }
668 void print(raw_ostream &O) {
669 if (Conds.empty() && ReqFeatures.empty()) {
670 O.indent(6) << "return true;\n";
676 for (std::vector<std::string>::iterator
677 I = Conds.begin(), E = Conds.end(); I != E; ++I) {
678 if (I != Conds.begin()) {
687 O.indent(6) << "// " << Result << "\n";
689 // Directly mangle mapped operands into the string. Each operand is
690 // identified by a '$' sign followed by a byte identifying the number of the
691 // operand. We add one to the index to avoid zero bytes.
692 std::pair<StringRef, StringRef> ASM = StringRef(AsmString).split(' ');
693 SmallString<128> OutString = ASM.first;
694 if (!ASM.second.empty()) {
695 raw_svector_ostream OS(OutString);
697 for (StringRef::iterator I = ASM.second.begin(), E = ASM.second.end();
701 StringRef::iterator Start = ++I;
703 ((*I >= 'a' && *I <= 'z') || (*I >= 'A' && *I <= 'Z') ||
704 (*I >= '0' && *I <= '9') || *I == '_'))
706 StringRef Name(Start, I - Start);
707 assert(isOpMapped(Name) && "Unmapped operand!");
708 OS << format("\\x%02X", (unsigned char)getOpIndex(Name) + 1);
716 O.indent(6) << "AsmString = \"" << OutString.str() << "\";\n";
718 O.indent(6) << "break;\n";
722 bool operator==(const IAPrinter &RHS) {
723 if (Conds.size() != RHS.Conds.size())
727 for (std::vector<std::string>::iterator
728 I = Conds.begin(), E = Conds.end(); I != E; ++I)
729 if (*I != RHS.Conds[Idx++])
735 bool operator()(const IAPrinter &RHS) {
736 if (Conds.size() < RHS.Conds.size())
740 for (std::vector<std::string>::iterator
741 I = Conds.begin(), E = Conds.end(); I != E; ++I)
742 if (*I != RHS.Conds[Idx++])
743 return *I < RHS.Conds[Idx++];
749 } // end anonymous namespace
751 static unsigned CountNumOperands(StringRef AsmString) {
753 std::pair<StringRef, StringRef> ASM = AsmString.split(' ');
755 while (!ASM.second.empty()) {
757 ASM = ASM.second.split(' ');
763 static unsigned CountResultNumOperands(StringRef AsmString) {
765 std::pair<StringRef, StringRef> ASM = AsmString.split('\t');
767 if (!ASM.second.empty()) {
768 size_t I = ASM.second.find('{');
769 StringRef Str = ASM.second;
770 if (I != StringRef::npos)
771 Str = ASM.second.substr(I, ASM.second.find('|', I));
773 ASM = Str.split(' ');
777 ASM = ASM.second.split(' ');
778 } while (!ASM.second.empty());
784 void AsmWriterEmitter::EmitPrintAliasInstruction(raw_ostream &O) {
785 CodeGenTarget Target(Records);
786 Record *AsmWriter = Target.getAsmWriter();
788 if (!AsmWriter->getValueAsBit("isMCAsmWriter"))
791 O << "\n#ifdef PRINT_ALIAS_INSTR\n";
792 O << "#undef PRINT_ALIAS_INSTR\n\n";
794 // Emit the method that prints the alias instruction.
795 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
797 std::vector<Record*> AllInstAliases =
798 Records.getAllDerivedDefinitions("InstAlias");
800 // Create a map from the qualified name to a list of potential matches.
801 std::map<std::string, std::vector<CodeGenInstAlias*> > AliasMap;
802 for (std::vector<Record*>::iterator
803 I = AllInstAliases.begin(), E = AllInstAliases.end(); I != E; ++I) {
804 CodeGenInstAlias *Alias = new CodeGenInstAlias(*I, Target);
805 const Record *R = *I;
806 if (!R->getValueAsBit("EmitAlias"))
807 continue; // We were told not to emit the alias, but to emit the aliasee.
808 const DagInit *DI = R->getValueAsDag("ResultInst");
809 const DefInit *Op = cast<DefInit>(DI->getOperator());
810 AliasMap[getQualifiedName(Op->getDef())].push_back(Alias);
813 // A map of which conditions need to be met for each instruction operand
814 // before it can be matched to the mnemonic.
815 std::map<std::string, std::vector<IAPrinter*> > IAPrinterMap;
817 for (std::map<std::string, std::vector<CodeGenInstAlias*> >::iterator
818 I = AliasMap.begin(), E = AliasMap.end(); I != E; ++I) {
819 std::vector<CodeGenInstAlias*> &Aliases = I->second;
821 for (std::vector<CodeGenInstAlias*>::iterator
822 II = Aliases.begin(), IE = Aliases.end(); II != IE; ++II) {
823 const CodeGenInstAlias *CGA = *II;
824 unsigned LastOpNo = CGA->ResultInstOperandIndex.size();
825 unsigned NumResultOps =
826 CountResultNumOperands(CGA->ResultInst->AsmString);
828 // Don't emit the alias if it has more operands than what it's aliasing.
829 if (NumResultOps < CountNumOperands(CGA->AsmString))
832 IAPrinter *IAP = new IAPrinter(CGA->Result->getAsString(),
836 Cond = std::string("MI->getNumOperands() == ") + llvm::utostr(LastOpNo);
839 bool CantHandle = false;
841 for (unsigned i = 0, e = LastOpNo; i != e; ++i) {
842 const CodeGenInstAlias::ResultOperand &RO = CGA->ResultOperands[i];
845 case CodeGenInstAlias::ResultOperand::K_Record: {
846 const Record *Rec = RO.getRecord();
847 StringRef ROName = RO.getName();
850 if (Rec->isSubClassOf("RegisterOperand"))
851 Rec = Rec->getValueAsDef("RegClass");
852 if (Rec->isSubClassOf("RegisterClass")) {
853 Cond = std::string("MI->getOperand(")+llvm::utostr(i)+").isReg()";
856 if (!IAP->isOpMapped(ROName)) {
857 IAP->addOperand(ROName, i);
858 Record *R = CGA->ResultOperands[i].getRecord();
859 if (R->isSubClassOf("RegisterOperand"))
860 R = R->getValueAsDef("RegClass");
861 Cond = std::string("MRI.getRegClass(") + Target.getName() + "::" +
862 R->getName() + "RegClassID)"
863 ".contains(MI->getOperand(" + llvm::utostr(i) + ").getReg())";
866 Cond = std::string("MI->getOperand(") +
867 llvm::utostr(i) + ").getReg() == MI->getOperand(" +
868 llvm::utostr(IAP->getOpIndex(ROName)) + ").getReg()";
872 assert(Rec->isSubClassOf("Operand") && "Unexpected operand!");
873 // FIXME: We may need to handle these situations.
882 case CodeGenInstAlias::ResultOperand::K_Imm: {
883 std::string Op = "MI->getOperand(" + llvm::utostr(i) + ")";
885 // Just because the alias has an immediate result, doesn't mean the
886 // MCInst will. An MCExpr could be present, for example.
887 IAP->addCond(Op + ".isImm()");
889 Cond = Op + ".getImm() == "
890 + llvm::utostr(CGA->ResultOperands[i].getImm());
894 case CodeGenInstAlias::ResultOperand::K_Reg:
895 // If this is zero_reg, something's playing tricks we're not
896 // equipped to handle.
897 if (!CGA->ResultOperands[i].getRegister()) {
902 Cond = std::string("MI->getOperand(") +
903 llvm::utostr(i) + ").getReg() == " + Target.getName() +
904 "::" + CGA->ResultOperands[i].getRegister()->getName();
912 if (CantHandle) continue;
913 IAPrinterMap[I->first].push_back(IAP);
918 raw_string_ostream HeaderO(Header);
920 HeaderO << "bool " << Target.getName() << ClassName
921 << "::printAliasInstr(const MCInst"
922 << " *MI, raw_ostream &OS) {\n";
925 raw_string_ostream CasesO(Cases);
927 for (std::map<std::string, std::vector<IAPrinter*> >::iterator
928 I = IAPrinterMap.begin(), E = IAPrinterMap.end(); I != E; ++I) {
929 std::vector<IAPrinter*> &IAPs = I->second;
930 std::vector<IAPrinter*> UniqueIAPs;
932 for (std::vector<IAPrinter*>::iterator
933 II = IAPs.begin(), IE = IAPs.end(); II != IE; ++II) {
934 IAPrinter *LHS = *II;
936 for (std::vector<IAPrinter*>::iterator
937 III = IAPs.begin(), IIE = IAPs.end(); III != IIE; ++III) {
938 IAPrinter *RHS = *III;
939 if (LHS != RHS && *LHS == *RHS) {
945 if (!IsDup) UniqueIAPs.push_back(LHS);
948 if (UniqueIAPs.empty()) continue;
950 CasesO.indent(2) << "case " << I->first << ":\n";
952 for (std::vector<IAPrinter*>::iterator
953 II = UniqueIAPs.begin(), IE = UniqueIAPs.end(); II != IE; ++II) {
954 IAPrinter *IAP = *II;
960 CasesO.indent(4) << "return false;\n";
963 if (CasesO.str().empty()) {
965 O << " return false;\n";
967 O << "#endif // PRINT_ALIAS_INSTR\n";
972 O.indent(2) << "const char *AsmString;\n";
973 O.indent(2) << "switch (MI->getOpcode()) {\n";
974 O.indent(2) << "default: return false;\n";
976 O.indent(2) << "}\n\n";
978 // Code that prints the alias, replacing the operands with the ones from the
980 O << " unsigned I = 0;\n";
981 O << " while (AsmString[I] != ' ' && AsmString[I] != '\\0')\n";
983 O << " OS << '\\t' << StringRef(AsmString, I);\n";
985 O << " if (AsmString[I] != '\\0') {\n";
986 O << " OS << '\\t';\n";
988 O << " if (AsmString[I] == '$') {\n";
990 O << " printOperand(MI, unsigned(AsmString[I++]) - 1, OS);\n";
992 O << " OS << AsmString[I++];\n";
994 O << " } while (AsmString[I] != '\\0');\n";
997 O << " return true;\n";
1000 O << "#endif // PRINT_ALIAS_INSTR\n";
1003 void AsmWriterEmitter::run(raw_ostream &O) {
1004 EmitPrintInstruction(O);
1005 EmitGetRegisterName(O);
1006 EmitPrintAliasInstruction(O);
1012 void EmitAsmWriter(RecordKeeper &RK, raw_ostream &OS) {
1013 emitSourceFileHeader("Assembly Writer Source Fragment", OS);
1014 AsmWriterEmitter(RK).run(OS);
1017 } // End llvm namespace