delete the fixme too! :)
[oota-llvm.git] / lib / Target / X86 / AsmPrinter / X86IntelAsmPrinter.cpp
1 //===-- X86IntelAsmPrinter.cpp - Convert X86 LLVM code to Intel assembly --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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 #define DEBUG_TYPE "asm-printer"
17 #include "X86IntelAsmPrinter.h"
18 #include "X86InstrInfo.h"
19 #include "X86MCAsmInfo.h"
20 #include "X86.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Module.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/CodeGen/DwarfWriter.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/Mangler.h"
36 using namespace llvm;
37
38 STATISTIC(EmittedInsts, "Number of machine instrs printed");
39
40 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
41                                                     const TargetData *TD) {
42   X86MachineFunctionInfo Info;
43   uint64_t Size = 0;
44
45   switch (F->getCallingConv()) {
46   case CallingConv::X86_StdCall:
47     Info.setDecorationStyle(StdCall);
48     break;
49   case CallingConv::X86_FastCall:
50     Info.setDecorationStyle(FastCall);
51     break;
52   default:
53     return Info;
54   }
55
56   unsigned argNum = 1;
57   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
58        AI != AE; ++AI, ++argNum) {
59     const Type* Ty = AI->getType();
60
61     // 'Dereference' type in case of byval parameter attribute
62     if (F->paramHasAttr(argNum, Attribute::ByVal))
63       Ty = cast<PointerType>(Ty)->getElementType();
64
65     // Size should be aligned to DWORD boundary
66     Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
67   }
68
69   // We're not supporting tooooo huge arguments :)
70   Info.setBytesToPopOnReturn((unsigned int)Size);
71   return Info;
72 }
73
74
75 /// decorateName - Query FunctionInfoMap and use this information for various
76 /// name decoration.
77 void X86IntelAsmPrinter::decorateName(std::string &Name,
78                                       const GlobalValue *GV) {
79   const Function *F = dyn_cast<Function>(GV);
80   if (!F) return;
81
82   // We don't want to decorate non-stdcall or non-fastcall functions right now
83   CallingConv::ID CC = F->getCallingConv();
84   if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
85     return;
86
87   FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
88
89   const X86MachineFunctionInfo *Info;
90   if (info_item == FunctionInfoMap.end()) {
91     // Calculate apropriate function info and populate map
92     FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
93     Info = &FunctionInfoMap[F];
94   } else {
95     Info = &info_item->second;
96   }
97
98   const FunctionType *FT = F->getFunctionType();
99   switch (Info->getDecorationStyle()) {
100   case None:
101     break;
102   case StdCall:
103     // "Pure" variadic functions do not receive @0 suffix.
104     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
105         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
106       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
107     break;
108   case FastCall:
109     // "Pure" variadic functions do not receive @0 suffix.
110     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
111         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
112       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
113
114     if (Name[0] == '_')
115       Name[0] = '@';
116     else
117       Name = '@' + Name;
118
119     break;
120   default:
121     llvm_unreachable("Unsupported DecorationStyle");
122   }
123 }
124
125 /// runOnMachineFunction - This uses the printMachineInstruction()
126 /// method to print assembly for each instruction.
127 ///
128 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
129   this->MF = &MF;
130   SetupMachineFunction(MF);
131   O << "\n\n";
132
133   // Print out constants referenced by the function
134   EmitConstantPool(MF.getConstantPool());
135
136   // Print out labels for the function.
137   const Function *F = MF.getFunction();
138   CallingConv::ID CC = F->getCallingConv();
139   unsigned FnAlign = MF.getAlignment();
140
141   // Populate function information map.  Actually, We don't want to populate
142   // non-stdcall or non-fastcall functions' information right now.
143   if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
144     FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
145
146   decorateName(CurrentFnName, F);
147
148   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
149
150   switch (F->getLinkage()) {
151   default: llvm_unreachable("Unsupported linkage type!");
152   case Function::PrivateLinkage:
153   case Function::LinkerPrivateLinkage:
154   case Function::InternalLinkage:
155     EmitAlignment(FnAlign);
156     break;
157   case Function::DLLExportLinkage:
158     DLLExportedFns.insert(CurrentFnName);
159     //FALLS THROUGH
160   case Function::ExternalLinkage:
161     O << "\tpublic " << CurrentFnName << "\n";
162     EmitAlignment(FnAlign);
163     break;
164   }
165
166   O << CurrentFnName << "\tproc near\n";
167
168   // Print out code for the function.
169   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
170        I != E; ++I) {
171     // Print a label for the basic block if there are any predecessors.
172     if (!I->pred_empty()) {
173       EmitBasicBlockStart(I);
174       O << '\n';
175     }
176     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
177          II != E; ++II) {
178       // Print the assembly for the instruction.
179       printMachineInstruction(II);
180     }
181   }
182
183   // Print out jump tables referenced by the function.
184   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
185
186   O << CurrentFnName << "\tendp\n";
187
188   // We didn't modify anything.
189   return false;
190 }
191
192 void X86IntelAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
193   unsigned char value = MI->getOperand(Op).getImm();
194   assert(value <= 7 && "Invalid ssecc argument!");
195   switch (value) {
196   case 0: O << "eq"; break;
197   case 1: O << "lt"; break;
198   case 2: O << "le"; break;
199   case 3: O << "unord"; break;
200   case 4: O << "neq"; break;
201   case 5: O << "nlt"; break;
202   case 6: O << "nle"; break;
203   case 7: O << "ord"; break;
204   }
205 }
206
207 void X86IntelAsmPrinter::printOp(const MachineOperand &MO,
208                                  const char *Modifier) {
209   switch (MO.getType()) {
210   case MachineOperand::MO_Register: {
211     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
212       unsigned Reg = MO.getReg();
213       if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
214         EVT VT = (strcmp(Modifier,"subreg64") == 0) ?
215           MVT::i64 : ((strcmp(Modifier, "subreg32") == 0) ? MVT::i32 :
216                       ((strcmp(Modifier,"subreg16") == 0) ? MVT::i16 :MVT::i8));
217         Reg = getX86SubSuperRegister(Reg, VT);
218       }
219       O << TRI->getName(Reg);
220     } else
221       O << "reg" << MO.getReg();
222     return;
223   }
224   case MachineOperand::MO_Immediate:
225     O << MO.getImm();
226     return;
227   case MachineOperand::MO_JumpTableIndex: {
228     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
229     if (!isMemOp) O << "OFFSET ";
230     O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
231       << "_" << MO.getIndex();
232     return;
233   }
234   case MachineOperand::MO_ConstantPoolIndex: {
235     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
236     if (!isMemOp) O << "OFFSET ";
237     O << "[" << MAI->getPrivateGlobalPrefix() << "CPI"
238       << getFunctionNumber() << "_" << MO.getIndex();
239     printOffset(MO.getOffset());
240     O << "]";
241     return;
242   }
243   case MachineOperand::MO_GlobalAddress: {
244     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
245     GlobalValue *GV = MO.getGlobal();
246     std::string Name = Mang->getMangledName(GV);
247     decorateName(Name, GV);
248
249     if (!isMemOp) O << "OFFSET ";
250     
251     // Handle dllimport linkage.
252     // FIXME: This should be fixed with full support of stdcall & fastcall
253     // CC's
254     if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
255       O << "__imp_";
256     
257     O << Name;
258     printOffset(MO.getOffset());
259     return;
260   }
261   case MachineOperand::MO_ExternalSymbol: {
262     O << MAI->getGlobalPrefix() << MO.getSymbolName();
263     return;
264   }
265   default:
266     O << "<unknown operand type>"; return;
267   }
268 }
269
270 void X86IntelAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo){
271   const MachineOperand &MO = MI->getOperand(OpNo);
272   switch (MO.getType()) {
273   default: llvm_unreachable("Unknown pcrel immediate operand");
274   case MachineOperand::MO_Immediate:
275     O << MO.getImm();
276     return;
277   case MachineOperand::MO_MachineBasicBlock:
278     GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
279     return;
280     
281   case MachineOperand::MO_GlobalAddress: {
282     GlobalValue *GV = MO.getGlobal();
283     std::string Name = Mang->getMangledName(GV);
284     decorateName(Name, GV);
285     
286     // Handle dllimport linkage.
287     // FIXME: This should be fixed with full support of stdcall & fastcall
288     // CC's
289     if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
290       O << "__imp_";
291     O << Name;
292     printOffset(MO.getOffset());
293     return;
294   }
295
296   case MachineOperand::MO_ExternalSymbol:
297     O << MAI->getGlobalPrefix() << MO.getSymbolName();
298     return;
299   }
300 }
301
302
303 void X86IntelAsmPrinter::printLeaMemReference(const MachineInstr *MI,
304                                               unsigned Op,
305                                               const char *Modifier) {
306   const MachineOperand &BaseReg  = MI->getOperand(Op);
307   int ScaleVal                   = MI->getOperand(Op+1).getImm();
308   const MachineOperand &IndexReg = MI->getOperand(Op+2);
309   const MachineOperand &DispSpec = MI->getOperand(Op+3);
310
311   O << "[";
312   bool NeedPlus = false;
313   if (BaseReg.getReg()) {
314     printOp(BaseReg, Modifier);
315     NeedPlus = true;
316   }
317
318   if (IndexReg.getReg()) {
319     if (NeedPlus) O << " + ";
320     if (ScaleVal != 1)
321       O << ScaleVal << "*";
322     printOp(IndexReg, Modifier);
323     NeedPlus = true;
324   }
325
326   if (DispSpec.isGlobal() || DispSpec.isCPI() ||
327       DispSpec.isJTI()) {
328     if (NeedPlus)
329       O << " + ";
330     printOp(DispSpec, "mem");
331   } else {
332     int DispVal = DispSpec.getImm();
333     if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
334       if (NeedPlus) {
335         if (DispVal > 0)
336           O << " + ";
337         else {
338           O << " - ";
339           DispVal = -DispVal;
340         }
341       }
342       O << DispVal;
343     }
344   }
345   O << "]";
346 }
347
348 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
349                                            const char *Modifier) {
350   assert(isMem(MI, Op) && "Invalid memory reference!");
351   MachineOperand Segment = MI->getOperand(Op+4);
352   if (Segment.getReg()) {
353       printOperand(MI, Op+4, Modifier);
354       O << ':';
355     }
356   printLeaMemReference(MI, Op, Modifier);
357 }
358
359 void X86IntelAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
360                                            const MachineBasicBlock *MBB) const {
361   if (!MAI->getSetDirective())
362     return;
363
364   O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
365     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
366   GetMBBSymbol(MBB->getNumber())->print(O, MAI);
367   O << '-' << "\"L" << getFunctionNumber() << "$pb\"'\n";
368 }
369
370 void X86IntelAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
371   O << "L" << getFunctionNumber() << "$pb\n";
372   O << "L" << getFunctionNumber() << "$pb:";
373 }
374
375 bool X86IntelAsmPrinter::printAsmMRegister(const MachineOperand &MO,
376                                            const char Mode) {
377   unsigned Reg = MO.getReg();
378   switch (Mode) {
379   default: return true;  // Unknown mode.
380   case 'b': // Print QImode register
381     Reg = getX86SubSuperRegister(Reg, MVT::i8);
382     break;
383   case 'h': // Print QImode high register
384     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
385     break;
386   case 'w': // Print HImode register
387     Reg = getX86SubSuperRegister(Reg, MVT::i16);
388     break;
389   case 'k': // Print SImode register
390     Reg = getX86SubSuperRegister(Reg, MVT::i32);
391     break;
392   }
393
394   O << TRI->getName(Reg);
395   return false;
396 }
397
398 /// PrintAsmOperand - Print out an operand for an inline asm expression.
399 ///
400 bool X86IntelAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
401                                          unsigned AsmVariant,
402                                          const char *ExtraCode) {
403   // Does this asm operand have a single letter operand modifier?
404   if (ExtraCode && ExtraCode[0]) {
405     if (ExtraCode[1] != 0) return true; // Unknown modifier.
406
407     switch (ExtraCode[0]) {
408     default: return true;  // Unknown modifier.
409     case 'b': // Print QImode register
410     case 'h': // Print QImode high register
411     case 'w': // Print HImode register
412     case 'k': // Print SImode register
413       return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
414     }
415   }
416
417   printOperand(MI, OpNo);
418   return false;
419 }
420
421 bool X86IntelAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
422                                                unsigned OpNo,
423                                                unsigned AsmVariant,
424                                                const char *ExtraCode) {
425   if (ExtraCode && ExtraCode[0])
426     return true; // Unknown modifier.
427   printMemReference(MI, OpNo);
428   return false;
429 }
430
431 /// printMachineInstruction -- Print out a single X86 LLVM instruction
432 /// MI in Intel syntax to the current output stream.
433 ///
434 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
435   ++EmittedInsts;
436
437   processDebugLoc(MI->getDebugLoc());
438
439   // Call the autogenerated instruction printer routines.
440   printInstruction(MI);
441   
442   if (VerboseAsm && !MI->getDebugLoc().isUnknown())
443     EmitComments(*MI);
444   O << '\n';
445 }
446
447 bool X86IntelAsmPrinter::doInitialization(Module &M) {
448   bool Result = AsmPrinter::doInitialization(M);
449
450   O << "\t.686\n\t.MMX\n\t.XMM\n\t.model flat\n\n";
451
452   // Emit declarations for external functions.
453   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
454     if (I->isDeclaration()) {
455       std::string Name = Mang->getMangledName(I);
456       decorateName(Name, I);
457
458       O << "\tEXTERN " ;
459       if (I->hasDLLImportLinkage()) {
460         O << "__imp_";
461       }
462       O << Name << ":near\n";
463     }
464
465   // Emit declarations for external globals.  Note that VC++ always declares
466   // external globals to have type byte, and if that's good enough for VC++...
467   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
468        I != E; ++I) {
469     if (I->isDeclaration()) {
470       std::string Name = Mang->getMangledName(I);
471
472       O << "\tEXTERN " ;
473       if (I->hasDLLImportLinkage()) {
474         O << "__imp_";
475       }
476       O << Name << ":byte\n";
477     }
478   }
479
480   return Result;
481 }
482
483 void X86IntelAsmPrinter::PrintGlobalVariable(const GlobalVariable *GV) {
484   // Check to see if this is a special global used by LLVM, if so, emit it.
485   if (GV->isDeclaration() ||
486       EmitSpecialLLVMGlobal(GV))
487     return;
488   
489   const TargetData *TD = TM.getTargetData();
490
491   std::string name = Mang->getMangledName(GV);
492   Constant *C = GV->getInitializer();
493   unsigned Align = TD->getPreferredAlignmentLog(GV);
494   bool bCustomSegment = false;
495   
496   switch (GV->getLinkage()) {
497   case GlobalValue::CommonLinkage:
498   case GlobalValue::LinkOnceAnyLinkage:
499   case GlobalValue::LinkOnceODRLinkage:
500   case GlobalValue::WeakAnyLinkage:
501   case GlobalValue::WeakODRLinkage:
502     // FIXME: make a MCSection.
503     O << name << "?\tSEGEMNT PARA common 'COMMON'\n";
504     bCustomSegment = true;
505     // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
506     // are also available.
507     break;
508   case GlobalValue::AppendingLinkage:
509     // FIXME: make a MCSection.
510     O << name << "?\tSEGMENT PARA public 'DATA'\n";
511     bCustomSegment = true;
512     // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
513     // are also available.
514     break;
515   case GlobalValue::DLLExportLinkage:
516     DLLExportedGVs.insert(name);
517     // FALL THROUGH
518   case GlobalValue::ExternalLinkage:
519     O << "\tpublic " << name << "\n";
520     // FALL THROUGH
521   case GlobalValue::InternalLinkage:
522     OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
523     break;
524   default:
525     llvm_unreachable("Unknown linkage type!");
526   }
527   
528   if (!bCustomSegment)
529     EmitAlignment(Align, GV);
530   
531   O << name << ":";
532   if (VerboseAsm)
533     O.PadToColumn(MAI->getCommentColumn());
534     O << MAI->getCommentString()
535     << " " << GV->getName();
536   O << '\n';
537   
538   EmitGlobalConstant(C);
539   
540   if (bCustomSegment)
541     O << name << "?\tends\n";
542 }
543
544 bool X86IntelAsmPrinter::doFinalization(Module &M) {
545   // Output linker support code for dllexported globals
546   if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
547     O << "; WARNING: The following code is valid only with MASM v8.x"
548       << "and (possible) higher\n"
549       << "; This version of MASM is usually shipped with Microsoft "
550       << "Visual Studio 2005\n"
551       << "; or (possible) further versions. Unfortunately, there is no "
552       << "way to support\n"
553       << "; dllexported symbols in the earlier versions of MASM in fully "
554       << "automatic way\n\n";
555     O << "_drectve\t segment info alias('.drectve')\n";
556
557     for (StringSet<>::iterator i = DLLExportedGVs.begin(),
558            e = DLLExportedGVs.end();
559            i != e; ++i)
560       O << "\t db ' /EXPORT:" << i->getKeyData() << ",data'\n";
561
562     for (StringSet<>::iterator i = DLLExportedFns.begin(),
563            e = DLLExportedFns.end();
564            i != e; ++i)
565       O << "\t db ' /EXPORT:" << i->getKeyData() << "'\n";
566
567     O << "_drectve\t ends\n";
568   }
569
570   // Bypass X86SharedAsmPrinter::doFinalization().
571   bool Result = AsmPrinter::doFinalization(M);
572   O << "\tend\n";
573   return Result;
574 }
575
576 void X86IntelAsmPrinter::EmitString(const ConstantArray *CVA) const {
577   unsigned NumElts = CVA->getNumOperands();
578   if (NumElts) {
579     // ML does not have escape sequences except '' for '.  It also has a maximum
580     // string length of 255.
581     unsigned len = 0;
582     bool inString = false;
583     for (unsigned i = 0; i < NumElts; i++) {
584       int n = cast<ConstantInt>(CVA->getOperand(i))->getZExtValue() & 255;
585       if (len == 0)
586         O << "\tdb ";
587
588       if (n >= 32 && n <= 127) {
589         if (!inString) {
590           if (len > 0) {
591             O << ",'";
592             len += 2;
593           } else {
594             O << "'";
595             len++;
596           }
597           inString = true;
598         }
599         if (n == '\'') {
600           O << "'";
601           len++;
602         }
603         O << char(n);
604       } else {
605         if (inString) {
606           O << "'";
607           len++;
608           inString = false;
609         }
610         if (len > 0) {
611           O << ",";
612           len++;
613         }
614         O << n;
615         len += 1 + (n > 9) + (n > 99);
616       }
617
618       if (len > 60) {
619         if (inString) {
620           O << "'";
621           inString = false;
622         }
623         O << "\n";
624         len = 0;
625       }
626     }
627
628     if (len > 0) {
629       if (inString)
630         O << "'";
631       O << "\n";
632     }
633   }
634 }
635
636 // Include the auto-generated portion of the assembly writer.
637 #include "X86GenAsmWriter1.inc"