1 //===-- X86ATTAsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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'.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "asm-printer"
17 #include "X86ATTAsmPrinter.h"
18 #include "X86ATTInstPrinter.h"
19 #include "X86MCInstLower.h"
22 #include "X86MachineFunctionInfo.h"
23 #include "X86TargetMachine.h"
24 #include "llvm/CallingConv.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Module.h"
27 #include "llvm/Type.h"
28 #include "llvm/Assembly/Writer.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCSectionMachO.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/FormattedStream.h"
36 #include "llvm/Support/Mangler.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/Target/TargetLoweringObjectFile.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/ADT/Statistic.h"
44 STATISTIC(EmittedInsts
, "Number of machine instrs printed");
46 //===----------------------------------------------------------------------===//
47 // Primitive Helper Functions.
48 //===----------------------------------------------------------------------===//
50 void X86ATTAsmPrinter::printMCInst(const MCInst
*MI
) {
51 X86ATTInstPrinter(O
, *MAI
).printInstruction(MI
);
54 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
55 // FIXME: Gross const cast hack.
56 X86ATTAsmPrinter
*AP
= const_cast<X86ATTAsmPrinter
*>(this);
57 X86MCInstLower(OutContext
, 0, *AP
).GetPICBaseSymbol()->print(O
, MAI
);
60 static X86MachineFunctionInfo
calculateFunctionInfo(const Function
*F
,
61 const TargetData
*TD
) {
62 X86MachineFunctionInfo Info
;
65 switch (F
->getCallingConv()) {
66 case CallingConv::X86_StdCall
:
67 Info
.setDecorationStyle(StdCall
);
69 case CallingConv::X86_FastCall
:
70 Info
.setDecorationStyle(FastCall
);
77 for (Function::const_arg_iterator AI
= F
->arg_begin(), AE
= F
->arg_end();
78 AI
!= AE
; ++AI
, ++argNum
) {
79 const Type
* Ty
= AI
->getType();
81 // 'Dereference' type in case of byval parameter attribute
82 if (F
->paramHasAttr(argNum
, Attribute::ByVal
))
83 Ty
= cast
<PointerType
>(Ty
)->getElementType();
85 // Size should be aligned to DWORD boundary
86 Size
+= ((TD
->getTypeAllocSize(Ty
) + 3)/4)*4;
89 // We're not supporting tooooo huge arguments :)
90 Info
.setBytesToPopOnReturn((unsigned int)Size
);
94 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
95 /// various name decorations for Cygwin and MingW.
96 void X86ATTAsmPrinter::DecorateCygMingName(SmallVectorImpl
<char> &Name
,
97 const GlobalValue
*GV
) {
98 assert(Subtarget
->isTargetCygMing() && "This is only for cygwin and mingw");
100 const Function
*F
= dyn_cast
<Function
>(GV
);
103 // Save function name for later type emission.
104 if (F
->isDeclaration())
105 CygMingStubs
.insert(StringRef(Name
.data(), Name
.size()));
107 // We don't want to decorate non-stdcall or non-fastcall functions right now
108 CallingConv::ID CC
= F
->getCallingConv();
109 if (CC
!= CallingConv::X86_StdCall
&& CC
!= CallingConv::X86_FastCall
)
113 const X86MachineFunctionInfo
*Info
;
115 FMFInfoMap::const_iterator info_item
= FunctionInfoMap
.find(F
);
116 if (info_item
== FunctionInfoMap
.end()) {
117 // Calculate apropriate function info and populate map
118 FunctionInfoMap
[F
] = calculateFunctionInfo(F
, TM
.getTargetData());
119 Info
= &FunctionInfoMap
[F
];
121 Info
= &info_item
->second
;
124 if (Info
->getDecorationStyle() == None
) return;
125 const FunctionType
*FT
= F
->getFunctionType();
127 // "Pure" variadic functions do not receive @0 suffix.
128 if (!FT
->isVarArg() || FT
->getNumParams() == 0 ||
129 (FT
->getNumParams() == 1 && F
->hasStructRetAttr()))
130 raw_svector_ostream(Name
) << '@' << Info
->getBytesToPopOnReturn();
132 if (Info
->getDecorationStyle() == FastCall
) {
136 Name
.insert(Name
.begin(), '@');
140 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
141 /// various name decorations for Cygwin and MingW.
142 void X86ATTAsmPrinter::DecorateCygMingName(std::string
&Name
,
143 const GlobalValue
*GV
) {
144 SmallString
<128> NameStr(Name
.begin(), Name
.end());
145 DecorateCygMingName(NameStr
, GV
);
146 Name
.assign(NameStr
.begin(), NameStr
.end());
149 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction
&MF
) {
150 unsigned FnAlign
= MF
.getAlignment();
151 const Function
*F
= MF
.getFunction();
153 if (Subtarget
->isTargetCygMing())
154 DecorateCygMingName(CurrentFnName
, F
);
156 OutStreamer
.SwitchSection(getObjFileLowering().SectionForGlobal(F
, Mang
, TM
));
157 EmitAlignment(FnAlign
, F
);
159 switch (F
->getLinkage()) {
160 default: llvm_unreachable("Unknown linkage type!");
161 case Function::InternalLinkage
: // Symbols default to internal.
162 case Function::PrivateLinkage
:
164 case Function::DLLExportLinkage
:
165 case Function::ExternalLinkage
:
166 O
<< "\t.globl\t" << CurrentFnName
<< '\n';
168 case Function::LinkerPrivateLinkage
:
169 case Function::LinkOnceAnyLinkage
:
170 case Function::LinkOnceODRLinkage
:
171 case Function::WeakAnyLinkage
:
172 case Function::WeakODRLinkage
:
173 if (Subtarget
->isTargetDarwin()) {
174 O
<< "\t.globl\t" << CurrentFnName
<< '\n';
175 O
<< MAI
->getWeakDefDirective() << CurrentFnName
<< '\n';
176 } else if (Subtarget
->isTargetCygMing()) {
177 O
<< "\t.globl\t" << CurrentFnName
<< "\n"
178 "\t.linkonce discard\n";
180 O
<< "\t.weak\t" << CurrentFnName
<< '\n';
185 printVisibility(CurrentFnName
, F
->getVisibility());
187 if (Subtarget
->isTargetELF())
188 O
<< "\t.type\t" << CurrentFnName
<< ",@function\n";
189 else if (Subtarget
->isTargetCygMing()) {
190 O
<< "\t.def\t " << CurrentFnName
192 (F
->hasInternalLinkage() ? COFF::C_STAT
: COFF::C_EXT
)
193 << ";\t.type\t" << (COFF::DT_FCN
<< COFF::N_BTSHFT
)
197 O
<< CurrentFnName
<< ':';
199 O
.PadToColumn(MAI
->getCommentColumn());
200 O
<< MAI
->getCommentString() << ' ';
201 WriteAsOperand(O
, F
, /*PrintType=*/false, F
->getParent());
205 // Add some workaround for linkonce linkage on Cygwin\MinGW
206 if (Subtarget
->isTargetCygMing() &&
207 (F
->hasLinkOnceLinkage() || F
->hasWeakLinkage()))
208 O
<< "Lllvm$workaround$fake$stub$" << CurrentFnName
<< ":\n";
211 /// runOnMachineFunction - This uses the printMachineInstruction()
212 /// method to print assembly for each instruction.
214 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction
&MF
) {
215 const Function
*F
= MF
.getFunction();
217 CallingConv::ID CC
= F
->getCallingConv();
219 SetupMachineFunction(MF
);
222 // Populate function information map. Actually, We don't want to populate
223 // non-stdcall or non-fastcall functions' information right now.
224 if (CC
== CallingConv::X86_StdCall
|| CC
== CallingConv::X86_FastCall
)
225 FunctionInfoMap
[F
] = *MF
.getInfo
<X86MachineFunctionInfo
>();
227 // Print out constants referenced by the function
228 EmitConstantPool(MF
.getConstantPool());
230 if (F
->hasDLLExportLinkage())
231 DLLExportedFns
.insert(Mang
->getMangledName(F
));
233 // Print the 'header' of function
234 emitFunctionHeader(MF
);
236 // Emit pre-function debug and/or EH information.
237 if (MAI
->doesSupportDebugInformation() || MAI
->doesSupportExceptionHandling())
238 DW
->BeginFunction(&MF
);
240 // Print out code for the function.
241 bool hasAnyRealCode
= false;
242 for (MachineFunction::const_iterator I
= MF
.begin(), E
= MF
.end();
244 // Print a label for the basic block.
245 if (!VerboseAsm
&& (I
->pred_empty() || I
->isOnlyReachableByFallthrough())) {
246 // This is an entry block or a block that's only reachable via a
247 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
249 EmitBasicBlockStart(I
);
252 for (MachineBasicBlock::const_iterator II
= I
->begin(), IE
= I
->end();
254 // Print the assembly for the instruction.
256 hasAnyRealCode
= true;
257 printMachineInstruction(II
);
261 if (Subtarget
->isTargetDarwin() && !hasAnyRealCode
) {
262 // If the function is empty, then we need to emit *something*. Otherwise,
263 // the function's label might be associated with something that it wasn't
264 // meant to be associated with. We emit a noop in this situation.
265 // We are assuming inline asms are code.
269 if (MAI
->hasDotTypeDotSizeDirective())
270 O
<< "\t.size\t" << CurrentFnName
<< ", .-" << CurrentFnName
<< '\n';
272 // Emit post-function debug information.
273 if (MAI
->doesSupportDebugInformation() || MAI
->doesSupportExceptionHandling())
274 DW
->EndFunction(&MF
);
276 // Print out jump tables referenced by the function.
277 EmitJumpTableInfo(MF
.getJumpTableInfo(), MF
);
279 // We didn't modify anything.
283 /// printSymbolOperand - Print a raw symbol reference operand. This handles
284 /// jump tables, constant pools, global address and external symbols, all of
285 /// which print to a label with various suffixes for relocation types etc.
286 void X86ATTAsmPrinter::printSymbolOperand(const MachineOperand
&MO
) {
287 switch (MO
.getType()) {
288 default: llvm_unreachable("unknown symbol type!");
289 case MachineOperand::MO_JumpTableIndex
:
290 O
<< MAI
->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
293 case MachineOperand::MO_ConstantPoolIndex
:
294 O
<< MAI
->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
296 printOffset(MO
.getOffset());
298 case MachineOperand::MO_GlobalAddress
: {
299 const GlobalValue
*GV
= MO
.getGlobal();
301 const char *Suffix
= "";
302 if (MO
.getTargetFlags() == X86II::MO_DARWIN_STUB
)
304 else if (MO
.getTargetFlags() == X86II::MO_DARWIN_NONLAZY
||
305 MO
.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE
||
306 MO
.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE
)
307 Suffix
= "$non_lazy_ptr";
309 std::string Name
= Mang
->getMangledName(GV
, Suffix
, Suffix
[0] != '\0');
310 if (Subtarget
->isTargetCygMing())
311 DecorateCygMingName(Name
, GV
);
313 // Handle dllimport linkage.
314 if (MO
.getTargetFlags() == X86II::MO_DLLIMPORT
)
315 Name
= "__imp_" + Name
;
317 if (MO
.getTargetFlags() == X86II::MO_DARWIN_NONLAZY
||
318 MO
.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE
) {
319 SmallString
<128> NameStr
;
320 Mang
->getNameWithPrefix(NameStr
, GV
, true);
321 NameStr
+= "$non_lazy_ptr";
322 MCSymbol
*Sym
= OutContext
.GetOrCreateSymbol(NameStr
.str());
323 MCSymbol
*&StubSym
= GVStubs
[Sym
];
326 Mang
->getNameWithPrefix(NameStr
, GV
, false);
327 StubSym
= OutContext
.GetOrCreateSymbol(NameStr
.str());
329 } else if (MO
.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE
){
330 SmallString
<128> NameStr
;
331 Mang
->getNameWithPrefix(NameStr
, GV
, true);
332 NameStr
+= "$non_lazy_ptr";
333 MCSymbol
*Sym
= OutContext
.GetOrCreateSymbol(NameStr
.str());
334 MCSymbol
*&StubSym
= HiddenGVStubs
[Sym
];
337 Mang
->getNameWithPrefix(NameStr
, GV
, false);
338 StubSym
= OutContext
.GetOrCreateSymbol(NameStr
.str());
340 } else if (MO
.getTargetFlags() == X86II::MO_DARWIN_STUB
) {
341 SmallString
<128> NameStr
;
342 Mang
->getNameWithPrefix(NameStr
, GV
, true);
344 MCSymbol
*Sym
= OutContext
.GetOrCreateSymbol(NameStr
.str());
345 MCSymbol
*&StubSym
= FnStubs
[Sym
];
348 Mang
->getNameWithPrefix(NameStr
, GV
, false);
349 StubSym
= OutContext
.GetOrCreateSymbol(NameStr
.str());
353 // If the name begins with a dollar-sign, enclose it in parens. We do this
354 // to avoid having it look like an integer immediate to the assembler.
356 O
<< '(' << Name
<< ')';
360 printOffset(MO
.getOffset());
363 case MachineOperand::MO_ExternalSymbol
: {
364 std::string Name
= Mang
->makeNameProper(MO
.getSymbolName());
365 if (MO
.getTargetFlags() == X86II::MO_DARWIN_STUB
) {
367 MCSymbol
*&StubSym
= FnStubs
[OutContext
.GetOrCreateSymbol(Name
)];
369 Name
.erase(Name
.end()-5, Name
.end());
370 StubSym
= OutContext
.GetOrCreateSymbol(Name
);
374 // If the name begins with a dollar-sign, enclose it in parens. We do this
375 // to avoid having it look like an integer immediate to the assembler.
377 O
<< '(' << Name
<< ')';
384 switch (MO
.getTargetFlags()) {
386 llvm_unreachable("Unknown target flag on GV operand");
387 case X86II::MO_NO_FLAG
: // No flag.
389 case X86II::MO_DARWIN_NONLAZY
:
390 case X86II::MO_DLLIMPORT
:
391 case X86II::MO_DARWIN_STUB
:
392 // These affect the name of the symbol, not any suffix.
394 case X86II::MO_GOT_ABSOLUTE_ADDRESS
:
396 PrintPICBaseSymbol();
399 case X86II::MO_PIC_BASE_OFFSET
:
400 case X86II::MO_DARWIN_NONLAZY_PIC_BASE
:
401 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE
:
403 PrintPICBaseSymbol();
405 case X86II::MO_TLSGD
: O
<< "@TLSGD"; break;
406 case X86II::MO_GOTTPOFF
: O
<< "@GOTTPOFF"; break;
407 case X86II::MO_INDNTPOFF
: O
<< "@INDNTPOFF"; break;
408 case X86II::MO_TPOFF
: O
<< "@TPOFF"; break;
409 case X86II::MO_NTPOFF
: O
<< "@NTPOFF"; break;
410 case X86II::MO_GOTPCREL
: O
<< "@GOTPCREL"; break;
411 case X86II::MO_GOT
: O
<< "@GOT"; break;
412 case X86II::MO_GOTOFF
: O
<< "@GOTOFF"; break;
413 case X86II::MO_PLT
: O
<< "@PLT"; break;
417 /// print_pcrel_imm - This is used to print an immediate value that ends up
418 /// being encoded as a pc-relative value. These print slightly differently, for
419 /// example, a $ is not emitted.
420 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr
*MI
, unsigned OpNo
) {
421 const MachineOperand
&MO
= MI
->getOperand(OpNo
);
422 switch (MO
.getType()) {
423 default: llvm_unreachable("Unknown pcrel immediate operand");
424 case MachineOperand::MO_Immediate
:
427 case MachineOperand::MO_MachineBasicBlock
:
428 GetMBBSymbol(MO
.getMBB()->getNumber())->print(O
, MAI
);
430 case MachineOperand::MO_GlobalAddress
:
431 case MachineOperand::MO_ExternalSymbol
:
432 printSymbolOperand(MO
);
438 void X86ATTAsmPrinter::printOperand(const MachineInstr
*MI
, unsigned OpNo
,
439 const char *Modifier
) {
440 const MachineOperand
&MO
= MI
->getOperand(OpNo
);
441 switch (MO
.getType()) {
442 default: llvm_unreachable("unknown operand type!");
443 case MachineOperand::MO_Register
: {
445 unsigned Reg
= MO
.getReg();
446 if (Modifier
&& strncmp(Modifier
, "subreg", strlen("subreg")) == 0) {
447 EVT VT
= (strcmp(Modifier
+6,"64") == 0) ?
448 MVT::i64
: ((strcmp(Modifier
+6, "32") == 0) ? MVT::i32
:
449 ((strcmp(Modifier
+6,"16") == 0) ? MVT::i16
: MVT::i8
));
450 Reg
= getX86SubSuperRegister(Reg
, VT
);
452 O
<< X86ATTInstPrinter::getRegisterName(Reg
);
456 case MachineOperand::MO_Immediate
:
457 O
<< '$' << MO
.getImm();
460 case MachineOperand::MO_JumpTableIndex
:
461 case MachineOperand::MO_ConstantPoolIndex
:
462 case MachineOperand::MO_GlobalAddress
:
463 case MachineOperand::MO_ExternalSymbol
: {
465 printSymbolOperand(MO
);
471 void X86ATTAsmPrinter::printSSECC(const MachineInstr
*MI
, unsigned Op
) {
472 unsigned char value
= MI
->getOperand(Op
).getImm();
473 assert(value
<= 7 && "Invalid ssecc argument!");
475 case 0: O
<< "eq"; break;
476 case 1: O
<< "lt"; break;
477 case 2: O
<< "le"; break;
478 case 3: O
<< "unord"; break;
479 case 4: O
<< "neq"; break;
480 case 5: O
<< "nlt"; break;
481 case 6: O
<< "nle"; break;
482 case 7: O
<< "ord"; break;
486 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr
*MI
, unsigned Op
,
487 const char *Modifier
) {
488 const MachineOperand
&BaseReg
= MI
->getOperand(Op
);
489 const MachineOperand
&IndexReg
= MI
->getOperand(Op
+2);
490 const MachineOperand
&DispSpec
= MI
->getOperand(Op
+3);
492 // If we really don't want to print out (rip), don't.
493 bool HasBaseReg
= BaseReg
.getReg() != 0;
494 if (HasBaseReg
&& Modifier
&& !strcmp(Modifier
, "no-rip") &&
495 BaseReg
.getReg() == X86::RIP
)
498 // HasParenPart - True if we will print out the () part of the mem ref.
499 bool HasParenPart
= IndexReg
.getReg() || HasBaseReg
;
501 if (DispSpec
.isImm()) {
502 int DispVal
= DispSpec
.getImm();
503 if (DispVal
|| !HasParenPart
)
506 assert(DispSpec
.isGlobal() || DispSpec
.isCPI() ||
507 DispSpec
.isJTI() || DispSpec
.isSymbol());
508 printSymbolOperand(MI
->getOperand(Op
+3));
512 assert(IndexReg
.getReg() != X86::ESP
&&
513 "X86 doesn't allow scaling by ESP");
517 printOperand(MI
, Op
, Modifier
);
519 if (IndexReg
.getReg()) {
521 printOperand(MI
, Op
+2, Modifier
);
522 unsigned ScaleVal
= MI
->getOperand(Op
+1).getImm();
524 O
<< ',' << ScaleVal
;
530 void X86ATTAsmPrinter::printMemReference(const MachineInstr
*MI
, unsigned Op
,
531 const char *Modifier
) {
532 assert(isMem(MI
, Op
) && "Invalid memory reference!");
533 const MachineOperand
&Segment
= MI
->getOperand(Op
+4);
534 if (Segment
.getReg()) {
535 printOperand(MI
, Op
+4, Modifier
);
538 printLeaMemReference(MI
, Op
, Modifier
);
541 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid
,
542 const MachineBasicBlock
*MBB
) const {
543 if (!MAI
->getSetDirective())
546 // We don't need .set machinery if we have GOT-style relocations
547 if (Subtarget
->isPICStyleGOT())
550 O
<< MAI
->getSetDirective() << ' ' << MAI
->getPrivateGlobalPrefix()
551 << getFunctionNumber() << '_' << uid
<< "_set_" << MBB
->getNumber() << ',';
553 GetMBBSymbol(MBB
->getNumber())->print(O
, MAI
);
555 if (Subtarget
->isPICStyleRIPRel())
556 O
<< '-' << MAI
->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
557 << '_' << uid
<< '\n';
560 PrintPICBaseSymbol();
566 void X86ATTAsmPrinter::printPICLabel(const MachineInstr
*MI
, unsigned Op
) {
567 PrintPICBaseSymbol();
569 PrintPICBaseSymbol();
573 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo
*MJTI
,
574 const MachineBasicBlock
*MBB
,
575 unsigned uid
) const {
576 const char *JTEntryDirective
= MJTI
->getEntrySize() == 4 ?
577 MAI
->getData32bitsDirective() : MAI
->getData64bitsDirective();
579 O
<< JTEntryDirective
<< ' ';
581 if (Subtarget
->isPICStyleRIPRel() || Subtarget
->isPICStyleStubPIC()) {
582 O
<< MAI
->getPrivateGlobalPrefix() << getFunctionNumber()
583 << '_' << uid
<< "_set_" << MBB
->getNumber();
584 } else if (Subtarget
->isPICStyleGOT()) {
585 GetMBBSymbol(MBB
->getNumber())->print(O
, MAI
);
588 GetMBBSymbol(MBB
->getNumber())->print(O
, MAI
);
591 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand
&MO
, char Mode
) {
592 unsigned Reg
= MO
.getReg();
594 default: return true; // Unknown mode.
595 case 'b': // Print QImode register
596 Reg
= getX86SubSuperRegister(Reg
, MVT::i8
);
598 case 'h': // Print QImode high register
599 Reg
= getX86SubSuperRegister(Reg
, MVT::i8
, true);
601 case 'w': // Print HImode register
602 Reg
= getX86SubSuperRegister(Reg
, MVT::i16
);
604 case 'k': // Print SImode register
605 Reg
= getX86SubSuperRegister(Reg
, MVT::i32
);
607 case 'q': // Print DImode register
608 Reg
= getX86SubSuperRegister(Reg
, MVT::i64
);
612 O
<< '%' << X86ATTInstPrinter::getRegisterName(Reg
);
616 /// PrintAsmOperand - Print out an operand for an inline asm expression.
618 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr
*MI
, unsigned OpNo
,
620 const char *ExtraCode
) {
621 // Does this asm operand have a single letter operand modifier?
622 if (ExtraCode
&& ExtraCode
[0]) {
623 if (ExtraCode
[1] != 0) return true; // Unknown modifier.
625 const MachineOperand
&MO
= MI
->getOperand(OpNo
);
627 switch (ExtraCode
[0]) {
628 default: return true; // Unknown modifier.
629 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
634 if (MO
.isGlobal() || MO
.isCPI() || MO
.isJTI() || MO
.isSymbol()) {
635 printSymbolOperand(MO
);
640 printOperand(MI
, OpNo
);
646 case 'c': // Don't print "$" before a global var name or constant.
649 else if (MO
.isGlobal() || MO
.isCPI() || MO
.isJTI() || MO
.isSymbol())
650 printSymbolOperand(MO
);
652 printOperand(MI
, OpNo
);
655 case 'A': // Print '*' before a register (it must be a register)
658 printOperand(MI
, OpNo
);
663 case 'b': // Print QImode register
664 case 'h': // Print QImode high register
665 case 'w': // Print HImode register
666 case 'k': // Print SImode register
667 case 'q': // Print DImode register
669 return printAsmMRegister(MO
, ExtraCode
[0]);
670 printOperand(MI
, OpNo
);
673 case 'P': // This is the operand of a call, treat specially.
674 print_pcrel_imm(MI
, OpNo
);
677 case 'n': // Negate the immediate or print a '-' before the operand.
678 // Note: this is a temporary solution. It should be handled target
679 // independently as part of the 'MC' work.
688 printOperand(MI
, OpNo
);
692 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr
*MI
,
695 const char *ExtraCode
) {
696 if (ExtraCode
&& ExtraCode
[0]) {
697 if (ExtraCode
[1] != 0) return true; // Unknown modifier.
699 switch (ExtraCode
[0]) {
700 default: return true; // Unknown modifier.
701 case 'b': // Print QImode register
702 case 'h': // Print QImode high register
703 case 'w': // Print HImode register
704 case 'k': // Print SImode register
705 case 'q': // Print SImode register
706 // These only apply to registers, ignore on mem.
708 case 'P': // Don't print @PLT, but do print as memory.
709 printMemReference(MI
, OpNo
, "no-rip");
713 printMemReference(MI
, OpNo
);
719 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
720 /// AT&T syntax to the current output stream.
722 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr
*MI
) {
725 processDebugLoc(MI
->getDebugLoc());
727 printInstructionThroughMCStreamer(MI
);
729 if (VerboseAsm
&& !MI
->getDebugLoc().isUnknown())
734 void X86ATTAsmPrinter::PrintGlobalVariable(const GlobalVariable
* GVar
) {
735 const TargetData
*TD
= TM
.getTargetData();
737 if (!GVar
->hasInitializer())
738 return; // External global require no code
740 // Check to see if this is a special global used by LLVM, if so, emit it.
741 if (EmitSpecialLLVMGlobal(GVar
)) {
742 if (Subtarget
->isTargetDarwin() &&
743 TM
.getRelocationModel() == Reloc::Static
) {
744 if (GVar
->getName() == "llvm.global_ctors")
745 O
<< ".reference .constructors_used\n";
746 else if (GVar
->getName() == "llvm.global_dtors")
747 O
<< ".reference .destructors_used\n";
752 std::string name
= Mang
->getMangledName(GVar
);
753 Constant
*C
= GVar
->getInitializer();
754 const Type
*Type
= C
->getType();
755 unsigned Size
= TD
->getTypeAllocSize(Type
);
756 unsigned Align
= TD
->getPreferredAlignmentLog(GVar
);
758 printVisibility(name
, GVar
->getVisibility());
760 if (Subtarget
->isTargetELF())
761 O
<< "\t.type\t" << name
<< ",@object\n";
764 SectionKind GVKind
= TargetLoweringObjectFile::getKindForGlobal(GVar
, TM
);
765 const MCSection
*TheSection
=
766 getObjFileLowering().SectionForGlobal(GVar
, GVKind
, Mang
, TM
);
767 OutStreamer
.SwitchSection(TheSection
);
769 // FIXME: get this stuff from section kind flags.
770 if (C
->isNullValue() && !GVar
->hasSection() &&
771 // Don't put things that should go in the cstring section into "comm".
772 !TheSection
->getKind().isMergeableCString()) {
773 if (GVar
->hasExternalLinkage()) {
774 if (const char *Directive
= MAI
->getZeroFillDirective()) {
775 O
<< "\t.globl " << name
<< '\n';
776 O
<< Directive
<< "__DATA, __common, " << name
<< ", "
777 << Size
<< ", " << Align
<< '\n';
782 if (!GVar
->isThreadLocal() &&
783 (GVar
->hasLocalLinkage() || GVar
->isWeakForLinker())) {
784 if (Size
== 0) Size
= 1; // .comm Foo, 0 is undefined, avoid it.
786 if (MAI
->getLCOMMDirective() != NULL
) {
787 if (GVar
->hasLocalLinkage()) {
788 O
<< MAI
->getLCOMMDirective() << name
<< ',' << Size
;
789 if (Subtarget
->isTargetDarwin())
791 } else if (Subtarget
->isTargetDarwin() && !GVar
->hasCommonLinkage()) {
792 O
<< "\t.globl " << name
<< '\n'
793 << MAI
->getWeakDefDirective() << name
<< '\n';
794 EmitAlignment(Align
, GVar
);
797 O
.PadToColumn(MAI
->getCommentColumn());
798 O
<< MAI
->getCommentString() << ' ';
799 WriteAsOperand(O
, GVar
, /*PrintType=*/false, GVar
->getParent());
802 EmitGlobalConstant(C
);
805 O
<< MAI
->getCOMMDirective() << name
<< ',' << Size
;
806 if (MAI
->getCOMMDirectiveTakesAlignment())
807 O
<< ',' << (MAI
->getAlignmentIsInBytes() ? (1 << Align
) : Align
);
810 if (!Subtarget
->isTargetCygMing()) {
811 if (GVar
->hasLocalLinkage())
812 O
<< "\t.local\t" << name
<< '\n';
814 O
<< MAI
->getCOMMDirective() << name
<< ',' << Size
;
815 if (MAI
->getCOMMDirectiveTakesAlignment())
816 O
<< ',' << (MAI
->getAlignmentIsInBytes() ? (1 << Align
) : Align
);
819 O
.PadToColumn(MAI
->getCommentColumn());
820 O
<< MAI
->getCommentString() << ' ';
821 WriteAsOperand(O
, GVar
, /*PrintType=*/false, GVar
->getParent());
828 switch (GVar
->getLinkage()) {
829 case GlobalValue::CommonLinkage
:
830 case GlobalValue::LinkOnceAnyLinkage
:
831 case GlobalValue::LinkOnceODRLinkage
:
832 case GlobalValue::WeakAnyLinkage
:
833 case GlobalValue::WeakODRLinkage
:
834 case GlobalValue::LinkerPrivateLinkage
:
835 if (Subtarget
->isTargetDarwin()) {
836 O
<< "\t.globl " << name
<< '\n'
837 << MAI
->getWeakDefDirective() << name
<< '\n';
838 } else if (Subtarget
->isTargetCygMing()) {
839 O
<< "\t.globl\t" << name
<< "\n"
840 "\t.linkonce same_size\n";
842 O
<< "\t.weak\t" << name
<< '\n';
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';
853 case GlobalValue::PrivateLinkage
:
854 case GlobalValue::InternalLinkage
:
857 llvm_unreachable("Unknown linkage type!");
860 EmitAlignment(Align
, GVar
);
863 O
.PadToColumn(MAI
->getCommentColumn());
864 O
<< MAI
->getCommentString() << ' ';
865 WriteAsOperand(O
, GVar
, /*PrintType=*/false, GVar
->getParent());
869 EmitGlobalConstant(C
);
871 if (MAI
->hasDotTypeDotSizeDirective())
872 O
<< "\t.size\t" << name
<< ", " << Size
<< '\n';
875 static int SortSymbolPair(const void *LHS
, const void *RHS
) {
876 MCSymbol
*LHSS
= ((const std::pair
<MCSymbol
*, MCSymbol
*>*)LHS
)->first
;
877 MCSymbol
*RHSS
= ((const std::pair
<MCSymbol
*, MCSymbol
*>*)RHS
)->first
;
878 return LHSS
->getName().compare(RHSS
->getName());
881 /// GetSortedStubs - Return the entries from a DenseMap in a deterministic
883 static std::vector
<std::pair
<MCSymbol
*, MCSymbol
*> >
884 GetSortedStubs(const DenseMap
<MCSymbol
*, MCSymbol
*> &Map
) {
885 assert(!Map
.empty());
886 std::vector
<std::pair
<MCSymbol
*, MCSymbol
*> > List(Map
.begin(), Map
.end());
887 qsort(&List
[0], List
.size(), sizeof(List
[0]), SortSymbolPair
);
891 bool X86ATTAsmPrinter::doFinalization(Module
&M
) {
892 // Print out module-level global variables here.
893 for (Module::const_global_iterator I
= M
.global_begin(), E
= M
.global_end();
895 if (I
->hasDLLExportLinkage())
896 DLLExportedGVs
.insert(Mang
->getMangledName(I
));
899 if (Subtarget
->isTargetDarwin()) {
900 // All darwin targets use mach-o.
901 TargetLoweringObjectFileMachO
&TLOFMacho
=
902 static_cast<TargetLoweringObjectFileMachO
&>(getObjFileLowering());
904 // Add the (possibly multiple) personalities to the set of global value
905 // stubs. Only referenced functions get into the Personalities list.
906 if (MAI
->doesSupportExceptionHandling() && MMI
&& !Subtarget
->is64Bit()) {
907 const std::vector
<Function
*> &Personalities
= MMI
->getPersonalities();
908 for (unsigned i
= 0, e
= Personalities
.size(); i
!= e
; ++i
) {
909 if (Personalities
[i
] == 0)
912 SmallString
<128> Name
;
913 Mang
->getNameWithPrefix(Name
, Personalities
[i
], true /*private label*/);
914 Name
+= "$non_lazy_ptr";
915 MCSymbol
*NLPName
= OutContext
.GetOrCreateSymbol(Name
.str());
917 MCSymbol
*&StubName
= GVStubs
[NLPName
];
918 if (StubName
!= 0) continue;
922 Mang
->getNameWithPrefix(Name
, Personalities
[i
], false);
923 StubName
= OutContext
.GetOrCreateSymbol(Name
.str());
927 // Output stubs for dynamically-linked functions
928 if (!FnStubs
.empty()) {
929 const MCSection
*TheSection
=
930 TLOFMacho
.getMachOSection("__IMPORT", "__jump_table",
931 MCSectionMachO::S_SYMBOL_STUBS
|
932 MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE
|
933 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS
,
934 5, SectionKind::getMetadata());
935 OutStreamer
.SwitchSection(TheSection
);
937 std::vector
<std::pair
<MCSymbol
*, MCSymbol
*> > Stubs
938 = GetSortedStubs(FnStubs
);
939 for (unsigned i
= 0, e
= Stubs
.size(); i
!= e
; ++i
) {
940 Stubs
[i
].first
->print(O
, MAI
);
941 O
<< ":\n" << "\t.indirect_symbol ";
942 // Get the MCSymbol without the $stub suffix.
943 Stubs
[i
].second
->print(O
, MAI
);
944 O
<< "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
949 // Output stubs for external and common global variables.
950 if (!GVStubs
.empty()) {
951 const MCSection
*TheSection
=
952 TLOFMacho
.getMachOSection("__IMPORT", "__pointers",
953 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS
,
954 SectionKind::getMetadata());
955 OutStreamer
.SwitchSection(TheSection
);
957 std::vector
<std::pair
<MCSymbol
*, MCSymbol
*> > Stubs
958 = GetSortedStubs(GVStubs
);
959 for (unsigned i
= 0, e
= Stubs
.size(); i
!= e
; ++i
) {
960 Stubs
[i
].first
->print(O
, MAI
);
961 O
<< ":\n\t.indirect_symbol ";
962 Stubs
[i
].second
->print(O
, MAI
);
963 O
<< "\n\t.long\t0\n";
967 if (!HiddenGVStubs
.empty()) {
968 OutStreamer
.SwitchSection(getObjFileLowering().getDataSection());
971 std::vector
<std::pair
<MCSymbol
*, MCSymbol
*> > Stubs
972 = GetSortedStubs(HiddenGVStubs
);
973 for (unsigned i
= 0, e
= Stubs
.size(); i
!= e
; ++i
) {
974 Stubs
[i
].first
->print(O
, MAI
);
975 O
<< ":\n" << MAI
->getData32bitsDirective();
976 Stubs
[i
].second
->print(O
, MAI
);
981 // Funny Darwin hack: This flag tells the linker that no global symbols
982 // contain code that falls through to other global symbols (e.g. the obvious
983 // implementation of multiple entry points). If this doesn't occur, the
984 // linker can safely perform dead code stripping. Since LLVM never
985 // generates code that does this, it is always safe to set.
986 O
<< "\t.subsections_via_symbols\n";
987 } else if (Subtarget
->isTargetCygMing()) {
988 // Emit type information for external functions
989 for (StringSet
<>::iterator i
= CygMingStubs
.begin(), e
= CygMingStubs
.end();
991 O
<< "\t.def\t " << i
->getKeyData()
992 << ";\t.scl\t" << COFF::C_EXT
993 << ";\t.type\t" << (COFF::DT_FCN
<< COFF::N_BTSHFT
)
999 // Output linker support code for dllexported globals on windows.
1000 if (!DLLExportedGVs
.empty() || !DLLExportedFns
.empty()) {
1001 // dllexport symbols only exist on coff targets.
1002 TargetLoweringObjectFileCOFF
&TLOFMacho
=
1003 static_cast<TargetLoweringObjectFileCOFF
&>(getObjFileLowering());
1005 OutStreamer
.SwitchSection(TLOFMacho
.getCOFFSection(".section .drectve",true,
1006 SectionKind::getMetadata()));
1008 for (StringSet
<>::iterator i
= DLLExportedGVs
.begin(),
1009 e
= DLLExportedGVs
.end(); i
!= e
; ++i
)
1010 O
<< "\t.ascii \" -export:" << i
->getKeyData() << ",data\"\n";
1012 for (StringSet
<>::iterator i
= DLLExportedFns
.begin(),
1013 e
= DLLExportedFns
.end();
1015 O
<< "\t.ascii \" -export:" << i
->getKeyData() << "\"\n";
1018 // Do common shutdown.
1019 return AsmPrinter::doFinalization(M
);