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