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, Attribute::ByVal))
58 Ty = cast<PointerType>(Ty)->getElementType();
60 // Size should be aligned to DWORD boundary
61 Size += ((TD->getTypePaddedSize(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");
120 /// runOnMachineFunction - This uses the printMachineInstruction()
121 /// method to print assembly for each instruction.
123 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
124 SetupMachineFunction(MF);
127 // Print out constants referenced by the function
128 EmitConstantPool(MF.getConstantPool());
130 // Print out labels for the function.
131 const Function *F = MF.getFunction();
132 unsigned CC = F->getCallingConv();
134 // Populate function information map. Actually, We don't want to populate
135 // non-stdcall or non-fastcall functions' information right now.
136 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
137 FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
139 decorateName(CurrentFnName, F);
141 SwitchToTextSection("_text", F);
143 unsigned FnAlign = 4;
144 if (F->hasFnAttr(Attribute::OptimizeForSize))
146 switch (F->getLinkage()) {
147 default: assert(0 && "Unsupported linkage type!");
148 case Function::PrivateLinkage:
149 case Function::InternalLinkage:
150 EmitAlignment(FnAlign);
152 case Function::DLLExportLinkage:
153 DLLExportedFns.insert(CurrentFnName);
155 case Function::ExternalLinkage:
156 O << "\tpublic " << CurrentFnName << "\n";
157 EmitAlignment(FnAlign);
161 O << CurrentFnName << "\tproc near\n";
163 // Print out code for the function.
164 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
166 // Print a label for the basic block if there are any predecessors.
167 if (!I->pred_empty()) {
168 printBasicBlockLabel(I, true, true);
171 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
173 // Print the assembly for the instruction.
174 printMachineInstruction(II);
178 // Print out jump tables referenced by the function.
179 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
181 O << CurrentFnName << "\tendp\n";
185 // We didn't modify anything.
189 void X86IntelAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
190 unsigned char value = MI->getOperand(Op).getImm();
191 assert(value <= 7 && "Invalid ssecc argument!");
193 case 0: O << "eq"; break;
194 case 1: O << "lt"; break;
195 case 2: O << "le"; break;
196 case 3: O << "unord"; break;
197 case 4: O << "neq"; break;
198 case 5: O << "nlt"; break;
199 case 6: O << "nle"; break;
200 case 7: O << "ord"; break;
204 void X86IntelAsmPrinter::printOp(const MachineOperand &MO,
205 const char *Modifier) {
206 switch (MO.getType()) {
207 case MachineOperand::MO_Register: {
208 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
209 unsigned Reg = MO.getReg();
210 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
211 MVT VT = (strcmp(Modifier,"subreg64") == 0) ?
212 MVT::i64 : ((strcmp(Modifier, "subreg32") == 0) ? MVT::i32 :
213 ((strcmp(Modifier,"subreg16") == 0) ? MVT::i16 :MVT::i8));
214 Reg = getX86SubSuperRegister(Reg, VT);
216 O << TRI->getName(Reg);
218 O << "reg" << MO.getReg();
221 case MachineOperand::MO_Immediate:
224 case MachineOperand::MO_MachineBasicBlock:
225 printBasicBlockLabel(MO.getMBB());
227 case MachineOperand::MO_JumpTableIndex: {
228 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
229 if (!isMemOp) O << "OFFSET ";
230 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
231 << "_" << MO.getIndex();
234 case MachineOperand::MO_ConstantPoolIndex: {
235 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
236 if (!isMemOp) O << "OFFSET ";
237 O << "[" << TAI->getPrivateGlobalPrefix() << "CPI"
238 << getFunctionNumber() << "_" << MO.getIndex();
239 printOffset(MO.getOffset());
243 case MachineOperand::MO_GlobalAddress: {
244 bool isCallOp = Modifier && !strcmp(Modifier, "call");
245 bool isMemOp = Modifier && !strcmp(Modifier, "mem");
246 GlobalValue *GV = MO.getGlobal();
247 std::string Name = Mang->getValueName(GV);
249 decorateName(Name, GV);
251 if (!isMemOp && !isCallOp) O << "OFFSET ";
252 if (GV->hasDLLImportLinkage()) {
253 // FIXME: This should be fixed with full support of stdcall & fastcall
258 printOffset(MO.getOffset());
261 case MachineOperand::MO_ExternalSymbol: {
262 bool isCallOp = Modifier && !strcmp(Modifier, "call");
263 if (!isCallOp) O << "OFFSET ";
264 O << TAI->getGlobalPrefix() << MO.getSymbolName();
268 O << "<unknown operand type>"; return;
272 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
273 const char *Modifier) {
274 assert(isMem(MI, Op) && "Invalid memory reference!");
276 const MachineOperand &BaseReg = MI->getOperand(Op);
277 int ScaleVal = MI->getOperand(Op+1).getImm();
278 const MachineOperand &IndexReg = MI->getOperand(Op+2);
279 const MachineOperand &DispSpec = MI->getOperand(Op+3);
282 bool NeedPlus = false;
283 if (BaseReg.getReg()) {
284 printOp(BaseReg, Modifier);
288 if (IndexReg.getReg()) {
289 if (NeedPlus) O << " + ";
291 O << ScaleVal << "*";
292 printOp(IndexReg, Modifier);
296 if (DispSpec.isGlobal() || DispSpec.isCPI() ||
300 printOp(DispSpec, "mem");
302 int DispVal = DispSpec.getImm();
303 if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
318 void X86IntelAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
319 const MachineBasicBlock *MBB) const {
320 if (!TAI->getSetDirective())
323 O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
324 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
325 printBasicBlockLabel(MBB, false, false, false);
326 O << '-' << "\"L" << getFunctionNumber() << "$pb\"'\n";
329 void X86IntelAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
330 O << "\"L" << getFunctionNumber() << "$pb\"\n";
331 O << "\"L" << getFunctionNumber() << "$pb\":";
334 bool X86IntelAsmPrinter::printAsmMRegister(const MachineOperand &MO,
336 unsigned Reg = MO.getReg();
338 default: return true; // Unknown mode.
339 case 'b': // Print QImode register
340 Reg = getX86SubSuperRegister(Reg, MVT::i8);
342 case 'h': // Print QImode high register
343 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
345 case 'w': // Print HImode register
346 Reg = getX86SubSuperRegister(Reg, MVT::i16);
348 case 'k': // Print SImode register
349 Reg = getX86SubSuperRegister(Reg, MVT::i32);
353 O << '%' << TRI->getName(Reg);
357 /// PrintAsmOperand - Print out an operand for an inline asm expression.
359 bool X86IntelAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
361 const char *ExtraCode) {
362 // Does this asm operand have a single letter operand modifier?
363 if (ExtraCode && ExtraCode[0]) {
364 if (ExtraCode[1] != 0) return true; // Unknown modifier.
366 switch (ExtraCode[0]) {
367 default: return true; // Unknown modifier.
368 case 'b': // Print QImode register
369 case 'h': // Print QImode high register
370 case 'w': // Print HImode register
371 case 'k': // Print SImode register
372 return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
376 printOperand(MI, OpNo);
380 bool X86IntelAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
383 const char *ExtraCode) {
384 if (ExtraCode && ExtraCode[0])
385 return true; // Unknown modifier.
386 printMemReference(MI, OpNo);
390 /// printMachineInstruction -- Print out a single X86 LLVM instruction
391 /// MI in Intel syntax to the current output stream.
393 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
396 // Call the autogenerated instruction printer routines.
397 printInstruction(MI);
400 bool X86IntelAsmPrinter::doInitialization(Module &M) {
401 bool Result = AsmPrinter::doInitialization(M);
403 Mang->markCharUnacceptable('.');
405 O << "\t.686\n\t.model flat\n\n";
407 // Emit declarations for external functions.
408 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
409 if (I->isDeclaration()) {
410 std::string Name = Mang->getValueName(I);
411 decorateName(Name, I);
414 if (I->hasDLLImportLinkage()) {
417 O << Name << ":near\n";
420 // Emit declarations for external globals. Note that VC++ always declares
421 // external globals to have type byte, and if that's good enough for VC++...
422 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
424 if (I->isDeclaration()) {
425 std::string Name = Mang->getValueName(I);
428 if (I->hasDLLImportLinkage()) {
431 O << Name << ":byte\n";
438 bool X86IntelAsmPrinter::doFinalization(Module &M) {
439 const TargetData *TD = TM.getTargetData();
441 // Print out module-level global variables here.
442 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
444 if (I->isDeclaration()) continue; // External global require no code
446 // Check to see if this is a special global used by LLVM, if so, emit it.
447 if (EmitSpecialLLVMGlobal(I))
450 std::string name = Mang->getValueName(I);
451 Constant *C = I->getInitializer();
452 unsigned Align = TD->getPreferredAlignmentLog(I);
453 bool bCustomSegment = false;
455 switch (I->getLinkage()) {
456 case GlobalValue::CommonLinkage:
457 case GlobalValue::LinkOnceLinkage:
458 case GlobalValue::WeakLinkage:
459 SwitchToDataSection("");
460 O << name << "?\tsegment common 'COMMON'\n";
461 bCustomSegment = true;
462 // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
463 // are also available.
465 case GlobalValue::AppendingLinkage:
466 SwitchToDataSection("");
467 O << name << "?\tsegment public 'DATA'\n";
468 bCustomSegment = true;
469 // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
470 // are also available.
472 case GlobalValue::DLLExportLinkage:
473 DLLExportedGVs.insert(name);
475 case GlobalValue::ExternalLinkage:
476 O << "\tpublic " << name << "\n";
478 case GlobalValue::InternalLinkage:
479 SwitchToSection(TAI->getDataSection());
482 assert(0 && "Unknown linkage type!");
486 EmitAlignment(Align, I);
488 O << name << ":\t\t\t\t" << TAI->getCommentString()
489 << " " << I->getName() << '\n';
491 EmitGlobalConstant(C);
494 O << name << "?\tends\n";
497 // Output linker support code for dllexported globals
498 if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
499 SwitchToDataSection("");
500 O << "; WARNING: The following code is valid only with MASM v8.x"
501 << "and (possible) higher\n"
502 << "; This version of MASM is usually shipped with Microsoft "
503 << "Visual Studio 2005\n"
504 << "; or (possible) further versions. Unfortunately, there is no "
505 << "way to support\n"
506 << "; dllexported symbols in the earlier versions of MASM in fully "
507 << "automatic way\n\n";
508 O << "_drectve\t segment info alias('.drectve')\n";
511 for (StringSet<>::iterator i = DLLExportedGVs.begin(),
512 e = DLLExportedGVs.end();
514 O << "\t db ' /EXPORT:" << i->getKeyData() << ",data'\n";
516 for (StringSet<>::iterator i = DLLExportedFns.begin(),
517 e = DLLExportedFns.end();
519 O << "\t db ' /EXPORT:" << i->getKeyData() << "'\n";
521 if (!DLLExportedGVs.empty() || !DLLExportedFns.empty())
522 O << "_drectve\t ends\n";
524 // Bypass X86SharedAsmPrinter::doFinalization().
525 bool Result = AsmPrinter::doFinalization(M);
526 SwitchToDataSection("");
531 void X86IntelAsmPrinter::EmitString(const ConstantArray *CVA) const {
532 unsigned NumElts = CVA->getNumOperands();
534 // ML does not have escape sequences except '' for '. It also has a maximum
535 // string length of 255.
537 bool inString = false;
538 for (unsigned i = 0; i < NumElts; i++) {
539 int n = cast<ConstantInt>(CVA->getOperand(i))->getZExtValue() & 255;
543 if (n >= 32 && n <= 127) {
570 len += 1 + (n > 9) + (n > 99);
591 // Include the auto-generated portion of the assembly writer.
592 #include "X86GenAsmWriter1.inc"