1. Clean up code due to changes in SwitchTo*Section(2)
[oota-llvm.git] / lib / Target / X86 / X86ATTAsmPrinter.cpp
1 //===-- X86ATTAsmPrinter.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 AT&T format assembly
12 // language. This printer is the output mechanism used by `llc'.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "X86ATTAsmPrinter.h"
17 #include "X86.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetAsmInfo.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Module.h"
23 #include "llvm/Support/Mangler.h"
24 #include "llvm/Target/TargetAsmInfo.h"
25 #include "llvm/Target/TargetOptions.h"
26 #include <iostream>
27 using namespace llvm;
28
29 /// getSectionForFunction - Return the section that we should emit the
30 /// specified function body into.
31 std::string X86ATTAsmPrinter::getSectionForFunction(const Function &F) const {
32   switch (F.getLinkage()) {
33   default: assert(0 && "Unknown linkage type!");
34   case Function::InternalLinkage: 
35   case Function::DLLExportLinkage:
36   case Function::ExternalLinkage:
37     return TAI->getTextSection();
38   case Function::WeakLinkage:
39   case Function::LinkOnceLinkage:
40     if (Subtarget->isTargetDarwin()) {
41       return ".section __TEXT,__textcoal_nt,coalesced,pure_instructions";
42     } else if (Subtarget->isTargetCygwin()) {
43       return "\t.section\t.text$linkonce." + CurrentFnName + ",\"ax\"\n";
44     } else {
45       return "\t.section\t.llvm.linkonce.t." + CurrentFnName +
46              ",\"ax\",@progbits\n";
47     }
48   }
49 }
50
51 /// runOnMachineFunction - This uses the printMachineInstruction()
52 /// method to print assembly for each instruction.
53 ///
54 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
55   if (Subtarget->isTargetDarwin() ||
56       Subtarget->isTargetELF() ||
57       Subtarget->isTargetCygwin()) {
58     // Let PassManager know we need debug information and relay
59     // the MachineDebugInfo address on to DwarfWriter.
60     DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
61   }
62
63   SetupMachineFunction(MF);
64   O << "\n\n";
65
66   // Print out constants referenced by the function
67   EmitConstantPool(MF.getConstantPool());
68
69   // Print out labels for the function.
70   const Function *F = MF.getFunction();
71   unsigned CC = F->getCallingConv();
72
73   // Populate function information map.  Actually, We don't want to populate
74   // non-stdcall or non-fastcall functions' information right now.
75   if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
76     FunctionInfoMap[F] = *MF.getInfo<X86FunctionInfo>();
77
78   X86SharedAsmPrinter::decorateName(CurrentFnName, F);
79
80   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
81   
82   switch (F->getLinkage()) {
83   default: assert(0 && "Unknown linkage type!");
84   case Function::InternalLinkage:  // Symbols default to internal.
85     EmitAlignment(4, F);     // FIXME: This should be parameterized somewhere.
86     break;
87   case Function::DLLExportLinkage:
88     DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
89     //FALLS THROUGH
90   case Function::ExternalLinkage:
91     EmitAlignment(4, F);     // FIXME: This should be parameterized somewhere.
92     O << "\t.globl\t" << CurrentFnName << "\n";    
93     break;
94   case Function::LinkOnceLinkage:
95   case Function::WeakLinkage:
96     if (Subtarget->isTargetDarwin()) {
97       O << "\t.globl\t" << CurrentFnName << "\n";
98       O << "\t.weak_definition\t" << CurrentFnName << "\n";
99     } else if (Subtarget->isTargetCygwin()) {
100       EmitAlignment(4, F);     // FIXME: This should be parameterized somewhere.
101       O << "\t.linkonce discard\n";
102       O << "\t.globl " << CurrentFnName << "\n";
103     } else {
104       EmitAlignment(4, F);     // FIXME: This should be parameterized somewhere.
105       O << "\t.weak " << CurrentFnName << "\n";
106     }
107     break;
108   }
109   O << CurrentFnName << ":\n";
110   // Add some workaround for linkonce linkage on Cygwin\MinGW
111   if (Subtarget->isTargetCygwin() &&
112       (F->getLinkage() == Function::LinkOnceLinkage ||
113        F->getLinkage() == Function::WeakLinkage))
114     O << "_llvm$workaround$fake$stub_" << CurrentFnName << ":\n";
115
116   if (Subtarget->isTargetDarwin() ||
117       Subtarget->isTargetELF() ||
118       Subtarget->isTargetCygwin()) {
119     // Emit pre-function debug information.
120     DW.BeginFunction(&MF);
121   }
122
123   // Print out code for the function.
124   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
125        I != E; ++I) {
126     // Print a label for the basic block.
127     if (I->pred_begin() != I->pred_end()) {
128       printBasicBlockLabel(I, true);
129       O << '\n';
130     }
131     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
132          II != E; ++II) {
133       // Print the assembly for the instruction.
134       O << "\t";
135       printMachineInstruction(II);
136     }
137   }
138
139   // Print out jump tables referenced by the function.
140   
141   // Mac OS X requires that the jump table follow the function, so that the jump
142   // table is part of the same atom that the function is in.
143   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
144   
145   if (TAI->hasDotTypeDotSizeDirective())
146     O << "\t.size " << CurrentFnName << ", .-" << CurrentFnName << "\n";
147
148   if (Subtarget->isTargetDarwin() ||
149       Subtarget->isTargetELF() ||
150       Subtarget->isTargetCygwin()) {
151     // Emit post-function debug information.
152     DW.EndFunction();
153   }
154
155   // We didn't modify anything.
156   return false;
157 }
158
159 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
160                                     const char *Modifier) {
161   const MachineOperand &MO = MI->getOperand(OpNo);
162   const MRegisterInfo &RI = *TM.getRegisterInfo();
163   switch (MO.getType()) {
164   case MachineOperand::MO_Register: {
165     assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
166            "Virtual registers should not make it this far!");
167     O << '%';
168     unsigned Reg = MO.getReg();
169     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
170       MVT::ValueType VT = (strcmp(Modifier+6,"64") == 0) ?
171         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
172                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
173       Reg = getX86SubSuperRegister(Reg, VT);
174     }
175     for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
176       O << (char)tolower(*Name);
177     return;
178   }
179
180   case MachineOperand::MO_Immediate:
181     if (!Modifier || strcmp(Modifier, "debug") != 0)
182       O << '$';
183     O << MO.getImmedValue();
184     return;
185   case MachineOperand::MO_MachineBasicBlock:
186     printBasicBlockLabel(MO.getMachineBasicBlock());
187     return;
188   case MachineOperand::MO_JumpTableIndex: {
189     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
190     if (!isMemOp) O << '$';
191     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << "_"
192       << MO.getJumpTableIndex();
193     if (X86PICStyle == PICStyle::Stub &&
194         TM.getRelocationModel() == Reloc::PIC_)
195       O << "-\"L" << getFunctionNumber() << "$pb\"";
196     if (Subtarget->is64Bit())
197       O << "(%rip)";
198     return;
199   }
200   case MachineOperand::MO_ConstantPoolIndex: {
201     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
202     if (!isMemOp) O << '$';
203     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
204       << MO.getConstantPoolIndex();
205     if (X86PICStyle == PICStyle::Stub &&
206         TM.getRelocationModel() == Reloc::PIC_)
207       O << "-\"L" << getFunctionNumber() << "$pb\"";
208     int Offset = MO.getOffset();
209     if (Offset > 0)
210       O << "+" << Offset;
211     else if (Offset < 0)
212       O << Offset;
213
214     if (Subtarget->is64Bit())
215       O << "(%rip)";
216     return;
217   }
218   case MachineOperand::MO_GlobalAddress: {
219     bool isCallOp = Modifier && !strcmp(Modifier, "call");
220     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
221     if (!isMemOp && !isCallOp) O << '$';
222
223     GlobalValue *GV = MO.getGlobal();
224     std::string Name = Mang->getValueName(GV);
225     
226     bool isExt = (GV->isExternal() || GV->hasWeakLinkage() ||
227                   GV->hasLinkOnceLinkage());
228     
229     X86SharedAsmPrinter::decorateName(Name, GV);
230     
231     if (X86PICStyle == PICStyle::Stub &&
232         TM.getRelocationModel() != Reloc::Static) {
233       // Link-once, External, or Weakly-linked global variables need
234       // non-lazily-resolved stubs
235       if (isExt) {
236         // Dynamically-resolved functions need a stub for the function.
237         if (isCallOp && isa<Function>(GV)) {
238           FnStubs.insert(Name);
239           O << "L" << Name << "$stub";
240         } else {
241           GVStubs.insert(Name);
242           O << "L" << Name << "$non_lazy_ptr";
243         }
244       } else {
245         if (GV->hasDLLImportLinkage()) {
246           O << "__imp_";          
247         } 
248         O << Name;
249       }
250       
251       if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
252         O << "-\"L" << getFunctionNumber() << "$pb\"";
253     } else {
254       if (GV->hasDLLImportLinkage()) {
255         O << "__imp_";          
256       }       
257       O << Name;
258     }
259     
260     int Offset = MO.getOffset();
261     if (Offset > 0)
262       O << "+" << Offset;
263     else if (Offset < 0)
264       O << Offset;
265
266     if (!isCallOp &&
267         Subtarget->is64Bit()) {
268       if (isExt && TM.getRelocationModel() != Reloc::Static)
269         O << "@GOTPCREL";
270       O << "(%rip)";
271     }
272
273     return;
274   }
275   case MachineOperand::MO_ExternalSymbol: {
276     bool isCallOp = Modifier && !strcmp(Modifier, "call");
277     if (isCallOp && 
278         X86PICStyle == PICStyle::Stub &&
279         TM.getRelocationModel() != Reloc::Static) {
280       std::string Name(TAI->getGlobalPrefix());
281       Name += MO.getSymbolName();
282       FnStubs.insert(Name);
283       O << "L" << Name << "$stub";
284       return;
285     }
286     if (!isCallOp) O << '$';
287     O << TAI->getGlobalPrefix() << MO.getSymbolName();
288
289     if (!isCallOp &&
290         Subtarget->is64Bit())
291       O << "(%rip)";
292
293     return;
294   }
295   default:
296     O << "<unknown operand type>"; return;
297   }
298 }
299
300 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
301   unsigned char value = MI->getOperand(Op).getImmedValue();
302   assert(value <= 7 && "Invalid ssecc argument!");
303   switch (value) {
304   case 0: O << "eq"; break;
305   case 1: O << "lt"; break;
306   case 2: O << "le"; break;
307   case 3: O << "unord"; break;
308   case 4: O << "neq"; break;
309   case 5: O << "nlt"; break;
310   case 6: O << "nle"; break;
311   case 7: O << "ord"; break;
312   }
313 }
314
315 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
316                                          const char *Modifier){
317   assert(isMem(MI, Op) && "Invalid memory reference!");
318
319   const MachineOperand &BaseReg  = MI->getOperand(Op);
320   int ScaleVal                   = MI->getOperand(Op+1).getImmedValue();
321   const MachineOperand &IndexReg = MI->getOperand(Op+2);
322   const MachineOperand &DispSpec = MI->getOperand(Op+3);
323
324   if (BaseReg.isFrameIndex()) {
325     O << "[frame slot #" << BaseReg.getFrameIndex();
326     if (DispSpec.getImmedValue())
327       O << " + " << DispSpec.getImmedValue();
328     O << "]";
329     return;
330   }
331
332   if (DispSpec.isGlobalAddress() ||
333       DispSpec.isConstantPoolIndex() ||
334       DispSpec.isJumpTableIndex()) {
335     printOperand(MI, Op+3, "mem");
336   } else {
337     int DispVal = DispSpec.getImmedValue();
338     if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
339       O << DispVal;
340   }
341
342   if (IndexReg.getReg() || BaseReg.getReg()) {
343     O << "(";
344     if (BaseReg.getReg()) {
345       printOperand(MI, Op, Modifier);
346     }
347
348     if (IndexReg.getReg()) {
349       O << ",";
350       printOperand(MI, Op+2, Modifier);
351       if (ScaleVal != 1)
352         O << "," << ScaleVal;
353     }
354
355     O << ")";
356   }
357 }
358
359 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
360   O << "\"L" << getFunctionNumber() << "$pb\"\n";
361   O << "\"L" << getFunctionNumber() << "$pb\":";
362 }
363
364
365 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
366                                          const char Mode) {
367   const MRegisterInfo &RI = *TM.getRegisterInfo();
368   unsigned Reg = MO.getReg();
369   switch (Mode) {
370   default: return true;  // Unknown mode.
371   case 'b': // Print QImode register
372     Reg = getX86SubSuperRegister(Reg, MVT::i8);
373     break;
374   case 'h': // Print QImode high register
375     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
376     break;
377   case 'w': // Print HImode register
378     Reg = getX86SubSuperRegister(Reg, MVT::i16);
379     break;
380   case 'k': // Print SImode register
381     Reg = getX86SubSuperRegister(Reg, MVT::i32);
382     break;
383   }
384
385   O << '%';
386   for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
387     O << (char)tolower(*Name);
388   return false;
389 }
390
391 /// PrintAsmOperand - Print out an operand for an inline asm expression.
392 ///
393 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
394                                        unsigned AsmVariant, 
395                                        const char *ExtraCode) {
396   // Does this asm operand have a single letter operand modifier?
397   if (ExtraCode && ExtraCode[0]) {
398     if (ExtraCode[1] != 0) return true; // Unknown modifier.
399     
400     switch (ExtraCode[0]) {
401     default: return true;  // Unknown modifier.
402     case 'b': // Print QImode register
403     case 'h': // Print QImode high register
404     case 'w': // Print HImode register
405     case 'k': // Print SImode register
406       return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
407     }
408   }
409   
410   printOperand(MI, OpNo);
411   return false;
412 }
413
414 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
415                                              unsigned OpNo,
416                                              unsigned AsmVariant, 
417                                              const char *ExtraCode) {
418   if (ExtraCode && ExtraCode[0])
419     return true; // Unknown modifier.
420   printMemReference(MI, OpNo);
421   return false;
422 }
423
424 /// printMachineInstruction -- Print out a single X86 LLVM instruction
425 /// MI in Intel syntax to the current output stream.
426 ///
427 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
428   ++EmittedInsts;
429
430   // See if a truncate instruction can be turned into a nop.
431   switch (MI->getOpcode()) {
432   default: break;
433   case X86::TRUNC_64to32:
434   case X86::TRUNC_64to16:
435   case X86::TRUNC_32to16:
436   case X86::TRUNC_32to8:
437   case X86::TRUNC_16to8:
438   case X86::TRUNC_32_to8:
439   case X86::TRUNC_16_to8: {
440     const MachineOperand &MO0 = MI->getOperand(0);
441     const MachineOperand &MO1 = MI->getOperand(1);
442     unsigned Reg0 = MO0.getReg();
443     unsigned Reg1 = MO1.getReg();
444     unsigned Opc = MI->getOpcode();
445     if (Opc == X86::TRUNC_64to32)
446       Reg1 = getX86SubSuperRegister(Reg1, MVT::i32);
447     else if (Opc == X86::TRUNC_32to16 || Opc == X86::TRUNC_64to16)
448       Reg1 = getX86SubSuperRegister(Reg1, MVT::i16);
449     else
450       Reg1 = getX86SubSuperRegister(Reg1, MVT::i8);
451     O << TAI->getCommentString() << " TRUNCATE ";
452     if (Reg0 != Reg1)
453       O << "\n\t";
454     break;
455   }
456   case X86::PsMOVZX64rr32:
457     O << TAI->getCommentString() << " ZERO-EXTEND " << "\n\t";
458     break;
459   }
460
461   // Call the autogenerated instruction printer routines.
462   printInstruction(MI);
463 }
464
465 // Include the auto-generated portion of the assembly writer.
466 #include "X86GenAsmWriter.inc"
467