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/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/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/MC/MCSectionMachO.h"
35 #include "llvm/Target/TargetAsmInfo.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegistry.h"
41 #include "llvm/Support/Mangler.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/Compiler.h"
47 #include "llvm/Support/FormattedStream.h"
48 #include "llvm/ADT/Statistic.h"
49 #include "llvm/ADT/StringExtras.h"
50 #include "llvm/ADT/StringSet.h"
53 STATISTIC(EmittedInsts, "Number of machine instrs printed");
56 class VISIBILITY_HIDDEN PPCAsmPrinter : public AsmPrinter {
59 std::string Stub, LazyPtr, AnonSymbol;
63 void Init(const GlobalValue *GV, Mangler *Mang) {
64 // Already initialized.
65 if (!Stub.empty()) return;
66 Stub = Mang->getMangledName(GV, "$stub", true);
67 LazyPtr = Mang->getMangledName(GV, "$lazy_ptr", true);
68 AnonSymbol = Mang->getMangledName(GV, "$stub$tmp", true);
71 void Init(const std::string &GV, Mangler *Mang) {
72 // Already initialized.
73 if (!Stub.empty()) return;
74 Stub = Mang->makeNameProper(GV + "$stub",
76 LazyPtr = Mang->makeNameProper(GV + "$lazy_ptr",
78 AnonSymbol = Mang->makeNameProper(GV + "$stub$tmp",
83 StringMap<FnStubInfo> FnStubs;
84 StringMap<std::string> GVStubs, HiddenGVStubs;
85 const PPCSubtarget &Subtarget;
87 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
88 const TargetAsmInfo *T, bool V)
89 : AsmPrinter(O, TM, T, V),
90 Subtarget(TM.getSubtarget<PPCSubtarget>()) {}
92 virtual const char *getPassName() const {
93 return "PowerPC Assembly Printer";
96 PPCTargetMachine &getTM() {
97 return static_cast<PPCTargetMachine&>(TM);
100 unsigned enumRegToMachineReg(unsigned enumReg) {
102 default: llvm_unreachable("Unhandled register!");
103 case PPC::CR0: return 0;
104 case PPC::CR1: return 1;
105 case PPC::CR2: return 2;
106 case PPC::CR3: return 3;
107 case PPC::CR4: return 4;
108 case PPC::CR5: return 5;
109 case PPC::CR6: return 6;
110 case PPC::CR7: return 7;
115 /// printInstruction - This method is automatically generated by tablegen
116 /// from the instruction set description. This method returns true if the
117 /// machine instruction was sufficiently described to print it, otherwise it
119 void printInstruction(const MachineInstr *MI);
121 void printMachineInstruction(const MachineInstr *MI);
122 void printOp(const MachineOperand &MO);
124 /// stripRegisterPrefix - This method strips the character prefix from a
125 /// register name so that only the number is left. Used by for linux asm.
126 const char *stripRegisterPrefix(const char *RegName) {
127 switch (RegName[0]) {
130 case 'v': return RegName + 1;
131 case 'c': if (RegName[1] == 'r') return RegName + 2;
137 /// printRegister - Print register according to target requirements.
139 void printRegister(const MachineOperand &MO, bool R0AsZero) {
140 unsigned RegNo = MO.getReg();
141 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
143 // If we should use 0 for R0.
144 if (R0AsZero && RegNo == PPC::R0) {
149 const char *RegName = TM.getRegisterInfo()->get(RegNo).AsmName;
150 // Linux assembler (Others?) does not take register mnemonics.
151 // FIXME - What about special registers used in mfspr/mtspr?
152 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
156 void printOperand(const MachineInstr *MI, unsigned OpNo) {
157 const MachineOperand &MO = MI->getOperand(OpNo);
159 printRegister(MO, false);
160 } else if (MO.isImm()) {
167 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
168 unsigned AsmVariant, const char *ExtraCode);
169 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
170 unsigned AsmVariant, const char *ExtraCode);
173 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
174 char value = MI->getOperand(OpNo).getImm();
175 value = (value << (32-5)) >> (32-5);
178 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
179 unsigned char value = MI->getOperand(OpNo).getImm();
180 assert(value <= 31 && "Invalid u5imm argument!");
181 O << (unsigned int)value;
183 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
184 unsigned char value = MI->getOperand(OpNo).getImm();
185 assert(value <= 63 && "Invalid u6imm argument!");
186 O << (unsigned int)value;
188 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
189 O << (short)MI->getOperand(OpNo).getImm();
191 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
192 O << (unsigned short)MI->getOperand(OpNo).getImm();
194 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
195 if (MI->getOperand(OpNo).isImm()) {
196 O << (short)(MI->getOperand(OpNo).getImm()*4);
199 printOp(MI->getOperand(OpNo));
200 if (TM.getRelocationModel() == Reloc::PIC_)
201 O << "-\"L" << getFunctionNumber() << "$pb\")";
206 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
207 // Branches can take an immediate operand. This is used by the branch
208 // selection pass to print $+8, an eight byte displacement from the PC.
209 if (MI->getOperand(OpNo).isImm()) {
210 O << "$+" << MI->getOperand(OpNo).getImm()*4;
212 printOp(MI->getOperand(OpNo));
215 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
216 const MachineOperand &MO = MI->getOperand(OpNo);
217 if (TM.getRelocationModel() != Reloc::Static) {
218 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
219 GlobalValue *GV = MO.getGlobal();
220 if (GV->isDeclaration() || GV->isWeakForLinker()) {
221 // Dynamically-resolved functions need a stub for the function.
222 FnStubInfo &FnInfo = FnStubs[Mang->getMangledName(GV)];
223 FnInfo.Init(GV, Mang);
228 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
229 FnStubInfo &FnInfo =FnStubs[Mang->makeNameProper(MO.getSymbolName())];
230 FnInfo.Init(MO.getSymbolName(), Mang);
236 printOp(MI->getOperand(OpNo));
238 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
239 O << (int)MI->getOperand(OpNo).getImm()*4;
241 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
242 O << "\"L" << getFunctionNumber() << "$pb\"\n";
243 O << "\"L" << getFunctionNumber() << "$pb\":";
245 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
246 if (MI->getOperand(OpNo).isImm()) {
247 printS16ImmOperand(MI, OpNo);
249 if (Subtarget.isDarwin()) O << "ha16(";
250 printOp(MI->getOperand(OpNo));
251 if (TM.getRelocationModel() == Reloc::PIC_)
252 O << "-\"L" << getFunctionNumber() << "$pb\"";
253 if (Subtarget.isDarwin())
259 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
260 if (MI->getOperand(OpNo).isImm()) {
261 printS16ImmOperand(MI, OpNo);
263 if (Subtarget.isDarwin()) O << "lo16(";
264 printOp(MI->getOperand(OpNo));
265 if (TM.getRelocationModel() == Reloc::PIC_)
266 O << "-\"L" << getFunctionNumber() << "$pb\"";
267 if (Subtarget.isDarwin())
273 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
274 unsigned CCReg = MI->getOperand(OpNo).getReg();
275 unsigned RegNo = enumRegToMachineReg(CCReg);
276 O << (0x80 >> RegNo);
278 // The new addressing mode printers.
279 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
280 printSymbolLo(MI, OpNo);
282 if (MI->getOperand(OpNo+1).isReg() &&
283 MI->getOperand(OpNo+1).getReg() == PPC::R0)
286 printOperand(MI, OpNo+1);
289 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
290 if (MI->getOperand(OpNo).isImm())
291 printS16X4ImmOperand(MI, OpNo);
293 printSymbolLo(MI, OpNo);
295 if (MI->getOperand(OpNo+1).isReg() &&
296 MI->getOperand(OpNo+1).getReg() == PPC::R0)
299 printOperand(MI, OpNo+1);
303 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
304 // When used as the base register, r0 reads constant zero rather than
305 // the value contained in the register. For this reason, the darwin
306 // assembler requires that we print r0 as 0 (no r) when used as the base.
307 const MachineOperand &MO = MI->getOperand(OpNo);
308 printRegister(MO, true);
310 printOperand(MI, OpNo+1);
313 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
314 const char *Modifier);
316 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
318 virtual void EmitExternalGlobal(const GlobalVariable *GV);
321 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
322 class VISIBILITY_HIDDEN PPCLinuxAsmPrinter : public PPCAsmPrinter {
324 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
325 const TargetAsmInfo *T, bool V)
326 : PPCAsmPrinter(O, TM, T, V){}
328 virtual const char *getPassName() const {
329 return "Linux PPC Assembly Printer";
332 bool runOnMachineFunction(MachineFunction &F);
334 void getAnalysisUsage(AnalysisUsage &AU) const {
335 AU.setPreservesAll();
336 AU.addRequired<MachineModuleInfo>();
337 AU.addRequired<DwarfWriter>();
338 PPCAsmPrinter::getAnalysisUsage(AU);
341 void PrintGlobalVariable(const GlobalVariable *GVar);
344 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
346 class VISIBILITY_HIDDEN PPCDarwinAsmPrinter : public PPCAsmPrinter {
347 formatted_raw_ostream &OS;
349 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
350 const TargetAsmInfo *T, bool V)
351 : PPCAsmPrinter(O, TM, T, V), OS(O) {}
353 virtual const char *getPassName() const {
354 return "Darwin PPC Assembly Printer";
357 bool runOnMachineFunction(MachineFunction &F);
358 bool doInitialization(Module &M);
359 bool doFinalization(Module &M);
361 void getAnalysisUsage(AnalysisUsage &AU) const {
362 AU.setPreservesAll();
363 AU.addRequired<MachineModuleInfo>();
364 AU.addRequired<DwarfWriter>();
365 PPCAsmPrinter::getAnalysisUsage(AU);
368 void PrintGlobalVariable(const GlobalVariable *GVar);
370 } // end of anonymous namespace
372 // Include the auto-generated portion of the assembly writer
373 #include "PPCGenAsmWriter.inc"
375 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
376 switch (MO.getType()) {
377 case MachineOperand::MO_Immediate:
378 llvm_unreachable("printOp() does not handle immediate values");
380 case MachineOperand::MO_MachineBasicBlock:
381 printBasicBlockLabel(MO.getMBB());
383 case MachineOperand::MO_JumpTableIndex:
384 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
385 << '_' << MO.getIndex();
386 // FIXME: PIC relocation model
388 case MachineOperand::MO_ConstantPoolIndex:
389 O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
390 << '_' << MO.getIndex();
392 case MachineOperand::MO_ExternalSymbol: {
393 // Computing the address of an external symbol, not calling it.
394 std::string Name(TAI->getGlobalPrefix());
395 Name += MO.getSymbolName();
397 if (TM.getRelocationModel() != Reloc::Static) {
398 GVStubs[Name] = Name+"$non_lazy_ptr";
399 Name += "$non_lazy_ptr";
404 case MachineOperand::MO_GlobalAddress: {
405 // Computing the address of a global symbol, not calling it.
406 GlobalValue *GV = MO.getGlobal();
409 // External or weakly linked global variables need non-lazily-resolved stubs
410 if (TM.getRelocationModel() != Reloc::Static &&
411 (GV->isDeclaration() || GV->isWeakForLinker())) {
412 if (!GV->hasHiddenVisibility()) {
413 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
414 GVStubs[Mang->getMangledName(GV)] = Name;
415 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
416 GV->hasAvailableExternallyLinkage()) {
417 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
418 HiddenGVStubs[Mang->getMangledName(GV)] = Name;
420 Name = Mang->getMangledName(GV);
423 Name = Mang->getMangledName(GV);
427 printOffset(MO.getOffset());
432 O << "<unknown operand type: " << MO.getType() << ">";
437 /// EmitExternalGlobal - In this case we need to use the indirect symbol.
439 void PPCAsmPrinter::EmitExternalGlobal(const GlobalVariable *GV) {
442 if (TM.getRelocationModel() != Reloc::Static) {
443 Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
445 Name = Mang->getMangledName(GV);
450 /// PrintAsmOperand - Print out an operand for an inline asm expression.
452 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
454 const char *ExtraCode) {
455 // Does this asm operand have a single letter operand modifier?
456 if (ExtraCode && ExtraCode[0]) {
457 if (ExtraCode[1] != 0) return true; // Unknown modifier.
459 switch (ExtraCode[0]) {
460 default: return true; // Unknown modifier.
461 case 'c': // Don't print "$" before a global var name or constant.
462 // PPC never has a prefix.
463 printOperand(MI, OpNo);
465 case 'L': // Write second word of DImode reference.
466 // Verify that this operand has two consecutive registers.
467 if (!MI->getOperand(OpNo).isReg() ||
468 OpNo+1 == MI->getNumOperands() ||
469 !MI->getOperand(OpNo+1).isReg())
471 ++OpNo; // Return the high-part.
474 // Write 'i' if an integer constant, otherwise nothing. Used to print
476 if (MI->getOperand(OpNo).isImm())
482 printOperand(MI, OpNo);
486 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
488 const char *ExtraCode) {
489 if (ExtraCode && ExtraCode[0])
490 return true; // Unknown modifier.
491 if (MI->getOperand(OpNo).isReg())
492 printMemRegReg(MI, OpNo);
494 printMemRegImm(MI, OpNo);
498 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
499 const char *Modifier) {
500 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
501 unsigned Code = MI->getOperand(OpNo).getImm();
502 if (!strcmp(Modifier, "cc")) {
503 switch ((PPC::Predicate)Code) {
504 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
505 case PPC::PRED_LT: O << "lt"; return;
506 case PPC::PRED_LE: O << "le"; return;
507 case PPC::PRED_EQ: O << "eq"; return;
508 case PPC::PRED_GE: O << "ge"; return;
509 case PPC::PRED_GT: O << "gt"; return;
510 case PPC::PRED_NE: O << "ne"; return;
511 case PPC::PRED_UN: O << "un"; return;
512 case PPC::PRED_NU: O << "nu"; return;
516 assert(!strcmp(Modifier, "reg") &&
517 "Need to specify 'cc' or 'reg' as predicate op modifier!");
518 // Don't print the register for 'always'.
519 if (Code == PPC::PRED_ALWAYS) return;
520 printOperand(MI, OpNo+1);
525 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
526 /// the current output stream.
528 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
531 // Check for slwi/srwi mnemonics.
532 if (MI->getOpcode() == PPC::RLWINM) {
533 bool FoundMnemonic = false;
534 unsigned char SH = MI->getOperand(2).getImm();
535 unsigned char MB = MI->getOperand(3).getImm();
536 unsigned char ME = MI->getOperand(4).getImm();
537 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
538 O << "\tslwi "; FoundMnemonic = true;
540 if (SH <= 31 && MB == (32-SH) && ME == 31) {
541 O << "\tsrwi "; FoundMnemonic = true;
548 O << ", " << (unsigned int)SH << '\n';
551 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
552 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
560 } else if (MI->getOpcode() == PPC::RLDICR) {
561 unsigned char SH = MI->getOperand(2).getImm();
562 unsigned char ME = MI->getOperand(3).getImm();
563 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
569 O << ", " << (unsigned int)SH << '\n';
574 printInstruction(MI);
577 /// runOnMachineFunction - This uses the printMachineInstruction()
578 /// method to print assembly for each instruction.
580 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
583 SetupMachineFunction(MF);
586 // Print out constants referenced by the function
587 EmitConstantPool(MF.getConstantPool());
589 // Print out labels for the function.
590 const Function *F = MF.getFunction();
591 SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
593 switch (F->getLinkage()) {
594 default: llvm_unreachable("Unknown linkage type!");
595 case Function::PrivateLinkage:
596 case Function::LinkerPrivateLinkage:
597 case Function::InternalLinkage: // Symbols default to internal.
599 case Function::ExternalLinkage:
600 O << "\t.global\t" << CurrentFnName << '\n'
601 << "\t.type\t" << CurrentFnName << ", @function\n";
603 case Function::WeakAnyLinkage:
604 case Function::WeakODRLinkage:
605 case Function::LinkOnceAnyLinkage:
606 case Function::LinkOnceODRLinkage:
607 O << "\t.global\t" << CurrentFnName << '\n';
608 O << "\t.weak\t" << CurrentFnName << '\n';
612 printVisibility(CurrentFnName, F->getVisibility());
614 EmitAlignment(MF.getAlignment(), F);
615 O << CurrentFnName << ":\n";
617 // Emit pre-function debug information.
618 DW->BeginFunction(&MF);
620 // Print out code for the function.
621 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
623 // Print a label for the basic block.
624 if (I != MF.begin()) {
625 printBasicBlockLabel(I, true, true);
628 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
630 // Print the assembly for the instruction.
631 printMachineInstruction(II);
635 O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << '\n';
637 // Print out jump tables referenced by the function.
638 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
640 SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
642 // Emit post-function debug information.
643 DW->EndFunction(&MF);
645 // We didn't modify anything.
649 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
650 /// Don't print things like \\n or \\0.
651 static void PrintUnmangledNameSafely(const Value *V,
652 formatted_raw_ostream &OS) {
653 for (StringRef::iterator it = V->getName().begin(),
654 ie = V->getName().end(); it != ie; ++it)
659 void PPCLinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
660 const TargetData *TD = TM.getTargetData();
662 if (!GVar->hasInitializer())
663 return; // External global require no code
665 // Check to see if this is a special global used by LLVM, if so, emit it.
666 if (EmitSpecialLLVMGlobal(GVar))
669 std::string name = Mang->getMangledName(GVar);
671 printVisibility(name, GVar->getVisibility());
673 Constant *C = GVar->getInitializer();
674 const Type *Type = C->getType();
675 unsigned Size = TD->getTypeAllocSize(Type);
676 unsigned Align = TD->getPreferredAlignmentLog(GVar);
678 SwitchToSection(getObjFileLowering().SectionForGlobal(GVar, Mang, TM));
680 if (C->isNullValue() && /* FIXME: Verify correct */
681 !GVar->hasSection() &&
682 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
683 GVar->isWeakForLinker())) {
684 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
686 if (GVar->hasExternalLinkage()) {
687 O << "\t.global " << name << '\n';
688 O << "\t.type " << name << ", @object\n";
690 O << "\t.zero " << Size << '\n';
691 } else if (GVar->hasLocalLinkage()) {
692 O << TAI->getLCOMMDirective() << name << ',' << Size;
694 O << ".comm " << name << ',' << Size;
697 O << "\t\t" << TAI->getCommentString() << " '";
698 PrintUnmangledNameSafely(GVar, O);
705 switch (GVar->getLinkage()) {
706 case GlobalValue::LinkOnceAnyLinkage:
707 case GlobalValue::LinkOnceODRLinkage:
708 case GlobalValue::WeakAnyLinkage:
709 case GlobalValue::WeakODRLinkage:
710 case GlobalValue::CommonLinkage:
711 O << "\t.global " << name << '\n'
712 << "\t.type " << name << ", @object\n"
713 << "\t.weak " << name << '\n';
715 case GlobalValue::AppendingLinkage:
716 // FIXME: appending linkage variables should go into a section of
717 // their name or something. For now, just emit them as external.
718 case GlobalValue::ExternalLinkage:
719 // If external or appending, declare as a global symbol
720 O << "\t.global " << name << '\n'
721 << "\t.type " << name << ", @object\n";
723 case GlobalValue::InternalLinkage:
724 case GlobalValue::PrivateLinkage:
725 case GlobalValue::LinkerPrivateLinkage:
728 llvm_unreachable("Unknown linkage type!");
731 EmitAlignment(Align, GVar);
734 O << "\t\t\t\t" << TAI->getCommentString() << " '";
735 PrintUnmangledNameSafely(GVar, O);
740 EmitGlobalConstant(C);
745 /// runOnMachineFunction - This uses the printMachineInstruction()
746 /// method to print assembly for each instruction.
748 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
751 SetupMachineFunction(MF);
754 // Print out constants referenced by the function
755 EmitConstantPool(MF.getConstantPool());
757 // Print out labels for the function.
758 const Function *F = MF.getFunction();
759 SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
761 switch (F->getLinkage()) {
762 default: llvm_unreachable("Unknown linkage type!");
763 case Function::PrivateLinkage:
764 case Function::LinkerPrivateLinkage:
765 case Function::InternalLinkage: // Symbols default to internal.
767 case Function::ExternalLinkage:
768 O << "\t.globl\t" << CurrentFnName << '\n';
770 case Function::WeakAnyLinkage:
771 case Function::WeakODRLinkage:
772 case Function::LinkOnceAnyLinkage:
773 case Function::LinkOnceODRLinkage:
774 O << "\t.globl\t" << CurrentFnName << '\n';
775 O << "\t.weak_definition\t" << CurrentFnName << '\n';
779 printVisibility(CurrentFnName, F->getVisibility());
781 EmitAlignment(MF.getAlignment(), F);
782 O << CurrentFnName << ":\n";
784 // Emit pre-function debug information.
785 DW->BeginFunction(&MF);
787 // If the function is empty, then we need to emit *something*. Otherwise, the
788 // function's label might be associated with something that it wasn't meant to
789 // be associated with. We emit a noop in this situation.
790 MachineFunction::iterator I = MF.begin();
792 if (++I == MF.end() && MF.front().empty())
795 // Print out code for the function.
796 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
798 // Print a label for the basic block.
799 if (I != MF.begin()) {
800 printBasicBlockLabel(I, true, true, VerboseAsm);
803 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
805 // Print the assembly for the instruction.
806 printMachineInstruction(II);
810 // Print out jump tables referenced by the function.
811 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
813 // Emit post-function debug information.
814 DW->EndFunction(&MF);
816 // We didn't modify anything.
821 bool PPCDarwinAsmPrinter::doInitialization(Module &M) {
822 static const char *const CPUDirectives[] = {
834 unsigned Directive = Subtarget.getDarwinDirective();
835 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
836 Directive = PPC::DIR_970;
837 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
838 Directive = PPC::DIR_7400;
839 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
840 Directive = PPC::DIR_64;
841 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
842 O << "\t.machine " << CPUDirectives[Directive] << '\n';
844 bool Result = AsmPrinter::doInitialization(M);
847 // Prime text sections so they are adjacent. This reduces the likelihood a
848 // large data or debug section causes a branch to exceed 16M limit.
849 TargetLoweringObjectFileMachO &TLOFMacho =
850 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
851 SwitchToSection(TLOFMacho.getTextCoalSection());
852 if (TM.getRelocationModel() == Reloc::PIC_) {
853 SwitchToSection(TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
854 MCSectionMachO::S_SYMBOL_STUBS |
855 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
856 32, SectionKind::getText()));
857 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
858 SwitchToSection(TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
859 MCSectionMachO::S_SYMBOL_STUBS |
860 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
861 16, SectionKind::getText()));
863 SwitchToSection(getObjFileLowering().getTextSection());
868 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
869 const TargetData *TD = TM.getTargetData();
871 if (!GVar->hasInitializer())
872 return; // External global require no code
874 // Check to see if this is a special global used by LLVM, if so, emit it.
875 if (EmitSpecialLLVMGlobal(GVar)) {
876 if (TM.getRelocationModel() == Reloc::Static) {
877 if (GVar->getName() == "llvm.global_ctors")
878 O << ".reference .constructors_used\n";
879 else if (GVar->getName() == "llvm.global_dtors")
880 O << ".reference .destructors_used\n";
885 std::string name = Mang->getMangledName(GVar);
886 printVisibility(name, GVar->getVisibility());
888 Constant *C = GVar->getInitializer();
889 const Type *Type = C->getType();
890 unsigned Size = TD->getTypeAllocSize(Type);
891 unsigned Align = TD->getPreferredAlignmentLog(GVar);
893 const MCSection *TheSection =
894 getObjFileLowering().SectionForGlobal(GVar, Mang, TM);
895 SwitchToSection(TheSection);
897 /// FIXME: Drive this off the section!
898 if (C->isNullValue() && /* FIXME: Verify correct */
899 !GVar->hasSection() &&
900 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
901 GVar->isWeakForLinker()) &&
902 // Don't put things that should go in the cstring section into "comm".
903 !TheSection->getKind().isMergeableCString()) {
904 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
906 if (GVar->hasExternalLinkage()) {
907 O << "\t.globl " << name << '\n';
908 O << "\t.zerofill __DATA, __common, " << name << ", "
909 << Size << ", " << Align;
910 } else if (GVar->hasLocalLinkage()) {
911 O << TAI->getLCOMMDirective() << name << ',' << Size << ',' << Align;
912 } else if (!GVar->hasCommonLinkage()) {
913 O << "\t.globl " << name << '\n'
914 << TAI->getWeakDefDirective() << name << '\n';
915 EmitAlignment(Align, GVar);
918 O << "\t\t\t\t" << TAI->getCommentString() << " ";
919 PrintUnmangledNameSafely(GVar, O);
922 EmitGlobalConstant(C);
925 O << ".comm " << name << ',' << Size;
926 // Darwin 9 and above support aligned common data.
927 if (Subtarget.isDarwin9())
931 O << "\t\t" << TAI->getCommentString() << " '";
932 PrintUnmangledNameSafely(GVar, O);
939 switch (GVar->getLinkage()) {
940 case GlobalValue::LinkOnceAnyLinkage:
941 case GlobalValue::LinkOnceODRLinkage:
942 case GlobalValue::WeakAnyLinkage:
943 case GlobalValue::WeakODRLinkage:
944 case GlobalValue::CommonLinkage:
945 O << "\t.globl " << name << '\n'
946 << "\t.weak_definition " << name << '\n';
948 case GlobalValue::AppendingLinkage:
949 // FIXME: appending linkage variables should go into a section of
950 // their name or something. For now, just emit them as external.
951 case GlobalValue::ExternalLinkage:
952 // If external or appending, declare as a global symbol
953 O << "\t.globl " << name << '\n';
955 case GlobalValue::InternalLinkage:
956 case GlobalValue::PrivateLinkage:
957 case GlobalValue::LinkerPrivateLinkage:
960 llvm_unreachable("Unknown linkage type!");
963 EmitAlignment(Align, GVar);
966 O << "\t\t\t\t" << TAI->getCommentString() << " '";
967 PrintUnmangledNameSafely(GVar, O);
972 EmitGlobalConstant(C);
976 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
977 const TargetData *TD = TM.getTargetData();
979 bool isPPC64 = TD->getPointerSizeInBits() == 64;
981 // Darwin/PPC always uses mach-o.
982 TargetLoweringObjectFileMachO &TLOFMacho =
983 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
986 const MCSection *LSPSection = 0;
987 if (!FnStubs.empty()) // .lazy_symbol_pointer
988 LSPSection = TLOFMacho.getLazySymbolPointerSection();
991 // Output stubs for dynamically-linked functions
992 if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
993 const MCSection *StubSection =
994 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
995 MCSectionMachO::S_SYMBOL_STUBS |
996 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
997 32, SectionKind::getText());
998 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1000 SwitchToSection(StubSection);
1002 const FnStubInfo &Info = I->second;
1003 O << Info.Stub << ":\n";
1004 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1006 O << "\tbcl 20,31," << Info.AnonSymbol << '\n';
1007 O << Info.AnonSymbol << ":\n";
1008 O << "\tmflr r11\n";
1009 O << "\taddis r11,r11,ha16(" << Info.LazyPtr << "-" << Info.AnonSymbol;
1012 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1013 O << Info.LazyPtr << "-" << Info.AnonSymbol << ")(r11)\n";
1014 O << "\tmtctr r12\n";
1017 SwitchToSection(LSPSection);
1018 O << Info.LazyPtr << ":\n";
1019 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1020 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1022 } else if (!FnStubs.empty()) {
1023 const MCSection *StubSection =
1024 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
1025 MCSectionMachO::S_SYMBOL_STUBS |
1026 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1027 16, SectionKind::getText());
1029 for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1031 SwitchToSection(StubSection);
1033 const FnStubInfo &Info = I->second;
1034 O << Info.Stub << ":\n";
1035 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1036 O << "\tlis r11,ha16(" << Info.LazyPtr << ")\n";
1037 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(";
1038 O << Info.LazyPtr << ")(r11)\n";
1039 O << "\tmtctr r12\n";
1041 SwitchToSection(LSPSection);
1042 O << Info.LazyPtr << ":\n";
1043 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1044 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1050 if (TAI->doesSupportExceptionHandling() && MMI) {
1051 // Add the (possibly multiple) personalities to the set of global values.
1052 // Only referenced functions get into the Personalities list.
1053 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1054 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1055 E = Personalities.end(); I != E; ++I) {
1057 GVStubs[Mang->getMangledName(*I)] =
1058 Mang->getMangledName(*I, "$non_lazy_ptr", true);
1062 // Output macho stubs for external and common global variables.
1063 if (!GVStubs.empty()) {
1064 // Switch with ".non_lazy_symbol_pointer" directive.
1065 SwitchToSection(TLOFMacho.getNonLazySymbolPointerSection());
1066 EmitAlignment(isPPC64 ? 3 : 2);
1068 for (StringMap<std::string>::iterator I = GVStubs.begin(),
1069 E = GVStubs.end(); I != E; ++I) {
1070 O << I->second << ":\n";
1071 O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1072 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1076 if (!HiddenGVStubs.empty()) {
1077 SwitchToSection(getObjFileLowering().getDataSection());
1078 EmitAlignment(isPPC64 ? 3 : 2);
1079 for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
1080 E = HiddenGVStubs.end(); I != E; ++I) {
1081 O << I->second << ":\n";
1082 O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << I->getKeyData() << '\n';
1086 // Funny Darwin hack: This flag tells the linker that no global symbols
1087 // contain code that falls through to other global symbols (e.g. the obvious
1088 // implementation of multiple entry points). If this doesn't occur, the
1089 // linker can safely perform dead code stripping. Since LLVM never generates
1090 // code that does this, it is always safe to set.
1091 O << "\t.subsections_via_symbols\n";
1093 return AsmPrinter::doFinalization(M);
1098 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1099 /// for a MachineFunction to the given output stream, in a format that the
1100 /// Darwin assembler can deal with.
1102 static FunctionPass *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1105 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1107 if (Subtarget->isDarwin())
1108 return new PPCDarwinAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
1109 return new PPCLinuxAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
1112 // Force static initialization.
1113 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1114 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1116 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);