1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains a printer that converts from our internal representation
10 // of machine-dependent LLVM code to PowerPC assembly language. This printer is
11 // the output mechanism used by `llc'.
12 //
13 // Documentation at http://developer.apple.com/documentation/DeveloperTools/
14 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
15 //
16 //===----------------------------------------------------------------------===//
17 
18 #include "MCTargetDesc/PPCInstPrinter.h"
19 #include "MCTargetDesc/PPCMCExpr.h"
20 #include "MCTargetDesc/PPCMCTargetDesc.h"
21 #include "MCTargetDesc/PPCPredicates.h"
22 #include "PPC.h"
23 #include "PPCInstrInfo.h"
24 #include "PPCMachineFunctionInfo.h"
25 #include "PPCSubtarget.h"
26 #include "PPCTargetMachine.h"
27 #include "PPCTargetStreamer.h"
28 #include "TargetInfo/PowerPCTargetInfo.h"
29 #include "llvm/ADT/MapVector.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/ADT/Triple.h"
33 #include "llvm/ADT/Twine.h"
34 #include "llvm/BinaryFormat/ELF.h"
35 #include "llvm/BinaryFormat/MachO.h"
36 #include "llvm/CodeGen/AsmPrinter.h"
37 #include "llvm/CodeGen/MachineBasicBlock.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstr.h"
40 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
41 #include "llvm/CodeGen/MachineOperand.h"
42 #include "llvm/CodeGen/MachineRegisterInfo.h"
43 #include "llvm/CodeGen/StackMaps.h"
44 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
45 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/GlobalValue.h"
47 #include "llvm/IR/GlobalVariable.h"
48 #include "llvm/IR/Module.h"
49 #include "llvm/MC/MCAsmInfo.h"
50 #include "llvm/MC/MCContext.h"
51 #include "llvm/MC/MCDirectives.h"
52 #include "llvm/MC/MCExpr.h"
53 #include "llvm/MC/MCInst.h"
54 #include "llvm/MC/MCInstBuilder.h"
55 #include "llvm/MC/MCSectionELF.h"
56 #include "llvm/MC/MCSectionMachO.h"
57 #include "llvm/MC/MCSectionXCOFF.h"
58 #include "llvm/MC/MCStreamer.h"
59 #include "llvm/MC/MCSymbol.h"
60 #include "llvm/MC/MCSymbolELF.h"
61 #include "llvm/MC/MCSymbolXCOFF.h"
62 #include "llvm/MC/SectionKind.h"
63 #include "llvm/Support/Casting.h"
64 #include "llvm/Support/CodeGen.h"
65 #include "llvm/Support/Debug.h"
66 #include "llvm/Support/ErrorHandling.h"
67 #include "llvm/Support/Process.h"
68 #include "llvm/Support/TargetRegistry.h"
69 #include "llvm/Support/raw_ostream.h"
70 #include "llvm/Target/TargetMachine.h"
71 #include "llvm/Transforms/Utils/ModuleUtils.h"
72 #include <algorithm>
73 #include <cassert>
74 #include <cstdint>
75 #include <memory>
76 #include <new>
77 
78 using namespace llvm;
79 
80 #define DEBUG_TYPE "asmprinter"
81 
82 namespace {
83 
84 class PPCAsmPrinter : public AsmPrinter {
85 protected:
86   MapVector<const MCSymbol *, MCSymbol *> TOC;
87   const PPCSubtarget *Subtarget = nullptr;
88   StackMaps SM;
89 
90 public:
91   explicit PPCAsmPrinter(TargetMachine &TM,
92                          std::unique_ptr<MCStreamer> Streamer)
93       : AsmPrinter(TM, std::move(Streamer)), SM(*this) {}
94 
95   StringRef getPassName() const override { return "PowerPC Assembly Printer"; }
96 
97   MCSymbol *lookUpOrCreateTOCEntry(const MCSymbol *Sym);
98 
99   bool doInitialization(Module &M) override {
100     if (!TOC.empty())
101       TOC.clear();
102     return AsmPrinter::doInitialization(M);
103   }
104 
105   void emitInstruction(const MachineInstr *MI) override;
106 
107   /// This function is for PrintAsmOperand and PrintAsmMemoryOperand,
108   /// invoked by EmitMSInlineAsmStr and EmitGCCInlineAsmStr only.
109   /// The \p MI would be INLINEASM ONLY.
110   void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
111 
112   void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &O) override;
113   bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
114                        const char *ExtraCode, raw_ostream &O) override;
115   bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
116                              const char *ExtraCode, raw_ostream &O) override;
117 
118   void emitEndOfAsmFile(Module &M) override;
119 
120   void LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI);
121   void LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI);
122   void EmitTlsCall(const MachineInstr *MI, MCSymbolRefExpr::VariantKind VK);
123   bool runOnMachineFunction(MachineFunction &MF) override {
124     Subtarget = &MF.getSubtarget<PPCSubtarget>();
125     bool Changed = AsmPrinter::runOnMachineFunction(MF);
126     emitXRayTable();
127     return Changed;
128   }
129 };
130 
131 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
132 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
133 public:
134   explicit PPCLinuxAsmPrinter(TargetMachine &TM,
135                               std::unique_ptr<MCStreamer> Streamer)
136       : PPCAsmPrinter(TM, std::move(Streamer)) {}
137 
138   StringRef getPassName() const override {
139     return "Linux PPC Assembly Printer";
140   }
141 
142   void emitStartOfAsmFile(Module &M) override;
143   void emitEndOfAsmFile(Module &) override;
144 
145   void emitFunctionEntryLabel() override;
146 
147   void emitFunctionBodyStart() override;
148   void emitFunctionBodyEnd() override;
149   void emitInstruction(const MachineInstr *MI) override;
150 };
151 
152 class PPCAIXAsmPrinter : public PPCAsmPrinter {
153 private:
154   /// Symbols lowered from ExternalSymbolSDNodes, we will need to emit extern
155   /// linkage for them in AIX.
156   SmallPtrSet<MCSymbol *, 8> ExtSymSDNodeSymbols;
157 
158   /// A format indicator and unique trailing identifier to form part of the
159   /// sinit/sterm function names.
160   std::string FormatIndicatorAndUniqueModId;
161 
162   static void ValidateGV(const GlobalVariable *GV);
163   // Record a list of GlobalAlias associated with a GlobalObject.
164   // This is used for AIX's extra-label-at-definition aliasing strategy.
165   DenseMap<const GlobalObject *, SmallVector<const GlobalAlias *, 1>>
166       GOAliasMap;
167 
168 public:
169   PPCAIXAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
170       : PPCAsmPrinter(TM, std::move(Streamer)) {
171     if (MAI->isLittleEndian())
172       report_fatal_error(
173           "cannot create AIX PPC Assembly Printer for a little-endian target");
174   }
175 
176   StringRef getPassName() const override { return "AIX PPC Assembly Printer"; }
177 
178   bool doInitialization(Module &M) override;
179 
180   void emitXXStructorList(const DataLayout &DL, const Constant *List,
181                           bool IsCtor) override;
182 
183   void SetupMachineFunction(MachineFunction &MF) override;
184 
185   void emitGlobalVariable(const GlobalVariable *GV) override;
186 
187   void emitFunctionDescriptor() override;
188 
189   void emitFunctionEntryLabel() override;
190 
191   void emitEndOfAsmFile(Module &) override;
192 
193   void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const override;
194 
195   void emitInstruction(const MachineInstr *MI) override;
196 
197   bool doFinalization(Module &M) override;
198 };
199 
200 } // end anonymous namespace
201 
202 void PPCAsmPrinter::PrintSymbolOperand(const MachineOperand &MO,
203                                        raw_ostream &O) {
204   // Computing the address of a global symbol, not calling it.
205   const GlobalValue *GV = MO.getGlobal();
206   getSymbol(GV)->print(O, MAI);
207   printOffset(MO.getOffset(), O);
208 }
209 
210 void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
211                                  raw_ostream &O) {
212   const DataLayout &DL = getDataLayout();
213   const MachineOperand &MO = MI->getOperand(OpNo);
214 
215   switch (MO.getType()) {
216   case MachineOperand::MO_Register: {
217     // The MI is INLINEASM ONLY and UseVSXReg is always false.
218     const char *RegName = PPCInstPrinter::getRegisterName(MO.getReg());
219 
220     // Linux assembler (Others?) does not take register mnemonics.
221     // FIXME - What about special registers used in mfspr/mtspr?
222     O << PPCRegisterInfo::stripRegisterPrefix(RegName);
223     return;
224   }
225   case MachineOperand::MO_Immediate:
226     O << MO.getImm();
227     return;
228 
229   case MachineOperand::MO_MachineBasicBlock:
230     MO.getMBB()->getSymbol()->print(O, MAI);
231     return;
232   case MachineOperand::MO_ConstantPoolIndex:
233     O << DL.getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
234       << MO.getIndex();
235     return;
236   case MachineOperand::MO_BlockAddress:
237     GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI);
238     return;
239   case MachineOperand::MO_GlobalAddress: {
240     PrintSymbolOperand(MO, O);
241     return;
242   }
243 
244   default:
245     O << "<unknown operand type: " << (unsigned)MO.getType() << ">";
246     return;
247   }
248 }
249 
250 /// PrintAsmOperand - Print out an operand for an inline asm expression.
251 ///
252 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
253                                     const char *ExtraCode, raw_ostream &O) {
254   // Does this asm operand have a single letter operand modifier?
255   if (ExtraCode && ExtraCode[0]) {
256     if (ExtraCode[1] != 0) return true; // Unknown modifier.
257 
258     switch (ExtraCode[0]) {
259     default:
260       // See if this is a generic print operand
261       return AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O);
262     case 'L': // Write second word of DImode reference.
263       // Verify that this operand has two consecutive registers.
264       if (!MI->getOperand(OpNo).isReg() ||
265           OpNo+1 == MI->getNumOperands() ||
266           !MI->getOperand(OpNo+1).isReg())
267         return true;
268       ++OpNo;   // Return the high-part.
269       break;
270     case 'I':
271       // Write 'i' if an integer constant, otherwise nothing.  Used to print
272       // addi vs add, etc.
273       if (MI->getOperand(OpNo).isImm())
274         O << "i";
275       return false;
276     case 'x':
277       if(!MI->getOperand(OpNo).isReg())
278         return true;
279       // This operand uses VSX numbering.
280       // If the operand is a VMX register, convert it to a VSX register.
281       Register Reg = MI->getOperand(OpNo).getReg();
282       if (PPCInstrInfo::isVRRegister(Reg))
283         Reg = PPC::VSX32 + (Reg - PPC::V0);
284       else if (PPCInstrInfo::isVFRegister(Reg))
285         Reg = PPC::VSX32 + (Reg - PPC::VF0);
286       const char *RegName;
287       RegName = PPCInstPrinter::getRegisterName(Reg);
288       RegName = PPCRegisterInfo::stripRegisterPrefix(RegName);
289       O << RegName;
290       return false;
291     }
292   }
293 
294   printOperand(MI, OpNo, O);
295   return false;
296 }
297 
298 // At the moment, all inline asm memory operands are a single register.
299 // In any case, the output of this routine should always be just one
300 // assembler operand.
301 
302 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
303                                           const char *ExtraCode,
304                                           raw_ostream &O) {
305   if (ExtraCode && ExtraCode[0]) {
306     if (ExtraCode[1] != 0) return true; // Unknown modifier.
307 
308     switch (ExtraCode[0]) {
309     default: return true;  // Unknown modifier.
310     case 'L': // A memory reference to the upper word of a double word op.
311       O << getDataLayout().getPointerSize() << "(";
312       printOperand(MI, OpNo, O);
313       O << ")";
314       return false;
315     case 'y': // A memory reference for an X-form instruction
316       O << "0, ";
317       printOperand(MI, OpNo, O);
318       return false;
319     case 'U': // Print 'u' for update form.
320     case 'X': // Print 'x' for indexed form.
321       // FIXME: Currently for PowerPC memory operands are always loaded
322       // into a register, so we never get an update or indexed form.
323       // This is bad even for offset forms, since even if we know we
324       // have a value in -16(r1), we will generate a load into r<n>
325       // and then load from 0(r<n>).  Until that issue is fixed,
326       // tolerate 'U' and 'X' but don't output anything.
327       assert(MI->getOperand(OpNo).isReg());
328       return false;
329     }
330   }
331 
332   assert(MI->getOperand(OpNo).isReg());
333   O << "0(";
334   printOperand(MI, OpNo, O);
335   O << ")";
336   return false;
337 }
338 
339 /// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry
340 /// exists for it.  If not, create one.  Then return a symbol that references
341 /// the TOC entry.
342 MCSymbol *PPCAsmPrinter::lookUpOrCreateTOCEntry(const MCSymbol *Sym) {
343   MCSymbol *&TOCEntry = TOC[Sym];
344   if (!TOCEntry)
345     TOCEntry = createTempSymbol("C");
346   return TOCEntry;
347 }
348 
349 void PPCAsmPrinter::emitEndOfAsmFile(Module &M) {
350   emitStackMaps(SM);
351 }
352 
353 void PPCAsmPrinter::LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI) {
354   unsigned NumNOPBytes = MI.getOperand(1).getImm();
355 
356   auto &Ctx = OutStreamer->getContext();
357   MCSymbol *MILabel = Ctx.createTempSymbol();
358   OutStreamer->emitLabel(MILabel);
359 
360   SM.recordStackMap(*MILabel, MI);
361   assert(NumNOPBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
362 
363   // Scan ahead to trim the shadow.
364   const MachineBasicBlock &MBB = *MI.getParent();
365   MachineBasicBlock::const_iterator MII(MI);
366   ++MII;
367   while (NumNOPBytes > 0) {
368     if (MII == MBB.end() || MII->isCall() ||
369         MII->getOpcode() == PPC::DBG_VALUE ||
370         MII->getOpcode() == TargetOpcode::PATCHPOINT ||
371         MII->getOpcode() == TargetOpcode::STACKMAP)
372       break;
373     ++MII;
374     NumNOPBytes -= 4;
375   }
376 
377   // Emit nops.
378   for (unsigned i = 0; i < NumNOPBytes; i += 4)
379     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
380 }
381 
382 // Lower a patchpoint of the form:
383 // [<def>], <id>, <numBytes>, <target>, <numArgs>
384 void PPCAsmPrinter::LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI) {
385   auto &Ctx = OutStreamer->getContext();
386   MCSymbol *MILabel = Ctx.createTempSymbol();
387   OutStreamer->emitLabel(MILabel);
388 
389   SM.recordPatchPoint(*MILabel, MI);
390   PatchPointOpers Opers(&MI);
391 
392   unsigned EncodedBytes = 0;
393   const MachineOperand &CalleeMO = Opers.getCallTarget();
394 
395   if (CalleeMO.isImm()) {
396     int64_t CallTarget = CalleeMO.getImm();
397     if (CallTarget) {
398       assert((CallTarget & 0xFFFFFFFFFFFF) == CallTarget &&
399              "High 16 bits of call target should be zero.");
400       Register ScratchReg = MI.getOperand(Opers.getNextScratchIdx()).getReg();
401       EncodedBytes = 0;
402       // Materialize the jump address:
403       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI8)
404                                       .addReg(ScratchReg)
405                                       .addImm((CallTarget >> 32) & 0xFFFF));
406       ++EncodedBytes;
407       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::RLDIC)
408                                       .addReg(ScratchReg)
409                                       .addReg(ScratchReg)
410                                       .addImm(32).addImm(16));
411       ++EncodedBytes;
412       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORIS8)
413                                       .addReg(ScratchReg)
414                                       .addReg(ScratchReg)
415                                       .addImm((CallTarget >> 16) & 0xFFFF));
416       ++EncodedBytes;
417       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORI8)
418                                       .addReg(ScratchReg)
419                                       .addReg(ScratchReg)
420                                       .addImm(CallTarget & 0xFFFF));
421 
422       // Save the current TOC pointer before the remote call.
423       int TOCSaveOffset = Subtarget->getFrameLowering()->getTOCSaveOffset();
424       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::STD)
425                                       .addReg(PPC::X2)
426                                       .addImm(TOCSaveOffset)
427                                       .addReg(PPC::X1));
428       ++EncodedBytes;
429 
430       // If we're on ELFv1, then we need to load the actual function pointer
431       // from the function descriptor.
432       if (!Subtarget->isELFv2ABI()) {
433         // Load the new TOC pointer and the function address, but not r11
434         // (needing this is rare, and loading it here would prevent passing it
435         // via a 'nest' parameter.
436         EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
437                                         .addReg(PPC::X2)
438                                         .addImm(8)
439                                         .addReg(ScratchReg));
440         ++EncodedBytes;
441         EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
442                                         .addReg(ScratchReg)
443                                         .addImm(0)
444                                         .addReg(ScratchReg));
445         ++EncodedBytes;
446       }
447 
448       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTCTR8)
449                                       .addReg(ScratchReg));
450       ++EncodedBytes;
451       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BCTRL8));
452       ++EncodedBytes;
453 
454       // Restore the TOC pointer after the call.
455       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
456                                       .addReg(PPC::X2)
457                                       .addImm(TOCSaveOffset)
458                                       .addReg(PPC::X1));
459       ++EncodedBytes;
460     }
461   } else if (CalleeMO.isGlobal()) {
462     const GlobalValue *GValue = CalleeMO.getGlobal();
463     MCSymbol *MOSymbol = getSymbol(GValue);
464     const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, OutContext);
465 
466     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL8_NOP)
467                                     .addExpr(SymVar));
468     EncodedBytes += 2;
469   }
470 
471   // Each instruction is 4 bytes.
472   EncodedBytes *= 4;
473 
474   // Emit padding.
475   unsigned NumBytes = Opers.getNumPatchBytes();
476   assert(NumBytes >= EncodedBytes &&
477          "Patchpoint can't request size less than the length of a call.");
478   assert((NumBytes - EncodedBytes) % 4 == 0 &&
479          "Invalid number of NOP bytes requested!");
480   for (unsigned i = EncodedBytes; i < NumBytes; i += 4)
481     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
482 }
483 
484 /// EmitTlsCall -- Given a GETtls[ld]ADDR[32] instruction, print a
485 /// call to __tls_get_addr to the current output stream.
486 void PPCAsmPrinter::EmitTlsCall(const MachineInstr *MI,
487                                 MCSymbolRefExpr::VariantKind VK) {
488   StringRef Name = "__tls_get_addr";
489   MCSymbol *TlsGetAddr = OutContext.getOrCreateSymbol(Name);
490   MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None;
491   unsigned Opcode = PPC::BL8_NOP_TLS;
492 
493   assert(MI->getNumOperands() >= 3 && "Expecting at least 3 operands from MI");
494   if (MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSGD_PCREL_FLAG ||
495       MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSLD_PCREL_FLAG) {
496     Kind = MCSymbolRefExpr::VK_PPC_NOTOC;
497     Opcode = PPC::BL8_NOTOC_TLS;
498   }
499   const Module *M = MF->getFunction().getParent();
500 
501   assert(MI->getOperand(0).isReg() &&
502          ((Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::X3) ||
503           (!Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::R3)) &&
504          "GETtls[ld]ADDR[32] must define GPR3");
505   assert(MI->getOperand(1).isReg() &&
506          ((Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::X3) ||
507           (!Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::R3)) &&
508          "GETtls[ld]ADDR[32] must read GPR3");
509 
510   if (Subtarget->is32BitELFABI() && isPositionIndependent())
511     Kind = MCSymbolRefExpr::VK_PLT;
512 
513   const MCExpr *TlsRef =
514     MCSymbolRefExpr::create(TlsGetAddr, Kind, OutContext);
515 
516   // Add 32768 offset to the symbol so we follow up the latest GOT/PLT ABI.
517   if (Kind == MCSymbolRefExpr::VK_PLT && Subtarget->isSecurePlt() &&
518       M->getPICLevel() == PICLevel::BigPIC)
519     TlsRef = MCBinaryExpr::createAdd(
520         TlsRef, MCConstantExpr::create(32768, OutContext), OutContext);
521   const MachineOperand &MO = MI->getOperand(2);
522   const GlobalValue *GValue = MO.getGlobal();
523   MCSymbol *MOSymbol = getSymbol(GValue);
524   const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
525   EmitToStreamer(*OutStreamer,
526                  MCInstBuilder(Subtarget->isPPC64() ? Opcode
527                                                     : (unsigned)PPC::BL_TLS)
528                      .addExpr(TlsRef)
529                      .addExpr(SymVar));
530 }
531 
532 /// Map a machine operand for a TOC pseudo-machine instruction to its
533 /// corresponding MCSymbol.
534 static MCSymbol *getMCSymbolForTOCPseudoMO(const MachineOperand &MO,
535                                            AsmPrinter &AP) {
536   switch (MO.getType()) {
537   case MachineOperand::MO_GlobalAddress:
538     return AP.getSymbol(MO.getGlobal());
539   case MachineOperand::MO_ConstantPoolIndex:
540     return AP.GetCPISymbol(MO.getIndex());
541   case MachineOperand::MO_JumpTableIndex:
542     return AP.GetJTISymbol(MO.getIndex());
543   case MachineOperand::MO_BlockAddress:
544     return AP.GetBlockAddressSymbol(MO.getBlockAddress());
545   default:
546     llvm_unreachable("Unexpected operand type to get symbol.");
547   }
548 }
549 
550 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
551 /// the current output stream.
552 ///
553 void PPCAsmPrinter::emitInstruction(const MachineInstr *MI) {
554   MCInst TmpInst;
555   const bool IsPPC64 = Subtarget->isPPC64();
556   const bool IsAIX = Subtarget->isAIXABI();
557   const Module *M = MF->getFunction().getParent();
558   PICLevel::Level PL = M->getPICLevel();
559 
560 #ifndef NDEBUG
561   // Validate that SPE and FPU are mutually exclusive in codegen
562   if (!MI->isInlineAsm()) {
563     for (const MachineOperand &MO: MI->operands()) {
564       if (MO.isReg()) {
565         Register Reg = MO.getReg();
566         if (Subtarget->hasSPE()) {
567           if (PPC::F4RCRegClass.contains(Reg) ||
568               PPC::F8RCRegClass.contains(Reg) ||
569               PPC::VFRCRegClass.contains(Reg) ||
570               PPC::VRRCRegClass.contains(Reg) ||
571               PPC::VSFRCRegClass.contains(Reg) ||
572               PPC::VSSRCRegClass.contains(Reg)
573               )
574             llvm_unreachable("SPE targets cannot have FPRegs!");
575         } else {
576           if (PPC::SPERCRegClass.contains(Reg))
577             llvm_unreachable("SPE register found in FPU-targeted code!");
578         }
579       }
580     }
581   }
582 #endif
583 
584   auto getTOCRelocAdjustedExprForXCOFF = [this](const MCExpr *Expr,
585                                                 ptrdiff_t OriginalOffset) {
586     // Apply an offset to the TOC-based expression such that the adjusted
587     // notional offset from the TOC base (to be encoded into the instruction's D
588     // or DS field) is the signed 16-bit truncation of the original notional
589     // offset from the TOC base.
590     // This is consistent with the treatment used both by XL C/C++ and
591     // by AIX ld -r.
592     ptrdiff_t Adjustment =
593         OriginalOffset - llvm::SignExtend32<16>(OriginalOffset);
594     return MCBinaryExpr::createAdd(
595         Expr, MCConstantExpr::create(-Adjustment, OutContext), OutContext);
596   };
597 
598   auto getTOCEntryLoadingExprForXCOFF =
599       [IsPPC64, getTOCRelocAdjustedExprForXCOFF,
600        this](const MCSymbol *MOSymbol, const MCExpr *Expr) -> const MCExpr * {
601     const unsigned EntryByteSize = IsPPC64 ? 8 : 4;
602     const auto TOCEntryIter = TOC.find(MOSymbol);
603     assert(TOCEntryIter != TOC.end() &&
604            "Could not find the TOC entry for this symbol.");
605     const ptrdiff_t EntryDistanceFromTOCBase =
606         (TOCEntryIter - TOC.begin()) * EntryByteSize;
607     constexpr int16_t PositiveTOCRange = INT16_MAX;
608 
609     if (EntryDistanceFromTOCBase > PositiveTOCRange)
610       return getTOCRelocAdjustedExprForXCOFF(Expr, EntryDistanceFromTOCBase);
611 
612     return Expr;
613   };
614 
615   // Lower multi-instruction pseudo operations.
616   switch (MI->getOpcode()) {
617   default: break;
618   case TargetOpcode::DBG_VALUE:
619     llvm_unreachable("Should be handled target independently");
620   case TargetOpcode::STACKMAP:
621     return LowerSTACKMAP(SM, *MI);
622   case TargetOpcode::PATCHPOINT:
623     return LowerPATCHPOINT(SM, *MI);
624 
625   case PPC::MoveGOTtoLR: {
626     // Transform %lr = MoveGOTtoLR
627     // Into this: bl _GLOBAL_OFFSET_TABLE_@local-4
628     // _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding
629     // _GLOBAL_OFFSET_TABLE_) has exactly one instruction:
630     //      blrl
631     // This will return the pointer to _GLOBAL_OFFSET_TABLE_@local
632     MCSymbol *GOTSymbol =
633       OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
634     const MCExpr *OffsExpr =
635       MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol,
636                                                       MCSymbolRefExpr::VK_PPC_LOCAL,
637                                                       OutContext),
638                               MCConstantExpr::create(4, OutContext),
639                               OutContext);
640 
641     // Emit the 'bl'.
642     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr));
643     return;
644   }
645   case PPC::MovePCtoLR:
646   case PPC::MovePCtoLR8: {
647     // Transform %lr = MovePCtoLR
648     // Into this, where the label is the PIC base:
649     //     bl L1$pb
650     // L1$pb:
651     MCSymbol *PICBase = MF->getPICBaseSymbol();
652 
653     // Emit the 'bl'.
654     EmitToStreamer(*OutStreamer,
655                    MCInstBuilder(PPC::BL)
656                        // FIXME: We would like an efficient form for this, so we
657                        // don't have to do a lot of extra uniquing.
658                        .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
659 
660     // Emit the label.
661     OutStreamer->emitLabel(PICBase);
662     return;
663   }
664   case PPC::UpdateGBR: {
665     // Transform %rd = UpdateGBR(%rt, %ri)
666     // Into: lwz %rt, .L0$poff - .L0$pb(%ri)
667     //       add %rd, %rt, %ri
668     // or into (if secure plt mode is on):
669     //       addis r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@ha
670     //       addi r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@l
671     // Get the offset from the GOT Base Register to the GOT
672     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
673     if (Subtarget->isSecurePlt() && isPositionIndependent() ) {
674       unsigned PICR = TmpInst.getOperand(0).getReg();
675       MCSymbol *BaseSymbol = OutContext.getOrCreateSymbol(
676           M->getPICLevel() == PICLevel::SmallPIC ? "_GLOBAL_OFFSET_TABLE_"
677                                                  : ".LTOC");
678       const MCExpr *PB =
679           MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
680 
681       const MCExpr *DeltaExpr = MCBinaryExpr::createSub(
682           MCSymbolRefExpr::create(BaseSymbol, OutContext), PB, OutContext);
683 
684       const MCExpr *DeltaHi = PPCMCExpr::createHa(DeltaExpr, OutContext);
685       EmitToStreamer(
686           *OutStreamer,
687           MCInstBuilder(PPC::ADDIS).addReg(PICR).addReg(PICR).addExpr(DeltaHi));
688 
689       const MCExpr *DeltaLo = PPCMCExpr::createLo(DeltaExpr, OutContext);
690       EmitToStreamer(
691           *OutStreamer,
692           MCInstBuilder(PPC::ADDI).addReg(PICR).addReg(PICR).addExpr(DeltaLo));
693       return;
694     } else {
695       MCSymbol *PICOffset =
696         MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol(*MF);
697       TmpInst.setOpcode(PPC::LWZ);
698       const MCExpr *Exp =
699         MCSymbolRefExpr::create(PICOffset, MCSymbolRefExpr::VK_None, OutContext);
700       const MCExpr *PB =
701         MCSymbolRefExpr::create(MF->getPICBaseSymbol(),
702                                 MCSymbolRefExpr::VK_None,
703                                 OutContext);
704       const MCOperand TR = TmpInst.getOperand(1);
705       const MCOperand PICR = TmpInst.getOperand(0);
706 
707       // Step 1: lwz %rt, .L$poff - .L$pb(%ri)
708       TmpInst.getOperand(1) =
709           MCOperand::createExpr(MCBinaryExpr::createSub(Exp, PB, OutContext));
710       TmpInst.getOperand(0) = TR;
711       TmpInst.getOperand(2) = PICR;
712       EmitToStreamer(*OutStreamer, TmpInst);
713 
714       TmpInst.setOpcode(PPC::ADD4);
715       TmpInst.getOperand(0) = PICR;
716       TmpInst.getOperand(1) = TR;
717       TmpInst.getOperand(2) = PICR;
718       EmitToStreamer(*OutStreamer, TmpInst);
719       return;
720     }
721   }
722   case PPC::LWZtoc: {
723     // Transform %rN = LWZtoc @op1, %r2
724     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
725 
726     // Change the opcode to LWZ.
727     TmpInst.setOpcode(PPC::LWZ);
728 
729     const MachineOperand &MO = MI->getOperand(1);
730     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
731            "Invalid operand for LWZtoc.");
732 
733     // Map the operand to its corresponding MCSymbol.
734     const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
735 
736     // Create a reference to the GOT entry for the symbol. The GOT entry will be
737     // synthesized later.
738     if (PL == PICLevel::SmallPIC && !IsAIX) {
739       const MCExpr *Exp =
740         MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_GOT,
741                                 OutContext);
742       TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
743       EmitToStreamer(*OutStreamer, TmpInst);
744       return;
745     }
746 
747     // Otherwise, use the TOC. 'TOCEntry' is a label used to reference the
748     // storage allocated in the TOC which contains the address of
749     // 'MOSymbol'. Said TOC entry will be synthesized later.
750     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
751     const MCExpr *Exp =
752         MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_None, OutContext);
753 
754     // AIX uses the label directly as the lwz displacement operand for
755     // references into the toc section. The displacement value will be generated
756     // relative to the toc-base.
757     if (IsAIX) {
758       assert(
759           TM.getCodeModel() == CodeModel::Small &&
760           "This pseudo should only be selected for 32-bit small code model.");
761       Exp = getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp);
762       TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
763       EmitToStreamer(*OutStreamer, TmpInst);
764       return;
765     }
766 
767     // Create an explicit subtract expression between the local symbol and
768     // '.LTOC' to manifest the toc-relative offset.
769     const MCExpr *PB = MCSymbolRefExpr::create(
770         OutContext.getOrCreateSymbol(Twine(".LTOC")), OutContext);
771     Exp = MCBinaryExpr::createSub(Exp, PB, OutContext);
772     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
773     EmitToStreamer(*OutStreamer, TmpInst);
774     return;
775   }
776   case PPC::LDtocJTI:
777   case PPC::LDtocCPT:
778   case PPC::LDtocBA:
779   case PPC::LDtoc: {
780     // Transform %x3 = LDtoc @min1, %x2
781     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
782 
783     // Change the opcode to LD.
784     TmpInst.setOpcode(PPC::LD);
785 
786     const MachineOperand &MO = MI->getOperand(1);
787     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
788            "Invalid operand!");
789 
790     // Map the operand to its corresponding MCSymbol.
791     const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
792 
793     // Map the machine operand to its corresponding MCSymbol, then map the
794     // global address operand to be a reference to the TOC entry we will
795     // synthesize later.
796     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
797 
798     const MCSymbolRefExpr::VariantKind VK =
799         IsAIX ? MCSymbolRefExpr::VK_None : MCSymbolRefExpr::VK_PPC_TOC;
800     const MCExpr *Exp =
801         MCSymbolRefExpr::create(TOCEntry, VK, OutContext);
802     TmpInst.getOperand(1) = MCOperand::createExpr(
803         IsAIX ? getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp) : Exp);
804     EmitToStreamer(*OutStreamer, TmpInst);
805     return;
806   }
807   case PPC::ADDIStocHA: {
808     assert((IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large) &&
809            "This pseudo should only be selected for 32-bit large code model on"
810            " AIX.");
811 
812     // Transform %rd = ADDIStocHA %rA, @sym(%r2)
813     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
814 
815     // Change the opcode to ADDIS.
816     TmpInst.setOpcode(PPC::ADDIS);
817 
818     const MachineOperand &MO = MI->getOperand(2);
819     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
820            "Invalid operand for ADDIStocHA.");
821 
822     // Map the machine operand to its corresponding MCSymbol.
823     MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
824 
825     // Always use TOC on AIX. Map the global address operand to be a reference
826     // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
827     // reference the storage allocated in the TOC which contains the address of
828     // 'MOSymbol'.
829     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
830     const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
831                                                 MCSymbolRefExpr::VK_PPC_U,
832                                                 OutContext);
833     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
834     EmitToStreamer(*OutStreamer, TmpInst);
835     return;
836   }
837   case PPC::LWZtocL: {
838     assert(IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large &&
839            "This pseudo should only be selected for 32-bit large code model on"
840            " AIX.");
841 
842     // Transform %rd = LWZtocL @sym, %rs.
843     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
844 
845     // Change the opcode to lwz.
846     TmpInst.setOpcode(PPC::LWZ);
847 
848     const MachineOperand &MO = MI->getOperand(1);
849     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
850            "Invalid operand for LWZtocL.");
851 
852     // Map the machine operand to its corresponding MCSymbol.
853     MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
854 
855     // Always use TOC on AIX. Map the global address operand to be a reference
856     // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
857     // reference the storage allocated in the TOC which contains the address of
858     // 'MOSymbol'.
859     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
860     const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
861                                                 MCSymbolRefExpr::VK_PPC_L,
862                                                 OutContext);
863     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
864     EmitToStreamer(*OutStreamer, TmpInst);
865     return;
866   }
867   case PPC::ADDIStocHA8: {
868     // Transform %xd = ADDIStocHA8 %x2, @sym
869     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
870 
871     // Change the opcode to ADDIS8. If the global address is the address of
872     // an external symbol, is a jump table address, is a block address, or is a
873     // constant pool index with large code model enabled, then generate a TOC
874     // entry and reference that. Otherwise, reference the symbol directly.
875     TmpInst.setOpcode(PPC::ADDIS8);
876 
877     const MachineOperand &MO = MI->getOperand(2);
878     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
879            "Invalid operand for ADDIStocHA8!");
880 
881     const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
882 
883     const bool GlobalToc =
884         MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal());
885     if (GlobalToc || MO.isJTI() || MO.isBlockAddress() ||
886         (MO.isCPI() && TM.getCodeModel() == CodeModel::Large))
887       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
888 
889     const MCSymbolRefExpr::VariantKind VK =
890         IsAIX ? MCSymbolRefExpr::VK_PPC_U : MCSymbolRefExpr::VK_PPC_TOC_HA;
891 
892     const MCExpr *Exp =
893         MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
894 
895     if (!MO.isJTI() && MO.getOffset())
896       Exp = MCBinaryExpr::createAdd(Exp,
897                                     MCConstantExpr::create(MO.getOffset(),
898                                                            OutContext),
899                                     OutContext);
900 
901     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
902     EmitToStreamer(*OutStreamer, TmpInst);
903     return;
904   }
905   case PPC::LDtocL: {
906     // Transform %xd = LDtocL @sym, %xs
907     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
908 
909     // Change the opcode to LD. If the global address is the address of
910     // an external symbol, is a jump table address, is a block address, or is
911     // a constant pool index with large code model enabled, then generate a
912     // TOC entry and reference that. Otherwise, reference the symbol directly.
913     TmpInst.setOpcode(PPC::LD);
914 
915     const MachineOperand &MO = MI->getOperand(1);
916     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() ||
917             MO.isBlockAddress()) &&
918            "Invalid operand for LDtocL!");
919 
920     LLVM_DEBUG(assert(
921         (!MO.isGlobal() || Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
922         "LDtocL used on symbol that could be accessed directly is "
923         "invalid. Must match ADDIStocHA8."));
924 
925     const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
926 
927     if (!MO.isCPI() || TM.getCodeModel() == CodeModel::Large)
928       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
929 
930     const MCSymbolRefExpr::VariantKind VK =
931         IsAIX ? MCSymbolRefExpr::VK_PPC_L : MCSymbolRefExpr::VK_PPC_TOC_LO;
932     const MCExpr *Exp =
933         MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
934     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
935     EmitToStreamer(*OutStreamer, TmpInst);
936     return;
937   }
938   case PPC::ADDItocL: {
939     // Transform %xd = ADDItocL %xs, @sym
940     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
941 
942     // Change the opcode to ADDI8. If the global address is external, then
943     // generate a TOC entry and reference that. Otherwise, reference the
944     // symbol directly.
945     TmpInst.setOpcode(PPC::ADDI8);
946 
947     const MachineOperand &MO = MI->getOperand(2);
948     assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL.");
949 
950     LLVM_DEBUG(assert(
951         !(MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
952         "Interposable definitions must use indirect access."));
953 
954     const MCExpr *Exp =
955         MCSymbolRefExpr::create(getMCSymbolForTOCPseudoMO(MO, *this),
956                                 MCSymbolRefExpr::VK_PPC_TOC_LO, OutContext);
957     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
958     EmitToStreamer(*OutStreamer, TmpInst);
959     return;
960   }
961   case PPC::ADDISgotTprelHA: {
962     // Transform: %xd = ADDISgotTprelHA %x2, @sym
963     // Into:      %xd = ADDIS8 %x2, sym@got@tlsgd@ha
964     assert(IsPPC64 && "Not supported for 32-bit PowerPC");
965     const MachineOperand &MO = MI->getOperand(2);
966     const GlobalValue *GValue = MO.getGlobal();
967     MCSymbol *MOSymbol = getSymbol(GValue);
968     const MCExpr *SymGotTprel =
969         MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA,
970                                 OutContext);
971     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
972                                  .addReg(MI->getOperand(0).getReg())
973                                  .addReg(MI->getOperand(1).getReg())
974                                  .addExpr(SymGotTprel));
975     return;
976   }
977   case PPC::LDgotTprelL:
978   case PPC::LDgotTprelL32: {
979     // Transform %xd = LDgotTprelL @sym, %xs
980     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
981 
982     // Change the opcode to LD.
983     TmpInst.setOpcode(IsPPC64 ? PPC::LD : PPC::LWZ);
984     const MachineOperand &MO = MI->getOperand(1);
985     const GlobalValue *GValue = MO.getGlobal();
986     MCSymbol *MOSymbol = getSymbol(GValue);
987     const MCExpr *Exp = MCSymbolRefExpr::create(
988         MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO
989                           : MCSymbolRefExpr::VK_PPC_GOT_TPREL,
990         OutContext);
991     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
992     EmitToStreamer(*OutStreamer, TmpInst);
993     return;
994   }
995 
996   case PPC::PPC32PICGOT: {
997     MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
998     MCSymbol *GOTRef = OutContext.createTempSymbol();
999     MCSymbol *NextInstr = OutContext.createTempSymbol();
1000 
1001     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL)
1002       // FIXME: We would like an efficient form for this, so we don't have to do
1003       // a lot of extra uniquing.
1004       .addExpr(MCSymbolRefExpr::create(NextInstr, OutContext)));
1005     const MCExpr *OffsExpr =
1006       MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, OutContext),
1007                                 MCSymbolRefExpr::create(GOTRef, OutContext),
1008         OutContext);
1009     OutStreamer->emitLabel(GOTRef);
1010     OutStreamer->emitValue(OffsExpr, 4);
1011     OutStreamer->emitLabel(NextInstr);
1012     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR)
1013                                  .addReg(MI->getOperand(0).getReg()));
1014     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ)
1015                                  .addReg(MI->getOperand(1).getReg())
1016                                  .addImm(0)
1017                                  .addReg(MI->getOperand(0).getReg()));
1018     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD4)
1019                                  .addReg(MI->getOperand(0).getReg())
1020                                  .addReg(MI->getOperand(1).getReg())
1021                                  .addReg(MI->getOperand(0).getReg()));
1022     return;
1023   }
1024   case PPC::PPC32GOT: {
1025     MCSymbol *GOTSymbol =
1026         OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
1027     const MCExpr *SymGotTlsL = MCSymbolRefExpr::create(
1028         GOTSymbol, MCSymbolRefExpr::VK_PPC_LO, OutContext);
1029     const MCExpr *SymGotTlsHA = MCSymbolRefExpr::create(
1030         GOTSymbol, MCSymbolRefExpr::VK_PPC_HA, OutContext);
1031     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI)
1032                                  .addReg(MI->getOperand(0).getReg())
1033                                  .addExpr(SymGotTlsL));
1034     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1035                                  .addReg(MI->getOperand(0).getReg())
1036                                  .addReg(MI->getOperand(0).getReg())
1037                                  .addExpr(SymGotTlsHA));
1038     return;
1039   }
1040   case PPC::ADDIStlsgdHA: {
1041     // Transform: %xd = ADDIStlsgdHA %x2, @sym
1042     // Into:      %xd = ADDIS8 %x2, sym@got@tlsgd@ha
1043     assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1044     const MachineOperand &MO = MI->getOperand(2);
1045     const GlobalValue *GValue = MO.getGlobal();
1046     MCSymbol *MOSymbol = getSymbol(GValue);
1047     const MCExpr *SymGotTlsGD =
1048       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA,
1049                               OutContext);
1050     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1051                                  .addReg(MI->getOperand(0).getReg())
1052                                  .addReg(MI->getOperand(1).getReg())
1053                                  .addExpr(SymGotTlsGD));
1054     return;
1055   }
1056   case PPC::ADDItlsgdL:
1057     // Transform: %xd = ADDItlsgdL %xs, @sym
1058     // Into:      %xd = ADDI8 %xs, sym@got@tlsgd@l
1059   case PPC::ADDItlsgdL32: {
1060     // Transform: %rd = ADDItlsgdL32 %rs, @sym
1061     // Into:      %rd = ADDI %rs, sym@got@tlsgd
1062     const MachineOperand &MO = MI->getOperand(2);
1063     const GlobalValue *GValue = MO.getGlobal();
1064     MCSymbol *MOSymbol = getSymbol(GValue);
1065     const MCExpr *SymGotTlsGD = MCSymbolRefExpr::create(
1066         MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO
1067                           : MCSymbolRefExpr::VK_PPC_GOT_TLSGD,
1068         OutContext);
1069     EmitToStreamer(*OutStreamer,
1070                    MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1071                    .addReg(MI->getOperand(0).getReg())
1072                    .addReg(MI->getOperand(1).getReg())
1073                    .addExpr(SymGotTlsGD));
1074     return;
1075   }
1076   case PPC::GETtlsADDR:
1077     // Transform: %x3 = GETtlsADDR %x3, @sym
1078     // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsgd)
1079   case PPC::GETtlsADDR32: {
1080     // Transform: %r3 = GETtlsADDR32 %r3, @sym
1081     // Into: BL_TLS __tls_get_addr(sym at tlsgd)@PLT
1082     EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSGD);
1083     return;
1084   }
1085   case PPC::ADDIStlsldHA: {
1086     // Transform: %xd = ADDIStlsldHA %x2, @sym
1087     // Into:      %xd = ADDIS8 %x2, sym@got@tlsld@ha
1088     assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1089     const MachineOperand &MO = MI->getOperand(2);
1090     const GlobalValue *GValue = MO.getGlobal();
1091     MCSymbol *MOSymbol = getSymbol(GValue);
1092     const MCExpr *SymGotTlsLD =
1093       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA,
1094                               OutContext);
1095     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1096                                  .addReg(MI->getOperand(0).getReg())
1097                                  .addReg(MI->getOperand(1).getReg())
1098                                  .addExpr(SymGotTlsLD));
1099     return;
1100   }
1101   case PPC::ADDItlsldL:
1102     // Transform: %xd = ADDItlsldL %xs, @sym
1103     // Into:      %xd = ADDI8 %xs, sym@got@tlsld@l
1104   case PPC::ADDItlsldL32: {
1105     // Transform: %rd = ADDItlsldL32 %rs, @sym
1106     // Into:      %rd = ADDI %rs, sym@got@tlsld
1107     const MachineOperand &MO = MI->getOperand(2);
1108     const GlobalValue *GValue = MO.getGlobal();
1109     MCSymbol *MOSymbol = getSymbol(GValue);
1110     const MCExpr *SymGotTlsLD = MCSymbolRefExpr::create(
1111         MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO
1112                           : MCSymbolRefExpr::VK_PPC_GOT_TLSLD,
1113         OutContext);
1114     EmitToStreamer(*OutStreamer,
1115                    MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1116                        .addReg(MI->getOperand(0).getReg())
1117                        .addReg(MI->getOperand(1).getReg())
1118                        .addExpr(SymGotTlsLD));
1119     return;
1120   }
1121   case PPC::GETtlsldADDR:
1122     // Transform: %x3 = GETtlsldADDR %x3, @sym
1123     // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsld)
1124   case PPC::GETtlsldADDR32: {
1125     // Transform: %r3 = GETtlsldADDR32 %r3, @sym
1126     // Into: BL_TLS __tls_get_addr(sym at tlsld)@PLT
1127     EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSLD);
1128     return;
1129   }
1130   case PPC::ADDISdtprelHA:
1131     // Transform: %xd = ADDISdtprelHA %xs, @sym
1132     // Into:      %xd = ADDIS8 %xs, sym@dtprel@ha
1133   case PPC::ADDISdtprelHA32: {
1134     // Transform: %rd = ADDISdtprelHA32 %rs, @sym
1135     // Into:      %rd = ADDIS %rs, sym@dtprel@ha
1136     const MachineOperand &MO = MI->getOperand(2);
1137     const GlobalValue *GValue = MO.getGlobal();
1138     MCSymbol *MOSymbol = getSymbol(GValue);
1139     const MCExpr *SymDtprel =
1140       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_HA,
1141                               OutContext);
1142     EmitToStreamer(
1143         *OutStreamer,
1144         MCInstBuilder(IsPPC64 ? PPC::ADDIS8 : PPC::ADDIS)
1145             .addReg(MI->getOperand(0).getReg())
1146             .addReg(MI->getOperand(1).getReg())
1147             .addExpr(SymDtprel));
1148     return;
1149   }
1150   case PPC::PADDIdtprel: {
1151     // Transform: %rd = PADDIdtprel %rs, @sym
1152     // Into:      %rd = PADDI8 %rs, sym@dtprel
1153     const MachineOperand &MO = MI->getOperand(2);
1154     const GlobalValue *GValue = MO.getGlobal();
1155     MCSymbol *MOSymbol = getSymbol(GValue);
1156     const MCExpr *SymDtprel = MCSymbolRefExpr::create(
1157         MOSymbol, MCSymbolRefExpr::VK_DTPREL, OutContext);
1158     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::PADDI8)
1159                                      .addReg(MI->getOperand(0).getReg())
1160                                      .addReg(MI->getOperand(1).getReg())
1161                                      .addExpr(SymDtprel));
1162     return;
1163   }
1164 
1165   case PPC::ADDIdtprelL:
1166     // Transform: %xd = ADDIdtprelL %xs, @sym
1167     // Into:      %xd = ADDI8 %xs, sym@dtprel@l
1168   case PPC::ADDIdtprelL32: {
1169     // Transform: %rd = ADDIdtprelL32 %rs, @sym
1170     // Into:      %rd = ADDI %rs, sym@dtprel@l
1171     const MachineOperand &MO = MI->getOperand(2);
1172     const GlobalValue *GValue = MO.getGlobal();
1173     MCSymbol *MOSymbol = getSymbol(GValue);
1174     const MCExpr *SymDtprel =
1175       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_LO,
1176                               OutContext);
1177     EmitToStreamer(*OutStreamer,
1178                    MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1179                        .addReg(MI->getOperand(0).getReg())
1180                        .addReg(MI->getOperand(1).getReg())
1181                        .addExpr(SymDtprel));
1182     return;
1183   }
1184   case PPC::MFOCRF:
1185   case PPC::MFOCRF8:
1186     if (!Subtarget->hasMFOCRF()) {
1187       // Transform: %r3 = MFOCRF %cr7
1188       // Into:      %r3 = MFCR   ;; cr7
1189       unsigned NewOpcode =
1190         MI->getOpcode() == PPC::MFOCRF ? PPC::MFCR : PPC::MFCR8;
1191       OutStreamer->AddComment(PPCInstPrinter::
1192                               getRegisterName(MI->getOperand(1).getReg()));
1193       EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1194                                   .addReg(MI->getOperand(0).getReg()));
1195       return;
1196     }
1197     break;
1198   case PPC::MTOCRF:
1199   case PPC::MTOCRF8:
1200     if (!Subtarget->hasMFOCRF()) {
1201       // Transform: %cr7 = MTOCRF %r3
1202       // Into:      MTCRF mask, %r3 ;; cr7
1203       unsigned NewOpcode =
1204         MI->getOpcode() == PPC::MTOCRF ? PPC::MTCRF : PPC::MTCRF8;
1205       unsigned Mask = 0x80 >> OutContext.getRegisterInfo()
1206                               ->getEncodingValue(MI->getOperand(0).getReg());
1207       OutStreamer->AddComment(PPCInstPrinter::
1208                               getRegisterName(MI->getOperand(0).getReg()));
1209       EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1210                                      .addImm(Mask)
1211                                      .addReg(MI->getOperand(1).getReg()));
1212       return;
1213     }
1214     break;
1215   case PPC::LD:
1216   case PPC::STD:
1217   case PPC::LWA_32:
1218   case PPC::LWA: {
1219     // Verify alignment is legal, so we don't create relocations
1220     // that can't be supported.
1221     // FIXME:  This test is currently disabled for Darwin.  The test
1222     // suite shows a handful of test cases that fail this check for
1223     // Darwin.  Those need to be investigated before this sanity test
1224     // can be enabled for those subtargets.
1225     unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1;
1226     const MachineOperand &MO = MI->getOperand(OpNum);
1227     if (MO.isGlobal()) {
1228       const DataLayout &DL = MO.getGlobal()->getParent()->getDataLayout();
1229       if (MO.getGlobal()->getPointerAlignment(DL) < 4)
1230         llvm_unreachable("Global must be word-aligned for LD, STD, LWA!");
1231     }
1232     // Now process the instruction normally.
1233     break;
1234   }
1235   }
1236 
1237   LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1238   EmitToStreamer(*OutStreamer, TmpInst);
1239 }
1240 
1241 void PPCLinuxAsmPrinter::emitInstruction(const MachineInstr *MI) {
1242   if (!Subtarget->isPPC64())
1243     return PPCAsmPrinter::emitInstruction(MI);
1244 
1245   switch (MI->getOpcode()) {
1246   default:
1247     return PPCAsmPrinter::emitInstruction(MI);
1248   case TargetOpcode::PATCHABLE_FUNCTION_ENTER: {
1249     // .begin:
1250     //   b .end # lis 0, FuncId[16..32]
1251     //   nop    # li  0, FuncId[0..15]
1252     //   std 0, -8(1)
1253     //   mflr 0
1254     //   bl __xray_FunctionEntry
1255     //   mtlr 0
1256     // .end:
1257     //
1258     // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1259     // of instructions change.
1260     MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1261     MCSymbol *EndOfSled = OutContext.createTempSymbol();
1262     OutStreamer->emitLabel(BeginOfSled);
1263     EmitToStreamer(*OutStreamer,
1264                    MCInstBuilder(PPC::B).addExpr(
1265                        MCSymbolRefExpr::create(EndOfSled, OutContext)));
1266     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1267     EmitToStreamer(
1268         *OutStreamer,
1269         MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1270     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1271     EmitToStreamer(*OutStreamer,
1272                    MCInstBuilder(PPC::BL8_NOP)
1273                        .addExpr(MCSymbolRefExpr::create(
1274                            OutContext.getOrCreateSymbol("__xray_FunctionEntry"),
1275                            OutContext)));
1276     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1277     OutStreamer->emitLabel(EndOfSled);
1278     recordSled(BeginOfSled, *MI, SledKind::FUNCTION_ENTER, 2);
1279     break;
1280   }
1281   case TargetOpcode::PATCHABLE_RET: {
1282     unsigned RetOpcode = MI->getOperand(0).getImm();
1283     MCInst RetInst;
1284     RetInst.setOpcode(RetOpcode);
1285     for (const auto &MO :
1286          make_range(std::next(MI->operands_begin()), MI->operands_end())) {
1287       MCOperand MCOp;
1288       if (LowerPPCMachineOperandToMCOperand(MO, MCOp, *this))
1289         RetInst.addOperand(MCOp);
1290     }
1291 
1292     bool IsConditional;
1293     if (RetOpcode == PPC::BCCLR) {
1294       IsConditional = true;
1295     } else if (RetOpcode == PPC::TCRETURNdi8 || RetOpcode == PPC::TCRETURNri8 ||
1296                RetOpcode == PPC::TCRETURNai8) {
1297       break;
1298     } else if (RetOpcode == PPC::BLR8 || RetOpcode == PPC::TAILB8) {
1299       IsConditional = false;
1300     } else {
1301       EmitToStreamer(*OutStreamer, RetInst);
1302       break;
1303     }
1304 
1305     MCSymbol *FallthroughLabel;
1306     if (IsConditional) {
1307       // Before:
1308       //   bgtlr cr0
1309       //
1310       // After:
1311       //   ble cr0, .end
1312       // .p2align 3
1313       // .begin:
1314       //   blr    # lis 0, FuncId[16..32]
1315       //   nop    # li  0, FuncId[0..15]
1316       //   std 0, -8(1)
1317       //   mflr 0
1318       //   bl __xray_FunctionExit
1319       //   mtlr 0
1320       //   blr
1321       // .end:
1322       //
1323       // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1324       // of instructions change.
1325       FallthroughLabel = OutContext.createTempSymbol();
1326       EmitToStreamer(
1327           *OutStreamer,
1328           MCInstBuilder(PPC::BCC)
1329               .addImm(PPC::InvertPredicate(
1330                   static_cast<PPC::Predicate>(MI->getOperand(1).getImm())))
1331               .addReg(MI->getOperand(2).getReg())
1332               .addExpr(MCSymbolRefExpr::create(FallthroughLabel, OutContext)));
1333       RetInst = MCInst();
1334       RetInst.setOpcode(PPC::BLR8);
1335     }
1336     // .p2align 3
1337     // .begin:
1338     //   b(lr)? # lis 0, FuncId[16..32]
1339     //   nop    # li  0, FuncId[0..15]
1340     //   std 0, -8(1)
1341     //   mflr 0
1342     //   bl __xray_FunctionExit
1343     //   mtlr 0
1344     //   b(lr)?
1345     //
1346     // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1347     // of instructions change.
1348     OutStreamer->emitCodeAlignment(8);
1349     MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1350     OutStreamer->emitLabel(BeginOfSled);
1351     EmitToStreamer(*OutStreamer, RetInst);
1352     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1353     EmitToStreamer(
1354         *OutStreamer,
1355         MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1356     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1357     EmitToStreamer(*OutStreamer,
1358                    MCInstBuilder(PPC::BL8_NOP)
1359                        .addExpr(MCSymbolRefExpr::create(
1360                            OutContext.getOrCreateSymbol("__xray_FunctionExit"),
1361                            OutContext)));
1362     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1363     EmitToStreamer(*OutStreamer, RetInst);
1364     if (IsConditional)
1365       OutStreamer->emitLabel(FallthroughLabel);
1366     recordSled(BeginOfSled, *MI, SledKind::FUNCTION_EXIT, 2);
1367     break;
1368   }
1369   case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
1370     llvm_unreachable("PATCHABLE_FUNCTION_EXIT should never be emitted");
1371   case TargetOpcode::PATCHABLE_TAIL_CALL:
1372     // TODO: Define a trampoline `__xray_FunctionTailExit` and differentiate a
1373     // normal function exit from a tail exit.
1374     llvm_unreachable("Tail call is handled in the normal case. See comments "
1375                      "around this assert.");
1376   }
1377 }
1378 
1379 void PPCLinuxAsmPrinter::emitStartOfAsmFile(Module &M) {
1380   if (static_cast<const PPCTargetMachine &>(TM).isELFv2ABI()) {
1381     PPCTargetStreamer *TS =
1382       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1383 
1384     if (TS)
1385       TS->emitAbiVersion(2);
1386   }
1387 
1388   if (static_cast<const PPCTargetMachine &>(TM).isPPC64() ||
1389       !isPositionIndependent())
1390     return AsmPrinter::emitStartOfAsmFile(M);
1391 
1392   if (M.getPICLevel() == PICLevel::SmallPIC)
1393     return AsmPrinter::emitStartOfAsmFile(M);
1394 
1395   OutStreamer->SwitchSection(OutContext.getELFSection(
1396       ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC));
1397 
1398   MCSymbol *TOCSym = OutContext.getOrCreateSymbol(Twine(".LTOC"));
1399   MCSymbol *CurrentPos = OutContext.createTempSymbol();
1400 
1401   OutStreamer->emitLabel(CurrentPos);
1402 
1403   // The GOT pointer points to the middle of the GOT, in order to reference the
1404   // entire 64kB range.  0x8000 is the midpoint.
1405   const MCExpr *tocExpr =
1406     MCBinaryExpr::createAdd(MCSymbolRefExpr::create(CurrentPos, OutContext),
1407                             MCConstantExpr::create(0x8000, OutContext),
1408                             OutContext);
1409 
1410   OutStreamer->emitAssignment(TOCSym, tocExpr);
1411 
1412   OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
1413 }
1414 
1415 void PPCLinuxAsmPrinter::emitFunctionEntryLabel() {
1416   // linux/ppc32 - Normal entry label.
1417   if (!Subtarget->isPPC64() &&
1418       (!isPositionIndependent() ||
1419        MF->getFunction().getParent()->getPICLevel() == PICLevel::SmallPIC))
1420     return AsmPrinter::emitFunctionEntryLabel();
1421 
1422   if (!Subtarget->isPPC64()) {
1423     const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1424     if (PPCFI->usesPICBase() && !Subtarget->isSecurePlt()) {
1425       MCSymbol *RelocSymbol = PPCFI->getPICOffsetSymbol(*MF);
1426       MCSymbol *PICBase = MF->getPICBaseSymbol();
1427       OutStreamer->emitLabel(RelocSymbol);
1428 
1429       const MCExpr *OffsExpr =
1430         MCBinaryExpr::createSub(
1431           MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")),
1432                                                                OutContext),
1433                                   MCSymbolRefExpr::create(PICBase, OutContext),
1434           OutContext);
1435       OutStreamer->emitValue(OffsExpr, 4);
1436       OutStreamer->emitLabel(CurrentFnSym);
1437       return;
1438     } else
1439       return AsmPrinter::emitFunctionEntryLabel();
1440   }
1441 
1442   // ELFv2 ABI - Normal entry label.
1443   if (Subtarget->isELFv2ABI()) {
1444     // In the Large code model, we allow arbitrary displacements between
1445     // the text section and its associated TOC section.  We place the
1446     // full 8-byte offset to the TOC in memory immediately preceding
1447     // the function global entry point.
1448     if (TM.getCodeModel() == CodeModel::Large
1449         && !MF->getRegInfo().use_empty(PPC::X2)) {
1450       const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1451 
1452       MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1453       MCSymbol *GlobalEPSymbol = PPCFI->getGlobalEPSymbol(*MF);
1454       const MCExpr *TOCDeltaExpr =
1455         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1456                                 MCSymbolRefExpr::create(GlobalEPSymbol,
1457                                                         OutContext),
1458                                 OutContext);
1459 
1460       OutStreamer->emitLabel(PPCFI->getTOCOffsetSymbol(*MF));
1461       OutStreamer->emitValue(TOCDeltaExpr, 8);
1462     }
1463     return AsmPrinter::emitFunctionEntryLabel();
1464   }
1465 
1466   // Emit an official procedure descriptor.
1467   MCSectionSubPair Current = OutStreamer->getCurrentSection();
1468   MCSectionELF *Section = OutStreamer->getContext().getELFSection(
1469       ".opd", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1470   OutStreamer->SwitchSection(Section);
1471   OutStreamer->emitLabel(CurrentFnSym);
1472   OutStreamer->emitValueToAlignment(8);
1473   MCSymbol *Symbol1 = CurrentFnSymForSize;
1474   // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function
1475   // entry point.
1476   OutStreamer->emitValue(MCSymbolRefExpr::create(Symbol1, OutContext),
1477                          8 /*size*/);
1478   MCSymbol *Symbol2 = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1479   // Generates a R_PPC64_TOC relocation for TOC base insertion.
1480   OutStreamer->emitValue(
1481     MCSymbolRefExpr::create(Symbol2, MCSymbolRefExpr::VK_PPC_TOCBASE, OutContext),
1482     8/*size*/);
1483   // Emit a null environment pointer.
1484   OutStreamer->emitIntValue(0, 8 /* size */);
1485   OutStreamer->SwitchSection(Current.first, Current.second);
1486 }
1487 
1488 void PPCLinuxAsmPrinter::emitEndOfAsmFile(Module &M) {
1489   const DataLayout &DL = getDataLayout();
1490 
1491   bool isPPC64 = DL.getPointerSizeInBits() == 64;
1492 
1493   PPCTargetStreamer *TS =
1494       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1495 
1496   if (!TOC.empty()) {
1497     const char *Name = isPPC64 ? ".toc" : ".got2";
1498     MCSectionELF *Section = OutContext.getELFSection(
1499         Name, ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1500     OutStreamer->SwitchSection(Section);
1501     if (!isPPC64)
1502       OutStreamer->emitValueToAlignment(4);
1503 
1504     for (const auto &TOCMapPair : TOC) {
1505       const MCSymbol *const TOCEntryTarget = TOCMapPair.first;
1506       MCSymbol *const TOCEntryLabel = TOCMapPair.second;
1507 
1508       OutStreamer->emitLabel(TOCEntryLabel);
1509       if (isPPC64 && TS != nullptr)
1510         TS->emitTCEntry(*TOCEntryTarget);
1511       else
1512         OutStreamer->emitSymbolValue(TOCEntryTarget, 4);
1513     }
1514   }
1515 
1516   PPCAsmPrinter::emitEndOfAsmFile(M);
1517 }
1518 
1519 /// EmitFunctionBodyStart - Emit a global entry point prefix for ELFv2.
1520 void PPCLinuxAsmPrinter::emitFunctionBodyStart() {
1521   // In the ELFv2 ABI, in functions that use the TOC register, we need to
1522   // provide two entry points.  The ABI guarantees that when calling the
1523   // local entry point, r2 is set up by the caller to contain the TOC base
1524   // for this function, and when calling the global entry point, r12 is set
1525   // up by the caller to hold the address of the global entry point.  We
1526   // thus emit a prefix sequence along the following lines:
1527   //
1528   // func:
1529   // .Lfunc_gepNN:
1530   //         # global entry point
1531   //         addis r2,r12,(.TOC.-.Lfunc_gepNN)@ha
1532   //         addi  r2,r2,(.TOC.-.Lfunc_gepNN)@l
1533   // .Lfunc_lepNN:
1534   //         .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1535   //         # local entry point, followed by function body
1536   //
1537   // For the Large code model, we create
1538   //
1539   // .Lfunc_tocNN:
1540   //         .quad .TOC.-.Lfunc_gepNN      # done by EmitFunctionEntryLabel
1541   // func:
1542   // .Lfunc_gepNN:
1543   //         # global entry point
1544   //         ld    r2,.Lfunc_tocNN-.Lfunc_gepNN(r12)
1545   //         add   r2,r2,r12
1546   // .Lfunc_lepNN:
1547   //         .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1548   //         # local entry point, followed by function body
1549   //
1550   // This ensures we have r2 set up correctly while executing the function
1551   // body, no matter which entry point is called.
1552   const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1553   const bool UsesX2OrR2 = !MF->getRegInfo().use_empty(PPC::X2) ||
1554                           !MF->getRegInfo().use_empty(PPC::R2);
1555   const bool PCrelGEPRequired = Subtarget->isUsingPCRelativeCalls() &&
1556                                 UsesX2OrR2 && PPCFI->usesTOCBasePtr();
1557   const bool NonPCrelGEPRequired = !Subtarget->isUsingPCRelativeCalls() &&
1558                                    Subtarget->isELFv2ABI() && UsesX2OrR2;
1559 
1560   // Only do all that if the function uses R2 as the TOC pointer
1561   // in the first place. We don't need the global entry point if the
1562   // function uses R2 as an allocatable register.
1563   if (NonPCrelGEPRequired || PCrelGEPRequired) {
1564     // Note: The logic here must be synchronized with the code in the
1565     // branch-selection pass which sets the offset of the first block in the
1566     // function. This matters because it affects the alignment.
1567     MCSymbol *GlobalEntryLabel = PPCFI->getGlobalEPSymbol(*MF);
1568     OutStreamer->emitLabel(GlobalEntryLabel);
1569     const MCSymbolRefExpr *GlobalEntryLabelExp =
1570       MCSymbolRefExpr::create(GlobalEntryLabel, OutContext);
1571 
1572     if (TM.getCodeModel() != CodeModel::Large) {
1573       MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1574       const MCExpr *TOCDeltaExpr =
1575         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1576                                 GlobalEntryLabelExp, OutContext);
1577 
1578       const MCExpr *TOCDeltaHi = PPCMCExpr::createHa(TOCDeltaExpr, OutContext);
1579       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1580                                    .addReg(PPC::X2)
1581                                    .addReg(PPC::X12)
1582                                    .addExpr(TOCDeltaHi));
1583 
1584       const MCExpr *TOCDeltaLo = PPCMCExpr::createLo(TOCDeltaExpr, OutContext);
1585       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI)
1586                                    .addReg(PPC::X2)
1587                                    .addReg(PPC::X2)
1588                                    .addExpr(TOCDeltaLo));
1589     } else {
1590       MCSymbol *TOCOffset = PPCFI->getTOCOffsetSymbol(*MF);
1591       const MCExpr *TOCOffsetDeltaExpr =
1592         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCOffset, OutContext),
1593                                 GlobalEntryLabelExp, OutContext);
1594 
1595       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
1596                                    .addReg(PPC::X2)
1597                                    .addExpr(TOCOffsetDeltaExpr)
1598                                    .addReg(PPC::X12));
1599       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD8)
1600                                    .addReg(PPC::X2)
1601                                    .addReg(PPC::X2)
1602                                    .addReg(PPC::X12));
1603     }
1604 
1605     MCSymbol *LocalEntryLabel = PPCFI->getLocalEPSymbol(*MF);
1606     OutStreamer->emitLabel(LocalEntryLabel);
1607     const MCSymbolRefExpr *LocalEntryLabelExp =
1608        MCSymbolRefExpr::create(LocalEntryLabel, OutContext);
1609     const MCExpr *LocalOffsetExp =
1610       MCBinaryExpr::createSub(LocalEntryLabelExp,
1611                               GlobalEntryLabelExp, OutContext);
1612 
1613     PPCTargetStreamer *TS =
1614       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1615 
1616     if (TS)
1617       TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), LocalOffsetExp);
1618   } else if (Subtarget->isUsingPCRelativeCalls()) {
1619     // When generating the entry point for a function we have a few scenarios
1620     // based on whether or not that function uses R2 and whether or not that
1621     // function makes calls (or is a leaf function).
1622     // 1) A leaf function that does not use R2 (or treats it as callee-saved
1623     //    and preserves it). In this case st_other=0 and both
1624     //    the local and global entry points for the function are the same.
1625     //    No special entry point code is required.
1626     // 2) A function uses the TOC pointer R2. This function may or may not have
1627     //    calls. In this case st_other=[2,6] and the global and local entry
1628     //    points are different. Code to correctly setup the TOC pointer in R2
1629     //    is put between the global and local entry points. This case is
1630     //    covered by the if statatement above.
1631     // 3) A function does not use the TOC pointer R2 but does have calls.
1632     //    In this case st_other=1 since we do not know whether or not any
1633     //    of the callees clobber R2. This case is dealt with in this else if
1634     //    block. Tail calls are considered calls and the st_other should also
1635     //    be set to 1 in that case as well.
1636     // 4) The function does not use the TOC pointer but R2 is used inside
1637     //    the function. In this case st_other=1 once again.
1638     // 5) This function uses inline asm. We mark R2 as reserved if the function
1639     //    has inline asm as we have to assume that it may be used.
1640     if (MF->getFrameInfo().hasCalls() || MF->getFrameInfo().hasTailCall() ||
1641         MF->hasInlineAsm() || (!PPCFI->usesTOCBasePtr() && UsesX2OrR2)) {
1642       PPCTargetStreamer *TS =
1643           static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1644       if (TS)
1645         TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym),
1646                            MCConstantExpr::create(1, OutContext));
1647     }
1648   }
1649 }
1650 
1651 /// EmitFunctionBodyEnd - Print the traceback table before the .size
1652 /// directive.
1653 ///
1654 void PPCLinuxAsmPrinter::emitFunctionBodyEnd() {
1655   // Only the 64-bit target requires a traceback table.  For now,
1656   // we only emit the word of zeroes that GDB requires to find
1657   // the end of the function, and zeroes for the eight-byte
1658   // mandatory fields.
1659   // FIXME: We should fill in the eight-byte mandatory fields as described in
1660   // the PPC64 ELF ABI (this is a low-priority item because GDB does not
1661   // currently make use of these fields).
1662   if (Subtarget->isPPC64()) {
1663     OutStreamer->emitIntValue(0, 4/*size*/);
1664     OutStreamer->emitIntValue(0, 8/*size*/);
1665   }
1666 }
1667 
1668 void PPCAIXAsmPrinter::emitLinkage(const GlobalValue *GV,
1669                                    MCSymbol *GVSym) const {
1670 
1671   assert(MAI->hasVisibilityOnlyWithLinkage() &&
1672          "AIX's linkage directives take a visibility setting.");
1673 
1674   MCSymbolAttr LinkageAttr = MCSA_Invalid;
1675   switch (GV->getLinkage()) {
1676   case GlobalValue::ExternalLinkage:
1677     LinkageAttr = GV->isDeclaration() ? MCSA_Extern : MCSA_Global;
1678     break;
1679   case GlobalValue::LinkOnceAnyLinkage:
1680   case GlobalValue::LinkOnceODRLinkage:
1681   case GlobalValue::WeakAnyLinkage:
1682   case GlobalValue::WeakODRLinkage:
1683   case GlobalValue::ExternalWeakLinkage:
1684     LinkageAttr = MCSA_Weak;
1685     break;
1686   case GlobalValue::AvailableExternallyLinkage:
1687     LinkageAttr = MCSA_Extern;
1688     break;
1689   case GlobalValue::PrivateLinkage:
1690     return;
1691   case GlobalValue::InternalLinkage:
1692     assert(GV->getVisibility() == GlobalValue::DefaultVisibility &&
1693            "InternalLinkage should not have other visibility setting.");
1694     LinkageAttr = MCSA_LGlobal;
1695     break;
1696   case GlobalValue::AppendingLinkage:
1697     llvm_unreachable("Should never emit this");
1698   case GlobalValue::CommonLinkage:
1699     llvm_unreachable("CommonLinkage of XCOFF should not come to this path");
1700   }
1701 
1702   assert(LinkageAttr != MCSA_Invalid && "LinkageAttr should not MCSA_Invalid.");
1703 
1704   MCSymbolAttr VisibilityAttr = MCSA_Invalid;
1705   if (!TM.getIgnoreXCOFFVisibility()) {
1706     switch (GV->getVisibility()) {
1707 
1708     // TODO: "exported" and "internal" Visibility needs to go here.
1709     case GlobalValue::DefaultVisibility:
1710       break;
1711     case GlobalValue::HiddenVisibility:
1712       VisibilityAttr = MAI->getHiddenVisibilityAttr();
1713       break;
1714     case GlobalValue::ProtectedVisibility:
1715       VisibilityAttr = MAI->getProtectedVisibilityAttr();
1716       break;
1717     }
1718   }
1719 
1720   OutStreamer->emitXCOFFSymbolLinkageWithVisibility(GVSym, LinkageAttr,
1721                                                     VisibilityAttr);
1722 }
1723 
1724 void PPCAIXAsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1725   // Setup CurrentFnDescSym and its containing csect.
1726   MCSectionXCOFF *FnDescSec =
1727       cast<MCSectionXCOFF>(getObjFileLowering().getSectionForFunctionDescriptor(
1728           &MF.getFunction(), TM));
1729   FnDescSec->setAlignment(Align(Subtarget->isPPC64() ? 8 : 4));
1730 
1731   CurrentFnDescSym = FnDescSec->getQualNameSymbol();
1732 
1733   return AsmPrinter::SetupMachineFunction(MF);
1734 }
1735 
1736 void PPCAIXAsmPrinter::ValidateGV(const GlobalVariable *GV) {
1737   // Early error checking limiting what is supported.
1738   if (GV->isThreadLocal())
1739     report_fatal_error("Thread local not yet supported on AIX.");
1740 
1741   if (GV->hasSection())
1742     report_fatal_error("Custom section for Data not yet supported.");
1743 
1744   if (GV->hasComdat())
1745     report_fatal_error("COMDAT not yet supported by AIX.");
1746 }
1747 
1748 static bool isSpecialLLVMGlobalArrayToSkip(const GlobalVariable *GV) {
1749   return GV->hasAppendingLinkage() &&
1750          StringSwitch<bool>(GV->getName())
1751              // TODO: Linker could still eliminate the GV if we just skip
1752              // handling llvm.used array. Skipping them for now until we or the
1753              // AIX OS team come up with a good solution.
1754              .Case("llvm.used", true)
1755              // It's correct to just skip llvm.compiler.used array here.
1756              .Case("llvm.compiler.used", true)
1757              .Default(false);
1758 }
1759 
1760 static bool isSpecialLLVMGlobalArrayForStaticInit(const GlobalVariable *GV) {
1761   return StringSwitch<bool>(GV->getName())
1762       .Cases("llvm.global_ctors", "llvm.global_dtors", true)
1763       .Default(false);
1764 }
1765 
1766 void PPCAIXAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
1767   // Special LLVM global arrays have been handled at the initialization.
1768   if (isSpecialLLVMGlobalArrayToSkip(GV) || isSpecialLLVMGlobalArrayForStaticInit(GV))
1769     return;
1770 
1771   assert(!GV->getName().startswith("llvm.") &&
1772          "Unhandled intrinsic global variable.");
1773   ValidateGV(GV);
1774 
1775   MCSymbolXCOFF *GVSym = cast<MCSymbolXCOFF>(getSymbol(GV));
1776 
1777   if (GV->isDeclarationForLinker()) {
1778     emitLinkage(GV, GVSym);
1779     return;
1780   }
1781 
1782   SectionKind GVKind = getObjFileLowering().getKindForGlobal(GV, TM);
1783   if (!GVKind.isGlobalWriteableData() && !GVKind.isReadOnly())
1784     report_fatal_error("Encountered a global variable kind that is "
1785                        "not supported yet.");
1786 
1787   MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
1788       getObjFileLowering().SectionForGlobal(GV, GVKind, TM));
1789 
1790   // Switch to the containing csect.
1791   OutStreamer->SwitchSection(Csect);
1792 
1793   const DataLayout &DL = GV->getParent()->getDataLayout();
1794 
1795   // Handle common symbols.
1796   if (GVKind.isCommon() || GVKind.isBSSLocal()) {
1797     Align Alignment = GV->getAlign().getValueOr(DL.getPreferredAlign(GV));
1798     uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
1799     GVSym->setStorageClass(
1800         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GV));
1801 
1802     if (GVKind.isBSSLocal())
1803       OutStreamer->emitXCOFFLocalCommonSymbol(
1804           OutContext.getOrCreateSymbol(GVSym->getSymbolTableName()), Size,
1805           GVSym, Alignment.value());
1806     else
1807       OutStreamer->emitCommonSymbol(GVSym, Size, Alignment.value());
1808     return;
1809   }
1810 
1811   MCSymbol *EmittedInitSym = GVSym;
1812   emitLinkage(GV, EmittedInitSym);
1813   emitAlignment(getGVAlignment(GV, DL), GV);
1814   // When -fdata-sections is enabled, every GlobalVariable will
1815   // be put into its own csect; therefore, label is not necessary here.
1816   if (!TM.getDataSections())
1817     OutStreamer->emitLabel(EmittedInitSym);
1818 
1819   // Emit aliasing label for global variable.
1820   llvm::for_each(GOAliasMap[GV], [this](const GlobalAlias *Alias) {
1821     OutStreamer->emitLabel(getSymbol(Alias));
1822   });
1823 
1824   emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
1825 }
1826 
1827 void PPCAIXAsmPrinter::emitFunctionDescriptor() {
1828   const DataLayout &DL = getDataLayout();
1829   const unsigned PointerSize = DL.getPointerSizeInBits() == 64 ? 8 : 4;
1830 
1831   MCSectionSubPair Current = OutStreamer->getCurrentSection();
1832   // Emit function descriptor.
1833   OutStreamer->SwitchSection(
1834       cast<MCSymbolXCOFF>(CurrentFnDescSym)->getRepresentedCsect());
1835 
1836   // Emit aliasing label for function descriptor csect.
1837   llvm::for_each(GOAliasMap[&MF->getFunction()],
1838                  [this](const GlobalAlias *Alias) {
1839                    OutStreamer->emitLabel(getSymbol(Alias));
1840                  });
1841 
1842   // Emit function entry point address.
1843   OutStreamer->emitValue(MCSymbolRefExpr::create(CurrentFnSym, OutContext),
1844                          PointerSize);
1845   // Emit TOC base address.
1846   const MCSymbol *TOCBaseSym =
1847       cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
1848           ->getQualNameSymbol();
1849   OutStreamer->emitValue(MCSymbolRefExpr::create(TOCBaseSym, OutContext),
1850                          PointerSize);
1851   // Emit a null environment pointer.
1852   OutStreamer->emitIntValue(0, PointerSize);
1853 
1854   OutStreamer->SwitchSection(Current.first, Current.second);
1855 }
1856 
1857 void PPCAIXAsmPrinter::emitFunctionEntryLabel() {
1858   // It's not necessary to emit the label when we have individual
1859   // function in its own csect.
1860   if (!TM.getFunctionSections())
1861     PPCAsmPrinter::emitFunctionEntryLabel();
1862 
1863   // Emit aliasing label for function entry point label.
1864   llvm::for_each(
1865       GOAliasMap[&MF->getFunction()], [this](const GlobalAlias *Alias) {
1866         OutStreamer->emitLabel(
1867             getObjFileLowering().getFunctionEntryPointSymbol(Alias, TM));
1868       });
1869 }
1870 
1871 void PPCAIXAsmPrinter::emitEndOfAsmFile(Module &M) {
1872   // If there are no functions in this module, we will never need to reference
1873   // the TOC base.
1874   if (M.empty())
1875     return;
1876 
1877   // Switch to section to emit TOC base.
1878   OutStreamer->SwitchSection(getObjFileLowering().getTOCBaseSection());
1879 
1880   PPCTargetStreamer *TS =
1881       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1882 
1883   for (auto &I : TOC) {
1884     // Setup the csect for the current TC entry.
1885     MCSectionXCOFF *TCEntry = cast<MCSectionXCOFF>(
1886         getObjFileLowering().getSectionForTOCEntry(I.first, TM));
1887     OutStreamer->SwitchSection(TCEntry);
1888 
1889     OutStreamer->emitLabel(I.second);
1890     if (TS != nullptr)
1891       TS->emitTCEntry(*I.first);
1892   }
1893 }
1894 
1895 bool PPCAIXAsmPrinter::doInitialization(Module &M) {
1896   const bool Result = PPCAsmPrinter::doInitialization(M);
1897 
1898   auto setCsectAlignment = [this](const GlobalObject *GO) {
1899     // Declarations have 0 alignment which is set by default.
1900     if (GO->isDeclarationForLinker())
1901       return;
1902 
1903     SectionKind GOKind = getObjFileLowering().getKindForGlobal(GO, TM);
1904     MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
1905         getObjFileLowering().SectionForGlobal(GO, GOKind, TM));
1906 
1907     Align GOAlign = getGVAlignment(GO, GO->getParent()->getDataLayout());
1908     if (GOAlign > Csect->getAlignment())
1909       Csect->setAlignment(GOAlign);
1910   };
1911 
1912   // We need to know, up front, the alignment of csects for the assembly path,
1913   // because once a .csect directive gets emitted, we could not change the
1914   // alignment value on it.
1915   for (const auto &G : M.globals()) {
1916     if (isSpecialLLVMGlobalArrayToSkip(&G))
1917       continue;
1918 
1919     if (isSpecialLLVMGlobalArrayForStaticInit(&G)) {
1920       // Generate a format indicator and a unique module id to be a part of
1921       // the sinit and sterm function names.
1922       if (FormatIndicatorAndUniqueModId.empty()) {
1923         std::string UniqueModuleId = getUniqueModuleId(&M);
1924         if (UniqueModuleId.compare("") != 0)
1925           // TODO: Use source file full path to generate the unique module id
1926           // and add a format indicator as a part of function name in case we
1927           // will support more than one format.
1928           FormatIndicatorAndUniqueModId = "clang_" + UniqueModuleId.substr(1);
1929         else
1930           // Use the Pid and current time as the unique module id when we cannot
1931           // generate one based on a module's strong external symbols.
1932           // FIXME: Adjust the comment accordingly after we use source file full
1933           // path instead.
1934           FormatIndicatorAndUniqueModId =
1935               "clangPidTime_" + llvm::itostr(sys::Process::getProcessId()) +
1936               "_" + llvm::itostr(time(nullptr));
1937       }
1938 
1939       emitSpecialLLVMGlobal(&G);
1940       continue;
1941     }
1942 
1943     setCsectAlignment(&G);
1944   }
1945 
1946   for (const auto &F : M)
1947     setCsectAlignment(&F);
1948 
1949   // Construct an aliasing list for each GlobalObject.
1950   for (const auto &Alias : M.aliases()) {
1951     const GlobalObject *Base = Alias.getBaseObject();
1952     if (!Base)
1953       report_fatal_error(
1954           "alias without a base object is not yet supported on AIX");
1955     GOAliasMap[Base].push_back(&Alias);
1956   }
1957 
1958   return Result;
1959 }
1960 
1961 void PPCAIXAsmPrinter::emitInstruction(const MachineInstr *MI) {
1962   switch (MI->getOpcode()) {
1963   default:
1964     break;
1965   case PPC::BL8:
1966   case PPC::BL:
1967   case PPC::BL8_NOP:
1968   case PPC::BL_NOP: {
1969     const MachineOperand &MO = MI->getOperand(0);
1970     if (MO.isSymbol()) {
1971       MCSymbolXCOFF *S =
1972           cast<MCSymbolXCOFF>(OutContext.getOrCreateSymbol(MO.getSymbolName()));
1973       ExtSymSDNodeSymbols.insert(S);
1974     }
1975   } break;
1976   case PPC::BL_TLS:
1977   case PPC::BL8_TLS:
1978   case PPC::BL8_TLS_:
1979   case PPC::BL8_NOP_TLS:
1980     report_fatal_error("TLS call not yet implemented");
1981   case PPC::TAILB:
1982   case PPC::TAILB8:
1983   case PPC::TAILBA:
1984   case PPC::TAILBA8:
1985   case PPC::TAILBCTR:
1986   case PPC::TAILBCTR8:
1987     if (MI->getOperand(0).isSymbol())
1988       report_fatal_error("Tail call for extern symbol not yet supported.");
1989     break;
1990   }
1991   return PPCAsmPrinter::emitInstruction(MI);
1992 }
1993 
1994 bool PPCAIXAsmPrinter::doFinalization(Module &M) {
1995   for (MCSymbol *Sym : ExtSymSDNodeSymbols)
1996     OutStreamer->emitSymbolAttribute(Sym, MCSA_Extern);
1997   return PPCAsmPrinter::doFinalization(M);
1998 }
1999 
2000 void PPCAIXAsmPrinter::emitXXStructorList(const DataLayout &DL,
2001                                           const Constant *List, bool IsCtor) {
2002   SmallVector<Structor, 8> Structors;
2003   preprocessXXStructorList(DL, List, Structors);
2004   if (Structors.empty())
2005     return;
2006 
2007   unsigned Index = 0;
2008   for (Structor &S : Structors) {
2009     if (S.Priority != 65535)
2010       report_fatal_error(
2011           "prioritized sinit and sterm functions are not yet supported on AIX");
2012 
2013     llvm::GlobalAlias::create(
2014         GlobalValue::ExternalLinkage,
2015         (IsCtor ? llvm::Twine("__sinit") : llvm::Twine("__sterm")) +
2016             llvm::Twine("80000000_", FormatIndicatorAndUniqueModId) +
2017             llvm::Twine("_", llvm::utostr(Index++)),
2018         cast<Function>(S.Func));
2019   }
2020 }
2021 
2022 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
2023 /// for a MachineFunction to the given output stream, in a format that the
2024 /// Darwin assembler can deal with.
2025 ///
2026 static AsmPrinter *
2027 createPPCAsmPrinterPass(TargetMachine &tm,
2028                         std::unique_ptr<MCStreamer> &&Streamer) {
2029   if (tm.getTargetTriple().isOSAIX())
2030     return new PPCAIXAsmPrinter(tm, std::move(Streamer));
2031 
2032   return new PPCLinuxAsmPrinter(tm, std::move(Streamer));
2033 }
2034 
2035 // Force static initialization.
2036 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCAsmPrinter() {
2037   TargetRegistry::RegisterAsmPrinter(getThePPC32Target(),
2038                                      createPPCAsmPrinterPass);
2039   TargetRegistry::RegisterAsmPrinter(getThePPC64Target(),
2040                                      createPPCAsmPrinterPass);
2041   TargetRegistry::RegisterAsmPrinter(getThePPC64LETarget(),
2042                                      createPPCAsmPrinterPass);
2043 }
2044