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/CodeGen/AsmPrinter.h"
36 #include "llvm/CodeGen/MachineBasicBlock.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineInstr.h"
39 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
40 #include "llvm/CodeGen/MachineOperand.h"
41 #include "llvm/CodeGen/MachineRegisterInfo.h"
42 #include "llvm/CodeGen/StackMaps.h"
43 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
44 #include "llvm/IR/DataLayout.h"
45 #include "llvm/IR/GlobalValue.h"
46 #include "llvm/IR/GlobalVariable.h"
47 #include "llvm/IR/Module.h"
48 #include "llvm/MC/MCAsmInfo.h"
49 #include "llvm/MC/MCContext.h"
50 #include "llvm/MC/MCDirectives.h"
51 #include "llvm/MC/MCExpr.h"
52 #include "llvm/MC/MCInst.h"
53 #include "llvm/MC/MCInstBuilder.h"
54 #include "llvm/MC/MCSectionELF.h"
55 #include "llvm/MC/MCSectionXCOFF.h"
56 #include "llvm/MC/MCStreamer.h"
57 #include "llvm/MC/MCSymbol.h"
58 #include "llvm/MC/MCSymbolELF.h"
59 #include "llvm/MC/MCSymbolXCOFF.h"
60 #include "llvm/MC/SectionKind.h"
61 #include "llvm/MC/TargetRegistry.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/CodeGen.h"
64 #include "llvm/Support/Debug.h"
65 #include "llvm/Support/Error.h"
66 #include "llvm/Support/ErrorHandling.h"
67 #include "llvm/Support/Process.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Target/TargetMachine.h"
70 #include "llvm/Transforms/Utils/ModuleUtils.h"
71 #include <algorithm>
72 #include <cassert>
73 #include <cstdint>
74 #include <memory>
75 #include <new>
76 
77 using namespace llvm;
78 using namespace llvm::XCOFF;
79 
80 #define DEBUG_TYPE "asmprinter"
81 
82 static cl::opt<bool> EnableSSPCanaryBitInTB(
83     "aix-ssp-tb-bit", cl::init(false),
84     cl::desc("Enable Passing SSP Canary info in Trackback on AIX"), cl::Hidden);
85 
86 // Specialize DenseMapInfo to allow
87 // std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind> in DenseMap.
88 // This specialization is needed here because that type is used as keys in the
89 // map representing TOC entries.
90 namespace llvm {
91 template <>
92 struct DenseMapInfo<std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>> {
93   using TOCKey = std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>;
94 
95   static inline TOCKey getEmptyKey() {
96     return {nullptr, MCSymbolRefExpr::VariantKind::VK_None};
97   }
98   static inline TOCKey getTombstoneKey() {
99     return {nullptr, MCSymbolRefExpr::VariantKind::VK_Invalid};
100   }
101   static unsigned getHashValue(const TOCKey &PairVal) {
102     return detail::combineHashValue(
103         DenseMapInfo<const MCSymbol *>::getHashValue(PairVal.first),
104         DenseMapInfo<int>::getHashValue(PairVal.second));
105   }
106   static bool isEqual(const TOCKey &A, const TOCKey &B) { return A == B; }
107 };
108 } // end namespace llvm
109 
110 namespace {
111 
112 enum {
113   // GNU attribute tags for PowerPC ABI
114   Tag_GNU_Power_ABI_FP = 4,
115   Tag_GNU_Power_ABI_Vector = 8,
116   Tag_GNU_Power_ABI_Struct_Return = 12,
117 
118   // GNU attribute values for PowerPC float ABI, as combination of two parts
119   Val_GNU_Power_ABI_NoFloat = 0b00,
120   Val_GNU_Power_ABI_HardFloat_DP = 0b01,
121   Val_GNU_Power_ABI_SoftFloat_DP = 0b10,
122   Val_GNU_Power_ABI_HardFloat_SP = 0b11,
123 
124   Val_GNU_Power_ABI_LDBL_IBM128 = 0b0100,
125   Val_GNU_Power_ABI_LDBL_64 = 0b1000,
126   Val_GNU_Power_ABI_LDBL_IEEE128 = 0b1100,
127 };
128 
129 class PPCAsmPrinter : public AsmPrinter {
130 protected:
131   // For TLS on AIX, we need to be able to identify TOC entries of specific
132   // VariantKind so we can add the right relocations when we generate the
133   // entries. So each entry is represented by a pair of MCSymbol and
134   // VariantKind. For example, we need to be able to identify the following
135   // entry as a TLSGD entry so we can add the @m relocation:
136   //   .tc .i[TC],i[TL]@m
137   // By default, VK_None is used for the VariantKind.
138   MapVector<std::pair<const MCSymbol *, MCSymbolRefExpr::VariantKind>,
139             MCSymbol *>
140       TOC;
141   const PPCSubtarget *Subtarget = nullptr;
142   StackMaps SM;
143 
144 public:
145   explicit PPCAsmPrinter(TargetMachine &TM,
146                          std::unique_ptr<MCStreamer> Streamer)
147       : AsmPrinter(TM, std::move(Streamer)), SM(*this) {}
148 
149   StringRef getPassName() const override { return "PowerPC Assembly Printer"; }
150 
151   MCSymbol *lookUpOrCreateTOCEntry(const MCSymbol *Sym,
152                                    MCSymbolRefExpr::VariantKind Kind =
153                                        MCSymbolRefExpr::VariantKind::VK_None);
154 
155   bool doInitialization(Module &M) override {
156     if (!TOC.empty())
157       TOC.clear();
158     return AsmPrinter::doInitialization(M);
159   }
160 
161   void emitInstruction(const MachineInstr *MI) override;
162 
163   /// This function is for PrintAsmOperand and PrintAsmMemoryOperand,
164   /// invoked by EmitMSInlineAsmStr and EmitGCCInlineAsmStr only.
165   /// The \p MI would be INLINEASM ONLY.
166   void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
167 
168   void PrintSymbolOperand(const MachineOperand &MO, raw_ostream &O) override;
169   bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
170                        const char *ExtraCode, raw_ostream &O) override;
171   bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
172                              const char *ExtraCode, raw_ostream &O) override;
173 
174   void emitEndOfAsmFile(Module &M) override;
175 
176   void LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI);
177   void LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI);
178   void EmitTlsCall(const MachineInstr *MI, MCSymbolRefExpr::VariantKind VK);
179   bool runOnMachineFunction(MachineFunction &MF) override {
180     Subtarget = &MF.getSubtarget<PPCSubtarget>();
181     bool Changed = AsmPrinter::runOnMachineFunction(MF);
182     emitXRayTable();
183     return Changed;
184   }
185 };
186 
187 /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
188 class PPCLinuxAsmPrinter : public PPCAsmPrinter {
189 public:
190   explicit PPCLinuxAsmPrinter(TargetMachine &TM,
191                               std::unique_ptr<MCStreamer> Streamer)
192       : PPCAsmPrinter(TM, std::move(Streamer)) {}
193 
194   StringRef getPassName() const override {
195     return "Linux PPC Assembly Printer";
196   }
197 
198   void emitGNUAttributes(Module &M);
199 
200   void emitStartOfAsmFile(Module &M) override;
201   void emitEndOfAsmFile(Module &) override;
202 
203   void emitFunctionEntryLabel() override;
204 
205   void emitFunctionBodyStart() override;
206   void emitFunctionBodyEnd() override;
207   void emitInstruction(const MachineInstr *MI) override;
208 };
209 
210 class PPCAIXAsmPrinter : public PPCAsmPrinter {
211 private:
212   /// Symbols lowered from ExternalSymbolSDNodes, we will need to emit extern
213   /// linkage for them in AIX.
214   SmallPtrSet<MCSymbol *, 8> ExtSymSDNodeSymbols;
215 
216   /// A format indicator and unique trailing identifier to form part of the
217   /// sinit/sterm function names.
218   std::string FormatIndicatorAndUniqueModId;
219 
220   // Record a list of GlobalAlias associated with a GlobalObject.
221   // This is used for AIX's extra-label-at-definition aliasing strategy.
222   DenseMap<const GlobalObject *, SmallVector<const GlobalAlias *, 1>>
223       GOAliasMap;
224 
225   uint16_t getNumberOfVRSaved();
226   void emitTracebackTable();
227 
228   SmallVector<const GlobalVariable *, 8> TOCDataGlobalVars;
229 
230   void emitGlobalVariableHelper(const GlobalVariable *);
231 
232 public:
233   PPCAIXAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
234       : PPCAsmPrinter(TM, std::move(Streamer)) {
235     if (MAI->isLittleEndian())
236       report_fatal_error(
237           "cannot create AIX PPC Assembly Printer for a little-endian target");
238   }
239 
240   StringRef getPassName() const override { return "AIX PPC Assembly Printer"; }
241 
242   bool doInitialization(Module &M) override;
243 
244   void emitXXStructorList(const DataLayout &DL, const Constant *List,
245                           bool IsCtor) override;
246 
247   void SetupMachineFunction(MachineFunction &MF) override;
248 
249   void emitGlobalVariable(const GlobalVariable *GV) override;
250 
251   void emitFunctionDescriptor() override;
252 
253   void emitFunctionEntryLabel() override;
254 
255   void emitFunctionBodyEnd() override;
256 
257   void emitPGORefs();
258 
259   void emitEndOfAsmFile(Module &) override;
260 
261   void emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const override;
262 
263   void emitInstruction(const MachineInstr *MI) override;
264 
265   bool doFinalization(Module &M) override;
266 
267   void emitTTypeReference(const GlobalValue *GV, unsigned Encoding) override;
268 };
269 
270 } // end anonymous namespace
271 
272 void PPCAsmPrinter::PrintSymbolOperand(const MachineOperand &MO,
273                                        raw_ostream &O) {
274   // Computing the address of a global symbol, not calling it.
275   const GlobalValue *GV = MO.getGlobal();
276   getSymbol(GV)->print(O, MAI);
277   printOffset(MO.getOffset(), O);
278 }
279 
280 void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
281                                  raw_ostream &O) {
282   const DataLayout &DL = getDataLayout();
283   const MachineOperand &MO = MI->getOperand(OpNo);
284 
285   switch (MO.getType()) {
286   case MachineOperand::MO_Register: {
287     // The MI is INLINEASM ONLY and UseVSXReg is always false.
288     const char *RegName = PPCInstPrinter::getRegisterName(MO.getReg());
289 
290     // Linux assembler (Others?) does not take register mnemonics.
291     // FIXME - What about special registers used in mfspr/mtspr?
292     O << PPCRegisterInfo::stripRegisterPrefix(RegName);
293     return;
294   }
295   case MachineOperand::MO_Immediate:
296     O << MO.getImm();
297     return;
298 
299   case MachineOperand::MO_MachineBasicBlock:
300     MO.getMBB()->getSymbol()->print(O, MAI);
301     return;
302   case MachineOperand::MO_ConstantPoolIndex:
303     O << DL.getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
304       << MO.getIndex();
305     return;
306   case MachineOperand::MO_BlockAddress:
307     GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI);
308     return;
309   case MachineOperand::MO_GlobalAddress: {
310     PrintSymbolOperand(MO, O);
311     return;
312   }
313 
314   default:
315     O << "<unknown operand type: " << (unsigned)MO.getType() << ">";
316     return;
317   }
318 }
319 
320 /// PrintAsmOperand - Print out an operand for an inline asm expression.
321 ///
322 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
323                                     const char *ExtraCode, raw_ostream &O) {
324   // Does this asm operand have a single letter operand modifier?
325   if (ExtraCode && ExtraCode[0]) {
326     if (ExtraCode[1] != 0) return true; // Unknown modifier.
327 
328     switch (ExtraCode[0]) {
329     default:
330       // See if this is a generic print operand
331       return AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O);
332     case 'L': // Write second word of DImode reference.
333       // Verify that this operand has two consecutive registers.
334       if (!MI->getOperand(OpNo).isReg() ||
335           OpNo+1 == MI->getNumOperands() ||
336           !MI->getOperand(OpNo+1).isReg())
337         return true;
338       ++OpNo;   // Return the high-part.
339       break;
340     case 'I':
341       // Write 'i' if an integer constant, otherwise nothing.  Used to print
342       // addi vs add, etc.
343       if (MI->getOperand(OpNo).isImm())
344         O << "i";
345       return false;
346     case 'x':
347       if(!MI->getOperand(OpNo).isReg())
348         return true;
349       // This operand uses VSX numbering.
350       // If the operand is a VMX register, convert it to a VSX register.
351       Register Reg = MI->getOperand(OpNo).getReg();
352       if (PPCInstrInfo::isVRRegister(Reg))
353         Reg = PPC::VSX32 + (Reg - PPC::V0);
354       else if (PPCInstrInfo::isVFRegister(Reg))
355         Reg = PPC::VSX32 + (Reg - PPC::VF0);
356       const char *RegName;
357       RegName = PPCInstPrinter::getRegisterName(Reg);
358       RegName = PPCRegisterInfo::stripRegisterPrefix(RegName);
359       O << RegName;
360       return false;
361     }
362   }
363 
364   printOperand(MI, OpNo, O);
365   return false;
366 }
367 
368 // At the moment, all inline asm memory operands are a single register.
369 // In any case, the output of this routine should always be just one
370 // assembler operand.
371 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
372                                           const char *ExtraCode,
373                                           raw_ostream &O) {
374   if (ExtraCode && ExtraCode[0]) {
375     if (ExtraCode[1] != 0) return true; // Unknown modifier.
376 
377     switch (ExtraCode[0]) {
378     default: return true;  // Unknown modifier.
379     case 'L': // A memory reference to the upper word of a double word op.
380       O << getDataLayout().getPointerSize() << "(";
381       printOperand(MI, OpNo, O);
382       O << ")";
383       return false;
384     case 'y': // A memory reference for an X-form instruction
385       O << "0, ";
386       printOperand(MI, OpNo, O);
387       return false;
388     case 'I':
389       // Write 'i' if an integer constant, otherwise nothing.  Used to print
390       // addi vs add, etc.
391       if (MI->getOperand(OpNo).isImm())
392         O << "i";
393       return false;
394     case 'U': // Print 'u' for update form.
395     case 'X': // Print 'x' for indexed form.
396       // FIXME: Currently for PowerPC memory operands are always loaded
397       // into a register, so we never get an update or indexed form.
398       // This is bad even for offset forms, since even if we know we
399       // have a value in -16(r1), we will generate a load into r<n>
400       // and then load from 0(r<n>).  Until that issue is fixed,
401       // tolerate 'U' and 'X' but don't output anything.
402       assert(MI->getOperand(OpNo).isReg());
403       return false;
404     }
405   }
406 
407   assert(MI->getOperand(OpNo).isReg());
408   O << "0(";
409   printOperand(MI, OpNo, O);
410   O << ")";
411   return false;
412 }
413 
414 /// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry
415 /// exists for it.  If not, create one.  Then return a symbol that references
416 /// the TOC entry.
417 MCSymbol *
418 PPCAsmPrinter::lookUpOrCreateTOCEntry(const MCSymbol *Sym,
419                                       MCSymbolRefExpr::VariantKind Kind) {
420   MCSymbol *&TOCEntry = TOC[{Sym, Kind}];
421   if (!TOCEntry)
422     TOCEntry = createTempSymbol("C");
423   return TOCEntry;
424 }
425 
426 void PPCAsmPrinter::emitEndOfAsmFile(Module &M) {
427   emitStackMaps(SM);
428 }
429 
430 void PPCAsmPrinter::LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI) {
431   unsigned NumNOPBytes = MI.getOperand(1).getImm();
432 
433   auto &Ctx = OutStreamer->getContext();
434   MCSymbol *MILabel = Ctx.createTempSymbol();
435   OutStreamer->emitLabel(MILabel);
436 
437   SM.recordStackMap(*MILabel, MI);
438   assert(NumNOPBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
439 
440   // Scan ahead to trim the shadow.
441   const MachineBasicBlock &MBB = *MI.getParent();
442   MachineBasicBlock::const_iterator MII(MI);
443   ++MII;
444   while (NumNOPBytes > 0) {
445     if (MII == MBB.end() || MII->isCall() ||
446         MII->getOpcode() == PPC::DBG_VALUE ||
447         MII->getOpcode() == TargetOpcode::PATCHPOINT ||
448         MII->getOpcode() == TargetOpcode::STACKMAP)
449       break;
450     ++MII;
451     NumNOPBytes -= 4;
452   }
453 
454   // Emit nops.
455   for (unsigned i = 0; i < NumNOPBytes; i += 4)
456     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
457 }
458 
459 // Lower a patchpoint of the form:
460 // [<def>], <id>, <numBytes>, <target>, <numArgs>
461 void PPCAsmPrinter::LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI) {
462   auto &Ctx = OutStreamer->getContext();
463   MCSymbol *MILabel = Ctx.createTempSymbol();
464   OutStreamer->emitLabel(MILabel);
465 
466   SM.recordPatchPoint(*MILabel, MI);
467   PatchPointOpers Opers(&MI);
468 
469   unsigned EncodedBytes = 0;
470   const MachineOperand &CalleeMO = Opers.getCallTarget();
471 
472   if (CalleeMO.isImm()) {
473     int64_t CallTarget = CalleeMO.getImm();
474     if (CallTarget) {
475       assert((CallTarget & 0xFFFFFFFFFFFF) == CallTarget &&
476              "High 16 bits of call target should be zero.");
477       Register ScratchReg = MI.getOperand(Opers.getNextScratchIdx()).getReg();
478       EncodedBytes = 0;
479       // Materialize the jump address:
480       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI8)
481                                       .addReg(ScratchReg)
482                                       .addImm((CallTarget >> 32) & 0xFFFF));
483       ++EncodedBytes;
484       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::RLDIC)
485                                       .addReg(ScratchReg)
486                                       .addReg(ScratchReg)
487                                       .addImm(32).addImm(16));
488       ++EncodedBytes;
489       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORIS8)
490                                       .addReg(ScratchReg)
491                                       .addReg(ScratchReg)
492                                       .addImm((CallTarget >> 16) & 0xFFFF));
493       ++EncodedBytes;
494       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORI8)
495                                       .addReg(ScratchReg)
496                                       .addReg(ScratchReg)
497                                       .addImm(CallTarget & 0xFFFF));
498 
499       // Save the current TOC pointer before the remote call.
500       int TOCSaveOffset = Subtarget->getFrameLowering()->getTOCSaveOffset();
501       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::STD)
502                                       .addReg(PPC::X2)
503                                       .addImm(TOCSaveOffset)
504                                       .addReg(PPC::X1));
505       ++EncodedBytes;
506 
507       // If we're on ELFv1, then we need to load the actual function pointer
508       // from the function descriptor.
509       if (!Subtarget->isELFv2ABI()) {
510         // Load the new TOC pointer and the function address, but not r11
511         // (needing this is rare, and loading it here would prevent passing it
512         // via a 'nest' parameter.
513         EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
514                                         .addReg(PPC::X2)
515                                         .addImm(8)
516                                         .addReg(ScratchReg));
517         ++EncodedBytes;
518         EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
519                                         .addReg(ScratchReg)
520                                         .addImm(0)
521                                         .addReg(ScratchReg));
522         ++EncodedBytes;
523       }
524 
525       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTCTR8)
526                                       .addReg(ScratchReg));
527       ++EncodedBytes;
528       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BCTRL8));
529       ++EncodedBytes;
530 
531       // Restore the TOC pointer after the call.
532       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
533                                       .addReg(PPC::X2)
534                                       .addImm(TOCSaveOffset)
535                                       .addReg(PPC::X1));
536       ++EncodedBytes;
537     }
538   } else if (CalleeMO.isGlobal()) {
539     const GlobalValue *GValue = CalleeMO.getGlobal();
540     MCSymbol *MOSymbol = getSymbol(GValue);
541     const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, OutContext);
542 
543     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL8_NOP)
544                                     .addExpr(SymVar));
545     EncodedBytes += 2;
546   }
547 
548   // Each instruction is 4 bytes.
549   EncodedBytes *= 4;
550 
551   // Emit padding.
552   unsigned NumBytes = Opers.getNumPatchBytes();
553   assert(NumBytes >= EncodedBytes &&
554          "Patchpoint can't request size less than the length of a call.");
555   assert((NumBytes - EncodedBytes) % 4 == 0 &&
556          "Invalid number of NOP bytes requested!");
557   for (unsigned i = EncodedBytes; i < NumBytes; i += 4)
558     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
559 }
560 
561 /// This helper function creates the TlsGetAddr MCSymbol for AIX. We will
562 /// create the csect and use the qual-name symbol instead of creating just the
563 /// external symbol.
564 static MCSymbol *createMCSymbolForTlsGetAddr(MCContext &Ctx) {
565   return Ctx
566       .getXCOFFSection(".__tls_get_addr", SectionKind::getText(),
567                        XCOFF::CsectProperties(XCOFF::XMC_PR, XCOFF::XTY_ER))
568       ->getQualNameSymbol();
569 }
570 
571 /// EmitTlsCall -- Given a GETtls[ld]ADDR[32] instruction, print a
572 /// call to __tls_get_addr to the current output stream.
573 void PPCAsmPrinter::EmitTlsCall(const MachineInstr *MI,
574                                 MCSymbolRefExpr::VariantKind VK) {
575   MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None;
576   unsigned Opcode = PPC::BL8_NOP_TLS;
577 
578   assert(MI->getNumOperands() >= 3 && "Expecting at least 3 operands from MI");
579   if (MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSGD_PCREL_FLAG ||
580       MI->getOperand(2).getTargetFlags() == PPCII::MO_GOT_TLSLD_PCREL_FLAG) {
581     Kind = MCSymbolRefExpr::VK_PPC_NOTOC;
582     Opcode = PPC::BL8_NOTOC_TLS;
583   }
584   const Module *M = MF->getFunction().getParent();
585 
586   assert(MI->getOperand(0).isReg() &&
587          ((Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::X3) ||
588           (!Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::R3)) &&
589          "GETtls[ld]ADDR[32] must define GPR3");
590   assert(MI->getOperand(1).isReg() &&
591          ((Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::X3) ||
592           (!Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::R3)) &&
593          "GETtls[ld]ADDR[32] must read GPR3");
594 
595   if (Subtarget->isAIXABI()) {
596     // On AIX, the variable offset should already be in R4 and the region handle
597     // should already be in R3.
598     // For TLSGD, which currently is the only supported access model, we only
599     // need to generate an absolute branch to .__tls_get_addr.
600     Register VarOffsetReg = Subtarget->isPPC64() ? PPC::X4 : PPC::R4;
601     (void)VarOffsetReg;
602     assert(MI->getOperand(2).isReg() &&
603            MI->getOperand(2).getReg() == VarOffsetReg &&
604            "GETtls[ld]ADDR[32] must read GPR4");
605     MCSymbol *TlsGetAddr = createMCSymbolForTlsGetAddr(OutContext);
606     const MCExpr *TlsRef = MCSymbolRefExpr::create(
607         TlsGetAddr, MCSymbolRefExpr::VK_None, OutContext);
608     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BLA).addExpr(TlsRef));
609     return;
610   }
611 
612   MCSymbol *TlsGetAddr = OutContext.getOrCreateSymbol("__tls_get_addr");
613 
614   if (Subtarget->is32BitELFABI() && isPositionIndependent())
615     Kind = MCSymbolRefExpr::VK_PLT;
616 
617   const MCExpr *TlsRef =
618     MCSymbolRefExpr::create(TlsGetAddr, Kind, OutContext);
619 
620   // Add 32768 offset to the symbol so we follow up the latest GOT/PLT ABI.
621   if (Kind == MCSymbolRefExpr::VK_PLT && Subtarget->isSecurePlt() &&
622       M->getPICLevel() == PICLevel::BigPIC)
623     TlsRef = MCBinaryExpr::createAdd(
624         TlsRef, MCConstantExpr::create(32768, OutContext), OutContext);
625   const MachineOperand &MO = MI->getOperand(2);
626   const GlobalValue *GValue = MO.getGlobal();
627   MCSymbol *MOSymbol = getSymbol(GValue);
628   const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
629   EmitToStreamer(*OutStreamer,
630                  MCInstBuilder(Subtarget->isPPC64() ? Opcode
631                                                     : (unsigned)PPC::BL_TLS)
632                      .addExpr(TlsRef)
633                      .addExpr(SymVar));
634 }
635 
636 /// Map a machine operand for a TOC pseudo-machine instruction to its
637 /// corresponding MCSymbol.
638 static MCSymbol *getMCSymbolForTOCPseudoMO(const MachineOperand &MO,
639                                            AsmPrinter &AP) {
640   switch (MO.getType()) {
641   case MachineOperand::MO_GlobalAddress:
642     return AP.getSymbol(MO.getGlobal());
643   case MachineOperand::MO_ConstantPoolIndex:
644     return AP.GetCPISymbol(MO.getIndex());
645   case MachineOperand::MO_JumpTableIndex:
646     return AP.GetJTISymbol(MO.getIndex());
647   case MachineOperand::MO_BlockAddress:
648     return AP.GetBlockAddressSymbol(MO.getBlockAddress());
649   default:
650     llvm_unreachable("Unexpected operand type to get symbol.");
651   }
652 }
653 
654 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
655 /// the current output stream.
656 ///
657 void PPCAsmPrinter::emitInstruction(const MachineInstr *MI) {
658   MCInst TmpInst;
659   const bool IsPPC64 = Subtarget->isPPC64();
660   const bool IsAIX = Subtarget->isAIXABI();
661   const Module *M = MF->getFunction().getParent();
662   PICLevel::Level PL = M->getPICLevel();
663 
664 #ifndef NDEBUG
665   // Validate that SPE and FPU are mutually exclusive in codegen
666   if (!MI->isInlineAsm()) {
667     for (const MachineOperand &MO: MI->operands()) {
668       if (MO.isReg()) {
669         Register Reg = MO.getReg();
670         if (Subtarget->hasSPE()) {
671           if (PPC::F4RCRegClass.contains(Reg) ||
672               PPC::F8RCRegClass.contains(Reg) ||
673               PPC::VFRCRegClass.contains(Reg) ||
674               PPC::VRRCRegClass.contains(Reg) ||
675               PPC::VSFRCRegClass.contains(Reg) ||
676               PPC::VSSRCRegClass.contains(Reg)
677               )
678             llvm_unreachable("SPE targets cannot have FPRegs!");
679         } else {
680           if (PPC::SPERCRegClass.contains(Reg))
681             llvm_unreachable("SPE register found in FPU-targeted code!");
682         }
683       }
684     }
685   }
686 #endif
687 
688   auto getTOCRelocAdjustedExprForXCOFF = [this](const MCExpr *Expr,
689                                                 ptrdiff_t OriginalOffset) {
690     // Apply an offset to the TOC-based expression such that the adjusted
691     // notional offset from the TOC base (to be encoded into the instruction's D
692     // or DS field) is the signed 16-bit truncation of the original notional
693     // offset from the TOC base.
694     // This is consistent with the treatment used both by XL C/C++ and
695     // by AIX ld -r.
696     ptrdiff_t Adjustment =
697         OriginalOffset - llvm::SignExtend32<16>(OriginalOffset);
698     return MCBinaryExpr::createAdd(
699         Expr, MCConstantExpr::create(-Adjustment, OutContext), OutContext);
700   };
701 
702   auto getTOCEntryLoadingExprForXCOFF =
703       [IsPPC64, getTOCRelocAdjustedExprForXCOFF,
704        this](const MCSymbol *MOSymbol, const MCExpr *Expr,
705              MCSymbolRefExpr::VariantKind VK =
706                  MCSymbolRefExpr::VariantKind::VK_None) -> const MCExpr * {
707     const unsigned EntryByteSize = IsPPC64 ? 8 : 4;
708     const auto TOCEntryIter = TOC.find({MOSymbol, VK});
709     assert(TOCEntryIter != TOC.end() &&
710            "Could not find the TOC entry for this symbol.");
711     const ptrdiff_t EntryDistanceFromTOCBase =
712         (TOCEntryIter - TOC.begin()) * EntryByteSize;
713     constexpr int16_t PositiveTOCRange = INT16_MAX;
714 
715     if (EntryDistanceFromTOCBase > PositiveTOCRange)
716       return getTOCRelocAdjustedExprForXCOFF(Expr, EntryDistanceFromTOCBase);
717 
718     return Expr;
719   };
720   auto GetVKForMO = [&](const MachineOperand &MO) {
721     // For GD TLS access on AIX, we have two TOC entries for the symbol (one for
722     // the variable offset and the other for the region handle). They are
723     // differentiated by MO_TLSGD_FLAG and MO_TLSGDM_FLAG.
724     if (MO.getTargetFlags() & PPCII::MO_TLSGDM_FLAG)
725       return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGDM;
726     if (MO.getTargetFlags() & PPCII::MO_TLSGD_FLAG)
727       return MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGD;
728     return MCSymbolRefExpr::VariantKind::VK_None;
729   };
730 
731   // Lower multi-instruction pseudo operations.
732   switch (MI->getOpcode()) {
733   default: break;
734   case TargetOpcode::DBG_VALUE:
735     llvm_unreachable("Should be handled target independently");
736   case TargetOpcode::STACKMAP:
737     return LowerSTACKMAP(SM, *MI);
738   case TargetOpcode::PATCHPOINT:
739     return LowerPATCHPOINT(SM, *MI);
740 
741   case PPC::MoveGOTtoLR: {
742     // Transform %lr = MoveGOTtoLR
743     // Into this: bl _GLOBAL_OFFSET_TABLE_@local-4
744     // _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding
745     // _GLOBAL_OFFSET_TABLE_) has exactly one instruction:
746     //      blrl
747     // This will return the pointer to _GLOBAL_OFFSET_TABLE_@local
748     MCSymbol *GOTSymbol =
749       OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
750     const MCExpr *OffsExpr =
751       MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol,
752                                                       MCSymbolRefExpr::VK_PPC_LOCAL,
753                                                       OutContext),
754                               MCConstantExpr::create(4, OutContext),
755                               OutContext);
756 
757     // Emit the 'bl'.
758     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr));
759     return;
760   }
761   case PPC::MovePCtoLR:
762   case PPC::MovePCtoLR8: {
763     // Transform %lr = MovePCtoLR
764     // Into this, where the label is the PIC base:
765     //     bl L1$pb
766     // L1$pb:
767     MCSymbol *PICBase = MF->getPICBaseSymbol();
768 
769     // Emit the 'bl'.
770     EmitToStreamer(*OutStreamer,
771                    MCInstBuilder(PPC::BL)
772                        // FIXME: We would like an efficient form for this, so we
773                        // don't have to do a lot of extra uniquing.
774                        .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
775 
776     // Emit the label.
777     OutStreamer->emitLabel(PICBase);
778     return;
779   }
780   case PPC::UpdateGBR: {
781     // Transform %rd = UpdateGBR(%rt, %ri)
782     // Into: lwz %rt, .L0$poff - .L0$pb(%ri)
783     //       add %rd, %rt, %ri
784     // or into (if secure plt mode is on):
785     //       addis r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@ha
786     //       addi r30, r30, {.LTOC,_GLOBAL_OFFSET_TABLE} - .L0$pb@l
787     // Get the offset from the GOT Base Register to the GOT
788     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
789     if (Subtarget->isSecurePlt() && isPositionIndependent() ) {
790       unsigned PICR = TmpInst.getOperand(0).getReg();
791       MCSymbol *BaseSymbol = OutContext.getOrCreateSymbol(
792           M->getPICLevel() == PICLevel::SmallPIC ? "_GLOBAL_OFFSET_TABLE_"
793                                                  : ".LTOC");
794       const MCExpr *PB =
795           MCSymbolRefExpr::create(MF->getPICBaseSymbol(), OutContext);
796 
797       const MCExpr *DeltaExpr = MCBinaryExpr::createSub(
798           MCSymbolRefExpr::create(BaseSymbol, OutContext), PB, OutContext);
799 
800       const MCExpr *DeltaHi = PPCMCExpr::createHa(DeltaExpr, OutContext);
801       EmitToStreamer(
802           *OutStreamer,
803           MCInstBuilder(PPC::ADDIS).addReg(PICR).addReg(PICR).addExpr(DeltaHi));
804 
805       const MCExpr *DeltaLo = PPCMCExpr::createLo(DeltaExpr, OutContext);
806       EmitToStreamer(
807           *OutStreamer,
808           MCInstBuilder(PPC::ADDI).addReg(PICR).addReg(PICR).addExpr(DeltaLo));
809       return;
810     } else {
811       MCSymbol *PICOffset =
812         MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol(*MF);
813       TmpInst.setOpcode(PPC::LWZ);
814       const MCExpr *Exp =
815         MCSymbolRefExpr::create(PICOffset, MCSymbolRefExpr::VK_None, OutContext);
816       const MCExpr *PB =
817         MCSymbolRefExpr::create(MF->getPICBaseSymbol(),
818                                 MCSymbolRefExpr::VK_None,
819                                 OutContext);
820       const MCOperand TR = TmpInst.getOperand(1);
821       const MCOperand PICR = TmpInst.getOperand(0);
822 
823       // Step 1: lwz %rt, .L$poff - .L$pb(%ri)
824       TmpInst.getOperand(1) =
825           MCOperand::createExpr(MCBinaryExpr::createSub(Exp, PB, OutContext));
826       TmpInst.getOperand(0) = TR;
827       TmpInst.getOperand(2) = PICR;
828       EmitToStreamer(*OutStreamer, TmpInst);
829 
830       TmpInst.setOpcode(PPC::ADD4);
831       TmpInst.getOperand(0) = PICR;
832       TmpInst.getOperand(1) = TR;
833       TmpInst.getOperand(2) = PICR;
834       EmitToStreamer(*OutStreamer, TmpInst);
835       return;
836     }
837   }
838   case PPC::LWZtoc: {
839     // Transform %rN = LWZtoc @op1, %r2
840     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
841 
842     // Change the opcode to LWZ.
843     TmpInst.setOpcode(PPC::LWZ);
844 
845     const MachineOperand &MO = MI->getOperand(1);
846     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
847            "Invalid operand for LWZtoc.");
848 
849     // Map the operand to its corresponding MCSymbol.
850     const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
851 
852     // Create a reference to the GOT entry for the symbol. The GOT entry will be
853     // synthesized later.
854     if (PL == PICLevel::SmallPIC && !IsAIX) {
855       const MCExpr *Exp =
856         MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_GOT,
857                                 OutContext);
858       TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
859       EmitToStreamer(*OutStreamer, TmpInst);
860       return;
861     }
862 
863     MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
864 
865     // Otherwise, use the TOC. 'TOCEntry' is a label used to reference the
866     // storage allocated in the TOC which contains the address of
867     // 'MOSymbol'. Said TOC entry will be synthesized later.
868     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK);
869     const MCExpr *Exp =
870         MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_None, OutContext);
871 
872     // AIX uses the label directly as the lwz displacement operand for
873     // references into the toc section. The displacement value will be generated
874     // relative to the toc-base.
875     if (IsAIX) {
876       assert(
877           TM.getCodeModel() == CodeModel::Small &&
878           "This pseudo should only be selected for 32-bit small code model.");
879       Exp = getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp, VK);
880       TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
881 
882       // Print MO for better readability
883       if (isVerbose())
884         OutStreamer->GetCommentOS() << MO << '\n';
885       EmitToStreamer(*OutStreamer, TmpInst);
886       return;
887     }
888 
889     // Create an explicit subtract expression between the local symbol and
890     // '.LTOC' to manifest the toc-relative offset.
891     const MCExpr *PB = MCSymbolRefExpr::create(
892         OutContext.getOrCreateSymbol(Twine(".LTOC")), OutContext);
893     Exp = MCBinaryExpr::createSub(Exp, PB, OutContext);
894     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
895     EmitToStreamer(*OutStreamer, TmpInst);
896     return;
897   }
898   case PPC::ADDItoc:
899   case PPC::ADDItoc8: {
900     assert(IsAIX && TM.getCodeModel() == CodeModel::Small &&
901            "PseudoOp only valid for small code model AIX");
902 
903     // Transform %rN = ADDItoc/8 @op1, %r2.
904     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
905 
906     // Change the opcode to load address.
907     TmpInst.setOpcode((!IsPPC64) ? (PPC::LA) : (PPC::LA8));
908 
909     const MachineOperand &MO = MI->getOperand(1);
910     assert(MO.isGlobal() && "Invalid operand for ADDItoc[8].");
911 
912     // Map the operand to its corresponding MCSymbol.
913     const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
914 
915     const MCExpr *Exp =
916         MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_None, OutContext);
917 
918     TmpInst.getOperand(1) = TmpInst.getOperand(2);
919     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
920     EmitToStreamer(*OutStreamer, TmpInst);
921     return;
922   }
923   case PPC::LDtocJTI:
924   case PPC::LDtocCPT:
925   case PPC::LDtocBA:
926   case PPC::LDtoc: {
927     // Transform %x3 = LDtoc @min1, %x2
928     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
929 
930     // Change the opcode to LD.
931     TmpInst.setOpcode(PPC::LD);
932 
933     const MachineOperand &MO = MI->getOperand(1);
934     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
935            "Invalid operand!");
936 
937     // Map the operand to its corresponding MCSymbol.
938     const MCSymbol *const MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
939 
940     MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
941 
942     // Map the machine operand to its corresponding MCSymbol, then map the
943     // global address operand to be a reference to the TOC entry we will
944     // synthesize later.
945     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK);
946 
947     MCSymbolRefExpr::VariantKind VKExpr =
948         IsAIX ? MCSymbolRefExpr::VK_None : MCSymbolRefExpr::VK_PPC_TOC;
949     const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry, VKExpr, OutContext);
950     TmpInst.getOperand(1) = MCOperand::createExpr(
951         IsAIX ? getTOCEntryLoadingExprForXCOFF(MOSymbol, Exp, VK) : Exp);
952 
953     // Print MO for better readability
954     if (isVerbose() && IsAIX)
955       OutStreamer->GetCommentOS() << MO << '\n';
956     EmitToStreamer(*OutStreamer, TmpInst);
957     return;
958   }
959   case PPC::ADDIStocHA: {
960     assert((IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large) &&
961            "This pseudo should only be selected for 32-bit large code model on"
962            " AIX.");
963 
964     // Transform %rd = ADDIStocHA %rA, @sym(%r2)
965     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
966 
967     // Change the opcode to ADDIS.
968     TmpInst.setOpcode(PPC::ADDIS);
969 
970     const MachineOperand &MO = MI->getOperand(2);
971     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
972            "Invalid operand for ADDIStocHA.");
973 
974     // Map the machine operand to its corresponding MCSymbol.
975     MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
976 
977     MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
978 
979     // Always use TOC on AIX. Map the global address operand to be a reference
980     // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
981     // reference the storage allocated in the TOC which contains the address of
982     // 'MOSymbol'.
983     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK);
984     const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
985                                                 MCSymbolRefExpr::VK_PPC_U,
986                                                 OutContext);
987     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
988     EmitToStreamer(*OutStreamer, TmpInst);
989     return;
990   }
991   case PPC::LWZtocL: {
992     assert(IsAIX && !IsPPC64 && TM.getCodeModel() == CodeModel::Large &&
993            "This pseudo should only be selected for 32-bit large code model on"
994            " AIX.");
995 
996     // Transform %rd = LWZtocL @sym, %rs.
997     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
998 
999     // Change the opcode to lwz.
1000     TmpInst.setOpcode(PPC::LWZ);
1001 
1002     const MachineOperand &MO = MI->getOperand(1);
1003     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
1004            "Invalid operand for LWZtocL.");
1005 
1006     // Map the machine operand to its corresponding MCSymbol.
1007     MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1008 
1009     MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1010 
1011     // Always use TOC on AIX. Map the global address operand to be a reference
1012     // to the TOC entry we will synthesize later. 'TOCEntry' is a label used to
1013     // reference the storage allocated in the TOC which contains the address of
1014     // 'MOSymbol'.
1015     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol, VK);
1016     const MCExpr *Exp = MCSymbolRefExpr::create(TOCEntry,
1017                                                 MCSymbolRefExpr::VK_PPC_L,
1018                                                 OutContext);
1019     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1020     EmitToStreamer(*OutStreamer, TmpInst);
1021     return;
1022   }
1023   case PPC::ADDIStocHA8: {
1024     // Transform %xd = ADDIStocHA8 %x2, @sym
1025     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1026 
1027     // Change the opcode to ADDIS8. If the global address is the address of
1028     // an external symbol, is a jump table address, is a block address, or is a
1029     // constant pool index with large code model enabled, then generate a TOC
1030     // entry and reference that. Otherwise, reference the symbol directly.
1031     TmpInst.setOpcode(PPC::ADDIS8);
1032 
1033     const MachineOperand &MO = MI->getOperand(2);
1034     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress()) &&
1035            "Invalid operand for ADDIStocHA8!");
1036 
1037     const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1038 
1039     MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1040 
1041     const bool GlobalToc =
1042         MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal());
1043     if (GlobalToc || MO.isJTI() || MO.isBlockAddress() ||
1044         (MO.isCPI() && TM.getCodeModel() == CodeModel::Large))
1045       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol, VK);
1046 
1047     VK = IsAIX ? MCSymbolRefExpr::VK_PPC_U : MCSymbolRefExpr::VK_PPC_TOC_HA;
1048 
1049     const MCExpr *Exp =
1050         MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
1051 
1052     if (!MO.isJTI() && MO.getOffset())
1053       Exp = MCBinaryExpr::createAdd(Exp,
1054                                     MCConstantExpr::create(MO.getOffset(),
1055                                                            OutContext),
1056                                     OutContext);
1057 
1058     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
1059     EmitToStreamer(*OutStreamer, TmpInst);
1060     return;
1061   }
1062   case PPC::LDtocL: {
1063     // Transform %xd = LDtocL @sym, %xs
1064     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1065 
1066     // Change the opcode to LD. If the global address is the address of
1067     // an external symbol, is a jump table address, is a block address, or is
1068     // a constant pool index with large code model enabled, then generate a
1069     // TOC entry and reference that. Otherwise, reference the symbol directly.
1070     TmpInst.setOpcode(PPC::LD);
1071 
1072     const MachineOperand &MO = MI->getOperand(1);
1073     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() ||
1074             MO.isBlockAddress()) &&
1075            "Invalid operand for LDtocL!");
1076 
1077     LLVM_DEBUG(assert(
1078         (!MO.isGlobal() || Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
1079         "LDtocL used on symbol that could be accessed directly is "
1080         "invalid. Must match ADDIStocHA8."));
1081 
1082     const MCSymbol *MOSymbol = getMCSymbolForTOCPseudoMO(MO, *this);
1083 
1084     MCSymbolRefExpr::VariantKind VK = GetVKForMO(MO);
1085 
1086     if (!MO.isCPI() || TM.getCodeModel() == CodeModel::Large)
1087       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol, VK);
1088 
1089     VK = IsAIX ? MCSymbolRefExpr::VK_PPC_L : MCSymbolRefExpr::VK_PPC_TOC_LO;
1090     const MCExpr *Exp =
1091         MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
1092     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1093     EmitToStreamer(*OutStreamer, TmpInst);
1094     return;
1095   }
1096   case PPC::ADDItocL: {
1097     // Transform %xd = ADDItocL %xs, @sym
1098     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1099 
1100     // Change the opcode to ADDI8. If the global address is external, then
1101     // generate a TOC entry and reference that. Otherwise, reference the
1102     // symbol directly.
1103     TmpInst.setOpcode(PPC::ADDI8);
1104 
1105     const MachineOperand &MO = MI->getOperand(2);
1106     assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL.");
1107 
1108     LLVM_DEBUG(assert(
1109         !(MO.isGlobal() && Subtarget->isGVIndirectSymbol(MO.getGlobal())) &&
1110         "Interposable definitions must use indirect access."));
1111 
1112     const MCExpr *Exp =
1113         MCSymbolRefExpr::create(getMCSymbolForTOCPseudoMO(MO, *this),
1114                                 MCSymbolRefExpr::VK_PPC_TOC_LO, OutContext);
1115     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
1116     EmitToStreamer(*OutStreamer, TmpInst);
1117     return;
1118   }
1119   case PPC::ADDISgotTprelHA: {
1120     // Transform: %xd = ADDISgotTprelHA %x2, @sym
1121     // Into:      %xd = ADDIS8 %x2, sym@got@tlsgd@ha
1122     assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1123     const MachineOperand &MO = MI->getOperand(2);
1124     const GlobalValue *GValue = MO.getGlobal();
1125     MCSymbol *MOSymbol = getSymbol(GValue);
1126     const MCExpr *SymGotTprel =
1127         MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA,
1128                                 OutContext);
1129     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1130                                  .addReg(MI->getOperand(0).getReg())
1131                                  .addReg(MI->getOperand(1).getReg())
1132                                  .addExpr(SymGotTprel));
1133     return;
1134   }
1135   case PPC::LDgotTprelL:
1136   case PPC::LDgotTprelL32: {
1137     // Transform %xd = LDgotTprelL @sym, %xs
1138     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1139 
1140     // Change the opcode to LD.
1141     TmpInst.setOpcode(IsPPC64 ? PPC::LD : PPC::LWZ);
1142     const MachineOperand &MO = MI->getOperand(1);
1143     const GlobalValue *GValue = MO.getGlobal();
1144     MCSymbol *MOSymbol = getSymbol(GValue);
1145     const MCExpr *Exp = MCSymbolRefExpr::create(
1146         MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO
1147                           : MCSymbolRefExpr::VK_PPC_GOT_TPREL,
1148         OutContext);
1149     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
1150     EmitToStreamer(*OutStreamer, TmpInst);
1151     return;
1152   }
1153 
1154   case PPC::PPC32PICGOT: {
1155     MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
1156     MCSymbol *GOTRef = OutContext.createTempSymbol();
1157     MCSymbol *NextInstr = OutContext.createTempSymbol();
1158 
1159     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL)
1160       // FIXME: We would like an efficient form for this, so we don't have to do
1161       // a lot of extra uniquing.
1162       .addExpr(MCSymbolRefExpr::create(NextInstr, OutContext)));
1163     const MCExpr *OffsExpr =
1164       MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, OutContext),
1165                                 MCSymbolRefExpr::create(GOTRef, OutContext),
1166         OutContext);
1167     OutStreamer->emitLabel(GOTRef);
1168     OutStreamer->emitValue(OffsExpr, 4);
1169     OutStreamer->emitLabel(NextInstr);
1170     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR)
1171                                  .addReg(MI->getOperand(0).getReg()));
1172     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ)
1173                                  .addReg(MI->getOperand(1).getReg())
1174                                  .addImm(0)
1175                                  .addReg(MI->getOperand(0).getReg()));
1176     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD4)
1177                                  .addReg(MI->getOperand(0).getReg())
1178                                  .addReg(MI->getOperand(1).getReg())
1179                                  .addReg(MI->getOperand(0).getReg()));
1180     return;
1181   }
1182   case PPC::PPC32GOT: {
1183     MCSymbol *GOTSymbol =
1184         OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
1185     const MCExpr *SymGotTlsL = MCSymbolRefExpr::create(
1186         GOTSymbol, MCSymbolRefExpr::VK_PPC_LO, OutContext);
1187     const MCExpr *SymGotTlsHA = MCSymbolRefExpr::create(
1188         GOTSymbol, MCSymbolRefExpr::VK_PPC_HA, OutContext);
1189     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI)
1190                                  .addReg(MI->getOperand(0).getReg())
1191                                  .addExpr(SymGotTlsL));
1192     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1193                                  .addReg(MI->getOperand(0).getReg())
1194                                  .addReg(MI->getOperand(0).getReg())
1195                                  .addExpr(SymGotTlsHA));
1196     return;
1197   }
1198   case PPC::ADDIStlsgdHA: {
1199     // Transform: %xd = ADDIStlsgdHA %x2, @sym
1200     // Into:      %xd = ADDIS8 %x2, sym@got@tlsgd@ha
1201     assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1202     const MachineOperand &MO = MI->getOperand(2);
1203     const GlobalValue *GValue = MO.getGlobal();
1204     MCSymbol *MOSymbol = getSymbol(GValue);
1205     const MCExpr *SymGotTlsGD =
1206       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA,
1207                               OutContext);
1208     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1209                                  .addReg(MI->getOperand(0).getReg())
1210                                  .addReg(MI->getOperand(1).getReg())
1211                                  .addExpr(SymGotTlsGD));
1212     return;
1213   }
1214   case PPC::ADDItlsgdL:
1215     // Transform: %xd = ADDItlsgdL %xs, @sym
1216     // Into:      %xd = ADDI8 %xs, sym@got@tlsgd@l
1217   case PPC::ADDItlsgdL32: {
1218     // Transform: %rd = ADDItlsgdL32 %rs, @sym
1219     // Into:      %rd = ADDI %rs, sym@got@tlsgd
1220     const MachineOperand &MO = MI->getOperand(2);
1221     const GlobalValue *GValue = MO.getGlobal();
1222     MCSymbol *MOSymbol = getSymbol(GValue);
1223     const MCExpr *SymGotTlsGD = MCSymbolRefExpr::create(
1224         MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO
1225                           : MCSymbolRefExpr::VK_PPC_GOT_TLSGD,
1226         OutContext);
1227     EmitToStreamer(*OutStreamer,
1228                    MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1229                    .addReg(MI->getOperand(0).getReg())
1230                    .addReg(MI->getOperand(1).getReg())
1231                    .addExpr(SymGotTlsGD));
1232     return;
1233   }
1234   case PPC::GETtlsADDR:
1235     // Transform: %x3 = GETtlsADDR %x3, @sym
1236     // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsgd)
1237   case PPC::GETtlsADDRPCREL:
1238   case PPC::GETtlsADDR32AIX:
1239   case PPC::GETtlsADDR64AIX:
1240     // Transform: %r3 = GETtlsADDRNNAIX %r3, %r4 (for NN == 32/64).
1241     // Into: BLA .__tls_get_addr()
1242     // Unlike on Linux, there is no symbol or relocation needed for this call.
1243   case PPC::GETtlsADDR32: {
1244     // Transform: %r3 = GETtlsADDR32 %r3, @sym
1245     // Into: BL_TLS __tls_get_addr(sym at tlsgd)@PLT
1246     EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSGD);
1247     return;
1248   }
1249   case PPC::ADDIStlsldHA: {
1250     // Transform: %xd = ADDIStlsldHA %x2, @sym
1251     // Into:      %xd = ADDIS8 %x2, sym@got@tlsld@ha
1252     assert(IsPPC64 && "Not supported for 32-bit PowerPC");
1253     const MachineOperand &MO = MI->getOperand(2);
1254     const GlobalValue *GValue = MO.getGlobal();
1255     MCSymbol *MOSymbol = getSymbol(GValue);
1256     const MCExpr *SymGotTlsLD =
1257       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA,
1258                               OutContext);
1259     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
1260                                  .addReg(MI->getOperand(0).getReg())
1261                                  .addReg(MI->getOperand(1).getReg())
1262                                  .addExpr(SymGotTlsLD));
1263     return;
1264   }
1265   case PPC::ADDItlsldL:
1266     // Transform: %xd = ADDItlsldL %xs, @sym
1267     // Into:      %xd = ADDI8 %xs, sym@got@tlsld@l
1268   case PPC::ADDItlsldL32: {
1269     // Transform: %rd = ADDItlsldL32 %rs, @sym
1270     // Into:      %rd = ADDI %rs, sym@got@tlsld
1271     const MachineOperand &MO = MI->getOperand(2);
1272     const GlobalValue *GValue = MO.getGlobal();
1273     MCSymbol *MOSymbol = getSymbol(GValue);
1274     const MCExpr *SymGotTlsLD = MCSymbolRefExpr::create(
1275         MOSymbol, IsPPC64 ? MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO
1276                           : MCSymbolRefExpr::VK_PPC_GOT_TLSLD,
1277         OutContext);
1278     EmitToStreamer(*OutStreamer,
1279                    MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1280                        .addReg(MI->getOperand(0).getReg())
1281                        .addReg(MI->getOperand(1).getReg())
1282                        .addExpr(SymGotTlsLD));
1283     return;
1284   }
1285   case PPC::GETtlsldADDR:
1286     // Transform: %x3 = GETtlsldADDR %x3, @sym
1287     // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsld)
1288   case PPC::GETtlsldADDRPCREL:
1289   case PPC::GETtlsldADDR32: {
1290     // Transform: %r3 = GETtlsldADDR32 %r3, @sym
1291     // Into: BL_TLS __tls_get_addr(sym at tlsld)@PLT
1292     EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSLD);
1293     return;
1294   }
1295   case PPC::ADDISdtprelHA:
1296     // Transform: %xd = ADDISdtprelHA %xs, @sym
1297     // Into:      %xd = ADDIS8 %xs, sym@dtprel@ha
1298   case PPC::ADDISdtprelHA32: {
1299     // Transform: %rd = ADDISdtprelHA32 %rs, @sym
1300     // Into:      %rd = ADDIS %rs, sym@dtprel@ha
1301     const MachineOperand &MO = MI->getOperand(2);
1302     const GlobalValue *GValue = MO.getGlobal();
1303     MCSymbol *MOSymbol = getSymbol(GValue);
1304     const MCExpr *SymDtprel =
1305       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_HA,
1306                               OutContext);
1307     EmitToStreamer(
1308         *OutStreamer,
1309         MCInstBuilder(IsPPC64 ? PPC::ADDIS8 : PPC::ADDIS)
1310             .addReg(MI->getOperand(0).getReg())
1311             .addReg(MI->getOperand(1).getReg())
1312             .addExpr(SymDtprel));
1313     return;
1314   }
1315   case PPC::PADDIdtprel: {
1316     // Transform: %rd = PADDIdtprel %rs, @sym
1317     // Into:      %rd = PADDI8 %rs, sym@dtprel
1318     const MachineOperand &MO = MI->getOperand(2);
1319     const GlobalValue *GValue = MO.getGlobal();
1320     MCSymbol *MOSymbol = getSymbol(GValue);
1321     const MCExpr *SymDtprel = MCSymbolRefExpr::create(
1322         MOSymbol, MCSymbolRefExpr::VK_DTPREL, OutContext);
1323     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::PADDI8)
1324                                      .addReg(MI->getOperand(0).getReg())
1325                                      .addReg(MI->getOperand(1).getReg())
1326                                      .addExpr(SymDtprel));
1327     return;
1328   }
1329 
1330   case PPC::ADDIdtprelL:
1331     // Transform: %xd = ADDIdtprelL %xs, @sym
1332     // Into:      %xd = ADDI8 %xs, sym@dtprel@l
1333   case PPC::ADDIdtprelL32: {
1334     // Transform: %rd = ADDIdtprelL32 %rs, @sym
1335     // Into:      %rd = ADDI %rs, sym@dtprel@l
1336     const MachineOperand &MO = MI->getOperand(2);
1337     const GlobalValue *GValue = MO.getGlobal();
1338     MCSymbol *MOSymbol = getSymbol(GValue);
1339     const MCExpr *SymDtprel =
1340       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_LO,
1341                               OutContext);
1342     EmitToStreamer(*OutStreamer,
1343                    MCInstBuilder(IsPPC64 ? PPC::ADDI8 : PPC::ADDI)
1344                        .addReg(MI->getOperand(0).getReg())
1345                        .addReg(MI->getOperand(1).getReg())
1346                        .addExpr(SymDtprel));
1347     return;
1348   }
1349   case PPC::MFOCRF:
1350   case PPC::MFOCRF8:
1351     if (!Subtarget->hasMFOCRF()) {
1352       // Transform: %r3 = MFOCRF %cr7
1353       // Into:      %r3 = MFCR   ;; cr7
1354       unsigned NewOpcode =
1355         MI->getOpcode() == PPC::MFOCRF ? PPC::MFCR : PPC::MFCR8;
1356       OutStreamer->AddComment(PPCInstPrinter::
1357                               getRegisterName(MI->getOperand(1).getReg()));
1358       EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1359                                   .addReg(MI->getOperand(0).getReg()));
1360       return;
1361     }
1362     break;
1363   case PPC::MTOCRF:
1364   case PPC::MTOCRF8:
1365     if (!Subtarget->hasMFOCRF()) {
1366       // Transform: %cr7 = MTOCRF %r3
1367       // Into:      MTCRF mask, %r3 ;; cr7
1368       unsigned NewOpcode =
1369         MI->getOpcode() == PPC::MTOCRF ? PPC::MTCRF : PPC::MTCRF8;
1370       unsigned Mask = 0x80 >> OutContext.getRegisterInfo()
1371                               ->getEncodingValue(MI->getOperand(0).getReg());
1372       OutStreamer->AddComment(PPCInstPrinter::
1373                               getRegisterName(MI->getOperand(0).getReg()));
1374       EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1375                                      .addImm(Mask)
1376                                      .addReg(MI->getOperand(1).getReg()));
1377       return;
1378     }
1379     break;
1380   case PPC::LD:
1381   case PPC::STD:
1382   case PPC::LWA_32:
1383   case PPC::LWA: {
1384     // Verify alignment is legal, so we don't create relocations
1385     // that can't be supported.
1386     unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1;
1387     const MachineOperand &MO = MI->getOperand(OpNum);
1388     if (MO.isGlobal()) {
1389       const DataLayout &DL = MO.getGlobal()->getParent()->getDataLayout();
1390       if (MO.getGlobal()->getPointerAlignment(DL) < 4)
1391         llvm_unreachable("Global must be word-aligned for LD, STD, LWA!");
1392     }
1393     // Now process the instruction normally.
1394     break;
1395   }
1396   case PPC::PseudoEIEIO: {
1397     EmitToStreamer(
1398         *OutStreamer,
1399         MCInstBuilder(PPC::ORI).addReg(PPC::X2).addReg(PPC::X2).addImm(0));
1400     EmitToStreamer(
1401         *OutStreamer,
1402         MCInstBuilder(PPC::ORI).addReg(PPC::X2).addReg(PPC::X2).addImm(0));
1403     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::EnforceIEIO));
1404     return;
1405   }
1406   }
1407 
1408   LowerPPCMachineInstrToMCInst(MI, TmpInst, *this);
1409   EmitToStreamer(*OutStreamer, TmpInst);
1410 }
1411 
1412 void PPCLinuxAsmPrinter::emitGNUAttributes(Module &M) {
1413   // Emit float ABI into GNU attribute
1414   Metadata *MD = M.getModuleFlag("float-abi");
1415   MDString *FloatABI = dyn_cast_or_null<MDString>(MD);
1416   if (!FloatABI)
1417     return;
1418   StringRef flt = FloatABI->getString();
1419   // TODO: Support emitting soft-fp and hard double/single attributes.
1420   if (flt == "doubledouble")
1421     OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP,
1422                                   Val_GNU_Power_ABI_HardFloat_DP |
1423                                       Val_GNU_Power_ABI_LDBL_IBM128);
1424   else if (flt == "ieeequad")
1425     OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP,
1426                                   Val_GNU_Power_ABI_HardFloat_DP |
1427                                       Val_GNU_Power_ABI_LDBL_IEEE128);
1428   else if (flt == "ieeedouble")
1429     OutStreamer->emitGNUAttribute(Tag_GNU_Power_ABI_FP,
1430                                   Val_GNU_Power_ABI_HardFloat_DP |
1431                                       Val_GNU_Power_ABI_LDBL_64);
1432 }
1433 
1434 void PPCLinuxAsmPrinter::emitInstruction(const MachineInstr *MI) {
1435   if (!Subtarget->isPPC64())
1436     return PPCAsmPrinter::emitInstruction(MI);
1437 
1438   switch (MI->getOpcode()) {
1439   default:
1440     return PPCAsmPrinter::emitInstruction(MI);
1441   case TargetOpcode::PATCHABLE_FUNCTION_ENTER: {
1442     // .begin:
1443     //   b .end # lis 0, FuncId[16..32]
1444     //   nop    # li  0, FuncId[0..15]
1445     //   std 0, -8(1)
1446     //   mflr 0
1447     //   bl __xray_FunctionEntry
1448     //   mtlr 0
1449     // .end:
1450     //
1451     // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1452     // of instructions change.
1453     MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1454     MCSymbol *EndOfSled = OutContext.createTempSymbol();
1455     OutStreamer->emitLabel(BeginOfSled);
1456     EmitToStreamer(*OutStreamer,
1457                    MCInstBuilder(PPC::B).addExpr(
1458                        MCSymbolRefExpr::create(EndOfSled, OutContext)));
1459     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1460     EmitToStreamer(
1461         *OutStreamer,
1462         MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1463     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1464     EmitToStreamer(*OutStreamer,
1465                    MCInstBuilder(PPC::BL8_NOP)
1466                        .addExpr(MCSymbolRefExpr::create(
1467                            OutContext.getOrCreateSymbol("__xray_FunctionEntry"),
1468                            OutContext)));
1469     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1470     OutStreamer->emitLabel(EndOfSled);
1471     recordSled(BeginOfSled, *MI, SledKind::FUNCTION_ENTER, 2);
1472     break;
1473   }
1474   case TargetOpcode::PATCHABLE_RET: {
1475     unsigned RetOpcode = MI->getOperand(0).getImm();
1476     MCInst RetInst;
1477     RetInst.setOpcode(RetOpcode);
1478     for (const auto &MO : llvm::drop_begin(MI->operands())) {
1479       MCOperand MCOp;
1480       if (LowerPPCMachineOperandToMCOperand(MO, MCOp, *this))
1481         RetInst.addOperand(MCOp);
1482     }
1483 
1484     bool IsConditional;
1485     if (RetOpcode == PPC::BCCLR) {
1486       IsConditional = true;
1487     } else if (RetOpcode == PPC::TCRETURNdi8 || RetOpcode == PPC::TCRETURNri8 ||
1488                RetOpcode == PPC::TCRETURNai8) {
1489       break;
1490     } else if (RetOpcode == PPC::BLR8 || RetOpcode == PPC::TAILB8) {
1491       IsConditional = false;
1492     } else {
1493       EmitToStreamer(*OutStreamer, RetInst);
1494       break;
1495     }
1496 
1497     MCSymbol *FallthroughLabel;
1498     if (IsConditional) {
1499       // Before:
1500       //   bgtlr cr0
1501       //
1502       // After:
1503       //   ble cr0, .end
1504       // .p2align 3
1505       // .begin:
1506       //   blr    # lis 0, FuncId[16..32]
1507       //   nop    # li  0, FuncId[0..15]
1508       //   std 0, -8(1)
1509       //   mflr 0
1510       //   bl __xray_FunctionExit
1511       //   mtlr 0
1512       //   blr
1513       // .end:
1514       //
1515       // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1516       // of instructions change.
1517       FallthroughLabel = OutContext.createTempSymbol();
1518       EmitToStreamer(
1519           *OutStreamer,
1520           MCInstBuilder(PPC::BCC)
1521               .addImm(PPC::InvertPredicate(
1522                   static_cast<PPC::Predicate>(MI->getOperand(1).getImm())))
1523               .addReg(MI->getOperand(2).getReg())
1524               .addExpr(MCSymbolRefExpr::create(FallthroughLabel, OutContext)));
1525       RetInst = MCInst();
1526       RetInst.setOpcode(PPC::BLR8);
1527     }
1528     // .p2align 3
1529     // .begin:
1530     //   b(lr)? # lis 0, FuncId[16..32]
1531     //   nop    # li  0, FuncId[0..15]
1532     //   std 0, -8(1)
1533     //   mflr 0
1534     //   bl __xray_FunctionExit
1535     //   mtlr 0
1536     //   b(lr)?
1537     //
1538     // Update compiler-rt/lib/xray/xray_powerpc64.cc accordingly when number
1539     // of instructions change.
1540     OutStreamer->emitCodeAlignment(8, &getSubtargetInfo());
1541     MCSymbol *BeginOfSled = OutContext.createTempSymbol();
1542     OutStreamer->emitLabel(BeginOfSled);
1543     EmitToStreamer(*OutStreamer, RetInst);
1544     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
1545     EmitToStreamer(
1546         *OutStreamer,
1547         MCInstBuilder(PPC::STD).addReg(PPC::X0).addImm(-8).addReg(PPC::X1));
1548     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR8).addReg(PPC::X0));
1549     EmitToStreamer(*OutStreamer,
1550                    MCInstBuilder(PPC::BL8_NOP)
1551                        .addExpr(MCSymbolRefExpr::create(
1552                            OutContext.getOrCreateSymbol("__xray_FunctionExit"),
1553                            OutContext)));
1554     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTLR8).addReg(PPC::X0));
1555     EmitToStreamer(*OutStreamer, RetInst);
1556     if (IsConditional)
1557       OutStreamer->emitLabel(FallthroughLabel);
1558     recordSled(BeginOfSled, *MI, SledKind::FUNCTION_EXIT, 2);
1559     break;
1560   }
1561   case TargetOpcode::PATCHABLE_FUNCTION_EXIT:
1562     llvm_unreachable("PATCHABLE_FUNCTION_EXIT should never be emitted");
1563   case TargetOpcode::PATCHABLE_TAIL_CALL:
1564     // TODO: Define a trampoline `__xray_FunctionTailExit` and differentiate a
1565     // normal function exit from a tail exit.
1566     llvm_unreachable("Tail call is handled in the normal case. See comments "
1567                      "around this assert.");
1568   }
1569 }
1570 
1571 void PPCLinuxAsmPrinter::emitStartOfAsmFile(Module &M) {
1572   if (static_cast<const PPCTargetMachine &>(TM).isELFv2ABI()) {
1573     PPCTargetStreamer *TS =
1574       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1575 
1576     if (TS)
1577       TS->emitAbiVersion(2);
1578   }
1579 
1580   if (static_cast<const PPCTargetMachine &>(TM).isPPC64() ||
1581       !isPositionIndependent())
1582     return AsmPrinter::emitStartOfAsmFile(M);
1583 
1584   if (M.getPICLevel() == PICLevel::SmallPIC)
1585     return AsmPrinter::emitStartOfAsmFile(M);
1586 
1587   OutStreamer->SwitchSection(OutContext.getELFSection(
1588       ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC));
1589 
1590   MCSymbol *TOCSym = OutContext.getOrCreateSymbol(Twine(".LTOC"));
1591   MCSymbol *CurrentPos = OutContext.createTempSymbol();
1592 
1593   OutStreamer->emitLabel(CurrentPos);
1594 
1595   // The GOT pointer points to the middle of the GOT, in order to reference the
1596   // entire 64kB range.  0x8000 is the midpoint.
1597   const MCExpr *tocExpr =
1598     MCBinaryExpr::createAdd(MCSymbolRefExpr::create(CurrentPos, OutContext),
1599                             MCConstantExpr::create(0x8000, OutContext),
1600                             OutContext);
1601 
1602   OutStreamer->emitAssignment(TOCSym, tocExpr);
1603 
1604   OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
1605 }
1606 
1607 void PPCLinuxAsmPrinter::emitFunctionEntryLabel() {
1608   // linux/ppc32 - Normal entry label.
1609   if (!Subtarget->isPPC64() &&
1610       (!isPositionIndependent() ||
1611        MF->getFunction().getParent()->getPICLevel() == PICLevel::SmallPIC))
1612     return AsmPrinter::emitFunctionEntryLabel();
1613 
1614   if (!Subtarget->isPPC64()) {
1615     const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1616     if (PPCFI->usesPICBase() && !Subtarget->isSecurePlt()) {
1617       MCSymbol *RelocSymbol = PPCFI->getPICOffsetSymbol(*MF);
1618       MCSymbol *PICBase = MF->getPICBaseSymbol();
1619       OutStreamer->emitLabel(RelocSymbol);
1620 
1621       const MCExpr *OffsExpr =
1622         MCBinaryExpr::createSub(
1623           MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")),
1624                                                                OutContext),
1625                                   MCSymbolRefExpr::create(PICBase, OutContext),
1626           OutContext);
1627       OutStreamer->emitValue(OffsExpr, 4);
1628       OutStreamer->emitLabel(CurrentFnSym);
1629       return;
1630     } else
1631       return AsmPrinter::emitFunctionEntryLabel();
1632   }
1633 
1634   // ELFv2 ABI - Normal entry label.
1635   if (Subtarget->isELFv2ABI()) {
1636     // In the Large code model, we allow arbitrary displacements between
1637     // the text section and its associated TOC section.  We place the
1638     // full 8-byte offset to the TOC in memory immediately preceding
1639     // the function global entry point.
1640     if (TM.getCodeModel() == CodeModel::Large
1641         && !MF->getRegInfo().use_empty(PPC::X2)) {
1642       const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1643 
1644       MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1645       MCSymbol *GlobalEPSymbol = PPCFI->getGlobalEPSymbol(*MF);
1646       const MCExpr *TOCDeltaExpr =
1647         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1648                                 MCSymbolRefExpr::create(GlobalEPSymbol,
1649                                                         OutContext),
1650                                 OutContext);
1651 
1652       OutStreamer->emitLabel(PPCFI->getTOCOffsetSymbol(*MF));
1653       OutStreamer->emitValue(TOCDeltaExpr, 8);
1654     }
1655     return AsmPrinter::emitFunctionEntryLabel();
1656   }
1657 
1658   // Emit an official procedure descriptor.
1659   MCSectionSubPair Current = OutStreamer->getCurrentSection();
1660   MCSectionELF *Section = OutStreamer->getContext().getELFSection(
1661       ".opd", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1662   OutStreamer->SwitchSection(Section);
1663   OutStreamer->emitLabel(CurrentFnSym);
1664   OutStreamer->emitValueToAlignment(8);
1665   MCSymbol *Symbol1 = CurrentFnSymForSize;
1666   // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function
1667   // entry point.
1668   OutStreamer->emitValue(MCSymbolRefExpr::create(Symbol1, OutContext),
1669                          8 /*size*/);
1670   MCSymbol *Symbol2 = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1671   // Generates a R_PPC64_TOC relocation for TOC base insertion.
1672   OutStreamer->emitValue(
1673     MCSymbolRefExpr::create(Symbol2, MCSymbolRefExpr::VK_PPC_TOCBASE, OutContext),
1674     8/*size*/);
1675   // Emit a null environment pointer.
1676   OutStreamer->emitIntValue(0, 8 /* size */);
1677   OutStreamer->SwitchSection(Current.first, Current.second);
1678 }
1679 
1680 void PPCLinuxAsmPrinter::emitEndOfAsmFile(Module &M) {
1681   const DataLayout &DL = getDataLayout();
1682 
1683   bool isPPC64 = DL.getPointerSizeInBits() == 64;
1684 
1685   PPCTargetStreamer *TS =
1686       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1687 
1688   emitGNUAttributes(M);
1689 
1690   if (!TOC.empty()) {
1691     const char *Name = isPPC64 ? ".toc" : ".got2";
1692     MCSectionELF *Section = OutContext.getELFSection(
1693         Name, ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1694     OutStreamer->SwitchSection(Section);
1695     if (!isPPC64)
1696       OutStreamer->emitValueToAlignment(4);
1697 
1698     for (const auto &TOCMapPair : TOC) {
1699       const MCSymbol *const TOCEntryTarget = TOCMapPair.first.first;
1700       MCSymbol *const TOCEntryLabel = TOCMapPair.second;
1701 
1702       OutStreamer->emitLabel(TOCEntryLabel);
1703       if (isPPC64 && TS != nullptr)
1704         TS->emitTCEntry(*TOCEntryTarget, TOCMapPair.first.second);
1705       else
1706         OutStreamer->emitSymbolValue(TOCEntryTarget, 4);
1707     }
1708   }
1709 
1710   PPCAsmPrinter::emitEndOfAsmFile(M);
1711 }
1712 
1713 /// EmitFunctionBodyStart - Emit a global entry point prefix for ELFv2.
1714 void PPCLinuxAsmPrinter::emitFunctionBodyStart() {
1715   // In the ELFv2 ABI, in functions that use the TOC register, we need to
1716   // provide two entry points.  The ABI guarantees that when calling the
1717   // local entry point, r2 is set up by the caller to contain the TOC base
1718   // for this function, and when calling the global entry point, r12 is set
1719   // up by the caller to hold the address of the global entry point.  We
1720   // thus emit a prefix sequence along the following lines:
1721   //
1722   // func:
1723   // .Lfunc_gepNN:
1724   //         # global entry point
1725   //         addis r2,r12,(.TOC.-.Lfunc_gepNN)@ha
1726   //         addi  r2,r2,(.TOC.-.Lfunc_gepNN)@l
1727   // .Lfunc_lepNN:
1728   //         .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1729   //         # local entry point, followed by function body
1730   //
1731   // For the Large code model, we create
1732   //
1733   // .Lfunc_tocNN:
1734   //         .quad .TOC.-.Lfunc_gepNN      # done by EmitFunctionEntryLabel
1735   // func:
1736   // .Lfunc_gepNN:
1737   //         # global entry point
1738   //         ld    r2,.Lfunc_tocNN-.Lfunc_gepNN(r12)
1739   //         add   r2,r2,r12
1740   // .Lfunc_lepNN:
1741   //         .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1742   //         # local entry point, followed by function body
1743   //
1744   // This ensures we have r2 set up correctly while executing the function
1745   // body, no matter which entry point is called.
1746   const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1747   const bool UsesX2OrR2 = !MF->getRegInfo().use_empty(PPC::X2) ||
1748                           !MF->getRegInfo().use_empty(PPC::R2);
1749   const bool PCrelGEPRequired = Subtarget->isUsingPCRelativeCalls() &&
1750                                 UsesX2OrR2 && PPCFI->usesTOCBasePtr();
1751   const bool NonPCrelGEPRequired = !Subtarget->isUsingPCRelativeCalls() &&
1752                                    Subtarget->isELFv2ABI() && UsesX2OrR2;
1753 
1754   // Only do all that if the function uses R2 as the TOC pointer
1755   // in the first place. We don't need the global entry point if the
1756   // function uses R2 as an allocatable register.
1757   if (NonPCrelGEPRequired || PCrelGEPRequired) {
1758     // Note: The logic here must be synchronized with the code in the
1759     // branch-selection pass which sets the offset of the first block in the
1760     // function. This matters because it affects the alignment.
1761     MCSymbol *GlobalEntryLabel = PPCFI->getGlobalEPSymbol(*MF);
1762     OutStreamer->emitLabel(GlobalEntryLabel);
1763     const MCSymbolRefExpr *GlobalEntryLabelExp =
1764       MCSymbolRefExpr::create(GlobalEntryLabel, OutContext);
1765 
1766     if (TM.getCodeModel() != CodeModel::Large) {
1767       MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1768       const MCExpr *TOCDeltaExpr =
1769         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1770                                 GlobalEntryLabelExp, OutContext);
1771 
1772       const MCExpr *TOCDeltaHi = PPCMCExpr::createHa(TOCDeltaExpr, OutContext);
1773       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1774                                    .addReg(PPC::X2)
1775                                    .addReg(PPC::X12)
1776                                    .addExpr(TOCDeltaHi));
1777 
1778       const MCExpr *TOCDeltaLo = PPCMCExpr::createLo(TOCDeltaExpr, OutContext);
1779       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI)
1780                                    .addReg(PPC::X2)
1781                                    .addReg(PPC::X2)
1782                                    .addExpr(TOCDeltaLo));
1783     } else {
1784       MCSymbol *TOCOffset = PPCFI->getTOCOffsetSymbol(*MF);
1785       const MCExpr *TOCOffsetDeltaExpr =
1786         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCOffset, OutContext),
1787                                 GlobalEntryLabelExp, OutContext);
1788 
1789       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
1790                                    .addReg(PPC::X2)
1791                                    .addExpr(TOCOffsetDeltaExpr)
1792                                    .addReg(PPC::X12));
1793       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD8)
1794                                    .addReg(PPC::X2)
1795                                    .addReg(PPC::X2)
1796                                    .addReg(PPC::X12));
1797     }
1798 
1799     MCSymbol *LocalEntryLabel = PPCFI->getLocalEPSymbol(*MF);
1800     OutStreamer->emitLabel(LocalEntryLabel);
1801     const MCSymbolRefExpr *LocalEntryLabelExp =
1802        MCSymbolRefExpr::create(LocalEntryLabel, OutContext);
1803     const MCExpr *LocalOffsetExp =
1804       MCBinaryExpr::createSub(LocalEntryLabelExp,
1805                               GlobalEntryLabelExp, OutContext);
1806 
1807     PPCTargetStreamer *TS =
1808       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1809 
1810     if (TS)
1811       TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), LocalOffsetExp);
1812   } else if (Subtarget->isUsingPCRelativeCalls()) {
1813     // When generating the entry point for a function we have a few scenarios
1814     // based on whether or not that function uses R2 and whether or not that
1815     // function makes calls (or is a leaf function).
1816     // 1) A leaf function that does not use R2 (or treats it as callee-saved
1817     //    and preserves it). In this case st_other=0 and both
1818     //    the local and global entry points for the function are the same.
1819     //    No special entry point code is required.
1820     // 2) A function uses the TOC pointer R2. This function may or may not have
1821     //    calls. In this case st_other=[2,6] and the global and local entry
1822     //    points are different. Code to correctly setup the TOC pointer in R2
1823     //    is put between the global and local entry points. This case is
1824     //    covered by the if statatement above.
1825     // 3) A function does not use the TOC pointer R2 but does have calls.
1826     //    In this case st_other=1 since we do not know whether or not any
1827     //    of the callees clobber R2. This case is dealt with in this else if
1828     //    block. Tail calls are considered calls and the st_other should also
1829     //    be set to 1 in that case as well.
1830     // 4) The function does not use the TOC pointer but R2 is used inside
1831     //    the function. In this case st_other=1 once again.
1832     // 5) This function uses inline asm. We mark R2 as reserved if the function
1833     //    has inline asm as we have to assume that it may be used.
1834     if (MF->getFrameInfo().hasCalls() || MF->getFrameInfo().hasTailCall() ||
1835         MF->hasInlineAsm() || (!PPCFI->usesTOCBasePtr() && UsesX2OrR2)) {
1836       PPCTargetStreamer *TS =
1837           static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1838       if (TS)
1839         TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym),
1840                            MCConstantExpr::create(1, OutContext));
1841     }
1842   }
1843 }
1844 
1845 /// EmitFunctionBodyEnd - Print the traceback table before the .size
1846 /// directive.
1847 ///
1848 void PPCLinuxAsmPrinter::emitFunctionBodyEnd() {
1849   // Only the 64-bit target requires a traceback table.  For now,
1850   // we only emit the word of zeroes that GDB requires to find
1851   // the end of the function, and zeroes for the eight-byte
1852   // mandatory fields.
1853   // FIXME: We should fill in the eight-byte mandatory fields as described in
1854   // the PPC64 ELF ABI (this is a low-priority item because GDB does not
1855   // currently make use of these fields).
1856   if (Subtarget->isPPC64()) {
1857     OutStreamer->emitIntValue(0, 4/*size*/);
1858     OutStreamer->emitIntValue(0, 8/*size*/);
1859   }
1860 }
1861 
1862 void PPCAIXAsmPrinter::emitLinkage(const GlobalValue *GV,
1863                                    MCSymbol *GVSym) const {
1864 
1865   assert(MAI->hasVisibilityOnlyWithLinkage() &&
1866          "AIX's linkage directives take a visibility setting.");
1867 
1868   MCSymbolAttr LinkageAttr = MCSA_Invalid;
1869   switch (GV->getLinkage()) {
1870   case GlobalValue::ExternalLinkage:
1871     LinkageAttr = GV->isDeclaration() ? MCSA_Extern : MCSA_Global;
1872     break;
1873   case GlobalValue::LinkOnceAnyLinkage:
1874   case GlobalValue::LinkOnceODRLinkage:
1875   case GlobalValue::WeakAnyLinkage:
1876   case GlobalValue::WeakODRLinkage:
1877   case GlobalValue::ExternalWeakLinkage:
1878     LinkageAttr = MCSA_Weak;
1879     break;
1880   case GlobalValue::AvailableExternallyLinkage:
1881     LinkageAttr = MCSA_Extern;
1882     break;
1883   case GlobalValue::PrivateLinkage:
1884     return;
1885   case GlobalValue::InternalLinkage:
1886     assert(GV->getVisibility() == GlobalValue::DefaultVisibility &&
1887            "InternalLinkage should not have other visibility setting.");
1888     LinkageAttr = MCSA_LGlobal;
1889     break;
1890   case GlobalValue::AppendingLinkage:
1891     llvm_unreachable("Should never emit this");
1892   case GlobalValue::CommonLinkage:
1893     llvm_unreachable("CommonLinkage of XCOFF should not come to this path");
1894   }
1895 
1896   assert(LinkageAttr != MCSA_Invalid && "LinkageAttr should not MCSA_Invalid.");
1897 
1898   MCSymbolAttr VisibilityAttr = MCSA_Invalid;
1899   if (!TM.getIgnoreXCOFFVisibility()) {
1900     switch (GV->getVisibility()) {
1901 
1902     // TODO: "exported" and "internal" Visibility needs to go here.
1903     case GlobalValue::DefaultVisibility:
1904       break;
1905     case GlobalValue::HiddenVisibility:
1906       VisibilityAttr = MAI->getHiddenVisibilityAttr();
1907       break;
1908     case GlobalValue::ProtectedVisibility:
1909       VisibilityAttr = MAI->getProtectedVisibilityAttr();
1910       break;
1911     }
1912   }
1913 
1914   OutStreamer->emitXCOFFSymbolLinkageWithVisibility(GVSym, LinkageAttr,
1915                                                     VisibilityAttr);
1916 }
1917 
1918 void PPCAIXAsmPrinter::SetupMachineFunction(MachineFunction &MF) {
1919   // Setup CurrentFnDescSym and its containing csect.
1920   MCSectionXCOFF *FnDescSec =
1921       cast<MCSectionXCOFF>(getObjFileLowering().getSectionForFunctionDescriptor(
1922           &MF.getFunction(), TM));
1923   FnDescSec->setAlignment(Align(Subtarget->isPPC64() ? 8 : 4));
1924 
1925   CurrentFnDescSym = FnDescSec->getQualNameSymbol();
1926 
1927   return AsmPrinter::SetupMachineFunction(MF);
1928 }
1929 
1930 uint16_t PPCAIXAsmPrinter::getNumberOfVRSaved() {
1931   // Calculate the number of VRs be saved.
1932   // Vector registers 20 through 31 are marked as reserved and cannot be used
1933   // in the default ABI.
1934   const PPCSubtarget &Subtarget = MF->getSubtarget<PPCSubtarget>();
1935   if (Subtarget.isAIXABI() && Subtarget.hasAltivec() &&
1936       TM.getAIXExtendedAltivecABI()) {
1937     const MachineRegisterInfo &MRI = MF->getRegInfo();
1938     for (unsigned Reg = PPC::V20; Reg <= PPC::V31; ++Reg)
1939       if (MRI.isPhysRegModified(Reg))
1940         // Number of VRs saved.
1941         return PPC::V31 - Reg + 1;
1942   }
1943   return 0;
1944 }
1945 
1946 void PPCAIXAsmPrinter::emitFunctionBodyEnd() {
1947 
1948   if (!TM.getXCOFFTracebackTable())
1949     return;
1950 
1951   emitTracebackTable();
1952 
1953   // If ShouldEmitEHBlock returns true, then the eh info table
1954   // will be emitted via `AIXException::endFunction`. Otherwise, we
1955   // need to emit a dumy eh info table when VRs are saved. We could not
1956   // consolidate these two places into one because there is no easy way
1957   // to access register information in `AIXException` class.
1958   if (!TargetLoweringObjectFileXCOFF::ShouldEmitEHBlock(MF) &&
1959       (getNumberOfVRSaved() > 0)) {
1960     // Emit dummy EH Info Table.
1961     OutStreamer->SwitchSection(getObjFileLowering().getCompactUnwindSection());
1962     MCSymbol *EHInfoLabel =
1963         TargetLoweringObjectFileXCOFF::getEHInfoTableSymbol(MF);
1964     OutStreamer->emitLabel(EHInfoLabel);
1965 
1966     // Version number.
1967     OutStreamer->emitInt32(0);
1968 
1969     const DataLayout &DL = MMI->getModule()->getDataLayout();
1970     const unsigned PointerSize = DL.getPointerSize();
1971     // Add necessary paddings in 64 bit mode.
1972     OutStreamer->emitValueToAlignment(PointerSize);
1973 
1974     OutStreamer->emitIntValue(0, PointerSize);
1975     OutStreamer->emitIntValue(0, PointerSize);
1976     OutStreamer->SwitchSection(MF->getSection());
1977   }
1978 }
1979 
1980 void PPCAIXAsmPrinter::emitTracebackTable() {
1981 
1982   // Create a symbol for the end of function.
1983   MCSymbol *FuncEnd = createTempSymbol(MF->getName());
1984   OutStreamer->emitLabel(FuncEnd);
1985 
1986   OutStreamer->AddComment("Traceback table begin");
1987   // Begin with a fullword of zero.
1988   OutStreamer->emitIntValueInHexWithPadding(0, 4 /*size*/);
1989 
1990   SmallString<128> CommentString;
1991   raw_svector_ostream CommentOS(CommentString);
1992 
1993   auto EmitComment = [&]() {
1994     OutStreamer->AddComment(CommentOS.str());
1995     CommentString.clear();
1996   };
1997 
1998   auto EmitCommentAndValue = [&](uint64_t Value, int Size) {
1999     EmitComment();
2000     OutStreamer->emitIntValueInHexWithPadding(Value, Size);
2001   };
2002 
2003   unsigned int Version = 0;
2004   CommentOS << "Version = " << Version;
2005   EmitCommentAndValue(Version, 1);
2006 
2007   // There is a lack of information in the IR to assist with determining the
2008   // source language. AIX exception handling mechanism would only search for
2009   // personality routine and LSDA area when such language supports exception
2010   // handling. So to be conservatively correct and allow runtime to do its job,
2011   // we need to set it to C++ for now.
2012   TracebackTable::LanguageID LanguageIdentifier =
2013       TracebackTable::CPlusPlus; // C++
2014 
2015   CommentOS << "Language = "
2016             << getNameForTracebackTableLanguageId(LanguageIdentifier);
2017   EmitCommentAndValue(LanguageIdentifier, 1);
2018 
2019   //  This is only populated for the third and fourth bytes.
2020   uint32_t FirstHalfOfMandatoryField = 0;
2021 
2022   // Emit the 3rd byte of the mandatory field.
2023 
2024   // We always set traceback offset bit to true.
2025   FirstHalfOfMandatoryField |= TracebackTable::HasTraceBackTableOffsetMask;
2026 
2027   const PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>();
2028   const MachineRegisterInfo &MRI = MF->getRegInfo();
2029 
2030   // Check the function uses floating-point processor instructions or not
2031   for (unsigned Reg = PPC::F0; Reg <= PPC::F31; ++Reg) {
2032     if (MRI.isPhysRegUsed(Reg, /* SkipRegMaskTest */ true)) {
2033       FirstHalfOfMandatoryField |= TracebackTable::IsFloatingPointPresentMask;
2034       break;
2035     }
2036   }
2037 
2038 #define GENBOOLCOMMENT(Prefix, V, Field)                                       \
2039   CommentOS << (Prefix) << ((V) & (TracebackTable::Field##Mask) ? "+" : "-")   \
2040             << #Field
2041 
2042 #define GENVALUECOMMENT(PrefixAndName, V, Field)                               \
2043   CommentOS << (PrefixAndName) << " = "                                        \
2044             << static_cast<unsigned>(((V) & (TracebackTable::Field##Mask)) >>  \
2045                                      (TracebackTable::Field##Shift))
2046 
2047   GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsGlobaLinkage);
2048   GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsOutOfLineEpilogOrPrologue);
2049   EmitComment();
2050 
2051   GENBOOLCOMMENT("", FirstHalfOfMandatoryField, HasTraceBackTableOffset);
2052   GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsInternalProcedure);
2053   EmitComment();
2054 
2055   GENBOOLCOMMENT("", FirstHalfOfMandatoryField, HasControlledStorage);
2056   GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsTOCless);
2057   EmitComment();
2058 
2059   GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsFloatingPointPresent);
2060   EmitComment();
2061   GENBOOLCOMMENT("", FirstHalfOfMandatoryField,
2062                  IsFloatingPointOperationLogOrAbortEnabled);
2063   EmitComment();
2064 
2065   OutStreamer->emitIntValueInHexWithPadding(
2066       (FirstHalfOfMandatoryField & 0x0000ff00) >> 8, 1);
2067 
2068   // Set the 4th byte of the mandatory field.
2069   FirstHalfOfMandatoryField |= TracebackTable::IsFunctionNamePresentMask;
2070 
2071   const PPCRegisterInfo *RegInfo =
2072       static_cast<const PPCRegisterInfo *>(Subtarget->getRegisterInfo());
2073   Register FrameReg = RegInfo->getFrameRegister(*MF);
2074   if (FrameReg == (Subtarget->isPPC64() ? PPC::X31 : PPC::R31))
2075     FirstHalfOfMandatoryField |= TracebackTable::IsAllocaUsedMask;
2076 
2077   const SmallVectorImpl<Register> &MustSaveCRs = FI->getMustSaveCRs();
2078   if (!MustSaveCRs.empty())
2079     FirstHalfOfMandatoryField |= TracebackTable::IsCRSavedMask;
2080 
2081   if (FI->mustSaveLR())
2082     FirstHalfOfMandatoryField |= TracebackTable::IsLRSavedMask;
2083 
2084   GENBOOLCOMMENT("", FirstHalfOfMandatoryField, IsInterruptHandler);
2085   GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsFunctionNamePresent);
2086   GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsAllocaUsed);
2087   EmitComment();
2088   GENVALUECOMMENT("OnConditionDirective", FirstHalfOfMandatoryField,
2089                   OnConditionDirective);
2090   GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsCRSaved);
2091   GENBOOLCOMMENT(", ", FirstHalfOfMandatoryField, IsLRSaved);
2092   EmitComment();
2093   OutStreamer->emitIntValueInHexWithPadding((FirstHalfOfMandatoryField & 0xff),
2094                                             1);
2095 
2096   // Set the 5th byte of mandatory field.
2097   uint32_t SecondHalfOfMandatoryField = 0;
2098 
2099   // Always store back chain.
2100   SecondHalfOfMandatoryField |= TracebackTable::IsBackChainStoredMask;
2101 
2102   uint32_t FPRSaved = 0;
2103   for (unsigned Reg = PPC::F14; Reg <= PPC::F31; ++Reg) {
2104     if (MRI.isPhysRegModified(Reg)) {
2105       FPRSaved = PPC::F31 - Reg + 1;
2106       break;
2107     }
2108   }
2109   SecondHalfOfMandatoryField |= (FPRSaved << TracebackTable::FPRSavedShift) &
2110                                 TracebackTable::FPRSavedMask;
2111   GENBOOLCOMMENT("", SecondHalfOfMandatoryField, IsBackChainStored);
2112   GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, IsFixup);
2113   GENVALUECOMMENT(", NumOfFPRsSaved", SecondHalfOfMandatoryField, FPRSaved);
2114   EmitComment();
2115   OutStreamer->emitIntValueInHexWithPadding(
2116       (SecondHalfOfMandatoryField & 0xff000000) >> 24, 1);
2117 
2118   // Set the 6th byte of mandatory field.
2119 
2120   // Check whether has Vector Instruction,We only treat instructions uses vector
2121   // register as vector instructions.
2122   bool HasVectorInst = false;
2123   for (unsigned Reg = PPC::V0; Reg <= PPC::V31; ++Reg)
2124     if (MRI.isPhysRegUsed(Reg, /* SkipRegMaskTest */ true)) {
2125       // Has VMX instruction.
2126       HasVectorInst = true;
2127       break;
2128     }
2129 
2130   if (FI->hasVectorParms() || HasVectorInst)
2131     SecondHalfOfMandatoryField |= TracebackTable::HasVectorInfoMask;
2132 
2133   uint16_t NumOfVRSaved = getNumberOfVRSaved();
2134   bool ShouldEmitEHBlock =
2135       TargetLoweringObjectFileXCOFF::ShouldEmitEHBlock(MF) || NumOfVRSaved > 0;
2136 
2137   if (ShouldEmitEHBlock)
2138     SecondHalfOfMandatoryField |= TracebackTable::HasExtensionTableMask;
2139 
2140   uint32_t GPRSaved = 0;
2141 
2142   // X13 is reserved under 64-bit environment.
2143   unsigned GPRBegin = Subtarget->isPPC64() ? PPC::X14 : PPC::R13;
2144   unsigned GPREnd = Subtarget->isPPC64() ? PPC::X31 : PPC::R31;
2145 
2146   for (unsigned Reg = GPRBegin; Reg <= GPREnd; ++Reg) {
2147     if (MRI.isPhysRegModified(Reg)) {
2148       GPRSaved = GPREnd - Reg + 1;
2149       break;
2150     }
2151   }
2152 
2153   SecondHalfOfMandatoryField |= (GPRSaved << TracebackTable::GPRSavedShift) &
2154                                 TracebackTable::GPRSavedMask;
2155 
2156   GENBOOLCOMMENT("", SecondHalfOfMandatoryField, HasExtensionTable);
2157   GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, HasVectorInfo);
2158   GENVALUECOMMENT(", NumOfGPRsSaved", SecondHalfOfMandatoryField, GPRSaved);
2159   EmitComment();
2160   OutStreamer->emitIntValueInHexWithPadding(
2161       (SecondHalfOfMandatoryField & 0x00ff0000) >> 16, 1);
2162 
2163   // Set the 7th byte of mandatory field.
2164   uint32_t NumberOfFixedParms = FI->getFixedParmsNum();
2165   SecondHalfOfMandatoryField |=
2166       (NumberOfFixedParms << TracebackTable::NumberOfFixedParmsShift) &
2167       TracebackTable::NumberOfFixedParmsMask;
2168   GENVALUECOMMENT("NumberOfFixedParms", SecondHalfOfMandatoryField,
2169                   NumberOfFixedParms);
2170   EmitComment();
2171   OutStreamer->emitIntValueInHexWithPadding(
2172       (SecondHalfOfMandatoryField & 0x0000ff00) >> 8, 1);
2173 
2174   // Set the 8th byte of mandatory field.
2175 
2176   // Always set parameter on stack.
2177   SecondHalfOfMandatoryField |= TracebackTable::HasParmsOnStackMask;
2178 
2179   uint32_t NumberOfFPParms = FI->getFloatingPointParmsNum();
2180   SecondHalfOfMandatoryField |=
2181       (NumberOfFPParms << TracebackTable::NumberOfFloatingPointParmsShift) &
2182       TracebackTable::NumberOfFloatingPointParmsMask;
2183 
2184   GENVALUECOMMENT("NumberOfFPParms", SecondHalfOfMandatoryField,
2185                   NumberOfFloatingPointParms);
2186   GENBOOLCOMMENT(", ", SecondHalfOfMandatoryField, HasParmsOnStack);
2187   EmitComment();
2188   OutStreamer->emitIntValueInHexWithPadding(SecondHalfOfMandatoryField & 0xff,
2189                                             1);
2190 
2191   // Generate the optional fields of traceback table.
2192 
2193   // Parameter type.
2194   if (NumberOfFixedParms || NumberOfFPParms) {
2195     uint32_t ParmsTypeValue = FI->getParmsType();
2196 
2197     Expected<SmallString<32>> ParmsType =
2198         FI->hasVectorParms()
2199             ? XCOFF::parseParmsTypeWithVecInfo(
2200                   ParmsTypeValue, NumberOfFixedParms, NumberOfFPParms,
2201                   FI->getVectorParmsNum())
2202             : XCOFF::parseParmsType(ParmsTypeValue, NumberOfFixedParms,
2203                                     NumberOfFPParms);
2204 
2205     assert(ParmsType && toString(ParmsType.takeError()).c_str());
2206     if (ParmsType) {
2207       CommentOS << "Parameter type = " << ParmsType.get();
2208       EmitComment();
2209     }
2210     OutStreamer->emitIntValueInHexWithPadding(ParmsTypeValue,
2211                                               sizeof(ParmsTypeValue));
2212   }
2213   // Traceback table offset.
2214   OutStreamer->AddComment("Function size");
2215   if (FirstHalfOfMandatoryField & TracebackTable::HasTraceBackTableOffsetMask) {
2216     MCSymbol *FuncSectSym = getObjFileLowering().getFunctionEntryPointSymbol(
2217         &(MF->getFunction()), TM);
2218     OutStreamer->emitAbsoluteSymbolDiff(FuncEnd, FuncSectSym, 4);
2219   }
2220 
2221   // Since we unset the Int_Handler.
2222   if (FirstHalfOfMandatoryField & TracebackTable::IsInterruptHandlerMask)
2223     report_fatal_error("Hand_Mask not implement yet");
2224 
2225   if (FirstHalfOfMandatoryField & TracebackTable::HasControlledStorageMask)
2226     report_fatal_error("Ctl_Info not implement yet");
2227 
2228   if (FirstHalfOfMandatoryField & TracebackTable::IsFunctionNamePresentMask) {
2229     StringRef Name = MF->getName().substr(0, INT16_MAX);
2230     int16_t NameLength = Name.size();
2231     CommentOS << "Function name len = "
2232               << static_cast<unsigned int>(NameLength);
2233     EmitCommentAndValue(NameLength, 2);
2234     OutStreamer->AddComment("Function Name");
2235     OutStreamer->emitBytes(Name);
2236   }
2237 
2238   if (FirstHalfOfMandatoryField & TracebackTable::IsAllocaUsedMask) {
2239     uint8_t AllocReg = XCOFF::AllocRegNo;
2240     OutStreamer->AddComment("AllocaUsed");
2241     OutStreamer->emitIntValueInHex(AllocReg, sizeof(AllocReg));
2242   }
2243 
2244   if (SecondHalfOfMandatoryField & TracebackTable::HasVectorInfoMask) {
2245     uint16_t VRData = 0;
2246     if (NumOfVRSaved) {
2247       // Number of VRs saved.
2248       VRData |= (NumOfVRSaved << TracebackTable::NumberOfVRSavedShift) &
2249                 TracebackTable::NumberOfVRSavedMask;
2250       // This bit is supposed to set only when the special register
2251       // VRSAVE is saved on stack.
2252       // However, IBM XL compiler sets the bit when any vector registers
2253       // are saved on the stack. We will follow XL's behavior on AIX
2254       // so that we don't get surprise behavior change for C code.
2255       VRData |= TracebackTable::IsVRSavedOnStackMask;
2256     }
2257 
2258     // Set has_varargs.
2259     if (FI->getVarArgsFrameIndex())
2260       VRData |= TracebackTable::HasVarArgsMask;
2261 
2262     // Vector parameters number.
2263     unsigned VectorParmsNum = FI->getVectorParmsNum();
2264     VRData |= (VectorParmsNum << TracebackTable::NumberOfVectorParmsShift) &
2265               TracebackTable::NumberOfVectorParmsMask;
2266 
2267     if (HasVectorInst)
2268       VRData |= TracebackTable::HasVMXInstructionMask;
2269 
2270     GENVALUECOMMENT("NumOfVRsSaved", VRData, NumberOfVRSaved);
2271     GENBOOLCOMMENT(", ", VRData, IsVRSavedOnStack);
2272     GENBOOLCOMMENT(", ", VRData, HasVarArgs);
2273     EmitComment();
2274     OutStreamer->emitIntValueInHexWithPadding((VRData & 0xff00) >> 8, 1);
2275 
2276     GENVALUECOMMENT("NumOfVectorParams", VRData, NumberOfVectorParms);
2277     GENBOOLCOMMENT(", ", VRData, HasVMXInstruction);
2278     EmitComment();
2279     OutStreamer->emitIntValueInHexWithPadding(VRData & 0x00ff, 1);
2280 
2281     uint32_t VecParmTypeValue = FI->getVecExtParmsType();
2282 
2283     Expected<SmallString<32>> VecParmsType =
2284         XCOFF::parseVectorParmsType(VecParmTypeValue, VectorParmsNum);
2285     assert(VecParmsType && toString(VecParmsType.takeError()).c_str());
2286     if (VecParmsType) {
2287       CommentOS << "Vector Parameter type = " << VecParmsType.get();
2288       EmitComment();
2289     }
2290     OutStreamer->emitIntValueInHexWithPadding(VecParmTypeValue,
2291                                               sizeof(VecParmTypeValue));
2292     // Padding 2 bytes.
2293     CommentOS << "Padding";
2294     EmitCommentAndValue(0, 2);
2295   }
2296 
2297   uint8_t ExtensionTableFlag = 0;
2298   if (SecondHalfOfMandatoryField & TracebackTable::HasExtensionTableMask) {
2299     if (ShouldEmitEHBlock)
2300       ExtensionTableFlag |= ExtendedTBTableFlag::TB_EH_INFO;
2301     if (EnableSSPCanaryBitInTB &&
2302         TargetLoweringObjectFileXCOFF::ShouldSetSSPCanaryBitInTB(MF))
2303       ExtensionTableFlag |= ExtendedTBTableFlag::TB_SSP_CANARY;
2304 
2305     CommentOS << "ExtensionTableFlag = "
2306               << getExtendedTBTableFlagString(ExtensionTableFlag);
2307     EmitCommentAndValue(ExtensionTableFlag, sizeof(ExtensionTableFlag));
2308   }
2309 
2310   if (ExtensionTableFlag & ExtendedTBTableFlag::TB_EH_INFO) {
2311     auto &Ctx = OutStreamer->getContext();
2312     MCSymbol *EHInfoSym =
2313         TargetLoweringObjectFileXCOFF::getEHInfoTableSymbol(MF);
2314     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(EHInfoSym);
2315     const MCSymbol *TOCBaseSym =
2316         cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
2317             ->getQualNameSymbol();
2318     const MCExpr *Exp =
2319         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCEntry, Ctx),
2320                                 MCSymbolRefExpr::create(TOCBaseSym, Ctx), Ctx);
2321 
2322     const DataLayout &DL = getDataLayout();
2323     OutStreamer->emitValueToAlignment(4);
2324     OutStreamer->AddComment("EHInfo Table");
2325     OutStreamer->emitValue(Exp, DL.getPointerSize());
2326   }
2327 #undef GENBOOLCOMMENT
2328 #undef GENVALUECOMMENT
2329 }
2330 
2331 static bool isSpecialLLVMGlobalArrayToSkip(const GlobalVariable *GV) {
2332   return GV->hasAppendingLinkage() &&
2333          StringSwitch<bool>(GV->getName())
2334              // TODO: Linker could still eliminate the GV if we just skip
2335              // handling llvm.used array. Skipping them for now until we or the
2336              // AIX OS team come up with a good solution.
2337              .Case("llvm.used", true)
2338              // It's correct to just skip llvm.compiler.used array here.
2339              .Case("llvm.compiler.used", true)
2340              .Default(false);
2341 }
2342 
2343 static bool isSpecialLLVMGlobalArrayForStaticInit(const GlobalVariable *GV) {
2344   return StringSwitch<bool>(GV->getName())
2345       .Cases("llvm.global_ctors", "llvm.global_dtors", true)
2346       .Default(false);
2347 }
2348 
2349 void PPCAIXAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
2350   // Special LLVM global arrays have been handled at the initialization.
2351   if (isSpecialLLVMGlobalArrayToSkip(GV) || isSpecialLLVMGlobalArrayForStaticInit(GV))
2352     return;
2353 
2354   // If the Global Variable has the toc-data attribute, it needs to be emitted
2355   // when we emit the .toc section.
2356   if (GV->hasAttribute("toc-data")) {
2357     TOCDataGlobalVars.push_back(GV);
2358     return;
2359   }
2360 
2361   emitGlobalVariableHelper(GV);
2362 }
2363 
2364 void PPCAIXAsmPrinter::emitGlobalVariableHelper(const GlobalVariable *GV) {
2365   assert(!GV->getName().startswith("llvm.") &&
2366          "Unhandled intrinsic global variable.");
2367 
2368   if (GV->hasComdat())
2369     report_fatal_error("COMDAT not yet supported by AIX.");
2370 
2371   MCSymbolXCOFF *GVSym = cast<MCSymbolXCOFF>(getSymbol(GV));
2372 
2373   if (GV->isDeclarationForLinker()) {
2374     emitLinkage(GV, GVSym);
2375     return;
2376   }
2377 
2378   SectionKind GVKind = getObjFileLowering().getKindForGlobal(GV, TM);
2379   if (!GVKind.isGlobalWriteableData() && !GVKind.isReadOnly() &&
2380       !GVKind.isThreadLocal()) // Checks for both ThreadData and ThreadBSS.
2381     report_fatal_error("Encountered a global variable kind that is "
2382                        "not supported yet.");
2383 
2384   // Print GV in verbose mode
2385   if (isVerbose()) {
2386     if (GV->hasInitializer()) {
2387       GV->printAsOperand(OutStreamer->GetCommentOS(),
2388                          /*PrintType=*/false, GV->getParent());
2389       OutStreamer->GetCommentOS() << '\n';
2390     }
2391   }
2392 
2393   MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
2394       getObjFileLowering().SectionForGlobal(GV, GVKind, TM));
2395 
2396   // Switch to the containing csect.
2397   OutStreamer->SwitchSection(Csect);
2398 
2399   const DataLayout &DL = GV->getParent()->getDataLayout();
2400 
2401   // Handle common and zero-initialized local symbols.
2402   if (GV->hasCommonLinkage() || GVKind.isBSSLocal() ||
2403       GVKind.isThreadBSSLocal()) {
2404     Align Alignment = GV->getAlign().getValueOr(DL.getPreferredAlign(GV));
2405     uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
2406     GVSym->setStorageClass(
2407         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GV));
2408 
2409     if (GVKind.isBSSLocal() || GVKind.isThreadBSSLocal())
2410       OutStreamer->emitXCOFFLocalCommonSymbol(
2411           OutContext.getOrCreateSymbol(GVSym->getSymbolTableName()), Size,
2412           GVSym, Alignment.value());
2413     else
2414       OutStreamer->emitCommonSymbol(GVSym, Size, Alignment.value());
2415     return;
2416   }
2417 
2418   MCSymbol *EmittedInitSym = GVSym;
2419   emitLinkage(GV, EmittedInitSym);
2420   emitAlignment(getGVAlignment(GV, DL), GV);
2421 
2422   // When -fdata-sections is enabled, every GlobalVariable will
2423   // be put into its own csect; therefore, label is not necessary here.
2424   if (!TM.getDataSections() || GV->hasSection()) {
2425     OutStreamer->emitLabel(EmittedInitSym);
2426   }
2427 
2428   // Emit aliasing label for global variable.
2429   llvm::for_each(GOAliasMap[GV], [this](const GlobalAlias *Alias) {
2430     OutStreamer->emitLabel(getSymbol(Alias));
2431   });
2432 
2433   emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
2434 }
2435 
2436 void PPCAIXAsmPrinter::emitFunctionDescriptor() {
2437   const DataLayout &DL = getDataLayout();
2438   const unsigned PointerSize = DL.getPointerSizeInBits() == 64 ? 8 : 4;
2439 
2440   MCSectionSubPair Current = OutStreamer->getCurrentSection();
2441   // Emit function descriptor.
2442   OutStreamer->SwitchSection(
2443       cast<MCSymbolXCOFF>(CurrentFnDescSym)->getRepresentedCsect());
2444 
2445   // Emit aliasing label for function descriptor csect.
2446   llvm::for_each(GOAliasMap[&MF->getFunction()],
2447                  [this](const GlobalAlias *Alias) {
2448                    OutStreamer->emitLabel(getSymbol(Alias));
2449                  });
2450 
2451   // Emit function entry point address.
2452   OutStreamer->emitValue(MCSymbolRefExpr::create(CurrentFnSym, OutContext),
2453                          PointerSize);
2454   // Emit TOC base address.
2455   const MCSymbol *TOCBaseSym =
2456       cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
2457           ->getQualNameSymbol();
2458   OutStreamer->emitValue(MCSymbolRefExpr::create(TOCBaseSym, OutContext),
2459                          PointerSize);
2460   // Emit a null environment pointer.
2461   OutStreamer->emitIntValue(0, PointerSize);
2462 
2463   OutStreamer->SwitchSection(Current.first, Current.second);
2464 }
2465 
2466 void PPCAIXAsmPrinter::emitFunctionEntryLabel() {
2467   // It's not necessary to emit the label when we have individual
2468   // function in its own csect.
2469   if (!TM.getFunctionSections())
2470     PPCAsmPrinter::emitFunctionEntryLabel();
2471 
2472   // Emit aliasing label for function entry point label.
2473   llvm::for_each(
2474       GOAliasMap[&MF->getFunction()], [this](const GlobalAlias *Alias) {
2475         OutStreamer->emitLabel(
2476             getObjFileLowering().getFunctionEntryPointSymbol(Alias, TM));
2477       });
2478 }
2479 
2480 void PPCAIXAsmPrinter::emitPGORefs() {
2481   if (OutContext.hasXCOFFSection(
2482           "__llvm_prf_cnts",
2483           XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD))) {
2484     MCSection *CntsSection = OutContext.getXCOFFSection(
2485         "__llvm_prf_cnts", SectionKind::getData(),
2486         XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD),
2487         /*MultiSymbolsAllowed*/ true);
2488 
2489     OutStreamer->SwitchSection(CntsSection);
2490     if (OutContext.hasXCOFFSection(
2491             "__llvm_prf_data",
2492             XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD)))
2493       OutStreamer->emitXCOFFRefDirective("__llvm_prf_data[RW]");
2494     if (OutContext.hasXCOFFSection(
2495             "__llvm_prf_names",
2496             XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD)))
2497       OutStreamer->emitXCOFFRefDirective("__llvm_prf_names[RO]");
2498     if (OutContext.hasXCOFFSection(
2499             "__llvm_prf_vnds",
2500             XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD)))
2501       OutStreamer->emitXCOFFRefDirective("__llvm_prf_vnds[RW]");
2502   }
2503 }
2504 
2505 void PPCAIXAsmPrinter::emitEndOfAsmFile(Module &M) {
2506   // If there are no functions and there are no toc-data definitions in this
2507   // module, we will never need to reference the TOC base.
2508   if (M.empty() && TOCDataGlobalVars.empty())
2509     return;
2510 
2511   emitPGORefs();
2512 
2513   // Switch to section to emit TOC base.
2514   OutStreamer->SwitchSection(getObjFileLowering().getTOCBaseSection());
2515 
2516   PPCTargetStreamer *TS =
2517       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
2518 
2519   for (auto &I : TOC) {
2520     MCSectionXCOFF *TCEntry;
2521     // Setup the csect for the current TC entry. If the variant kind is
2522     // VK_PPC_AIX_TLSGDM the entry represents the region handle, we create a
2523     // new symbol to prefix the name with a dot.
2524     if (I.first.second == MCSymbolRefExpr::VariantKind::VK_PPC_AIX_TLSGDM) {
2525       SmallString<128> Name;
2526       StringRef Prefix = ".";
2527       Name += Prefix;
2528       Name += I.first.first->getName();
2529       MCSymbol *S = OutContext.getOrCreateSymbol(Name);
2530       TCEntry = cast<MCSectionXCOFF>(
2531           getObjFileLowering().getSectionForTOCEntry(S, TM));
2532     } else {
2533       TCEntry = cast<MCSectionXCOFF>(
2534           getObjFileLowering().getSectionForTOCEntry(I.first.first, TM));
2535     }
2536     OutStreamer->SwitchSection(TCEntry);
2537 
2538     OutStreamer->emitLabel(I.second);
2539     if (TS != nullptr)
2540       TS->emitTCEntry(*I.first.first, I.first.second);
2541   }
2542 
2543   for (const auto *GV : TOCDataGlobalVars)
2544     emitGlobalVariableHelper(GV);
2545 }
2546 
2547 bool PPCAIXAsmPrinter::doInitialization(Module &M) {
2548   const bool Result = PPCAsmPrinter::doInitialization(M);
2549 
2550   auto setCsectAlignment = [this](const GlobalObject *GO) {
2551     // Declarations have 0 alignment which is set by default.
2552     if (GO->isDeclarationForLinker())
2553       return;
2554 
2555     SectionKind GOKind = getObjFileLowering().getKindForGlobal(GO, TM);
2556     MCSectionXCOFF *Csect = cast<MCSectionXCOFF>(
2557         getObjFileLowering().SectionForGlobal(GO, GOKind, TM));
2558 
2559     Align GOAlign = getGVAlignment(GO, GO->getParent()->getDataLayout());
2560     if (GOAlign > Csect->getAlignment())
2561       Csect->setAlignment(GOAlign);
2562   };
2563 
2564   // We need to know, up front, the alignment of csects for the assembly path,
2565   // because once a .csect directive gets emitted, we could not change the
2566   // alignment value on it.
2567   for (const auto &G : M.globals()) {
2568     if (isSpecialLLVMGlobalArrayToSkip(&G))
2569       continue;
2570 
2571     if (isSpecialLLVMGlobalArrayForStaticInit(&G)) {
2572       // Generate a format indicator and a unique module id to be a part of
2573       // the sinit and sterm function names.
2574       if (FormatIndicatorAndUniqueModId.empty()) {
2575         std::string UniqueModuleId = getUniqueModuleId(&M);
2576         if (UniqueModuleId != "")
2577           // TODO: Use source file full path to generate the unique module id
2578           // and add a format indicator as a part of function name in case we
2579           // will support more than one format.
2580           FormatIndicatorAndUniqueModId = "clang_" + UniqueModuleId.substr(1);
2581         else
2582           // Use the Pid and current time as the unique module id when we cannot
2583           // generate one based on a module's strong external symbols.
2584           // FIXME: Adjust the comment accordingly after we use source file full
2585           // path instead.
2586           FormatIndicatorAndUniqueModId =
2587               "clangPidTime_" + llvm::itostr(sys::Process::getProcessId()) +
2588               "_" + llvm::itostr(time(nullptr));
2589       }
2590 
2591       emitSpecialLLVMGlobal(&G);
2592       continue;
2593     }
2594 
2595     setCsectAlignment(&G);
2596   }
2597 
2598   for (const auto &F : M)
2599     setCsectAlignment(&F);
2600 
2601   // Construct an aliasing list for each GlobalObject.
2602   for (const auto &Alias : M.aliases()) {
2603     const GlobalObject *Base = Alias.getAliaseeObject();
2604     if (!Base)
2605       report_fatal_error(
2606           "alias without a base object is not yet supported on AIX");
2607     GOAliasMap[Base].push_back(&Alias);
2608   }
2609 
2610   return Result;
2611 }
2612 
2613 void PPCAIXAsmPrinter::emitInstruction(const MachineInstr *MI) {
2614   switch (MI->getOpcode()) {
2615   default:
2616     break;
2617   case PPC::GETtlsADDR64AIX:
2618   case PPC::GETtlsADDR32AIX: {
2619     // The reference to .__tls_get_addr is unknown to the assembler
2620     // so we need to emit an external symbol reference.
2621     MCSymbol *TlsGetAddr = createMCSymbolForTlsGetAddr(OutContext);
2622     ExtSymSDNodeSymbols.insert(TlsGetAddr);
2623     break;
2624   }
2625   case PPC::BL8:
2626   case PPC::BL:
2627   case PPC::BL8_NOP:
2628   case PPC::BL_NOP: {
2629     const MachineOperand &MO = MI->getOperand(0);
2630     if (MO.isSymbol()) {
2631       MCSymbolXCOFF *S =
2632           cast<MCSymbolXCOFF>(OutContext.getOrCreateSymbol(MO.getSymbolName()));
2633       ExtSymSDNodeSymbols.insert(S);
2634     }
2635   } break;
2636   case PPC::BL_TLS:
2637   case PPC::BL8_TLS:
2638   case PPC::BL8_TLS_:
2639   case PPC::BL8_NOP_TLS:
2640     report_fatal_error("TLS call not yet implemented");
2641   case PPC::TAILB:
2642   case PPC::TAILB8:
2643   case PPC::TAILBA:
2644   case PPC::TAILBA8:
2645   case PPC::TAILBCTR:
2646   case PPC::TAILBCTR8:
2647     if (MI->getOperand(0).isSymbol())
2648       report_fatal_error("Tail call for extern symbol not yet supported.");
2649     break;
2650   case PPC::DST:
2651   case PPC::DST64:
2652   case PPC::DSTT:
2653   case PPC::DSTT64:
2654   case PPC::DSTST:
2655   case PPC::DSTST64:
2656   case PPC::DSTSTT:
2657   case PPC::DSTSTT64:
2658     EmitToStreamer(
2659         *OutStreamer,
2660         MCInstBuilder(PPC::ORI).addReg(PPC::R0).addReg(PPC::R0).addImm(0));
2661     return;
2662   }
2663   return PPCAsmPrinter::emitInstruction(MI);
2664 }
2665 
2666 bool PPCAIXAsmPrinter::doFinalization(Module &M) {
2667   // Do streamer related finalization for DWARF.
2668   if (!MAI->usesDwarfFileAndLocDirectives() && MMI->hasDebugInfo())
2669     OutStreamer->doFinalizationAtSectionEnd(
2670         OutStreamer->getContext().getObjectFileInfo()->getTextSection());
2671 
2672   for (MCSymbol *Sym : ExtSymSDNodeSymbols)
2673     OutStreamer->emitSymbolAttribute(Sym, MCSA_Extern);
2674   return PPCAsmPrinter::doFinalization(M);
2675 }
2676 
2677 static unsigned mapToSinitPriority(int P) {
2678   if (P < 0 || P > 65535)
2679     report_fatal_error("invalid init priority");
2680 
2681   if (P <= 20)
2682     return P;
2683 
2684   if (P < 81)
2685     return 20 + (P - 20) * 16;
2686 
2687   if (P <= 1124)
2688     return 1004 + (P - 81);
2689 
2690   if (P < 64512)
2691     return 2047 + (P - 1124) * 33878;
2692 
2693   return 2147482625u + (P - 64512);
2694 }
2695 
2696 static std::string convertToSinitPriority(int Priority) {
2697   // This helper function converts clang init priority to values used in sinit
2698   // and sterm functions.
2699   //
2700   // The conversion strategies are:
2701   // We map the reserved clang/gnu priority range [0, 100] into the sinit/sterm
2702   // reserved priority range [0, 1023] by
2703   // - directly mapping the first 21 and the last 20 elements of the ranges
2704   // - linear interpolating the intermediate values with a step size of 16.
2705   //
2706   // We map the non reserved clang/gnu priority range of [101, 65535] into the
2707   // sinit/sterm priority range [1024, 2147483648] by:
2708   // - directly mapping the first and the last 1024 elements of the ranges
2709   // - linear interpolating the intermediate values with a step size of 33878.
2710   unsigned int P = mapToSinitPriority(Priority);
2711 
2712   std::string PrioritySuffix;
2713   llvm::raw_string_ostream os(PrioritySuffix);
2714   os << llvm::format_hex_no_prefix(P, 8);
2715   os.flush();
2716   return PrioritySuffix;
2717 }
2718 
2719 void PPCAIXAsmPrinter::emitXXStructorList(const DataLayout &DL,
2720                                           const Constant *List, bool IsCtor) {
2721   SmallVector<Structor, 8> Structors;
2722   preprocessXXStructorList(DL, List, Structors);
2723   if (Structors.empty())
2724     return;
2725 
2726   unsigned Index = 0;
2727   for (Structor &S : Structors) {
2728     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(S.Func))
2729       S.Func = CE->getOperand(0);
2730 
2731     llvm::GlobalAlias::create(
2732         GlobalValue::ExternalLinkage,
2733         (IsCtor ? llvm::Twine("__sinit") : llvm::Twine("__sterm")) +
2734             llvm::Twine(convertToSinitPriority(S.Priority)) +
2735             llvm::Twine("_", FormatIndicatorAndUniqueModId) +
2736             llvm::Twine("_", llvm::utostr(Index++)),
2737         cast<Function>(S.Func));
2738   }
2739 }
2740 
2741 void PPCAIXAsmPrinter::emitTTypeReference(const GlobalValue *GV,
2742                                           unsigned Encoding) {
2743   if (GV) {
2744     MCSymbol *TypeInfoSym = TM.getSymbol(GV);
2745     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(TypeInfoSym);
2746     const MCSymbol *TOCBaseSym =
2747         cast<MCSectionXCOFF>(getObjFileLowering().getTOCBaseSection())
2748             ->getQualNameSymbol();
2749     auto &Ctx = OutStreamer->getContext();
2750     const MCExpr *Exp =
2751         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCEntry, Ctx),
2752                                 MCSymbolRefExpr::create(TOCBaseSym, Ctx), Ctx);
2753     OutStreamer->emitValue(Exp, GetSizeOfEncodedValue(Encoding));
2754   } else
2755     OutStreamer->emitIntValue(0, GetSizeOfEncodedValue(Encoding));
2756 }
2757 
2758 // Return a pass that prints the PPC assembly code for a MachineFunction to the
2759 // given output stream.
2760 static AsmPrinter *
2761 createPPCAsmPrinterPass(TargetMachine &tm,
2762                         std::unique_ptr<MCStreamer> &&Streamer) {
2763   if (tm.getTargetTriple().isOSAIX())
2764     return new PPCAIXAsmPrinter(tm, std::move(Streamer));
2765 
2766   return new PPCLinuxAsmPrinter(tm, std::move(Streamer));
2767 }
2768 
2769 // Force static initialization.
2770 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializePowerPCAsmPrinter() {
2771   TargetRegistry::RegisterAsmPrinter(getThePPC32Target(),
2772                                      createPPCAsmPrinterPass);
2773   TargetRegistry::RegisterAsmPrinter(getThePPC32LETarget(),
2774                                      createPPCAsmPrinterPass);
2775   TargetRegistry::RegisterAsmPrinter(getThePPC64Target(),
2776                                      createPPCAsmPrinterPass);
2777   TargetRegistry::RegisterAsmPrinter(getThePPC64LETarget(),
2778                                      createPPCAsmPrinterPass);
2779 }
2780