Rename PaddedSize to AllocSize, in the hope that this
[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
136   // Populate function information map.  Actually, We don't want to populate
137   // non-stdcall or non-fastcall functions' information right now.
138   if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
139     FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
140
141   decorateName(CurrentFnName, F);
142
143   SwitchToTextSection("_text", F);
144
145   unsigned FnAlign = 4;
146   if (F->hasFnAttr(Attribute::OptimizeForSize))
147     FnAlign = 1;
148   switch (F->getLinkage()) {
149   default: assert(0 && "Unsupported linkage type!");
150   case Function::PrivateLinkage:
151   case Function::InternalLinkage:
152     EmitAlignment(FnAlign);
153     break;
154   case Function::DLLExportLinkage:
155     DLLExportedFns.insert(CurrentFnName);
156     //FALLS THROUGH
157   case Function::ExternalLinkage:
158     O << "\tpublic " << CurrentFnName << "\n";
159     EmitAlignment(FnAlign);
160     break;
161   }
162
163   O << CurrentFnName << "\tproc near\n";
164
165   // Print out code for the function.
166   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
167        I != E; ++I) {
168     // Print a label for the basic block if there are any predecessors.
169     if (!I->pred_empty()) {
170       printBasicBlockLabel(I, true, true);
171       O << '\n';
172     }
173     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
174          II != E; ++II) {
175       // Print the assembly for the instruction.
176       printMachineInstruction(II);
177     }
178   }
179
180   // Print out jump tables referenced by the function.
181   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
182
183   O << CurrentFnName << "\tendp\n";
184
185   O.flush();
186
187   // We didn't modify anything.
188   return false;
189 }
190
191 void X86IntelAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
192   unsigned char value = MI->getOperand(Op).getImm();
193   assert(value <= 7 && "Invalid ssecc argument!");
194   switch (value) {
195   case 0: O << "eq"; break;
196   case 1: O << "lt"; break;
197   case 2: O << "le"; break;
198   case 3: O << "unord"; break;
199   case 4: O << "neq"; break;
200   case 5: O << "nlt"; break;
201   case 6: O << "nle"; break;
202   case 7: O << "ord"; break;
203   }
204 }
205
206 void X86IntelAsmPrinter::printOp(const MachineOperand &MO,
207                                  const char *Modifier) {
208   switch (MO.getType()) {
209   case MachineOperand::MO_Register: {
210     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
211       unsigned Reg = MO.getReg();
212       if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
213         MVT VT = (strcmp(Modifier,"subreg64") == 0) ?
214           MVT::i64 : ((strcmp(Modifier, "subreg32") == 0) ? MVT::i32 :
215                       ((strcmp(Modifier,"subreg16") == 0) ? MVT::i16 :MVT::i8));
216         Reg = getX86SubSuperRegister(Reg, VT);
217       }
218       O << TRI->getName(Reg);
219     } else
220       O << "reg" << MO.getReg();
221     return;
222   }
223   case MachineOperand::MO_Immediate:
224     O << MO.getImm();
225     return;
226   case MachineOperand::MO_MachineBasicBlock:
227     printBasicBlockLabel(MO.getMBB());
228     return;
229   case MachineOperand::MO_JumpTableIndex: {
230     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
231     if (!isMemOp) O << "OFFSET ";
232     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
233       << "_" << MO.getIndex();
234     return;
235   }
236   case MachineOperand::MO_ConstantPoolIndex: {
237     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
238     if (!isMemOp) O << "OFFSET ";
239     O << "[" << TAI->getPrivateGlobalPrefix() << "CPI"
240       << getFunctionNumber() << "_" << MO.getIndex();
241     printOffset(MO.getOffset());
242     O << "]";
243     return;
244   }
245   case MachineOperand::MO_GlobalAddress: {
246     bool isCallOp = Modifier && !strcmp(Modifier, "call");
247     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
248     GlobalValue *GV = MO.getGlobal();
249     std::string Name = Mang->getValueName(GV);
250
251     decorateName(Name, GV);
252
253     if (!isMemOp && !isCallOp) O << "OFFSET ";
254     if (GV->hasDLLImportLinkage()) {
255       // FIXME: This should be fixed with full support of stdcall & fastcall
256       // CC's
257       O << "__imp_";
258     }
259     O << Name;
260     printOffset(MO.getOffset());
261     return;
262   }
263   case MachineOperand::MO_ExternalSymbol: {
264     bool isCallOp = Modifier && !strcmp(Modifier, "call");
265     if (!isCallOp) O << "OFFSET ";
266     O << TAI->getGlobalPrefix() << MO.getSymbolName();
267     return;
268   }
269   default:
270     O << "<unknown operand type>"; return;
271   }
272 }
273
274 void X86IntelAsmPrinter::printLeaMemReference(const MachineInstr *MI,
275                                               unsigned Op,
276                                               const char *Modifier) {
277   const MachineOperand &BaseReg  = MI->getOperand(Op);
278   int ScaleVal                   = MI->getOperand(Op+1).getImm();
279   const MachineOperand &IndexReg = MI->getOperand(Op+2);
280   const MachineOperand &DispSpec = MI->getOperand(Op+3);
281
282   O << "[";
283   bool NeedPlus = false;
284   if (BaseReg.getReg()) {
285     printOp(BaseReg, Modifier);
286     NeedPlus = true;
287   }
288
289   if (IndexReg.getReg()) {
290     if (NeedPlus) O << " + ";
291     if (ScaleVal != 1)
292       O << ScaleVal << "*";
293     printOp(IndexReg, Modifier);
294     NeedPlus = true;
295   }
296
297   if (DispSpec.isGlobal() || DispSpec.isCPI() ||
298       DispSpec.isJTI()) {
299     if (NeedPlus)
300       O << " + ";
301     printOp(DispSpec, "mem");
302   } else {
303     int DispVal = DispSpec.getImm();
304     if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
305       if (NeedPlus) {
306         if (DispVal > 0)
307           O << " + ";
308         else {
309           O << " - ";
310           DispVal = -DispVal;
311         }
312       }
313       O << DispVal;
314     }
315   }
316   O << "]";
317 }
318
319 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
320                                            const char *Modifier) {
321   assert(isMem(MI, Op) && "Invalid memory reference!");
322   MachineOperand Segment = MI->getOperand(Op+4);
323   if (Segment.getReg()) {
324       printOperand(MI, Op+4, Modifier);
325       O << ':';
326     }
327   printLeaMemReference(MI, Op, Modifier);
328 }
329
330 void X86IntelAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
331                                            const MachineBasicBlock *MBB) const {
332   if (!TAI->getSetDirective())
333     return;
334
335   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
336     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
337   printBasicBlockLabel(MBB, false, false, false);
338   O << '-' << "\"L" << getFunctionNumber() << "$pb\"'\n";
339 }
340
341 void X86IntelAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
342   O << "\"L" << getFunctionNumber() << "$pb\"\n";
343   O << "\"L" << getFunctionNumber() << "$pb\":";
344 }
345
346 bool X86IntelAsmPrinter::printAsmMRegister(const MachineOperand &MO,
347                                            const char Mode) {
348   unsigned Reg = MO.getReg();
349   switch (Mode) {
350   default: return true;  // Unknown mode.
351   case 'b': // Print QImode register
352     Reg = getX86SubSuperRegister(Reg, MVT::i8);
353     break;
354   case 'h': // Print QImode high register
355     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
356     break;
357   case 'w': // Print HImode register
358     Reg = getX86SubSuperRegister(Reg, MVT::i16);
359     break;
360   case 'k': // Print SImode register
361     Reg = getX86SubSuperRegister(Reg, MVT::i32);
362     break;
363   }
364
365   O << '%' << TRI->getName(Reg);
366   return false;
367 }
368
369 /// PrintAsmOperand - Print out an operand for an inline asm expression.
370 ///
371 bool X86IntelAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
372                                          unsigned AsmVariant,
373                                          const char *ExtraCode) {
374   // Does this asm operand have a single letter operand modifier?
375   if (ExtraCode && ExtraCode[0]) {
376     if (ExtraCode[1] != 0) return true; // Unknown modifier.
377
378     switch (ExtraCode[0]) {
379     default: return true;  // Unknown modifier.
380     case 'b': // Print QImode register
381     case 'h': // Print QImode high register
382     case 'w': // Print HImode register
383     case 'k': // Print SImode register
384       return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
385     }
386   }
387
388   printOperand(MI, OpNo);
389   return false;
390 }
391
392 bool X86IntelAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
393                                                unsigned OpNo,
394                                                unsigned AsmVariant,
395                                                const char *ExtraCode) {
396   if (ExtraCode && ExtraCode[0])
397     return true; // Unknown modifier.
398   printMemReference(MI, OpNo);
399   return false;
400 }
401
402 /// printMachineInstruction -- Print out a single X86 LLVM instruction
403 /// MI in Intel syntax to the current output stream.
404 ///
405 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
406   ++EmittedInsts;
407
408   // Call the autogenerated instruction printer routines.
409   printInstruction(MI);
410 }
411
412 bool X86IntelAsmPrinter::doInitialization(Module &M) {
413   bool Result = AsmPrinter::doInitialization(M);
414
415   Mang->markCharUnacceptable('.');
416
417   O << "\t.686\n\t.model flat\n\n";
418
419   // Emit declarations for external functions.
420   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
421     if (I->isDeclaration()) {
422       std::string Name = Mang->getValueName(I);
423       decorateName(Name, I);
424
425       O << "\textern " ;
426       if (I->hasDLLImportLinkage()) {
427         O << "__imp_";
428       }
429       O << Name << ":near\n";
430     }
431
432   // Emit declarations for external globals.  Note that VC++ always declares
433   // external globals to have type byte, and if that's good enough for VC++...
434   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
435        I != E; ++I) {
436     if (I->isDeclaration()) {
437       std::string Name = Mang->getValueName(I);
438
439       O << "\textern " ;
440       if (I->hasDLLImportLinkage()) {
441         O << "__imp_";
442       }
443       O << Name << ":byte\n";
444     }
445   }
446
447   return Result;
448 }
449
450 bool X86IntelAsmPrinter::doFinalization(Module &M) {
451   const TargetData *TD = TM.getTargetData();
452
453   // Print out module-level global variables here.
454   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
455        I != E; ++I) {
456     if (I->isDeclaration()) continue;   // External global require no code
457
458     // Check to see if this is a special global used by LLVM, if so, emit it.
459     if (EmitSpecialLLVMGlobal(I))
460       continue;
461
462     std::string name = Mang->getValueName(I);
463     Constant *C = I->getInitializer();
464     unsigned Align = TD->getPreferredAlignmentLog(I);
465     bool bCustomSegment = false;
466
467     switch (I->getLinkage()) {
468     case GlobalValue::CommonLinkage:
469     case GlobalValue::LinkOnceAnyLinkage:
470     case GlobalValue::LinkOnceODRLinkage:
471     case GlobalValue::WeakAnyLinkage:
472     case GlobalValue::WeakODRLinkage:
473       SwitchToDataSection("");
474       O << name << "?\tsegment common 'COMMON'\n";
475       bCustomSegment = true;
476       // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
477       // are also available.
478       break;
479     case GlobalValue::AppendingLinkage:
480       SwitchToDataSection("");
481       O << name << "?\tsegment public 'DATA'\n";
482       bCustomSegment = true;
483       // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
484       // are also available.
485       break;
486     case GlobalValue::DLLExportLinkage:
487       DLLExportedGVs.insert(name);
488       // FALL THROUGH
489     case GlobalValue::ExternalLinkage:
490       O << "\tpublic " << name << "\n";
491       // FALL THROUGH
492     case GlobalValue::InternalLinkage:
493       SwitchToSection(TAI->getDataSection());
494       break;
495     default:
496       assert(0 && "Unknown linkage type!");
497     }
498
499     if (!bCustomSegment)
500       EmitAlignment(Align, I);
501
502     O << name << ":";
503     if (VerboseAsm)
504       O << "\t\t\t\t" << TAI->getCommentString()
505         << " " << I->getName();
506     O << '\n';
507
508     EmitGlobalConstant(C);
509
510     if (bCustomSegment)
511       O << name << "?\tends\n";
512   }
513
514     // Output linker support code for dllexported globals
515   if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
516     SwitchToDataSection("");
517     O << "; WARNING: The following code is valid only with MASM v8.x"
518       << "and (possible) higher\n"
519       << "; This version of MASM is usually shipped with Microsoft "
520       << "Visual Studio 2005\n"
521       << "; or (possible) further versions. Unfortunately, there is no "
522       << "way to support\n"
523       << "; dllexported symbols in the earlier versions of MASM in fully "
524       << "automatic way\n\n";
525     O << "_drectve\t segment info alias('.drectve')\n";
526   }
527
528   for (StringSet<>::iterator i = DLLExportedGVs.begin(),
529          e = DLLExportedGVs.end();
530          i != e; ++i)
531     O << "\t db ' /EXPORT:" << i->getKeyData() << ",data'\n";
532
533   for (StringSet<>::iterator i = DLLExportedFns.begin(),
534          e = DLLExportedFns.end();
535          i != e; ++i)
536     O << "\t db ' /EXPORT:" << i->getKeyData() << "'\n";
537
538   if (!DLLExportedGVs.empty() || !DLLExportedFns.empty())
539     O << "_drectve\t ends\n";
540
541   // Bypass X86SharedAsmPrinter::doFinalization().
542   bool Result = AsmPrinter::doFinalization(M);
543   SwitchToDataSection("");
544   O << "\tend\n";
545   return Result;
546 }
547
548 void X86IntelAsmPrinter::EmitString(const ConstantArray *CVA) const {
549   unsigned NumElts = CVA->getNumOperands();
550   if (NumElts) {
551     // ML does not have escape sequences except '' for '.  It also has a maximum
552     // string length of 255.
553     unsigned len = 0;
554     bool inString = false;
555     for (unsigned i = 0; i < NumElts; i++) {
556       int n = cast<ConstantInt>(CVA->getOperand(i))->getZExtValue() & 255;
557       if (len == 0)
558         O << "\tdb ";
559
560       if (n >= 32 && n <= 127) {
561         if (!inString) {
562           if (len > 0) {
563             O << ",'";
564             len += 2;
565           } else {
566             O << "'";
567             len++;
568           }
569           inString = true;
570         }
571         if (n == '\'') {
572           O << "'";
573           len++;
574         }
575         O << char(n);
576       } else {
577         if (inString) {
578           O << "'";
579           len++;
580           inString = false;
581         }
582         if (len > 0) {
583           O << ",";
584           len++;
585         }
586         O << n;
587         len += 1 + (n > 9) + (n > 99);
588       }
589
590       if (len > 60) {
591         if (inString) {
592           O << "'";
593           inString = false;
594         }
595         O << "\n";
596         len = 0;
597       }
598     }
599
600     if (len > 0) {
601       if (inString)
602         O << "'";
603       O << "\n";
604     }
605   }
606 }
607
608 // Include the auto-generated portion of the assembly writer.
609 #include "X86GenAsmWriter1.inc"