1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC 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 PowerPC assembly language. This printer is
12 // the output mechanism used by `llc'.
14 // Documentation at http://developer.apple.com/documentation/DeveloperTools/
15 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "asmprinter"
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/MDNode.h"
28 #include "llvm/Assembly/Writer.h"
29 #include "llvm/CodeGen/AsmPrinter.h"
30 #include "llvm/CodeGen/DwarfWriter.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineFunctionPass.h"
33 #include "llvm/CodeGen/MachineInstr.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/Support/Mangler.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/Compiler.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetAsmInfo.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/StringSet.h"
50 STATISTIC(EmittedInsts, "Number of machine instrs printed");
53 class VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
55 StringSet<> FnStubs, GVStubs, HiddenGVStubs;
56 const PPCSubtarget &Subtarget;
58 explicit PPCAsmPrinter(raw_ostream &O, TargetMachine &TM,
59 const TargetAsmInfo *T, bool V)
60 : AsmPrinter(O, TM, T, V),
61 Subtarget(TM.getSubtarget<PPCSubtarget>()) {}
63 virtual const char *getPassName() const {
64 return "PowerPC Assembly Printer";
67 PPCTargetMachine &getTM() {
68 return static_cast<PPCTargetMachine&>(TM);
71 unsigned enumRegToMachineReg(unsigned enumReg) {
73 default: assert(0 && "Unhandled register!"); break;
74 case PPC::CR0: return 0;
75 case PPC::CR1: return 1;
76 case PPC::CR2: return 2;
77 case PPC::CR3: return 3;
78 case PPC::CR4: return 4;
79 case PPC::CR5: return 5;
80 case PPC::CR6: return 6;
81 case PPC::CR7: return 7;
86 /// printInstruction - This method is automatically generated by tablegen
87 /// from the instruction set description. This method returns true if the
88 /// machine instruction was sufficiently described to print it, otherwise it
90 bool printInstruction(const MachineInstr *MI);
92 void printMachineInstruction(const MachineInstr *MI);
93 void printOp(const MachineOperand &MO);
95 /// stripRegisterPrefix - This method strips the character prefix from a
96 /// register name so that only the number is left. Used by for linux asm.
97 const char *stripRegisterPrefix(const char *RegName) {
101 case 'v': return RegName + 1;
102 case 'c': if (RegName[1] == 'r') return RegName + 2;
108 /// printRegister - Print register according to target requirements.
110 void printRegister(const MachineOperand &MO, bool R0AsZero) {
111 unsigned RegNo = MO.getReg();
112 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
114 // If we should use 0 for R0.
115 if (R0AsZero && RegNo == PPC::R0) {
120 const char *RegName = TM.getRegisterInfo()->get(RegNo).AsmName;
121 // Linux assembler (Others?) does not take register mnemonics.
122 // FIXME - What about special registers used in mfspr/mtspr?
123 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
127 void printOperand(const MachineInstr *MI, unsigned OpNo) {
128 const MachineOperand &MO = MI->getOperand(OpNo);
130 printRegister(MO, false);
131 } else if (MO.isImm()) {
138 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
139 unsigned AsmVariant, const char *ExtraCode);
140 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
141 unsigned AsmVariant, const char *ExtraCode);
144 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
145 char value = MI->getOperand(OpNo).getImm();
146 value = (value << (32-5)) >> (32-5);
149 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
150 unsigned char value = MI->getOperand(OpNo).getImm();
151 assert(value <= 31 && "Invalid u5imm argument!");
152 O << (unsigned int)value;
154 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
155 unsigned char value = MI->getOperand(OpNo).getImm();
156 assert(value <= 63 && "Invalid u6imm argument!");
157 O << (unsigned int)value;
159 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
160 O << (short)MI->getOperand(OpNo).getImm();
162 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
163 O << (unsigned short)MI->getOperand(OpNo).getImm();
165 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
166 if (MI->getOperand(OpNo).isImm()) {
167 O << (short)(MI->getOperand(OpNo).getImm()*4);
170 printOp(MI->getOperand(OpNo));
171 if (TM.getRelocationModel() == Reloc::PIC_)
172 O << "-\"L" << getFunctionNumber() << "$pb\")";
177 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
178 // Branches can take an immediate operand. This is used by the branch
179 // selection pass to print $+8, an eight byte displacement from the PC.
180 if (MI->getOperand(OpNo).isImm()) {
181 O << "$+" << MI->getOperand(OpNo).getImm()*4;
183 printOp(MI->getOperand(OpNo));
186 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
187 const MachineOperand &MO = MI->getOperand(OpNo);
188 if (TM.getRelocationModel() != Reloc::Static) {
189 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
190 GlobalValue *GV = MO.getGlobal();
191 if (GV->isDeclaration() || GV->isWeakForLinker()) {
192 // Dynamically-resolved functions need a stub for the function.
193 std::string Name = Mang->getValueName(GV);
194 FnStubs.insert(Name);
195 printSuffixedName(Name, "$stub");
199 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
200 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
201 FnStubs.insert(Name);
202 printSuffixedName(Name, "$stub");
207 printOp(MI->getOperand(OpNo));
209 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
210 O << (int)MI->getOperand(OpNo).getImm()*4;
212 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
213 O << "\"L" << getFunctionNumber() << "$pb\"\n";
214 O << "\"L" << getFunctionNumber() << "$pb\":";
216 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
217 if (MI->getOperand(OpNo).isImm()) {
218 printS16ImmOperand(MI, OpNo);
220 if (Subtarget.isDarwin()) O << "ha16(";
221 printOp(MI->getOperand(OpNo));
222 if (TM.getRelocationModel() == Reloc::PIC_)
223 O << "-\"L" << getFunctionNumber() << "$pb\"";
224 if (Subtarget.isDarwin())
230 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
231 if (MI->getOperand(OpNo).isImm()) {
232 printS16ImmOperand(MI, OpNo);
234 if (Subtarget.isDarwin()) O << "lo16(";
235 printOp(MI->getOperand(OpNo));
236 if (TM.getRelocationModel() == Reloc::PIC_)
237 O << "-\"L" << getFunctionNumber() << "$pb\"";
238 if (Subtarget.isDarwin())
244 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
245 unsigned CCReg = MI->getOperand(OpNo).getReg();
246 unsigned RegNo = enumRegToMachineReg(CCReg);
247 O << (0x80 >> RegNo);
249 // The new addressing mode printers.
250 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
251 printSymbolLo(MI, OpNo);
253 if (MI->getOperand(OpNo+1).isReg() &&
254 MI->getOperand(OpNo+1).getReg() == PPC::R0)
257 printOperand(MI, OpNo+1);
260 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
261 if (MI->getOperand(OpNo).isImm())
262 printS16X4ImmOperand(MI, OpNo);
264 printSymbolLo(MI, OpNo);
266 if (MI->getOperand(OpNo+1).isReg() &&
267 MI->getOperand(OpNo+1).getReg() == PPC::R0)
270 printOperand(MI, OpNo+1);
274 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
275 // When used as the base register, r0 reads constant zero rather than
276 // the value contained in the register. For this reason, the darwin
277 // assembler requires that we print r0 as 0 (no r) when used as the base.
278 const MachineOperand &MO = MI->getOperand(OpNo);
279 printRegister(MO, true);
281 printOperand(MI, OpNo+1);
284 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
285 const char *Modifier);
287 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
288 virtual bool doFinalization(Module &M) = 0;
290 virtual void EmitExternalGlobal(const GlobalVariable *GV);
293 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
294 class VISIBILITY_HIDDEN PPCLinuxAsmPrinter : public PPCAsmPrinter {
296 explicit PPCLinuxAsmPrinter(raw_ostream &O, PPCTargetMachine &TM,
297 const TargetAsmInfo *T, bool V)
298 : PPCAsmPrinter(O, TM, T, V){}
300 virtual const char *getPassName() const {
301 return "Linux PPC Assembly Printer";
304 bool runOnMachineFunction(MachineFunction &F);
305 bool doFinalization(Module &M);
307 void getAnalysisUsage(AnalysisUsage &AU) const {
308 AU.setPreservesAll();
309 AU.addRequired<MachineModuleInfo>();
310 AU.addRequired<DwarfWriter>();
311 PPCAsmPrinter::getAnalysisUsage(AU);
314 void printModuleLevelGV(const GlobalVariable* GVar);
317 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
319 class VISIBILITY_HIDDEN PPCDarwinAsmPrinter : public PPCAsmPrinter {
322 explicit PPCDarwinAsmPrinter(raw_ostream &O, PPCTargetMachine &TM,
323 const TargetAsmInfo *T, bool V)
324 : PPCAsmPrinter(O, TM, T, V), OS(O) {}
326 virtual const char *getPassName() const {
327 return "Darwin PPC Assembly Printer";
330 bool runOnMachineFunction(MachineFunction &F);
331 bool doInitialization(Module &M);
332 bool doFinalization(Module &M);
334 void getAnalysisUsage(AnalysisUsage &AU) const {
335 AU.setPreservesAll();
336 AU.addRequired<MachineModuleInfo>();
337 AU.addRequired<DwarfWriter>();
338 PPCAsmPrinter::getAnalysisUsage(AU);
341 void printModuleLevelGV(const GlobalVariable* GVar);
343 } // end of anonymous namespace
345 // Include the auto-generated portion of the assembly writer
346 #include "PPCGenAsmWriter.inc"
348 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
349 switch (MO.getType()) {
350 case MachineOperand::MO_Immediate:
351 cerr << "printOp() does not handle immediate values\n";
355 case MachineOperand::MO_MachineBasicBlock:
356 printBasicBlockLabel(MO.getMBB());
358 case MachineOperand::MO_JumpTableIndex:
359 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
360 << '_' << MO.getIndex();
361 // FIXME: PIC relocation model
363 case MachineOperand::MO_ConstantPoolIndex:
364 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
365 << '_' << MO.getIndex();
367 case MachineOperand::MO_ExternalSymbol:
368 // Computing the address of an external symbol, not calling it.
369 if (TM.getRelocationModel() != Reloc::Static) {
370 std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
371 GVStubs.insert(Name);
372 printSuffixedName(Name, "$non_lazy_ptr");
375 O << TAI->getGlobalPrefix() << MO.getSymbolName();
377 case MachineOperand::MO_GlobalAddress: {
378 // Computing the address of a global symbol, not calling it.
379 GlobalValue *GV = MO.getGlobal();
380 std::string Name = Mang->getValueName(GV);
382 // External or weakly linked global variables need non-lazily-resolved stubs
383 if (TM.getRelocationModel() != Reloc::Static) {
384 if (GV->isDeclaration() || GV->isWeakForLinker()) {
385 if (GV->hasHiddenVisibility()) {
386 if (GV->isDeclaration() || GV->hasCommonLinkage() ||
387 GV->hasAvailableExternallyLinkage()) {
388 HiddenGVStubs.insert(Name);
389 printSuffixedName(Name, "$non_lazy_ptr");
394 GVStubs.insert(Name);
395 printSuffixedName(Name, "$non_lazy_ptr");
402 printOffset(MO.getOffset());
407 O << "<unknown operand type: " << MO.getType() << ">";
412 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
414 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
416 getGlobalLinkName(GV, Name);
417 if (TM.getRelocationModel() != Reloc::Static) {
418 if (GV->hasHiddenVisibility())
419 HiddenGVStubs.insert(Name);
421 GVStubs.insert(Name);
422 printSuffixedName(Name, "$non_lazy_ptr");
428 /// PrintAsmOperand - Print out an operand for an inline asm expression.
430 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
432 const char *ExtraCode) {
433 // Does this asm operand have a single letter operand modifier?
434 if (ExtraCode && ExtraCode[0]) {
435 if (ExtraCode[1] != 0) return true; // Unknown modifier.
437 switch (ExtraCode[0]) {
438 default: return true; // Unknown modifier.
439 case 'c': // Don't print "$" before a global var name or constant.
440 // PPC never has a prefix.
441 printOperand(MI, OpNo);
443 case 'L': // Write second word of DImode reference.
444 // Verify that this operand has two consecutive registers.
445 if (!MI->getOperand(OpNo).isReg() ||
446 OpNo+1 == MI->getNumOperands() ||
447 !MI->getOperand(OpNo+1).isReg())
449 ++OpNo; // Return the high-part.
452 // Write 'i' if an integer constant, otherwise nothing. Used to print
454 if (MI->getOperand(OpNo).isImm())
460 printOperand(MI, OpNo);
464 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
466 const char *ExtraCode) {
467 if (ExtraCode && ExtraCode[0])
468 return true; // Unknown modifier.
469 if (MI->getOperand(OpNo).isReg())
470 printMemRegReg(MI, OpNo);
472 printMemRegImm(MI, OpNo);
476 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
477 const char *Modifier) {
478 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
479 unsigned Code = MI->getOperand(OpNo).getImm();
480 if (!strcmp(Modifier, "cc")) {
481 switch ((PPC::Predicate)Code) {
482 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
483 case PPC::PRED_LT: O << "lt"; return;
484 case PPC::PRED_LE: O << "le"; return;
485 case PPC::PRED_EQ: O << "eq"; return;
486 case PPC::PRED_GE: O << "ge"; return;
487 case PPC::PRED_GT: O << "gt"; return;
488 case PPC::PRED_NE: O << "ne"; return;
489 case PPC::PRED_UN: O << "un"; return;
490 case PPC::PRED_NU: O << "nu"; return;
494 assert(!strcmp(Modifier, "reg") &&
495 "Need to specify 'cc' or 'reg' as predicate op modifier!");
496 // Don't print the register for 'always'.
497 if (Code == PPC::PRED_ALWAYS) return;
498 printOperand(MI, OpNo+1);
503 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
504 /// the current output stream.
506 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
509 // Check for slwi/srwi mnemonics.
510 if (MI->getOpcode() == PPC::RLWINM) {
511 bool FoundMnemonic = false;
512 unsigned char SH = MI->getOperand(2).getImm();
513 unsigned char MB = MI->getOperand(3).getImm();
514 unsigned char ME = MI->getOperand(4).getImm();
515 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
516 O << "\tslwi "; FoundMnemonic = true;
518 if (SH <= 31 && MB == (32-SH) && ME == 31) {
519 O << "\tsrwi "; FoundMnemonic = true;
526 O << ", " << (unsigned int)SH << '\n';
529 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
530 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
538 } else if (MI->getOpcode() == PPC::RLDICR) {
539 unsigned char SH = MI->getOperand(2).getImm();
540 unsigned char ME = MI->getOperand(3).getImm();
541 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
547 O << ", " << (unsigned int)SH << '\n';
552 if (printInstruction(MI))
553 return; // Printer was automatically generated
555 assert(0 && "Unhandled instruction in asm writer!");
560 /// runOnMachineFunction - This uses the printMachineInstruction()
561 /// method to print assembly for each instruction.
563 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
566 SetupMachineFunction(MF);
569 // Print out constants referenced by the function
570 EmitConstantPool(MF.getConstantPool());
572 // Print out labels for the function.
573 const Function *F = MF.getFunction();
574 SwitchToSection(TAI->SectionForGlobal(F));
576 switch (F->getLinkage()) {
577 default: assert(0 && "Unknown linkage type!");
578 case Function::PrivateLinkage:
579 case Function::InternalLinkage: // Symbols default to internal.
581 case Function::ExternalLinkage:
582 O << "\t.global\t" << CurrentFnName << '\n'
583 << "\t.type\t" << CurrentFnName << ", @function\n";
585 case Function::WeakAnyLinkage:
586 case Function::WeakODRLinkage:
587 case Function::LinkOnceAnyLinkage:
588 case Function::LinkOnceODRLinkage:
589 O << "\t.global\t" << CurrentFnName << '\n';
590 O << "\t.weak\t" << CurrentFnName << '\n';
594 printVisibility(CurrentFnName, F->getVisibility());
596 EmitAlignment(MF.getAlignment(), F);
597 O << CurrentFnName << ":\n";
599 // Emit pre-function debug information.
600 DW->BeginFunction(&MF);
602 // Print out code for the function.
603 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
605 // Print a label for the basic block.
606 if (I != MF.begin()) {
607 printBasicBlockLabel(I, true, true);
610 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
612 // Print the assembly for the instruction.
613 printMachineInstruction(II);
617 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
619 // Print out jump tables referenced by the function.
620 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
622 SwitchToSection(TAI->SectionForGlobal(F));
624 // Emit post-function debug information.
625 DW->EndFunction(&MF);
629 // We didn't modify anything.
633 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
634 /// Don't print things like \\n or \\0.
635 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
636 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
642 void PPCLinuxAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
643 const TargetData *TD = TM.getTargetData();
645 if (!GVar->hasInitializer())
646 return; // External global require no code
648 // Check to see if this is a special global used by LLVM, if so, emit it.
649 if (EmitSpecialLLVMGlobal(GVar))
652 std::string name = Mang->getValueName(GVar);
654 printVisibility(name, GVar->getVisibility());
656 Constant *C = GVar->getInitializer();
657 if (isa<MDNode>(C) || isa<MDString>(C))
659 const Type *Type = C->getType();
660 unsigned Size = TD->getTypeAllocSize(Type);
661 unsigned Align = TD->getPreferredAlignmentLog(GVar);
663 SwitchToSection(TAI->SectionForGlobal(GVar));
665 if (C->isNullValue() && /* FIXME: Verify correct */
666 !GVar->hasSection() &&
667 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
668 GVar->isWeakForLinker())) {
669 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
671 if (GVar->hasExternalLinkage()) {
672 O << "\t.global " << name << '\n';
673 O << "\t.type " << name << ", @object\n";
675 O << "\t.zero " << Size << '\n';
676 } else if (GVar->hasLocalLinkage()) {
677 O << TAI->getLCOMMDirective() << name << ',' << Size;
679 O << ".comm " << name << ',' << Size;
682 O << "\t\t" << TAI->getCommentString() << " '";
683 PrintUnmangledNameSafely(GVar, O);
690 switch (GVar->getLinkage()) {
691 case GlobalValue::LinkOnceAnyLinkage:
692 case GlobalValue::LinkOnceODRLinkage:
693 case GlobalValue::WeakAnyLinkage:
694 case GlobalValue::WeakODRLinkage:
695 case GlobalValue::CommonLinkage:
696 O << "\t.global " << name << '\n'
697 << "\t.type " << name << ", @object\n"
698 << "\t.weak " << name << '\n';
700 case GlobalValue::AppendingLinkage:
701 // FIXME: appending linkage variables should go into a section of
702 // their name or something. For now, just emit them as external.
703 case GlobalValue::ExternalLinkage:
704 // If external or appending, declare as a global symbol
705 O << "\t.global " << name << '\n'
706 << "\t.type " << name << ", @object\n";
708 case GlobalValue::InternalLinkage:
709 case GlobalValue::PrivateLinkage:
712 cerr << "Unknown linkage type!";
716 EmitAlignment(Align, GVar);
719 O << "\t\t\t\t" << TAI->getCommentString() << " '";
720 PrintUnmangledNameSafely(GVar, O);
725 EmitGlobalConstant(C);
729 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
730 // Print out module-level global variables here.
731 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
733 printModuleLevelGV(I);
735 return AsmPrinter::doFinalization(M);
738 /// runOnMachineFunction - This uses the printMachineInstruction()
739 /// method to print assembly for each instruction.
741 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
744 SetupMachineFunction(MF);
747 // Print out constants referenced by the function
748 EmitConstantPool(MF.getConstantPool());
750 // Print out labels for the function.
751 const Function *F = MF.getFunction();
752 SwitchToSection(TAI->SectionForGlobal(F));
754 switch (F->getLinkage()) {
755 default: assert(0 && "Unknown linkage type!");
756 case Function::PrivateLinkage:
757 case Function::InternalLinkage: // Symbols default to internal.
759 case Function::ExternalLinkage:
760 O << "\t.globl\t" << CurrentFnName << '\n';
762 case Function::WeakAnyLinkage:
763 case Function::WeakODRLinkage:
764 case Function::LinkOnceAnyLinkage:
765 case Function::LinkOnceODRLinkage:
766 O << "\t.globl\t" << CurrentFnName << '\n';
767 O << "\t.weak_definition\t" << CurrentFnName << '\n';
771 printVisibility(CurrentFnName, F->getVisibility());
773 EmitAlignment(MF.getAlignment(), F);
774 O << CurrentFnName << ":\n";
776 // Emit pre-function debug information.
777 DW->BeginFunction(&MF);
779 // If the function is empty, then we need to emit *something*. Otherwise, the
780 // function's label might be associated with something that it wasn't meant to
781 // be associated with. We emit a noop in this situation.
782 MachineFunction::iterator I = MF.begin();
784 if (++I == MF.end() && MF.front().empty())
787 // Print out code for the function.
788 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
790 // Print a label for the basic block.
791 if (I != MF.begin()) {
792 printBasicBlockLabel(I, true, true, VerboseAsm);
795 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
797 // Print the assembly for the instruction.
798 printMachineInstruction(II);
802 // Print out jump tables referenced by the function.
803 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
805 // Emit post-function debug information.
806 DW->EndFunction(&MF);
808 // We didn't modify anything.
813 bool PPCDarwinAsmPrinter::doInitialization(Module &M) {
814 static const char *const CPUDirectives[] = {
826 unsigned Directive = Subtarget.getDarwinDirective();
827 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
828 Directive = PPC::DIR_970;
829 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
830 Directive = PPC::DIR_7400;
831 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
832 Directive = PPC::DIR_64;
833 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
834 O << "\t.machine " << CPUDirectives[Directive] << '\n';
836 bool Result = AsmPrinter::doInitialization(M);
839 // Prime text sections so they are adjacent. This reduces the likelihood a
840 // large data or debug section causes a branch to exceed 16M limit.
841 SwitchToTextSection("\t.section __TEXT,__textcoal_nt,coalesced,"
842 "pure_instructions");
843 if (TM.getRelocationModel() == Reloc::PIC_) {
844 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
845 "pure_instructions,32");
846 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
847 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
848 "pure_instructions,16");
850 SwitchToSection(TAI->getTextSection());
855 void PPCDarwinAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
856 const TargetData *TD = TM.getTargetData();
858 if (!GVar->hasInitializer())
859 return; // External global require no code
861 // Check to see if this is a special global used by LLVM, if so, emit it.
862 if (EmitSpecialLLVMGlobal(GVar)) {
863 if (TM.getRelocationModel() == Reloc::Static) {
864 if (GVar->getName() == "llvm.global_ctors")
865 O << ".reference .constructors_used\n";
866 else if (GVar->getName() == "llvm.global_dtors")
867 O << ".reference .destructors_used\n";
872 std::string name = Mang->getValueName(GVar);
874 printVisibility(name, GVar->getVisibility());
876 Constant *C = GVar->getInitializer();
877 const Type *Type = C->getType();
878 unsigned Size = TD->getTypeAllocSize(Type);
879 unsigned Align = TD->getPreferredAlignmentLog(GVar);
881 SwitchToSection(TAI->SectionForGlobal(GVar));
883 if (C->isNullValue() && /* FIXME: Verify correct */
884 !GVar->hasSection() &&
885 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
886 GVar->isWeakForLinker()) &&
887 TAI->SectionKindForGlobal(GVar) != SectionKind::RODataMergeStr) {
888 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
890 if (GVar->hasExternalLinkage()) {
891 O << "\t.globl " << name << '\n';
892 O << "\t.zerofill __DATA, __common, " << name << ", "
893 << Size << ", " << Align;
894 } else if (GVar->hasLocalLinkage()) {
895 O << TAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
896 } else if (!GVar->hasCommonLinkage()) {
897 O << "\t.globl " << name << '\n'
898 << TAI->getWeakDefDirective() << name << '\n';
899 EmitAlignment(Align, GVar);
902 O << "\t\t\t\t" << TAI->getCommentString() << " ";
903 PrintUnmangledNameSafely(GVar, O);
906 EmitGlobalConstant(C);
909 O << ".comm " << name << ',' << Size;
910 // Darwin 9 and above support aligned common data.
911 if (Subtarget.isDarwin9())
915 O << "\t\t" << TAI->getCommentString() << " '";
916 PrintUnmangledNameSafely(GVar, O);
923 switch (GVar->getLinkage()) {
924 case GlobalValue::LinkOnceAnyLinkage:
925 case GlobalValue::LinkOnceODRLinkage:
926 case GlobalValue::WeakAnyLinkage:
927 case GlobalValue::WeakODRLinkage:
928 case GlobalValue::CommonLinkage:
929 O << "\t.globl " << name << '\n'
930 << "\t.weak_definition " << name << '\n';
932 case GlobalValue::AppendingLinkage:
933 // FIXME: appending linkage variables should go into a section of
934 // their name or something. For now, just emit them as external.
935 case GlobalValue::ExternalLinkage:
936 // If external or appending, declare as a global symbol
937 O << "\t.globl " << name << '\n';
939 case GlobalValue::InternalLinkage:
940 case GlobalValue::PrivateLinkage:
943 cerr << "Unknown linkage type!";
947 EmitAlignment(Align, GVar);
950 O << "\t\t\t\t" << TAI->getCommentString() << " '";
951 PrintUnmangledNameSafely(GVar, O);
956 EmitGlobalConstant(C);
960 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
961 const TargetData *TD = TM.getTargetData();
963 // Print out module-level global variables here.
964 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
966 printModuleLevelGV(I);
968 bool isPPC64 = TD->getPointerSizeInBits() == 64;
970 // Output stubs for dynamically-linked functions
971 if (TM.getRelocationModel() == Reloc::PIC_) {
972 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
974 SwitchToTextSection("\t.section __TEXT,__picsymbolstub1,symbol_stubs,"
975 "pure_instructions,32");
977 const char *p = i->getKeyData();
978 bool hasQuote = p[0]=='\"';
979 printSuffixedName(p, "$stub");
981 O << "\t.indirect_symbol " << p << '\n';
985 O << "\"L0$" << &p[1];
990 O << "\"L0$" << &p[1];
995 O << "\taddis r11,r11,ha16(";
996 printSuffixedName(p, "$lazy_ptr");
999 O << "\"L0$" << &p[1];
1005 O << "\tldu r12,lo16(";
1007 O << "\tlwzu r12,lo16(";
1008 printSuffixedName(p, "$lazy_ptr");
1011 O << "\"L0$" << &p[1];
1015 O << "\tmtctr r12\n";
1017 SwitchToDataSection(".lazy_symbol_pointer");
1018 printSuffixedName(p, "$lazy_ptr");
1020 O << "\t.indirect_symbol " << p << '\n';
1022 O << "\t.quad dyld_stub_binding_helper\n";
1024 O << "\t.long dyld_stub_binding_helper\n";
1027 for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1029 SwitchToTextSection("\t.section __TEXT,__symbol_stub1,symbol_stubs,"
1030 "pure_instructions,16");
1032 const char *p = i->getKeyData();
1033 printSuffixedName(p, "$stub");
1035 O << "\t.indirect_symbol " << p << '\n';
1036 O << "\tlis r11,ha16(";
1037 printSuffixedName(p, "$lazy_ptr");
1040 O << "\tldu r12,lo16(";
1042 O << "\tlwzu r12,lo16(";
1043 printSuffixedName(p, "$lazy_ptr");
1045 O << "\tmtctr r12\n";
1047 SwitchToDataSection(".lazy_symbol_pointer");
1048 printSuffixedName(p, "$lazy_ptr");
1050 O << "\t.indirect_symbol " << p << '\n';
1052 O << "\t.quad dyld_stub_binding_helper\n";
1054 O << "\t.long dyld_stub_binding_helper\n";
1060 if (TAI->doesSupportExceptionHandling() && MMI) {
1061 // Add the (possibly multiple) personalities to the set of global values.
1062 // Only referenced functions get into the Personalities list.
1063 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1064 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1065 E = Personalities.end(); I != E; ++I)
1066 if (*I) GVStubs.insert("_" + (*I)->getName());
1069 // Output stubs for external and common global variables.
1070 if (!GVStubs.empty()) {
1071 SwitchToDataSection(".non_lazy_symbol_pointer");
1072 for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
1074 std::string p = i->getKeyData();
1075 printSuffixedName(p, "$non_lazy_ptr");
1077 O << "\t.indirect_symbol " << p << '\n';
1079 O << "\t.quad\t0\n";
1081 O << "\t.long\t0\n";
1085 if (!HiddenGVStubs.empty()) {
1086 SwitchToSection(TAI->getDataSection());
1087 for (StringSet<>::iterator i = HiddenGVStubs.begin(), e = HiddenGVStubs.end();
1089 std::string p = i->getKeyData();
1090 EmitAlignment(isPPC64 ? 3 : 2);
1091 printSuffixedName(p, "$non_lazy_ptr");
1101 // Funny Darwin hack: This flag tells the linker that no global symbols
1102 // contain code that falls through to other global symbols (e.g. the obvious
1103 // implementation of multiple entry points). If this doesn't occur, the
1104 // linker can safely perform dead code stripping. Since LLVM never generates
1105 // code that does this, it is always safe to set.
1106 O << "\t.subsections_via_symbols\n";
1108 return AsmPrinter::doFinalization(M);
1113 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1114 /// for a MachineFunction to the given output stream, in a format that the
1115 /// Darwin assembler can deal with.
1117 FunctionPass *llvm::createPPCAsmPrinterPass(raw_ostream &o,
1118 PPCTargetMachine &tm,
1120 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1122 if (Subtarget->isDarwin()) {
1123 return new PPCDarwinAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
1125 return new PPCLinuxAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
1130 static struct Register {
1132 PPCTargetMachine::registerAsmPrinter(createPPCAsmPrinterPass);
1137 extern "C" int PowerPCAsmPrinterForceLink;
1138 int PowerPCAsmPrinterForceLink = 0;
1140 // Force static initialization.
1141 extern "C" void LLVMInitializePowerPCAsmPrinter() { }