MASM doesn't have one of these.
[oota-llvm.git] / lib / Target / X86 / X86IntelAsmPrinter.cpp
1 //===-- X86IntelAsmPrinter.cpp - Convert X86 LLVM code to Intel assembly --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to Intel format assembly language.
12 // This printer is the output mechanism used by `llc'.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "X86IntelAsmPrinter.h"
17 #include "X86.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Module.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/Support/Mangler.h"
22 #include "llvm/Target/TargetOptions.h"
23 using namespace llvm;
24
25 X86IntelAsmPrinter::X86IntelAsmPrinter(std::ostream &O, X86TargetMachine &TM)
26     : X86SharedAsmPrinter(O, TM) {
27 }
28
29 /// runOnMachineFunction - This uses the printMachineInstruction()
30 /// method to print assembly for each instruction.
31 ///
32 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
33   SetupMachineFunction(MF);
34   O << "\n\n";
35
36   // Print out constants referenced by the function
37   EmitConstantPool(MF.getConstantPool());
38
39   // Print out labels for the function.
40   SwitchToTextSection("_text", MF.getFunction());
41   EmitAlignment(4);
42   if (MF.getFunction()->getLinkage() == GlobalValue::ExternalLinkage)
43     O << "\tpublic " << CurrentFnName << "\n";
44   O << CurrentFnName << "\tproc near\n";
45   
46   // Print out code for the function.
47   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
48        I != E; ++I) {
49     // Print a label for the basic block if there are any predecessors.
50     if (I->pred_begin() != I->pred_end()) {
51       printBasicBlockLabel(I, true);
52       O << '\n';
53     }
54     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
55          II != E; ++II) {
56       // Print the assembly for the instruction.
57       O << "\t";
58       printMachineInstruction(II);
59     }
60   }
61
62   O << CurrentFnName << "\tendp\n";
63
64   // We didn't modify anything.
65   return false;
66 }
67
68 void X86IntelAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
69   unsigned char value = MI->getOperand(Op).getImmedValue();
70   assert(value <= 7 && "Invalid ssecc argument!");
71   switch (value) {
72   case 0: O << "eq"; break;
73   case 1: O << "lt"; break;
74   case 2: O << "le"; break;
75   case 3: O << "unord"; break;
76   case 4: O << "neq"; break;
77   case 5: O << "nlt"; break;
78   case 6: O << "nle"; break;
79   case 7: O << "ord"; break;
80   }
81 }
82
83 void X86IntelAsmPrinter::printOp(const MachineOperand &MO, 
84                                  const char *Modifier) {
85   const MRegisterInfo &RI = *TM.getRegisterInfo();
86   switch (MO.getType()) {
87   case MachineOperand::MO_Register:
88     if (MRegisterInfo::isPhysicalRegister(MO.getReg())) {
89       unsigned Reg = MO.getReg();
90       if (Modifier && strncmp(Modifier, "trunc", strlen("trunc")) == 0) {
91         MVT::ValueType VT = (strcmp(Modifier,"trunc16") == 0)
92           ? MVT::i16 : MVT::i8;
93         Reg = getX86SubSuperRegister(Reg, VT);
94       }
95       O << RI.get(Reg).Name;
96     } else
97       O << "reg" << MO.getReg();
98     return;
99
100   case MachineOperand::MO_Immediate:
101     O << (int)MO.getImmedValue();
102     return;
103   case MachineOperand::MO_MachineBasicBlock:
104     printBasicBlockLabel(MO.getMachineBasicBlock());
105     return;
106   case MachineOperand::MO_ConstantPoolIndex: {
107     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
108     if (!isMemOp) O << "OFFSET ";
109     O << "[" << PrivateGlobalPrefix << "CPI" << getFunctionNumber() << "_"
110       << MO.getConstantPoolIndex();
111     int Offset = MO.getOffset();
112     if (Offset > 0)
113       O << " + " << Offset;
114     else if (Offset < 0)
115       O << Offset;
116     O << "]";
117     return;
118   }
119   case MachineOperand::MO_GlobalAddress: {
120     bool isCallOp = Modifier && !strcmp(Modifier, "call");
121     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
122     if (!isMemOp && !isCallOp) O << "OFFSET ";
123     O << Mang->getValueName(MO.getGlobal());
124     int Offset = MO.getOffset();
125     if (Offset > 0)
126       O << " + " << Offset;
127     else if (Offset < 0)
128       O << Offset;
129     return;
130   }
131   case MachineOperand::MO_ExternalSymbol: {
132     bool isCallOp = Modifier && !strcmp(Modifier, "call");
133     if (!isCallOp) O << "OFFSET ";
134     O << GlobalPrefix << MO.getSymbolName();
135     return;
136   }
137   default:
138     O << "<unknown operand type>"; return;
139   }
140 }
141
142 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op){
143   assert(isMem(MI, Op) && "Invalid memory reference!");
144
145   const MachineOperand &BaseReg  = MI->getOperand(Op);
146   int ScaleVal                   = MI->getOperand(Op+1).getImmedValue();
147   const MachineOperand &IndexReg = MI->getOperand(Op+2);
148   const MachineOperand &DispSpec = MI->getOperand(Op+3);
149
150   if (BaseReg.isFrameIndex()) {
151     O << "[frame slot #" << BaseReg.getFrameIndex();
152     if (DispSpec.getImmedValue())
153       O << " + " << DispSpec.getImmedValue();
154     O << "]";
155     return;
156   }
157
158   O << "[";
159   bool NeedPlus = false;
160   if (BaseReg.getReg()) {
161     printOp(BaseReg, "mem");
162     NeedPlus = true;
163   }
164
165   if (IndexReg.getReg()) {
166     if (NeedPlus) O << " + ";
167     if (ScaleVal != 1)
168       O << ScaleVal << "*";
169     printOp(IndexReg);
170     NeedPlus = true;
171   }
172
173   if (DispSpec.isGlobalAddress() || DispSpec.isConstantPoolIndex()) {
174     if (NeedPlus)
175       O << " + ";
176     printOp(DispSpec, "mem");
177   } else {
178     int DispVal = DispSpec.getImmedValue();
179     if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
180       if (NeedPlus)
181         if (DispVal > 0)
182           O << " + ";
183         else {
184           O << " - ";
185           DispVal = -DispVal;
186         }
187       O << DispVal;
188     }
189   }
190   O << "]";
191 }
192
193 void X86IntelAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
194   O << "\"L" << getFunctionNumber() << "$pb\"\n";
195   O << "\"L" << getFunctionNumber() << "$pb\":";
196 }
197
198 bool X86IntelAsmPrinter::printAsmMRegister(const MachineOperand &MO,
199                                            const char Mode) {
200   const MRegisterInfo &RI = *TM.getRegisterInfo();
201   unsigned Reg = MO.getReg();
202   switch (Mode) {
203   default: return true;  // Unknown mode.
204   case 'b': // Print QImode register
205     Reg = getX86SubSuperRegister(Reg, MVT::i8);
206     break;
207   case 'h': // Print QImode high register
208     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
209     break;
210   case 'w': // Print HImode register
211     Reg = getX86SubSuperRegister(Reg, MVT::i16);
212     break;
213   case 'k': // Print SImode register
214     Reg = getX86SubSuperRegister(Reg, MVT::i32);
215     break;
216   }
217
218   O << '%' << RI.get(Reg).Name;
219   return false;
220 }
221
222 /// PrintAsmOperand - Print out an operand for an inline asm expression.
223 ///
224 bool X86IntelAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
225                                          unsigned AsmVariant, 
226                                          const char *ExtraCode) {
227   // Does this asm operand have a single letter operand modifier?
228   if (ExtraCode && ExtraCode[0]) {
229     if (ExtraCode[1] != 0) return true; // Unknown modifier.
230     
231     switch (ExtraCode[0]) {
232     default: return true;  // Unknown modifier.
233     case 'b': // Print QImode register
234     case 'h': // Print QImode high register
235     case 'w': // Print HImode register
236     case 'k': // Print SImode register
237       return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
238     }
239   }
240   
241   printOperand(MI, OpNo);
242   return false;
243 }
244
245 bool X86IntelAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
246                                                unsigned OpNo,
247                                                unsigned AsmVariant, 
248                                                const char *ExtraCode) {
249   if (ExtraCode && ExtraCode[0])
250     return true; // Unknown modifier.
251   printMemReference(MI, OpNo);
252   return false;
253 }
254
255 /// printMachineInstruction -- Print out a single X86 LLVM instruction
256 /// MI in Intel syntax to the current output stream.
257 ///
258 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
259   ++EmittedInsts;
260
261   // See if a truncate instruction can be turned into a nop.
262   switch (MI->getOpcode()) {
263   default: break;
264   case X86::TRUNC_R32_R16:
265   case X86::TRUNC_R32_R8:
266   case X86::TRUNC_R16_R8: {
267     const MachineOperand &MO0 = MI->getOperand(0);
268     const MachineOperand &MO1 = MI->getOperand(1);
269     unsigned Reg0 = MO0.getReg();
270     unsigned Reg1 = MO1.getReg();
271     if (MI->getOpcode() == X86::TRUNC_R32_R16)
272       Reg1 = getX86SubSuperRegister(Reg1, MVT::i16);
273     else
274       Reg1 = getX86SubSuperRegister(Reg1, MVT::i8);
275     O << CommentString << " TRUNCATE ";
276     if (Reg0 != Reg1)
277       O << "\n\t";
278     break;
279   }
280   }
281
282   // Call the autogenerated instruction printer routines.
283   printInstruction(MI);
284 }
285
286 bool X86IntelAsmPrinter::doInitialization(Module &M) {
287   MLSections = true;
288   GlobalPrefix = "_";
289   CommentString = ";";
290
291   X86SharedAsmPrinter::doInitialization(M);
292
293   PrivateGlobalPrefix = "$";
294   AlignDirective = "\talign\t";
295   ZeroDirective = "\tdb\t";
296   ZeroDirectiveSuffix = " dup(0)";
297   AsciiDirective = "\tdb\t";
298   AscizDirective = 0;
299   Data8bitsDirective = "\tdb\t";
300   Data16bitsDirective = "\tdw\t";
301   Data32bitsDirective = "\tdd\t";
302   Data64bitsDirective = "\tdq\t";
303   HasDotTypeDotSizeDirective = false;
304   Mang->markCharUnacceptable('.');
305   
306   DefaultTextSection = "_text";
307   DefaultDataSection = "_data";
308   SwitchToSectionDirective = "";
309
310   O << "\t.686\n\t.model flat\n\n";
311
312   // Emit declarations for external functions.
313   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
314     if (I->isExternal())
315       O << "\textern " << Mang->getValueName(I) << ":near\n";
316
317   // Emit declarations for external globals.  Note that VC++ always declares
318   // external globals to have type byte, and if that's good enough for VC++...
319   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
320        I != E; ++I) {
321     if (I->isExternal())
322       O << "\textern " << Mang->getValueName(I) << ":byte\n";
323   }
324
325   return false;
326 }
327
328 bool X86IntelAsmPrinter::doFinalization(Module &M) {
329   const TargetData *TD = TM.getTargetData();
330
331   // Print out module-level global variables here.
332   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
333        I != E; ++I) {
334     if (I->isExternal()) continue;   // External global require no code
335     
336     // Check to see if this is a special global used by LLVM, if so, emit it.
337     if (EmitSpecialLLVMGlobal(I))
338       continue;
339     
340     std::string name = Mang->getValueName(I);
341     Constant *C = I->getInitializer();
342     unsigned Size = TD->getTypeSize(C->getType());
343     unsigned Align = getPreferredAlignmentLog(I);
344     bool bCustomSegment = false;
345
346     switch (I->getLinkage()) {
347     case GlobalValue::LinkOnceLinkage:
348     case GlobalValue::WeakLinkage:
349       SwitchToDataSection("", 0);
350       O << name << "?\tsegment common 'COMMON'\n";
351       bCustomSegment = true;
352       // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
353       // are also available.
354       break;
355     case GlobalValue::AppendingLinkage:
356       SwitchToDataSection("", 0);
357       O << name << "?\tsegment public 'DATA'\n";
358       bCustomSegment = true;
359       // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
360       // are also available.
361       break;
362     case GlobalValue::ExternalLinkage:
363       O << "\tpublic " << name << "\n";
364       // FALL THROUGH
365     case GlobalValue::InternalLinkage:
366       SwitchToDataSection(DefaultDataSection, I);
367       break;
368     default:
369       assert(0 && "Unknown linkage type!");
370     }
371
372     if (!bCustomSegment)
373       EmitAlignment(Align, I);
374
375     O << name << ":\t\t\t\t" << CommentString << " " << I->getName() << '\n';
376
377     EmitGlobalConstant(C);
378
379     if (bCustomSegment)
380       O << name << "?\tends\n";
381   }
382   
383   // Bypass X86SharedAsmPrinter::doFinalization().
384   AsmPrinter::doFinalization(M);
385   SwitchToDataSection("", 0);
386   O << "\tend\n";
387   return false; // success
388 }
389
390 void X86IntelAsmPrinter::EmitString(const ConstantArray *CVA) const {
391   unsigned NumElts = CVA->getNumOperands();
392   if (NumElts) {
393     // ML does not have escape sequences except '' for '.  It also has a maximum
394     // string length of 255.
395     unsigned len = 0;
396     bool inString = false;
397     for (unsigned i = 0; i < NumElts; i++) {
398       int n = cast<ConstantInt>(CVA->getOperand(i))->getRawValue() & 255;
399       if (len == 0)
400         O << "\tdb ";
401
402       if (n >= 32 && n <= 127) {
403         if (!inString) {
404           if (len > 0) {
405             O << ",'";
406             len += 2;
407           } else {
408             O << "'";
409             len++;
410           }
411           inString = true;
412         }
413         if (n == '\'') {
414           O << "'";
415           len++;
416         }
417         O << char(n);
418       } else {
419         if (inString) {
420           O << "'";
421           len++;
422           inString = false;
423         }
424         if (len > 0) {
425           O << ",";
426           len++;
427         }
428         O << n;
429         len += 1 + (n > 9) + (n > 99);
430       }
431
432       if (len > 60) {
433         if (inString) {
434           O << "'";
435           inString = false;
436         }
437         O << "\n";
438         len = 0;
439       }
440     }
441
442     if (len > 0) {
443       if (inString)
444         O << "'";
445       O << "\n";
446     }
447   }
448 }
449
450 // Include the auto-generated portion of the assembly writer.
451 #include "X86GenAsmWriter1.inc"