blob: 6058698ca0c213526c414c8b9a7200fcbcb8bc41 [file] [log] [blame]
Chris Lattner0dc32ea2009-09-20 07:41:30 +00001//===-- X86AsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly --------===//
Misha Brukman0e0a7a452005-04-21 23:38:14 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman0e0a7a452005-04-21 23:38:14 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner72614082002-10-25 22:55:53 +00009//
Chris Lattner0dc32ea2009-09-20 07:41:30 +000010// 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'.
Chris Lattner72614082002-10-25 22:55:53 +000013//
14//===----------------------------------------------------------------------===//
15
Chris Lattner0dc32ea2009-09-20 07:41:30 +000016#define DEBUG_TYPE "asm-printer"
17#include "X86AsmPrinter.h"
18#include "X86ATTInstPrinter.h"
19#include "X86IntelInstPrinter.h"
20#include "X86MCInstLower.h"
21#include "X86.h"
22#include "X86COFF.h"
23#include "X86COFFMachineModuleInfo.h"
24#include "X86MachineFunctionInfo.h"
25#include "X86TargetMachine.h"
26#include "llvm/CallingConv.h"
27#include "llvm/DerivedTypes.h"
28#include "llvm/Module.h"
29#include "llvm/Type.h"
30#include "llvm/Assembly/Writer.h"
31#include "llvm/MC/MCContext.h"
32#include "llvm/MC/MCSectionMachO.h"
33#include "llvm/MC/MCStreamer.h"
34#include "llvm/MC/MCSymbol.h"
35#include "llvm/CodeGen/MachineJumpTableInfo.h"
36#include "llvm/CodeGen/MachineModuleInfoImpls.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/FormattedStream.h"
39#include "llvm/Support/Mangler.h"
40#include "llvm/MC/MCAsmInfo.h"
41#include "llvm/Target/TargetLoweringObjectFile.h"
42#include "llvm/Target/TargetOptions.h"
43#include "llvm/Target/TargetRegistry.h"
44#include "llvm/ADT/SmallString.h"
45#include "llvm/ADT/Statistic.h"
46using namespace llvm;
47
48STATISTIC(EmittedInsts, "Number of machine instrs printed");
49
50//===----------------------------------------------------------------------===//
51// Primitive Helper Functions.
52//===----------------------------------------------------------------------===//
53
54void X86AsmPrinter::printMCInst(const MCInst *MI) {
55 if (MAI->getAssemblerDialect() == 0)
56 X86ATTInstPrinter(O, *MAI).printInstruction(MI);
57 else
58 X86IntelInstPrinter(O, *MAI).printInstruction(MI);
59}
60
61void X86AsmPrinter::PrintPICBaseSymbol() const {
62 // FIXME: Gross const cast hack.
63 X86AsmPrinter *AP = const_cast<X86AsmPrinter*>(this);
64 X86MCInstLower(OutContext, 0, *AP).GetPICBaseSymbol()->print(O, MAI);
65}
66
67void X86AsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
68 unsigned FnAlign = MF.getAlignment();
69 const Function *F = MF.getFunction();
70
71 if (Subtarget->isTargetCygMing()) {
72 X86COFFMachineModuleInfo &COFFMMI =
73 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
74 COFFMMI.DecorateCygMingName(CurrentFnName, F, *TM.getTargetData());
75 }
76
77 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
78 EmitAlignment(FnAlign, F);
79
80 switch (F->getLinkage()) {
81 default: llvm_unreachable("Unknown linkage type!");
82 case Function::InternalLinkage: // Symbols default to internal.
83 case Function::PrivateLinkage:
84 break;
85 case Function::DLLExportLinkage:
86 case Function::ExternalLinkage:
87 O << "\t.globl\t" << CurrentFnName << '\n';
88 break;
89 case Function::LinkerPrivateLinkage:
90 case Function::LinkOnceAnyLinkage:
91 case Function::LinkOnceODRLinkage:
92 case Function::WeakAnyLinkage:
93 case Function::WeakODRLinkage:
94 if (Subtarget->isTargetDarwin()) {
95 O << "\t.globl\t" << CurrentFnName << '\n';
96 O << MAI->getWeakDefDirective() << CurrentFnName << '\n';
97 } else if (Subtarget->isTargetCygMing()) {
98 O << "\t.globl\t" << CurrentFnName << "\n"
99 "\t.linkonce discard\n";
100 } else {
101 O << "\t.weak\t" << CurrentFnName << '\n';
102 }
103 break;
104 }
105
106 printVisibility(CurrentFnName, F->getVisibility());
107
108 if (Subtarget->isTargetELF())
109 O << "\t.type\t" << CurrentFnName << ",@function\n";
110 else if (Subtarget->isTargetCygMing()) {
111 O << "\t.def\t " << CurrentFnName
112 << ";\t.scl\t" <<
113 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
114 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
115 << ";\t.endef\n";
116 }
117
118 O << CurrentFnName << ':';
119 if (VerboseAsm) {
120 O.PadToColumn(MAI->getCommentColumn());
121 O << MAI->getCommentString() << ' ';
122 WriteAsOperand(O, F, /*PrintType=*/false, F->getParent());
123 }
124 O << '\n';
125
126 // Add some workaround for linkonce linkage on Cygwin\MinGW
127 if (Subtarget->isTargetCygMing() &&
128 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
129 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
130}
131
132/// runOnMachineFunction - This uses the printMachineInstruction()
133/// method to print assembly for each instruction.
134///
135bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
136 const Function *F = MF.getFunction();
137 this->MF = &MF;
138 CallingConv::ID CC = F->getCallingConv();
139
140 SetupMachineFunction(MF);
141 O << "\n\n";
142
143 if (Subtarget->isTargetCOFF()) {
144 X86COFFMachineModuleInfo &COFFMMI =
145 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
146
147 // Populate function information map. Don't want to populate
148 // non-stdcall or non-fastcall functions' information right now.
149 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
150 COFFMMI.AddFunctionInfo(F, *MF.getInfo<X86MachineFunctionInfo>());
151 }
152
153 // Print out constants referenced by the function
154 EmitConstantPool(MF.getConstantPool());
155
156 // Print the 'header' of function
157 emitFunctionHeader(MF);
158
159 // Emit pre-function debug and/or EH information.
160 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
161 DW->BeginFunction(&MF);
162
163 // Print out code for the function.
164 bool hasAnyRealCode = false;
165 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
166 I != E; ++I) {
167 // Print a label for the basic block.
Dan Gohmane3cc3f32009-10-06 17:38:38 +0000168 EmitBasicBlockStart(I);
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000169 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
170 II != IE; ++II) {
171 // Print the assembly for the instruction.
172 if (!II->isLabel())
173 hasAnyRealCode = true;
174 printMachineInstruction(II);
175 }
176 }
177
178 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
179 // If the function is empty, then we need to emit *something*. Otherwise,
180 // the function's label might be associated with something that it wasn't
181 // meant to be associated with. We emit a noop in this situation.
182 // We are assuming inline asms are code.
183 O << "\tnop\n";
184 }
185
186 if (MAI->hasDotTypeDotSizeDirective())
187 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
188
189 // Emit post-function debug information.
190 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
191 DW->EndFunction(&MF);
192
193 // Print out jump tables referenced by the function.
194 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
195
196 // We didn't modify anything.
197 return false;
198}
199
200/// printSymbolOperand - Print a raw symbol reference operand. This handles
201/// jump tables, constant pools, global address and external symbols, all of
202/// which print to a label with various suffixes for relocation types etc.
203void X86AsmPrinter::printSymbolOperand(const MachineOperand &MO) {
Chris Lattner48130352010-01-13 06:38:18 +0000204 SmallString<128> TempNameStr;
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000205 switch (MO.getType()) {
206 default: llvm_unreachable("unknown symbol type!");
207 case MachineOperand::MO_JumpTableIndex:
208 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
209 << MO.getIndex();
210 break;
211 case MachineOperand::MO_ConstantPoolIndex:
212 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
213 << MO.getIndex();
214 printOffset(MO.getOffset());
215 break;
216 case MachineOperand::MO_GlobalAddress: {
217 const GlobalValue *GV = MO.getGlobal();
218
219 const char *Suffix = "";
220 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
221 Suffix = "$stub";
222 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
223 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
224 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
225 Suffix = "$non_lazy_ptr";
226
227 std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
228 if (Subtarget->isTargetCygMing()) {
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000229 X86COFFMachineModuleInfo &COFFMMI =
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000230 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
231 COFFMMI.DecorateCygMingName(Name, GV, *TM.getTargetData());
232 }
233
234 // Handle dllimport linkage.
235 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
236 Name = "__imp_" + Name;
237
238 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
239 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
Chris Lattner48130352010-01-13 06:38:18 +0000240 Mang->getNameWithPrefix(TempNameStr, GV, true);
241 TempNameStr += "$non_lazy_ptr";
242 MCSymbol *Sym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000243
244 const MCSymbol *&StubSym =
245 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(Sym);
246 if (StubSym == 0) {
Chris Lattner48130352010-01-13 06:38:18 +0000247 TempNameStr.clear();
248 Mang->getNameWithPrefix(TempNameStr, GV, false);
249 StubSym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000250 }
251 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
Chris Lattner48130352010-01-13 06:38:18 +0000252 Mang->getNameWithPrefix(TempNameStr, GV, true);
253 TempNameStr += "$non_lazy_ptr";
254 MCSymbol *Sym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000255 const MCSymbol *&StubSym =
256 MMI->getObjFileInfo<MachineModuleInfoMachO>().getHiddenGVStubEntry(Sym);
257 if (StubSym == 0) {
Chris Lattner48130352010-01-13 06:38:18 +0000258 TempNameStr.clear();
259 Mang->getNameWithPrefix(TempNameStr, GV, false);
260 StubSym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000261 }
262 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
Chris Lattner48130352010-01-13 06:38:18 +0000263 Mang->getNameWithPrefix(TempNameStr, GV, true);
264 TempNameStr += "$stub";
265 MCSymbol *Sym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000266 const MCSymbol *&StubSym =
267 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
268 if (StubSym == 0) {
Chris Lattner48130352010-01-13 06:38:18 +0000269 TempNameStr.clear();
270 Mang->getNameWithPrefix(TempNameStr, GV, false);
271 StubSym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000272 }
273 }
274
275 // If the name begins with a dollar-sign, enclose it in parens. We do this
276 // to avoid having it look like an integer immediate to the assembler.
277 if (Name[0] == '$')
278 O << '(' << Name << ')';
279 else
280 O << Name;
281
282 printOffset(MO.getOffset());
283 break;
284 }
285 case MachineOperand::MO_ExternalSymbol: {
Chris Lattner48130352010-01-13 06:38:18 +0000286 Mang->makeNameProper(TempNameStr, MO.getSymbolName());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000287 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
Chris Lattner48130352010-01-13 06:38:18 +0000288 TempNameStr += "$stub";
289 MCSymbol *Sym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000290 const MCSymbol *&StubSym =
291 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
292 if (StubSym == 0) {
Chris Lattner48130352010-01-13 06:38:18 +0000293 TempNameStr.erase(TempNameStr.end()-5, TempNameStr.end());
294 StubSym = OutContext.GetOrCreateSymbol(TempNameStr.str());
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000295 }
296 }
297
298 // If the name begins with a dollar-sign, enclose it in parens. We do this
299 // to avoid having it look like an integer immediate to the assembler.
Chris Lattner48130352010-01-13 06:38:18 +0000300 if (TempNameStr[0] == '$')
301 O << '(' << TempNameStr << ')';
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000302 else
Chris Lattner48130352010-01-13 06:38:18 +0000303 O << TempNameStr;
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000304 break;
305 }
306 }
307
308 switch (MO.getTargetFlags()) {
309 default:
310 llvm_unreachable("Unknown target flag on GV operand");
311 case X86II::MO_NO_FLAG: // No flag.
312 break;
313 case X86II::MO_DARWIN_NONLAZY:
314 case X86II::MO_DLLIMPORT:
315 case X86II::MO_DARWIN_STUB:
316 // These affect the name of the symbol, not any suffix.
317 break;
318 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
319 O << " + [.-";
320 PrintPICBaseSymbol();
321 O << ']';
322 break;
323 case X86II::MO_PIC_BASE_OFFSET:
324 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
325 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
326 O << '-';
327 PrintPICBaseSymbol();
328 break;
329 case X86II::MO_TLSGD: O << "@TLSGD"; break;
330 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
331 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
332 case X86II::MO_TPOFF: O << "@TPOFF"; break;
333 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
334 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
335 case X86II::MO_GOT: O << "@GOT"; break;
336 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
337 case X86II::MO_PLT: O << "@PLT"; break;
338 }
339}
340
341/// print_pcrel_imm - This is used to print an immediate value that ends up
342/// being encoded as a pc-relative value. These print slightly differently, for
343/// example, a $ is not emitted.
344void X86AsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
345 const MachineOperand &MO = MI->getOperand(OpNo);
346 switch (MO.getType()) {
347 default: llvm_unreachable("Unknown pcrel immediate operand");
348 case MachineOperand::MO_Immediate:
349 O << MO.getImm();
350 return;
351 case MachineOperand::MO_MachineBasicBlock:
352 GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
353 return;
354 case MachineOperand::MO_GlobalAddress:
355 case MachineOperand::MO_ExternalSymbol:
356 printSymbolOperand(MO);
357 return;
358 }
359}
360
361
362void X86AsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
363 const char *Modifier) {
364 const MachineOperand &MO = MI->getOperand(OpNo);
365 switch (MO.getType()) {
366 default: llvm_unreachable("unknown operand type!");
367 case MachineOperand::MO_Register: {
368 O << '%';
369 unsigned Reg = MO.getReg();
370 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
371 EVT VT = (strcmp(Modifier+6,"64") == 0) ?
372 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
373 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
374 Reg = getX86SubSuperRegister(Reg, VT);
375 }
376 O << X86ATTInstPrinter::getRegisterName(Reg);
377 return;
378 }
379
380 case MachineOperand::MO_Immediate:
381 O << '$' << MO.getImm();
382 return;
383
384 case MachineOperand::MO_JumpTableIndex:
385 case MachineOperand::MO_ConstantPoolIndex:
386 case MachineOperand::MO_GlobalAddress:
387 case MachineOperand::MO_ExternalSymbol: {
388 O << '$';
389 printSymbolOperand(MO);
390 break;
391 }
392 }
393}
394
395void X86AsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
396 unsigned char value = MI->getOperand(Op).getImm();
397 assert(value <= 7 && "Invalid ssecc argument!");
398 switch (value) {
399 case 0: O << "eq"; break;
400 case 1: O << "lt"; break;
401 case 2: O << "le"; break;
402 case 3: O << "unord"; break;
403 case 4: O << "neq"; break;
404 case 5: O << "nlt"; break;
405 case 6: O << "nle"; break;
406 case 7: O << "ord"; break;
407 }
408}
409
410void X86AsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
411 const char *Modifier) {
412 const MachineOperand &BaseReg = MI->getOperand(Op);
413 const MachineOperand &IndexReg = MI->getOperand(Op+2);
414 const MachineOperand &DispSpec = MI->getOperand(Op+3);
415
416 // If we really don't want to print out (rip), don't.
417 bool HasBaseReg = BaseReg.getReg() != 0;
418 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
419 BaseReg.getReg() == X86::RIP)
420 HasBaseReg = false;
421
422 // HasParenPart - True if we will print out the () part of the mem ref.
423 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
424
425 if (DispSpec.isImm()) {
426 int DispVal = DispSpec.getImm();
427 if (DispVal || !HasParenPart)
428 O << DispVal;
429 } else {
430 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
431 DispSpec.isJTI() || DispSpec.isSymbol());
432 printSymbolOperand(MI->getOperand(Op+3));
433 }
434
435 if (HasParenPart) {
436 assert(IndexReg.getReg() != X86::ESP &&
437 "X86 doesn't allow scaling by ESP");
438
439 O << '(';
440 if (HasBaseReg)
441 printOperand(MI, Op, Modifier);
442
443 if (IndexReg.getReg()) {
444 O << ',';
445 printOperand(MI, Op+2, Modifier);
446 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
447 if (ScaleVal != 1)
448 O << ',' << ScaleVal;
449 }
450 O << ')';
451 }
452}
453
454void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
455 const char *Modifier) {
456 assert(isMem(MI, Op) && "Invalid memory reference!");
457 const MachineOperand &Segment = MI->getOperand(Op+4);
458 if (Segment.getReg()) {
459 printOperand(MI, Op+4, Modifier);
460 O << ':';
461 }
462 printLeaMemReference(MI, Op, Modifier);
463}
464
465void X86AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
466 const MachineBasicBlock *MBB) const {
467 if (!MAI->getSetDirective())
468 return;
469
470 // We don't need .set machinery if we have GOT-style relocations
471 if (Subtarget->isPICStyleGOT())
472 return;
473
474 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
475 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
476
477 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
478
479 if (Subtarget->isPICStyleRIPRel())
480 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
481 << '_' << uid << '\n';
482 else {
483 O << '-';
484 PrintPICBaseSymbol();
485 O << '\n';
486 }
487}
488
489
490void X86AsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
491 PrintPICBaseSymbol();
492 O << '\n';
493 PrintPICBaseSymbol();
494 O << ':';
495}
496
497void X86AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
498 const MachineBasicBlock *MBB,
499 unsigned uid) const {
500 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
501 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
502
503 O << JTEntryDirective << ' ';
504
505 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
506 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
507 << '_' << uid << "_set_" << MBB->getNumber();
508 } else if (Subtarget->isPICStyleGOT()) {
509 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
510 O << "@GOTOFF";
511 } else
512 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
513}
514
515bool X86AsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
516 unsigned Reg = MO.getReg();
517 switch (Mode) {
518 default: return true; // Unknown mode.
519 case 'b': // Print QImode register
520 Reg = getX86SubSuperRegister(Reg, MVT::i8);
521 break;
522 case 'h': // Print QImode high register
523 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
524 break;
525 case 'w': // Print HImode register
526 Reg = getX86SubSuperRegister(Reg, MVT::i16);
527 break;
528 case 'k': // Print SImode register
529 Reg = getX86SubSuperRegister(Reg, MVT::i32);
530 break;
531 case 'q': // Print DImode register
532 Reg = getX86SubSuperRegister(Reg, MVT::i64);
533 break;
534 }
535
536 O << '%' << X86ATTInstPrinter::getRegisterName(Reg);
537 return false;
538}
539
540/// PrintAsmOperand - Print out an operand for an inline asm expression.
541///
542bool X86AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
543 unsigned AsmVariant,
544 const char *ExtraCode) {
545 // Does this asm operand have a single letter operand modifier?
546 if (ExtraCode && ExtraCode[0]) {
547 if (ExtraCode[1] != 0) return true; // Unknown modifier.
548
549 const MachineOperand &MO = MI->getOperand(OpNo);
550
551 switch (ExtraCode[0]) {
552 default: return true; // Unknown modifier.
553 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
554 if (MO.isImm()) {
555 O << MO.getImm();
556 return false;
557 }
558 if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
559 printSymbolOperand(MO);
560 return false;
561 }
562 if (MO.isReg()) {
563 O << '(';
564 printOperand(MI, OpNo);
565 O << ')';
566 return false;
567 }
568 return true;
569
570 case 'c': // Don't print "$" before a global var name or constant.
571 if (MO.isImm())
572 O << MO.getImm();
573 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
574 printSymbolOperand(MO);
575 else
576 printOperand(MI, OpNo);
577 return false;
578
579 case 'A': // Print '*' before a register (it must be a register)
580 if (MO.isReg()) {
581 O << '*';
582 printOperand(MI, OpNo);
583 return false;
584 }
585 return true;
586
587 case 'b': // Print QImode register
588 case 'h': // Print QImode high register
589 case 'w': // Print HImode register
590 case 'k': // Print SImode register
591 case 'q': // Print DImode register
592 if (MO.isReg())
593 return printAsmMRegister(MO, ExtraCode[0]);
594 printOperand(MI, OpNo);
595 return false;
596
597 case 'P': // This is the operand of a call, treat specially.
598 print_pcrel_imm(MI, OpNo);
599 return false;
600
601 case 'n': // Negate the immediate or print a '-' before the operand.
602 // Note: this is a temporary solution. It should be handled target
603 // independently as part of the 'MC' work.
604 if (MO.isImm()) {
605 O << -MO.getImm();
606 return false;
607 }
608 O << '-';
609 }
610 }
611
612 printOperand(MI, OpNo);
613 return false;
614}
615
616bool X86AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
617 unsigned OpNo, unsigned AsmVariant,
618 const char *ExtraCode) {
619 if (ExtraCode && ExtraCode[0]) {
620 if (ExtraCode[1] != 0) return true; // Unknown modifier.
621
622 switch (ExtraCode[0]) {
623 default: return true; // Unknown modifier.
624 case 'b': // Print QImode register
625 case 'h': // Print QImode high register
626 case 'w': // Print HImode register
627 case 'k': // Print SImode register
628 case 'q': // Print SImode register
629 // These only apply to registers, ignore on mem.
630 break;
631 case 'P': // Don't print @PLT, but do print as memory.
632 printMemReference(MI, OpNo, "no-rip");
633 return false;
634 }
635 }
636 printMemReference(MI, OpNo);
637 return false;
638}
639
640
641
642/// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
643/// AT&T syntax to the current output stream.
644///
645void X86AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
646 ++EmittedInsts;
647
Devang Patelaf0e2722009-10-06 02:19:11 +0000648 processDebugLoc(MI, true);
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000649
650 printInstructionThroughMCStreamer(MI);
651
David Greene1924aab2009-11-13 21:34:57 +0000652 if (VerboseAsm)
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000653 EmitComments(*MI);
654 O << '\n';
Devang Patelaf0e2722009-10-06 02:19:11 +0000655
656 processDebugLoc(MI, false);
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000657}
658
659void X86AsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
660 if (!GVar->hasInitializer())
661 return; // External global require no code
662
663 // Check to see if this is a special global used by LLVM, if so, emit it.
664 if (EmitSpecialLLVMGlobal(GVar)) {
665 if (Subtarget->isTargetDarwin() &&
666 TM.getRelocationModel() == Reloc::Static) {
667 if (GVar->getName() == "llvm.global_ctors")
668 O << ".reference .constructors_used\n";
669 else if (GVar->getName() == "llvm.global_dtors")
670 O << ".reference .destructors_used\n";
671 }
672 return;
673 }
674
675 const TargetData *TD = TM.getTargetData();
676
677 std::string name = Mang->getMangledName(GVar);
678 Constant *C = GVar->getInitializer();
679 const Type *Type = C->getType();
680 unsigned Size = TD->getTypeAllocSize(Type);
681 unsigned Align = TD->getPreferredAlignmentLog(GVar);
682
683 printVisibility(name, GVar->getVisibility());
684
685 if (Subtarget->isTargetELF())
686 O << "\t.type\t" << name << ",@object\n";
687
688
689 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
690 const MCSection *TheSection =
691 getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
692 OutStreamer.SwitchSection(TheSection);
693
694 // FIXME: get this stuff from section kind flags.
695 if (C->isNullValue() && !GVar->hasSection() &&
696 // Don't put things that should go in the cstring section into "comm".
697 !TheSection->getKind().isMergeableCString()) {
698 if (GVar->hasExternalLinkage()) {
699 if (const char *Directive = MAI->getZeroFillDirective()) {
700 O << "\t.globl " << name << '\n';
701 O << Directive << "__DATA, __common, " << name << ", "
702 << Size << ", " << Align << '\n';
703 return;
704 }
705 }
706
707 if (!GVar->isThreadLocal() &&
708 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
709 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
710
711 if (MAI->getLCOMMDirective() != NULL) {
712 if (GVar->hasLocalLinkage()) {
713 O << MAI->getLCOMMDirective() << name << ',' << Size;
714 if (Subtarget->isTargetDarwin())
715 O << ',' << Align;
716 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
717 O << "\t.globl " << name << '\n'
718 << MAI->getWeakDefDirective() << name << '\n';
719 EmitAlignment(Align, GVar);
720 O << name << ":";
721 if (VerboseAsm) {
722 O.PadToColumn(MAI->getCommentColumn());
723 O << MAI->getCommentString() << ' ';
724 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
725 }
726 O << '\n';
727 EmitGlobalConstant(C);
728 return;
729 } else {
730 O << MAI->getCOMMDirective() << name << ',' << Size;
731 if (MAI->getCOMMDirectiveTakesAlignment())
732 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
733 }
734 } else {
735 if (!Subtarget->isTargetCygMing()) {
736 if (GVar->hasLocalLinkage())
737 O << "\t.local\t" << name << '\n';
738 }
739 O << MAI->getCOMMDirective() << name << ',' << Size;
740 if (MAI->getCOMMDirectiveTakesAlignment())
741 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
742 }
743 if (VerboseAsm) {
744 O.PadToColumn(MAI->getCommentColumn());
745 O << MAI->getCommentString() << ' ';
746 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
747 }
748 O << '\n';
749 return;
750 }
751 }
752
753 switch (GVar->getLinkage()) {
754 case GlobalValue::CommonLinkage:
755 case GlobalValue::LinkOnceAnyLinkage:
756 case GlobalValue::LinkOnceODRLinkage:
757 case GlobalValue::WeakAnyLinkage:
758 case GlobalValue::WeakODRLinkage:
759 case GlobalValue::LinkerPrivateLinkage:
760 if (Subtarget->isTargetDarwin()) {
761 O << "\t.globl " << name << '\n'
762 << MAI->getWeakDefDirective() << name << '\n';
763 } else if (Subtarget->isTargetCygMing()) {
764 O << "\t.globl\t" << name << "\n"
765 "\t.linkonce same_size\n";
766 } else {
767 O << "\t.weak\t" << name << '\n';
768 }
769 break;
770 case GlobalValue::DLLExportLinkage:
771 case GlobalValue::AppendingLinkage:
772 // FIXME: appending linkage variables should go into a section of
773 // their name or something. For now, just emit them as external.
774 case GlobalValue::ExternalLinkage:
775 // If external or appending, declare as a global symbol
776 O << "\t.globl " << name << '\n';
777 // FALL THROUGH
778 case GlobalValue::PrivateLinkage:
779 case GlobalValue::InternalLinkage:
780 break;
781 default:
782 llvm_unreachable("Unknown linkage type!");
783 }
784
785 EmitAlignment(Align, GVar);
786 O << name << ":";
787 if (VerboseAsm){
788 O.PadToColumn(MAI->getCommentColumn());
789 O << MAI->getCommentString() << ' ';
790 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
791 }
792 O << '\n';
793
794 EmitGlobalConstant(C);
795
796 if (MAI->hasDotTypeDotSizeDirective())
797 O << "\t.size\t" << name << ", " << Size << '\n';
798}
799
800void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
801 if (Subtarget->isTargetDarwin()) {
802 // All darwin targets use mach-o.
803 TargetLoweringObjectFileMachO &TLOFMacho =
804 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
805
806 MachineModuleInfoMachO &MMIMacho =
807 MMI->getObjFileInfo<MachineModuleInfoMachO>();
808
809 // Output stubs for dynamically-linked functions.
810 MachineModuleInfoMachO::SymbolListTy Stubs;
811
812 Stubs = MMIMacho.GetFnStubList();
813 if (!Stubs.empty()) {
814 const MCSection *TheSection =
815 TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
816 MCSectionMachO::S_SYMBOL_STUBS |
817 MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
818 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
819 5, SectionKind::getMetadata());
820 OutStreamer.SwitchSection(TheSection);
821
822 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
823 Stubs[i].first->print(O, MAI);
824 O << ":\n" << "\t.indirect_symbol ";
825 // Get the MCSymbol without the $stub suffix.
826 Stubs[i].second->print(O, MAI);
827 O << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
828 }
829 O << '\n';
830
831 Stubs.clear();
832 }
833
834 // Output stubs for external and common global variables.
835 Stubs = MMIMacho.GetGVStubList();
836 if (!Stubs.empty()) {
837 const MCSection *TheSection =
838 TLOFMacho.getMachOSection("__IMPORT", "__pointers",
839 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
840 SectionKind::getMetadata());
841 OutStreamer.SwitchSection(TheSection);
842
843 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
844 Stubs[i].first->print(O, MAI);
845 O << ":\n\t.indirect_symbol ";
846 Stubs[i].second->print(O, MAI);
847 O << "\n\t.long\t0\n";
848 }
849 Stubs.clear();
850 }
851
852 Stubs = MMIMacho.GetHiddenGVStubList();
853 if (!Stubs.empty()) {
854 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
855 EmitAlignment(2);
856
857 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
858 Stubs[i].first->print(O, MAI);
859 O << ":\n" << MAI->getData32bitsDirective();
860 Stubs[i].second->print(O, MAI);
861 O << '\n';
862 }
863 Stubs.clear();
864 }
865
866 // Funny Darwin hack: This flag tells the linker that no global symbols
867 // contain code that falls through to other global symbols (e.g. the obvious
868 // implementation of multiple entry points). If this doesn't occur, the
869 // linker can safely perform dead code stripping. Since LLVM never
870 // generates code that does this, it is always safe to set.
Chris Lattner74cd3b72009-10-19 18:03:08 +0000871 OutStreamer.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000872 }
873
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000874 if (Subtarget->isTargetCOFF()) {
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000875 X86COFFMachineModuleInfo &COFFMMI =
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000876 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000877
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000878 // Emit type information for external functions
879 for (X86COFFMachineModuleInfo::stub_iterator I = COFFMMI.stub_begin(),
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000880 E = COFFMMI.stub_end(); I != E; ++I) {
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000881 O << "\t.def\t " << I->getKeyData()
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000882 << ";\t.scl\t" << COFF::C_EXT
883 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
884 << ";\t.endef\n";
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000885 }
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000886
887 if (Subtarget->isTargetCygMing()) {
888 // Necessary for dllexport support
889 std::vector<std::string> DLLExportedFns, DLLExportedGlobals;
890
891 TargetLoweringObjectFileCOFF &TLOFCOFF =
892 static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
893
894 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
895 if (I->hasDLLExportLinkage()) {
896 std::string Name = Mang->getMangledName(I);
897 COFFMMI.DecorateCygMingName(Name, I, *TM.getTargetData());
898 DLLExportedFns.push_back(Name);
899 }
900
901 for (Module::const_global_iterator I = M.global_begin(),
902 E = M.global_end(); I != E; ++I)
903 if (I->hasDLLExportLinkage()) {
904 std::string Name = Mang->getMangledName(I);
905 COFFMMI.DecorateCygMingName(Name, I, *TM.getTargetData());
906 DLLExportedGlobals.push_back(Mang->getMangledName(I));
907 }
908
909 // Output linker support code for dllexported globals on windows.
910 if (!DLLExportedGlobals.empty() || !DLLExportedFns.empty()) {
911 OutStreamer.SwitchSection(TLOFCOFF.getCOFFSection(".section .drectve",
912 true,
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000913 SectionKind::getMetadata()));
Anton Korobeynikov4fac9472009-10-15 22:36:18 +0000914 for (unsigned i = 0, e = DLLExportedGlobals.size(); i != e; ++i)
915 O << "\t.ascii \" -export:" << DLLExportedGlobals[i] << ",data\"\n";
916
917 for (unsigned i = 0, e = DLLExportedFns.size(); i != e; ++i)
918 O << "\t.ascii \" -export:" << DLLExportedFns[i] << "\"\n";
919 }
Chris Lattner0dc32ea2009-09-20 07:41:30 +0000920 }
921 }
922}
923
924
925//===----------------------------------------------------------------------===//
926// Target Registry Stuff
927//===----------------------------------------------------------------------===//
928
929static MCInstPrinter *createX86MCInstPrinter(const Target &T,
930 unsigned SyntaxVariant,
931 const MCAsmInfo &MAI,
932 raw_ostream &O) {
933 if (SyntaxVariant == 0)
934 return new X86ATTInstPrinter(O, MAI);
935 if (SyntaxVariant == 1)
936 return new X86IntelInstPrinter(O, MAI);
937 return 0;
938}
939
940// Force static initialization.
941extern "C" void LLVMInitializeX86AsmPrinter() {
942 RegisterAsmPrinter<X86AsmPrinter> X(TheX86_32Target);
943 RegisterAsmPrinter<X86AsmPrinter> Y(TheX86_64Target);
944
945 TargetRegistry::RegisterMCInstPrinter(TheX86_32Target,createX86MCInstPrinter);
946 TargetRegistry::RegisterMCInstPrinter(TheX86_64Target,createX86MCInstPrinter);
947}