another missed SSE optimization
[oota-llvm.git] / lib / Target / X86 / X86IntelAsmPrinter.cpp
1 //===-- X86IntelAsmPrinter.cpp - Convert X86 LLVM code to Intel assembly --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 Intel format assembly language.
12 // This printer is the output mechanism used by `llc'.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "asm-printer"
17 #include "X86IntelAsmPrinter.h"
18 #include "X86TargetAsmInfo.h"
19 #include "X86.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Module.h"
23 #include "llvm/Assembly/Writer.h"
24 #include "llvm/Support/Mangler.h"
25 #include "llvm/Target/TargetAsmInfo.h"
26 #include "llvm/Target/TargetOptions.h"
27 #include "llvm/ADT/Statistic.h"
28 using namespace llvm;
29
30 STATISTIC(EmittedInsts, "Number of machine instrs printed");
31
32 std::string X86IntelAsmPrinter::getSectionForFunction(const Function &F) const {
33   // Intel asm always emits functions to _text.
34   return "_text";
35 }
36
37 /// runOnMachineFunction - This uses the printMachineInstruction()
38 /// method to print assembly for each instruction.
39 ///
40 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
41   SetupMachineFunction(MF);
42   O << "\n\n";
43
44   // Print out constants referenced by the function
45   EmitConstantPool(MF.getConstantPool());
46
47   // Print out labels for the function.
48   const Function *F = MF.getFunction();
49   unsigned CC = F->getCallingConv();
50
51   // Populate function information map.  Actually, We don't want to populate
52   // non-stdcall or non-fastcall functions' information right now.
53   if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
54     FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
55
56   X86SharedAsmPrinter::decorateName(CurrentFnName, F);
57
58   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
59
60   switch (F->getLinkage()) {
61   default: assert(0 && "Unsupported linkage type!");
62   case Function::InternalLinkage:
63     EmitAlignment(4);
64     break;    
65   case Function::DLLExportLinkage:
66     DLLExportedFns.insert(CurrentFnName);
67     //FALLS THROUGH
68   case Function::ExternalLinkage:
69     O << "\tpublic " << CurrentFnName << "\n";
70     EmitAlignment(4);
71     break;    
72   }
73   
74   O << CurrentFnName << "\tproc near\n";
75   
76   // Print out code for the function.
77   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
78        I != E; ++I) {
79     // Print a label for the basic block if there are any predecessors.
80     if (I->pred_begin() != I->pred_end()) {
81       printBasicBlockLabel(I, true);
82       O << '\n';
83     }
84     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
85          II != E; ++II) {
86       // Print the assembly for the instruction.
87       O << "\t";
88       printMachineInstruction(II);
89     }
90   }
91
92   // Print out jump tables referenced by the function.
93   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
94
95   O << CurrentFnName << "\tendp\n";
96
97   // We didn't modify anything.
98   return false;
99 }
100
101 void X86IntelAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
102   unsigned char value = MI->getOperand(Op).getImmedValue();
103   assert(value <= 7 && "Invalid ssecc argument!");
104   switch (value) {
105   case 0: O << "eq"; break;
106   case 1: O << "lt"; break;
107   case 2: O << "le"; break;
108   case 3: O << "unord"; break;
109   case 4: O << "neq"; break;
110   case 5: O << "nlt"; break;
111   case 6: O << "nle"; break;
112   case 7: O << "ord"; break;
113   }
114 }
115
116 void X86IntelAsmPrinter::printOp(const MachineOperand &MO, 
117                                  const char *Modifier) {
118   const MRegisterInfo &RI = *TM.getRegisterInfo();
119   switch (MO.getType()) {
120   case MachineOperand::MO_Register: {      
121     if (MRegisterInfo::isPhysicalRegister(MO.getReg())) {
122       unsigned Reg = MO.getReg();
123       if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
124         MVT::ValueType VT = (strcmp(Modifier,"subreg64") == 0) ?
125           MVT::i64 : ((strcmp(Modifier, "subreg32") == 0) ? MVT::i32 :
126                       ((strcmp(Modifier,"subreg16") == 0) ? MVT::i16 :MVT::i8));
127         Reg = getX86SubSuperRegister(Reg, VT);
128       }
129       O << RI.get(Reg).Name;
130     } else
131       O << "reg" << MO.getReg();
132     return;
133   }
134   case MachineOperand::MO_Immediate:
135     O << MO.getImmedValue();
136     return;
137   case MachineOperand::MO_MachineBasicBlock:
138     printBasicBlockLabel(MO.getMachineBasicBlock());
139     return;
140   case MachineOperand::MO_JumpTableIndex: {
141     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
142     if (!isMemOp) O << "OFFSET ";
143     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
144       << "_" << MO.getJumpTableIndex();
145     return;
146   }    
147   case MachineOperand::MO_ConstantPoolIndex: {
148     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
149     if (!isMemOp) O << "OFFSET ";
150     O << "[" << TAI->getPrivateGlobalPrefix() << "CPI"
151       << getFunctionNumber() << "_" << MO.getConstantPoolIndex();
152     int Offset = MO.getOffset();
153     if (Offset > 0)
154       O << " + " << Offset;
155     else if (Offset < 0)
156       O << Offset;
157     O << "]";
158     return;
159   }
160   case MachineOperand::MO_GlobalAddress: {
161     bool isCallOp = Modifier && !strcmp(Modifier, "call");
162     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
163     GlobalValue *GV = MO.getGlobal();    
164     std::string Name = Mang->getValueName(GV);
165
166     X86SharedAsmPrinter::decorateName(Name, GV);
167
168     if (!isMemOp && !isCallOp) O << "OFFSET ";
169     if (GV->hasDLLImportLinkage()) {
170       // FIXME: This should be fixed with full support of stdcall & fastcall
171       // CC's
172       O << "__imp_";          
173     } 
174     O << Name;
175     int Offset = MO.getOffset();
176     if (Offset > 0)
177       O << " + " << Offset;
178     else if (Offset < 0)
179       O << Offset;
180     return;
181   }
182   case MachineOperand::MO_ExternalSymbol: {
183     bool isCallOp = Modifier && !strcmp(Modifier, "call");
184     if (!isCallOp) O << "OFFSET ";
185     O << TAI->getGlobalPrefix() << MO.getSymbolName();
186     return;
187   }
188   default:
189     O << "<unknown operand type>"; return;
190   }
191 }
192
193 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
194                                            const char *Modifier) {
195   assert(isMem(MI, Op) && "Invalid memory reference!");
196
197   const MachineOperand &BaseReg  = MI->getOperand(Op);
198   int ScaleVal                   = MI->getOperand(Op+1).getImmedValue();
199   const MachineOperand &IndexReg = MI->getOperand(Op+2);
200   const MachineOperand &DispSpec = MI->getOperand(Op+3);
201
202   O << "[";
203   bool NeedPlus = false;
204   if (BaseReg.getReg()) {
205     printOp(BaseReg, Modifier);
206     NeedPlus = true;
207   }
208
209   if (IndexReg.getReg()) {
210     if (NeedPlus) O << " + ";
211     if (ScaleVal != 1)
212       O << ScaleVal << "*";
213     printOp(IndexReg, Modifier);
214     NeedPlus = true;
215   }
216
217   if (DispSpec.isGlobalAddress() || DispSpec.isConstantPoolIndex() ||
218       DispSpec.isJumpTableIndex()) {
219     if (NeedPlus)
220       O << " + ";
221     printOp(DispSpec, "mem");
222   } else {
223     int DispVal = DispSpec.getImmedValue();
224     if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
225       if (NeedPlus)
226         if (DispVal > 0)
227           O << " + ";
228         else {
229           O << " - ";
230           DispVal = -DispVal;
231         }
232       O << DispVal;
233     }
234   }
235   O << "]";
236 }
237
238 void X86IntelAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
239   O << "\"L" << getFunctionNumber() << "$pb\"\n";
240   O << "\"L" << getFunctionNumber() << "$pb\":";
241 }
242
243 bool X86IntelAsmPrinter::printAsmMRegister(const MachineOperand &MO,
244                                            const char Mode) {
245   const MRegisterInfo &RI = *TM.getRegisterInfo();
246   unsigned Reg = MO.getReg();
247   switch (Mode) {
248   default: return true;  // Unknown mode.
249   case 'b': // Print QImode register
250     Reg = getX86SubSuperRegister(Reg, MVT::i8);
251     break;
252   case 'h': // Print QImode high register
253     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
254     break;
255   case 'w': // Print HImode register
256     Reg = getX86SubSuperRegister(Reg, MVT::i16);
257     break;
258   case 'k': // Print SImode register
259     Reg = getX86SubSuperRegister(Reg, MVT::i32);
260     break;
261   }
262
263   O << '%' << RI.get(Reg).Name;
264   return false;
265 }
266
267 /// PrintAsmOperand - Print out an operand for an inline asm expression.
268 ///
269 bool X86IntelAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
270                                          unsigned AsmVariant, 
271                                          const char *ExtraCode) {
272   // Does this asm operand have a single letter operand modifier?
273   if (ExtraCode && ExtraCode[0]) {
274     if (ExtraCode[1] != 0) return true; // Unknown modifier.
275     
276     switch (ExtraCode[0]) {
277     default: return true;  // Unknown modifier.
278     case 'b': // Print QImode register
279     case 'h': // Print QImode high register
280     case 'w': // Print HImode register
281     case 'k': // Print SImode register
282       return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
283     }
284   }
285   
286   printOperand(MI, OpNo);
287   return false;
288 }
289
290 bool X86IntelAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
291                                                unsigned OpNo,
292                                                unsigned AsmVariant, 
293                                                const char *ExtraCode) {
294   if (ExtraCode && ExtraCode[0])
295     return true; // Unknown modifier.
296   printMemReference(MI, OpNo);
297   return false;
298 }
299
300 /// printMachineInstruction -- Print out a single X86 LLVM instruction
301 /// MI in Intel syntax to the current output stream.
302 ///
303 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
304   ++EmittedInsts;
305
306   // See if a truncate instruction can be turned into a nop.
307   switch (MI->getOpcode()) {
308   default: break;
309   case X86::TRUNC_64to32:
310   case X86::TRUNC_64to16:
311   case X86::TRUNC_32to16:
312   case X86::TRUNC_32to8:
313   case X86::TRUNC_16to8:
314   case X86::TRUNC_32_to8:
315   case X86::TRUNC_16_to8: {
316     const MachineOperand &MO0 = MI->getOperand(0);
317     const MachineOperand &MO1 = MI->getOperand(1);
318     unsigned Reg0 = MO0.getReg();
319     unsigned Reg1 = MO1.getReg();
320     unsigned Opc = MI->getOpcode();
321     if (Opc == X86::TRUNC_64to32)
322       Reg1 = getX86SubSuperRegister(Reg1, MVT::i32);
323     else if (Opc == X86::TRUNC_32to16 || Opc == X86::TRUNC_64to16)
324       Reg1 = getX86SubSuperRegister(Reg1, MVT::i16);
325     else
326       Reg1 = getX86SubSuperRegister(Reg1, MVT::i8);
327     O << TAI->getCommentString() << " TRUNCATE ";
328     if (Reg0 != Reg1)
329       O << "\n\t";
330     break;
331   }
332   case X86::PsMOVZX64rr32:
333     O << TAI->getCommentString() << " ZERO-EXTEND " << "\n\t";
334     break;
335   }
336
337   // Call the autogenerated instruction printer routines.
338   printInstruction(MI);
339 }
340
341 bool X86IntelAsmPrinter::doInitialization(Module &M) {
342   X86SharedAsmPrinter::doInitialization(M);
343   
344   Mang->markCharUnacceptable('.');
345
346   O << "\t.686\n\t.model flat\n\n";
347
348   // Emit declarations for external functions.
349   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
350     if (I->isDeclaration()) {
351       std::string Name = Mang->getValueName(I);
352       X86SharedAsmPrinter::decorateName(Name, I);
353
354       O << "\textern " ;
355       if (I->hasDLLImportLinkage()) {
356         O << "__imp_";
357       }      
358       O << Name << ":near\n";
359     }
360   
361   // Emit declarations for external globals.  Note that VC++ always declares
362   // external globals to have type byte, and if that's good enough for VC++...
363   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
364        I != E; ++I) {
365     if (I->isDeclaration()) {
366       std::string Name = Mang->getValueName(I);
367
368       O << "\textern " ;
369       if (I->hasDLLImportLinkage()) {
370         O << "__imp_";
371       }      
372       O << Name << ":byte\n";
373     }
374   }
375
376   return false;
377 }
378
379 bool X86IntelAsmPrinter::doFinalization(Module &M) {
380   const TargetData *TD = TM.getTargetData();
381
382   // Print out module-level global variables here.
383   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
384        I != E; ++I) {
385     if (I->isDeclaration()) continue;   // External global require no code
386     
387     // Check to see if this is a special global used by LLVM, if so, emit it.
388     if (EmitSpecialLLVMGlobal(I))
389       continue;
390     
391     std::string name = Mang->getValueName(I);
392     Constant *C = I->getInitializer();
393     unsigned Align = TD->getPreferredAlignmentLog(I);
394     bool bCustomSegment = false;
395
396     switch (I->getLinkage()) {
397     case GlobalValue::LinkOnceLinkage:
398     case GlobalValue::WeakLinkage:
399       SwitchToDataSection("");
400       O << name << "?\tsegment common 'COMMON'\n";
401       bCustomSegment = true;
402       // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
403       // are also available.
404       break;
405     case GlobalValue::AppendingLinkage:
406       SwitchToDataSection("");
407       O << name << "?\tsegment public 'DATA'\n";
408       bCustomSegment = true;
409       // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
410       // are also available.
411       break;
412     case GlobalValue::DLLExportLinkage:
413       DLLExportedGVs.insert(name);
414       // FALL THROUGH
415     case GlobalValue::ExternalLinkage:
416       O << "\tpublic " << name << "\n";
417       // FALL THROUGH
418     case GlobalValue::InternalLinkage:
419       SwitchToDataSection(TAI->getDataSection(), I);
420       break;
421     default:
422       assert(0 && "Unknown linkage type!");
423     }
424
425     if (!bCustomSegment)
426       EmitAlignment(Align, I);
427
428     O << name << ":\t\t\t\t" << TAI->getCommentString()
429       << " " << I->getName() << '\n';
430
431     EmitGlobalConstant(C);
432
433     if (bCustomSegment)
434       O << name << "?\tends\n";
435   }
436
437     // Output linker support code for dllexported globals
438   if ((DLLExportedGVs.begin() != DLLExportedGVs.end()) ||
439       (DLLExportedFns.begin() != DLLExportedFns.end())) {
440     SwitchToDataSection("");
441     O << "; WARNING: The following code is valid only with MASM v8.x and (possible) higher\n"
442       << "; This version of MASM is usually shipped with Microsoft Visual Studio 2005\n"
443       << "; or (possible) further versions. Unfortunately, there is no way to support\n"
444       << "; dllexported symbols in the earlier versions of MASM in fully automatic way\n\n";
445     O << "_drectve\t segment info alias('.drectve')\n";
446   }
447
448   for (std::set<std::string>::iterator i = DLLExportedGVs.begin(),
449          e = DLLExportedGVs.end();
450          i != e; ++i) {
451     O << "\t db ' /EXPORT:" << *i << ",data'\n";
452   }    
453
454   for (std::set<std::string>::iterator i = DLLExportedFns.begin(),
455          e = DLLExportedFns.end();
456          i != e; ++i) {
457     O << "\t db ' /EXPORT:" << *i << "'\n";
458   }    
459
460   if ((DLLExportedGVs.begin() != DLLExportedGVs.end()) ||
461       (DLLExportedFns.begin() != DLLExportedFns.end())) {
462     O << "_drectve\t ends\n";    
463   }
464   
465   // Bypass X86SharedAsmPrinter::doFinalization().
466   AsmPrinter::doFinalization(M);
467   SwitchToDataSection("");
468   O << "\tend\n";
469   return false; // success
470 }
471
472 void X86IntelAsmPrinter::EmitString(const ConstantArray *CVA) const {
473   unsigned NumElts = CVA->getNumOperands();
474   if (NumElts) {
475     // ML does not have escape sequences except '' for '.  It also has a maximum
476     // string length of 255.
477     unsigned len = 0;
478     bool inString = false;
479     for (unsigned i = 0; i < NumElts; i++) {
480       int n = cast<ConstantInt>(CVA->getOperand(i))->getZExtValue() & 255;
481       if (len == 0)
482         O << "\tdb ";
483
484       if (n >= 32 && n <= 127) {
485         if (!inString) {
486           if (len > 0) {
487             O << ",'";
488             len += 2;
489           } else {
490             O << "'";
491             len++;
492           }
493           inString = true;
494         }
495         if (n == '\'') {
496           O << "'";
497           len++;
498         }
499         O << char(n);
500       } else {
501         if (inString) {
502           O << "'";
503           len++;
504           inString = false;
505         }
506         if (len > 0) {
507           O << ",";
508           len++;
509         }
510         O << n;
511         len += 1 + (n > 9) + (n > 99);
512       }
513
514       if (len > 60) {
515         if (inString) {
516           O << "'";
517           inString = false;
518         }
519         O << "\n";
520         len = 0;
521       }
522     }
523
524     if (len > 0) {
525       if (inString)
526         O << "'";
527       O << "\n";
528     }
529   }
530 }
531
532 // Include the auto-generated portion of the assembly writer.
533 #include "X86GenAsmWriter1.inc"