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