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