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/Support/Mangler.h"
29 #include "llvm/Target/TargetAsmInfo.h"
30 #include "llvm/Target/TargetOptions.h"
33 STATISTIC(EmittedInsts, "Number of machine instrs printed");
35 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
36 const TargetData *TD) {
37 X86MachineFunctionInfo Info;
40 switch (F->getCallingConv()) {
41 case CallingConv::X86_StdCall:
42 Info.setDecorationStyle(StdCall);
44 case CallingConv::X86_FastCall:
45 Info.setDecorationStyle(FastCall);
52 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
53 AI != AE; ++AI, ++argNum) {
54 const Type* Ty = AI->getType();
56 // 'Dereference' type in case of byval parameter attribute
57 if (F->paramHasAttr(argNum, ParamAttr::ByVal))
58 Ty = cast<PointerType>(Ty)->getElementType();
60 // Size should be aligned to DWORD boundary
61 Size += ((TD->getABITypeSize(Ty) + 3)/4)*4;
64 // We're not supporting tooooo huge arguments :)
65 Info.setBytesToPopOnReturn((unsigned int)Size);
70 /// decorateName - Query FunctionInfoMap and use this information for various
72 void X86IntelAsmPrinter::decorateName(std::string &Name,
73 const GlobalValue *GV) {
74 const Function *F = dyn_cast<Function>(GV);
77 // We don't want to decorate non-stdcall or non-fastcall functions right now
78 unsigned CC = F->getCallingConv();
79 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
82 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
84 const X86MachineFunctionInfo *Info;
85 if (info_item == FunctionInfoMap.end()) {
86 // Calculate apropriate function info and populate map
87 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
88 Info = &FunctionInfoMap[F];
90 Info = &info_item->second;
93 const FunctionType *FT = F->getFunctionType();
94 switch (Info->getDecorationStyle()) {
98 // "Pure" variadic functions do not receive @0 suffix.
99 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
100 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
101 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
104 // "Pure" variadic functions do not receive @0 suffix.
105 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
106 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
107 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
116 assert(0 && "Unsupported DecorationStyle");
121 std::string X86IntelAsmPrinter::getSectionForFunction(const Function &F) const {
122 // Intel asm always emits functions to _text.
126 /// runOnMachineFunction - This uses the printMachineInstruction()
127 /// method to print assembly for each instruction.
129 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 unsigned CC = F->getCallingConv();
140 // Populate function information map. Actually, We don't want to populate
141 // non-stdcall or non-fastcall functions' information right now.
142 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
143 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
145 decorateName(CurrentFnName, F);
147 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
149 unsigned FnAlign = OptimizeForSize ? 1 : 4;
150 if (FnAlign == 4 && (F->getNotes() & FN_NOTE_OptimizeForSize))
152 switch (F->getLinkage()) {
153 default: assert(0 && "Unsupported linkage type!");
154 case Function::InternalLinkage:
155 EmitAlignment(FnAlign);
157 case Function::DLLExportLinkage:
158 DLLExportedFns.insert(CurrentFnName);
160 case Function::ExternalLinkage:
161 O << "\tpublic " << CurrentFnName << "\n";
162 EmitAlignment(FnAlign);
166 O << CurrentFnName << "\tproc near\n";
168 // Print out code for the function.
169 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
171 // Print a label for the basic block if there are any predecessors.
172 if (!I->pred_empty()) {
173 printBasicBlockLabel(I, true, true);
176 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
178 // Print the assembly for the instruction.
179 printMachineInstruction(II);
183 // Print out jump tables referenced by the function.
184 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
186 O << CurrentFnName << "\tendp\n";
188 // We didn't modify anything.
192 void X86IntelAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
193 unsigned char value = MI->getOperand(Op).getImm();
194 assert(value <= 7 && "Invalid ssecc argument!");
196 case 0: O << "eq"; break;
197 case 1: O << "lt"; break;
198 case 2: O << "le"; break;
199 case 3: O << "unord"; break;
200 case 4: O << "neq"; break;
201 case 5: O << "nlt"; break;
202 case 6: O << "nle"; break;
203 case 7: O << "ord"; break;
207 void X86IntelAsmPrinter::printOp(const MachineOperand &MO,
208 const char *Modifier) {
209 switch (MO.getType()) {
210 case MachineOperand::MO_Register: {
211 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
212 unsigned Reg = MO.getReg();
213 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
214 MVT VT = (strcmp(Modifier,"subreg64") == 0) ?
215 MVT::i64 : ((strcmp(Modifier, "subreg32") == 0) ? MVT::i32 :
216 ((strcmp(Modifier,"subreg16") == 0) ? MVT::i16 :MVT::i8));
217 Reg = getX86SubSuperRegister(Reg, VT);
219 O << TRI->getName(Reg);
221 O << "reg" << MO.getReg();
224 case MachineOperand::MO_Immediate:
227 case MachineOperand::MO_MachineBasicBlock:
228 printBasicBlockLabel(MO.getMBB());
230 case MachineOperand::MO_JumpTableIndex: {
231 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
232 if (!isMemOp) O << "OFFSET ";
233 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
234 << "_" << MO.getIndex();
237 case MachineOperand::MO_ConstantPoolIndex: {
238 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
239 if (!isMemOp) O << "OFFSET ";
240 O << "[" << TAI->getPrivateGlobalPrefix() << "CPI"
241 << getFunctionNumber() << "_" << MO.getIndex();
242 int Offset = MO.getOffset();
244 O << " + " << Offset;
250 case MachineOperand::MO_GlobalAddress: {
251 bool isCallOp = Modifier && !strcmp(Modifier, "call");
252 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
253 GlobalValue *GV = MO.getGlobal();
254 std::string Name = Mang->getValueName(GV);
256 decorateName(Name, GV);
258 if (!isMemOp && !isCallOp) O << "OFFSET ";
259 if (GV->hasDLLImportLinkage()) {
260 // FIXME: This should be fixed with full support of stdcall & fastcall
265 int Offset = MO.getOffset();
267 O << " + " << Offset;
272 case MachineOperand::MO_ExternalSymbol: {
273 bool isCallOp = Modifier && !strcmp(Modifier, "call");
274 if (!isCallOp) O << "OFFSET ";
275 O << TAI->getGlobalPrefix() << MO.getSymbolName();
279 O << "<unknown operand type>"; return;
283 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
284 const char *Modifier) {
285 assert(isMem(MI, Op) && "Invalid memory reference!");
287 const MachineOperand &BaseReg = MI->getOperand(Op);
288 int ScaleVal = MI->getOperand(Op+1).getImm();
289 const MachineOperand &IndexReg = MI->getOperand(Op+2);
290 const MachineOperand &DispSpec = MI->getOperand(Op+3);
293 bool NeedPlus = false;
294 if (BaseReg.getReg()) {
295 printOp(BaseReg, Modifier);
299 if (IndexReg.getReg()) {
300 if (NeedPlus) O << " + ";
302 O << ScaleVal << "*";
303 printOp(IndexReg, Modifier);
307 if (DispSpec.isGlobalAddress() || DispSpec.isConstantPoolIndex() ||
308 DispSpec.isJumpTableIndex()) {
311 printOp(DispSpec, "mem");
313 int DispVal = DispSpec.getImm();
314 if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
329 void X86IntelAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
330 const MachineBasicBlock *MBB) const {
331 if (!TAI->getSetDirective())
334 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
335 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
336 printBasicBlockLabel(MBB, false, false, false);
337 O << '-' << "\"L" << getFunctionNumber() << "$pb\"'\n";
340 void X86IntelAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
341 O << "\"L" << getFunctionNumber() << "$pb\"\n";
342 O << "\"L" << getFunctionNumber() << "$pb\":";
345 bool X86IntelAsmPrinter::printAsmMRegister(const MachineOperand &MO,
347 unsigned Reg = MO.getReg();
349 default: return true; // Unknown mode.
350 case 'b': // Print QImode register
351 Reg = getX86SubSuperRegister(Reg, MVT::i8);
353 case 'h': // Print QImode high register
354 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
356 case 'w': // Print HImode register
357 Reg = getX86SubSuperRegister(Reg, MVT::i16);
359 case 'k': // Print SImode register
360 Reg = getX86SubSuperRegister(Reg, MVT::i32);
364 O << '%' << TRI->getName(Reg);
368 /// PrintAsmOperand - Print out an operand for an inline asm expression.
370 bool X86IntelAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
372 const char *ExtraCode) {
373 // Does this asm operand have a single letter operand modifier?
374 if (ExtraCode && ExtraCode[0]) {
375 if (ExtraCode[1] != 0) return true; // Unknown modifier.
377 switch (ExtraCode[0]) {
378 default: return true; // Unknown modifier.
379 case 'b': // Print QImode register
380 case 'h': // Print QImode high register
381 case 'w': // Print HImode register
382 case 'k': // Print SImode register
383 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
387 printOperand(MI, OpNo);
391 bool X86IntelAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
394 const char *ExtraCode) {
395 if (ExtraCode && ExtraCode[0])
396 return true; // Unknown modifier.
397 printMemReference(MI, OpNo);
401 /// printMachineInstruction -- Print out a single X86 LLVM instruction
402 /// MI in Intel syntax to the current output stream.
404 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
407 // Call the autogenerated instruction printer routines.
408 printInstruction(MI);
411 bool X86IntelAsmPrinter::doInitialization(Module &M) {
412 bool Result = AsmPrinter::doInitialization(M);
414 Mang->markCharUnacceptable('.');
416 O << "\t.686\n\t.model flat\n\n";
418 // Emit declarations for external functions.
419 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
420 if (I->isDeclaration()) {
421 std::string Name = Mang->getValueName(I);
422 decorateName(Name, I);
425 if (I->hasDLLImportLinkage()) {
428 O << Name << ":near\n";
431 // Emit declarations for external globals. Note that VC++ always declares
432 // external globals to have type byte, and if that's good enough for VC++...
433 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
435 if (I->isDeclaration()) {
436 std::string Name = Mang->getValueName(I);
439 if (I->hasDLLImportLinkage()) {
442 O << Name << ":byte\n";
449 bool X86IntelAsmPrinter::doFinalization(Module &M) {
450 const TargetData *TD = TM.getTargetData();
452 // Print out module-level global variables here.
453 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
455 if (I->isDeclaration()) continue; // External global require no code
457 // Check to see if this is a special global used by LLVM, if so, emit it.
458 if (EmitSpecialLLVMGlobal(I))
461 std::string name = Mang->getValueName(I);
462 Constant *C = I->getInitializer();
463 unsigned Align = TD->getPreferredAlignmentLog(I);
464 bool bCustomSegment = false;
466 switch (I->getLinkage()) {
467 case GlobalValue::CommonLinkage:
468 case GlobalValue::LinkOnceLinkage:
469 case GlobalValue::WeakLinkage:
470 SwitchToDataSection("");
471 O << name << "?\tsegment common 'COMMON'\n";
472 bCustomSegment = true;
473 // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
474 // are also available.
476 case GlobalValue::AppendingLinkage:
477 SwitchToDataSection("");
478 O << name << "?\tsegment public 'DATA'\n";
479 bCustomSegment = true;
480 // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
481 // are also available.
483 case GlobalValue::DLLExportLinkage:
484 DLLExportedGVs.insert(name);
486 case GlobalValue::ExternalLinkage:
487 O << "\tpublic " << name << "\n";
489 case GlobalValue::InternalLinkage:
490 SwitchToDataSection(TAI->getDataSection(), I);
493 assert(0 && "Unknown linkage type!");
497 EmitAlignment(Align, I);
499 O << name << ":\t\t\t\t" << TAI->getCommentString()
500 << " " << I->getName() << '\n';
502 EmitGlobalConstant(C);
505 O << name << "?\tends\n";
508 // Output linker support code for dllexported globals
509 if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
510 SwitchToDataSection("");
511 O << "; WARNING: The following code is valid only with MASM v8.x"
512 << "and (possible) higher\n"
513 << "; This version of MASM is usually shipped with Microsoft "
514 << "Visual Studio 2005\n"
515 << "; or (possible) further versions. Unfortunately, there is no "
516 << "way to support\n"
517 << "; dllexported symbols in the earlier versions of MASM in fully "
518 << "automatic way\n\n";
519 O << "_drectve\t segment info alias('.drectve')\n";
522 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
523 e = DLLExportedGVs.end();
525 O << "\t db ' /EXPORT:" << i->getKeyData() << ",data'\n";
527 for (StringSet<>::iterator i = DLLExportedFns.begin(),
528 e = DLLExportedFns.end();
530 O << "\t db ' /EXPORT:" << i->getKeyData() << "'\n";
532 if (!DLLExportedGVs.empty() || !DLLExportedFns.empty())
533 O << "_drectve\t ends\n";
535 // Bypass X86SharedAsmPrinter::doFinalization().
536 bool Result = AsmPrinter::doFinalization(M);
537 SwitchToDataSection("");
542 void X86IntelAsmPrinter::EmitString(const ConstantArray *CVA) const {
543 unsigned NumElts = CVA->getNumOperands();
545 // ML does not have escape sequences except '' for '. It also has a maximum
546 // string length of 255.
548 bool inString = false;
549 for (unsigned i = 0; i < NumElts; i++) {
550 int n = cast<ConstantInt>(CVA->getOperand(i))->getZExtValue() & 255;
554 if (n >= 32 && n <= 127) {
581 len += 1 + (n > 9) + (n > 99);
602 // Include the auto-generated portion of the assembly writer.
603 #include "X86GenAsmWriter1.inc"