df0b107f9d84b4446cc6ccf1f338098da9a1722c
[oota-llvm.git] / lib / Target / X86 / AsmPrinter / X86ATTAsmPrinter.cpp
1 //===-- X86ATTAsmPrinter.cpp - Convert X86 LLVM code to AT&T 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 AT&T format assembly
12 // language. This printer is the output mechanism used by `llc'.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "asm-printer"
17 #include "X86ATTAsmPrinter.h"
18 #include "X86.h"
19 #include "X86COFF.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetAsmInfo.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Module.h"
26 #include "llvm/Type.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/CodeGen/MachineJumpTableInfo.h"
30 #include "llvm/Support/Mangler.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetAsmInfo.h"
33 #include "llvm/Target/TargetOptions.h"
34 using namespace llvm;
35
36 STATISTIC(EmittedInsts, "Number of machine instrs printed");
37
38 static std::string getPICLabelString(unsigned FnNum,
39                                      const TargetAsmInfo *TAI,
40                                      const X86Subtarget* Subtarget) {
41   std::string label;
42   if (Subtarget->isTargetDarwin())
43     label =  "\"L" + utostr_32(FnNum) + "$pb\"";
44   else if (Subtarget->isTargetELF())
45     label = ".Lllvm$" + utostr_32(FnNum) + "." "$piclabel";
46   else
47     assert(0 && "Don't know how to print PIC label!\n");
48
49   return label;
50 }
51
52 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
53                                                     const TargetData *TD) {
54   X86MachineFunctionInfo Info;
55   uint64_t Size = 0;
56
57   switch (F->getCallingConv()) {
58   case CallingConv::X86_StdCall:
59     Info.setDecorationStyle(StdCall);
60     break;
61   case CallingConv::X86_FastCall:
62     Info.setDecorationStyle(FastCall);
63     break;
64   default:
65     return Info;
66   }
67
68   unsigned argNum = 1;
69   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
70        AI != AE; ++AI, ++argNum) {
71     const Type* Ty = AI->getType();
72
73     // 'Dereference' type in case of byval parameter attribute
74     if (F->paramHasAttr(argNum, Attribute::ByVal))
75       Ty = cast<PointerType>(Ty)->getElementType();
76
77     // Size should be aligned to DWORD boundary
78     Size += ((TD->getTypePaddedSize(Ty) + 3)/4)*4;
79   }
80
81   // We're not supporting tooooo huge arguments :)
82   Info.setBytesToPopOnReturn((unsigned int)Size);
83   return Info;
84 }
85
86 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
87 /// Don't print things like \n or \0.
88 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
89   for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
90        Name != E; ++Name)
91     if (isprint(*Name))
92       OS << *Name;
93 }
94
95 /// decorateName - Query FunctionInfoMap and use this information for various
96 /// name decoration.
97 void X86ATTAsmPrinter::decorateName(std::string &Name,
98                                     const GlobalValue *GV) {
99   const Function *F = dyn_cast<Function>(GV);
100   if (!F) return;
101
102   // We don't want to decorate non-stdcall or non-fastcall functions right now
103   unsigned CC = F->getCallingConv();
104   if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
105     return;
106
107   // Decorate names only when we're targeting Cygwin/Mingw32 targets
108   if (!Subtarget->isTargetCygMing())
109     return;
110
111   FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
112
113   const X86MachineFunctionInfo *Info;
114   if (info_item == FunctionInfoMap.end()) {
115     // Calculate apropriate function info and populate map
116     FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
117     Info = &FunctionInfoMap[F];
118   } else {
119     Info = &info_item->second;
120   }
121
122   const FunctionType *FT = F->getFunctionType();
123   switch (Info->getDecorationStyle()) {
124   case None:
125     break;
126   case StdCall:
127     // "Pure" variadic functions do not receive @0 suffix.
128     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
129         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
130       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
131     break;
132   case FastCall:
133     // "Pure" variadic functions do not receive @0 suffix.
134     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
135         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
136       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
137
138     if (Name[0] == '_') {
139       Name[0] = '@';
140     } else {
141       Name = '@' + Name;
142     }
143     break;
144   default:
145     assert(0 && "Unsupported DecorationStyle");
146   }
147 }
148
149 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
150   const Function *F = MF.getFunction();
151
152   decorateName(CurrentFnName, F);
153
154   SwitchToSection(TAI->SectionForGlobal(F));
155
156   unsigned FnAlign = 4;
157   if (F->hasFnAttr(Attribute::OptimizeForSize))
158     FnAlign = 1;
159   switch (F->getLinkage()) {
160   default: assert(0 && "Unknown linkage type!");
161   case Function::InternalLinkage:  // Symbols default to internal.
162   case Function::PrivateLinkage:
163     EmitAlignment(FnAlign, F);
164     break;
165   case Function::DLLExportLinkage:
166   case Function::ExternalLinkage:
167     EmitAlignment(FnAlign, F);
168     O << "\t.globl\t" << CurrentFnName << '\n';
169     break;
170   case Function::LinkOnceLinkage:
171   case Function::WeakLinkage:
172     EmitAlignment(FnAlign, F);
173     if (Subtarget->isTargetDarwin()) {
174       O << "\t.globl\t" << CurrentFnName << '\n';
175       O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
176     } else if (Subtarget->isTargetCygMing()) {
177       O << "\t.globl\t" << CurrentFnName << "\n"
178            "\t.linkonce discard\n";
179     } else {
180       O << "\t.weak\t" << CurrentFnName << '\n';
181     }
182     break;
183   }
184
185   printVisibility(CurrentFnName, F->getVisibility());
186
187   if (Subtarget->isTargetELF())
188     O << "\t.type\t" << CurrentFnName << ",@function\n";
189   else if (Subtarget->isTargetCygMing()) {
190     O << "\t.def\t " << CurrentFnName
191       << ";\t.scl\t" <<
192       (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
193       << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
194       << ";\t.endef\n";
195   }
196
197   O << CurrentFnName << ":\n";
198   // Add some workaround for linkonce linkage on Cygwin\MinGW
199   if (Subtarget->isTargetCygMing() &&
200       (F->getLinkage() == Function::LinkOnceLinkage ||
201        F->getLinkage() == Function::WeakLinkage))
202     O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
203 }
204
205 /// runOnMachineFunction - This uses the printMachineInstruction()
206 /// method to print assembly for each instruction.
207 ///
208 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
209   const Function *F = MF.getFunction();
210   unsigned CC = F->getCallingConv();
211
212   SetupMachineFunction(MF);
213   O << "\n\n";
214
215   // Populate function information map.  Actually, We don't want to populate
216   // non-stdcall or non-fastcall functions' information right now.
217   if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
218     FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
219
220   // Print out constants referenced by the function
221   EmitConstantPool(MF.getConstantPool());
222
223   if (F->hasDLLExportLinkage())
224     DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
225
226   // Print the 'header' of function
227   emitFunctionHeader(MF);
228
229   // Emit pre-function debug and/or EH information.
230   if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
231     DW->BeginFunction(&MF);
232
233   // Print out code for the function.
234   bool hasAnyRealCode = false;
235   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
236        I != E; ++I) {
237     // Print a label for the basic block.
238     if (!I->pred_empty()) {
239       printBasicBlockLabel(I, true, true);
240       O << '\n';
241     }
242     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
243          II != IE; ++II) {
244       // Print the assembly for the instruction.
245       if (!II->isLabel())
246         hasAnyRealCode = true;
247       printMachineInstruction(II);
248     }
249   }
250
251   if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
252     // If the function is empty, then we need to emit *something*. Otherwise,
253     // the function's label might be associated with something that it wasn't
254     // meant to be associated with. We emit a noop in this situation.
255     // We are assuming inline asms are code.
256     O << "\tnop\n";
257   }
258
259   if (TAI->hasDotTypeDotSizeDirective())
260     O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
261
262   // Emit post-function debug information.
263   if (TAI->doesSupportDebugInformation())
264     DW->EndFunction(&MF);
265
266   // Print out jump tables referenced by the function.
267   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
268
269   O.flush();
270
271   // We didn't modify anything.
272   return false;
273 }
274
275 static inline bool shouldPrintGOT(TargetMachine &TM, const X86Subtarget* ST) {
276   return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
277 }
278
279 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
280   return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_ &&
281       (ST->isPICStyleRIPRel() || ST->isPICStyleGOT());
282 }
283
284 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
285   return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
286 }
287
288 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
289                                     const char *Modifier, bool NotRIPRel) {
290   const MachineOperand &MO = MI->getOperand(OpNo);
291   switch (MO.getType()) {
292   case MachineOperand::MO_Register: {
293     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
294            "Virtual registers should not make it this far!");
295     O << '%';
296     unsigned Reg = MO.getReg();
297     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
298       MVT VT = (strcmp(Modifier+6,"64") == 0) ?
299         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
300                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
301       Reg = getX86SubSuperRegister(Reg, VT);
302     }
303     O << TRI->getAsmName(Reg);
304     return;
305   }
306
307   case MachineOperand::MO_Immediate:
308     if (!Modifier ||
309         (strcmp(Modifier, "debug") && strcmp(Modifier, "mem")))
310       O << '$';
311     O << MO.getImm();
312     return;
313   case MachineOperand::MO_MachineBasicBlock:
314     printBasicBlockLabel(MO.getMBB());
315     return;
316   case MachineOperand::MO_JumpTableIndex: {
317     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
318     if (!isMemOp) O << '$';
319     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
320       << MO.getIndex();
321
322     if (TM.getRelocationModel() == Reloc::PIC_) {
323       if (Subtarget->isPICStyleStub())
324         O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
325           << "$pb\"";
326       else if (Subtarget->isPICStyleGOT())
327         O << "@GOTOFF";
328     }
329
330     if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
331       O << "(%rip)";
332     return;
333   }
334   case MachineOperand::MO_ConstantPoolIndex: {
335     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
336     if (!isMemOp) O << '$';
337     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
338       << MO.getIndex();
339
340     if (TM.getRelocationModel() == Reloc::PIC_) {
341       if (Subtarget->isPICStyleStub())
342         O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
343           << "$pb\"";
344       else if (Subtarget->isPICStyleGOT())
345         O << "@GOTOFF";
346     }
347
348     printOffset(MO.getOffset());
349
350     if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
351       O << "(%rip)";
352     return;
353   }
354   case MachineOperand::MO_GlobalAddress: {
355     bool isCallOp = Modifier && !strcmp(Modifier, "call");
356     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
357     bool needCloseParen = false;
358
359     const GlobalValue *GV = MO.getGlobal();
360     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
361     if (!GVar) {
362       // If GV is an alias then use the aliasee for determining
363       // thread-localness.
364       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
365         GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
366     }
367
368     bool isThreadLocal = GVar && GVar->isThreadLocal();
369
370     std::string Name = Mang->getValueName(GV);
371     decorateName(Name, GV);
372
373     if (!isMemOp && !isCallOp)
374       O << '$';
375     else if (Name[0] == '$') {
376       // The name begins with a dollar-sign. In order to avoid having it look
377       // like an integer immediate to the assembler, enclose it in parens.
378       O << '(';
379       needCloseParen = true;
380     }
381
382     if (shouldPrintStub(TM, Subtarget)) {
383       // Link-once, declaration, or Weakly-linked global variables need
384       // non-lazily-resolved stubs
385       if (GV->isDeclaration() || GV->mayBeOverridden()) {
386         // Dynamically-resolved functions need a stub for the function.
387         if (isCallOp && isa<Function>(GV)) {
388           // Function stubs are no longer needed for Mac OS X 10.5 and up.
389           if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
390             O << Name;
391           } else {
392             FnStubs.insert(Name);
393             printSuffixedName(Name, "$stub");
394           }
395         } else if (GV->hasHiddenVisibility()) {
396           if (!GV->isDeclaration() && !GV->hasCommonLinkage())
397             // Definition is not definitely in the current translation unit.
398             O << Name;
399           else {
400             HiddenGVStubs.insert(Name);
401             printSuffixedName(Name, "$non_lazy_ptr");
402           }
403         } else {
404           GVStubs.insert(Name);
405           printSuffixedName(Name, "$non_lazy_ptr");
406         }
407       } else {
408         if (GV->hasDLLImportLinkage())
409           O << "__imp_";
410         O << Name;
411       }
412
413       if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
414         O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget);
415     } else {
416       if (GV->hasDLLImportLinkage()) {
417         O << "__imp_";
418       }
419       O << Name;
420
421       if (isCallOp) {
422         if (shouldPrintPLT(TM, Subtarget)) {
423           // Assemble call via PLT for externally visible symbols
424           if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
425               !GV->hasLocalLinkage())
426             O << "@PLT";
427         }
428         if (Subtarget->isTargetCygMing() && GV->isDeclaration())
429           // Save function name for later type emission
430           FnStubs.insert(Name);
431       }
432     }
433
434     if (GV->hasExternalWeakLinkage())
435       ExtWeakSymbols.insert(GV);
436
437     printOffset(MO.getOffset());
438
439     if (isThreadLocal) {
440       if (TM.getRelocationModel() == Reloc::PIC_ || Subtarget->is64Bit())
441         O << "@TLSGD"; // general dynamic TLS model
442       else
443         if (GV->isDeclaration())
444           O << "@INDNTPOFF"; // initial exec TLS model
445         else
446           O << "@NTPOFF"; // local exec TLS model
447     } else if (isMemOp) {
448       if (shouldPrintGOT(TM, Subtarget)) {
449         if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
450           O << "@GOT";
451         else
452           O << "@GOTOFF";
453       } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel &&
454                  TM.getRelocationModel() != Reloc::Static) {
455         if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
456           O << "@GOTPCREL";
457
458         if (needCloseParen) {
459           needCloseParen = false;
460           O << ')';
461         }
462
463         // Use rip when possible to reduce code size, except when
464         // index or base register are also part of the address. e.g.
465         // foo(%rip)(%rcx,%rax,4) is not legal
466         O << "(%rip)";
467       }
468     }
469
470     if (needCloseParen)
471       O << ')';
472
473     return;
474   }
475   case MachineOperand::MO_ExternalSymbol: {
476     bool isCallOp = Modifier && !strcmp(Modifier, "call");
477     bool needCloseParen = false;
478     std::string Name(TAI->getGlobalPrefix());
479     Name += MO.getSymbolName();
480     // Print function stub suffix unless it's Mac OS X 10.5 and up.
481     if (isCallOp && shouldPrintStub(TM, Subtarget) && 
482         !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
483       FnStubs.insert(Name);
484       printSuffixedName(Name, "$stub");
485       return;
486     }
487     if (!isCallOp)
488       O << '$';
489     else if (Name[0] == '$') {
490       // The name begins with a dollar-sign. In order to avoid having it look
491       // like an integer immediate to the assembler, enclose it in parens.
492       O << '(';
493       needCloseParen = true;
494     }
495
496     O << Name;
497
498     if (shouldPrintPLT(TM, Subtarget)) {
499       std::string GOTName(TAI->getGlobalPrefix());
500       GOTName+="_GLOBAL_OFFSET_TABLE_";
501       if (Name == GOTName)
502         // HACK! Emit extra offset to PC during printing GOT offset to
503         // compensate for the size of popl instruction. The resulting code
504         // should look like:
505         //   call .piclabel
506         // piclabel:
507         //   popl %some_register
508         //   addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
509         O << " + [.-"
510           << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
511
512       if (isCallOp)
513         O << "@PLT";
514     }
515
516     if (needCloseParen)
517       O << ')';
518
519     if (!isCallOp && Subtarget->isPICStyleRIPRel())
520       O << "(%rip)";
521
522     return;
523   }
524   default:
525     O << "<unknown operand type>"; return;
526   }
527 }
528
529 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
530   unsigned char value = MI->getOperand(Op).getImm();
531   assert(value <= 7 && "Invalid ssecc argument!");
532   switch (value) {
533   case 0: O << "eq"; break;
534   case 1: O << "lt"; break;
535   case 2: O << "le"; break;
536   case 3: O << "unord"; break;
537   case 4: O << "neq"; break;
538   case 5: O << "nlt"; break;
539   case 6: O << "nle"; break;
540   case 7: O << "ord"; break;
541   }
542 }
543
544 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
545                                          const char *Modifier){
546   assert(isMem(MI, Op) && "Invalid memory reference!");
547   MachineOperand BaseReg  = MI->getOperand(Op);
548   MachineOperand IndexReg = MI->getOperand(Op+2);
549   const MachineOperand &DispSpec = MI->getOperand(Op+3);
550
551   bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
552   if (DispSpec.isGlobal() ||
553       DispSpec.isCPI() ||
554       DispSpec.isJTI()) {
555     printOperand(MI, Op+3, "mem", NotRIPRel);
556   } else {
557     int DispVal = DispSpec.getImm();
558     if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
559       O << DispVal;
560   }
561
562   if (IndexReg.getReg() || BaseReg.getReg()) {
563     unsigned ScaleVal = MI->getOperand(Op+1).getImm();
564     unsigned BaseRegOperand = 0, IndexRegOperand = 2;
565
566     // There are cases where we can end up with ESP/RSP in the indexreg slot.
567     // If this happens, swap the base/index register to support assemblers that
568     // don't work when the index is *SP.
569     if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
570       assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
571       std::swap(BaseReg, IndexReg);
572       std::swap(BaseRegOperand, IndexRegOperand);
573     }
574
575     O << '(';
576     if (BaseReg.getReg())
577       printOperand(MI, Op+BaseRegOperand, Modifier);
578
579     if (IndexReg.getReg()) {
580       O << ',';
581       printOperand(MI, Op+IndexRegOperand, Modifier);
582       if (ScaleVal != 1)
583         O << ',' << ScaleVal;
584     }
585     O << ')';
586   }
587 }
588
589 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
590                                            const MachineBasicBlock *MBB) const {
591   if (!TAI->getSetDirective())
592     return;
593
594   // We don't need .set machinery if we have GOT-style relocations
595   if (Subtarget->isPICStyleGOT())
596     return;
597
598   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
599     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
600   printBasicBlockLabel(MBB, false, false, false);
601   if (Subtarget->isPICStyleRIPRel())
602     O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
603       << '_' << uid << '\n';
604   else
605     O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << '\n';
606 }
607
608 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
609   std::string label = getPICLabelString(getFunctionNumber(), TAI, Subtarget);
610   O << label << '\n' << label << ':';
611 }
612
613
614 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
615                                               const MachineBasicBlock *MBB,
616                                               unsigned uid) const
617 {
618   const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
619     TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
620
621   O << JTEntryDirective << ' ';
622
623   if (TM.getRelocationModel() == Reloc::PIC_) {
624     if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
625       O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
626         << '_' << uid << "_set_" << MBB->getNumber();
627     } else if (Subtarget->isPICStyleGOT()) {
628       printBasicBlockLabel(MBB, false, false, false);
629       O << "@GOTOFF";
630     } else
631       assert(0 && "Don't know how to print MBB label for this PIC mode");
632   } else
633     printBasicBlockLabel(MBB, false, false, false);
634 }
635
636 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
637                                          const char Mode) {
638   unsigned Reg = MO.getReg();
639   switch (Mode) {
640   default: return true;  // Unknown mode.
641   case 'b': // Print QImode register
642     Reg = getX86SubSuperRegister(Reg, MVT::i8);
643     break;
644   case 'h': // Print QImode high register
645     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
646     break;
647   case 'w': // Print HImode register
648     Reg = getX86SubSuperRegister(Reg, MVT::i16);
649     break;
650   case 'k': // Print SImode register
651     Reg = getX86SubSuperRegister(Reg, MVT::i32);
652     break;
653   case 'q': // Print DImode register
654     Reg = getX86SubSuperRegister(Reg, MVT::i64);
655     break;
656   }
657
658   O << '%'<< TRI->getAsmName(Reg);
659   return false;
660 }
661
662 /// PrintAsmOperand - Print out an operand for an inline asm expression.
663 ///
664 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
665                                        unsigned AsmVariant,
666                                        const char *ExtraCode) {
667   // Does this asm operand have a single letter operand modifier?
668   if (ExtraCode && ExtraCode[0]) {
669     if (ExtraCode[1] != 0) return true; // Unknown modifier.
670
671     switch (ExtraCode[0]) {
672     default: return true;  // Unknown modifier.
673     case 'c': // Don't print "$" before a global var name or constant.
674       printOperand(MI, OpNo, "mem");
675       return false;
676     case 'b': // Print QImode register
677     case 'h': // Print QImode high register
678     case 'w': // Print HImode register
679     case 'k': // Print SImode register
680     case 'q': // Print DImode register
681       if (MI->getOperand(OpNo).isReg())
682         return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
683       printOperand(MI, OpNo);
684       return false;
685
686     case 'P': // Don't print @PLT, but do print as memory.
687       printOperand(MI, OpNo, "mem");
688       return false;
689     }
690   }
691
692   printOperand(MI, OpNo);
693   return false;
694 }
695
696 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
697                                              unsigned OpNo,
698                                              unsigned AsmVariant,
699                                              const char *ExtraCode) {
700   if (ExtraCode && ExtraCode[0]) {
701     if (ExtraCode[1] != 0) return true; // Unknown modifier.
702
703     switch (ExtraCode[0]) {
704     default: return true;  // Unknown modifier.
705     case 'b': // Print QImode register
706     case 'h': // Print QImode high register
707     case 'w': // Print HImode register
708     case 'k': // Print SImode register
709     case 'q': // Print SImode register
710       // These only apply to registers, ignore on mem.
711       break;
712     }
713   }
714   printMemReference(MI, OpNo);
715   return false;
716 }
717
718 /// printMachineInstruction -- Print out a single X86 LLVM instruction
719 /// MI in AT&T syntax to the current output stream.
720 ///
721 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
722   ++EmittedInsts;
723
724   // Call the autogenerated instruction printer routines.
725   printInstruction(MI);
726 }
727
728 /// doInitialization
729 bool X86ATTAsmPrinter::doInitialization(Module &M) {
730
731   bool Result = AsmPrinter::doInitialization(M);
732
733   if (TAI->doesSupportDebugInformation()) {
734     // Let PassManager know we need debug information and relay
735     // the MachineModuleInfo address on to DwarfWriter.
736     // AsmPrinter::doInitialization did this analysis.
737     MMI = getAnalysisToUpdate<MachineModuleInfo>();
738     DW = getAnalysisToUpdate<DwarfWriter>();
739     DW->BeginModule(&M, MMI, O, this, TAI);
740   }
741
742   // Darwin wants symbols to be quoted if they have complex names.
743   if (Subtarget->isTargetDarwin())
744     Mang->setUseQuotes(true);
745
746   return Result;
747 }
748
749
750 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
751   const TargetData *TD = TM.getTargetData();
752
753   if (!GVar->hasInitializer())
754     return;   // External global require no code
755
756   // Check to see if this is a special global used by LLVM, if so, emit it.
757   if (EmitSpecialLLVMGlobal(GVar)) {
758     if (Subtarget->isTargetDarwin() &&
759         TM.getRelocationModel() == Reloc::Static) {
760       if (GVar->getName() == "llvm.global_ctors")
761         O << ".reference .constructors_used\n";
762       else if (GVar->getName() == "llvm.global_dtors")
763         O << ".reference .destructors_used\n";
764     }
765     return;
766   }
767
768   std::string name = Mang->getValueName(GVar);
769   Constant *C = GVar->getInitializer();
770   const Type *Type = C->getType();
771   unsigned Size = TD->getTypePaddedSize(Type);
772   unsigned Align = TD->getPreferredAlignmentLog(GVar);
773
774   printVisibility(name, GVar->getVisibility());
775
776   if (Subtarget->isTargetELF())
777     O << "\t.type\t" << name << ",@object\n";
778
779   SwitchToSection(TAI->SectionForGlobal(GVar));
780
781   if (C->isNullValue() && !GVar->hasSection()) {
782     // FIXME: This seems to be pretty darwin-specific
783     if (GVar->hasExternalLinkage()) {
784       if (const char *Directive = TAI->getZeroFillDirective()) {
785         O << "\t.globl " << name << '\n';
786         O << Directive << "__DATA, __common, " << name << ", "
787           << Size << ", " << Align << '\n';
788         return;
789       }
790     }
791
792     if (!GVar->isThreadLocal() &&
793         (GVar->hasLocalLinkage() || GVar->mayBeOverridden())) {
794       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
795
796       if (TAI->getLCOMMDirective() != NULL) {
797         if (GVar->hasLocalLinkage()) {
798           O << TAI->getLCOMMDirective() << name << ',' << Size;
799           if (Subtarget->isTargetDarwin())
800             O << ',' << Align;
801         } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
802           O << "\t.globl " << name << '\n'
803             << TAI->getWeakDefDirective() << name << '\n';
804           EmitAlignment(Align, GVar);
805           O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
806           PrintUnmangledNameSafely(GVar, O);
807           O << '\n';
808           EmitGlobalConstant(C);
809           return;
810         } else {
811           O << TAI->getCOMMDirective()  << name << ',' << Size;
812           if (TAI->getCOMMDirectiveTakesAlignment())
813             O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
814         }
815       } else {
816         if (!Subtarget->isTargetCygMing()) {
817           if (GVar->hasLocalLinkage())
818             O << "\t.local\t" << name << '\n';
819         }
820         O << TAI->getCOMMDirective()  << name << ',' << Size;
821         if (TAI->getCOMMDirectiveTakesAlignment())
822           O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
823       }
824       O << "\t\t" << TAI->getCommentString() << ' ';
825       PrintUnmangledNameSafely(GVar, O);
826       O << '\n';
827       return;
828     }
829   }
830
831   switch (GVar->getLinkage()) {
832   case GlobalValue::CommonLinkage:
833   case GlobalValue::LinkOnceLinkage:
834   case GlobalValue::WeakLinkage:
835     if (Subtarget->isTargetDarwin()) {
836       O << "\t.globl " << name << '\n'
837         << TAI->getWeakDefDirective() << name << '\n';
838     } else if (Subtarget->isTargetCygMing()) {
839       O << "\t.globl\t" << name << "\n"
840            "\t.linkonce same_size\n";
841     } else {
842       O << "\t.weak\t" << name << '\n';
843     }
844     break;
845   case GlobalValue::DLLExportLinkage:
846   case GlobalValue::AppendingLinkage:
847     // FIXME: appending linkage variables should go into a section of
848     // their name or something.  For now, just emit them as external.
849   case GlobalValue::ExternalLinkage:
850     // If external or appending, declare as a global symbol
851     O << "\t.globl " << name << '\n';
852     // FALL THROUGH
853   case GlobalValue::PrivateLinkage:
854   case GlobalValue::InternalLinkage:
855      break;
856   default:
857     assert(0 && "Unknown linkage type!");
858   }
859
860   EmitAlignment(Align, GVar);
861   O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
862   PrintUnmangledNameSafely(GVar, O);
863   O << '\n';
864   if (TAI->hasDotTypeDotSizeDirective())
865     O << "\t.size\t" << name << ", " << Size << '\n';
866
867   // If the initializer is a extern weak symbol, remember to emit the weak
868   // reference!
869   if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
870     if (GV->hasExternalWeakLinkage())
871       ExtWeakSymbols.insert(GV);
872
873   EmitGlobalConstant(C);
874 }
875
876 /// printGVStub - Print stub for a global value.
877 ///
878 void X86ATTAsmPrinter::printGVStub(const char *GV, const char *Prefix) {
879   printSuffixedName(GV, "$non_lazy_ptr", Prefix);
880   O << ":\n\t.indirect_symbol ";
881   if (Prefix) O << Prefix;
882   O << GV << "\n\t.long\t0\n";
883 }
884
885 /// printHiddenGVStub - Print stub for a hidden global value.
886 ///
887 void X86ATTAsmPrinter::printHiddenGVStub(const char *GV, const char *Prefix) {
888   EmitAlignment(2);
889   printSuffixedName(GV, "$non_lazy_ptr", Prefix);
890   if (Prefix) O << Prefix;
891   O << ":\n" << TAI->getData32bitsDirective() << GV << '\n';
892 }
893
894
895 bool X86ATTAsmPrinter::doFinalization(Module &M) {
896   // Print out module-level global variables here.
897   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
898        I != E; ++I) {
899     printModuleLevelGV(I);
900
901     if (I->hasDLLExportLinkage())
902       DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
903   }
904
905   // Output linker support code for dllexported globals
906   if (!DLLExportedGVs.empty())
907     SwitchToDataSection(".section .drectve");
908
909   for (StringSet<>::iterator i = DLLExportedGVs.begin(),
910          e = DLLExportedGVs.end();
911          i != e; ++i)
912     O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
913
914   if (!DLLExportedFns.empty()) {
915     SwitchToDataSection(".section .drectve");
916   }
917
918   for (StringSet<>::iterator i = DLLExportedFns.begin(),
919          e = DLLExportedFns.end();
920          i != e; ++i)
921     O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
922
923   if (Subtarget->isTargetDarwin()) {
924     SwitchToDataSection("");
925
926     // Output stubs for dynamically-linked functions
927     for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
928          i != e; ++i) {
929       SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
930                           "self_modifying_code+pure_instructions,5", 0);
931       const char *p = i->getKeyData();
932       printSuffixedName(p, "$stub");
933       O << ":\n"
934            "\t.indirect_symbol " << p << "\n"
935            "\thlt ; hlt ; hlt ; hlt ; hlt\n";
936     }
937
938     O << '\n';
939
940     // Print global value stubs.
941     bool InStubSection = false;
942     if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
943       // Add the (possibly multiple) personalities to the set of global values.
944       // Only referenced functions get into the Personalities list.
945       const std::vector<Function *>& Personalities = MMI->getPersonalities();
946       for (std::vector<Function *>::const_iterator I = Personalities.begin(),
947              E = Personalities.end(); I != E; ++I) {
948         if (!*I)
949           continue;
950         if (!InStubSection) {
951           SwitchToDataSection(
952                      "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
953           InStubSection = true;
954         }
955         printGVStub((*I)->getNameStart(), "_");
956       }
957     }
958
959     // Output stubs for external and common global variables.
960     if (!InStubSection && !GVStubs.empty())
961       SwitchToDataSection(
962                     "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
963     for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
964          i != e; ++i)
965       printGVStub(i->getKeyData());
966
967     if (!HiddenGVStubs.empty()) {
968       SwitchToSection(TAI->getDataSection());
969       for (StringSet<>::iterator i = HiddenGVStubs.begin(), e = HiddenGVStubs.end();
970            i != e; ++i)
971         printHiddenGVStub(i->getKeyData());
972     }
973
974     // Emit final debug information.
975     DwarfWriter *DW = getAnalysisToUpdate<DwarfWriter>();
976     DW->EndModule();
977
978     // Funny Darwin hack: This flag tells the linker that no global symbols
979     // contain code that falls through to other global symbols (e.g. the obvious
980     // implementation of multiple entry points).  If this doesn't occur, the
981     // linker can safely perform dead code stripping.  Since LLVM never
982     // generates code that does this, it is always safe to set.
983     O << "\t.subsections_via_symbols\n";
984   } else if (Subtarget->isTargetCygMing()) {
985     // Emit type information for external functions
986     for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
987          i != e; ++i) {
988       O << "\t.def\t " << i->getKeyData()
989         << ";\t.scl\t" << COFF::C_EXT
990         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
991         << ";\t.endef\n";
992     }
993
994     // Emit final debug information.
995     DwarfWriter *DW = getAnalysisToUpdate<DwarfWriter>();
996     DW->EndModule();
997   } else if (Subtarget->isTargetELF()) {
998     // Emit final debug information.
999     DwarfWriter *DW = getAnalysisToUpdate<DwarfWriter>();
1000     DW->EndModule();
1001   }
1002
1003   return AsmPrinter::doFinalization(M);
1004 }
1005
1006 // Include the auto-generated portion of the assembly writer.
1007 #include "X86GenAsmWriter.inc"