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     Kind = MCSymbolRefExpr::VK_PPC_NOTOC;
496     Opcode = PPC::BL8_NOTOC_TLS;
497   }
498   const Module *M = MF->getFunction().getParent();
499 
500   assert(MI->getOperand(0).isReg() &&
501          ((Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::X3) ||
502           (!Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::R3)) &&
503          "GETtls[ld]ADDR[32] must define GPR3");
504   assert(MI->getOperand(1).isReg() &&
505          ((Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::X3) ||
506           (!Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::R3)) &&
507          "GETtls[ld]ADDR[32] must read GPR3");
508 
509   if (Subtarget->is32BitELFABI() && isPositionIndependent())
510     Kind = MCSymbolRefExpr::VK_PLT;
511 
512   const MCExpr *TlsRef =
513     MCSymbolRefExpr::create(TlsGetAddr, Kind, OutContext);
514 
515   // Add 32768 offset to the symbol so we follow up the latest GOT/PLT ABI.
516   if (Kind == MCSymbolRefExpr::VK_PLT && Subtarget->isSecurePlt() &&
517       M->getPICLevel() == PICLevel::BigPIC)
518     TlsRef = MCBinaryExpr::createAdd(
519         TlsRef, MCConstantExpr::create(32768, OutContext), OutContext);
520   const MachineOperand &MO = MI->getOperand(2);
521   const GlobalValue *GValue = MO.getGlobal();
522   MCSymbol *MOSymbol = getSymbol(GValue);
523   const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
524   EmitToStreamer(*OutStreamer,
525                  MCInstBuilder(Subtarget->isPPC64() ? Opcode
526                                                     : (unsigned)PPC::BL_TLS)
527                      .addExpr(TlsRef)
528                      .addExpr(SymVar));
529 }
530 
531 /// Map a machine operand for a TOC pseudo-machine instruction to its
532 /// corresponding MCSymbol.
533 static MCSymbol *getMCSymbolForTOCPseudoMO(const MachineOperand &MO,
534                                            AsmPrinter &AP) {
535   switch (MO.getType()) {
536   case MachineOperand::MO_GlobalAddress:
537     return AP.getSymbol(MO.getGlobal());
538   case MachineOperand::MO_ConstantPoolIndex:
539     return AP.GetCPISymbol(MO.getIndex());
540   case MachineOperand::MO_JumpTableIndex:
541     return AP.GetJTISymbol(MO.getIndex());
542   case MachineOperand::MO_BlockAddress:
543     return AP.GetBlockAddressSymbol(MO.getBlockAddress());
544   default:
545     llvm_unreachable("Unexpected operand type to get symbol.");
546   }
547 }
548 
549 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
550 /// the current output stream.
551 ///
552 void PPCAsmPrinter::emitInstruction(const MachineInstr *MI) {
553   MCInst TmpInst;
554   const bool IsPPC64 = Subtarget->isPPC64();
555   const bool IsAIX = Subtarget->isAIXABI();
556   const Module *M = MF->getFunction().getParent();
557   PICLevel::Level PL = M->getPICLevel();
558 
559 #ifndef NDEBUG
560   // Validate that SPE and FPU are mutually exclusive in codegen
561   if (!MI->isInlineAsm()) {
562     for (const MachineOperand &MO: MI->operands()) {
563       if (MO.isReg()) {
564         Register Reg = MO.getReg();
565         if (Subtarget->hasSPE()) {
566           if (PPC::F4RCRegClass.contains(Reg) ||
567               PPC::F8RCRegClass.contains(Reg) ||
568               PPC::VFRCRegClass.contains(Reg) ||
569               PPC::VRRCRegClass.contains(Reg) ||
570               PPC::VSFRCRegClass.contains(Reg) ||
571               PPC::VSSRCRegClass.contains(Reg)
572               )
573             llvm_unreachable("SPE targets cannot have FPRegs!");
574         } else {
575           if (PPC::SPERCRegClass.contains(Reg))
576             llvm_unreachable("SPE register found in FPU-targeted code!");
577         }
578       }
579     }
580   }
581 #endif
582 
583   auto getTOCRelocAdjustedExprForXCOFF = [this](const MCExpr *Expr,
584                                                 ptrdiff_t OriginalOffset) {
585     // Apply an offset to the TOC-based expression such that the adjusted
586     // notional offset from the TOC base (to be encoded into the instruction's D
587     // or DS field) is the signed 16-bit truncation of the original notional
588     // offset from the TOC base.
589     // This is consistent with the treatment used both by XL C/C++ and
590     // by AIX ld -r.
591     ptrdiff_t Adjustment =
592         OriginalOffset - llvm::SignExtend32<16>(OriginalOffset);
593     return MCBinaryExpr::createAdd(
594         Expr, MCConstantExpr::create(-Adjustment, OutContext), OutContext);
595   };
596 
597   auto getTOCEntryLoadingExprForXCOFF =
598       [IsPPC64, getTOCRelocAdjustedExprForXCOFF,
599        this](const MCSymbol *MOSymbol, const MCExpr *Expr) -> const MCExpr * {
600     const unsigned EntryByteSize = IsPPC64 ? 8 : 4;
601     const auto TOCEntryIter = TOC.find(MOSymbol);
602     assert(TOCEntryIter != TOC.end() &&
603            "Could not find the TOC entry for this symbol.");
604     const ptrdiff_t EntryDistanceFromTOCBase =
605         (TOCEntryIter - TOC.begin()) * EntryByteSize;
606     constexpr int16_t PositiveTOCRange = INT16_MAX;
607 
608     if (EntryDistanceFromTOCBase > PositiveTOCRange)
609       return getTOCRelocAdjustedExprForXCOFF(Expr, EntryDistanceFromTOCBase);
610 
611     return Expr;
612   };
613 
614   // Lower multi-instruction pseudo operations.
615   switch (MI->getOpcode()) {
616   default: break;
617   case TargetOpcode::DBG_VALUE:
618     llvm_unreachable("Should be handled target independently");
619   case TargetOpcode::STACKMAP:
620     return LowerSTACKMAP(SM, *MI);
621   case TargetOpcode::PATCHPOINT:
622     return LowerPATCHPOINT(SM, *MI);
623 
624   case PPC::MoveGOTtoLR: {
625     // Transform %lr = MoveGOTtoLR
626     // Into this: bl _GLOBAL_OFFSET_TABLE_@local-4
627     // _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding
628     // _GLOBAL_OFFSET_TABLE_) has exactly one instruction:
629     //      blrl
630     // This will return the pointer to _GLOBAL_OFFSET_TABLE_@local
631     MCSymbol *GOTSymbol =
632       OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
633     const MCExpr *OffsExpr =
634       MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol,
635                                                       MCSymbolRefExpr::VK_PPC_LOCAL,
636                                                       OutContext),
637                               MCConstantExpr::create(4, OutContext),
638                               OutContext);
639 
640     // Emit the 'bl'.
641     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr));
642     return;
643   }
644   case PPC::MovePCtoLR:
645   case PPC::MovePCtoLR8: {
646     // Transform %lr = MovePCtoLR
647     // Into this, where the label is the PIC base:
648     //     bl L1$pb
649     // L1$pb:
650     MCSymbol *PICBase = MF->getPICBaseSymbol();
651 
652     // Emit the 'bl'.
653     EmitToStreamer(*OutStreamer,
654                    MCInstBuilder(PPC::BL)
655                        // FIXME: We would like an efficient form for this, so we
656                        // don't have to do a lot of extra uniquing.
657                        .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
658 
659     // Emit the label.
660     OutStreamer->emitLabel(PICBase);
661     return;
662   }
663   case PPC::UpdateGBR: {
664     // Transform %rd = UpdateGBR(%rt, %ri)
665     // Into: lwz %rt, .L0$poff - .L0$pb(%ri)
666     //       add %rd, %rt, %ri
667     // or into (if secure plt mode is on):
668     //       addis r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@ha
669     //       addi r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@l
670     // Get the offset from the GOT Base Register to the GOT
671     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
672     if (Subtarget->isSecurePlt() && isPositionIndependent() ) {
673       unsigned PICR = TmpInst.getOperand(0).getReg();
674       MCSymbol *BaseSymbol = OutContext.getOrCreateSymbol(
675           M->getPICLevel() == PICLevel::SmallPIC ? "_GLOBAL_OFFSET_TABLE_"
676                                                  : ".LTOC");
677       const MCExpr *PB =
678           MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
679 
680       const MCExpr *DeltaExpr = MCBinaryExpr::createSub(
681           MCSymbolRefExpr::create(BaseSymbol, OutContext), PB, OutContext);
682 
683       const MCExpr *DeltaHi = PPCMCExpr::createHa(DeltaExpr, OutContext);
684       EmitToStreamer(
685           *OutStreamer,
686           MCInstBuilder(PPC::ADDIS).addReg(PICR).addReg(PICR).addExpr(DeltaHi));
687 
688       const MCExpr *DeltaLo = PPCMCExpr::createLo(DeltaExpr, OutContext);
689       EmitToStreamer(
690           *OutStreamer,
691           MCInstBuilder(PPC::ADDI).addReg(PICR).addReg(PICR).addExpr(DeltaLo));
692       return;
693     } else {
694       MCSymbol *PICOffset =
695         MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol(*MF);
696       TmpInst.setOpcode(PPC::LWZ);
697       const MCExpr *Exp =
698         MCSymbolRefExpr::create(PICOffset, MCSymbolRefExpr::VK_None, OutContext);
699       const MCExpr *PB =
700         MCSymbolRefExpr::create(MF->getPICBaseSymbol(),
701                                 MCSymbolRefExpr::VK_None,
702                                 OutContext);
703       const MCOperand TR = TmpInst.getOperand(1);
704       const MCOperand PICR = TmpInst.getOperand(0);
705 
706       // Step 1: lwz %rt, .L$poff - .L$pb(%ri)
707       TmpInst.getOperand(1) =
708           MCOperand::createExpr(MCBinaryExpr::createSub(Exp, PB, OutContext));
709       TmpInst.getOperand(0) = TR;
710       TmpInst.getOperand(2) = PICR;
711       EmitToStreamer(*OutStreamer, TmpInst);
712 
713       TmpInst.setOpcode(PPC::ADD4);
714       TmpInst.getOperand(0) = PICR;
715       TmpInst.getOperand(1) = TR;
716       TmpInst.getOperand(2) = PICR;
717       EmitToStreamer(*OutStreamer, TmpInst);
718       return;
719     }
720   }
721   case PPC::LWZtoc: {
722     // Transform %rN = LWZtoc @op1, %r2
723     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
724 
725     // Change the opcode to LWZ.
726     TmpInst.setOpcode(PPC::LWZ);
727 
728     const MachineOperand &MO = MI->getOperand(1);
729     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
730            "Invalid operand for LWZtoc.");
731 
732     // Map the operand to its corresponding MCSymbol.
733     const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
734 
735     // Create a reference to the GOT entry for the symbol. The GOT entry will be
736     // synthesized later.
737     if (PL == PICLevel::SmallPIC && !IsAIX) {
738       const MCExpr *Exp =
739         MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_GOT,
740                                 OutContext);
741       TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
742       EmitToStreamer(*OutStreamer, TmpInst);
743       return;
744     }
745 
746     // Otherwise, use the TOC. 'TOCEntry' is a label used to reference the
747     // storage allocated in the TOC which contains the address of
748     // 'MOSymbol'. Said TOC entry will be synthesized later.
749     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
750     const MCExpr *Exp =
751         MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_None, OutContext);
752 
753     // AIX uses the label directly as the lwz displacement operand for
754     // references into the toc section. The displacement value will be generated
755     // relative to the toc-base.
756     if (IsAIX) {
757       assert(
758           TM.getCodeModel() == CodeModel::Small &&
759           "This pseudo should only be selected for 32-bit small code model.");
760       Exp = getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp);
761       TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
762       EmitToStreamer(*OutStreamer, TmpInst);
763       return;
764     }
765 
766     // Create an explicit subtract expression between the local symbol and
767     // '.LTOC' to manifest the toc-relative offset.
768     const MCExpr *PB = MCSymbolRefExpr::create(
769         OutContext.getOrCreateSymbol(Twine(".LTOC")), OutContext);
770     Exp = MCBinaryExpr::createSub(Exp, PB, OutContext);
771     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
772     EmitToStreamer(*OutStreamer, TmpInst);
773     return;
774   }
775   case PPC::LDtocJTI:
776   case PPC::LDtocCPT:
777   case PPC::LDtocBA:
778   case PPC::LDtoc: {
779     // Transform %x3 = LDtoc @min1, %x2
780     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
781 
782     // Change the opcode to LD.
783     TmpInst.setOpcode(PPC::LD);
784 
785     const MachineOperand &MO = MI->getOperand(1);
786     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
787            "Invalid operand!");
788 
789     // Map the operand to its corresponding MCSymbol.
790     const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
791 
792     // Map the machine operand to its corresponding MCSymbol, then map the
793     // global address operand to be a reference to the TOC entry we will
794     // synthesize later.
795     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
796 
797     const MCSymbolRefExpr::VariantKind VK =
798         IsAIX ? MCSymbolRefExpr::VK_None : MCSymbolRefExpr::VK_PPC_TOC;
799     const MCExpr *Exp =
800         MCSymbolRefExpr::create(TOCEntry, VK, OutContext);
801     TmpInst.getOperand(1) = MCOperand::createExpr(
802         IsAIX ? getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp) : Exp);
803     EmitToStreamer(*OutStreamer, TmpInst);
804     return;
805   }
806   case PPC::ADDIStocHA: {
807     assert((IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large) &&
808            "This pseudo should only be selected for 32-bit large code model on"
809            " AIX.");
810 
811     // Transform %rd = ADDIStocHA %rA, @sym(%r2)
812     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
813 
814     // Change the opcode to ADDIS.
815     TmpInst.setOpcode(PPC::ADDIS);
816 
817     const MachineOperand &MO = MI->getOperand(2);
818     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
819            "Invalid operand for ADDIStocHA.");
820 
821     // Map the machine operand to its corresponding MCSymbol.
822     MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
823 
824     // Always use TOC on AIX. Map the global address operand to be a reference
825     // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
826     // reference the storage allocated in the TOC which contains the address of
827     // 'MOSymbol'.
828     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
829     const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
830                                                 MCSymbolRefExpr::VK_PPC_U,
831                                                 OutContext);
832     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
833     EmitToStreamer(*OutStreamer, TmpInst);
834     return;
835   }
836   case PPC::LWZtocL: {
837     assert(IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large &&
838            "This pseudo should only be selected for 32-bit large code model on"
839            " AIX.");
840 
841     // Transform %rd = LWZtocL @sym, %rs.
842     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
843 
844     // Change the opcode to lwz.
845     TmpInst.setOpcode(PPC::LWZ);
846 
847     const MachineOperand &MO = MI->getOperand(1);
848     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
849            "Invalid operand for LWZtocL.");
850 
851     // Map the machine operand to its corresponding MCSymbol.
852     MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
853 
854     // Always use TOC on AIX. Map the global address operand to be a reference
855     // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
856     // reference the storage allocated in the TOC which contains the address of
857     // 'MOSymbol'.
858     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
859     const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
860                                                 MCSymbolRefExpr::VK_PPC_L,
861                                                 OutContext);
862     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
863     EmitToStreamer(*OutStreamer, TmpInst);
864     return;
865   }
866   case PPC::ADDIStocHA8: {
867     // Transform %xd = ADDIStocHA8 %x2, @sym
868     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
869 
870     // Change the opcode to ADDIS8. If the global address is the address of
871     // an external symbol, is a jump table address, is a block address, or is a
872     // constant pool index with large code model enabled, then generate a TOC
873     // entry and reference that. Otherwise, reference the symbol directly.
874     TmpInst.setOpcode(PPC::ADDIS8);
875 
876     const MachineOperand &MO = MI->getOperand(2);
877     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
878            "Invalid operand for ADDIStocHA8!");
879 
880     const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
881 
882     const bool GlobalToc =
883         MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal());
884     if (GlobalToc || MO.isJTI() || MO.isBlockAddress() ||
885         (MO.isCPI() && TM.getCodeModel() == CodeModel::Large))
886       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
887 
888     const MCSymbolRefExpr::VariantKind VK =
889         IsAIX ? MCSymbolRefExpr::VK_PPC_U : MCSymbolRefExpr::VK_PPC_TOC_HA;
890 
891     const MCExpr *Exp =
892         MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
893 
894     if (!MO.isJTI() && MO.getOffset())
895       Exp = MCBinaryExpr::createAdd(Exp,
896                                     MCConstantExpr::create(MO.getOffset(),
897                                                            OutContext),
898                                     OutContext);
899 
900     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
901     EmitToStreamer(*OutStreamer, TmpInst);
902     return;
903   }
904   case PPC::LDtocL: {
905     // Transform %xd = LDtocL @sym, %xs
906     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
907 
908     // Change the opcode to LD. If the global address is the address of
909     // an external symbol, is a jump table address, is a block address, or is
910     // a constant pool index with large code model enabled, then generate a
911     // TOC entry and reference that. Otherwise, reference the symbol directly.
912     TmpInst.setOpcode(PPC::LD);
913 
914     const MachineOperand &MO = MI->getOperand(1);
915     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() ||
916             MO.isBlockAddress()) &&
917            "Invalid operand for LDtocL!");
918 
919     LLVM_DEBUG(assert(
920         (!MO.isGlobal() || Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
921         "LDtocL used on symbol that could be accessed directly is "
922         "invalid. Must match ADDIStocHA8."));
923 
924     const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
925 
926     if (!MO.isCPI() || TM.getCodeModel() == CodeModel::Large)
927       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
928 
929     const MCSymbolRefExpr::VariantKind VK =
930         IsAIX ? MCSymbolRefExpr::VK_PPC_L : MCSymbolRefExpr::VK_PPC_TOC_LO;
931     const MCExpr *Exp =
932         MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
933     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
934     EmitToStreamer(*OutStreamer, TmpInst);
935     return;
936   }
937   case PPC::ADDItocL: {
938     // Transform %xd = ADDItocL %xs, @sym
939     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
940 
941     // Change the opcode to ADDI8. If the global address is external, then
942     // generate a TOC entry and reference that. Otherwise, reference the
943     // symbol directly.
944     TmpInst.setOpcode(PPC::ADDI8);
945 
946     const MachineOperand &MO = MI->getOperand(2);
947     assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL.");
948 
949     LLVM_DEBUG(assert(
950         !(MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
951         "Interposable definitions must use indirect access."));
952 
953     const MCExpr *Exp =
954         MCSymbolRefExpr::create(getMCSymbolForTOCPseudoMO(MO, *this),
955                                 MCSymbolRefExpr::VK_PPC_TOC_LO, OutContext);
956     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
957     EmitToStreamer(*OutStreamer, TmpInst);
958     return;
959   }
960   case PPC::ADDISgotTprelHA: {
961     // Transform: %xd = ADDISgotTprelHA %x2, @sym
962     // Into:      %xd = ADDIS8 %x2, sym@got@tlsgd@ha
963     assert(IsPPC64 && "Not supported for 32-bit PowerPC");
964     const MachineOperand &MO = MI->getOperand(2);
965     const GlobalValue *GValue = MO.getGlobal();
966     MCSymbol *MOSymbol = getSymbol(GValue);
967     const MCExpr *SymGotTprel =
968         MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA,
969                                 OutContext);
970     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
971                                  .addReg(MI->getOperand(0).getReg())
972                                  .addReg(MI->getOperand(1).getReg())
973                                  .addExpr(SymGotTprel));
974     return;
975   }
976   case PPC::LDgotTprelL:
977   case PPC::LDgotTprelL32: {
978     // Transform %xd = LDgotTprelL @sym, %xs
979     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
980 
981     // Change the opcode to LD.
982     TmpInst.setOpcode(IsPPC64 ? PPC::LD : PPC::LWZ);
983     const MachineOperand &MO = MI->getOperand(1);
984     const GlobalValue *GValue = MO.getGlobal();
985     MCSymbol *MOSymbol = getSymbol(GValue);
986     const MCExpr *Exp = MCSymbolRefExpr::create(
987         MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO
988                           : MCSymbolRefExpr::VK_PPC_GOT_TPREL,
989         OutContext);
990     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
991     EmitToStreamer(*OutStreamer, TmpInst);
992     return;
993   }
994 
995   case PPC::PPC32PICGOT: {
996     MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
997     MCSymbol *GOTRef = OutContext.createTempSymbol();
998     MCSymbol *NextInstr = OutContext.createTempSymbol();
999 
1000     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL)
1001       // FIXME: We would like an efficient form for this, so we don't have to do
1002       // a lot of extra uniquing.
1003       .addExpr(MCSymbolRefExpr::create(NextInstr, OutContext)));
1004     const MCExpr *OffsExpr =
1005       MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, OutContext),
1006                                 MCSymbolRefExpr::create(GOTRef, OutContext),
1007         OutContext);
1008     OutStreamer->emitLabel(GOTRef);
1009     OutStreamer->emitValue(OffsExpr, 4);
1010     OutStreamer->emitLabel(NextInstr);
1011     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR)
1012                                  .addReg(MI->getOperand(0).getReg()));
1013     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ)
1014                                  .addReg(MI->getOperand(1).getReg())
1015                                  .addImm(0)
1016                                  .addReg(MI->getOperand(0).getReg()));
1017     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD4)
1018                                  .addReg(MI->getOperand(0).getReg())
1019                                  .addReg(MI->getOperand(1).getReg())
1020                                  .addReg(MI->getOperand(0).getReg()));
1021     return;
1022   }
1023   case PPC::PPC32GOT: {
1024     MCSymbol *GOTSymbol =
1025         OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
1026     const MCExpr *SymGotTlsL = MCSymbolRefExpr::create(
1027         GOTSymbol, MCSymbolRefExpr::VK_PPC_LO, OutContext);
1028     const MCExpr *SymGotTlsHA = MCSymbolRefExpr::create(
1029         GOTSymbol, MCSymbolRefExpr::VK_PPC_HA, OutContext);
1030     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI)
1031                                  .addReg(MI->getOperand(0).getReg())
1032                                  .addExpr(SymGotTlsL));
1033     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1034                                  .addReg(MI->getOperand(0).getReg())
1035                                  .addReg(MI->getOperand(0).getReg())
1036                                  .addExpr(SymGotTlsHA));
1037     return;
1038   }
1039   case PPC::ADDIStlsgdHA: {
1040     // Transform: %xd = ADDIStlsgdHA %x2, @sym
1041     // Into:      %xd = ADDIS8 %x2, sym@got@tlsgd@ha
1042     assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1043     const MachineOperand &MO = MI->getOperand(2);
1044     const GlobalValue *GValue = MO.getGlobal();
1045     MCSymbol *MOSymbol = getSymbol(GValue);
1046     const MCExpr *SymGotTlsGD =
1047       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA,
1048                               OutContext);
1049     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1050                                  .addReg(MI->getOperand(0).getReg())
1051                                  .addReg(MI->getOperand(1).getReg())
1052                                  .addExpr(SymGotTlsGD));
1053     return;
1054   }
1055   case PPC::ADDItlsgdL:
1056     // Transform: %xd = ADDItlsgdL %xs, @sym
1057     // Into:      %xd = ADDI8 %xs, sym@got@tlsgd@l
1058   case PPC::ADDItlsgdL32: {
1059     // Transform: %rd = ADDItlsgdL32 %rs, @sym
1060     // Into:      %rd = ADDI %rs, sym@got@tlsgd
1061     const MachineOperand &MO = MI->getOperand(2);
1062     const GlobalValue *GValue = MO.getGlobal();
1063     MCSymbol *MOSymbol = getSymbol(GValue);
1064     const MCExpr *SymGotTlsGD = MCSymbolRefExpr::create(
1065         MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO
1066                           : MCSymbolRefExpr::VK_PPC_GOT_TLSGD,
1067         OutContext);
1068     EmitToStreamer(*OutStreamer,
1069                    MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1070                    .addReg(MI->getOperand(0).getReg())
1071                    .addReg(MI->getOperand(1).getReg())
1072                    .addExpr(SymGotTlsGD));
1073     return;
1074   }
1075   case PPC::GETtlsADDR:
1076     // Transform: %x3 = GETtlsADDR %x3, @sym
1077     // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsgd)
1078   case PPC::GETtlsADDR32: {
1079     // Transform: %r3 = GETtlsADDR32 %r3, @sym
1080     // Into: BL_TLS __tls_get_addr(sym at tlsgd)@PLT
1081     EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSGD);
1082     return;
1083   }
1084   case PPC::ADDIStlsldHA: {
1085     // Transform: %xd = ADDIStlsldHA %x2, @sym
1086     // Into:      %xd = ADDIS8 %x2, sym@got@tlsld@ha
1087     assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1088     const MachineOperand &MO = MI->getOperand(2);
1089     const GlobalValue *GValue = MO.getGlobal();
1090     MCSymbol *MOSymbol = getSymbol(GValue);
1091     const MCExpr *SymGotTlsLD =
1092       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA,
1093                               OutContext);
1094     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1095                                  .addReg(MI->getOperand(0).getReg())
1096                                  .addReg(MI->getOperand(1).getReg())
1097                                  .addExpr(SymGotTlsLD));
1098     return;
1099   }
1100   case PPC::ADDItlsldL:
1101     // Transform: %xd = ADDItlsldL %xs, @sym
1102     // Into:      %xd = ADDI8 %xs, sym@got@tlsld@l
1103   case PPC::ADDItlsldL32: {
1104     // Transform: %rd = ADDItlsldL32 %rs, @sym
1105     // Into:      %rd = ADDI %rs, sym@got@tlsld
1106     const MachineOperand &MO = MI->getOperand(2);
1107     const GlobalValue *GValue = MO.getGlobal();
1108     MCSymbol *MOSymbol = getSymbol(GValue);
1109     const MCExpr *SymGotTlsLD = MCSymbolRefExpr::create(
1110         MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO
1111                           : MCSymbolRefExpr::VK_PPC_GOT_TLSLD,
1112         OutContext);
1113     EmitToStreamer(*OutStreamer,
1114                    MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1115                        .addReg(MI->getOperand(0).getReg())
1116                        .addReg(MI->getOperand(1).getReg())
1117                        .addExpr(SymGotTlsLD));
1118     return;
1119   }
1120   case PPC::GETtlsldADDR:
1121     // Transform: %x3 = GETtlsldADDR %x3, @sym
1122     // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsld)
1123   case PPC::GETtlsldADDR32: {
1124     // Transform: %r3 = GETtlsldADDR32 %r3, @sym
1125     // Into: BL_TLS __tls_get_addr(sym at tlsld)@PLT
1126     EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSLD);
1127     return;
1128   }
1129   case PPC::ADDISdtprelHA:
1130     // Transform: %xd = ADDISdtprelHA %xs, @sym
1131     // Into:      %xd = ADDIS8 %xs, sym@dtprel@ha
1132   case PPC::ADDISdtprelHA32: {
1133     // Transform: %rd = ADDISdtprelHA32 %rs, @sym
1134     // Into:      %rd = ADDIS %rs, sym@dtprel@ha
1135     const MachineOperand &MO = MI->getOperand(2);
1136     const GlobalValue *GValue = MO.getGlobal();
1137     MCSymbol *MOSymbol = getSymbol(GValue);
1138     const MCExpr *SymDtprel =
1139       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_HA,
1140                               OutContext);
1141     EmitToStreamer(
1142         *OutStreamer,
1143         MCInstBuilder(IsPPC64 ? PPC::ADDIS8 : PPC::ADDIS)
1144             .addReg(MI->getOperand(0).getReg())
1145             .addReg(MI->getOperand(1).getReg())
1146             .addExpr(SymDtprel));
1147     return;
1148   }
1149   case PPC::ADDIdtprelL:
1150     // Transform: %xd = ADDIdtprelL %xs, @sym
1151     // Into:      %xd = ADDI8 %xs, sym@dtprel@l
1152   case PPC::ADDIdtprelL32: {
1153     // Transform: %rd = ADDIdtprelL32 %rs, @sym
1154     // Into:      %rd = ADDI %rs, sym@dtprel@l
1155     const MachineOperand &MO = MI->getOperand(2);
1156     const GlobalValue *GValue = MO.getGlobal();
1157     MCSymbol *MOSymbol = getSymbol(GValue);
1158     const MCExpr *SymDtprel =
1159       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_LO,
1160                               OutContext);
1161     EmitToStreamer(*OutStreamer,
1162                    MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1163                        .addReg(MI->getOperand(0).getReg())
1164                        .addReg(MI->getOperand(1).getReg())
1165                        .addExpr(SymDtprel));
1166     return;
1167   }
1168   case PPC::MFOCRF:
1169   case PPC::MFOCRF8:
1170     if (!Subtarget->hasMFOCRF()) {
1171       // Transform: %r3 = MFOCRF %cr7
1172       // Into:      %r3 = MFCR   ;; cr7
1173       unsigned NewOpcode =
1174         MI->getOpcode() == PPC::MFOCRF ? PPC::MFCR : PPC::MFCR8;
1175       OutStreamer->AddComment(PPCInstPrinter::
1176                               getRegisterName(MI->getOperand(1).getReg()));
1177       EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1178                                   .addReg(MI->getOperand(0).getReg()));
1179       return;
1180     }
1181     break;
1182   case PPC::MTOCRF:
1183   case PPC::MTOCRF8:
1184     if (!Subtarget->hasMFOCRF()) {
1185       // Transform: %cr7 = MTOCRF %r3
1186       // Into:      MTCRF mask, %r3 ;; cr7
1187       unsigned NewOpcode =
1188         MI->getOpcode() == PPC::MTOCRF ? PPC::MTCRF : PPC::MTCRF8;
1189       unsigned Mask = 0x80 >> OutContext.getRegisterInfo()
1190                               ->getEncodingValue(MI->getOperand(0).getReg());
1191       OutStreamer->AddComment(PPCInstPrinter::
1192                               getRegisterName(MI->getOperand(0).getReg()));
1193       EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1194                                      .addImm(Mask)
1195                                      .addReg(MI->getOperand(1).getReg()));
1196       return;
1197     }
1198     break;
1199   case PPC::LD:
1200   case PPC::STD:
1201   case PPC::LWA_32:
1202   case PPC::LWA: {
1203     // Verify alignment is legal, so we don't create relocations
1204     // that can't be supported.
1205     // FIXME:  This test is currently disabled for Darwin.  The test
1206     // suite shows a handful of test cases that fail this check for
1207     // Darwin.  Those need to be investigated before this sanity test
1208     // can be enabled for those subtargets.
1209     unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1;
1210     const MachineOperand &MO = MI->getOperand(OpNum);
1211     if (MO.isGlobal()) {
1212       const DataLayout &DL = MO.getGlobal()->getParent()->getDataLayout();
1213       if (MO.getGlobal()->getPointerAlignment(DL) < 4)
1214         llvm_unreachable("Global must be word-aligned for LD, STD, LWA!");
1215     }
1216     // Now process the instruction normally.
1217     break;
1218   }
1219   }
1220 
1221   LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1222   EmitToStreamer(*OutStreamer, TmpInst);
1223 }
1224 
1225 void PPCLinuxAsmPrinter::emitInstruction(const MachineInstr *MI) {
1226   if (!Subtarget->isPPC64())
1227     return PPCAsmPrinter::emitInstruction(MI);
1228 
1229   switch (MI->getOpcode()) {
1230   default:
1231     return PPCAsmPrinter::emitInstruction(MI);
1232   case TargetOpcode::PATCHABLE_FUNCTION_ENTER: {
1233     // .begin:
1234     //   b .end # lis 0, FuncId[16..32]
1235     //   nop    # li  0, FuncId[0..15]
1236     //   std 0, -8(1)
1237     //   mflr 0
1238     //   bl __xray_FunctionEntry
1239     //   mtlr 0
1240     // .end:
1241     //
1242     // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1243     // of instructions change.
1244     MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1245     MCSymbol *EndOfSled = OutContext.createTempSymbol();
1246     OutStreamer->emitLabel(BeginOfSled);
1247     EmitToStreamer(*OutStreamer,
1248                    MCInstBuilder(PPC::B).addExpr(
1249                        MCSymbolRefExpr::create(EndOfSled, OutContext)));
1250     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1251     EmitToStreamer(
1252         *OutStreamer,
1253         MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1254     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1255     EmitToStreamer(*OutStreamer,
1256                    MCInstBuilder(PPC::BL8_NOP)
1257                        .addExpr(MCSymbolRefExpr::create(
1258                            OutContext.getOrCreateSymbol("__xray_FunctionEntry"),
1259                            OutContext)));
1260     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1261     OutStreamer->emitLabel(EndOfSled);
1262     recordSled(BeginOfSled, *MI, SledKind::FUNCTION_ENTER, 2);
1263     break;
1264   }
1265   case TargetOpcode::PATCHABLE_RET: {
1266     unsigned RetOpcode = MI->getOperand(0).getImm();
1267     MCInst RetInst;
1268     RetInst.setOpcode(RetOpcode);
1269     for (const auto &MO :
1270          make_range(std::next(MI->operands_begin()), MI->operands_end())) {
1271       MCOperand MCOp;
1272       if (LowerPPCMachineOperandToMCOperand(MO, MCOp, *this))
1273         RetInst.addOperand(MCOp);
1274     }
1275 
1276     bool IsConditional;
1277     if (RetOpcode == PPC::BCCLR) {
1278       IsConditional = true;
1279     } else if (RetOpcode == PPC::TCRETURNdi8 || RetOpcode == PPC::TCRETURNri8 ||
1280                RetOpcode == PPC::TCRETURNai8) {
1281       break;
1282     } else if (RetOpcode == PPC::BLR8 || RetOpcode == PPC::TAILB8) {
1283       IsConditional = false;
1284     } else {
1285       EmitToStreamer(*OutStreamer, RetInst);
1286       break;
1287     }
1288 
1289     MCSymbol *FallthroughLabel;
1290     if (IsConditional) {
1291       // Before:
1292       //   bgtlr cr0
1293       //
1294       // After:
1295       //   ble cr0, .end
1296       // .p2align 3
1297       // .begin:
1298       //   blr    # lis 0, FuncId[16..32]
1299       //   nop    # li  0, FuncId[0..15]
1300       //   std 0, -8(1)
1301       //   mflr 0
1302       //   bl __xray_FunctionExit
1303       //   mtlr 0
1304       //   blr
1305       // .end:
1306       //
1307       // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1308       // of instructions change.
1309       FallthroughLabel = OutContext.createTempSymbol();
1310       EmitToStreamer(
1311           *OutStreamer,
1312           MCInstBuilder(PPC::BCC)
1313               .addImm(PPC::InvertPredicate(
1314                   static_cast<PPC::Predicate>(MI->getOperand(1).getImm())))
1315               .addReg(MI->getOperand(2).getReg())
1316               .addExpr(MCSymbolRefExpr::create(FallthroughLabel, OutContext)));
1317       RetInst = MCInst();
1318       RetInst.setOpcode(PPC::BLR8);
1319     }
1320     // .p2align 3
1321     // .begin:
1322     //   b(lr)? # lis 0, FuncId[16..32]
1323     //   nop    # li  0, FuncId[0..15]
1324     //   std 0, -8(1)
1325     //   mflr 0
1326     //   bl __xray_FunctionExit
1327     //   mtlr 0
1328     //   b(lr)?
1329     //
1330     // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1331     // of instructions change.
1332     OutStreamer->emitCodeAlignment(8);
1333     MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1334     OutStreamer->emitLabel(BeginOfSled);
1335     EmitToStreamer(*OutStreamer, RetInst);
1336     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1337     EmitToStreamer(
1338         *OutStreamer,
1339         MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1340     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1341     EmitToStreamer(*OutStreamer,
1342                    MCInstBuilder(PPC::BL8_NOP)
1343                        .addExpr(MCSymbolRefExpr::create(
1344                            OutContext.getOrCreateSymbol("__xray_FunctionExit"),
1345                            OutContext)));
1346     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1347     EmitToStreamer(*OutStreamer, RetInst);
1348     if (IsConditional)
1349       OutStreamer->emitLabel(FallthroughLabel);
1350     recordSled(BeginOfSled, *MI, SledKind::FUNCTION_EXIT, 2);
1351     break;
1352   }
1353   case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
1354     llvm_unreachable("PATCHABLE_FUNCTION_EXIT should never be emitted");
1355   case TargetOpcode::PATCHABLE_TAIL_CALL:
1356     // TODO: Define a trampoline `__xray_FunctionTailExit` and differentiate a
1357     // normal function exit from a tail exit.
1358     llvm_unreachable("Tail call is handled in the normal case. See comments "
1359                      "around this assert.");
1360   }
1361 }
1362 
1363 void PPCLinuxAsmPrinter::emitStartOfAsmFile(Module &M) {
1364   if (static_cast<const PPCTargetMachine &>(TM).isELFv2ABI()) {
1365     PPCTargetStreamer *TS =
1366       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1367 
1368     if (TS)
1369       TS->emitAbiVersion(2);
1370   }
1371 
1372   if (static_cast<const PPCTargetMachine &>(TM).isPPC64() ||
1373       !isPositionIndependent())
1374     return AsmPrinter::emitStartOfAsmFile(M);
1375 
1376   if (M.getPICLevel() == PICLevel::SmallPIC)
1377     return AsmPrinter::emitStartOfAsmFile(M);
1378 
1379   OutStreamer->SwitchSection(OutContext.getELFSection(
1380       ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC));
1381 
1382   MCSymbol *TOCSym = OutContext.getOrCreateSymbol(Twine(".LTOC"));
1383   MCSymbol *CurrentPos = OutContext.createTempSymbol();
1384 
1385   OutStreamer->emitLabel(CurrentPos);
1386 
1387   // The GOT pointer points to the middle of the GOT, in order to reference the
1388   // entire 64kB range.  0x8000 is the midpoint.
1389   const MCExpr *tocExpr =
1390     MCBinaryExpr::createAdd(MCSymbolRefExpr::create(CurrentPos, OutContext),
1391                             MCConstantExpr::create(0x8000, OutContext),
1392                             OutContext);
1393 
1394   OutStreamer->emitAssignment(TOCSym, tocExpr);
1395 
1396   OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
1397 }
1398 
1399 void PPCLinuxAsmPrinter::emitFunctionEntryLabel() {
1400   // linux/ppc32 - Normal entry label.
1401   if (!Subtarget->isPPC64() &&
1402       (!isPositionIndependent() ||
1403        MF->getFunction().getParent()->getPICLevel() == PICLevel::SmallPIC))
1404     return AsmPrinter::emitFunctionEntryLabel();
1405 
1406   if (!Subtarget->isPPC64()) {
1407     const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1408     if (PPCFI->usesPICBase() && !Subtarget->isSecurePlt()) {
1409       MCSymbol *RelocSymbol = PPCFI->getPICOffsetSymbol(*MF);
1410       MCSymbol *PICBase = MF->getPICBaseSymbol();
1411       OutStreamer->emitLabel(RelocSymbol);
1412 
1413       const MCExpr *OffsExpr =
1414         MCBinaryExpr::createSub(
1415           MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")),
1416                                                                OutContext),
1417                                   MCSymbolRefExpr::create(PICBase, OutContext),
1418           OutContext);
1419       OutStreamer->emitValue(OffsExpr, 4);
1420       OutStreamer->emitLabel(CurrentFnSym);
1421       return;
1422     } else
1423       return AsmPrinter::emitFunctionEntryLabel();
1424   }
1425 
1426   // ELFv2 ABI - Normal entry label.
1427   if (Subtarget->isELFv2ABI()) {
1428     // In the Large code model, we allow arbitrary displacements between
1429     // the text section and its associated TOC section.  We place the
1430     // full 8-byte offset to the TOC in memory immediately preceding
1431     // the function global entry point.
1432     if (TM.getCodeModel() == CodeModel::Large
1433         && !MF->getRegInfo().use_empty(PPC::X2)) {
1434       const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1435 
1436       MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1437       MCSymbol *GlobalEPSymbol = PPCFI->getGlobalEPSymbol(*MF);
1438       const MCExpr *TOCDeltaExpr =
1439         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1440                                 MCSymbolRefExpr::create(GlobalEPSymbol,
1441                                                         OutContext),
1442                                 OutContext);
1443 
1444       OutStreamer->emitLabel(PPCFI->getTOCOffsetSymbol(*MF));
1445       OutStreamer->emitValue(TOCDeltaExpr, 8);
1446     }
1447     return AsmPrinter::emitFunctionEntryLabel();
1448   }
1449 
1450   // Emit an official procedure descriptor.
1451   MCSectionSubPair Current = OutStreamer->getCurrentSection();
1452   MCSectionELF *Section = OutStreamer->getContext().getELFSection(
1453       ".opd", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1454   OutStreamer->SwitchSection(Section);
1455   OutStreamer->emitLabel(CurrentFnSym);
1456   OutStreamer->emitValueToAlignment(8);
1457   MCSymbol *Symbol1 = CurrentFnSymForSize;
1458   // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function
1459   // entry point.
1460   OutStreamer->emitValue(MCSymbolRefExpr::create(Symbol1, OutContext),
1461                          8 /*size*/);
1462   MCSymbol *Symbol2 = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1463   // Generates a R_PPC64_TOC relocation for TOC base insertion.
1464   OutStreamer->emitValue(
1465     MCSymbolRefExpr::create(Symbol2, MCSymbolRefExpr::VK_PPC_TOCBASE, OutContext),
1466     8/*size*/);
1467   // Emit a null environment pointer.
1468   OutStreamer->emitIntValue(0, 8 /* size */);
1469   OutStreamer->SwitchSection(Current.first, Current.second);
1470 }
1471 
1472 void PPCLinuxAsmPrinter::emitEndOfAsmFile(Module &M) {
1473   const DataLayout &DL = getDataLayout();
1474 
1475   bool isPPC64 = DL.getPointerSizeInBits() == 64;
1476 
1477   PPCTargetStreamer *TS =
1478       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1479 
1480   if (!TOC.empty()) {
1481     const char *Name = isPPC64 ? ".toc" : ".got2";
1482     MCSectionELF *Section = OutContext.getELFSection(
1483         Name, ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1484     OutStreamer->SwitchSection(Section);
1485     if (!isPPC64)
1486       OutStreamer->emitValueToAlignment(4);
1487 
1488     for (const auto &TOCMapPair : TOC) {
1489       const MCSymbol *const TOCEntryTarget = TOCMapPair.first;
1490       MCSymbol *const TOCEntryLabel = TOCMapPair.second;
1491 
1492       OutStreamer->emitLabel(TOCEntryLabel);
1493       if (isPPC64 && TS != nullptr)
1494         TS->emitTCEntry(*TOCEntryTarget);
1495       else
1496         OutStreamer->emitSymbolValue(TOCEntryTarget, 4);
1497     }
1498   }
1499 
1500   PPCAsmPrinter::emitEndOfAsmFile(M);
1501 }
1502 
1503 /// EmitFunctionBodyStart - Emit a global entry point prefix for ELFv2.
1504 void PPCLinuxAsmPrinter::emitFunctionBodyStart() {
1505   // In the ELFv2 ABI, in functions that use the TOC register, we need to
1506   // provide two entry points.  The ABI guarantees that when calling the
1507   // local entry point, r2 is set up by the caller to contain the TOC base
1508   // for this function, and when calling the global entry point, r12 is set
1509   // up by the caller to hold the address of the global entry point.  We
1510   // thus emit a prefix sequence along the following lines:
1511   //
1512   // func:
1513   // .Lfunc_gepNN:
1514   //         # global entry point
1515   //         addis r2,r12,(.TOC.-.Lfunc_gepNN)@ha
1516   //         addi  r2,r2,(.TOC.-.Lfunc_gepNN)@l
1517   // .Lfunc_lepNN:
1518   //         .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1519   //         # local entry point, followed by function body
1520   //
1521   // For the Large code model, we create
1522   //
1523   // .Lfunc_tocNN:
1524   //         .quad .TOC.-.Lfunc_gepNN      # done by EmitFunctionEntryLabel
1525   // func:
1526   // .Lfunc_gepNN:
1527   //         # global entry point
1528   //         ld    r2,.Lfunc_tocNN-.Lfunc_gepNN(r12)
1529   //         add   r2,r2,r12
1530   // .Lfunc_lepNN:
1531   //         .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1532   //         # local entry point, followed by function body
1533   //
1534   // This ensures we have r2 set up correctly while executing the function
1535   // body, no matter which entry point is called.
1536   const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1537   const bool UsesX2OrR2 = !MF->getRegInfo().use_empty(PPC::X2) ||
1538                           !MF->getRegInfo().use_empty(PPC::R2);
1539   const bool PCrelGEPRequired = Subtarget->isUsingPCRelativeCalls() &&
1540                                 UsesX2OrR2 && PPCFI->usesTOCBasePtr();
1541   const bool NonPCrelGEPRequired = !Subtarget->isUsingPCRelativeCalls() &&
1542                                    Subtarget->isELFv2ABI() && UsesX2OrR2;
1543 
1544   // Only do all that if the function uses R2 as the TOC pointer
1545   // in the first place. We don't need the global entry point if the
1546   // function uses R2 as an allocatable register.
1547   if (NonPCrelGEPRequired || PCrelGEPRequired) {
1548     // Note: The logic here must be synchronized with the code in the
1549     // branch-selection pass which sets the offset of the first block in the
1550     // function. This matters because it affects the alignment.
1551     MCSymbol *GlobalEntryLabel = PPCFI->getGlobalEPSymbol(*MF);
1552     OutStreamer->emitLabel(GlobalEntryLabel);
1553     const MCSymbolRefExpr *GlobalEntryLabelExp =
1554       MCSymbolRefExpr::create(GlobalEntryLabel, OutContext);
1555 
1556     if (TM.getCodeModel() != CodeModel::Large) {
1557       MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1558       const MCExpr *TOCDeltaExpr =
1559         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1560                                 GlobalEntryLabelExp, OutContext);
1561 
1562       const MCExpr *TOCDeltaHi = PPCMCExpr::createHa(TOCDeltaExpr, OutContext);
1563       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1564                                    .addReg(PPC::X2)
1565                                    .addReg(PPC::X12)
1566                                    .addExpr(TOCDeltaHi));
1567 
1568       const MCExpr *TOCDeltaLo = PPCMCExpr::createLo(TOCDeltaExpr, OutContext);
1569       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI)
1570                                    .addReg(PPC::X2)
1571                                    .addReg(PPC::X2)
1572                                    .addExpr(TOCDeltaLo));
1573     } else {
1574       MCSymbol *TOCOffset = PPCFI->getTOCOffsetSymbol(*MF);
1575       const MCExpr *TOCOffsetDeltaExpr =
1576         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCOffset, OutContext),
1577                                 GlobalEntryLabelExp, OutContext);
1578 
1579       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
1580                                    .addReg(PPC::X2)
1581                                    .addExpr(TOCOffsetDeltaExpr)
1582                                    .addReg(PPC::X12));
1583       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD8)
1584                                    .addReg(PPC::X2)
1585                                    .addReg(PPC::X2)
1586                                    .addReg(PPC::X12));
1587     }
1588 
1589     MCSymbol *LocalEntryLabel = PPCFI->getLocalEPSymbol(*MF);
1590     OutStreamer->emitLabel(LocalEntryLabel);
1591     const MCSymbolRefExpr *LocalEntryLabelExp =
1592        MCSymbolRefExpr::create(LocalEntryLabel, OutContext);
1593     const MCExpr *LocalOffsetExp =
1594       MCBinaryExpr::createSub(LocalEntryLabelExp,
1595                               GlobalEntryLabelExp, OutContext);
1596 
1597     PPCTargetStreamer *TS =
1598       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1599 
1600     if (TS)
1601       TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), LocalOffsetExp);
1602   } else if (Subtarget->isUsingPCRelativeCalls()) {
1603     // When generating the entry point for a function we have a few scenarios
1604     // based on whether or not that function uses R2 and whether or not that
1605     // function makes calls (or is a leaf function).
1606     // 1) A leaf function that does not use R2 (or treats it as callee-saved
1607     //    and preserves it). In this case st_other=0 and both
1608     //    the local and global entry points for the function are the same.
1609     //    No special entry point code is required.
1610     // 2) A function uses the TOC pointer R2. This function may or may not have
1611     //    calls. In this case st_other=[2,6] and the global and local entry
1612     //    points are different. Code to correctly setup the TOC pointer in R2
1613     //    is put between the global and local entry points. This case is
1614     //    covered by the if statatement above.
1615     // 3) A function does not use the TOC pointer R2 but does have calls.
1616     //    In this case st_other=1 since we do not know whether or not any
1617     //    of the callees clobber R2. This case is dealt with in this else if
1618     //    block. Tail calls are considered calls and the st_other should also
1619     //    be set to 1 in that case as well.
1620     // 4) The function does not use the TOC pointer but R2 is used inside
1621     //    the function. In this case st_other=1 once again.
1622     // 5) This function uses inline asm. We mark R2 as reserved if the function
1623     //    has inline asm as we have to assume that it may be used.
1624     if (MF->getFrameInfo().hasCalls() || MF->getFrameInfo().hasTailCall() ||
1625         MF->hasInlineAsm() || (!PPCFI->usesTOCBasePtr() && UsesX2OrR2)) {
1626       PPCTargetStreamer *TS =
1627           static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1628       if (TS)
1629         TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym),
1630                            MCConstantExpr::create(1, OutContext));
1631     }
1632   }
1633 }
1634 
1635 /// EmitFunctionBodyEnd - Print the traceback table before the .size
1636 /// directive.
1637 ///
1638 void PPCLinuxAsmPrinter::emitFunctionBodyEnd() {
1639   // Only the 64-bit target requires a traceback table.  For now,
1640   // we only emit the word of zeroes that GDB requires to find
1641   // the end of the function, and zeroes for the eight-byte
1642   // mandatory fields.
1643   // FIXME: We should fill in the eight-byte mandatory fields as described in
1644   // the PPC64 ELF ABI (this is a low-priority item because GDB does not
1645   // currently make use of these fields).
1646   if (Subtarget->isPPC64()) {
1647     OutStreamer->emitIntValue(0, 4/*size*/);
1648     OutStreamer->emitIntValue(0, 8/*size*/);
1649   }
1650 }
1651 
1652 void PPCAIXAsmPrinter::emitLinkage(const GlobalValue *GV,
1653                                    MCSymbol *GVSym) const {
1654 
1655   assert(MAI->hasVisibilityOnlyWithLinkage() &&
1656          "AIX's linkage directives take a visibility setting.");
1657 
1658   MCSymbolAttr LinkageAttr = MCSA_Invalid;
1659   switch (GV->getLinkage()) {
1660   case GlobalValue::ExternalLinkage:
1661     LinkageAttr = GV->isDeclaration() ? MCSA_Extern : MCSA_Global;
1662     break;
1663   case GlobalValue::LinkOnceAnyLinkage:
1664   case GlobalValue::LinkOnceODRLinkage:
1665   case GlobalValue::WeakAnyLinkage:
1666   case GlobalValue::WeakODRLinkage:
1667   case GlobalValue::ExternalWeakLinkage:
1668     LinkageAttr = MCSA_Weak;
1669     break;
1670   case GlobalValue::AvailableExternallyLinkage:
1671     LinkageAttr = MCSA_Extern;
1672     break;
1673   case GlobalValue::PrivateLinkage:
1674     return;
1675   case GlobalValue::InternalLinkage:
1676     assert(GV->getVisibility() == GlobalValue::DefaultVisibility &&
1677            "InternalLinkage should not have other visibility setting.");
1678     LinkageAttr = MCSA_LGlobal;
1679     break;
1680   case GlobalValue::AppendingLinkage:
1681     llvm_unreachable("Should never emit this");
1682   case GlobalValue::CommonLinkage:
1683     llvm_unreachable("CommonLinkage of XCOFF should not come to this path");
1684   }
1685 
1686   assert(LinkageAttr != MCSA_Invalid && "LinkageAttr should not MCSA_Invalid.");
1687 
1688   MCSymbolAttr VisibilityAttr = MCSA_Invalid;
1689   switch (GV->getVisibility()) {
1690 
1691   // TODO: "exported" and "internal" Visibility needs to go here.
1692   case GlobalValue::DefaultVisibility:
1693     break;
1694   case GlobalValue::HiddenVisibility:
1695     VisibilityAttr = MAI->getHiddenVisibilityAttr();
1696     break;
1697   case GlobalValue::ProtectedVisibility:
1698     VisibilityAttr = MAI->getProtectedVisibilityAttr();
1699     break;
1700   }
1701 
1702   OutStreamer->emitXCOFFSymbolLinkageWithVisibility(GVSym, LinkageAttr,
1703                                                     VisibilityAttr);
1704 }
1705 
1706 void PPCAIXAsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1707   // Setup CurrentFnDescSym and its containing csect.
1708   MCSectionXCOFF *FnDescSec =
1709       cast<MCSectionXCOFF>(getObjFileLowering().getSectionForFunctionDescriptor(
1710           &MF.getFunction(), TM));
1711   FnDescSec->setAlignment(Align(Subtarget->isPPC64() ? 8 : 4));
1712 
1713   CurrentFnDescSym = FnDescSec->getQualNameSymbol();
1714 
1715   return AsmPrinter::SetupMachineFunction(MF);
1716 }
1717 
1718 void PPCAIXAsmPrinter::ValidateGV(const GlobalVariable *GV) {
1719   // Early error checking limiting what is supported.
1720   if (GV->isThreadLocal())
1721     report_fatal_error("Thread local not yet supported on AIX.");
1722 
1723   if (GV->hasSection())
1724     report_fatal_error("Custom section for Data not yet supported.");
1725 
1726   if (GV->hasComdat())
1727     report_fatal_error("COMDAT not yet supported by AIX.");
1728 }
1729 
1730 static bool isSpecialLLVMGlobalArrayToSkip(const GlobalVariable *GV) {
1731   return GV->hasAppendingLinkage() &&
1732          StringSwitch<bool>(GV->getName())
1733              // TODO: Linker could still eliminate the GV if we just skip
1734              // handling llvm.used array. Skipping them for now until we or the
1735              // AIX OS team come up with a good solution.
1736              .Case("llvm.used", true)
1737              // It's correct to just skip llvm.compiler.used array here.
1738              .Case("llvm.compiler.used", true)
1739              .Default(false);
1740 }
1741 
1742 static bool isSpecialLLVMGlobalArrayForStaticInit(const GlobalVariable *GV) {
1743   return StringSwitch<bool>(GV->getName())
1744       .Cases("llvm.global_ctors", "llvm.global_dtors", true)
1745       .Default(false);
1746 }
1747 
1748 void PPCAIXAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
1749   // Special LLVM global arrays have been handled at the initialization.
1750   if (isSpecialLLVMGlobalArrayToSkip(GV) || isSpecialLLVMGlobalArrayForStaticInit(GV))
1751     return;
1752 
1753   assert(!GV->getName().startswith("llvm.") &&
1754          "Unhandled intrinsic global variable.");
1755   ValidateGV(GV);
1756 
1757   MCSymbolXCOFF *GVSym = cast<MCSymbolXCOFF>(getSymbol(GV));
1758 
1759   if (GV->isDeclarationForLinker()) {
1760     emitLinkage(GV, GVSym);
1761     return;
1762   }
1763 
1764   SectionKind GVKind = getObjFileLowering().getKindForGlobal(GV, TM);
1765   if (!GVKind.isGlobalWriteableData() && !GVKind.isReadOnly())
1766     report_fatal_error("Encountered a global variable kind that is "
1767                        "not supported yet.");
1768 
1769   MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
1770       getObjFileLowering().SectionForGlobal(GV, GVKind, TM));
1771 
1772   // Switch to the containing csect.
1773   OutStreamer->SwitchSection(Csect);
1774 
1775   const DataLayout &DL = GV->getParent()->getDataLayout();
1776 
1777   // Handle common symbols.
1778   if (GVKind.isCommon() || GVKind.isBSSLocal()) {
1779     Align Alignment = GV->getAlign().getValueOr(DL.getPreferredAlign(GV));
1780     uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
1781     GVSym->setStorageClass(
1782         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GV));
1783 
1784     if (GVKind.isBSSLocal())
1785       OutStreamer->emitXCOFFLocalCommonSymbol(
1786           OutContext.getOrCreateSymbol(GVSym->getSymbolTableName()), Size,
1787           GVSym, Alignment.value());
1788     else
1789       OutStreamer->emitCommonSymbol(GVSym, Size, Alignment.value());
1790     return;
1791   }
1792 
1793   MCSymbol *EmittedInitSym = GVSym;
1794   emitLinkage(GV, EmittedInitSym);
1795   emitAlignment(getGVAlignment(GV, DL), GV);
1796   OutStreamer->emitLabel(EmittedInitSym);
1797   // Emit aliasing label for global variable.
1798   llvm::for_each(GOAliasMap[GV], [this](const GlobalAlias *Alias) {
1799     OutStreamer->emitLabel(getSymbol(Alias));
1800   });
1801   emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
1802 }
1803 
1804 void PPCAIXAsmPrinter::emitFunctionDescriptor() {
1805   const DataLayout &DL = getDataLayout();
1806   const unsigned PointerSize = DL.getPointerSizeInBits() == 64 ? 8 : 4;
1807 
1808   MCSectionSubPair Current = OutStreamer->getCurrentSection();
1809   // Emit function descriptor.
1810   OutStreamer->SwitchSection(
1811       cast<MCSymbolXCOFF>(CurrentFnDescSym)->getRepresentedCsect());
1812 
1813   // Emit aliasing label for function descriptor csect.
1814   llvm::for_each(GOAliasMap[&MF->getFunction()],
1815                  [this](const GlobalAlias *Alias) {
1816                    OutStreamer->emitLabel(getSymbol(Alias));
1817                  });
1818 
1819   // Emit function entry point address.
1820   OutStreamer->emitValue(MCSymbolRefExpr::create(CurrentFnSym, OutContext),
1821                          PointerSize);
1822   // Emit TOC base address.
1823   const MCSymbol *TOCBaseSym =
1824       cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
1825           ->getQualNameSymbol();
1826   OutStreamer->emitValue(MCSymbolRefExpr::create(TOCBaseSym, OutContext),
1827                          PointerSize);
1828   // Emit a null environment pointer.
1829   OutStreamer->emitIntValue(0, PointerSize);
1830 
1831   OutStreamer->SwitchSection(Current.first, Current.second);
1832 }
1833 
1834 void PPCAIXAsmPrinter::emitFunctionEntryLabel() {
1835   // It's not necessary to emit the label when we have individual
1836   // function in its own csect.
1837   if (!TM.getFunctionSections())
1838     PPCAsmPrinter::emitFunctionEntryLabel();
1839 
1840   // Emit aliasing label for function entry point label.
1841   llvm::for_each(
1842       GOAliasMap[&MF->getFunction()], [this](const GlobalAlias *Alias) {
1843         OutStreamer->emitLabel(
1844             getObjFileLowering().getFunctionEntryPointSymbol(Alias, TM));
1845       });
1846 }
1847 
1848 void PPCAIXAsmPrinter::emitEndOfAsmFile(Module &M) {
1849   // If there are no functions in this module, we will never need to reference
1850   // the TOC base.
1851   if (M.empty())
1852     return;
1853 
1854   // Switch to section to emit TOC base.
1855   OutStreamer->SwitchSection(getObjFileLowering().getTOCBaseSection());
1856 
1857   PPCTargetStreamer *TS =
1858       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1859 
1860   for (auto &I : TOC) {
1861     // Setup the csect for the current TC entry.
1862     MCSectionXCOFF *TCEntry = cast<MCSectionXCOFF>(
1863         getObjFileLowering().getSectionForTOCEntry(I.first, TM));
1864     OutStreamer->SwitchSection(TCEntry);
1865 
1866     OutStreamer->emitLabel(I.second);
1867     if (TS != nullptr)
1868       TS->emitTCEntry(*I.first);
1869   }
1870 }
1871 
1872 bool PPCAIXAsmPrinter::doInitialization(Module &M) {
1873   const bool Result = PPCAsmPrinter::doInitialization(M);
1874 
1875   auto setCsectAlignment = [this](const GlobalObject *GO) {
1876     // Declarations have 0 alignment which is set by default.
1877     if (GO->isDeclarationForLinker())
1878       return;
1879 
1880     SectionKind GOKind = getObjFileLowering().getKindForGlobal(GO, TM);
1881     MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
1882         getObjFileLowering().SectionForGlobal(GO, GOKind, TM));
1883 
1884     Align GOAlign = getGVAlignment(GO, GO->getParent()->getDataLayout());
1885     if (GOAlign > Csect->getAlignment())
1886       Csect->setAlignment(GOAlign);
1887   };
1888 
1889   // We need to know, up front, the alignment of csects for the assembly path,
1890   // because once a .csect directive gets emitted, we could not change the
1891   // alignment value on it.
1892   for (const auto &G : M.globals()) {
1893     if (isSpecialLLVMGlobalArrayToSkip(&G))
1894       continue;
1895 
1896     if (isSpecialLLVMGlobalArrayForStaticInit(&G)) {
1897       // Generate a format indicator and a unique module id to be a part of
1898       // the sinit and sterm function names.
1899       if (FormatIndicatorAndUniqueModId.empty()) {
1900         std::string UniqueModuleId = getUniqueModuleId(&M);
1901         if (UniqueModuleId.compare("") != 0)
1902           // TODO: Use source file full path to generate the unique module id
1903           // and add a format indicator as a part of function name in case we
1904           // will support more than one format.
1905           FormatIndicatorAndUniqueModId = "clang_" + UniqueModuleId.substr(1);
1906         else
1907           // Use the Pid and current time as the unique module id when we cannot
1908           // generate one based on a module's strong external symbols.
1909           // FIXME: Adjust the comment accordingly after we use source file full
1910           // path instead.
1911           FormatIndicatorAndUniqueModId =
1912               "clangPidTime_" + llvm::itostr(sys::Process::getProcessId()) +
1913               "_" + llvm::itostr(time(nullptr));
1914       }
1915 
1916       emitSpecialLLVMGlobal(&G);
1917       continue;
1918     }
1919 
1920     setCsectAlignment(&G);
1921   }
1922 
1923   for (const auto &F : M)
1924     setCsectAlignment(&F);
1925 
1926   // Construct an aliasing list for each GlobalObject.
1927   for (const auto &Alias : M.aliases()) {
1928     const GlobalObject *Base = Alias.getBaseObject();
1929     if (!Base)
1930       report_fatal_error(
1931           "alias without a base object is not yet supported on AIX");
1932     GOAliasMap[Base].push_back(&Alias);
1933   }
1934 
1935   return Result;
1936 }
1937 
1938 void PPCAIXAsmPrinter::emitInstruction(const MachineInstr *MI) {
1939   switch (MI->getOpcode()) {
1940   default:
1941     break;
1942   case PPC::BL8:
1943   case PPC::BL:
1944   case PPC::BL8_NOP:
1945   case PPC::BL_NOP: {
1946     const MachineOperand &MO = MI->getOperand(0);
1947     if (MO.isSymbol()) {
1948       MCSymbolXCOFF *S =
1949           cast<MCSymbolXCOFF>(OutContext.getOrCreateSymbol(MO.getSymbolName()));
1950       ExtSymSDNodeSymbols.insert(S);
1951     }
1952   } break;
1953   case PPC::BL_TLS:
1954   case PPC::BL8_TLS:
1955   case PPC::BL8_TLS_:
1956   case PPC::BL8_NOP_TLS:
1957     report_fatal_error("TLS call not yet implemented");
1958   case PPC::TAILB:
1959   case PPC::TAILB8:
1960   case PPC::TAILBA:
1961   case PPC::TAILBA8:
1962   case PPC::TAILBCTR:
1963   case PPC::TAILBCTR8:
1964     if (MI->getOperand(0).isSymbol())
1965       report_fatal_error("Tail call for extern symbol not yet supported.");
1966     break;
1967   }
1968   return PPCAsmPrinter::emitInstruction(MI);
1969 }
1970 
1971 bool PPCAIXAsmPrinter::doFinalization(Module &M) {
1972   for (MCSymbol *Sym : ExtSymSDNodeSymbols)
1973     OutStreamer->emitSymbolAttribute(Sym, MCSA_Extern);
1974   return PPCAsmPrinter::doFinalization(M);
1975 }
1976 
1977 void PPCAIXAsmPrinter::emitXXStructorList(const DataLayout &DL,
1978                                           const Constant *List, bool IsCtor) {
1979   SmallVector<Structor, 8> Structors;
1980   preprocessXXStructorList(DL, List, Structors);
1981   if (Structors.empty())
1982     return;
1983 
1984   unsigned Index = 0;
1985   for (Structor &S : Structors) {
1986     if (S.Priority != 65535)
1987       report_fatal_error(
1988           "prioritized sinit and sterm functions are not yet supported on AIX");
1989 
1990     llvm::GlobalAlias::create(
1991         GlobalValue::ExternalLinkage,
1992         (IsCtor ? llvm::Twine("__sinit") : llvm::Twine("__sterm")) +
1993             llvm::Twine("80000000_", FormatIndicatorAndUniqueModId) +
1994             llvm::Twine("_", llvm::utostr(Index++)),
1995         cast<Function>(S.Func));
1996   }
1997 }
1998 
1999 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
2000 /// for a MachineFunction to the given output stream, in a format that the
2001 /// Darwin assembler can deal with.
2002 ///
2003 static AsmPrinter *
2004 createPPCAsmPrinterPass(TargetMachine &tm,
2005                         std::unique_ptr<MCStreamer> &&Streamer) {
2006   if (tm.getTargetTriple().isOSAIX())
2007     return new PPCAIXAsmPrinter(tm, std::move(Streamer));
2008 
2009   return new PPCLinuxAsmPrinter(tm, std::move(Streamer));
2010 }
2011 
2012 // Force static initialization.
2013 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCAsmPrinter() {
2014   TargetRegistry::RegisterAsmPrinter(getThePPC32Target(),
2015                                      createPPCAsmPrinterPass);
2016   TargetRegistry::RegisterAsmPrinter(getThePPC64Target(),
2017                                      createPPCAsmPrinterPass);
2018   TargetRegistry::RegisterAsmPrinter(getThePPC64LETarget(),
2019                                      createPPCAsmPrinterPass);
2020 }
2021