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