Put code that generates debug labels into TableGen so that it can be used by
[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->getTypePaddedSize(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   SetupMachineFunction(MF);
126   O << "\n\n";
127
128   // Print out constants referenced by the function
129   EmitConstantPool(MF.getConstantPool());
130
131   // Print out labels for the function.
132   const Function *F = MF.getFunction();
133   unsigned CC = F->getCallingConv();
134
135   // Populate function information map.  Actually, We don't want to populate
136   // non-stdcall or non-fastcall functions' information right now.
137   if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
138     FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
139
140   decorateName(CurrentFnName, F);
141
142   SwitchToTextSection("_text", F);
143
144   unsigned FnAlign = 4;
145   if (F->hasFnAttr(Attribute::OptimizeForSize))
146     FnAlign = 1;
147   switch (F->getLinkage()) {
148   default: assert(0 && "Unsupported linkage type!");
149   case Function::PrivateLinkage:
150   case Function::InternalLinkage:
151     EmitAlignment(FnAlign);
152     break;
153   case Function::DLLExportLinkage:
154     DLLExportedFns.insert(CurrentFnName);
155     //FALLS THROUGH
156   case Function::ExternalLinkage:
157     O << "\tpublic " << CurrentFnName << "\n";
158     EmitAlignment(FnAlign);
159     break;
160   }
161
162   O << CurrentFnName << "\tproc near\n";
163
164   // Print out code for the function.
165   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
166        I != E; ++I) {
167     // Print a label for the basic block if there are any predecessors.
168     if (!I->pred_empty()) {
169       printBasicBlockLabel(I, true, true);
170       O << '\n';
171     }
172     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
173          II != E; ++II) {
174       // Print the assembly for the instruction.
175       printMachineInstruction(II);
176     }
177   }
178
179   // Print out jump tables referenced by the function.
180   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
181
182   O << CurrentFnName << "\tendp\n";
183
184   O.flush();
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     printOffset(MO.getOffset());
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     printOffset(MO.getOffset());
260     return;
261   }
262   case MachineOperand::MO_ExternalSymbol: {
263     bool isCallOp = Modifier && !strcmp(Modifier, "call");
264     if (!isCallOp) O << "OFFSET ";
265     O << TAI->getGlobalPrefix() << MO.getSymbolName();
266     return;
267   }
268   default:
269     O << "<unknown operand type>"; return;
270   }
271 }
272
273 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
274                                            const char *Modifier) {
275   assert(isMem(MI, Op) && "Invalid memory reference!");
276
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::printPICJumpTableSetLabel(unsigned uid,
320                                            const MachineBasicBlock *MBB) const {
321   if (!TAI->getSetDirective())
322     return;
323
324   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
325     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
326   printBasicBlockLabel(MBB, false, false, false);
327   O << '-' << "\"L" << getFunctionNumber() << "$pb\"'\n";
328 }
329
330 void X86IntelAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
331   O << "\"L" << getFunctionNumber() << "$pb\"\n";
332   O << "\"L" << getFunctionNumber() << "$pb\":";
333 }
334
335 bool X86IntelAsmPrinter::printAsmMRegister(const MachineOperand &MO,
336                                            const char Mode) {
337   unsigned Reg = MO.getReg();
338   switch (Mode) {
339   default: return true;  // Unknown mode.
340   case 'b': // Print QImode register
341     Reg = getX86SubSuperRegister(Reg, MVT::i8);
342     break;
343   case 'h': // Print QImode high register
344     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
345     break;
346   case 'w': // Print HImode register
347     Reg = getX86SubSuperRegister(Reg, MVT::i16);
348     break;
349   case 'k': // Print SImode register
350     Reg = getX86SubSuperRegister(Reg, MVT::i32);
351     break;
352   }
353
354   O << '%' << TRI->getName(Reg);
355   return false;
356 }
357
358 /// PrintAsmOperand - Print out an operand for an inline asm expression.
359 ///
360 bool X86IntelAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
361                                          unsigned AsmVariant,
362                                          const char *ExtraCode) {
363   // Does this asm operand have a single letter operand modifier?
364   if (ExtraCode && ExtraCode[0]) {
365     if (ExtraCode[1] != 0) return true; // Unknown modifier.
366
367     switch (ExtraCode[0]) {
368     default: return true;  // Unknown modifier.
369     case 'b': // Print QImode register
370     case 'h': // Print QImode high register
371     case 'w': // Print HImode register
372     case 'k': // Print SImode register
373       return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
374     }
375   }
376
377   printOperand(MI, OpNo);
378   return false;
379 }
380
381 bool X86IntelAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
382                                                unsigned OpNo,
383                                                unsigned AsmVariant,
384                                                const char *ExtraCode) {
385   if (ExtraCode && ExtraCode[0])
386     return true; // Unknown modifier.
387   printMemReference(MI, OpNo);
388   return false;
389 }
390
391 /// printMachineInstruction -- Print out a single X86 LLVM instruction
392 /// MI in Intel syntax to the current output stream.
393 ///
394 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
395   ++EmittedInsts;
396
397   // Call the autogenerated instruction printer routines.
398   printInstruction(MI);
399 }
400
401 bool X86IntelAsmPrinter::doInitialization(Module &M) {
402   bool Result = AsmPrinter::doInitialization(M);
403
404   Mang->markCharUnacceptable('.');
405
406   O << "\t.686\n\t.model flat\n\n";
407
408   // Emit declarations for external functions.
409   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
410     if (I->isDeclaration()) {
411       std::string Name = Mang->getValueName(I);
412       decorateName(Name, I);
413
414       O << "\textern " ;
415       if (I->hasDLLImportLinkage()) {
416         O << "__imp_";
417       }
418       O << Name << ":near\n";
419     }
420
421   // Emit declarations for external globals.  Note that VC++ always declares
422   // external globals to have type byte, and if that's good enough for VC++...
423   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
424        I != E; ++I) {
425     if (I->isDeclaration()) {
426       std::string Name = Mang->getValueName(I);
427
428       O << "\textern " ;
429       if (I->hasDLLImportLinkage()) {
430         O << "__imp_";
431       }
432       O << Name << ":byte\n";
433     }
434   }
435
436   return Result;
437 }
438
439 bool X86IntelAsmPrinter::doFinalization(Module &M) {
440   const TargetData *TD = TM.getTargetData();
441
442   // Print out module-level global variables here.
443   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
444        I != E; ++I) {
445     if (I->isDeclaration()) continue;   // External global require no code
446
447     // Check to see if this is a special global used by LLVM, if so, emit it.
448     if (EmitSpecialLLVMGlobal(I))
449       continue;
450
451     std::string name = Mang->getValueName(I);
452     Constant *C = I->getInitializer();
453     unsigned Align = TD->getPreferredAlignmentLog(I);
454     bool bCustomSegment = false;
455
456     switch (I->getLinkage()) {
457     case GlobalValue::CommonLinkage:
458     case GlobalValue::LinkOnceLinkage:
459     case GlobalValue::WeakLinkage:
460       SwitchToDataSection("");
461       O << name << "?\tsegment common 'COMMON'\n";
462       bCustomSegment = true;
463       // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
464       // are also available.
465       break;
466     case GlobalValue::AppendingLinkage:
467       SwitchToDataSection("");
468       O << name << "?\tsegment public 'DATA'\n";
469       bCustomSegment = true;
470       // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
471       // are also available.
472       break;
473     case GlobalValue::DLLExportLinkage:
474       DLLExportedGVs.insert(name);
475       // FALL THROUGH
476     case GlobalValue::ExternalLinkage:
477       O << "\tpublic " << name << "\n";
478       // FALL THROUGH
479     case GlobalValue::InternalLinkage:
480       SwitchToSection(TAI->getDataSection());
481       break;
482     default:
483       assert(0 && "Unknown linkage type!");
484     }
485
486     if (!bCustomSegment)
487       EmitAlignment(Align, I);
488
489     O << name << ":\t\t\t\t" << TAI->getCommentString()
490       << " " << I->getName() << '\n';
491
492     EmitGlobalConstant(C);
493
494     if (bCustomSegment)
495       O << name << "?\tends\n";
496   }
497
498     // Output linker support code for dllexported globals
499   if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
500     SwitchToDataSection("");
501     O << "; WARNING: The following code is valid only with MASM v8.x"
502       << "and (possible) higher\n"
503       << "; This version of MASM is usually shipped with Microsoft "
504       << "Visual Studio 2005\n"
505       << "; or (possible) further versions. Unfortunately, there is no "
506       << "way to support\n"
507       << "; dllexported symbols in the earlier versions of MASM in fully "
508       << "automatic way\n\n";
509     O << "_drectve\t segment info alias('.drectve')\n";
510   }
511
512   for (StringSet<>::iterator i = DLLExportedGVs.begin(),
513          e = DLLExportedGVs.end();
514          i != e; ++i)
515     O << "\t db ' /EXPORT:" << i->getKeyData() << ",data'\n";
516
517   for (StringSet<>::iterator i = DLLExportedFns.begin(),
518          e = DLLExportedFns.end();
519          i != e; ++i)
520     O << "\t db ' /EXPORT:" << i->getKeyData() << "'\n";
521
522   if (!DLLExportedGVs.empty() || !DLLExportedFns.empty())
523     O << "_drectve\t ends\n";
524
525   // Bypass X86SharedAsmPrinter::doFinalization().
526   bool Result = AsmPrinter::doFinalization(M);
527   SwitchToDataSection("");
528   O << "\tend\n";
529   return Result;
530 }
531
532 void X86IntelAsmPrinter::EmitString(const ConstantArray *CVA) const {
533   unsigned NumElts = CVA->getNumOperands();
534   if (NumElts) {
535     // ML does not have escape sequences except '' for '.  It also has a maximum
536     // string length of 255.
537     unsigned len = 0;
538     bool inString = false;
539     for (unsigned i = 0; i < NumElts; i++) {
540       int n = cast<ConstantInt>(CVA->getOperand(i))->getZExtValue() & 255;
541       if (len == 0)
542         O << "\tdb ";
543
544       if (n >= 32 && n <= 127) {
545         if (!inString) {
546           if (len > 0) {
547             O << ",'";
548             len += 2;
549           } else {
550             O << "'";
551             len++;
552           }
553           inString = true;
554         }
555         if (n == '\'') {
556           O << "'";
557           len++;
558         }
559         O << char(n);
560       } else {
561         if (inString) {
562           O << "'";
563           len++;
564           inString = false;
565         }
566         if (len > 0) {
567           O << ",";
568           len++;
569         }
570         O << n;
571         len += 1 + (n > 9) + (n > 99);
572       }
573
574       if (len > 60) {
575         if (inString) {
576           O << "'";
577           inString = false;
578         }
579         O << "\n";
580         len = 0;
581       }
582     }
583
584     if (len > 0) {
585       if (inString)
586         O << "'";
587       O << "\n";
588     }
589   }
590 }
591
592 // Include the auto-generated portion of the assembly writer.
593 #include "X86GenAsmWriter1.inc"