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