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