Added the LAR (load segment access rights)
[llvm/avr.git] / lib / Target / X86 / AsmPrinter / X86ATTAsmPrinter.cpp
blob6365bc0f9573429d517baf912c136c825678bf30
1 //===-- X86ATTAsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly -----===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to AT&T format assembly
12 // language. This printer is the output mechanism used by `llc'.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "asm-printer"
17 #include "X86ATTAsmPrinter.h"
18 #include "X86ATTInstPrinter.h"
19 #include "X86MCInstLower.h"
20 #include "X86.h"
21 #include "X86COFF.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/CodeGen/MachineModuleInfoImpls.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/FormattedStream.h"
37 #include "llvm/Support/Mangler.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/Target/TargetLoweringObjectFile.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/ADT/SmallString.h"
42 #include "llvm/ADT/Statistic.h"
43 using namespace llvm;
45 STATISTIC(EmittedInsts, "Number of machine instrs printed");
47 //===----------------------------------------------------------------------===//
48 // Primitive Helper Functions.
49 //===----------------------------------------------------------------------===//
51 void X86ATTAsmPrinter::printMCInst(const MCInst *MI) {
52 X86ATTInstPrinter(O, *MAI).printInstruction(MI);
55 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
56 // FIXME: Gross const cast hack.
57 X86ATTAsmPrinter *AP = const_cast<X86ATTAsmPrinter*>(this);
58 X86MCInstLower(OutContext, 0, *AP).GetPICBaseSymbol()->print(O, MAI);
61 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
62 const TargetData *TD) {
63 X86MachineFunctionInfo Info;
64 uint64_t Size = 0;
66 switch (F->getCallingConv()) {
67 case CallingConv::X86_StdCall:
68 Info.setDecorationStyle(StdCall);
69 break;
70 case CallingConv::X86_FastCall:
71 Info.setDecorationStyle(FastCall);
72 break;
73 default:
74 return Info;
77 unsigned argNum = 1;
78 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
79 AI != AE; ++AI, ++argNum) {
80 const Type* Ty = AI->getType();
82 // 'Dereference' type in case of byval parameter attribute
83 if (F->paramHasAttr(argNum, Attribute::ByVal))
84 Ty = cast<PointerType>(Ty)->getElementType();
86 // Size should be aligned to DWORD boundary
87 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
90 // We're not supporting tooooo huge arguments :)
91 Info.setBytesToPopOnReturn((unsigned int)Size);
92 return Info;
95 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
96 /// various name decorations for Cygwin and MingW.
97 void X86ATTAsmPrinter::DecorateCygMingName(SmallVectorImpl<char> &Name,
98 const GlobalValue *GV) {
99 assert(Subtarget->isTargetCygMing() && "This is only for cygwin and mingw");
101 const Function *F = dyn_cast<Function>(GV);
102 if (!F) return;
104 // Save function name for later type emission.
105 if (F->isDeclaration())
106 CygMingStubs.insert(StringRef(Name.data(), Name.size()));
108 // We don't want to decorate non-stdcall or non-fastcall functions right now
109 CallingConv::ID CC = F->getCallingConv();
110 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
111 return;
114 const X86MachineFunctionInfo *Info;
116 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
117 if (info_item == FunctionInfoMap.end()) {
118 // Calculate apropriate function info and populate map
119 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
120 Info = &FunctionInfoMap[F];
121 } else {
122 Info = &info_item->second;
125 if (Info->getDecorationStyle() == None) return;
126 const FunctionType *FT = F->getFunctionType();
128 // "Pure" variadic functions do not receive @0 suffix.
129 if (!FT->isVarArg() || FT->getNumParams() == 0 ||
130 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
131 raw_svector_ostream(Name) << '@' << Info->getBytesToPopOnReturn();
133 if (Info->getDecorationStyle() == FastCall) {
134 if (Name[0] == '_')
135 Name[0] = '@';
136 else
137 Name.insert(Name.begin(), '@');
141 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
142 /// various name decorations for Cygwin and MingW.
143 void X86ATTAsmPrinter::DecorateCygMingName(std::string &Name,
144 const GlobalValue *GV) {
145 SmallString<128> NameStr(Name.begin(), Name.end());
146 DecorateCygMingName(NameStr, GV);
147 Name.assign(NameStr.begin(), NameStr.end());
150 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
151 unsigned FnAlign = MF.getAlignment();
152 const Function *F = MF.getFunction();
154 if (Subtarget->isTargetCygMing())
155 DecorateCygMingName(CurrentFnName, F);
157 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
158 EmitAlignment(FnAlign, F);
160 switch (F->getLinkage()) {
161 default: llvm_unreachable("Unknown linkage type!");
162 case Function::InternalLinkage: // Symbols default to internal.
163 case Function::PrivateLinkage:
164 break;
165 case Function::DLLExportLinkage:
166 case Function::ExternalLinkage:
167 O << "\t.globl\t" << CurrentFnName << '\n';
168 break;
169 case Function::LinkerPrivateLinkage:
170 case Function::LinkOnceAnyLinkage:
171 case Function::LinkOnceODRLinkage:
172 case Function::WeakAnyLinkage:
173 case Function::WeakODRLinkage:
174 if (Subtarget->isTargetDarwin()) {
175 O << "\t.globl\t" << CurrentFnName << '\n';
176 O << MAI->getWeakDefDirective() << CurrentFnName << '\n';
177 } else if (Subtarget->isTargetCygMing()) {
178 O << "\t.globl\t" << CurrentFnName << "\n"
179 "\t.linkonce discard\n";
180 } else {
181 O << "\t.weak\t" << CurrentFnName << '\n';
183 break;
186 printVisibility(CurrentFnName, F->getVisibility());
188 if (Subtarget->isTargetELF())
189 O << "\t.type\t" << CurrentFnName << ",@function\n";
190 else if (Subtarget->isTargetCygMing()) {
191 O << "\t.def\t " << CurrentFnName
192 << ";\t.scl\t" <<
193 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
194 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
195 << ";\t.endef\n";
198 O << CurrentFnName << ':';
199 if (VerboseAsm) {
200 O.PadToColumn(MAI->getCommentColumn());
201 O << MAI->getCommentString() << ' ';
202 WriteAsOperand(O, F, /*PrintType=*/false, F->getParent());
204 O << '\n';
206 // Add some workaround for linkonce linkage on Cygwin\MinGW
207 if (Subtarget->isTargetCygMing() &&
208 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
209 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
212 /// runOnMachineFunction - This uses the printMachineInstruction()
213 /// method to print assembly for each instruction.
215 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
216 const Function *F = MF.getFunction();
217 this->MF = &MF;
218 CallingConv::ID CC = F->getCallingConv();
220 SetupMachineFunction(MF);
221 O << "\n\n";
223 // Populate function information map. Actually, We don't want to populate
224 // non-stdcall or non-fastcall functions' information right now.
225 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
226 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
228 // Print out constants referenced by the function
229 EmitConstantPool(MF.getConstantPool());
231 if (F->hasDLLExportLinkage())
232 DLLExportedFns.insert(Mang->getMangledName(F));
234 // Print the 'header' of function
235 emitFunctionHeader(MF);
237 // Emit pre-function debug and/or EH information.
238 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
239 DW->BeginFunction(&MF);
241 // Print out code for the function.
242 bool hasAnyRealCode = false;
243 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
244 I != E; ++I) {
245 // Print a label for the basic block.
246 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
247 // This is an entry block or a block that's only reachable via a
248 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
249 } else {
250 EmitBasicBlockStart(I);
251 O << '\n';
253 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
254 II != IE; ++II) {
255 // Print the assembly for the instruction.
256 if (!II->isLabel())
257 hasAnyRealCode = true;
258 printMachineInstruction(II);
262 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
263 // If the function is empty, then we need to emit *something*. Otherwise,
264 // the function's label might be associated with something that it wasn't
265 // meant to be associated with. We emit a noop in this situation.
266 // We are assuming inline asms are code.
267 O << "\tnop\n";
270 if (MAI->hasDotTypeDotSizeDirective())
271 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
273 // Emit post-function debug information.
274 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
275 DW->EndFunction(&MF);
277 // Print out jump tables referenced by the function.
278 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
280 // We didn't modify anything.
281 return false;
284 /// printSymbolOperand - Print a raw symbol reference operand. This handles
285 /// jump tables, constant pools, global address and external symbols, all of
286 /// which print to a label with various suffixes for relocation types etc.
287 void X86ATTAsmPrinter::printSymbolOperand(const MachineOperand &MO) {
288 switch (MO.getType()) {
289 default: llvm_unreachable("unknown symbol type!");
290 case MachineOperand::MO_JumpTableIndex:
291 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
292 << MO.getIndex();
293 break;
294 case MachineOperand::MO_ConstantPoolIndex:
295 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
296 << MO.getIndex();
297 printOffset(MO.getOffset());
298 break;
299 case MachineOperand::MO_GlobalAddress: {
300 const GlobalValue *GV = MO.getGlobal();
302 const char *Suffix = "";
303 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
304 Suffix = "$stub";
305 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
306 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
307 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
308 Suffix = "$non_lazy_ptr";
310 std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
311 if (Subtarget->isTargetCygMing())
312 DecorateCygMingName(Name, GV);
314 // Handle dllimport linkage.
315 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
316 Name = "__imp_" + Name;
318 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
319 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
320 SmallString<128> NameStr;
321 Mang->getNameWithPrefix(NameStr, GV, true);
322 NameStr += "$non_lazy_ptr";
323 MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
325 const MCSymbol *&StubSym =
326 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(Sym);
327 if (StubSym == 0) {
328 NameStr.clear();
329 Mang->getNameWithPrefix(NameStr, GV, false);
330 StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
332 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
333 SmallString<128> NameStr;
334 Mang->getNameWithPrefix(NameStr, GV, true);
335 NameStr += "$non_lazy_ptr";
336 MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
337 const MCSymbol *&StubSym =
338 MMI->getObjFileInfo<MachineModuleInfoMachO>().getHiddenGVStubEntry(Sym);
339 if (StubSym == 0) {
340 NameStr.clear();
341 Mang->getNameWithPrefix(NameStr, GV, false);
342 StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
344 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
345 SmallString<128> NameStr;
346 Mang->getNameWithPrefix(NameStr, GV, true);
347 NameStr += "$stub";
348 MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
349 const MCSymbol *&StubSym =
350 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
351 if (StubSym == 0) {
352 NameStr.clear();
353 Mang->getNameWithPrefix(NameStr, GV, false);
354 StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
358 // If the name begins with a dollar-sign, enclose it in parens. We do this
359 // to avoid having it look like an integer immediate to the assembler.
360 if (Name[0] == '$')
361 O << '(' << Name << ')';
362 else
363 O << Name;
365 printOffset(MO.getOffset());
366 break;
368 case MachineOperand::MO_ExternalSymbol: {
369 std::string Name = Mang->makeNameProper(MO.getSymbolName());
370 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
371 Name += "$stub";
372 MCSymbol *Sym = OutContext.GetOrCreateSymbol(Name);
373 const MCSymbol *&StubSym =
374 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
375 if (StubSym == 0) {
376 Name.erase(Name.end()-5, Name.end());
377 StubSym = OutContext.GetOrCreateSymbol(Name);
381 // If the name begins with a dollar-sign, enclose it in parens. We do this
382 // to avoid having it look like an integer immediate to the assembler.
383 if (Name[0] == '$')
384 O << '(' << Name << ')';
385 else
386 O << Name;
387 break;
391 switch (MO.getTargetFlags()) {
392 default:
393 llvm_unreachable("Unknown target flag on GV operand");
394 case X86II::MO_NO_FLAG: // No flag.
395 break;
396 case X86II::MO_DARWIN_NONLAZY:
397 case X86II::MO_DLLIMPORT:
398 case X86II::MO_DARWIN_STUB:
399 // These affect the name of the symbol, not any suffix.
400 break;
401 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
402 O << " + [.-";
403 PrintPICBaseSymbol();
404 O << ']';
405 break;
406 case X86II::MO_PIC_BASE_OFFSET:
407 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
408 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
409 O << '-';
410 PrintPICBaseSymbol();
411 break;
412 case X86II::MO_TLSGD: O << "@TLSGD"; break;
413 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
414 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
415 case X86II::MO_TPOFF: O << "@TPOFF"; break;
416 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
417 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
418 case X86II::MO_GOT: O << "@GOT"; break;
419 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
420 case X86II::MO_PLT: O << "@PLT"; break;
424 /// print_pcrel_imm - This is used to print an immediate value that ends up
425 /// being encoded as a pc-relative value. These print slightly differently, for
426 /// example, a $ is not emitted.
427 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
428 const MachineOperand &MO = MI->getOperand(OpNo);
429 switch (MO.getType()) {
430 default: llvm_unreachable("Unknown pcrel immediate operand");
431 case MachineOperand::MO_Immediate:
432 O << MO.getImm();
433 return;
434 case MachineOperand::MO_MachineBasicBlock:
435 GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
436 return;
437 case MachineOperand::MO_GlobalAddress:
438 case MachineOperand::MO_ExternalSymbol:
439 printSymbolOperand(MO);
440 return;
445 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
446 const char *Modifier) {
447 const MachineOperand &MO = MI->getOperand(OpNo);
448 switch (MO.getType()) {
449 default: llvm_unreachable("unknown operand type!");
450 case MachineOperand::MO_Register: {
451 O << '%';
452 unsigned Reg = MO.getReg();
453 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
454 EVT VT = (strcmp(Modifier+6,"64") == 0) ?
455 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
456 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
457 Reg = getX86SubSuperRegister(Reg, VT);
459 O << X86ATTInstPrinter::getRegisterName(Reg);
460 return;
463 case MachineOperand::MO_Immediate:
464 O << '$' << MO.getImm();
465 return;
467 case MachineOperand::MO_JumpTableIndex:
468 case MachineOperand::MO_ConstantPoolIndex:
469 case MachineOperand::MO_GlobalAddress:
470 case MachineOperand::MO_ExternalSymbol: {
471 O << '$';
472 printSymbolOperand(MO);
473 break;
478 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
479 unsigned char value = MI->getOperand(Op).getImm();
480 assert(value <= 7 && "Invalid ssecc argument!");
481 switch (value) {
482 case 0: O << "eq"; break;
483 case 1: O << "lt"; break;
484 case 2: O << "le"; break;
485 case 3: O << "unord"; break;
486 case 4: O << "neq"; break;
487 case 5: O << "nlt"; break;
488 case 6: O << "nle"; break;
489 case 7: O << "ord"; break;
493 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
494 const char *Modifier) {
495 const MachineOperand &BaseReg = MI->getOperand(Op);
496 const MachineOperand &IndexReg = MI->getOperand(Op+2);
497 const MachineOperand &DispSpec = MI->getOperand(Op+3);
499 // If we really don't want to print out (rip), don't.
500 bool HasBaseReg = BaseReg.getReg() != 0;
501 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
502 BaseReg.getReg() == X86::RIP)
503 HasBaseReg = false;
505 // HasParenPart - True if we will print out the () part of the mem ref.
506 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
508 if (DispSpec.isImm()) {
509 int DispVal = DispSpec.getImm();
510 if (DispVal || !HasParenPart)
511 O << DispVal;
512 } else {
513 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
514 DispSpec.isJTI() || DispSpec.isSymbol());
515 printSymbolOperand(MI->getOperand(Op+3));
518 if (HasParenPart) {
519 assert(IndexReg.getReg() != X86::ESP &&
520 "X86 doesn't allow scaling by ESP");
522 O << '(';
523 if (HasBaseReg)
524 printOperand(MI, Op, Modifier);
526 if (IndexReg.getReg()) {
527 O << ',';
528 printOperand(MI, Op+2, Modifier);
529 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
530 if (ScaleVal != 1)
531 O << ',' << ScaleVal;
533 O << ')';
537 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
538 const char *Modifier) {
539 assert(isMem(MI, Op) && "Invalid memory reference!");
540 const MachineOperand &Segment = MI->getOperand(Op+4);
541 if (Segment.getReg()) {
542 printOperand(MI, Op+4, Modifier);
543 O << ':';
545 printLeaMemReference(MI, Op, Modifier);
548 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
549 const MachineBasicBlock *MBB) const {
550 if (!MAI->getSetDirective())
551 return;
553 // We don't need .set machinery if we have GOT-style relocations
554 if (Subtarget->isPICStyleGOT())
555 return;
557 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
558 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
560 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
562 if (Subtarget->isPICStyleRIPRel())
563 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
564 << '_' << uid << '\n';
565 else {
566 O << '-';
567 PrintPICBaseSymbol();
568 O << '\n';
573 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
574 PrintPICBaseSymbol();
575 O << '\n';
576 PrintPICBaseSymbol();
577 O << ':';
580 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
581 const MachineBasicBlock *MBB,
582 unsigned uid) const {
583 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
584 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
586 O << JTEntryDirective << ' ';
588 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
589 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
590 << '_' << uid << "_set_" << MBB->getNumber();
591 } else if (Subtarget->isPICStyleGOT()) {
592 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
593 O << "@GOTOFF";
594 } else
595 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
598 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
599 unsigned Reg = MO.getReg();
600 switch (Mode) {
601 default: return true; // Unknown mode.
602 case 'b': // Print QImode register
603 Reg = getX86SubSuperRegister(Reg, MVT::i8);
604 break;
605 case 'h': // Print QImode high register
606 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
607 break;
608 case 'w': // Print HImode register
609 Reg = getX86SubSuperRegister(Reg, MVT::i16);
610 break;
611 case 'k': // Print SImode register
612 Reg = getX86SubSuperRegister(Reg, MVT::i32);
613 break;
614 case 'q': // Print DImode register
615 Reg = getX86SubSuperRegister(Reg, MVT::i64);
616 break;
619 O << '%' << X86ATTInstPrinter::getRegisterName(Reg);
620 return false;
623 /// PrintAsmOperand - Print out an operand for an inline asm expression.
625 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
626 unsigned AsmVariant,
627 const char *ExtraCode) {
628 // Does this asm operand have a single letter operand modifier?
629 if (ExtraCode && ExtraCode[0]) {
630 if (ExtraCode[1] != 0) return true; // Unknown modifier.
632 const MachineOperand &MO = MI->getOperand(OpNo);
634 switch (ExtraCode[0]) {
635 default: return true; // Unknown modifier.
636 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
637 if (MO.isImm()) {
638 O << MO.getImm();
639 return false;
641 if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
642 printSymbolOperand(MO);
643 return false;
645 if (MO.isReg()) {
646 O << '(';
647 printOperand(MI, OpNo);
648 O << ')';
649 return false;
651 return true;
653 case 'c': // Don't print "$" before a global var name or constant.
654 if (MO.isImm())
655 O << MO.getImm();
656 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
657 printSymbolOperand(MO);
658 else
659 printOperand(MI, OpNo);
660 return false;
662 case 'A': // Print '*' before a register (it must be a register)
663 if (MO.isReg()) {
664 O << '*';
665 printOperand(MI, OpNo);
666 return false;
668 return true;
670 case 'b': // Print QImode register
671 case 'h': // Print QImode high register
672 case 'w': // Print HImode register
673 case 'k': // Print SImode register
674 case 'q': // Print DImode register
675 if (MO.isReg())
676 return printAsmMRegister(MO, ExtraCode[0]);
677 printOperand(MI, OpNo);
678 return false;
680 case 'P': // This is the operand of a call, treat specially.
681 print_pcrel_imm(MI, OpNo);
682 return false;
684 case 'n': // Negate the immediate or print a '-' before the operand.
685 // Note: this is a temporary solution. It should be handled target
686 // independently as part of the 'MC' work.
687 if (MO.isImm()) {
688 O << -MO.getImm();
689 return false;
691 O << '-';
695 printOperand(MI, OpNo);
696 return false;
699 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
700 unsigned OpNo,
701 unsigned AsmVariant,
702 const char *ExtraCode) {
703 if (ExtraCode && ExtraCode[0]) {
704 if (ExtraCode[1] != 0) return true; // Unknown modifier.
706 switch (ExtraCode[0]) {
707 default: return true; // Unknown modifier.
708 case 'b': // Print QImode register
709 case 'h': // Print QImode high register
710 case 'w': // Print HImode register
711 case 'k': // Print SImode register
712 case 'q': // Print SImode register
713 // These only apply to registers, ignore on mem.
714 break;
715 case 'P': // Don't print @PLT, but do print as memory.
716 printMemReference(MI, OpNo, "no-rip");
717 return false;
720 printMemReference(MI, OpNo);
721 return false;
726 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
727 /// AT&T syntax to the current output stream.
729 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
730 ++EmittedInsts;
732 processDebugLoc(MI->getDebugLoc());
734 printInstructionThroughMCStreamer(MI);
736 if (VerboseAsm && !MI->getDebugLoc().isUnknown())
737 EmitComments(*MI);
738 O << '\n';
741 void X86ATTAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
742 if (!GVar->hasInitializer())
743 return; // External global require no code
745 // Check to see if this is a special global used by LLVM, if so, emit it.
746 if (EmitSpecialLLVMGlobal(GVar)) {
747 if (Subtarget->isTargetDarwin() &&
748 TM.getRelocationModel() == Reloc::Static) {
749 if (GVar->getName() == "llvm.global_ctors")
750 O << ".reference .constructors_used\n";
751 else if (GVar->getName() == "llvm.global_dtors")
752 O << ".reference .destructors_used\n";
754 return;
757 const TargetData *TD = TM.getTargetData();
759 std::string name = Mang->getMangledName(GVar);
760 Constant *C = GVar->getInitializer();
761 const Type *Type = C->getType();
762 unsigned Size = TD->getTypeAllocSize(Type);
763 unsigned Align = TD->getPreferredAlignmentLog(GVar);
765 printVisibility(name, GVar->getVisibility());
767 if (Subtarget->isTargetELF())
768 O << "\t.type\t" << name << ",@object\n";
771 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
772 const MCSection *TheSection =
773 getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
774 OutStreamer.SwitchSection(TheSection);
776 // FIXME: get this stuff from section kind flags.
777 if (C->isNullValue() && !GVar->hasSection() &&
778 // Don't put things that should go in the cstring section into "comm".
779 !TheSection->getKind().isMergeableCString()) {
780 if (GVar->hasExternalLinkage()) {
781 if (const char *Directive = MAI->getZeroFillDirective()) {
782 O << "\t.globl " << name << '\n';
783 O << Directive << "__DATA, __common, " << name << ", "
784 << Size << ", " << Align << '\n';
785 return;
789 if (!GVar->isThreadLocal() &&
790 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
791 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
793 if (MAI->getLCOMMDirective() != NULL) {
794 if (GVar->hasLocalLinkage()) {
795 O << MAI->getLCOMMDirective() << name << ',' << Size;
796 if (Subtarget->isTargetDarwin())
797 O << ',' << Align;
798 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
799 O << "\t.globl " << name << '\n'
800 << MAI->getWeakDefDirective() << name << '\n';
801 EmitAlignment(Align, GVar);
802 O << name << ":";
803 if (VerboseAsm) {
804 O.PadToColumn(MAI->getCommentColumn());
805 O << MAI->getCommentString() << ' ';
806 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
808 O << '\n';
809 EmitGlobalConstant(C);
810 return;
811 } else {
812 O << MAI->getCOMMDirective() << name << ',' << Size;
813 if (MAI->getCOMMDirectiveTakesAlignment())
814 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
816 } else {
817 if (!Subtarget->isTargetCygMing()) {
818 if (GVar->hasLocalLinkage())
819 O << "\t.local\t" << name << '\n';
821 O << MAI->getCOMMDirective() << name << ',' << Size;
822 if (MAI->getCOMMDirectiveTakesAlignment())
823 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
825 if (VerboseAsm) {
826 O.PadToColumn(MAI->getCommentColumn());
827 O << MAI->getCommentString() << ' ';
828 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
830 O << '\n';
831 return;
835 switch (GVar->getLinkage()) {
836 case GlobalValue::CommonLinkage:
837 case GlobalValue::LinkOnceAnyLinkage:
838 case GlobalValue::LinkOnceODRLinkage:
839 case GlobalValue::WeakAnyLinkage:
840 case GlobalValue::WeakODRLinkage:
841 case GlobalValue::LinkerPrivateLinkage:
842 if (Subtarget->isTargetDarwin()) {
843 O << "\t.globl " << name << '\n'
844 << MAI->getWeakDefDirective() << name << '\n';
845 } else if (Subtarget->isTargetCygMing()) {
846 O << "\t.globl\t" << name << "\n"
847 "\t.linkonce same_size\n";
848 } else {
849 O << "\t.weak\t" << name << '\n';
851 break;
852 case GlobalValue::DLLExportLinkage:
853 case GlobalValue::AppendingLinkage:
854 // FIXME: appending linkage variables should go into a section of
855 // their name or something. For now, just emit them as external.
856 case GlobalValue::ExternalLinkage:
857 // If external or appending, declare as a global symbol
858 O << "\t.globl " << name << '\n';
859 // FALL THROUGH
860 case GlobalValue::PrivateLinkage:
861 case GlobalValue::InternalLinkage:
862 break;
863 default:
864 llvm_unreachable("Unknown linkage type!");
867 EmitAlignment(Align, GVar);
868 O << name << ":";
869 if (VerboseAsm){
870 O.PadToColumn(MAI->getCommentColumn());
871 O << MAI->getCommentString() << ' ';
872 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
874 O << '\n';
876 EmitGlobalConstant(C);
878 if (MAI->hasDotTypeDotSizeDirective())
879 O << "\t.size\t" << name << ", " << Size << '\n';
882 bool X86ATTAsmPrinter::doFinalization(Module &M) {
883 if (Subtarget->isTargetDarwin()) {
884 // All darwin targets use mach-o.
885 TargetLoweringObjectFileMachO &TLOFMacho =
886 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
888 MachineModuleInfoMachO &MMIMacho =
889 MMI->getObjFileInfo<MachineModuleInfoMachO>();
891 // Add the (possibly multiple) personalities to the set of global value
892 // stubs. Only referenced functions get into the Personalities list.
893 if (!Subtarget->is64Bit()) {
894 const std::vector<Function*> &Personalities = MMI->getPersonalities();
895 for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
896 if (Personalities[i] == 0)
897 continue;
899 SmallString<128> Name;
900 Mang->getNameWithPrefix(Name, Personalities[i], true /*private label*/);
901 Name += "$non_lazy_ptr";
902 MCSymbol *NLPName = OutContext.GetOrCreateSymbol(Name.str());
904 const MCSymbol *&StubName = MMIMacho.getGVStubEntry(NLPName);
905 Name.clear();
906 Mang->getNameWithPrefix(Name, Personalities[i], false);
907 StubName = OutContext.GetOrCreateSymbol(Name.str());
911 // Output stubs for dynamically-linked functions.
912 MachineModuleInfoMachO::SymbolListTy Stubs;
914 Stubs = MMIMacho.GetFnStubList();
915 if (!Stubs.empty()) {
916 const MCSection *TheSection =
917 TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
918 MCSectionMachO::S_SYMBOL_STUBS |
919 MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
920 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
921 5, SectionKind::getMetadata());
922 OutStreamer.SwitchSection(TheSection);
924 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
925 Stubs[i].first->print(O, MAI);
926 O << ":\n" << "\t.indirect_symbol ";
927 // Get the MCSymbol without the $stub suffix.
928 Stubs[i].second->print(O, MAI);
929 O << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
931 O << '\n';
933 Stubs.clear();
936 // Output stubs for external and common global variables.
937 Stubs = MMIMacho.GetGVStubList();
938 if (!Stubs.empty()) {
939 const MCSection *TheSection =
940 TLOFMacho.getMachOSection("__IMPORT", "__pointers",
941 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
942 SectionKind::getMetadata());
943 OutStreamer.SwitchSection(TheSection);
945 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
946 Stubs[i].first->print(O, MAI);
947 O << ":\n\t.indirect_symbol ";
948 Stubs[i].second->print(O, MAI);
949 O << "\n\t.long\t0\n";
951 Stubs.clear();
954 Stubs = MMIMacho.GetHiddenGVStubList();
955 if (!Stubs.empty()) {
956 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
957 EmitAlignment(2);
959 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
960 Stubs[i].first->print(O, MAI);
961 O << ":\n" << MAI->getData32bitsDirective();
962 Stubs[i].second->print(O, MAI);
963 O << '\n';
965 Stubs.clear();
968 // Funny Darwin hack: This flag tells the linker that no global symbols
969 // contain code that falls through to other global symbols (e.g. the obvious
970 // implementation of multiple entry points). If this doesn't occur, the
971 // linker can safely perform dead code stripping. Since LLVM never
972 // generates code that does this, it is always safe to set.
973 O << "\t.subsections_via_symbols\n";
976 if (Subtarget->isTargetCOFF()) {
977 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
978 I != E; ++I)
979 if (I->hasDLLExportLinkage())
980 DLLExportedGVs.insert(Mang->getMangledName(I));
982 if (Subtarget->isTargetCygMing()) {
983 // Emit type information for external functions
984 for (StringSet<>::iterator i = CygMingStubs.begin(), e = CygMingStubs.end();
985 i != e; ++i) {
986 O << "\t.def\t " << i->getKeyData()
987 << ";\t.scl\t" << COFF::C_EXT
988 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
989 << ";\t.endef\n";
993 // Output linker support code for dllexported globals on windows.
994 if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
995 // dllexport symbols only exist on coff targets.
996 TargetLoweringObjectFileCOFF &TLOFCOFF =
997 static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
999 OutStreamer.SwitchSection(TLOFCOFF.getCOFFSection(".section .drectve",
1000 true,
1001 SectionKind::getMetadata()));
1003 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
1004 e = DLLExportedGVs.end(); i != e; ++i)
1005 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1007 for (StringSet<>::iterator i = DLLExportedFns.begin(),
1008 e = DLLExportedFns.end();
1009 i != e; ++i)
1010 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1014 // Do common shutdown.
1015 return AsmPrinter::doFinalization(M);