fc952273ff247d0db4341163d4ea4cd455c7afe9
[oota-llvm.git] / lib / Target / PowerPC / PPCAsmPrinter.cpp
1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC 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 PowerPC assembly language. This printer is
12 // the output mechanism used by `llc'.
13 //
14 // Documentation at http://developer.apple.com/documentation/DeveloperTools/
15 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "asmprinter"
20 #include "PPC.h"
21 #include "PPCPredicates.h"
22 #include "PPCTargetMachine.h"
23 #include "PPCSubtarget.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Module.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/CodeGen/AsmPrinter.h"
29 #include "llvm/CodeGen/DwarfWriter.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/Support/Mangler.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Target/TargetAsmInfo.h"
39 #include "llvm/Target/MRegisterInfo.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/ADT/Statistic.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include <set>
45 using namespace llvm;
46
47 STATISTIC(EmittedInsts, "Number of machine instrs printed");
48
49 namespace {
50   struct VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
51     std::set<std::string> FnStubs, GVStubs;
52     const PPCSubtarget &Subtarget;
53
54     PPCAsmPrinter(std::ostream &O, TargetMachine &TM, const TargetAsmInfo *T)
55       : AsmPrinter(O, TM, T), Subtarget(TM.getSubtarget<PPCSubtarget>()) {
56     }
57
58     virtual const char *getPassName() const {
59       return "PowerPC Assembly Printer";
60     }
61
62     PPCTargetMachine &getTM() {
63       return static_cast<PPCTargetMachine&>(TM);
64     }
65
66     unsigned enumRegToMachineReg(unsigned enumReg) {
67       switch (enumReg) {
68       default: assert(0 && "Unhandled register!"); break;
69       case PPC::CR0:  return  0;
70       case PPC::CR1:  return  1;
71       case PPC::CR2:  return  2;
72       case PPC::CR3:  return  3;
73       case PPC::CR4:  return  4;
74       case PPC::CR5:  return  5;
75       case PPC::CR6:  return  6;
76       case PPC::CR7:  return  7;
77       }
78       abort();
79     }
80
81     /// printInstruction - This method is automatically generated by tablegen
82     /// from the instruction set description.  This method returns true if the
83     /// machine instruction was sufficiently described to print it, otherwise it
84     /// returns false.
85     bool printInstruction(const MachineInstr *MI);
86
87     void printMachineInstruction(const MachineInstr *MI);
88     void printOp(const MachineOperand &MO);
89     
90     /// stripRegisterPrefix - This method strips the character prefix from a
91     /// register name so that only the number is left.  Used by for linux asm.
92     const char *stripRegisterPrefix(const char *RegName) {
93       switch (RegName[0]) {
94       case 'r':
95       case 'f':
96       case 'v': return RegName + 1;
97       case 'c': if (RegName[1] == 'r') return RegName + 2;
98       }
99        
100       return RegName;
101     }
102     
103     /// printRegister - Print register according to target requirements.
104     ///
105     void printRegister(const MachineOperand &MO, bool R0AsZero) {
106       unsigned RegNo = MO.getReg();
107       assert(MRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
108       
109       // If we should use 0 for R0.
110       if (R0AsZero && RegNo == PPC::R0) {
111         O << "0";
112         return;
113       }
114       
115       const char *RegName = TM.getRegisterInfo()->get(RegNo).Name;
116       // Linux assembler (Others?) does not take register mnemonics.
117       // FIXME - What about special registers used in mfspr/mtspr?
118       if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
119       O << RegName;
120     }
121
122     void printOperand(const MachineInstr *MI, unsigned OpNo) {
123       const MachineOperand &MO = MI->getOperand(OpNo);
124       if (MO.isRegister()) {
125         printRegister(MO, false);
126       } else if (MO.isImmediate()) {
127         O << MO.getImmedValue();
128       } else {
129         printOp(MO);
130       }
131     }
132     
133     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
134                          unsigned AsmVariant, const char *ExtraCode);
135     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
136                                unsigned AsmVariant, const char *ExtraCode);
137     
138     
139     void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
140       char value = MI->getOperand(OpNo).getImmedValue();
141       value = (value << (32-5)) >> (32-5);
142       O << (int)value;
143     }
144     void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
145       unsigned char value = MI->getOperand(OpNo).getImmedValue();
146       assert(value <= 31 && "Invalid u5imm argument!");
147       O << (unsigned int)value;
148     }
149     void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
150       unsigned char value = MI->getOperand(OpNo).getImmedValue();
151       assert(value <= 63 && "Invalid u6imm argument!");
152       O << (unsigned int)value;
153     }
154     void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
155       O << (short)MI->getOperand(OpNo).getImmedValue();
156     }
157     void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
158       O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
159     }
160     void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
161       if (MI->getOperand(OpNo).isImmediate()) {
162         O << (short)(MI->getOperand(OpNo).getImmedValue()*4);
163       } else {
164         O << "lo16(";
165         printOp(MI->getOperand(OpNo));
166         if (TM.getRelocationModel() == Reloc::PIC_)
167           O << "-\"L" << getFunctionNumber() << "$pb\")";
168         else
169           O << ')';
170       }
171     }
172     void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
173       // Branches can take an immediate operand.  This is used by the branch
174       // selection pass to print $+8, an eight byte displacement from the PC.
175       if (MI->getOperand(OpNo).isImmediate()) {
176         O << "$+" << MI->getOperand(OpNo).getImmedValue()*4;
177       } else {
178         printOp(MI->getOperand(OpNo));
179       }
180     }
181     void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
182       const MachineOperand &MO = MI->getOperand(OpNo);
183       if (TM.getRelocationModel() != Reloc::Static) {
184         if (MO.getType() == MachineOperand::MO_GlobalAddress) {
185           GlobalValue *GV = MO.getGlobal();
186           if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
187                 GV->hasLinkOnceLinkage()))) {
188             // Dynamically-resolved functions need a stub for the function.
189             std::string Name = Mang->getValueName(GV);
190             FnStubs.insert(Name);
191             O << "L" << Name << "$stub";
192             if (GV->hasExternalWeakLinkage())
193               ExtWeakSymbols.insert(GV);
194             return;
195           }
196         }
197         if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
198           std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
199           FnStubs.insert(Name);
200           O << "L" << Name << "$stub";
201           return;
202         }
203       }
204       
205       printOp(MI->getOperand(OpNo));
206     }
207     void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
208      O << (int)MI->getOperand(OpNo).getImmedValue()*4;
209     }
210     void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
211       O << "\"L" << getFunctionNumber() << "$pb\"\n";
212       O << "\"L" << getFunctionNumber() << "$pb\":";
213     }
214     void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
215       if (MI->getOperand(OpNo).isImmediate()) {
216         printS16ImmOperand(MI, OpNo);
217       } else {
218         O << "ha16(";
219         printOp(MI->getOperand(OpNo));
220         if (TM.getRelocationModel() == Reloc::PIC_)
221           O << "-\"L" << getFunctionNumber() << "$pb\")";
222         else
223           O << ')';
224       }
225     }
226     void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
227       if (MI->getOperand(OpNo).isImmediate()) {
228         printS16ImmOperand(MI, OpNo);
229       } else {
230         O << "lo16(";
231         printOp(MI->getOperand(OpNo));
232         if (TM.getRelocationModel() == Reloc::PIC_)
233           O << "-\"L" << getFunctionNumber() << "$pb\")";
234         else
235           O << ')';
236       }
237     }
238     void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
239       unsigned CCReg = MI->getOperand(OpNo).getReg();
240       unsigned RegNo = enumRegToMachineReg(CCReg);
241       O << (0x80 >> RegNo);
242     }
243     // The new addressing mode printers.
244     void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
245       printSymbolLo(MI, OpNo);
246       O << '(';
247       if (MI->getOperand(OpNo+1).isRegister() && 
248           MI->getOperand(OpNo+1).getReg() == PPC::R0)
249         O << "0";
250       else
251         printOperand(MI, OpNo+1);
252       O << ')';
253     }
254     void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
255       if (MI->getOperand(OpNo).isImmediate())
256         printS16X4ImmOperand(MI, OpNo);
257       else 
258         printSymbolLo(MI, OpNo);
259       O << '(';
260       if (MI->getOperand(OpNo+1).isRegister() && 
261           MI->getOperand(OpNo+1).getReg() == PPC::R0)
262         O << "0";
263       else
264         printOperand(MI, OpNo+1);
265       O << ')';
266     }
267     
268     void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
269       // When used as the base register, r0 reads constant zero rather than
270       // the value contained in the register.  For this reason, the darwin
271       // assembler requires that we print r0 as 0 (no r) when used as the base.
272       const MachineOperand &MO = MI->getOperand(OpNo);
273       printRegister(MO, true);
274       O << ", ";
275       printOperand(MI, OpNo+1);
276     }
277     
278     void printPredicateOperand(const MachineInstr *MI, unsigned OpNo, 
279                                const char *Modifier);
280     
281     virtual bool runOnMachineFunction(MachineFunction &F) = 0;
282     virtual bool doFinalization(Module &M) = 0;
283
284     virtual void EmitExternalGlobal(const GlobalVariable *GV);
285   };
286
287   /// LinuxAsmPrinter - PowerPC assembly printer, customized for Linux
288   struct VISIBILITY_HIDDEN LinuxAsmPrinter : public PPCAsmPrinter {
289
290     DwarfWriter DW;
291
292     LinuxAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
293                     const TargetAsmInfo *T)
294       : PPCAsmPrinter(O, TM, T), DW(O, this, T) {
295     }
296
297     virtual const char *getPassName() const {
298       return "Linux PPC Assembly Printer";
299     }
300
301     bool runOnMachineFunction(MachineFunction &F);
302     bool doInitialization(Module &M);
303     bool doFinalization(Module &M);
304     
305     void getAnalysisUsage(AnalysisUsage &AU) const {
306       AU.setPreservesAll();
307       AU.addRequired<MachineModuleInfo>();
308       PPCAsmPrinter::getAnalysisUsage(AU);
309     }
310
311     /// getSectionForFunction - Return the section that we should emit the
312     /// specified function body into.
313     virtual std::string getSectionForFunction(const Function &F) const;
314   };
315
316   /// DarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac OS
317   /// X
318   struct VISIBILITY_HIDDEN DarwinAsmPrinter : public PPCAsmPrinter {
319   
320     DwarfWriter DW;
321
322     DarwinAsmPrinter(std::ostream &O, PPCTargetMachine &TM,
323                      const TargetAsmInfo *T)
324       : PPCAsmPrinter(O, TM, T), DW(O, this, T) {
325     }
326
327     virtual const char *getPassName() const {
328       return "Darwin PPC Assembly Printer";
329     }
330     
331     bool runOnMachineFunction(MachineFunction &F);
332     bool doInitialization(Module &M);
333     bool doFinalization(Module &M);
334     
335     void getAnalysisUsage(AnalysisUsage &AU) const {
336       AU.setPreservesAll();
337       AU.addRequired<MachineModuleInfo>();
338       PPCAsmPrinter::getAnalysisUsage(AU);
339     }
340
341     /// getSectionForFunction - Return the section that we should emit the
342     /// specified function body into.
343     virtual std::string getSectionForFunction(const Function &F) const;
344   };
345 } // end of anonymous namespace
346
347 // Include the auto-generated portion of the assembly writer
348 #include "PPCGenAsmWriter.inc"
349
350 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
351   switch (MO.getType()) {
352   case MachineOperand::MO_Immediate:
353     cerr << "printOp() does not handle immediate values\n";
354     abort();
355     return;
356
357   case MachineOperand::MO_MachineBasicBlock:
358     printBasicBlockLabel(MO.getMachineBasicBlock());
359     return;
360   case MachineOperand::MO_JumpTableIndex:
361     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
362       << '_' << MO.getJumpTableIndex();
363     // FIXME: PIC relocation model
364     return;
365   case MachineOperand::MO_ConstantPoolIndex:
366     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
367       << '_' << MO.getConstantPoolIndex();
368     return;
369   case MachineOperand::MO_ExternalSymbol:
370     // Computing the address of an external symbol, not calling it.
371     if (TM.getRelocationModel() != Reloc::Static) {
372       std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
373       GVStubs.insert(Name);
374       O << "L" << Name << "$non_lazy_ptr";
375       return;
376     }
377     O << TAI->getGlobalPrefix() << MO.getSymbolName();
378     return;
379   case MachineOperand::MO_GlobalAddress: {
380     // Computing the address of a global symbol, not calling it.
381     GlobalValue *GV = MO.getGlobal();
382     std::string Name = Mang->getValueName(GV);
383
384     // External or weakly linked global variables need non-lazily-resolved stubs
385     if (TM.getRelocationModel() != Reloc::Static) {
386       if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
387             GV->hasLinkOnceLinkage()))) {
388         GVStubs.insert(Name);
389         O << "L" << Name << "$non_lazy_ptr";
390         return;
391       }
392     }
393     O << Name;
394     
395     if (GV->hasExternalWeakLinkage())
396       ExtWeakSymbols.insert(GV);
397     return;
398   }
399
400   default:
401     O << "<unknown operand type: " << MO.getType() << ">";
402     return;
403   }
404 }
405
406 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
407 ///
408 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
409   std::string Name = getGlobalLinkName(GV);
410   if (TM.getRelocationModel() != Reloc::Static) {
411     GVStubs.insert(Name);
412     O << "L" << Name << "$non_lazy_ptr";
413     return;
414   }
415   O << Name;
416 }
417
418 /// PrintAsmOperand - Print out an operand for an inline asm expression.
419 ///
420 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
421                                     unsigned AsmVariant, 
422                                     const char *ExtraCode) {
423   // Does this asm operand have a single letter operand modifier?
424   if (ExtraCode && ExtraCode[0]) {
425     if (ExtraCode[1] != 0) return true; // Unknown modifier.
426     
427     switch (ExtraCode[0]) {
428     default: return true;  // Unknown modifier.
429     case 'c': // Don't print "$" before a global var name or constant.
430       // PPC never has a prefix.
431       printOperand(MI, OpNo);
432       return false;
433     case 'L': // Write second word of DImode reference.  
434       // Verify that this operand has two consecutive registers.
435       if (!MI->getOperand(OpNo).isRegister() ||
436           OpNo+1 == MI->getNumOperands() ||
437           !MI->getOperand(OpNo+1).isRegister())
438         return true;
439       ++OpNo;   // Return the high-part.
440       break;
441     }
442   }
443   
444   printOperand(MI, OpNo);
445   return false;
446 }
447
448 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
449                                           unsigned AsmVariant, 
450                                           const char *ExtraCode) {
451   if (ExtraCode && ExtraCode[0])
452     return true; // Unknown modifier.
453   if (MI->getOperand(OpNo).isRegister())
454     printMemRegReg(MI, OpNo);
455   else
456     printMemRegImm(MI, OpNo);
457   return false;
458 }
459
460 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo, 
461                                           const char *Modifier) {
462   assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
463   unsigned Code = MI->getOperand(OpNo).getImm();
464   if (!strcmp(Modifier, "cc")) {
465     switch ((PPC::Predicate)Code) {
466     case PPC::PRED_ALWAYS: return; // Don't print anything for always.
467     case PPC::PRED_LT: O << "lt"; return;
468     case PPC::PRED_LE: O << "le"; return;
469     case PPC::PRED_EQ: O << "eq"; return;
470     case PPC::PRED_GE: O << "ge"; return;
471     case PPC::PRED_GT: O << "gt"; return;
472     case PPC::PRED_NE: O << "ne"; return;
473     case PPC::PRED_UN: O << "un"; return;
474     case PPC::PRED_NU: O << "nu"; return;
475     }
476       
477   } else {
478     assert(!strcmp(Modifier, "reg") &&
479            "Need to specify 'cc' or 'reg' as predicate op modifier!");
480     // Don't print the register for 'always'.
481     if (Code == PPC::PRED_ALWAYS) return;
482     printOperand(MI, OpNo+1);
483   }
484 }
485
486
487 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
488 /// the current output stream.
489 ///
490 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
491   ++EmittedInsts;
492
493   // Check for slwi/srwi mnemonics.
494   if (MI->getOpcode() == PPC::RLWINM) {
495     bool FoundMnemonic = false;
496     unsigned char SH = MI->getOperand(2).getImmedValue();
497     unsigned char MB = MI->getOperand(3).getImmedValue();
498     unsigned char ME = MI->getOperand(4).getImmedValue();
499     if (SH <= 31 && MB == 0 && ME == (31-SH)) {
500       O << "slwi "; FoundMnemonic = true;
501     }
502     if (SH <= 31 && MB == (32-SH) && ME == 31) {
503       O << "srwi "; FoundMnemonic = true;
504       SH = 32-SH;
505     }
506     if (FoundMnemonic) {
507       printOperand(MI, 0);
508       O << ", ";
509       printOperand(MI, 1);
510       O << ", " << (unsigned int)SH << "\n";
511       return;
512     }
513   } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
514     if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
515       O << "mr ";
516       printOperand(MI, 0);
517       O << ", ";
518       printOperand(MI, 1);
519       O << "\n";
520       return;
521     }
522   } else if (MI->getOpcode() == PPC::RLDICR) {
523     unsigned char SH = MI->getOperand(2).getImmedValue();
524     unsigned char ME = MI->getOperand(3).getImmedValue();
525     // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
526     if (63-SH == ME) {
527       O << "sldi ";
528       printOperand(MI, 0);
529       O << ", ";
530       printOperand(MI, 1);
531       O << ", " << (unsigned int)SH << "\n";
532       return;
533     }
534   }
535
536   if (printInstruction(MI))
537     return; // Printer was automatically generated
538
539   assert(0 && "Unhandled instruction in asm writer!");
540   abort();
541   return;
542 }
543
544 /// runOnMachineFunction - This uses the printMachineInstruction()
545 /// method to print assembly for each instruction.
546 ///
547 bool LinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
548   DW.SetModuleInfo(&getAnalysis<MachineModuleInfo>());
549
550   SetupMachineFunction(MF);
551   O << "\n\n";
552   
553   // Print out constants referenced by the function
554   EmitConstantPool(MF.getConstantPool());
555
556   // Print out labels for the function.
557   const Function *F = MF.getFunction();
558   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
559   
560   switch (F->getLinkage()) {
561   default: assert(0 && "Unknown linkage type!");
562   case Function::InternalLinkage:  // Symbols default to internal.
563     break;
564   case Function::ExternalLinkage:
565     O << "\t.global\t" << CurrentFnName << '\n'
566       << "\t.type\t" << CurrentFnName << ", @function\n";
567     break;
568   case Function::WeakLinkage:
569   case Function::LinkOnceLinkage:
570     O << "\t.global\t" << CurrentFnName << '\n';
571     O << "\t.weak\t" << CurrentFnName << '\n';
572     break;
573   }
574   
575   if (F->hasHiddenVisibility())
576     if (const char *Directive = TAI->getHiddenDirective())
577       O << Directive << CurrentFnName << "\n";
578   
579   EmitAlignment(2, F);
580   O << CurrentFnName << ":\n";
581
582   // Emit pre-function debug information.
583   DW.BeginFunction(&MF);
584
585   // Print out code for the function.
586   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
587        I != E; ++I) {
588     // Print a label for the basic block.
589     if (I != MF.begin()) {
590       printBasicBlockLabel(I, true);
591       O << '\n';
592     }
593     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
594          II != E; ++II) {
595       // Print the assembly for the instruction.
596       O << "\t";
597       printMachineInstruction(II);
598     }
599   }
600
601   O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << "\n";
602
603   // Print out jump tables referenced by the function.
604   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
605   
606   // Emit post-function debug information.
607   DW.EndFunction();
608   
609   // We didn't modify anything.
610   return false;
611 }
612
613 bool LinuxAsmPrinter::doInitialization(Module &M) {
614   AsmPrinter::doInitialization(M);
615   
616   // GNU as handles section names wrapped in quotes
617   Mang->setUseQuotes(true);
618
619   SwitchToTextSection(TAI->getTextSection());
620   
621   // Emit initial debug information.
622   DW.BeginModule(&M);
623   return false;
624 }
625
626 bool LinuxAsmPrinter::doFinalization(Module &M) {
627   const TargetData *TD = TM.getTargetData();
628
629   // Print out module-level global variables here.
630   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
631        I != E; ++I) {
632     if (!I->hasInitializer()) continue;   // External global require no code
633     
634     // Check to see if this is a special global used by LLVM, if so, emit it.
635     if (EmitSpecialLLVMGlobal(I))
636       continue;
637
638     std::string name = Mang->getValueName(I);
639
640     if (I->hasHiddenVisibility())
641       if (const char *Directive = TAI->getHiddenDirective())
642         O << Directive << name << "\n";
643     
644     Constant *C = I->getInitializer();
645     unsigned Size = TD->getTypeSize(C->getType());
646     unsigned Align = TD->getPreferredAlignmentLog(I);
647
648     if (C->isNullValue() && /* FIXME: Verify correct */
649         (I->hasInternalLinkage() || I->hasWeakLinkage() ||
650          I->hasLinkOnceLinkage() ||
651          (I->hasExternalLinkage() && !I->hasSection()))) {
652       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
653       if (I->hasExternalLinkage()) {
654         O << "\t.global " << name << '\n';
655         O << "\t.type " << name << ", @object\n";
656         //O << "\t.zerofill __DATA, __common, " << name << ", "
657         //  << Size << ", " << Align;
658       } else if (I->hasInternalLinkage()) {
659         SwitchToDataSection("\t.data", I);
660         O << TAI->getLCOMMDirective() << name << "," << Size;
661       } else {
662         SwitchToDataSection("\t.data", I);
663         O << ".comm " << name << "," << Size;
664       }
665       O << "\t\t" << TAI->getCommentString() << " '" << I->getName() << "'\n";
666     } else {
667       switch (I->getLinkage()) {
668       case GlobalValue::LinkOnceLinkage:
669       case GlobalValue::WeakLinkage:
670         O << "\t.global " << name << '\n'
671           << "\t.type " << name << ", @object\n"
672           << "\t.weak " << name << '\n';
673         SwitchToDataSection("\t.data", I);
674         break;
675       case GlobalValue::AppendingLinkage:
676         // FIXME: appending linkage variables should go into a section of
677         // their name or something.  For now, just emit them as external.
678       case GlobalValue::ExternalLinkage:
679         // If external or appending, declare as a global symbol
680         O << "\t.global " << name << "\n"
681           << "\t.type " << name << ", @object\n";
682         // FALL THROUGH
683       case GlobalValue::InternalLinkage:
684         if (I->isConstant()) {
685           const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
686           if (TAI->getCStringSection() && CVA && CVA->isCString()) {
687             SwitchToDataSection(TAI->getCStringSection(), I);
688             break;
689           }
690         }
691
692         // FIXME: special handling for ".ctors" & ".dtors" sections
693         if (I->hasSection() &&
694             (I->getSection() == ".ctors" ||
695              I->getSection() == ".dtors")) {
696           std::string SectionName = ".section " + I->getSection()
697                                                 + ",\"aw\",@progbits";
698           SwitchToDataSection(SectionName.c_str());
699         } else {
700           SwitchToDataSection(TAI->getDataSection(), I);
701         }
702         break;
703       default:
704         cerr << "Unknown linkage type!";
705         abort();
706       }
707
708       EmitAlignment(Align, I);
709       O << name << ":\t\t\t\t" << TAI->getCommentString() << " '"
710         << I->getName() << "'\n";
711
712       // If the initializer is a extern weak symbol, remember to emit the weak
713       // reference!
714       if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
715         if (GV->hasExternalWeakLinkage())
716           ExtWeakSymbols.insert(GV);
717
718       EmitGlobalConstant(C);
719       O << '\n';
720     }
721   }
722
723   // TODO
724
725   // Emit initial debug information.
726   DW.EndModule();
727
728   AsmPrinter::doFinalization(M);
729   return false; // success
730 }
731
732 std::string LinuxAsmPrinter::getSectionForFunction(const Function &F) const {
733   switch (F.getLinkage()) {
734   default: assert(0 && "Unknown linkage type!");
735   case Function::ExternalLinkage:
736   case Function::InternalLinkage: return TAI->getTextSection();
737   case Function::WeakLinkage:
738   case Function::LinkOnceLinkage:
739     return ".text";
740   }
741 }
742
743 std::string DarwinAsmPrinter::getSectionForFunction(const Function &F) const {
744   switch (F.getLinkage()) {
745   default: assert(0 && "Unknown linkage type!");
746   case Function::ExternalLinkage:
747   case Function::InternalLinkage: return TAI->getTextSection();
748   case Function::WeakLinkage:
749   case Function::LinkOnceLinkage:
750     return ".section __TEXT,__textcoal_nt,coalesced,pure_instructions";
751   }
752 }
753
754 /// runOnMachineFunction - This uses the printMachineInstruction()
755 /// method to print assembly for each instruction.
756 ///
757 bool DarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
758   DW.SetModuleInfo(&getAnalysis<MachineModuleInfo>());
759
760   SetupMachineFunction(MF);
761   O << "\n\n";
762   
763   // Print out constants referenced by the function
764   EmitConstantPool(MF.getConstantPool());
765
766   // Print out labels for the function.
767   const Function *F = MF.getFunction();
768   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
769   
770   switch (F->getLinkage()) {
771   default: assert(0 && "Unknown linkage type!");
772   case Function::InternalLinkage:  // Symbols default to internal.
773     break;
774   case Function::ExternalLinkage:
775     O << "\t.globl\t" << CurrentFnName << "\n";
776     break;
777   case Function::WeakLinkage:
778   case Function::LinkOnceLinkage:
779     O << "\t.globl\t" << CurrentFnName << "\n";
780     O << "\t.weak_definition\t" << CurrentFnName << "\n";
781     break;
782   }
783   
784   if (F->hasHiddenVisibility())
785     if (const char *Directive = TAI->getHiddenDirective())
786       O << Directive << CurrentFnName << "\n";
787   
788   EmitAlignment(4, F);
789   O << CurrentFnName << ":\n";
790
791   // Emit pre-function debug information.
792   DW.BeginFunction(&MF);
793
794   // Print out code for the function.
795   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
796        I != E; ++I) {
797     // Print a label for the basic block.
798     if (I != MF.begin()) {
799       printBasicBlockLabel(I, true);
800       O << '\n';
801     }
802     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
803          II != E; ++II) {
804       // Print the assembly for the instruction.
805       O << "\t";
806       printMachineInstruction(II);
807     }
808   }
809
810   // Print out jump tables referenced by the function.
811   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
812   
813   // Emit post-function debug information.
814   DW.EndFunction();
815   
816   // We didn't modify anything.
817   return false;
818 }
819
820
821 bool DarwinAsmPrinter::doInitialization(Module &M) {
822   static const char *CPUDirectives[] = {
823     "ppc",
824     "ppc601",
825     "ppc602",
826     "ppc603",
827     "ppc7400",
828     "ppc750",
829     "ppc970",
830     "ppc64"
831   };
832
833   unsigned Directive = Subtarget.getDarwinDirective();
834   if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
835     Directive = PPC::DIR_970;
836   if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
837     Directive = PPC::DIR_7400;
838   if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
839     Directive = PPC::DIR_64;
840   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
841   O << "\t.machine " << CPUDirectives[Directive] << "\n";
842      
843   AsmPrinter::doInitialization(M);
844   
845   // Darwin wants symbols to be quoted if they have complex names.
846   Mang->setUseQuotes(true);
847   
848   // Prime text sections so they are adjacent.  This reduces the likelihood a
849   // large data or debug section causes a branch to exceed 16M limit.
850   SwitchToTextSection(".section __TEXT,__textcoal_nt,coalesced,"
851                       "pure_instructions");
852   if (TM.getRelocationModel() == Reloc::PIC_) {
853     SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
854                           "pure_instructions,32");
855   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
856     SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
857                         "pure_instructions,16");
858   }
859   SwitchToTextSection(TAI->getTextSection());
860   
861   // Emit initial debug information.
862   DW.BeginModule(&M);
863   return false;
864 }
865
866 bool DarwinAsmPrinter::doFinalization(Module &M) {
867   const TargetData *TD = TM.getTargetData();
868
869   // Print out module-level global variables here.
870   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
871        I != E; ++I) {
872     if (!I->hasInitializer()) continue;   // External global require no code
873     
874     // Check to see if this is a special global used by LLVM, if so, emit it.
875     if (EmitSpecialLLVMGlobal(I)) {
876       if (TM.getRelocationModel() == Reloc::Static) {
877         if (I->getName() == "llvm.global_ctors")
878           O << ".reference .constructors_used\n";
879         else if (I->getName() == "llvm.global_dtors")
880           O << ".reference .destructors_used\n";
881       }
882       continue;
883     }
884     
885     std::string name = Mang->getValueName(I);
886     
887     if (I->hasHiddenVisibility())
888       if (const char *Directive = TAI->getHiddenDirective())
889         O << Directive << name << "\n";
890     
891     Constant *C = I->getInitializer();
892     unsigned Size = TD->getTypeSize(C->getType());
893     unsigned Align = TD->getPreferredAlignmentLog(I);
894
895     if (C->isNullValue() && /* FIXME: Verify correct */
896         (I->hasInternalLinkage() || I->hasWeakLinkage() ||
897          I->hasLinkOnceLinkage() ||
898          (I->hasExternalLinkage() && !I->hasSection()))) {
899       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
900       if (I->hasExternalLinkage()) {
901         O << "\t.globl " << name << '\n';
902         O << "\t.zerofill __DATA, __common, " << name << ", "
903           << Size << ", " << Align;
904       } else if (I->hasInternalLinkage()) {
905         SwitchToDataSection("\t.data", I);
906         O << TAI->getLCOMMDirective() << name << "," << Size << "," << Align;
907       } else {
908         SwitchToDataSection("\t.data", I);
909         O << ".comm " << name << "," << Size;
910       }
911       O << "\t\t" << TAI->getCommentString() << " '" << I->getName() << "'\n";
912     } else {
913       switch (I->getLinkage()) {
914       case GlobalValue::LinkOnceLinkage:
915       case GlobalValue::WeakLinkage:
916         O << "\t.globl " << name << '\n'
917           << "\t.weak_definition " << name << '\n';
918         SwitchToDataSection(".section __DATA,__datacoal_nt,coalesced", I);
919         break;
920       case GlobalValue::AppendingLinkage:
921         // FIXME: appending linkage variables should go into a section of
922         // their name or something.  For now, just emit them as external.
923       case GlobalValue::ExternalLinkage:
924         // If external or appending, declare as a global symbol
925         O << "\t.globl " << name << "\n";
926         // FALL THROUGH
927       case GlobalValue::InternalLinkage:
928         if (I->isConstant()) {
929           const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
930           if (TAI->getCStringSection() && CVA && CVA->isCString()) {
931             SwitchToDataSection(TAI->getCStringSection(), I);
932             break;
933           }
934         }
935
936         SwitchToDataSection("\t.data", I);
937         break;
938       default:
939         cerr << "Unknown linkage type!";
940         abort();
941       }
942
943       EmitAlignment(Align, I);
944       O << name << ":\t\t\t\t" << TAI->getCommentString() << " '"
945         << I->getName() << "'\n";
946
947       // If the initializer is a extern weak symbol, remember to emit the weak
948       // reference!
949       if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
950         if (GV->hasExternalWeakLinkage())
951           ExtWeakSymbols.insert(GV);
952
953       EmitGlobalConstant(C);
954       O << '\n';
955     }
956   }
957
958   bool isPPC64 = TD->getPointerSizeInBits() == 64;
959
960   // Output stubs for dynamically-linked functions
961   if (TM.getRelocationModel() == Reloc::PIC_) {
962     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
963          i != e; ++i) {
964       SwitchToTextSection(".section __TEXT,__picsymbolstub1,symbol_stubs,"
965                           "pure_instructions,32");
966       EmitAlignment(4);
967       O << "L" << *i << "$stub:\n";
968       O << "\t.indirect_symbol " << *i << "\n";
969       O << "\tmflr r0\n";
970       O << "\tbcl 20,31,L0$" << *i << "\n";
971       O << "L0$" << *i << ":\n";
972       O << "\tmflr r11\n";
973       O << "\taddis r11,r11,ha16(L" << *i << "$lazy_ptr-L0$" << *i << ")\n";
974       O << "\tmtlr r0\n";
975       if (isPPC64)
976         O << "\tldu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
977       else
978         O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr-L0$" << *i << ")(r11)\n";
979       O << "\tmtctr r12\n";
980       O << "\tbctr\n";
981       SwitchToDataSection(".lazy_symbol_pointer");
982       O << "L" << *i << "$lazy_ptr:\n";
983       O << "\t.indirect_symbol " << *i << "\n";
984       if (isPPC64)
985         O << "\t.quad dyld_stub_binding_helper\n";
986       else
987         O << "\t.long dyld_stub_binding_helper\n";
988     }
989   } else {
990     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
991          i != e; ++i) {
992       SwitchToTextSection(".section __TEXT,__symbol_stub1,symbol_stubs,"
993                           "pure_instructions,16");
994       EmitAlignment(4);
995       O << "L" << *i << "$stub:\n";
996       O << "\t.indirect_symbol " << *i << "\n";
997       O << "\tlis r11,ha16(L" << *i << "$lazy_ptr)\n";
998       if (isPPC64)
999         O << "\tldu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
1000       else
1001         O << "\tlwzu r12,lo16(L" << *i << "$lazy_ptr)(r11)\n";
1002       O << "\tmtctr r12\n";
1003       O << "\tbctr\n";
1004       SwitchToDataSection(".lazy_symbol_pointer");
1005       O << "L" << *i << "$lazy_ptr:\n";
1006       O << "\t.indirect_symbol " << *i << "\n";
1007       if (isPPC64)
1008         O << "\t.quad dyld_stub_binding_helper\n";
1009       else
1010         O << "\t.long dyld_stub_binding_helper\n";
1011     }
1012   }
1013
1014   O << "\n";
1015
1016   // Output stubs for external and common global variables.
1017   if (GVStubs.begin() != GVStubs.end()) {
1018     SwitchToDataSection(".non_lazy_symbol_pointer");
1019     for (std::set<std::string>::iterator I = GVStubs.begin(),
1020          E = GVStubs.end(); I != E; ++I) {
1021       O << "L" << *I << "$non_lazy_ptr:\n";
1022       O << "\t.indirect_symbol " << *I << "\n";
1023       if (isPPC64)
1024         O << "\t.quad\t0\n";
1025       else
1026         O << "\t.long\t0\n";
1027         
1028     }
1029   }
1030
1031   // Emit initial debug information.
1032   DW.EndModule();
1033
1034   // Funny Darwin hack: This flag tells the linker that no global symbols
1035   // contain code that falls through to other global symbols (e.g. the obvious
1036   // implementation of multiple entry points).  If this doesn't occur, the
1037   // linker can safely perform dead code stripping.  Since LLVM never generates
1038   // code that does this, it is always safe to set.
1039   O << "\t.subsections_via_symbols\n";
1040
1041   AsmPrinter::doFinalization(M);
1042   return false; // success
1043 }
1044
1045
1046
1047 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1048 /// for a MachineFunction to the given output stream, in a format that the
1049 /// Darwin assembler can deal with.
1050 ///
1051 FunctionPass *llvm::createPPCAsmPrinterPass(std::ostream &o,
1052                                             PPCTargetMachine &tm) {
1053   const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1054
1055   if (Subtarget->isDarwin()) {
1056     return new DarwinAsmPrinter(o, tm, tm.getTargetAsmInfo());
1057   } else {
1058     return new LinuxAsmPrinter(o, tm, tm.getTargetAsmInfo());
1059   }
1060 }
1061