1 //===-- X86IntelAsmPrinter.cpp - Convert X86 LLVM code to Intel assembly --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to Intel format assembly language.
12 // This printer is the output mechanism used by `llc'.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "asm-printer"
17 #include "X86IntelAsmPrinter.h"
18 #include "X86InstrInfo.h"
19 #include "X86TargetAsmInfo.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Module.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/CodeGen/DwarfWriter.h"
29 #include "llvm/Support/Mangler.h"
30 #include "llvm/Target/TargetAsmInfo.h"
31 #include "llvm/Target/TargetOptions.h"
34 STATISTIC(EmittedInsts, "Number of machine instrs printed");
36 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
37 const TargetData *TD) {
38 X86MachineFunctionInfo Info;
41 switch (F->getCallingConv()) {
42 case CallingConv::X86_StdCall:
43 Info.setDecorationStyle(StdCall);
45 case CallingConv::X86_FastCall:
46 Info.setDecorationStyle(FastCall);
53 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
54 AI != AE; ++AI, ++argNum) {
55 const Type* Ty = AI->getType();
57 // 'Dereference' type in case of byval parameter attribute
58 if (F->paramHasAttr(argNum, Attribute::ByVal))
59 Ty = cast<PointerType>(Ty)->getElementType();
61 // Size should be aligned to DWORD boundary
62 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
65 // We're not supporting tooooo huge arguments :)
66 Info.setBytesToPopOnReturn((unsigned int)Size);
71 /// decorateName - Query FunctionInfoMap and use this information for various
73 void X86IntelAsmPrinter::decorateName(std::string &Name,
74 const GlobalValue *GV) {
75 const Function *F = dyn_cast<Function>(GV);
78 // We don't want to decorate non-stdcall or non-fastcall functions right now
79 unsigned CC = F->getCallingConv();
80 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
83 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
85 const X86MachineFunctionInfo *Info;
86 if (info_item == FunctionInfoMap.end()) {
87 // Calculate apropriate function info and populate map
88 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
89 Info = &FunctionInfoMap[F];
91 Info = &info_item->second;
94 const FunctionType *FT = F->getFunctionType();
95 switch (Info->getDecorationStyle()) {
99 // "Pure" variadic functions do not receive @0 suffix.
100 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
101 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
102 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
105 // "Pure" variadic functions do not receive @0 suffix.
106 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
107 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
108 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
117 assert(0 && "Unsupported DecorationStyle");
121 /// runOnMachineFunction - This uses the printMachineInstruction()
122 /// method to print assembly for each instruction.
124 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
126 SetupMachineFunction(MF);
129 // Print out constants referenced by the function
130 EmitConstantPool(MF.getConstantPool());
132 // Print out labels for the function.
133 const Function *F = MF.getFunction();
134 unsigned CC = F->getCallingConv();
136 // Populate function information map. Actually, We don't want to populate
137 // non-stdcall or non-fastcall functions' information right now.
138 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
139 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
141 decorateName(CurrentFnName, F);
143 SwitchToTextSection("_text", F);
145 unsigned FnAlign = 4;
146 if (F->hasFnAttr(Attribute::OptimizeForSize))
148 switch (F->getLinkage()) {
149 default: assert(0 && "Unsupported linkage type!");
150 case Function::PrivateLinkage:
151 case Function::InternalLinkage:
152 EmitAlignment(FnAlign);
154 case Function::DLLExportLinkage:
155 DLLExportedFns.insert(CurrentFnName);
157 case Function::ExternalLinkage:
158 O << "\tpublic " << CurrentFnName << "\n";
159 EmitAlignment(FnAlign);
163 O << CurrentFnName << "\tproc near\n";
165 // Print out code for the function.
166 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
168 // Print a label for the basic block if there are any predecessors.
169 if (!I->pred_empty()) {
170 printBasicBlockLabel(I, true, true);
173 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
175 // Print the assembly for the instruction.
176 printMachineInstruction(II);
180 // Print out jump tables referenced by the function.
181 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
183 O << CurrentFnName << "\tendp\n";
187 // We didn't modify anything.
191 void X86IntelAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
192 unsigned char value = MI->getOperand(Op).getImm();
193 assert(value <= 7 && "Invalid ssecc argument!");
195 case 0: O << "eq"; break;
196 case 1: O << "lt"; break;
197 case 2: O << "le"; break;
198 case 3: O << "unord"; break;
199 case 4: O << "neq"; break;
200 case 5: O << "nlt"; break;
201 case 6: O << "nle"; break;
202 case 7: O << "ord"; break;
206 void X86IntelAsmPrinter::printOp(const MachineOperand &MO,
207 const char *Modifier) {
208 switch (MO.getType()) {
209 case MachineOperand::MO_Register: {
210 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
211 unsigned Reg = MO.getReg();
212 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
213 MVT VT = (strcmp(Modifier,"subreg64") == 0) ?
214 MVT::i64 : ((strcmp(Modifier, "subreg32") == 0) ? MVT::i32 :
215 ((strcmp(Modifier,"subreg16") == 0) ? MVT::i16 :MVT::i8));
216 Reg = getX86SubSuperRegister(Reg, VT);
218 O << TRI->getName(Reg);
220 O << "reg" << MO.getReg();
223 case MachineOperand::MO_Immediate:
226 case MachineOperand::MO_MachineBasicBlock:
228 assert(0 && "labels should only be used as pc-relative values");
229 printBasicBlockLabel(MO.getMBB());
231 case MachineOperand::MO_JumpTableIndex: {
232 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
233 if (!isMemOp) O << "OFFSET ";
234 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
235 << "_" << MO.getIndex();
238 case MachineOperand::MO_ConstantPoolIndex: {
239 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
240 if (!isMemOp) O << "OFFSET ";
241 O << "[" << TAI->getPrivateGlobalPrefix() << "CPI"
242 << getFunctionNumber() << "_" << MO.getIndex();
243 printOffset(MO.getOffset());
247 case MachineOperand::MO_GlobalAddress: {
248 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
249 GlobalValue *GV = MO.getGlobal();
250 std::string Name = Mang->getValueName(GV);
252 decorateName(Name, GV);
254 if (!isMemOp) O << "OFFSET ";
255 if (GV->hasDLLImportLinkage()) {
256 // FIXME: This should be fixed with full support of stdcall & fastcall
261 printOffset(MO.getOffset());
264 case MachineOperand::MO_ExternalSymbol: {
265 O << TAI->getGlobalPrefix() << MO.getSymbolName();
269 O << "<unknown operand type>"; return;
273 void X86IntelAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo){
274 const MachineOperand &MO = MI->getOperand(OpNo);
275 switch (MO.getType()) {
276 default: assert(0 && "Unknown pcrel immediate operand");
277 case MachineOperand::MO_Immediate:
280 case MachineOperand::MO_MachineBasicBlock:
281 printBasicBlockLabel(MO.getMBB());
284 case MachineOperand::MO_GlobalAddress: {
285 GlobalValue *GV = MO.getGlobal();
286 std::string Name = Mang->getValueName(GV);
287 decorateName(Name, GV);
289 if (GV->hasDLLImportLinkage()) {
290 // FIXME: This should be fixed with full support of stdcall & fastcall
295 printOffset(MO.getOffset());
299 case MachineOperand::MO_ExternalSymbol:
300 O << TAI->getGlobalPrefix() << MO.getSymbolName();
306 void X86IntelAsmPrinter::printLeaMemReference(const MachineInstr *MI,
308 const char *Modifier) {
309 const MachineOperand &BaseReg = MI->getOperand(Op);
310 int ScaleVal = MI->getOperand(Op+1).getImm();
311 const MachineOperand &IndexReg = MI->getOperand(Op+2);
312 const MachineOperand &DispSpec = MI->getOperand(Op+3);
315 bool NeedPlus = false;
316 if (BaseReg.getReg()) {
317 printOp(BaseReg, Modifier);
321 if (IndexReg.getReg()) {
322 if (NeedPlus) O << " + ";
324 O << ScaleVal << "*";
325 printOp(IndexReg, Modifier);
329 if (DispSpec.isGlobal() || DispSpec.isCPI() ||
333 printOp(DispSpec, "mem");
335 int DispVal = DispSpec.getImm();
336 if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
351 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
352 const char *Modifier) {
353 assert(isMem(MI, Op) && "Invalid memory reference!");
354 MachineOperand Segment = MI->getOperand(Op+4);
355 if (Segment.getReg()) {
356 printOperand(MI, Op+4, Modifier);
359 printLeaMemReference(MI, Op, Modifier);
362 void X86IntelAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
363 const MachineBasicBlock *MBB) const {
364 if (!TAI->getSetDirective())
367 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
368 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
369 printBasicBlockLabel(MBB, false, false, false);
370 O << '-' << "\"L" << getFunctionNumber() << "$pb\"'\n";
373 void X86IntelAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
374 O << "L" << getFunctionNumber() << "$pb\n";
375 O << "L" << getFunctionNumber() << "$pb:";
378 bool X86IntelAsmPrinter::printAsmMRegister(const MachineOperand &MO,
380 unsigned Reg = MO.getReg();
382 default: return true; // Unknown mode.
383 case 'b': // Print QImode register
384 Reg = getX86SubSuperRegister(Reg, MVT::i8);
386 case 'h': // Print QImode high register
387 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
389 case 'w': // Print HImode register
390 Reg = getX86SubSuperRegister(Reg, MVT::i16);
392 case 'k': // Print SImode register
393 Reg = getX86SubSuperRegister(Reg, MVT::i32);
397 O << TRI->getName(Reg);
401 /// PrintAsmOperand - Print out an operand for an inline asm expression.
403 bool X86IntelAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
405 const char *ExtraCode) {
406 // Does this asm operand have a single letter operand modifier?
407 if (ExtraCode && ExtraCode[0]) {
408 if (ExtraCode[1] != 0) return true; // Unknown modifier.
410 switch (ExtraCode[0]) {
411 default: return true; // Unknown modifier.
412 case 'b': // Print QImode register
413 case 'h': // Print QImode high register
414 case 'w': // Print HImode register
415 case 'k': // Print SImode register
416 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
420 printOperand(MI, OpNo);
424 bool X86IntelAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
427 const char *ExtraCode) {
428 if (ExtraCode && ExtraCode[0])
429 return true; // Unknown modifier.
430 printMemReference(MI, OpNo);
434 /// printMachineInstruction -- Print out a single X86 LLVM instruction
435 /// MI in Intel syntax to the current output stream.
437 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
440 // Call the autogenerated instruction printer routines.
441 printInstruction(MI);
444 bool X86IntelAsmPrinter::doInitialization(Module &M) {
445 bool Result = AsmPrinter::doInitialization(M);
447 Mang->markCharUnacceptable('.');
449 O << "\t.686\n\t.MMX\n\t.XMM\n\t.model flat\n\n";
451 // Emit declarations for external functions.
452 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
453 if (I->isDeclaration()) {
454 std::string Name = Mang->getValueName(I);
455 decorateName(Name, I);
458 if (I->hasDLLImportLinkage()) {
461 O << Name << ":near\n";
464 // Emit declarations for external globals. Note that VC++ always declares
465 // external globals to have type byte, and if that's good enough for VC++...
466 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
468 if (I->isDeclaration()) {
469 std::string Name = Mang->getValueName(I);
472 if (I->hasDLLImportLinkage()) {
475 O << Name << ":byte\n";
482 bool X86IntelAsmPrinter::doFinalization(Module &M) {
483 const TargetData *TD = TM.getTargetData();
485 // Print out module-level global variables here.
486 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
488 if (I->isDeclaration()) continue; // External global require no code
490 // Check to see if this is a special global used by LLVM, if so, emit it.
491 if (EmitSpecialLLVMGlobal(I))
494 std::string name = Mang->getValueName(I);
495 Constant *C = I->getInitializer();
496 unsigned Align = TD->getPreferredAlignmentLog(I);
497 bool bCustomSegment = false;
499 switch (I->getLinkage()) {
500 case GlobalValue::CommonLinkage:
501 case GlobalValue::LinkOnceAnyLinkage:
502 case GlobalValue::LinkOnceODRLinkage:
503 case GlobalValue::WeakAnyLinkage:
504 case GlobalValue::WeakODRLinkage:
505 SwitchToDataSection("");
506 O << name << "?\tSEGEMNT PARA common 'COMMON'\n";
507 bCustomSegment = true;
508 // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
509 // are also available.
511 case GlobalValue::AppendingLinkage:
512 SwitchToDataSection("");
513 O << name << "?\tSEGMENT PARA public 'DATA'\n";
514 bCustomSegment = true;
515 // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
516 // are also available.
518 case GlobalValue::DLLExportLinkage:
519 DLLExportedGVs.insert(name);
521 case GlobalValue::ExternalLinkage:
522 O << "\tpublic " << name << "\n";
524 case GlobalValue::InternalLinkage:
525 SwitchToSection(TAI->getDataSection());
528 assert(0 && "Unknown linkage type!");
532 EmitAlignment(Align, I);
536 O << "\t\t\t\t" << TAI->getCommentString()
537 << " " << I->getName();
540 EmitGlobalConstant(C);
543 O << name << "?\tends\n";
546 // Output linker support code for dllexported globals
547 if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
548 SwitchToDataSection("");
549 O << "; WARNING: The following code is valid only with MASM v8.x"
550 << "and (possible) higher\n"
551 << "; This version of MASM is usually shipped with Microsoft "
552 << "Visual Studio 2005\n"
553 << "; or (possible) further versions. Unfortunately, there is no "
554 << "way to support\n"
555 << "; dllexported symbols in the earlier versions of MASM in fully "
556 << "automatic way\n\n";
557 O << "_drectve\t segment info alias('.drectve')\n";
560 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
561 e = DLLExportedGVs.end();
563 O << "\t db ' /EXPORT:" << i->getKeyData() << ",data'\n";
565 for (StringSet<>::iterator i = DLLExportedFns.begin(),
566 e = DLLExportedFns.end();
568 O << "\t db ' /EXPORT:" << i->getKeyData() << "'\n";
570 if (!DLLExportedGVs.empty() || !DLLExportedFns.empty())
571 O << "_drectve\t ends\n";
573 // Bypass X86SharedAsmPrinter::doFinalization().
574 bool Result = AsmPrinter::doFinalization(M);
575 SwitchToDataSection("");
580 void X86IntelAsmPrinter::EmitString(const ConstantArray *CVA) const {
581 unsigned NumElts = CVA->getNumOperands();
583 // ML does not have escape sequences except '' for '. It also has a maximum
584 // string length of 255.
586 bool inString = false;
587 for (unsigned i = 0; i < NumElts; i++) {
588 int n = cast<ConstantInt>(CVA->getOperand(i))->getZExtValue() & 255;
592 if (n >= 32 && n <= 127) {
619 len += 1 + (n > 9) + (n > 99);
640 // Include the auto-generated portion of the assembly writer.
641 #include "X86GenAsmWriter1.inc"