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