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 "X86MCAsmInfo.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/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/Mangler.h"
38 STATISTIC(EmittedInsts, "Number of machine instrs printed");
40 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
41 const TargetData *TD) {
42 X86MachineFunctionInfo Info;
45 switch (F->getCallingConv()) {
46 case CallingConv::X86_StdCall:
47 Info.setDecorationStyle(StdCall);
49 case CallingConv::X86_FastCall:
50 Info.setDecorationStyle(FastCall);
57 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
58 AI != AE; ++AI, ++argNum) {
59 const Type* Ty = AI->getType();
61 // 'Dereference' type in case of byval parameter attribute
62 if (F->paramHasAttr(argNum, Attribute::ByVal))
63 Ty = cast<PointerType>(Ty)->getElementType();
65 // Size should be aligned to DWORD boundary
66 Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
69 // We're not supporting tooooo huge arguments :)
70 Info.setBytesToPopOnReturn((unsigned int)Size);
75 /// decorateName - Query FunctionInfoMap and use this information for various
77 void X86IntelAsmPrinter::decorateName(std::string &Name,
78 const GlobalValue *GV) {
79 const Function *F = dyn_cast<Function>(GV);
82 // We don't want to decorate non-stdcall or non-fastcall functions right now
83 CallingConv::ID CC = F->getCallingConv();
84 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
87 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
89 const X86MachineFunctionInfo *Info;
90 if (info_item == FunctionInfoMap.end()) {
91 // Calculate apropriate function info and populate map
92 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
93 Info = &FunctionInfoMap[F];
95 Info = &info_item->second;
98 const FunctionType *FT = F->getFunctionType();
99 switch (Info->getDecorationStyle()) {
103 // "Pure" variadic functions do not receive @0 suffix.
104 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
105 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
106 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
109 // "Pure" variadic functions do not receive @0 suffix.
110 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
111 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
112 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
121 llvm_unreachable("Unsupported DecorationStyle");
125 /// runOnMachineFunction - This uses the printMachineInstruction()
126 /// method to print assembly for each instruction.
128 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
130 SetupMachineFunction(MF);
133 // Print out constants referenced by the function
134 EmitConstantPool(MF.getConstantPool());
136 // Print out labels for the function.
137 const Function *F = MF.getFunction();
138 CallingConv::ID CC = F->getCallingConv();
139 unsigned FnAlign = MF.getAlignment();
141 // Populate function information map. Actually, We don't want to populate
142 // non-stdcall or non-fastcall functions' information right now.
143 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
144 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
146 decorateName(CurrentFnName, F);
148 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
150 switch (F->getLinkage()) {
151 default: llvm_unreachable("Unsupported linkage type!");
152 case Function::LinkOnceAnyLinkage:
153 case Function::LinkOnceODRLinkage:
154 case Function::WeakAnyLinkage:
155 case Function::WeakODRLinkage:
157 case Function::PrivateLinkage:
158 case Function::LinkerPrivateLinkage:
159 case Function::InternalLinkage:
160 EmitAlignment(FnAlign);
162 case Function::DLLExportLinkage:
163 DLLExportedFns.insert(CurrentFnName);
165 case Function::ExternalLinkage:
166 O << "\tpublic " << CurrentFnName << "\n";
167 EmitAlignment(FnAlign);
171 O << CurrentFnName << "\tproc near\n";
173 // Print out code for the function.
174 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
176 // Print a label for the basic block if there are any predecessors.
177 if (!I->pred_empty()) {
178 EmitBasicBlockStart(I);
181 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
183 // Print the assembly for the instruction.
184 printMachineInstruction(II);
188 // Print out jump tables referenced by the function.
189 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
191 O << CurrentFnName << "\tendp\n";
193 // We didn't modify anything.
197 void X86IntelAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
198 unsigned char value = MI->getOperand(Op).getImm();
199 assert(value <= 7 && "Invalid ssecc argument!");
201 case 0: O << "eq"; break;
202 case 1: O << "lt"; break;
203 case 2: O << "le"; break;
204 case 3: O << "unord"; break;
205 case 4: O << "neq"; break;
206 case 5: O << "nlt"; break;
207 case 6: O << "nle"; break;
208 case 7: O << "ord"; break;
212 static void PrintRegName(raw_ostream &O, StringRef RegName) {
213 for (unsigned i = 0, e = RegName.size(); i != e; ++i)
214 O << (char)toupper(RegName[i]);
217 void X86IntelAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
218 const char *Modifier) {
219 printOp(MI->getOperand(OpNo), Modifier);
222 void X86IntelAsmPrinter::printOp(const MachineOperand &MO,
223 const char *Modifier) {
224 switch (MO.getType()) {
225 case MachineOperand::MO_Register: {
226 assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()));
227 unsigned Reg = MO.getReg();
228 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
229 EVT VT = (strcmp(Modifier,"subreg64") == 0) ?
230 MVT::i64 : ((strcmp(Modifier, "subreg32") == 0) ? MVT::i32 :
231 ((strcmp(Modifier,"subreg16") == 0) ? MVT::i16 :MVT::i8));
232 Reg = getX86SubSuperRegister(Reg, VT);
234 PrintRegName(O, getRegisterName(Reg));
237 case MachineOperand::MO_Immediate:
240 case MachineOperand::MO_JumpTableIndex: {
241 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
242 if (!isMemOp) O << "OFFSET ";
243 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
244 << "_" << MO.getIndex();
247 case MachineOperand::MO_ConstantPoolIndex: {
248 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
249 if (!isMemOp) O << "OFFSET ";
250 O << "[" << MAI->getPrivateGlobalPrefix() << "CPI"
251 << getFunctionNumber() << "_" << MO.getIndex();
252 printOffset(MO.getOffset());
256 case MachineOperand::MO_GlobalAddress: {
257 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
258 GlobalValue *GV = MO.getGlobal();
259 std::string Name = Mang->getMangledName(GV);
260 decorateName(Name, GV);
262 if (!isMemOp) O << "OFFSET ";
264 // Handle dllimport linkage.
265 // FIXME: This should be fixed with full support of stdcall & fastcall
267 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
271 printOffset(MO.getOffset());
274 case MachineOperand::MO_ExternalSymbol: {
275 O << MAI->getGlobalPrefix() << MO.getSymbolName();
279 O << "<unknown operand type>"; return;
283 void X86IntelAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo){
284 const MachineOperand &MO = MI->getOperand(OpNo);
285 switch (MO.getType()) {
286 default: llvm_unreachable("Unknown pcrel immediate operand");
287 case MachineOperand::MO_Immediate:
290 case MachineOperand::MO_MachineBasicBlock:
291 GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
294 case MachineOperand::MO_GlobalAddress: {
295 GlobalValue *GV = MO.getGlobal();
296 std::string Name = Mang->getMangledName(GV);
297 decorateName(Name, GV);
299 // Handle dllimport linkage.
300 // FIXME: This should be fixed with full support of stdcall & fastcall
302 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
305 printOffset(MO.getOffset());
309 case MachineOperand::MO_ExternalSymbol:
310 O << MAI->getGlobalPrefix() << MO.getSymbolName();
316 void X86IntelAsmPrinter::printLeaMemReference(const MachineInstr *MI,
318 const char *Modifier) {
319 const MachineOperand &BaseReg = MI->getOperand(Op);
320 int ScaleVal = MI->getOperand(Op+1).getImm();
321 const MachineOperand &IndexReg = MI->getOperand(Op+2);
322 const MachineOperand &DispSpec = MI->getOperand(Op+3);
325 bool NeedPlus = false;
326 if (BaseReg.getReg()) {
327 printOp(BaseReg, Modifier);
331 if (IndexReg.getReg()) {
332 if (NeedPlus) O << " + ";
334 O << ScaleVal << "*";
335 printOp(IndexReg, Modifier);
339 if (DispSpec.isGlobal() || DispSpec.isCPI() ||
343 printOp(DispSpec, "mem");
345 int DispVal = DispSpec.getImm();
346 if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
361 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
362 const char *Modifier) {
363 assert(isMem(MI, Op) && "Invalid memory reference!");
364 MachineOperand Segment = MI->getOperand(Op+4);
365 if (Segment.getReg()) {
366 printOperand(MI, Op+4, Modifier);
369 printLeaMemReference(MI, Op, Modifier);
372 void X86IntelAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
373 const MachineBasicBlock *MBB) const {
374 if (!MAI->getSetDirective())
377 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
378 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
379 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
380 O << '-' << "\"L" << getFunctionNumber() << "$pb\"'\n";
383 void X86IntelAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
384 O << "L" << getFunctionNumber() << "$pb\n";
385 O << "L" << getFunctionNumber() << "$pb:";
388 bool X86IntelAsmPrinter::printAsmMRegister(const MachineOperand &MO,
390 unsigned Reg = MO.getReg();
392 default: return true; // Unknown mode.
393 case 'b': // Print QImode register
394 Reg = getX86SubSuperRegister(Reg, MVT::i8);
396 case 'h': // Print QImode high register
397 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
399 case 'w': // Print HImode register
400 Reg = getX86SubSuperRegister(Reg, MVT::i16);
402 case 'k': // Print SImode register
403 Reg = getX86SubSuperRegister(Reg, MVT::i32);
407 PrintRegName(O, getRegisterName(Reg));
411 /// PrintAsmOperand - Print out an operand for an inline asm expression.
413 bool X86IntelAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
415 const char *ExtraCode) {
416 // Does this asm operand have a single letter operand modifier?
417 if (ExtraCode && ExtraCode[0]) {
418 if (ExtraCode[1] != 0) return true; // Unknown modifier.
420 switch (ExtraCode[0]) {
421 default: return true; // Unknown modifier.
422 case 'b': // Print QImode register
423 case 'h': // Print QImode high register
424 case 'w': // Print HImode register
425 case 'k': // Print SImode register
426 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
430 printOperand(MI, OpNo);
434 bool X86IntelAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
437 const char *ExtraCode) {
438 if (ExtraCode && ExtraCode[0])
439 return true; // Unknown modifier.
440 printMemReference(MI, OpNo);
444 /// printMachineInstruction -- Print out a single X86 LLVM instruction
445 /// MI in Intel syntax to the current output stream.
447 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
450 processDebugLoc(MI->getDebugLoc());
452 // Call the autogenerated instruction printer routines.
453 printInstruction(MI);
455 if (VerboseAsm && !MI->getDebugLoc().isUnknown())
460 bool X86IntelAsmPrinter::doInitialization(Module &M) {
461 bool Result = AsmPrinter::doInitialization(M);
463 O << "\t.686\n\t.MMX\n\t.XMM\n\t.model flat\n\n";
465 // Emit declarations for external functions.
466 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
467 if (I->isDeclaration()) {
468 std::string Name = Mang->getMangledName(I);
469 decorateName(Name, I);
472 if (I->hasDLLImportLinkage()) {
475 O << Name << ":near\n";
478 // Emit declarations for external globals. Note that VC++ always declares
479 // external globals to have type byte, and if that's good enough for VC++...
480 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
482 if (I->isDeclaration()) {
483 std::string Name = Mang->getMangledName(I);
486 if (I->hasDLLImportLinkage()) {
489 O << Name << ":byte\n";
496 void X86IntelAsmPrinter::PrintGlobalVariable(const GlobalVariable *GV) {
497 // Check to see if this is a special global used by LLVM, if so, emit it.
498 if (GV->isDeclaration() ||
499 EmitSpecialLLVMGlobal(GV))
502 const TargetData *TD = TM.getTargetData();
504 std::string name = Mang->getMangledName(GV);
505 Constant *C = GV->getInitializer();
506 unsigned Align = TD->getPreferredAlignmentLog(GV);
507 bool bCustomSegment = false;
509 switch (GV->getLinkage()) {
510 case GlobalValue::CommonLinkage:
511 case GlobalValue::LinkOnceAnyLinkage:
512 case GlobalValue::LinkOnceODRLinkage:
513 case GlobalValue::WeakAnyLinkage:
514 case GlobalValue::WeakODRLinkage:
515 // FIXME: make a MCSection.
516 O << name << "?\tSEGEMNT PARA common 'COMMON'\n";
517 bCustomSegment = true;
518 // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
519 // are also available.
521 case GlobalValue::AppendingLinkage:
522 // FIXME: make a MCSection.
523 O << name << "?\tSEGMENT PARA public 'DATA'\n";
524 bCustomSegment = true;
525 // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
526 // are also available.
528 case GlobalValue::DLLExportLinkage:
529 DLLExportedGVs.insert(name);
531 case GlobalValue::ExternalLinkage:
532 O << "\tpublic " << name << "\n";
534 case GlobalValue::InternalLinkage:
535 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
538 llvm_unreachable("Unknown linkage type!");
542 EmitAlignment(Align, GV);
546 O.PadToColumn(MAI->getCommentColumn());
547 O << MAI->getCommentString()
548 << " " << GV->getName();
551 EmitGlobalConstant(C);
554 O << name << "?\tends\n";
557 bool X86IntelAsmPrinter::doFinalization(Module &M) {
558 // Output linker support code for dllexported globals
559 if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
560 O << "; WARNING: The following code is valid only with MASM v8.x"
561 << "and (possible) higher\n"
562 << "; This version of MASM is usually shipped with Microsoft "
563 << "Visual Studio 2005\n"
564 << "; or (possible) further versions. Unfortunately, there is no "
565 << "way to support\n"
566 << "; dllexported symbols in the earlier versions of MASM in fully "
567 << "automatic way\n\n";
568 O << "_drectve\t segment info alias('.drectve')\n";
570 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
571 e = DLLExportedGVs.end();
573 O << "\t db ' /EXPORT:" << i->getKeyData() << ",data'\n";
575 for (StringSet<>::iterator i = DLLExportedFns.begin(),
576 e = DLLExportedFns.end();
578 O << "\t db ' /EXPORT:" << i->getKeyData() << "'\n";
580 O << "_drectve\t ends\n";
583 // Bypass X86SharedAsmPrinter::doFinalization().
584 bool Result = AsmPrinter::doFinalization(M);
589 void X86IntelAsmPrinter::EmitString(const ConstantArray *CVA) const {
590 unsigned NumElts = CVA->getNumOperands();
591 if (NumElts == 0) return;
593 // ML does not have escape sequences except '' for '. It also has a maximum
594 // string length of 255.
596 bool inString = false;
597 for (unsigned i = 0; i < NumElts; i++) {
598 int n = cast<ConstantInt>(CVA->getOperand(i))->getZExtValue() & 255;
602 if (n >= 32 && n <= 127) {
629 len += 1 + (n > 9) + (n > 99);
649 // Include the auto-generated portion of the assembly writer.
650 #include "X86GenAsmWriter1.inc"