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/MCAsmInfo.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/MC/MCSectionMachO.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Target/Mangler.h"
40 #include "llvm/Target/TargetLoweringObjectFile.h"
41 #include "llvm/Target/TargetRegisterInfo.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include "llvm/Target/TargetRegistry.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/FormattedStream.h"
50 #include "llvm/ADT/Statistic.h"
51 #include "llvm/ADT/StringExtras.h"
52 #include "llvm/ADT/StringSet.h"
53 #include "llvm/ADT/SmallString.h"
56 STATISTIC(EmittedInsts, "Number of machine instrs printed");
59 class PPCAsmPrinter : public AsmPrinter {
62 MCSymbol *Stub, *LazyPtr, *AnonSymbol;
65 Stub = LazyPtr = AnonSymbol = 0;
68 void Init(const GlobalValue *GV, AsmPrinter *Printer) {
69 // Already initialized.
70 if (Stub != 0) return;
73 Stub = Printer->GetSymbolWithGlobalValueBase(GV, "$stub");
74 LazyPtr = Printer->GetSymbolWithGlobalValueBase(GV, "$lazy_ptr");
75 AnonSymbol = Printer->GetSymbolWithGlobalValueBase(GV, "$stub$tmp");
78 void Init(StringRef GVName, Mangler *Mang, MCContext &Ctx) {
79 assert(!GVName.empty() && "external symbol name shouldn't be empty");
80 if (Stub != 0) return; // Already initialized.
81 // Get the names for the external symbol name.
82 SmallString<128> TmpStr;
83 Mang->getNameWithPrefix(TmpStr, GVName, Mangler::Private);
85 Stub = Ctx.GetOrCreateSymbol(TmpStr.str());
86 TmpStr.erase(TmpStr.end()-5, TmpStr.end()); // Remove $stub
88 TmpStr += "$lazy_ptr";
89 LazyPtr = Ctx.GetOrCreateSymbol(TmpStr.str());
90 TmpStr.erase(TmpStr.end()-9, TmpStr.end()); // Remove $lazy_ptr
92 TmpStr += "$stub$tmp";
93 AnonSymbol = Ctx.GetOrCreateSymbol(TmpStr.str());
97 DenseMap<const MCSymbol*, FnStubInfo> FnStubs;
98 DenseMap<const MCSymbol*, const MCSymbol*> GVStubs, HiddenGVStubs, TOC;
99 const PPCSubtarget &Subtarget;
102 explicit PPCAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
103 const MCAsmInfo *T, bool V)
104 : AsmPrinter(O, TM, T, V),
105 Subtarget(TM.getSubtarget<PPCSubtarget>()), LabelID(0) {}
107 virtual const char *getPassName() const {
108 return "PowerPC Assembly Printer";
111 PPCTargetMachine &getTM() {
112 return static_cast<PPCTargetMachine&>(TM);
115 unsigned enumRegToMachineReg(unsigned enumReg) {
117 default: llvm_unreachable("Unhandled register!");
118 case PPC::CR0: return 0;
119 case PPC::CR1: return 1;
120 case PPC::CR2: return 2;
121 case PPC::CR3: return 3;
122 case PPC::CR4: return 4;
123 case PPC::CR5: return 5;
124 case PPC::CR6: return 6;
125 case PPC::CR7: return 7;
130 /// printInstruction - This method is automatically generated by tablegen
131 /// from the instruction set description. This method returns true if the
132 /// machine instruction was sufficiently described to print it, otherwise it
134 void printInstruction(const MachineInstr *MI);
135 static const char *getRegisterName(unsigned RegNo);
138 void printMachineInstruction(const MachineInstr *MI);
139 void printOp(const MachineOperand &MO);
141 /// stripRegisterPrefix - This method strips the character prefix from a
142 /// register name so that only the number is left. Used by for linux asm.
143 const char *stripRegisterPrefix(const char *RegName) {
144 switch (RegName[0]) {
147 case 'v': return RegName + 1;
148 case 'c': if (RegName[1] == 'r') return RegName + 2;
154 /// printRegister - Print register according to target requirements.
156 void printRegister(const MachineOperand &MO, bool R0AsZero) {
157 unsigned RegNo = MO.getReg();
158 assert(TargetRegisterInfo::isPhysicalRegister(RegNo) && "Not physreg??");
160 // If we should use 0 for R0.
161 if (R0AsZero && RegNo == PPC::R0) {
166 const char *RegName = getRegisterName(RegNo);
167 // Linux assembler (Others?) does not take register mnemonics.
168 // FIXME - What about special registers used in mfspr/mtspr?
169 if (!Subtarget.isDarwin()) RegName = stripRegisterPrefix(RegName);
173 void printOperand(const MachineInstr *MI, unsigned OpNo) {
174 const MachineOperand &MO = MI->getOperand(OpNo);
176 printRegister(MO, false);
177 } else if (MO.isImm()) {
184 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
185 unsigned AsmVariant, const char *ExtraCode);
186 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
187 unsigned AsmVariant, const char *ExtraCode);
190 void printS5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
191 char value = MI->getOperand(OpNo).getImm();
192 value = (value << (32-5)) >> (32-5);
195 void printU5ImmOperand(const MachineInstr *MI, unsigned OpNo) {
196 unsigned char value = MI->getOperand(OpNo).getImm();
197 assert(value <= 31 && "Invalid u5imm argument!");
198 O << (unsigned int)value;
200 void printU6ImmOperand(const MachineInstr *MI, unsigned OpNo) {
201 unsigned char value = MI->getOperand(OpNo).getImm();
202 assert(value <= 63 && "Invalid u6imm argument!");
203 O << (unsigned int)value;
205 void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
206 O << (short)MI->getOperand(OpNo).getImm();
208 void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo) {
209 O << (unsigned short)MI->getOperand(OpNo).getImm();
211 void printS16X4ImmOperand(const MachineInstr *MI, unsigned OpNo) {
212 if (MI->getOperand(OpNo).isImm()) {
213 O << (short)(MI->getOperand(OpNo).getImm()*4);
216 printOp(MI->getOperand(OpNo));
217 if (TM.getRelocationModel() == Reloc::PIC_)
218 O << "-\"L" << getFunctionNumber() << "$pb\")";
223 void printBranchOperand(const MachineInstr *MI, unsigned OpNo) {
224 // Branches can take an immediate operand. This is used by the branch
225 // selection pass to print $+8, an eight byte displacement from the PC.
226 if (MI->getOperand(OpNo).isImm()) {
227 O << "$+" << MI->getOperand(OpNo).getImm()*4;
229 printOp(MI->getOperand(OpNo));
232 void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
233 const MachineOperand &MO = MI->getOperand(OpNo);
234 if (TM.getRelocationModel() != Reloc::Static) {
235 if (MO.getType() == MachineOperand::MO_GlobalAddress) {
236 GlobalValue *GV = MO.getGlobal();
237 if (GV->isDeclaration() || GV->isWeakForLinker()) {
238 // Dynamically-resolved functions need a stub for the function.
239 FnStubInfo &FnInfo = FnStubs[GetGlobalValueSymbol(GV)];
240 FnInfo.Init(GV, this);
245 if (MO.getType() == MachineOperand::MO_ExternalSymbol) {
247 FnStubs[GetExternalSymbolSymbol(MO.getSymbolName())];
248 FnInfo.Init(MO.getSymbolName(), Mang, OutContext);
254 printOp(MI->getOperand(OpNo));
256 void printAbsAddrOperand(const MachineInstr *MI, unsigned OpNo) {
257 O << (int)MI->getOperand(OpNo).getImm()*4;
259 void printPICLabel(const MachineInstr *MI, unsigned OpNo) {
260 O << "\"L" << getFunctionNumber() << "$pb\"\n";
261 O << "\"L" << getFunctionNumber() << "$pb\":";
263 void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
264 if (MI->getOperand(OpNo).isImm()) {
265 printS16ImmOperand(MI, OpNo);
267 if (Subtarget.isDarwin()) O << "ha16(";
268 printOp(MI->getOperand(OpNo));
269 if (TM.getRelocationModel() == Reloc::PIC_)
270 O << "-\"L" << getFunctionNumber() << "$pb\"";
271 if (Subtarget.isDarwin())
277 void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
278 if (MI->getOperand(OpNo).isImm()) {
279 printS16ImmOperand(MI, OpNo);
281 if (Subtarget.isDarwin()) O << "lo16(";
282 printOp(MI->getOperand(OpNo));
283 if (TM.getRelocationModel() == Reloc::PIC_)
284 O << "-\"L" << getFunctionNumber() << "$pb\"";
285 if (Subtarget.isDarwin())
291 void printcrbitm(const MachineInstr *MI, unsigned OpNo) {
292 unsigned CCReg = MI->getOperand(OpNo).getReg();
293 unsigned RegNo = enumRegToMachineReg(CCReg);
294 O << (0x80 >> RegNo);
296 // The new addressing mode printers.
297 void printMemRegImm(const MachineInstr *MI, unsigned OpNo) {
298 printSymbolLo(MI, OpNo);
300 if (MI->getOperand(OpNo+1).isReg() &&
301 MI->getOperand(OpNo+1).getReg() == PPC::R0)
304 printOperand(MI, OpNo+1);
307 void printMemRegImmShifted(const MachineInstr *MI, unsigned OpNo) {
308 if (MI->getOperand(OpNo).isImm())
309 printS16X4ImmOperand(MI, OpNo);
311 printSymbolLo(MI, OpNo);
313 if (MI->getOperand(OpNo+1).isReg() &&
314 MI->getOperand(OpNo+1).getReg() == PPC::R0)
317 printOperand(MI, OpNo+1);
321 void printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
322 // When used as the base register, r0 reads constant zero rather than
323 // the value contained in the register. For this reason, the darwin
324 // assembler requires that we print r0 as 0 (no r) when used as the base.
325 const MachineOperand &MO = MI->getOperand(OpNo);
326 printRegister(MO, true);
328 printOperand(MI, OpNo+1);
331 void printTOCEntryLabel(const MachineInstr *MI, unsigned OpNo) {
332 const MachineOperand &MO = MI->getOperand(OpNo);
334 assert(MO.getType() == MachineOperand::MO_GlobalAddress);
336 const MCSymbol *Sym = GetGlobalValueSymbol(MO.getGlobal());
338 // Map symbol -> label of TOC entry.
339 const MCSymbol *&TOCEntry = TOC[Sym];
341 TOCEntry = OutContext.
342 GetOrCreateSymbol(StringRef(MAI->getPrivateGlobalPrefix()) + "C" +
345 O << *TOCEntry << "@toc";
348 void printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
349 const char *Modifier);
351 virtual bool runOnMachineFunction(MachineFunction &F) = 0;
354 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
355 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
357 explicit PPCLinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
358 const MCAsmInfo *T, bool V)
359 : PPCAsmPrinter(O, TM, T, V){}
361 virtual const char *getPassName() const {
362 return "Linux PPC Assembly Printer";
365 bool runOnMachineFunction(MachineFunction &F);
366 bool doFinalization(Module &M);
368 void getAnalysisUsage(AnalysisUsage &AU) const {
369 AU.setPreservesAll();
370 AU.addRequired<MachineModuleInfo>();
371 AU.addRequired<DwarfWriter>();
372 PPCAsmPrinter::getAnalysisUsage(AU);
375 void PrintGlobalVariable(const GlobalVariable *GVar);
378 /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
380 class PPCDarwinAsmPrinter : public PPCAsmPrinter {
381 formatted_raw_ostream &OS;
383 explicit PPCDarwinAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
384 const MCAsmInfo *T, bool V)
385 : PPCAsmPrinter(O, TM, T, V), OS(O) {}
387 virtual const char *getPassName() const {
388 return "Darwin PPC Assembly Printer";
391 bool runOnMachineFunction(MachineFunction &F);
392 bool doFinalization(Module &M);
393 void EmitStartOfAsmFile(Module &M);
395 void getAnalysisUsage(AnalysisUsage &AU) const {
396 AU.setPreservesAll();
397 AU.addRequired<MachineModuleInfo>();
398 AU.addRequired<DwarfWriter>();
399 PPCAsmPrinter::getAnalysisUsage(AU);
402 void PrintGlobalVariable(const GlobalVariable *GVar);
404 } // end of anonymous namespace
406 // Include the auto-generated portion of the assembly writer
407 #include "PPCGenAsmWriter.inc"
409 void PPCAsmPrinter::printOp(const MachineOperand &MO) {
410 switch (MO.getType()) {
411 case MachineOperand::MO_Immediate:
412 llvm_unreachable("printOp() does not handle immediate values");
414 case MachineOperand::MO_MachineBasicBlock:
415 O << *GetMBBSymbol(MO.getMBB()->getNumber());
417 case MachineOperand::MO_JumpTableIndex:
418 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
419 << '_' << MO.getIndex();
420 // FIXME: PIC relocation model
422 case MachineOperand::MO_ConstantPoolIndex:
423 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
424 << '_' << MO.getIndex();
426 case MachineOperand::MO_BlockAddress:
427 O << *GetBlockAddressSymbol(MO.getBlockAddress());
429 case MachineOperand::MO_ExternalSymbol: {
430 // Computing the address of an external symbol, not calling it.
431 const MCSymbol *SymName = GetExternalSymbolSymbol(MO.getSymbolName());
432 if (TM.getRelocationModel() == Reloc::Static) {
436 const MCSymbol *NLPSym =
437 OutContext.GetOrCreateSymbol(StringRef(MAI->getGlobalPrefix())+
438 MO.getSymbolName()+"$non_lazy_ptr");
439 GVStubs[SymName] = NLPSym;
443 case MachineOperand::MO_GlobalAddress: {
444 // Computing the address of a global symbol, not calling it.
445 GlobalValue *GV = MO.getGlobal();
446 MCSymbol *SymToPrint;
448 // External or weakly linked global variables need non-lazily-resolved stubs
449 if (TM.getRelocationModel() != Reloc::Static &&
450 (GV->isDeclaration() || GV->isWeakForLinker())) {
451 if (!GV->hasHiddenVisibility()) {
452 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
453 GVStubs[GetGlobalValueSymbol(GV)] = SymToPrint;
454 } else if (GV->isDeclaration() || GV->hasCommonLinkage() ||
455 GV->hasAvailableExternallyLinkage()) {
456 SymToPrint = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
457 HiddenGVStubs[GetGlobalValueSymbol(GV)] = SymToPrint;
459 SymToPrint = GetGlobalValueSymbol(GV);
462 SymToPrint = GetGlobalValueSymbol(GV);
467 printOffset(MO.getOffset());
472 O << "<unknown operand type: " << MO.getType() << ">";
477 /// PrintAsmOperand - Print out an operand for an inline asm expression.
479 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
481 const char *ExtraCode) {
482 // Does this asm operand have a single letter operand modifier?
483 if (ExtraCode && ExtraCode[0]) {
484 if (ExtraCode[1] != 0) return true; // Unknown modifier.
486 switch (ExtraCode[0]) {
487 default: return true; // Unknown modifier.
488 case 'c': // Don't print "$" before a global var name or constant.
489 // PPC never has a prefix.
490 printOperand(MI, OpNo);
492 case 'L': // Write second word of DImode reference.
493 // Verify that this operand has two consecutive registers.
494 if (!MI->getOperand(OpNo).isReg() ||
495 OpNo+1 == MI->getNumOperands() ||
496 !MI->getOperand(OpNo+1).isReg())
498 ++OpNo; // Return the high-part.
501 // Write 'i' if an integer constant, otherwise nothing. Used to print
503 if (MI->getOperand(OpNo).isImm())
509 printOperand(MI, OpNo);
513 // At the moment, all inline asm memory operands are a single register.
514 // In any case, the output of this routine should always be just one
515 // assembler operand.
517 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
519 const char *ExtraCode) {
520 if (ExtraCode && ExtraCode[0])
521 return true; // Unknown modifier.
522 assert (MI->getOperand(OpNo).isReg());
524 printOperand(MI, OpNo);
529 void PPCAsmPrinter::printPredicateOperand(const MachineInstr *MI, unsigned OpNo,
530 const char *Modifier) {
531 assert(Modifier && "Must specify 'cc' or 'reg' as predicate op modifier!");
532 unsigned Code = MI->getOperand(OpNo).getImm();
533 if (!strcmp(Modifier, "cc")) {
534 switch ((PPC::Predicate)Code) {
535 case PPC::PRED_ALWAYS: return; // Don't print anything for always.
536 case PPC::PRED_LT: O << "lt"; return;
537 case PPC::PRED_LE: O << "le"; return;
538 case PPC::PRED_EQ: O << "eq"; return;
539 case PPC::PRED_GE: O << "ge"; return;
540 case PPC::PRED_GT: O << "gt"; return;
541 case PPC::PRED_NE: O << "ne"; return;
542 case PPC::PRED_UN: O << "un"; return;
543 case PPC::PRED_NU: O << "nu"; return;
547 assert(!strcmp(Modifier, "reg") &&
548 "Need to specify 'cc' or 'reg' as predicate op modifier!");
549 // Don't print the register for 'always'.
550 if (Code == PPC::PRED_ALWAYS) return;
551 printOperand(MI, OpNo+1);
556 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax to
557 /// the current output stream.
559 void PPCAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
562 processDebugLoc(MI, true);
564 // Check for slwi/srwi mnemonics.
565 bool useSubstituteMnemonic = false;
566 if (MI->getOpcode() == PPC::RLWINM) {
567 unsigned char SH = MI->getOperand(2).getImm();
568 unsigned char MB = MI->getOperand(3).getImm();
569 unsigned char ME = MI->getOperand(4).getImm();
570 if (SH <= 31 && MB == 0 && ME == (31-SH)) {
571 O << "\tslwi "; useSubstituteMnemonic = true;
573 if (SH <= 31 && MB == (32-SH) && ME == 31) {
574 O << "\tsrwi "; useSubstituteMnemonic = true;
577 if (useSubstituteMnemonic) {
581 O << ", " << (unsigned int)SH;
583 } else if (MI->getOpcode() == PPC::OR || MI->getOpcode() == PPC::OR8) {
584 if (MI->getOperand(1).getReg() == MI->getOperand(2).getReg()) {
585 useSubstituteMnemonic = true;
591 } else if (MI->getOpcode() == PPC::RLDICR) {
592 unsigned char SH = MI->getOperand(2).getImm();
593 unsigned char ME = MI->getOperand(3).getImm();
594 // rldicr RA, RS, SH, 63-SH == sldi RA, RS, SH
596 useSubstituteMnemonic = true;
601 O << ", " << (unsigned int)SH;
605 if (!useSubstituteMnemonic)
606 printInstruction(MI);
612 processDebugLoc(MI, false);
615 /// runOnMachineFunction - This uses the printMachineInstruction()
616 /// method to print assembly for each instruction.
618 bool PPCLinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
621 SetupMachineFunction(MF);
624 // Print out constants referenced by the function
625 EmitConstantPool(MF.getConstantPool());
627 // Print out labels for the function.
628 const Function *F = MF.getFunction();
629 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
631 switch (F->getLinkage()) {
632 default: llvm_unreachable("Unknown linkage type!");
633 case Function::PrivateLinkage:
634 case Function::InternalLinkage: // Symbols default to internal.
636 case Function::ExternalLinkage:
637 O << "\t.global\t" << *CurrentFnSym << '\n' << "\t.type\t";
638 O << *CurrentFnSym << ", @function\n";
640 case Function::LinkerPrivateLinkage:
641 case Function::WeakAnyLinkage:
642 case Function::WeakODRLinkage:
643 case Function::LinkOnceAnyLinkage:
644 case Function::LinkOnceODRLinkage:
645 O << "\t.global\t" << *CurrentFnSym << '\n';
646 O << "\t.weak\t" << *CurrentFnSym << '\n';
650 printVisibility(CurrentFnSym, F->getVisibility());
652 EmitAlignment(MF.getAlignment(), F);
654 if (Subtarget.isPPC64()) {
655 // Emit an official procedure descriptor.
656 // FIXME 64-bit SVR4: Use MCSection here!
657 O << "\t.section\t\".opd\",\"aw\"\n";
659 O << *CurrentFnSym << ":\n";
660 O << "\t.quad .L." << *CurrentFnSym << ",.TOC.@tocbase\n";
661 O << "\t.previous\n";
662 O << ".L." << *CurrentFnSym << ":\n";
664 O << *CurrentFnSym << ":\n";
667 // Emit pre-function debug information.
668 DW->BeginFunction(&MF);
670 // Print out code for the function.
671 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
673 // Print a label for the basic block.
674 if (I != MF.begin()) {
675 EmitBasicBlockStart(I);
677 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
679 // Print the assembly for the instruction.
680 printMachineInstruction(II);
684 O << "\t.size\t" << *CurrentFnSym << ",.-" << *CurrentFnSym << '\n';
686 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
688 // Emit post-function debug information.
689 DW->EndFunction(&MF);
691 // Print out jump tables referenced by the function.
692 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
694 // We didn't modify anything.
698 void PPCLinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
699 const TargetData *TD = TM.getTargetData();
701 if (!GVar->hasInitializer())
702 return; // External global require no code
704 // Check to see if this is a special global used by LLVM, if so, emit it.
705 if (EmitSpecialLLVMGlobal(GVar))
708 MCSymbol *GVarSym = GetGlobalValueSymbol(GVar);
710 printVisibility(GVarSym, GVar->getVisibility());
712 Constant *C = GVar->getInitializer();
713 const Type *Type = C->getType();
714 unsigned Size = TD->getTypeAllocSize(Type);
715 unsigned Align = TD->getPreferredAlignmentLog(GVar);
717 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
719 // Handle normal common symbols.
720 if (GVKind.isCommon()) {
721 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
723 O << ".comm " << *GVarSym << ',' << Size;
724 if (MAI->getCOMMDirectiveTakesAlignment())
728 O << "\t\t" << MAI->getCommentString() << " '";
729 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
736 if (GVKind.isBSSLocal()) {
737 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
739 O << MAI->getLCOMMDirective() << *GVarSym << ',' << Size;
742 O << "\t\t" << MAI->getCommentString() << " '";
743 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
750 OutStreamer.SwitchSection(getObjFileLowering().
751 SectionForGlobal(GVar, GVKind, Mang, TM));
753 switch (GVar->getLinkage()) {
754 case GlobalValue::LinkOnceAnyLinkage:
755 case GlobalValue::LinkOnceODRLinkage:
756 case GlobalValue::WeakAnyLinkage:
757 case GlobalValue::WeakODRLinkage:
758 case GlobalValue::LinkerPrivateLinkage:
759 O << "\t.global " << *GVarSym;
760 O << "\n\t.type " << *GVarSym << ", @object\n\t.weak " << *GVarSym << '\n';
762 case GlobalValue::AppendingLinkage:
763 // FIXME: appending linkage variables should go into a section of
764 // their name or something. For now, just emit them as external.
765 case GlobalValue::ExternalLinkage:
766 // If external or appending, declare as a global symbol
767 O << "\t.global " << *GVarSym;
768 O << "\n\t.type " << *GVarSym << ", @object\n";
770 case GlobalValue::InternalLinkage:
771 case GlobalValue::PrivateLinkage:
774 llvm_unreachable("Unknown linkage type!");
777 EmitAlignment(Align, GVar);
778 O << *GVarSym << ":";
780 O << "\t\t\t\t" << MAI->getCommentString() << " '";
781 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
786 EmitGlobalConstant(C);
790 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
791 const TargetData *TD = TM.getTargetData();
793 bool isPPC64 = TD->getPointerSizeInBits() == 64;
795 if (isPPC64 && !TOC.empty()) {
796 // FIXME 64-bit SVR4: Use MCSection here?
797 O << "\t.section\t\".toc\",\"aw\"\n";
799 // FIXME: This is nondeterminstic!
800 for (DenseMap<const MCSymbol*, const MCSymbol*>::iterator I = TOC.begin(),
801 E = TOC.end(); I != E; ++I) {
802 O << *I->second << ":\n";
803 O << "\t.tc " << *I->first << "[TC]," << *I->first << '\n';
807 return AsmPrinter::doFinalization(M);
810 /// runOnMachineFunction - This uses the printMachineInstruction()
811 /// method to print assembly for each instruction.
813 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
816 SetupMachineFunction(MF);
819 // Print out constants referenced by the function
820 EmitConstantPool(MF.getConstantPool());
822 // Print out labels for the function.
823 const Function *F = MF.getFunction();
824 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
826 switch (F->getLinkage()) {
827 default: llvm_unreachable("Unknown linkage type!");
828 case Function::PrivateLinkage:
829 case Function::InternalLinkage: // Symbols default to internal.
831 case Function::ExternalLinkage:
832 O << "\t.globl\t" << *CurrentFnSym << '\n';
834 case Function::WeakAnyLinkage:
835 case Function::WeakODRLinkage:
836 case Function::LinkOnceAnyLinkage:
837 case Function::LinkOnceODRLinkage:
838 case Function::LinkerPrivateLinkage:
839 O << "\t.globl\t" << *CurrentFnSym << '\n';
840 O << "\t.weak_definition\t" << *CurrentFnSym << '\n';
844 printVisibility(CurrentFnSym, F->getVisibility());
846 EmitAlignment(MF.getAlignment(), F);
847 O << *CurrentFnSym << ":\n";
849 // Emit pre-function debug information.
850 DW->BeginFunction(&MF);
852 // If the function is empty, then we need to emit *something*. Otherwise, the
853 // function's label might be associated with something that it wasn't meant to
854 // be associated with. We emit a noop in this situation.
855 MachineFunction::iterator I = MF.begin();
857 if (++I == MF.end() && MF.front().empty())
860 // Print out code for the function.
861 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
863 // Print a label for the basic block.
864 if (I != MF.begin()) {
865 EmitBasicBlockStart(I);
867 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
869 // Print the assembly for the instruction.
870 printMachineInstruction(II);
874 // Emit post-function debug information.
875 DW->EndFunction(&MF);
877 // Print out jump tables referenced by the function.
878 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
880 // We didn't modify anything.
885 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
886 static const char *const CPUDirectives[] = {
898 unsigned Directive = Subtarget.getDarwinDirective();
899 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
900 Directive = PPC::DIR_970;
901 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
902 Directive = PPC::DIR_7400;
903 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
904 Directive = PPC::DIR_64;
905 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
906 O << "\t.machine " << CPUDirectives[Directive] << '\n';
908 // Prime text sections so they are adjacent. This reduces the likelihood a
909 // large data or debug section causes a branch to exceed 16M limit.
910 TargetLoweringObjectFileMachO &TLOFMacho =
911 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
912 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
913 if (TM.getRelocationModel() == Reloc::PIC_) {
914 OutStreamer.SwitchSection(
915 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
916 MCSectionMachO::S_SYMBOL_STUBS |
917 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
918 32, SectionKind::getText()));
919 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
920 OutStreamer.SwitchSection(
921 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
922 MCSectionMachO::S_SYMBOL_STUBS |
923 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
924 16, SectionKind::getText()));
926 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
929 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
930 const TargetData *TD = TM.getTargetData();
932 if (!GVar->hasInitializer())
933 return; // External global require no code
935 // Check to see if this is a special global used by LLVM, if so, emit it.
936 if (EmitSpecialLLVMGlobal(GVar))
939 MCSymbol *GVarSym = GetGlobalValueSymbol(GVar);
940 printVisibility(GVarSym, GVar->getVisibility());
942 Constant *C = GVar->getInitializer();
943 const Type *Type = C->getType();
944 unsigned Size = TD->getTypeAllocSize(Type);
945 unsigned Align = TD->getPreferredAlignmentLog(GVar);
947 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
949 // Handle normal common symbols.
950 if (GVKind.isCommon()) {
951 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
953 O << ".comm " << *GVarSym << ',' << Size;
954 if (MAI->getCOMMDirectiveTakesAlignment())
955 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
958 O << "\t\t" << MAI->getCommentString() << " '";
959 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
966 const MCSection *TheSection =
967 getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
969 // Handle the zerofill directive on darwin, which is a special form of BSS
971 if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
973 OutStreamer.EmitSymbolAttribute(GVarSym, MCStreamer::Global);
974 // .zerofill __DATA, __common, _foo, 400, 5
975 OutStreamer.EmitZerofill(TheSection, GVarSym, Size, 1 << Align);
979 if (GVKind.isBSSLocal()) {
980 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
982 O << MAI->getLCOMMDirective() << *GVarSym << ',' << Size << ',' << Align;
985 O << "\t\t" << MAI->getCommentString() << " '";
986 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
993 OutStreamer.SwitchSection(TheSection);
995 switch (GVar->getLinkage()) {
996 case GlobalValue::LinkOnceAnyLinkage:
997 case GlobalValue::LinkOnceODRLinkage:
998 case GlobalValue::WeakAnyLinkage:
999 case GlobalValue::WeakODRLinkage:
1000 case GlobalValue::CommonLinkage:
1001 case GlobalValue::LinkerPrivateLinkage:
1002 O << "\t.globl " << *GVarSym << "\n\t.weak_definition " << *GVarSym << '\n';
1004 case GlobalValue::AppendingLinkage:
1005 // FIXME: appending linkage variables should go into a section of
1006 // their name or something. For now, just emit them as external.
1007 case GlobalValue::ExternalLinkage:
1008 // If external or appending, declare as a global symbol
1009 O << "\t.globl " << *GVarSym << '\n';
1011 case GlobalValue::InternalLinkage:
1012 case GlobalValue::PrivateLinkage:
1015 llvm_unreachable("Unknown linkage type!");
1018 EmitAlignment(Align, GVar);
1019 O << *GVarSym << ":";
1021 O << "\t\t\t\t" << MAI->getCommentString() << " '";
1022 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1027 EmitGlobalConstant(C);
1031 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1032 const TargetData *TD = TM.getTargetData();
1034 bool isPPC64 = TD->getPointerSizeInBits() == 64;
1036 // Darwin/PPC always uses mach-o.
1037 TargetLoweringObjectFileMachO &TLOFMacho =
1038 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1041 const MCSection *LSPSection = 0;
1042 if (!FnStubs.empty()) // .lazy_symbol_pointer
1043 LSPSection = TLOFMacho.getLazySymbolPointerSection();
1046 // Output stubs for dynamically-linked functions
1047 if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
1048 const MCSection *StubSection =
1049 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
1050 MCSectionMachO::S_SYMBOL_STUBS |
1051 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1052 32, SectionKind::getText());
1053 // FIXME: This is emitting in nondeterminstic order!
1054 for (DenseMap<const MCSymbol*, FnStubInfo>::iterator I =
1055 FnStubs.begin(), E = FnStubs.end(); I != E; ++I) {
1056 OutStreamer.SwitchSection(StubSection);
1058 const FnStubInfo &Info = I->second;
1059 O << *Info.Stub << ":\n";
1060 O << "\t.indirect_symbol " << *I->first << '\n';
1062 O << "\tbcl 20,31," << *Info.AnonSymbol << '\n';
1063 O << *Info.AnonSymbol << ":\n";
1064 O << "\tmflr r11\n";
1065 O << "\taddis r11,r11,ha16(" << *Info.LazyPtr << '-' << *Info.AnonSymbol
1068 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *Info.LazyPtr
1069 << '-' << *Info.AnonSymbol << ")(r11)\n";
1070 O << "\tmtctr r12\n";
1073 OutStreamer.SwitchSection(LSPSection);
1074 O << *Info.LazyPtr << ":\n";
1075 O << "\t.indirect_symbol " << *I->first << '\n';
1076 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1078 } else if (!FnStubs.empty()) {
1079 const MCSection *StubSection =
1080 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
1081 MCSectionMachO::S_SYMBOL_STUBS |
1082 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1083 16, SectionKind::getText());
1085 // FIXME: This is emitting in nondeterminstic order!
1086 for (DenseMap<const MCSymbol*, FnStubInfo>::iterator I = FnStubs.begin(),
1087 E = FnStubs.end(); I != E; ++I) {
1088 OutStreamer.SwitchSection(StubSection);
1090 const FnStubInfo &Info = I->second;
1091 O << *Info.Stub << ":\n";
1092 O << "\t.indirect_symbol " << *I->first << '\n';
1093 O << "\tlis r11,ha16(" << *Info.LazyPtr << ")\n";
1094 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *Info.LazyPtr
1096 O << "\tmtctr r12\n";
1098 OutStreamer.SwitchSection(LSPSection);
1099 O << *Info.LazyPtr << ":\n";
1100 O << "\t.indirect_symbol " << *I->first << '\n';
1101 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1107 if (MAI->doesSupportExceptionHandling() && MMI) {
1108 // Add the (possibly multiple) personalities to the set of global values.
1109 // Only referenced functions get into the Personalities list.
1110 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1111 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1112 E = Personalities.end(); I != E; ++I) {
1114 GVStubs[GetGlobalValueSymbol(*I)] =
1115 GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
1119 // Output macho stubs for external and common global variables.
1120 if (!GVStubs.empty()) {
1121 // Switch with ".non_lazy_symbol_pointer" directive.
1122 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1123 EmitAlignment(isPPC64 ? 3 : 2);
1125 // FIXME: This is nondeterminstic.
1126 for (DenseMap<const MCSymbol *, const MCSymbol *>::iterator
1127 I = GVStubs.begin(), E = GVStubs.end(); I != E; ++I) {
1128 O << *I->second << ":\n";
1129 O << "\t.indirect_symbol " << *I->first << '\n';
1130 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1134 if (!HiddenGVStubs.empty()) {
1135 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
1136 EmitAlignment(isPPC64 ? 3 : 2);
1137 // FIXME: This is nondeterminstic.
1138 for (DenseMap<const MCSymbol *, const MCSymbol *>::iterator
1139 I = HiddenGVStubs.begin(), E = HiddenGVStubs.end(); I != E; ++I) {
1140 O << *I->second << ":\n";
1141 O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << *I->first << '\n';
1145 // Funny Darwin hack: This flag tells the linker that no global symbols
1146 // contain code that falls through to other global symbols (e.g. the obvious
1147 // implementation of multiple entry points). If this doesn't occur, the
1148 // linker can safely perform dead code stripping. Since LLVM never generates
1149 // code that does this, it is always safe to set.
1150 OutStreamer.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
1152 return AsmPrinter::doFinalization(M);
1157 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1158 /// for a MachineFunction to the given output stream, in a format that the
1159 /// Darwin assembler can deal with.
1161 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1163 const MCAsmInfo *tai,
1165 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1167 if (Subtarget->isDarwin())
1168 return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
1169 return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
1172 // Force static initialization.
1173 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1174 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1175 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);