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 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(GVar, Mang,
720 if (C->isNullValue() && /* FIXME: Verify correct */
721 !GVar->hasSection() &&
722 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
723 GVar->isWeakForLinker())) {
724 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
726 if (GVar->hasExternalLinkage()) {
727 O << "\t.global " << *GVarSym << '\n';
728 O << "\t.type " << *GVarSym << ", @object\n";
729 O << *GVarSym << ":\n";
730 O << "\t.zero " << Size << '\n';
731 } else if (GVar->hasLocalLinkage()) {
732 O << MAI->getLCOMMDirective() << *GVarSym << ',' << Size;
734 O << ".comm " << *GVarSym << ',' << Size;
737 O << "\t\t" << MAI->getCommentString() << " '";
738 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
745 switch (GVar->getLinkage()) {
746 case GlobalValue::LinkOnceAnyLinkage:
747 case GlobalValue::LinkOnceODRLinkage:
748 case GlobalValue::WeakAnyLinkage:
749 case GlobalValue::WeakODRLinkage:
750 case GlobalValue::CommonLinkage:
751 case GlobalValue::LinkerPrivateLinkage:
752 O << "\t.global " << *GVarSym;
753 O << "\n\t.type " << *GVarSym << ", @object\n\t.weak " << *GVarSym << '\n';
755 case GlobalValue::AppendingLinkage:
756 // FIXME: appending linkage variables should go into a section of
757 // their name or something. For now, just emit them as external.
758 case GlobalValue::ExternalLinkage:
759 // If external or appending, declare as a global symbol
760 O << "\t.global " << *GVarSym;
761 O << "\n\t.type " << *GVarSym << ", @object\n";
763 case GlobalValue::InternalLinkage:
764 case GlobalValue::PrivateLinkage:
767 llvm_unreachable("Unknown linkage type!");
770 EmitAlignment(Align, GVar);
771 O << *GVarSym << ":";
773 O << "\t\t\t\t" << MAI->getCommentString() << " '";
774 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
779 EmitGlobalConstant(C);
783 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
784 const TargetData *TD = TM.getTargetData();
786 bool isPPC64 = TD->getPointerSizeInBits() == 64;
788 if (isPPC64 && !TOC.empty()) {
789 // FIXME 64-bit SVR4: Use MCSection here?
790 O << "\t.section\t\".toc\",\"aw\"\n";
792 // FIXME: This is nondeterminstic!
793 for (DenseMap<const MCSymbol*, const MCSymbol*>::iterator I = TOC.begin(),
794 E = TOC.end(); I != E; ++I) {
795 O << *I->second << ":\n";
796 O << "\t.tc " << *I->first << "[TC]," << *I->first << '\n';
800 return AsmPrinter::doFinalization(M);
803 /// runOnMachineFunction - This uses the printMachineInstruction()
804 /// method to print assembly for each instruction.
806 bool PPCDarwinAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
809 SetupMachineFunction(MF);
812 // Print out constants referenced by the function
813 EmitConstantPool(MF.getConstantPool());
815 // Print out labels for the function.
816 const Function *F = MF.getFunction();
817 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
819 switch (F->getLinkage()) {
820 default: llvm_unreachable("Unknown linkage type!");
821 case Function::PrivateLinkage:
822 case Function::InternalLinkage: // Symbols default to internal.
824 case Function::ExternalLinkage:
825 O << "\t.globl\t" << *CurrentFnSym << '\n';
827 case Function::WeakAnyLinkage:
828 case Function::WeakODRLinkage:
829 case Function::LinkOnceAnyLinkage:
830 case Function::LinkOnceODRLinkage:
831 case Function::LinkerPrivateLinkage:
832 O << "\t.globl\t" << *CurrentFnSym << '\n';
833 O << "\t.weak_definition\t" << *CurrentFnSym << '\n';
837 printVisibility(CurrentFnSym, F->getVisibility());
839 EmitAlignment(MF.getAlignment(), F);
840 O << *CurrentFnSym << ":\n";
842 // Emit pre-function debug information.
843 DW->BeginFunction(&MF);
845 // If the function is empty, then we need to emit *something*. Otherwise, the
846 // function's label might be associated with something that it wasn't meant to
847 // be associated with. We emit a noop in this situation.
848 MachineFunction::iterator I = MF.begin();
850 if (++I == MF.end() && MF.front().empty())
853 // Print out code for the function.
854 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
856 // Print a label for the basic block.
857 if (I != MF.begin()) {
858 EmitBasicBlockStart(I);
860 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
862 // Print the assembly for the instruction.
863 printMachineInstruction(II);
867 // Emit post-function debug information.
868 DW->EndFunction(&MF);
870 // Print out jump tables referenced by the function.
871 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
873 // We didn't modify anything.
878 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
879 static const char *const CPUDirectives[] = {
891 unsigned Directive = Subtarget.getDarwinDirective();
892 if (Subtarget.isGigaProcessor() && Directive < PPC::DIR_970)
893 Directive = PPC::DIR_970;
894 if (Subtarget.hasAltivec() && Directive < PPC::DIR_7400)
895 Directive = PPC::DIR_7400;
896 if (Subtarget.isPPC64() && Directive < PPC::DIR_970)
897 Directive = PPC::DIR_64;
898 assert(Directive <= PPC::DIR_64 && "Directive out of range.");
899 O << "\t.machine " << CPUDirectives[Directive] << '\n';
901 // Prime text sections so they are adjacent. This reduces the likelihood a
902 // large data or debug section causes a branch to exceed 16M limit.
903 TargetLoweringObjectFileMachO &TLOFMacho =
904 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
905 OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
906 if (TM.getRelocationModel() == Reloc::PIC_) {
907 OutStreamer.SwitchSection(
908 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
909 MCSectionMachO::S_SYMBOL_STUBS |
910 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
911 32, SectionKind::getText()));
912 } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
913 OutStreamer.SwitchSection(
914 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
915 MCSectionMachO::S_SYMBOL_STUBS |
916 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
917 16, SectionKind::getText()));
919 OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
922 void PPCDarwinAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
923 const TargetData *TD = TM.getTargetData();
925 if (!GVar->hasInitializer())
926 return; // External global require no code
928 // Check to see if this is a special global used by LLVM, if so, emit it.
929 if (EmitSpecialLLVMGlobal(GVar)) {
930 if (TM.getRelocationModel() == Reloc::Static) {
931 if (GVar->getName() == "llvm.global_ctors")
932 O << ".reference .constructors_used\n";
933 else if (GVar->getName() == "llvm.global_dtors")
934 O << ".reference .destructors_used\n";
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);
948 const MCSection *TheSection =
949 getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
950 OutStreamer.SwitchSection(TheSection);
952 // Handle the zerofill directive on darwin, which is a special form of BSS
954 if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective()) {
955 TargetLoweringObjectFileMachO &TLOFMacho =
956 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
957 if (TLOFMacho.isDataCommonSection(TheSection)) {
959 OutStreamer.EmitSymbolAttribute(GVarSym, MCStreamer::Global);
960 // .zerofill __DATA, __common, _foo, 400, 5
961 OutStreamer.EmitZerofill(TheSection, GVarSym, Size, 1 << Align);
966 /// FIXME: Drive this off the section!
967 if (C->isNullValue() && /* FIXME: Verify correct */
968 !GVar->hasSection() &&
969 (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
970 GVar->isWeakForLinker()) &&
971 // Don't put things that should go in the cstring section into "comm".
972 !TheSection->getKind().isMergeableCString()) {
973 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
975 if (GVar->hasLocalLinkage()) {
976 O << MAI->getLCOMMDirective() << *GVarSym << ',' << Size << ',' << Align;
977 } else if (!GVar->hasCommonLinkage()) {
978 O << "\t.globl " << *GVarSym << '\n' << MAI->getWeakDefDirective();
979 O << *GVarSym << '\n';
980 EmitAlignment(Align, GVar);
981 O << *GVarSym << ":";
983 O << "\t\t\t\t" << MAI->getCommentString() << " ";
984 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
987 EmitGlobalConstant(C);
990 O << ".comm " << *GVarSym << ',' << Size;
991 // Darwin 9 and above support aligned common data.
992 if (Subtarget.isDarwin9())
996 O << "\t\t" << MAI->getCommentString() << " '";
997 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1004 switch (GVar->getLinkage()) {
1005 case GlobalValue::LinkOnceAnyLinkage:
1006 case GlobalValue::LinkOnceODRLinkage:
1007 case GlobalValue::WeakAnyLinkage:
1008 case GlobalValue::WeakODRLinkage:
1009 case GlobalValue::CommonLinkage:
1010 case GlobalValue::LinkerPrivateLinkage:
1011 O << "\t.globl " << *GVarSym << "\n\t.weak_definition " << *GVarSym << '\n';
1013 case GlobalValue::AppendingLinkage:
1014 // FIXME: appending linkage variables should go into a section of
1015 // their name or something. For now, just emit them as external.
1016 case GlobalValue::ExternalLinkage:
1017 // If external or appending, declare as a global symbol
1018 O << "\t.globl " << *GVarSym << '\n';
1020 case GlobalValue::InternalLinkage:
1021 case GlobalValue::PrivateLinkage:
1024 llvm_unreachable("Unknown linkage type!");
1027 EmitAlignment(Align, GVar);
1028 O << *GVarSym << ":";
1030 O << "\t\t\t\t" << MAI->getCommentString() << " '";
1031 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
1036 EmitGlobalConstant(C);
1040 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1041 const TargetData *TD = TM.getTargetData();
1043 bool isPPC64 = TD->getPointerSizeInBits() == 64;
1045 // Darwin/PPC always uses mach-o.
1046 TargetLoweringObjectFileMachO &TLOFMacho =
1047 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
1050 const MCSection *LSPSection = 0;
1051 if (!FnStubs.empty()) // .lazy_symbol_pointer
1052 LSPSection = TLOFMacho.getLazySymbolPointerSection();
1055 // Output stubs for dynamically-linked functions
1056 if (TM.getRelocationModel() == Reloc::PIC_ && !FnStubs.empty()) {
1057 const MCSection *StubSection =
1058 TLOFMacho.getMachOSection("__TEXT", "__picsymbolstub1",
1059 MCSectionMachO::S_SYMBOL_STUBS |
1060 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1061 32, SectionKind::getText());
1062 // FIXME: This is emitting in nondeterminstic order!
1063 for (DenseMap<const MCSymbol*, FnStubInfo>::iterator I =
1064 FnStubs.begin(), E = FnStubs.end(); I != E; ++I) {
1065 OutStreamer.SwitchSection(StubSection);
1067 const FnStubInfo &Info = I->second;
1068 O << *Info.Stub << ":\n";
1069 O << "\t.indirect_symbol " << *I->first << '\n';
1071 O << "\tbcl 20,31," << *Info.AnonSymbol << '\n';
1072 O << *Info.AnonSymbol << ":\n";
1073 O << "\tmflr r11\n";
1074 O << "\taddis r11,r11,ha16(" << *Info.LazyPtr << '-' << *Info.AnonSymbol
1077 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *Info.LazyPtr
1078 << '-' << *Info.AnonSymbol << ")(r11)\n";
1079 O << "\tmtctr r12\n";
1082 OutStreamer.SwitchSection(LSPSection);
1083 O << *Info.LazyPtr << ":\n";
1084 O << "\t.indirect_symbol " << *I->first << '\n';
1085 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1087 } else if (!FnStubs.empty()) {
1088 const MCSection *StubSection =
1089 TLOFMacho.getMachOSection("__TEXT","__symbol_stub1",
1090 MCSectionMachO::S_SYMBOL_STUBS |
1091 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
1092 16, SectionKind::getText());
1094 // FIXME: This is emitting in nondeterminstic order!
1095 for (DenseMap<const MCSymbol*, FnStubInfo>::iterator I = FnStubs.begin(),
1096 E = FnStubs.end(); I != E; ++I) {
1097 OutStreamer.SwitchSection(StubSection);
1099 const FnStubInfo &Info = I->second;
1100 O << *Info.Stub << ":\n";
1101 O << "\t.indirect_symbol " << *I->first << '\n';
1102 O << "\tlis r11,ha16(" << *Info.LazyPtr << ")\n";
1103 O << (isPPC64 ? "\tldu" : "\tlwzu") << " r12,lo16(" << *Info.LazyPtr
1105 O << "\tmtctr r12\n";
1107 OutStreamer.SwitchSection(LSPSection);
1108 O << *Info.LazyPtr << ":\n";
1109 O << "\t.indirect_symbol " << *I->first << '\n';
1110 O << (isPPC64 ? "\t.quad" : "\t.long") << " dyld_stub_binding_helper\n";
1116 if (MAI->doesSupportExceptionHandling() && MMI) {
1117 // Add the (possibly multiple) personalities to the set of global values.
1118 // Only referenced functions get into the Personalities list.
1119 const std::vector<Function *> &Personalities = MMI->getPersonalities();
1120 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1121 E = Personalities.end(); I != E; ++I) {
1123 GVStubs[GetGlobalValueSymbol(*I)] =
1124 GetSymbolWithGlobalValueBase(*I, "$non_lazy_ptr");
1128 // Output macho stubs for external and common global variables.
1129 if (!GVStubs.empty()) {
1130 // Switch with ".non_lazy_symbol_pointer" directive.
1131 OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1132 EmitAlignment(isPPC64 ? 3 : 2);
1134 // FIXME: This is nondeterminstic.
1135 for (DenseMap<const MCSymbol *, const MCSymbol *>::iterator
1136 I = GVStubs.begin(), E = GVStubs.end(); I != E; ++I) {
1137 O << *I->second << ":\n";
1138 O << "\t.indirect_symbol " << *I->first << '\n';
1139 O << (isPPC64 ? "\t.quad\t0\n" : "\t.long\t0\n");
1143 if (!HiddenGVStubs.empty()) {
1144 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
1145 EmitAlignment(isPPC64 ? 3 : 2);
1146 // FIXME: This is nondeterminstic.
1147 for (DenseMap<const MCSymbol *, const MCSymbol *>::iterator
1148 I = HiddenGVStubs.begin(), E = HiddenGVStubs.end(); I != E; ++I) {
1149 O << *I->second << ":\n";
1150 O << (isPPC64 ? "\t.quad\t" : "\t.long\t") << *I->first << '\n';
1154 // Funny Darwin hack: This flag tells the linker that no global symbols
1155 // contain code that falls through to other global symbols (e.g. the obvious
1156 // implementation of multiple entry points). If this doesn't occur, the
1157 // linker can safely perform dead code stripping. Since LLVM never generates
1158 // code that does this, it is always safe to set.
1159 OutStreamer.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
1161 return AsmPrinter::doFinalization(M);
1166 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1167 /// for a MachineFunction to the given output stream, in a format that the
1168 /// Darwin assembler can deal with.
1170 static AsmPrinter *createPPCAsmPrinterPass(formatted_raw_ostream &o,
1172 const MCAsmInfo *tai,
1174 const PPCSubtarget *Subtarget = &tm.getSubtarget<PPCSubtarget>();
1176 if (Subtarget->isDarwin())
1177 return new PPCDarwinAsmPrinter(o, tm, tai, verbose);
1178 return new PPCLinuxAsmPrinter(o, tm, tai, verbose);
1181 // Force static initialization.
1182 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1183 TargetRegistry::RegisterAsmPrinter(ThePPC32Target, createPPCAsmPrinterPass);
1184 TargetRegistry::RegisterAsmPrinter(ThePPC64Target, createPPCAsmPrinterPass);