Merge branch 'master' into systemz
[llvm/systemz.git] / lib / Target / X86 / AsmPrinter / X86ATTAsmPrinter.cpp
blob2cec3736a38976b8914e3074d62dde5be514f2b4
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 "X86.h"
19 #include "X86COFF.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetAsmInfo.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Module.h"
26 #include "llvm/MDNode.h"
27 #include "llvm/Type.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/CodeGen/DwarfWriter.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/FormattedStream.h"
38 #include "llvm/Support/Mangler.h"
39 #include "llvm/Target/TargetAsmInfo.h"
40 #include "llvm/Target/TargetOptions.h"
41 using namespace llvm;
43 STATISTIC(EmittedInsts, "Number of machine instrs printed");
45 static cl::opt<bool> NewAsmPrinter("experimental-asm-printer",
46 cl::Hidden);
48 //===----------------------------------------------------------------------===//
49 // Primitive Helper Functions.
50 //===----------------------------------------------------------------------===//
52 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
53 if (Subtarget->isTargetDarwin())
54 O << "\"L" << getFunctionNumber() << "$pb\"";
55 else if (Subtarget->isTargetELF())
56 O << ".Lllvm$" << getFunctionNumber() << ".$piclabel";
57 else
58 llvm_unreachable("Don't know how to print PIC label!");
61 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
62 /// Don't print things like \\n or \\0.
63 static void PrintUnmangledNameSafely(const Value *V,
64 formatted_raw_ostream &OS) {
65 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
66 Name != E; ++Name)
67 if (isprint(*Name))
68 OS << *Name;
71 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
72 const TargetData *TD) {
73 X86MachineFunctionInfo Info;
74 uint64_t Size = 0;
76 switch (F->getCallingConv()) {
77 case CallingConv::X86_StdCall:
78 Info.setDecorationStyle(StdCall);
79 break;
80 case CallingConv::X86_FastCall:
81 Info.setDecorationStyle(FastCall);
82 break;
83 default:
84 return Info;
87 unsigned argNum = 1;
88 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
89 AI != AE; ++AI, ++argNum) {
90 const Type* Ty = AI->getType();
92 // 'Dereference' type in case of byval parameter attribute
93 if (F->paramHasAttr(argNum, Attribute::ByVal))
94 Ty = cast<PointerType>(Ty)->getElementType();
96 // Size should be aligned to DWORD boundary
97 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
100 // We're not supporting tooooo huge arguments :)
101 Info.setBytesToPopOnReturn((unsigned int)Size);
102 return Info;
105 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
106 /// various name decorations for Cygwin and MingW.
107 void X86ATTAsmPrinter::DecorateCygMingName(std::string &Name,
108 const GlobalValue *GV) {
109 assert(Subtarget->isTargetCygMing() && "This is only for cygwin and mingw");
111 const Function *F = dyn_cast<Function>(GV);
112 if (!F) return;
114 // Save function name for later type emission.
115 if (F->isDeclaration())
116 CygMingStubs.insert(Name);
118 // We don't want to decorate non-stdcall or non-fastcall functions right now
119 unsigned CC = F->getCallingConv();
120 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
121 return;
124 const X86MachineFunctionInfo *Info;
126 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
127 if (info_item == FunctionInfoMap.end()) {
128 // Calculate apropriate function info and populate map
129 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
130 Info = &FunctionInfoMap[F];
131 } else {
132 Info = &info_item->second;
135 const FunctionType *FT = F->getFunctionType();
136 switch (Info->getDecorationStyle()) {
137 case None:
138 break;
139 case StdCall:
140 // "Pure" variadic functions do not receive @0 suffix.
141 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
142 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
143 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
144 break;
145 case FastCall:
146 // "Pure" variadic functions do not receive @0 suffix.
147 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
148 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
149 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
151 if (Name[0] == '_') {
152 Name[0] = '@';
153 } else {
154 Name = '@' + Name;
156 break;
157 default:
158 llvm_unreachable("Unsupported DecorationStyle");
162 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
163 unsigned FnAlign = MF.getAlignment();
164 const Function *F = MF.getFunction();
166 if (Subtarget->isTargetCygMing())
167 DecorateCygMingName(CurrentFnName, F);
169 SwitchToSection(TAI->SectionForGlobal(F));
170 switch (F->getLinkage()) {
171 default: llvm_unreachable("Unknown linkage type!");
172 case Function::InternalLinkage: // Symbols default to internal.
173 case Function::PrivateLinkage:
174 EmitAlignment(FnAlign, F);
175 break;
176 case Function::DLLExportLinkage:
177 case Function::ExternalLinkage:
178 EmitAlignment(FnAlign, F);
179 O << "\t.globl\t" << CurrentFnName << '\n';
180 break;
181 case Function::LinkOnceAnyLinkage:
182 case Function::LinkOnceODRLinkage:
183 case Function::WeakAnyLinkage:
184 case Function::WeakODRLinkage:
185 EmitAlignment(FnAlign, F);
186 if (Subtarget->isTargetDarwin()) {
187 O << "\t.globl\t" << CurrentFnName << '\n';
188 O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
189 } else if (Subtarget->isTargetCygMing()) {
190 O << "\t.globl\t" << CurrentFnName << "\n"
191 "\t.linkonce discard\n";
192 } else {
193 O << "\t.weak\t" << CurrentFnName << '\n';
195 break;
198 printVisibility(CurrentFnName, F->getVisibility());
200 if (Subtarget->isTargetELF())
201 O << "\t.type\t" << CurrentFnName << ",@function\n";
202 else if (Subtarget->isTargetCygMing()) {
203 O << "\t.def\t " << CurrentFnName
204 << ";\t.scl\t" <<
205 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
206 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
207 << ";\t.endef\n";
210 O << CurrentFnName << ":\n";
211 // Add some workaround for linkonce linkage on Cygwin\MinGW
212 if (Subtarget->isTargetCygMing() &&
213 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
214 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
217 /// runOnMachineFunction - This uses the printMachineInstruction()
218 /// method to print assembly for each instruction.
220 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
221 const Function *F = MF.getFunction();
222 this->MF = &MF;
223 unsigned CC = F->getCallingConv();
225 SetupMachineFunction(MF);
226 O << "\n\n";
228 // Populate function information map. Actually, We don't want to populate
229 // non-stdcall or non-fastcall functions' information right now.
230 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
231 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
233 // Print out constants referenced by the function
234 EmitConstantPool(MF.getConstantPool());
236 if (F->hasDLLExportLinkage())
237 DLLExportedFns.insert(Mang->getMangledName(F));
239 // Print the 'header' of function
240 emitFunctionHeader(MF);
242 // Emit pre-function debug and/or EH information.
243 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
244 DW->BeginFunction(&MF);
246 // Print out code for the function.
247 bool hasAnyRealCode = false;
248 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
249 I != E; ++I) {
250 // Print a label for the basic block.
251 if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
252 // This is an entry block or a block that's only reachable via a
253 // fallthrough edge. In non-VerboseAsm mode, don't print the label.
254 } else {
255 printBasicBlockLabel(I, true, true, VerboseAsm);
256 O << '\n';
258 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
259 II != IE; ++II) {
260 // Print the assembly for the instruction.
261 if (!II->isLabel())
262 hasAnyRealCode = true;
263 printMachineInstruction(II);
267 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
268 // If the function is empty, then we need to emit *something*. Otherwise,
269 // the function's label might be associated with something that it wasn't
270 // meant to be associated with. We emit a noop in this situation.
271 // We are assuming inline asms are code.
272 O << "\tnop\n";
275 if (TAI->hasDotTypeDotSizeDirective())
276 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
278 // Emit post-function debug information.
279 if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
280 DW->EndFunction(&MF);
282 // Print out jump tables referenced by the function.
283 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
285 O.flush();
287 // We didn't modify anything.
288 return false;
291 /// printSymbolOperand - Print a raw symbol reference operand. This handles
292 /// jump tables, constant pools, global address and external symbols, all of
293 /// which print to a label with various suffixes for relocation types etc.
294 void X86ATTAsmPrinter::printSymbolOperand(const MachineOperand &MO) {
295 switch (MO.getType()) {
296 default: llvm_unreachable("unknown symbol type!");
297 case MachineOperand::MO_JumpTableIndex:
298 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
299 << MO.getIndex();
300 break;
301 case MachineOperand::MO_ConstantPoolIndex:
302 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
303 << MO.getIndex();
304 printOffset(MO.getOffset());
305 break;
306 case MachineOperand::MO_GlobalAddress: {
307 const GlobalValue *GV = MO.getGlobal();
309 const char *Suffix = "";
310 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
311 Suffix = "$stub";
312 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
313 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
314 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
315 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
316 Suffix = "$non_lazy_ptr";
318 std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
319 if (Subtarget->isTargetCygMing())
320 DecorateCygMingName(Name, GV);
322 // Handle dllimport linkage.
323 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
324 Name = "__imp_" + Name;
326 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
327 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE)
328 GVStubs[Name] = Mang->getMangledName(GV);
329 else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
330 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
331 HiddenGVStubs[Name] = Mang->getMangledName(GV);
332 else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
333 FnStubs[Name] = Mang->getMangledName(GV);
335 // If the name begins with a dollar-sign, enclose it in parens. We do this
336 // to avoid having it look like an integer immediate to the assembler.
337 if (Name[0] == '$')
338 O << '(' << Name << ')';
339 else
340 O << Name;
342 printOffset(MO.getOffset());
343 break;
345 case MachineOperand::MO_ExternalSymbol: {
346 std::string Name = Mang->makeNameProper(MO.getSymbolName());
347 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
348 FnStubs[Name+"$stub"] = Name;
349 Name += "$stub";
352 // If the name begins with a dollar-sign, enclose it in parens. We do this
353 // to avoid having it look like an integer immediate to the assembler.
354 if (Name[0] == '$')
355 O << '(' << Name << ')';
356 else
357 O << Name;
358 break;
362 switch (MO.getTargetFlags()) {
363 default:
364 llvm_unreachable("Unknown target flag on GV operand");
365 case X86II::MO_NO_FLAG: // No flag.
366 break;
367 case X86II::MO_DARWIN_NONLAZY:
368 case X86II::MO_DARWIN_HIDDEN_NONLAZY:
369 case X86II::MO_DLLIMPORT:
370 case X86II::MO_DARWIN_STUB:
371 // These affect the name of the symbol, not any suffix.
372 break;
373 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
374 O << " + [.-";
375 PrintPICBaseSymbol();
376 O << ']';
377 break;
378 case X86II::MO_PIC_BASE_OFFSET:
379 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
380 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
381 O << '-';
382 PrintPICBaseSymbol();
383 break;
384 case X86II::MO_TLSGD: O << "@TLSGD"; break;
385 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
386 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
387 case X86II::MO_TPOFF: O << "@TPOFF"; break;
388 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
389 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
390 case X86II::MO_GOT: O << "@GOT"; break;
391 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
392 case X86II::MO_PLT: O << "@PLT"; break;
396 /// print_pcrel_imm - This is used to print an immediate value that ends up
397 /// being encoded as a pc-relative value. These print slightly differently, for
398 /// example, a $ is not emitted.
399 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
400 const MachineOperand &MO = MI->getOperand(OpNo);
401 switch (MO.getType()) {
402 default: llvm_unreachable("Unknown pcrel immediate operand");
403 case MachineOperand::MO_Immediate:
404 O << MO.getImm();
405 return;
406 case MachineOperand::MO_MachineBasicBlock:
407 printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
408 return;
409 case MachineOperand::MO_GlobalAddress:
410 case MachineOperand::MO_ExternalSymbol:
411 printSymbolOperand(MO);
412 return;
418 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
419 const char *Modifier) {
420 const MachineOperand &MO = MI->getOperand(OpNo);
421 switch (MO.getType()) {
422 default: llvm_unreachable("unknown operand type!");
423 case MachineOperand::MO_Register: {
424 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
425 "Virtual registers should not make it this far!");
426 O << '%';
427 unsigned Reg = MO.getReg();
428 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
429 MVT VT = (strcmp(Modifier+6,"64") == 0) ?
430 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
431 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
432 Reg = getX86SubSuperRegister(Reg, VT);
434 O << TRI->getAsmName(Reg);
435 return;
438 case MachineOperand::MO_Immediate:
439 O << '$' << MO.getImm();
440 return;
442 case MachineOperand::MO_JumpTableIndex:
443 case MachineOperand::MO_ConstantPoolIndex:
444 case MachineOperand::MO_GlobalAddress:
445 case MachineOperand::MO_ExternalSymbol: {
446 O << '$';
447 printSymbolOperand(MO);
448 break;
453 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
454 unsigned char value = MI->getOperand(Op).getImm();
455 assert(value <= 7 && "Invalid ssecc argument!");
456 switch (value) {
457 case 0: O << "eq"; break;
458 case 1: O << "lt"; break;
459 case 2: O << "le"; break;
460 case 3: O << "unord"; break;
461 case 4: O << "neq"; break;
462 case 5: O << "nlt"; break;
463 case 6: O << "nle"; break;
464 case 7: O << "ord"; break;
468 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
469 const char *Modifier) {
470 const MachineOperand &BaseReg = MI->getOperand(Op);
471 const MachineOperand &IndexReg = MI->getOperand(Op+2);
472 const MachineOperand &DispSpec = MI->getOperand(Op+3);
474 // If we really don't want to print out (rip), don't.
475 bool HasBaseReg = BaseReg.getReg() != 0;
476 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
477 BaseReg.getReg() == X86::RIP)
478 HasBaseReg = false;
480 // HasParenPart - True if we will print out the () part of the mem ref.
481 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
483 if (DispSpec.isImm()) {
484 int DispVal = DispSpec.getImm();
485 if (DispVal || !HasParenPart)
486 O << DispVal;
487 } else {
488 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
489 DispSpec.isJTI() || DispSpec.isSymbol());
490 printSymbolOperand(MI->getOperand(Op+3));
493 if (HasParenPart) {
494 assert(IndexReg.getReg() != X86::ESP &&
495 "X86 doesn't allow scaling by ESP");
497 O << '(';
498 if (HasBaseReg)
499 printOperand(MI, Op, Modifier);
501 if (IndexReg.getReg()) {
502 O << ',';
503 printOperand(MI, Op+2, Modifier);
504 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
505 if (ScaleVal != 1)
506 O << ',' << ScaleVal;
508 O << ')';
512 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
513 const char *Modifier) {
514 assert(isMem(MI, Op) && "Invalid memory reference!");
515 const MachineOperand &Segment = MI->getOperand(Op+4);
516 if (Segment.getReg()) {
517 printOperand(MI, Op+4, Modifier);
518 O << ':';
520 printLeaMemReference(MI, Op, Modifier);
523 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
524 const MachineBasicBlock *MBB) const {
525 if (!TAI->getSetDirective())
526 return;
528 // We don't need .set machinery if we have GOT-style relocations
529 if (Subtarget->isPICStyleGOT())
530 return;
532 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
533 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
534 printBasicBlockLabel(MBB, false, false, false);
535 if (Subtarget->isPICStyleRIPRel())
536 O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
537 << '_' << uid << '\n';
538 else {
539 O << '-';
540 PrintPICBaseSymbol();
541 O << '\n';
546 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
547 PrintPICBaseSymbol();
548 O << '\n';
549 PrintPICBaseSymbol();
550 O << ':';
554 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
555 const MachineBasicBlock *MBB,
556 unsigned uid) const {
557 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
558 TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
560 O << JTEntryDirective << ' ';
562 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
563 O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
564 << '_' << uid << "_set_" << MBB->getNumber();
565 } else if (Subtarget->isPICStyleGOT()) {
566 printBasicBlockLabel(MBB, false, false, false);
567 O << "@GOTOFF";
568 } else
569 printBasicBlockLabel(MBB, false, false, false);
572 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
573 unsigned Reg = MO.getReg();
574 switch (Mode) {
575 default: return true; // Unknown mode.
576 case 'b': // Print QImode register
577 Reg = getX86SubSuperRegister(Reg, MVT::i8);
578 break;
579 case 'h': // Print QImode high register
580 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
581 break;
582 case 'w': // Print HImode register
583 Reg = getX86SubSuperRegister(Reg, MVT::i16);
584 break;
585 case 'k': // Print SImode register
586 Reg = getX86SubSuperRegister(Reg, MVT::i32);
587 break;
588 case 'q': // Print DImode register
589 Reg = getX86SubSuperRegister(Reg, MVT::i64);
590 break;
593 O << '%'<< TRI->getAsmName(Reg);
594 return false;
597 /// PrintAsmOperand - Print out an operand for an inline asm expression.
599 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
600 unsigned AsmVariant,
601 const char *ExtraCode) {
602 // Does this asm operand have a single letter operand modifier?
603 if (ExtraCode && ExtraCode[0]) {
604 if (ExtraCode[1] != 0) return true; // Unknown modifier.
606 const MachineOperand &MO = MI->getOperand(OpNo);
608 switch (ExtraCode[0]) {
609 default: return true; // Unknown modifier.
610 case 'c': // Don't print "$" before a global var name or constant.
611 if (MO.isImm())
612 O << MO.getImm();
613 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
614 printSymbolOperand(MO);
615 else
616 printOperand(MI, OpNo);
617 return false;
619 case 'A': // Print '*' before a register (it must be a register)
620 if (MO.isReg()) {
621 O << '*';
622 printOperand(MI, OpNo);
623 return false;
625 return true;
627 case 'b': // Print QImode register
628 case 'h': // Print QImode high register
629 case 'w': // Print HImode register
630 case 'k': // Print SImode register
631 case 'q': // Print DImode register
632 if (MO.isReg())
633 return printAsmMRegister(MO, ExtraCode[0]);
634 printOperand(MI, OpNo);
635 return false;
637 case 'P': // This is the operand of a call, treat specially.
638 print_pcrel_imm(MI, OpNo);
639 return false;
641 case 'n': // Negate the immediate or print a '-' before the operand.
642 // Note: this is a temporary solution. It should be handled target
643 // independently as part of the 'MC' work.
644 if (MO.isImm()) {
645 O << -MO.getImm();
646 return false;
648 O << '-';
652 printOperand(MI, OpNo);
653 return false;
656 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
657 unsigned OpNo,
658 unsigned AsmVariant,
659 const char *ExtraCode) {
660 if (ExtraCode && ExtraCode[0]) {
661 if (ExtraCode[1] != 0) return true; // Unknown modifier.
663 switch (ExtraCode[0]) {
664 default: return true; // Unknown modifier.
665 case 'b': // Print QImode register
666 case 'h': // Print QImode high register
667 case 'w': // Print HImode register
668 case 'k': // Print SImode register
669 case 'q': // Print SImode register
670 // These only apply to registers, ignore on mem.
671 break;
672 case 'P': // Don't print @PLT, but do print as memory.
673 printMemReference(MI, OpNo, "no-rip");
674 return false;
677 printMemReference(MI, OpNo);
678 return false;
681 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
682 // Convert registers in the addr mode according to subreg64.
683 for (unsigned i = 0; i != 4; ++i) {
684 if (!MI->getOperand(i).isReg()) continue;
686 unsigned Reg = MI->getOperand(i).getReg();
687 if (Reg == 0) continue;
689 MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
693 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
694 /// AT&T syntax to the current output stream.
696 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
697 ++EmittedInsts;
699 if (NewAsmPrinter) {
700 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
701 O << "\t";
702 printInlineAsm(MI);
703 return;
704 } else if (MI->isLabel()) {
705 printLabel(MI);
706 return;
707 } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {
708 printDeclare(MI);
709 return;
710 } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
711 printImplicitDef(MI);
712 return;
715 O << "NEW: ";
716 MCInst TmpInst;
718 TmpInst.setOpcode(MI->getOpcode());
720 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
721 const MachineOperand &MO = MI->getOperand(i);
723 MCOperand MCOp;
724 if (MO.isReg()) {
725 MCOp.MakeReg(MO.getReg());
726 } else if (MO.isImm()) {
727 MCOp.MakeImm(MO.getImm());
728 } else if (MO.isMBB()) {
729 MCOp.MakeMBBLabel(getFunctionNumber(), MO.getMBB()->getNumber());
730 } else {
731 llvm_unreachable("Unimp");
734 TmpInst.addOperand(MCOp);
737 switch (TmpInst.getOpcode()) {
738 case X86::LEA64_32r:
739 // Handle the 'subreg rewriting' for the lea64_32mem operand.
740 lower_lea64_32mem(&TmpInst, 1);
741 break;
744 // FIXME: Convert TmpInst.
745 printInstruction(&TmpInst);
746 O << "OLD: ";
749 // Call the autogenerated instruction printer routines.
750 printInstruction(MI);
753 /// doInitialization
754 bool X86ATTAsmPrinter::doInitialization(Module &M) {
755 if (NewAsmPrinter) {
756 Context = new MCContext();
757 // FIXME: Send this to "O" instead of outs(). For now, we force it to
758 // stdout to make it easy to compare.
759 Streamer = createAsmStreamer(*Context, outs());
762 return AsmPrinter::doInitialization(M);
765 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
766 const TargetData *TD = TM.getTargetData();
768 if (!GVar->hasInitializer())
769 return; // External global require no code
771 // Check to see if this is a special global used by LLVM, if so, emit it.
772 if (EmitSpecialLLVMGlobal(GVar)) {
773 if (Subtarget->isTargetDarwin() &&
774 TM.getRelocationModel() == Reloc::Static) {
775 if (GVar->getName() == "llvm.global_ctors")
776 O << ".reference .constructors_used\n";
777 else if (GVar->getName() == "llvm.global_dtors")
778 O << ".reference .destructors_used\n";
780 return;
783 std::string name = Mang->getMangledName(GVar);
784 Constant *C = GVar->getInitializer();
785 if (isa<MDNode>(C) || isa<MDString>(C))
786 return;
787 const Type *Type = C->getType();
788 unsigned Size = TD->getTypeAllocSize(Type);
789 unsigned Align = TD->getPreferredAlignmentLog(GVar);
791 printVisibility(name, GVar->getVisibility());
793 if (Subtarget->isTargetELF())
794 O << "\t.type\t" << name << ",@object\n";
796 SwitchToSection(TAI->SectionForGlobal(GVar));
798 if (C->isNullValue() && !GVar->hasSection() &&
799 !(Subtarget->isTargetDarwin() &&
800 TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
801 // FIXME: This seems to be pretty darwin-specific
802 if (GVar->hasExternalLinkage()) {
803 if (const char *Directive = TAI->getZeroFillDirective()) {
804 O << "\t.globl " << name << '\n';
805 O << Directive << "__DATA, __common, " << name << ", "
806 << Size << ", " << Align << '\n';
807 return;
811 if (!GVar->isThreadLocal() &&
812 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
813 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
815 if (TAI->getLCOMMDirective() != NULL) {
816 if (GVar->hasLocalLinkage()) {
817 O << TAI->getLCOMMDirective() << name << ',' << Size;
818 if (Subtarget->isTargetDarwin())
819 O << ',' << Align;
820 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
821 O << "\t.globl " << name << '\n'
822 << TAI->getWeakDefDirective() << name << '\n';
823 EmitAlignment(Align, GVar);
824 O << name << ":";
825 if (VerboseAsm) {
826 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
827 PrintUnmangledNameSafely(GVar, O);
829 O << '\n';
830 EmitGlobalConstant(C);
831 return;
832 } else {
833 O << TAI->getCOMMDirective() << name << ',' << Size;
834 if (TAI->getCOMMDirectiveTakesAlignment())
835 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
837 } else {
838 if (!Subtarget->isTargetCygMing()) {
839 if (GVar->hasLocalLinkage())
840 O << "\t.local\t" << name << '\n';
842 O << TAI->getCOMMDirective() << name << ',' << Size;
843 if (TAI->getCOMMDirectiveTakesAlignment())
844 O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
846 if (VerboseAsm) {
847 O << "\t\t" << TAI->getCommentString() << ' ';
848 PrintUnmangledNameSafely(GVar, O);
850 O << '\n';
851 return;
855 switch (GVar->getLinkage()) {
856 case GlobalValue::CommonLinkage:
857 case GlobalValue::LinkOnceAnyLinkage:
858 case GlobalValue::LinkOnceODRLinkage:
859 case GlobalValue::WeakAnyLinkage:
860 case GlobalValue::WeakODRLinkage:
861 if (Subtarget->isTargetDarwin()) {
862 O << "\t.globl " << name << '\n'
863 << TAI->getWeakDefDirective() << name << '\n';
864 } else if (Subtarget->isTargetCygMing()) {
865 O << "\t.globl\t" << name << "\n"
866 "\t.linkonce same_size\n";
867 } else {
868 O << "\t.weak\t" << name << '\n';
870 break;
871 case GlobalValue::DLLExportLinkage:
872 case GlobalValue::AppendingLinkage:
873 // FIXME: appending linkage variables should go into a section of
874 // their name or something. For now, just emit them as external.
875 case GlobalValue::ExternalLinkage:
876 // If external or appending, declare as a global symbol
877 O << "\t.globl " << name << '\n';
878 // FALL THROUGH
879 case GlobalValue::PrivateLinkage:
880 case GlobalValue::InternalLinkage:
881 break;
882 default:
883 llvm_unreachable("Unknown linkage type!");
886 EmitAlignment(Align, GVar);
887 O << name << ":";
888 if (VerboseAsm){
889 O << "\t\t\t\t" << TAI->getCommentString() << ' ';
890 PrintUnmangledNameSafely(GVar, O);
892 O << '\n';
893 if (TAI->hasDotTypeDotSizeDirective())
894 O << "\t.size\t" << name << ", " << Size << '\n';
896 EmitGlobalConstant(C);
899 bool X86ATTAsmPrinter::doFinalization(Module &M) {
900 // Print out module-level global variables here.
901 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
902 I != E; ++I) {
903 printModuleLevelGV(I);
905 if (I->hasDLLExportLinkage())
906 DLLExportedGVs.insert(Mang->getMangledName(I));
909 if (Subtarget->isTargetDarwin()) {
910 SwitchToDataSection("");
912 // Add the (possibly multiple) personalities to the set of global value
913 // stubs. Only referenced functions get into the Personalities list.
914 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
915 const std::vector<Function*> &Personalities = MMI->getPersonalities();
916 for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
917 if (Personalities[i])
918 GVStubs[Mang->getMangledName(Personalities[i], "$non_lazy_ptr",
919 true /*private label*/)] =
920 Mang->getMangledName(Personalities[i]);
924 // Output stubs for dynamically-linked functions
925 if (!FnStubs.empty()) {
926 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
927 "self_modifying_code+pure_instructions,5", 0);
928 for (StringMap<std::string>::iterator I = FnStubs.begin(),
929 E = FnStubs.end(); I != E; ++I)
930 O << I->getKeyData() << ":\n" << "\t.indirect_symbol " << I->second
931 << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
932 O << '\n';
935 // Output stubs for external and common global variables.
936 if (!GVStubs.empty()) {
937 SwitchToDataSection(
938 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
939 for (StringMap<std::string>::iterator I = GVStubs.begin(),
940 E = GVStubs.end(); I != E; ++I)
941 O << I->getKeyData() << ":\n\t.indirect_symbol "
942 << I->second << "\n\t.long\t0\n";
945 if (!HiddenGVStubs.empty()) {
946 SwitchToSection(TAI->getDataSection());
947 EmitAlignment(2);
948 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
949 E = HiddenGVStubs.end(); I != E; ++I)
950 O << I->getKeyData() << ":\n" << TAI->getData32bitsDirective()
951 << I->second << '\n';
954 // Funny Darwin hack: This flag tells the linker that no global symbols
955 // contain code that falls through to other global symbols (e.g. the obvious
956 // implementation of multiple entry points). If this doesn't occur, the
957 // linker can safely perform dead code stripping. Since LLVM never
958 // generates code that does this, it is always safe to set.
959 O << "\t.subsections_via_symbols\n";
960 } else if (Subtarget->isTargetCygMing()) {
961 // Emit type information for external functions
962 for (StringSet<>::iterator i = CygMingStubs.begin(), e = CygMingStubs.end();
963 i != e; ++i) {
964 O << "\t.def\t " << i->getKeyData()
965 << ";\t.scl\t" << COFF::C_EXT
966 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
967 << ";\t.endef\n";
972 // Output linker support code for dllexported globals on windows.
973 if (!DLLExportedGVs.empty()) {
974 SwitchToDataSection(".section .drectve");
976 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
977 e = DLLExportedGVs.end(); i != e; ++i)
978 O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
981 if (!DLLExportedFns.empty()) {
982 SwitchToDataSection(".section .drectve");
984 for (StringSet<>::iterator i = DLLExportedFns.begin(),
985 e = DLLExportedFns.end();
986 i != e; ++i)
987 O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
990 // Do common shutdown.
991 bool Changed = AsmPrinter::doFinalization(M);
993 if (NewAsmPrinter) {
994 Streamer->Finish();
996 delete Streamer;
997 delete Context;
998 Streamer = 0;
999 Context = 0;
1002 return Changed;
1005 // Include the auto-generated portion of the assembly writer.
1006 #include "X86GenAsmWriter.inc"