1822c1f914a42eed9c820761a7251187532d5998
[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
121 std::string X86IntelAsmPrinter::getSectionForFunction(const Function &F) const {
122   // Intel asm always emits functions to _text.
123   return "_text";
124 }
125
126 /// runOnMachineFunction - This uses the printMachineInstruction()
127 /// method to print assembly for each instruction.
128 ///
129 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &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   unsigned CC = F->getCallingConv();
139
140   // Populate function information map.  Actually, We don't want to populate
141   // non-stdcall or non-fastcall functions' information right now.
142   if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
143     FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
144
145   decorateName(CurrentFnName, F);
146
147   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
148
149   unsigned FnAlign = OptimizeForSize ? 1 : 4;
150   switch (F->getLinkage()) {
151   default: assert(0 && "Unsupported linkage type!");
152   case Function::InternalLinkage:
153     EmitAlignment(FnAlign);
154     break;
155   case Function::DLLExportLinkage:
156     DLLExportedFns.insert(CurrentFnName);
157     //FALLS THROUGH
158   case Function::ExternalLinkage:
159     O << "\tpublic " << CurrentFnName << "\n";
160     EmitAlignment(FnAlign);
161     break;
162   }
163
164   O << CurrentFnName << "\tproc near\n";
165
166   // Print out code for the function.
167   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
168        I != E; ++I) {
169     // Print a label for the basic block if there are any predecessors.
170     if (!I->pred_empty()) {
171       printBasicBlockLabel(I, true, true);
172       O << '\n';
173     }
174     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
175          II != E; ++II) {
176       // Print the assembly for the instruction.
177       printMachineInstruction(II);
178     }
179   }
180
181   // Print out jump tables referenced by the function.
182   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
183
184   O << CurrentFnName << "\tendp\n";
185
186   // We didn't modify anything.
187   return false;
188 }
189
190 void X86IntelAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
191   unsigned char value = MI->getOperand(Op).getImm();
192   assert(value <= 7 && "Invalid ssecc argument!");
193   switch (value) {
194   case 0: O << "eq"; break;
195   case 1: O << "lt"; break;
196   case 2: O << "le"; break;
197   case 3: O << "unord"; break;
198   case 4: O << "neq"; break;
199   case 5: O << "nlt"; break;
200   case 6: O << "nle"; break;
201   case 7: O << "ord"; break;
202   }
203 }
204
205 void X86IntelAsmPrinter::printOp(const MachineOperand &MO,
206                                  const char *Modifier) {
207   switch (MO.getType()) {
208   case MachineOperand::MO_Register: {
209     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
210       unsigned Reg = MO.getReg();
211       if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
212         MVT VT = (strcmp(Modifier,"subreg64") == 0) ?
213           MVT::i64 : ((strcmp(Modifier, "subreg32") == 0) ? MVT::i32 :
214                       ((strcmp(Modifier,"subreg16") == 0) ? MVT::i16 :MVT::i8));
215         Reg = getX86SubSuperRegister(Reg, VT);
216       }
217       O << TRI->getName(Reg);
218     } else
219       O << "reg" << MO.getReg();
220     return;
221   }
222   case MachineOperand::MO_Immediate:
223     O << MO.getImm();
224     return;
225   case MachineOperand::MO_MachineBasicBlock:
226     printBasicBlockLabel(MO.getMBB());
227     return;
228   case MachineOperand::MO_JumpTableIndex: {
229     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
230     if (!isMemOp) O << "OFFSET ";
231     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
232       << "_" << MO.getIndex();
233     return;
234   }
235   case MachineOperand::MO_ConstantPoolIndex: {
236     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
237     if (!isMemOp) O << "OFFSET ";
238     O << "[" << TAI->getPrivateGlobalPrefix() << "CPI"
239       << getFunctionNumber() << "_" << MO.getIndex();
240     int Offset = MO.getOffset();
241     if (Offset > 0)
242       O << " + " << Offset;
243     else if (Offset < 0)
244       O << Offset;
245     O << "]";
246     return;
247   }
248   case MachineOperand::MO_GlobalAddress: {
249     bool isCallOp = Modifier && !strcmp(Modifier, "call");
250     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
251     GlobalValue *GV = MO.getGlobal();
252     std::string Name = Mang->getValueName(GV);
253
254     decorateName(Name, GV);
255
256     if (!isMemOp && !isCallOp) O << "OFFSET ";
257     if (GV->hasDLLImportLinkage()) {
258       // FIXME: This should be fixed with full support of stdcall & fastcall
259       // CC's
260       O << "__imp_";
261     }
262     O << Name;
263     int Offset = MO.getOffset();
264     if (Offset > 0)
265       O << " + " << Offset;
266     else if (Offset < 0)
267       O << Offset;
268     return;
269   }
270   case MachineOperand::MO_ExternalSymbol: {
271     bool isCallOp = Modifier && !strcmp(Modifier, "call");
272     if (!isCallOp) O << "OFFSET ";
273     O << TAI->getGlobalPrefix() << MO.getSymbolName();
274     return;
275   }
276   default:
277     O << "<unknown operand type>"; return;
278   }
279 }
280
281 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
282                                            const char *Modifier) {
283   assert(isMem(MI, Op) && "Invalid memory reference!");
284
285   const MachineOperand &BaseReg  = MI->getOperand(Op);
286   int ScaleVal                   = MI->getOperand(Op+1).getImm();
287   const MachineOperand &IndexReg = MI->getOperand(Op+2);
288   const MachineOperand &DispSpec = MI->getOperand(Op+3);
289
290   O << "[";
291   bool NeedPlus = false;
292   if (BaseReg.getReg()) {
293     printOp(BaseReg, Modifier);
294     NeedPlus = true;
295   }
296
297   if (IndexReg.getReg()) {
298     if (NeedPlus) O << " + ";
299     if (ScaleVal != 1)
300       O << ScaleVal << "*";
301     printOp(IndexReg, Modifier);
302     NeedPlus = true;
303   }
304
305   if (DispSpec.isGlobalAddress() || DispSpec.isConstantPoolIndex() ||
306       DispSpec.isJumpTableIndex()) {
307     if (NeedPlus)
308       O << " + ";
309     printOp(DispSpec, "mem");
310   } else {
311     int DispVal = DispSpec.getImm();
312     if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
313       if (NeedPlus) {
314         if (DispVal > 0)
315           O << " + ";
316         else {
317           O << " - ";
318           DispVal = -DispVal;
319         }
320       }
321       O << DispVal;
322     }
323   }
324   O << "]";
325 }
326
327 void X86IntelAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
328                                            const MachineBasicBlock *MBB) const {
329   if (!TAI->getSetDirective())
330     return;
331
332   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
333     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
334   printBasicBlockLabel(MBB, false, false, false);
335   O << '-' << "\"L" << getFunctionNumber() << "$pb\"'\n";
336 }
337
338 void X86IntelAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
339   O << "\"L" << getFunctionNumber() << "$pb\"\n";
340   O << "\"L" << getFunctionNumber() << "$pb\":";
341 }
342
343 bool X86IntelAsmPrinter::printAsmMRegister(const MachineOperand &MO,
344                                            const char Mode) {
345   unsigned Reg = MO.getReg();
346   switch (Mode) {
347   default: return true;  // Unknown mode.
348   case 'b': // Print QImode register
349     Reg = getX86SubSuperRegister(Reg, MVT::i8);
350     break;
351   case 'h': // Print QImode high register
352     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
353     break;
354   case 'w': // Print HImode register
355     Reg = getX86SubSuperRegister(Reg, MVT::i16);
356     break;
357   case 'k': // Print SImode register
358     Reg = getX86SubSuperRegister(Reg, MVT::i32);
359     break;
360   }
361
362   O << '%' << TRI->getName(Reg);
363   return false;
364 }
365
366 /// PrintAsmOperand - Print out an operand for an inline asm expression.
367 ///
368 bool X86IntelAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
369                                          unsigned AsmVariant,
370                                          const char *ExtraCode) {
371   // Does this asm operand have a single letter operand modifier?
372   if (ExtraCode && ExtraCode[0]) {
373     if (ExtraCode[1] != 0) return true; // Unknown modifier.
374
375     switch (ExtraCode[0]) {
376     default: return true;  // Unknown modifier.
377     case 'b': // Print QImode register
378     case 'h': // Print QImode high register
379     case 'w': // Print HImode register
380     case 'k': // Print SImode register
381       return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
382     }
383   }
384
385   printOperand(MI, OpNo);
386   return false;
387 }
388
389 bool X86IntelAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
390                                                unsigned OpNo,
391                                                unsigned AsmVariant,
392                                                const char *ExtraCode) {
393   if (ExtraCode && ExtraCode[0])
394     return true; // Unknown modifier.
395   printMemReference(MI, OpNo);
396   return false;
397 }
398
399 /// printMachineInstruction -- Print out a single X86 LLVM instruction
400 /// MI in Intel syntax to the current output stream.
401 ///
402 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
403   ++EmittedInsts;
404
405   // Call the autogenerated instruction printer routines.
406   printInstruction(MI);
407 }
408
409 bool X86IntelAsmPrinter::doInitialization(Module &M) {
410   bool Result = AsmPrinter::doInitialization(M);
411
412   Mang->markCharUnacceptable('.');
413
414   O << "\t.686\n\t.model flat\n\n";
415
416   // Emit declarations for external functions.
417   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
418     if (I->isDeclaration()) {
419       std::string Name = Mang->getValueName(I);
420       decorateName(Name, I);
421
422       O << "\textern " ;
423       if (I->hasDLLImportLinkage()) {
424         O << "__imp_";
425       }
426       O << Name << ":near\n";
427     }
428
429   // Emit declarations for external globals.  Note that VC++ always declares
430   // external globals to have type byte, and if that's good enough for VC++...
431   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
432        I != E; ++I) {
433     if (I->isDeclaration()) {
434       std::string Name = Mang->getValueName(I);
435
436       O << "\textern " ;
437       if (I->hasDLLImportLinkage()) {
438         O << "__imp_";
439       }
440       O << Name << ":byte\n";
441     }
442   }
443
444   return Result;
445 }
446
447 bool X86IntelAsmPrinter::doFinalization(Module &M) {
448   const TargetData *TD = TM.getTargetData();
449
450   // Print out module-level global variables here.
451   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
452        I != E; ++I) {
453     if (I->isDeclaration()) continue;   // External global require no code
454
455     // Check to see if this is a special global used by LLVM, if so, emit it.
456     if (EmitSpecialLLVMGlobal(I))
457       continue;
458
459     std::string name = Mang->getValueName(I);
460     Constant *C = I->getInitializer();
461     unsigned Align = TD->getPreferredAlignmentLog(I);
462     bool bCustomSegment = false;
463
464     switch (I->getLinkage()) {
465     case GlobalValue::CommonLinkage:
466     case GlobalValue::LinkOnceLinkage:
467     case GlobalValue::WeakLinkage:
468       SwitchToDataSection("");
469       O << name << "?\tsegment common 'COMMON'\n";
470       bCustomSegment = true;
471       // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
472       // are also available.
473       break;
474     case GlobalValue::AppendingLinkage:
475       SwitchToDataSection("");
476       O << name << "?\tsegment public 'DATA'\n";
477       bCustomSegment = true;
478       // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
479       // are also available.
480       break;
481     case GlobalValue::DLLExportLinkage:
482       DLLExportedGVs.insert(name);
483       // FALL THROUGH
484     case GlobalValue::ExternalLinkage:
485       O << "\tpublic " << name << "\n";
486       // FALL THROUGH
487     case GlobalValue::InternalLinkage:
488       SwitchToDataSection(TAI->getDataSection(), I);
489       break;
490     default:
491       assert(0 && "Unknown linkage type!");
492     }
493
494     if (!bCustomSegment)
495       EmitAlignment(Align, I);
496
497     O << name << ":\t\t\t\t" << TAI->getCommentString()
498       << " " << I->getName() << '\n';
499
500     EmitGlobalConstant(C);
501
502     if (bCustomSegment)
503       O << name << "?\tends\n";
504   }
505
506     // Output linker support code for dllexported globals
507   if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
508     SwitchToDataSection("");
509     O << "; WARNING: The following code is valid only with MASM v8.x and (possible) higher\n"
510       << "; This version of MASM is usually shipped with Microsoft Visual Studio 2005\n"
511       << "; or (possible) further versions. Unfortunately, there is no way to support\n"
512       << "; dllexported symbols in the earlier versions of MASM in fully 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"