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