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"
19 #include "StringToOffsetTable.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/MathExtras.h"
25 static void PrintCases(std::vector<std::pair<std::string,
26 AsmWriterOperand> > &OpsToPrint, raw_ostream &O) {
27 O << " case " << OpsToPrint.back().first << ": ";
28 AsmWriterOperand TheOp = OpsToPrint.back().second;
29 OpsToPrint.pop_back();
31 // Check to see if any other operands are identical in this list, and if so,
32 // emit a case label for them.
33 for (unsigned i = OpsToPrint.size(); i != 0; --i)
34 if (OpsToPrint[i-1].second == TheOp) {
35 O << "\n case " << OpsToPrint[i-1].first << ": ";
36 OpsToPrint.erase(OpsToPrint.begin()+i-1);
39 // Finally, emit the code.
45 /// EmitInstructions - Emit the last instruction in the vector and any other
46 /// instructions that are suitably similar to it.
47 static void EmitInstructions(std::vector<AsmWriterInst> &Insts,
49 AsmWriterInst FirstInst = Insts.back();
52 std::vector<AsmWriterInst> SimilarInsts;
53 unsigned DifferingOperand = ~0;
54 for (unsigned i = Insts.size(); i != 0; --i) {
55 unsigned DiffOp = Insts[i-1].MatchesAllButOneOp(FirstInst);
57 if (DifferingOperand == ~0U) // First match!
58 DifferingOperand = DiffOp;
60 // If this differs in the same operand as the rest of the instructions in
61 // this class, move it to the SimilarInsts list.
62 if (DifferingOperand == DiffOp || DiffOp == ~0U) {
63 SimilarInsts.push_back(Insts[i-1]);
64 Insts.erase(Insts.begin()+i-1);
69 O << " case " << FirstInst.CGI->Namespace << "::"
70 << FirstInst.CGI->TheDef->getName() << ":\n";
71 for (unsigned i = 0, e = SimilarInsts.size(); i != e; ++i)
72 O << " case " << SimilarInsts[i].CGI->Namespace << "::"
73 << SimilarInsts[i].CGI->TheDef->getName() << ":\n";
74 for (unsigned i = 0, e = FirstInst.Operands.size(); i != e; ++i) {
75 if (i != DifferingOperand) {
76 // If the operand is the same for all instructions, just print it.
77 O << " " << FirstInst.Operands[i].getCode();
79 // If this is the operand that varies between all of the instructions,
80 // emit a switch for just this operand now.
81 O << " switch (MI->getOpcode()) {\n";
82 std::vector<std::pair<std::string, AsmWriterOperand> > OpsToPrint;
83 OpsToPrint.push_back(std::make_pair(FirstInst.CGI->Namespace + "::" +
84 FirstInst.CGI->TheDef->getName(),
85 FirstInst.Operands[i]));
87 for (unsigned si = 0, e = SimilarInsts.size(); si != e; ++si) {
88 AsmWriterInst &AWI = SimilarInsts[si];
89 OpsToPrint.push_back(std::make_pair(AWI.CGI->Namespace+"::"+
90 AWI.CGI->TheDef->getName(),
93 std::reverse(OpsToPrint.begin(), OpsToPrint.end());
94 while (!OpsToPrint.empty())
95 PrintCases(OpsToPrint, O);
103 void AsmWriterEmitter::
104 FindUniqueOperandCommands(std::vector<std::string> &UniqueOperandCommands,
105 std::vector<unsigned> &InstIdxs,
106 std::vector<unsigned> &InstOpsUsed) const {
107 InstIdxs.assign(NumberedInstructions.size(), ~0U);
109 // This vector parallels UniqueOperandCommands, keeping track of which
110 // instructions each case are used for. It is a comma separated string of
112 std::vector<std::string> InstrsForCase;
113 InstrsForCase.resize(UniqueOperandCommands.size());
114 InstOpsUsed.assign(UniqueOperandCommands.size(), 0);
116 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
117 const AsmWriterInst *Inst = getAsmWriterInstByID(i);
118 if (Inst == 0) continue; // PHI, INLINEASM, DBG_LABEL, etc.
121 if (Inst->Operands.empty())
122 continue; // Instruction already done.
124 Command = " " + Inst->Operands[0].getCode() + "\n";
126 // Check to see if we already have 'Command' in UniqueOperandCommands.
128 bool FoundIt = false;
129 for (unsigned idx = 0, e = UniqueOperandCommands.size(); idx != e; ++idx)
130 if (UniqueOperandCommands[idx] == Command) {
132 InstrsForCase[idx] += ", ";
133 InstrsForCase[idx] += Inst->CGI->TheDef->getName();
138 InstIdxs[i] = UniqueOperandCommands.size();
139 UniqueOperandCommands.push_back(Command);
140 InstrsForCase.push_back(Inst->CGI->TheDef->getName());
142 // This command matches one operand so far.
143 InstOpsUsed.push_back(1);
147 // For each entry of UniqueOperandCommands, there is a set of instructions
148 // that uses it. If the next command of all instructions in the set are
149 // identical, fold it into the command.
150 for (unsigned CommandIdx = 0, e = UniqueOperandCommands.size();
151 CommandIdx != e; ++CommandIdx) {
153 for (unsigned Op = 1; ; ++Op) {
154 // Scan for the first instruction in the set.
155 std::vector<unsigned>::iterator NIT =
156 std::find(InstIdxs.begin(), InstIdxs.end(), CommandIdx);
157 if (NIT == InstIdxs.end()) break; // No commonality.
159 // If this instruction has no more operands, we isn't anything to merge
160 // into this command.
161 const AsmWriterInst *FirstInst =
162 getAsmWriterInstByID(NIT-InstIdxs.begin());
163 if (!FirstInst || FirstInst->Operands.size() == Op)
166 // Otherwise, scan to see if all of the other instructions in this command
167 // set share the operand.
169 // Keep track of the maximum, number of operands or any
170 // instruction we see in the group.
171 size_t MaxSize = FirstInst->Operands.size();
173 for (NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx);
174 NIT != InstIdxs.end();
175 NIT = std::find(NIT+1, InstIdxs.end(), CommandIdx)) {
176 // Okay, found another instruction in this command set. If the operand
177 // matches, we're ok, otherwise bail out.
178 const AsmWriterInst *OtherInst =
179 getAsmWriterInstByID(NIT-InstIdxs.begin());
182 OtherInst->Operands.size() > FirstInst->Operands.size())
183 MaxSize = std::max(MaxSize, OtherInst->Operands.size());
185 if (!OtherInst || OtherInst->Operands.size() == Op ||
186 OtherInst->Operands[Op] != FirstInst->Operands[Op]) {
193 // Okay, everything in this command set has the same next operand. Add it
194 // to UniqueOperandCommands and remember that it was consumed.
195 std::string Command = " " + FirstInst->Operands[Op].getCode() + "\n";
197 UniqueOperandCommands[CommandIdx] += Command;
198 InstOpsUsed[CommandIdx]++;
202 // Prepend some of the instructions each case is used for onto the case val.
203 for (unsigned i = 0, e = InstrsForCase.size(); i != e; ++i) {
204 std::string Instrs = InstrsForCase[i];
205 if (Instrs.size() > 70) {
206 Instrs.erase(Instrs.begin()+70, Instrs.end());
211 UniqueOperandCommands[i] = " // " + Instrs + "\n" +
212 UniqueOperandCommands[i];
217 static void UnescapeString(std::string &Str) {
218 for (unsigned i = 0; i != Str.size(); ++i) {
219 if (Str[i] == '\\' && i != Str.size()-1) {
221 default: continue; // Don't execute the code after the switch.
222 case 'a': Str[i] = '\a'; break;
223 case 'b': Str[i] = '\b'; break;
224 case 'e': Str[i] = 27; break;
225 case 'f': Str[i] = '\f'; break;
226 case 'n': Str[i] = '\n'; break;
227 case 'r': Str[i] = '\r'; break;
228 case 't': Str[i] = '\t'; break;
229 case 'v': Str[i] = '\v'; break;
230 case '"': Str[i] = '\"'; break;
231 case '\'': Str[i] = '\''; break;
232 case '\\': Str[i] = '\\'; break;
234 // Nuke the second character.
235 Str.erase(Str.begin()+i+1);
240 /// EmitPrintInstruction - Generate the code for the "printInstruction" method
242 void AsmWriterEmitter::EmitPrintInstruction(raw_ostream &O) {
243 CodeGenTarget Target;
244 Record *AsmWriter = Target.getAsmWriter();
245 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
248 "/// printInstruction - This method is automatically generated by tablegen\n"
249 "/// from the instruction set description.\n"
250 "void " << Target.getName() << ClassName
251 << "::printInstruction(const MachineInstr *MI) {\n";
253 std::vector<AsmWriterInst> Instructions;
255 for (CodeGenTarget::inst_iterator I = Target.inst_begin(),
256 E = Target.inst_end(); I != E; ++I)
257 if (!I->second.AsmString.empty() &&
258 I->second.TheDef->getName() != "PHI")
259 Instructions.push_back(AsmWriterInst(I->second, AsmWriter));
261 // Get the instruction numbering.
262 Target.getInstructionsByEnumValue(NumberedInstructions);
264 // Compute the CodeGenInstruction -> AsmWriterInst mapping. Note that not
265 // all machine instructions are necessarily being printed, so there may be
266 // target instructions not in this map.
267 for (unsigned i = 0, e = Instructions.size(); i != e; ++i)
268 CGIAWIMap.insert(std::make_pair(Instructions[i].CGI, &Instructions[i]));
270 // Build an aggregate string, and build a table of offsets into it.
271 StringToOffsetTable StringTable;
273 /// OpcodeInfo - This encodes the index of the string to use for the first
274 /// chunk of the output as well as indices used for operand printing.
275 std::vector<unsigned> OpcodeInfo;
277 unsigned MaxStringIdx = 0;
278 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
279 AsmWriterInst *AWI = CGIAWIMap[NumberedInstructions[i]];
282 // Something not handled by the asmwriter printer.
284 } else if (AWI->Operands[0].OperandType !=
285 AsmWriterOperand::isLiteralTextOperand ||
286 AWI->Operands[0].Str.empty()) {
287 // Something handled by the asmwriter printer, but with no leading string.
288 Idx = StringTable.GetOrAddStringOffset("");
290 std::string Str = AWI->Operands[0].Str;
292 Idx = StringTable.GetOrAddStringOffset(Str);
293 MaxStringIdx = std::max(MaxStringIdx, Idx);
295 // Nuke the string from the operand list. It is now handled!
296 AWI->Operands.erase(AWI->Operands.begin());
299 // Bias offset by one since we want 0 as a sentinel.
300 OpcodeInfo.push_back(Idx+1);
303 // Figure out how many bits we used for the string index.
304 unsigned AsmStrBits = Log2_32_Ceil(MaxStringIdx+2);
306 // To reduce code size, we compactify common instructions into a few bits
307 // in the opcode-indexed table.
308 unsigned BitsLeft = 32-AsmStrBits;
310 std::vector<std::vector<std::string> > TableDrivenOperandPrinters;
313 std::vector<std::string> UniqueOperandCommands;
314 std::vector<unsigned> InstIdxs;
315 std::vector<unsigned> NumInstOpsHandled;
316 FindUniqueOperandCommands(UniqueOperandCommands, InstIdxs,
319 // If we ran out of operands to print, we're done.
320 if (UniqueOperandCommands.empty()) break;
322 // Compute the number of bits we need to represent these cases, this is
323 // ceil(log2(numentries)).
324 unsigned NumBits = Log2_32_Ceil(UniqueOperandCommands.size());
326 // If we don't have enough bits for this operand, don't include it.
327 if (NumBits > BitsLeft) {
328 DEBUG(errs() << "Not enough bits to densely encode " << NumBits
333 // Otherwise, we can include this in the initial lookup table. Add it in.
335 for (unsigned i = 0, e = InstIdxs.size(); i != e; ++i)
336 if (InstIdxs[i] != ~0U)
337 OpcodeInfo[i] |= InstIdxs[i] << (BitsLeft+AsmStrBits);
339 // Remove the info about this operand.
340 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
341 if (AsmWriterInst *Inst = getAsmWriterInstByID(i))
342 if (!Inst->Operands.empty()) {
343 unsigned NumOps = NumInstOpsHandled[InstIdxs[i]];
344 assert(NumOps <= Inst->Operands.size() &&
345 "Can't remove this many ops!");
346 Inst->Operands.erase(Inst->Operands.begin(),
347 Inst->Operands.begin()+NumOps);
351 // Remember the handlers for this set of operands.
352 TableDrivenOperandPrinters.push_back(UniqueOperandCommands);
357 O<<" static const unsigned OpInfo[] = {\n";
358 for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
359 O << " " << OpcodeInfo[i] << "U,\t// "
360 << NumberedInstructions[i]->TheDef->getName() << "\n";
362 // Add a dummy entry so the array init doesn't end with a comma.
366 // Emit the string itself.
367 O << " const char *AsmStrs = \n";
368 StringTable.EmitString(O);
371 O << " O << \"\\t\";\n\n";
373 O << " // Emit the opcode for the instruction.\n"
374 << " unsigned Bits = OpInfo[MI->getOpcode()];\n"
375 << " assert(Bits != 0 && \"Cannot print this instruction.\");\n"
376 << " O << AsmStrs+(Bits & " << (1 << AsmStrBits)-1 << ")-1;\n\n";
378 // Output the table driven operand information.
379 BitsLeft = 32-AsmStrBits;
380 for (unsigned i = 0, e = TableDrivenOperandPrinters.size(); i != e; ++i) {
381 std::vector<std::string> &Commands = TableDrivenOperandPrinters[i];
383 // Compute the number of bits we need to represent these cases, this is
384 // ceil(log2(numentries)).
385 unsigned NumBits = Log2_32_Ceil(Commands.size());
386 assert(NumBits <= BitsLeft && "consistency error");
388 // Emit code to extract this field from Bits.
391 O << "\n // Fragment " << i << " encoded into " << NumBits
392 << " bits for " << Commands.size() << " unique commands.\n";
394 if (Commands.size() == 2) {
395 // Emit two possibilitys with if/else.
396 O << " if ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
397 << ((1 << NumBits)-1) << ") {\n"
403 O << " switch ((Bits >> " << (BitsLeft+AsmStrBits) << ") & "
404 << ((1 << NumBits)-1) << ") {\n"
405 << " default: // unreachable.\n";
407 // Print out all the cases.
408 for (unsigned i = 0, e = Commands.size(); i != e; ++i) {
409 O << " case " << i << ":\n";
417 // Okay, delete instructions with no operand info left.
418 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
419 // Entire instruction has been emitted?
420 AsmWriterInst &Inst = Instructions[i];
421 if (Inst.Operands.empty()) {
422 Instructions.erase(Instructions.begin()+i);
428 // Because this is a vector, we want to emit from the end. Reverse all of the
429 // elements in the vector.
430 std::reverse(Instructions.begin(), Instructions.end());
433 // Now that we've emitted all of the operand info that fit into 32 bits, emit
434 // information for those instructions that are left. This is a less dense
435 // encoding, but we expect the main 32-bit table to handle the majority of
437 if (!Instructions.empty()) {
438 // Find the opcode # of inline asm.
439 O << " switch (MI->getOpcode()) {\n";
440 while (!Instructions.empty())
441 EmitInstructions(Instructions, O);
451 void AsmWriterEmitter::EmitGetRegisterName(raw_ostream &O) {
452 CodeGenTarget Target;
453 Record *AsmWriter = Target.getAsmWriter();
454 std::string ClassName = AsmWriter->getValueAsString("AsmWriterClassName");
455 const std::vector<CodeGenRegister> &Registers = Target.getRegisters();
457 StringToOffsetTable StringTable;
459 "\n\n/// getRegisterName - This method is automatically generated by tblgen\n"
460 "/// from the register set description. This returns the assembler name\n"
461 "/// for the specified register.\n"
462 "const char *" << Target.getName() << ClassName
463 << "::getRegisterName(unsigned RegNo) {\n"
464 << " assert(RegNo && RegNo < " << (Registers.size()+1)
465 << " && \"Invalid register number!\");\n"
467 << " static const unsigned RegAsmOffset[] = {";
468 for (unsigned i = 0, e = Registers.size(); i != e; ++i) {
469 const CodeGenRegister &Reg = Registers[i];
471 std::string AsmName = Reg.TheDef->getValueAsString("AsmName");
473 AsmName = Reg.getName();
479 O << StringTable.GetOrAddStringOffset(AsmName) << ", ";
485 O << " const char *AsmStrs =\n";
486 StringTable.EmitString(O);
489 O << " return AsmStrs+RegAsmOffset[RegNo-1];\n"
494 void AsmWriterEmitter::run(raw_ostream &O) {
495 EmitSourceFileHeader("Assembly Writer Source Fragment", O);
497 EmitPrintInstruction(O);
498 EmitGetRegisterName(O);