1 //===-- PPCAsmPrinter.cpp - Print machine instrs to PowerPC assembly ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to PowerPC assembly language. This printer is
12 // the output mechanism used by `llc'.
13 //
14 // Documentation at http://developer.apple.com/documentation/DeveloperTools/
15 // Reference/Assembler/ASMIntroduction/chapter_1_section_1.html
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "PPC.h"
20 #include "InstPrinter/PPCInstPrinter.h"
21 #include "MCTargetDesc/PPCMCExpr.h"
22 #include "MCTargetDesc/PPCPredicates.h"
23 #include "PPCMachineFunctionInfo.h"
24 #include "PPCSubtarget.h"
25 #include "PPCTargetMachine.h"
26 #include "PPCTargetStreamer.h"
27 #include "llvm/ADT/MapVector.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/CodeGen/AsmPrinter.h"
30 #include "llvm/CodeGen/MachineConstantPool.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/StackMaps.h"
37 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DebugInfo.h"
40 #include "llvm/IR/DerivedTypes.h"
41 #include "llvm/IR/Mangler.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCInst.h"
47 #include "llvm/MC/MCInstBuilder.h"
48 #include "llvm/MC/MCSectionELF.h"
49 #include "llvm/MC/MCSectionMachO.h"
50 #include "llvm/MC/MCStreamer.h"
51 #include "llvm/MC/MCSymbolELF.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ELF.h"
54 #include "llvm/Support/ErrorHandling.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/TargetRegistry.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Target/TargetInstrInfo.h"
59 #include "llvm/Target/TargetOptions.h"
60 #include "llvm/Target/TargetRegisterInfo.h"
61 using namespace llvm;
62 
63 #define DEBUG_TYPE "asmprinter"
64 
65 namespace {
66 class PPCAsmPrinter : public AsmPrinter {
67 protected:
68   MapVector<MCSymbol *, MCSymbol *> TOC;
69   const PPCSubtarget *Subtarget;
70   StackMaps SM;
71 
72 public:
73   explicit PPCAsmPrinter(TargetMachine &TM,
74                          std::unique_ptr<MCStreamer> Streamer)
75       : AsmPrinter(TM, std::move(Streamer)), SM(*this) {}
76 
77   StringRef getPassName() const override { return "PowerPC Assembly Printer"; }
78 
79   MCSymbol *lookUpOrCreateTOCEntry(MCSymbol *Sym);
80 
81   virtual bool doInitialization(Module &M) override {
82     if (!TOC.empty())
83       TOC.clear();
84     return AsmPrinter::doInitialization(M);
85     }
86 
87     void EmitInstruction(const MachineInstr *MI) override;
88 
89     void printOperand(const MachineInstr *MI, unsigned OpNo, raw_ostream &O);
90 
91     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
92                          unsigned AsmVariant, const char *ExtraCode,
93                          raw_ostream &O) override;
94     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
95                                unsigned AsmVariant, const char *ExtraCode,
96                                raw_ostream &O) override;
97 
98     void EmitEndOfAsmFile(Module &M) override;
99 
100     void LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI);
101     void LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI);
102     void EmitTlsCall(const MachineInstr *MI, MCSymbolRefExpr::VariantKind VK);
103     bool runOnMachineFunction(MachineFunction &MF) override {
104       Subtarget = &MF.getSubtarget<PPCSubtarget>();
105       return AsmPrinter::runOnMachineFunction(MF);
106     }
107   };
108 
109   /// PPCLinuxAsmPrinter - PowerPC assembly printer, customized for Linux
110   class PPCLinuxAsmPrinter : public PPCAsmPrinter {
111   public:
112     explicit PPCLinuxAsmPrinter(TargetMachine &TM,
113                                 std::unique_ptr<MCStreamer> Streamer)
114         : PPCAsmPrinter(TM, std::move(Streamer)) {}
115 
116     StringRef getPassName() const override {
117       return "Linux PPC Assembly Printer";
118     }
119 
120     bool doFinalization(Module &M) override;
121     void EmitStartOfAsmFile(Module &M) override;
122 
123     void EmitFunctionEntryLabel() override;
124 
125     void EmitFunctionBodyStart() override;
126     void EmitFunctionBodyEnd() override;
127   };
128 
129   /// PPCDarwinAsmPrinter - PowerPC assembly printer, customized for Darwin/Mac
130   /// OS X
131   class PPCDarwinAsmPrinter : public PPCAsmPrinter {
132   public:
133     explicit PPCDarwinAsmPrinter(TargetMachine &TM,
134                                  std::unique_ptr<MCStreamer> Streamer)
135         : PPCAsmPrinter(TM, std::move(Streamer)) {}
136 
137     StringRef getPassName() const override {
138       return "Darwin PPC Assembly Printer";
139     }
140 
141     bool doFinalization(Module &M) override;
142     void EmitStartOfAsmFile(Module &M) override;
143   };
144 } // end of anonymous namespace
145 
146 /// stripRegisterPrefix - This method strips the character prefix from a
147 /// register name so that only the number is left.  Used by for linux asm.
148 static const char *stripRegisterPrefix(const char *RegName) {
149   switch (RegName[0]) {
150     case 'r':
151     case 'f':
152     case 'q': // for QPX
153     case 'v':
154       if (RegName[1] == 's')
155         return RegName + 2;
156       return RegName + 1;
157     case 'c': if (RegName[1] == 'r') return RegName + 2;
158   }
159 
160   return RegName;
161 }
162 
163 void PPCAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
164                                  raw_ostream &O) {
165   const DataLayout &DL = getDataLayout();
166   const MachineOperand &MO = MI->getOperand(OpNo);
167 
168   switch (MO.getType()) {
169   case MachineOperand::MO_Register: {
170     unsigned Reg = MO.getReg();
171 
172     // There are VSX instructions that use VSX register numbering (vs0 - vs63)
173     // as well as those that use VMX register numbering (v0 - v31 which
174     // correspond to vs32 - vs63). If we have an instruction that uses VSX
175     // numbering, we need to convert the VMX registers to VSX registers.
176     // Namely, we print 32-63 when the instruction operates on one of the
177     // VMX registers.
178     // (Please synchronize with PPCInstPrinter::printOperand)
179     if (MI->getDesc().TSFlags & PPCII::UseVSXReg) {
180       if (PPCInstrInfo::isVRRegister(Reg))
181         Reg = PPC::VSX32 + (Reg - PPC::V0);
182       else if (PPCInstrInfo::isVFRegister(Reg))
183         Reg = PPC::VSX32 + (Reg - PPC::VF0);
184     }
185     const char *RegName = PPCInstPrinter::getRegisterName(Reg);
186 
187     // Linux assembler (Others?) does not take register mnemonics.
188     // FIXME - What about special registers used in mfspr/mtspr?
189     if (!Subtarget->isDarwin())
190       RegName = stripRegisterPrefix(RegName);
191     O << RegName;
192     return;
193   }
194   case MachineOperand::MO_Immediate:
195     O << MO.getImm();
196     return;
197 
198   case MachineOperand::MO_MachineBasicBlock:
199     MO.getMBB()->getSymbol()->print(O, MAI);
200     return;
201   case MachineOperand::MO_ConstantPoolIndex:
202     O << DL.getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
203       << MO.getIndex();
204     return;
205   case MachineOperand::MO_BlockAddress:
206     GetBlockAddressSymbol(MO.getBlockAddress())->print(O, MAI);
207     return;
208   case MachineOperand::MO_GlobalAddress: {
209     // Computing the address of a global symbol, not calling it.
210     const GlobalValue *GV = MO.getGlobal();
211     MCSymbol *SymToPrint;
212 
213     // External or weakly linked global variables need non-lazily-resolved stubs
214     if (Subtarget->hasLazyResolverStub(GV)) {
215       SymToPrint = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
216       MachineModuleInfoImpl::StubValueTy &StubSym =
217           MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(
218               SymToPrint);
219       if (!StubSym.getPointer())
220         StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV),
221                                                      !GV->hasInternalLinkage());
222     } else {
223       SymToPrint = getSymbol(GV);
224     }
225 
226     SymToPrint->print(O, MAI);
227 
228     printOffset(MO.getOffset(), O);
229     return;
230   }
231 
232   default:
233     O << "<unknown operand type: " << (unsigned)MO.getType() << ">";
234     return;
235   }
236 }
237 
238 /// PrintAsmOperand - Print out an operand for an inline asm expression.
239 ///
240 bool PPCAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
241                                     unsigned AsmVariant,
242                                     const char *ExtraCode, raw_ostream &O) {
243   // Does this asm operand have a single letter operand modifier?
244   if (ExtraCode && ExtraCode[0]) {
245     if (ExtraCode[1] != 0) return true; // Unknown modifier.
246 
247     switch (ExtraCode[0]) {
248     default:
249       // See if this is a generic print operand
250       return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
251     case 'c': // Don't print "$" before a global var name or constant.
252       break; // PPC never has a prefix.
253     case 'L': // Write second word of DImode reference.
254       // Verify that this operand has two consecutive registers.
255       if (!MI->getOperand(OpNo).isReg() ||
256           OpNo+1 == MI->getNumOperands() ||
257           !MI->getOperand(OpNo+1).isReg())
258         return true;
259       ++OpNo;   // Return the high-part.
260       break;
261     case 'I':
262       // Write 'i' if an integer constant, otherwise nothing.  Used to print
263       // addi vs add, etc.
264       if (MI->getOperand(OpNo).isImm())
265         O << "i";
266       return false;
267     }
268   }
269 
270   printOperand(MI, OpNo, O);
271   return false;
272 }
273 
274 // At the moment, all inline asm memory operands are a single register.
275 // In any case, the output of this routine should always be just one
276 // assembler operand.
277 
278 bool PPCAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
279                                           unsigned AsmVariant,
280                                           const char *ExtraCode,
281                                           raw_ostream &O) {
282   if (ExtraCode && ExtraCode[0]) {
283     if (ExtraCode[1] != 0) return true; // Unknown modifier.
284 
285     switch (ExtraCode[0]) {
286     default: return true;  // Unknown modifier.
287     case 'y': // A memory reference for an X-form instruction
288       {
289         const char *RegName = "r0";
290         if (!Subtarget->isDarwin())
291           RegName = stripRegisterPrefix(RegName);
292         O << RegName << ", ";
293         printOperand(MI, OpNo, O);
294         return false;
295       }
296     case 'U': // Print 'u' for update form.
297     case 'X': // Print 'x' for indexed form.
298     {
299       // FIXME: Currently for PowerPC memory operands are always loaded
300       // into a register, so we never get an update or indexed form.
301       // This is bad even for offset forms, since even if we know we
302       // have a value in -16(r1), we will generate a load into r<n>
303       // and then load from 0(r<n>).  Until that issue is fixed,
304       // tolerate 'U' and 'X' but don't output anything.
305       assert(MI->getOperand(OpNo).isReg());
306       return false;
307     }
308     }
309   }
310 
311   assert(MI->getOperand(OpNo).isReg());
312   O << "0(";
313   printOperand(MI, OpNo, O);
314   O << ")";
315   return false;
316 }
317 
318 /// lookUpOrCreateTOCEntry -- Given a symbol, look up whether a TOC entry
319 /// exists for it.  If not, create one.  Then return a symbol that references
320 /// the TOC entry.
321 MCSymbol *PPCAsmPrinter::lookUpOrCreateTOCEntry(MCSymbol *Sym) {
322   MCSymbol *&TOCEntry = TOC[Sym];
323   if (!TOCEntry)
324     TOCEntry = createTempSymbol("C");
325   return TOCEntry;
326 }
327 
328 void PPCAsmPrinter::EmitEndOfAsmFile(Module &M) {
329   SM.serializeToStackMapSection();
330 }
331 
332 void PPCAsmPrinter::LowerSTACKMAP(StackMaps &SM, const MachineInstr &MI) {
333   unsigned NumNOPBytes = MI.getOperand(1).getImm();
334 
335   SM.recordStackMap(MI);
336   assert(NumNOPBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
337 
338   // Scan ahead to trim the shadow.
339   const MachineBasicBlock &MBB = *MI.getParent();
340   MachineBasicBlock::const_iterator MII(MI);
341   ++MII;
342   while (NumNOPBytes > 0) {
343     if (MII == MBB.end() || MII->isCall() ||
344         MII->getOpcode() == PPC::DBG_VALUE ||
345         MII->getOpcode() == TargetOpcode::PATCHPOINT ||
346         MII->getOpcode() == TargetOpcode::STACKMAP)
347       break;
348     ++MII;
349     NumNOPBytes -= 4;
350   }
351 
352   // Emit nops.
353   for (unsigned i = 0; i < NumNOPBytes; i += 4)
354     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
355 }
356 
357 // Lower a patchpoint of the form:
358 // [<def>], <id>, <numBytes>, <target>, <numArgs>
359 void PPCAsmPrinter::LowerPATCHPOINT(StackMaps &SM, const MachineInstr &MI) {
360   SM.recordPatchPoint(MI);
361   PatchPointOpers Opers(&MI);
362 
363   unsigned EncodedBytes = 0;
364   const MachineOperand &CalleeMO = Opers.getCallTarget();
365 
366   if (CalleeMO.isImm()) {
367     int64_t CallTarget = CalleeMO.getImm();
368     if (CallTarget) {
369       assert((CallTarget & 0xFFFFFFFFFFFF) == CallTarget &&
370              "High 16 bits of call target should be zero.");
371       unsigned ScratchReg = MI.getOperand(Opers.getNextScratchIdx()).getReg();
372       EncodedBytes = 0;
373       // Materialize the jump address:
374       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI8)
375                                       .addReg(ScratchReg)
376                                       .addImm((CallTarget >> 32) & 0xFFFF));
377       ++EncodedBytes;
378       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::RLDIC)
379                                       .addReg(ScratchReg)
380                                       .addReg(ScratchReg)
381                                       .addImm(32).addImm(16));
382       ++EncodedBytes;
383       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORIS8)
384                                       .addReg(ScratchReg)
385                                       .addReg(ScratchReg)
386                                       .addImm((CallTarget >> 16) & 0xFFFF));
387       ++EncodedBytes;
388       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ORI8)
389                                       .addReg(ScratchReg)
390                                       .addReg(ScratchReg)
391                                       .addImm(CallTarget & 0xFFFF));
392 
393       // Save the current TOC pointer before the remote call.
394       int TOCSaveOffset = Subtarget->isELFv2ABI() ? 24 : 40;
395       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::STD)
396                                       .addReg(PPC::X2)
397                                       .addImm(TOCSaveOffset)
398                                       .addReg(PPC::X1));
399       ++EncodedBytes;
400 
401       // If we're on ELFv1, then we need to load the actual function pointer
402       // from the function descriptor.
403       if (!Subtarget->isELFv2ABI()) {
404         // Load the new TOC pointer and the function address, but not r11
405         // (needing this is rare, and loading it here would prevent passing it
406         // via a 'nest' parameter.
407         EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
408                                         .addReg(PPC::X2)
409                                         .addImm(8)
410                                         .addReg(ScratchReg));
411         ++EncodedBytes;
412         EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
413                                         .addReg(ScratchReg)
414                                         .addImm(0)
415                                         .addReg(ScratchReg));
416         ++EncodedBytes;
417       }
418 
419       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MTCTR8)
420                                       .addReg(ScratchReg));
421       ++EncodedBytes;
422       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BCTRL8));
423       ++EncodedBytes;
424 
425       // Restore the TOC pointer after the call.
426       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
427                                       .addReg(PPC::X2)
428                                       .addImm(TOCSaveOffset)
429                                       .addReg(PPC::X1));
430       ++EncodedBytes;
431     }
432   } else if (CalleeMO.isGlobal()) {
433     const GlobalValue *GValue = CalleeMO.getGlobal();
434     MCSymbol *MOSymbol = getSymbol(GValue);
435     const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, OutContext);
436 
437     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL8_NOP)
438                                     .addExpr(SymVar));
439     EncodedBytes += 2;
440   }
441 
442   // Each instruction is 4 bytes.
443   EncodedBytes *= 4;
444 
445   // Emit padding.
446   unsigned NumBytes = Opers.getNumPatchBytes();
447   assert(NumBytes >= EncodedBytes &&
448          "Patchpoint can't request size less than the length of a call.");
449   assert((NumBytes - EncodedBytes) % 4 == 0 &&
450          "Invalid number of NOP bytes requested!");
451   for (unsigned i = EncodedBytes; i < NumBytes; i += 4)
452     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::NOP));
453 }
454 
455 /// EmitTlsCall -- Given a GETtls[ld]ADDR[32] instruction, print a
456 /// call to __tls_get_addr to the current output stream.
457 void PPCAsmPrinter::EmitTlsCall(const MachineInstr *MI,
458                                 MCSymbolRefExpr::VariantKind VK) {
459   StringRef Name = "__tls_get_addr";
460   MCSymbol *TlsGetAddr = OutContext.getOrCreateSymbol(Name);
461   MCSymbolRefExpr::VariantKind Kind = MCSymbolRefExpr::VK_None;
462 
463   assert(MI->getOperand(0).isReg() &&
464          ((Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::X3) ||
465           (!Subtarget->isPPC64() && MI->getOperand(0).getReg() == PPC::R3)) &&
466          "GETtls[ld]ADDR[32] must define GPR3");
467   assert(MI->getOperand(1).isReg() &&
468          ((Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::X3) ||
469           (!Subtarget->isPPC64() && MI->getOperand(1).getReg() == PPC::R3)) &&
470          "GETtls[ld]ADDR[32] must read GPR3");
471 
472   if (!Subtarget->isPPC64() && !Subtarget->isDarwin() &&
473       isPositionIndependent())
474     Kind = MCSymbolRefExpr::VK_PLT;
475   const MCSymbolRefExpr *TlsRef =
476     MCSymbolRefExpr::create(TlsGetAddr, Kind, OutContext);
477   const MachineOperand &MO = MI->getOperand(2);
478   const GlobalValue *GValue = MO.getGlobal();
479   MCSymbol *MOSymbol = getSymbol(GValue);
480   const MCExpr *SymVar = MCSymbolRefExpr::create(MOSymbol, VK, OutContext);
481   EmitToStreamer(*OutStreamer,
482                  MCInstBuilder(Subtarget->isPPC64() ?
483                                PPC::BL8_NOP_TLS : PPC::BL_TLS)
484                  .addExpr(TlsRef)
485                  .addExpr(SymVar));
486 }
487 
488 /// EmitInstruction -- Print out a single PowerPC MI in Darwin syntax to
489 /// the current output stream.
490 ///
491 void PPCAsmPrinter::EmitInstruction(const MachineInstr *MI) {
492   MCInst TmpInst;
493   bool isPPC64 = Subtarget->isPPC64();
494   bool isDarwin = TM.getTargetTriple().isOSDarwin();
495   const Module *M = MF->getFunction()->getParent();
496   PICLevel::Level PL = M->getPICLevel();
497 
498   // Lower multi-instruction pseudo operations.
499   switch (MI->getOpcode()) {
500   default: break;
501   case TargetOpcode::DBG_VALUE:
502     llvm_unreachable("Should be handled target independently");
503   case TargetOpcode::STACKMAP:
504     return LowerSTACKMAP(SM, *MI);
505   case TargetOpcode::PATCHPOINT:
506     return LowerPATCHPOINT(SM, *MI);
507 
508   case PPC::MoveGOTtoLR: {
509     // Transform %LR = MoveGOTtoLR
510     // Into this: bl _GLOBAL_OFFSET_TABLE_@local-4
511     // _GLOBAL_OFFSET_TABLE_@local-4 (instruction preceding
512     // _GLOBAL_OFFSET_TABLE_) has exactly one instruction:
513     //      blrl
514     // This will return the pointer to _GLOBAL_OFFSET_TABLE_@local
515     MCSymbol *GOTSymbol =
516       OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
517     const MCExpr *OffsExpr =
518       MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol,
519                                                       MCSymbolRefExpr::VK_PPC_LOCAL,
520                                                       OutContext),
521                               MCConstantExpr::create(4, OutContext),
522                               OutContext);
523 
524     // Emit the 'bl'.
525     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL).addExpr(OffsExpr));
526     return;
527   }
528   case PPC::MovePCtoLR:
529   case PPC::MovePCtoLR8: {
530     // Transform %LR = MovePCtoLR
531     // Into this, where the label is the PIC base:
532     //     bl L1$pb
533     // L1$pb:
534     MCSymbol *PICBase = MF->getPICBaseSymbol();
535 
536     // Emit the 'bl'.
537     EmitToStreamer(*OutStreamer,
538                    MCInstBuilder(PPC::BL)
539                        // FIXME: We would like an efficient form for this, so we
540                        // don't have to do a lot of extra uniquing.
541                        .addExpr(MCSymbolRefExpr::create(PICBase, OutContext)));
542 
543     // Emit the label.
544     OutStreamer->EmitLabel(PICBase);
545     return;
546   }
547   case PPC::UpdateGBR: {
548     // Transform %Rd = UpdateGBR(%Rt, %Ri)
549     // Into: lwz %Rt, .L0$poff - .L0$pb(%Ri)
550     //       add %Rd, %Rt, %Ri
551     // Get the offset from the GOT Base Register to the GOT
552     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
553     MCSymbol *PICOffset =
554       MF->getInfo<PPCFunctionInfo>()->getPICOffsetSymbol();
555     TmpInst.setOpcode(PPC::LWZ);
556     const MCExpr *Exp =
557       MCSymbolRefExpr::create(PICOffset, MCSymbolRefExpr::VK_None, OutContext);
558     const MCExpr *PB =
559       MCSymbolRefExpr::create(MF->getPICBaseSymbol(),
560                               MCSymbolRefExpr::VK_None,
561                               OutContext);
562     const MCOperand TR = TmpInst.getOperand(1);
563     const MCOperand PICR = TmpInst.getOperand(0);
564 
565     // Step 1: lwz %Rt, .L$poff - .L$pb(%Ri)
566     TmpInst.getOperand(1) =
567         MCOperand::createExpr(MCBinaryExpr::createSub(Exp, PB, OutContext));
568     TmpInst.getOperand(0) = TR;
569     TmpInst.getOperand(2) = PICR;
570     EmitToStreamer(*OutStreamer, TmpInst);
571 
572     TmpInst.setOpcode(PPC::ADD4);
573     TmpInst.getOperand(0) = PICR;
574     TmpInst.getOperand(1) = TR;
575     TmpInst.getOperand(2) = PICR;
576     EmitToStreamer(*OutStreamer, TmpInst);
577     return;
578   }
579   case PPC::LWZtoc: {
580     // Transform %R3 = LWZtoc <ga:@min1>, %R2
581     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
582 
583     // Change the opcode to LWZ, and the global address operand to be a
584     // reference to the GOT entry we will synthesize later.
585     TmpInst.setOpcode(PPC::LWZ);
586     const MachineOperand &MO = MI->getOperand(1);
587 
588     // Map symbol -> label of TOC entry
589     assert(MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress());
590     MCSymbol *MOSymbol = nullptr;
591     if (MO.isGlobal())
592       MOSymbol = getSymbol(MO.getGlobal());
593     else if (MO.isCPI())
594       MOSymbol = GetCPISymbol(MO.getIndex());
595     else if (MO.isJTI())
596       MOSymbol = GetJTISymbol(MO.getIndex());
597     else if (MO.isBlockAddress())
598       MOSymbol = GetBlockAddressSymbol(MO.getBlockAddress());
599 
600     if (PL == PICLevel::SmallPIC) {
601       const MCExpr *Exp =
602         MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_GOT,
603                                 OutContext);
604       TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
605     } else {
606       MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
607 
608       const MCExpr *Exp =
609         MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_None,
610                                 OutContext);
611       const MCExpr *PB =
612         MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")),
613                                                              OutContext);
614       Exp = MCBinaryExpr::createSub(Exp, PB, OutContext);
615       TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
616     }
617     EmitToStreamer(*OutStreamer, TmpInst);
618     return;
619   }
620   case PPC::LDtocJTI:
621   case PPC::LDtocCPT:
622   case PPC::LDtocBA:
623   case PPC::LDtoc: {
624     // Transform %X3 = LDtoc <ga:@min1>, %X2
625     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
626 
627     // Change the opcode to LD, and the global address operand to be a
628     // reference to the TOC entry we will synthesize later.
629     TmpInst.setOpcode(PPC::LD);
630     const MachineOperand &MO = MI->getOperand(1);
631 
632     // Map symbol -> label of TOC entry
633     assert(MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isBlockAddress());
634     MCSymbol *MOSymbol = nullptr;
635     if (MO.isGlobal())
636       MOSymbol = getSymbol(MO.getGlobal());
637     else if (MO.isCPI())
638       MOSymbol = GetCPISymbol(MO.getIndex());
639     else if (MO.isJTI())
640       MOSymbol = GetJTISymbol(MO.getIndex());
641     else if (MO.isBlockAddress())
642       MOSymbol = GetBlockAddressSymbol(MO.getBlockAddress());
643 
644     MCSymbol *TOCEntry = lookUpOrCreateTOCEntry(MOSymbol);
645 
646     const MCExpr *Exp =
647       MCSymbolRefExpr::create(TOCEntry, MCSymbolRefExpr::VK_PPC_TOC,
648                               OutContext);
649     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
650     EmitToStreamer(*OutStreamer, TmpInst);
651     return;
652   }
653 
654   case PPC::ADDIStocHA: {
655     // Transform %Xd = ADDIStocHA %X2, <ga:@sym>
656     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
657 
658     // Change the opcode to ADDIS8.  If the global address is external, has
659     // common linkage, is a non-local function address, or is a jump table
660     // address, then generate a TOC entry and reference that.  Otherwise
661     // reference the symbol directly.
662     TmpInst.setOpcode(PPC::ADDIS8);
663     const MachineOperand &MO = MI->getOperand(2);
664     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() ||
665             MO.isBlockAddress()) &&
666            "Invalid operand for ADDIStocHA!");
667     MCSymbol *MOSymbol = nullptr;
668     bool GlobalToc = false;
669 
670     if (MO.isGlobal()) {
671       const GlobalValue *GV = MO.getGlobal();
672       MOSymbol = getSymbol(GV);
673       unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
674       GlobalToc = (GVFlags & PPCII::MO_NLP_FLAG);
675     } else if (MO.isCPI()) {
676       MOSymbol = GetCPISymbol(MO.getIndex());
677     } else if (MO.isJTI()) {
678       MOSymbol = GetJTISymbol(MO.getIndex());
679     } else if (MO.isBlockAddress()) {
680       MOSymbol = GetBlockAddressSymbol(MO.getBlockAddress());
681     }
682 
683     if (GlobalToc || MO.isJTI() || MO.isBlockAddress() ||
684         TM.getCodeModel() == CodeModel::Large)
685       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
686 
687     const MCExpr *Exp =
688       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC_HA,
689                               OutContext);
690 
691     if (!MO.isJTI() && MO.getOffset())
692       Exp = MCBinaryExpr::createAdd(Exp,
693                                     MCConstantExpr::create(MO.getOffset(),
694                                                            OutContext),
695                                     OutContext);
696 
697     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
698     EmitToStreamer(*OutStreamer, TmpInst);
699     return;
700   }
701   case PPC::LDtocL: {
702     // Transform %Xd = LDtocL <ga:@sym>, %Xs
703     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
704 
705     // Change the opcode to LD.  If the global address is external, has
706     // common linkage, or is a jump table address, then reference the
707     // associated TOC entry.  Otherwise reference the symbol directly.
708     TmpInst.setOpcode(PPC::LD);
709     const MachineOperand &MO = MI->getOperand(1);
710     assert((MO.isGlobal() || MO.isCPI() || MO.isJTI() ||
711             MO.isBlockAddress()) &&
712            "Invalid operand for LDtocL!");
713     MCSymbol *MOSymbol = nullptr;
714 
715     if (MO.isJTI())
716       MOSymbol = lookUpOrCreateTOCEntry(GetJTISymbol(MO.getIndex()));
717     else if (MO.isBlockAddress()) {
718       MOSymbol = GetBlockAddressSymbol(MO.getBlockAddress());
719       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
720     }
721     else if (MO.isCPI()) {
722       MOSymbol = GetCPISymbol(MO.getIndex());
723       if (TM.getCodeModel() == CodeModel::Large)
724         MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
725     }
726     else if (MO.isGlobal()) {
727       const GlobalValue *GV = MO.getGlobal();
728       MOSymbol = getSymbol(GV);
729       DEBUG(
730         unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
731         assert((GVFlags & PPCII::MO_NLP_FLAG) &&
732                "LDtocL used on symbol that could be accessed directly is "
733                "invalid. Must match ADDIStocHA."));
734       MOSymbol = lookUpOrCreateTOCEntry(MOSymbol);
735     }
736 
737     const MCExpr *Exp =
738       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC_LO,
739                               OutContext);
740     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
741     EmitToStreamer(*OutStreamer, TmpInst);
742     return;
743   }
744   case PPC::ADDItocL: {
745     // Transform %Xd = ADDItocL %Xs, <ga:@sym>
746     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
747 
748     // Change the opcode to ADDI8.  If the global address is external, then
749     // generate a TOC entry and reference that.  Otherwise reference the
750     // symbol directly.
751     TmpInst.setOpcode(PPC::ADDI8);
752     const MachineOperand &MO = MI->getOperand(2);
753     assert((MO.isGlobal() || MO.isCPI()) && "Invalid operand for ADDItocL");
754     MCSymbol *MOSymbol = nullptr;
755 
756     if (MO.isGlobal()) {
757       const GlobalValue *GV = MO.getGlobal();
758       DEBUG(
759         unsigned char GVFlags = Subtarget->classifyGlobalReference(GV);
760         assert (
761             !(GVFlags & PPCII::MO_NLP_FLAG) &&
762             "Interposable definitions must use indirect access."));
763       MOSymbol = getSymbol(GV);
764     } else if (MO.isCPI()) {
765       MOSymbol = GetCPISymbol(MO.getIndex());
766     }
767 
768     const MCExpr *Exp =
769       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_TOC_LO,
770                               OutContext);
771     TmpInst.getOperand(2) = MCOperand::createExpr(Exp);
772     EmitToStreamer(*OutStreamer, TmpInst);
773     return;
774   }
775   case PPC::ADDISgotTprelHA: {
776     // Transform: %Xd = ADDISgotTprelHA %X2, <ga:@sym>
777     // Into:      %Xd = ADDIS8 %X2, sym@got@tlsgd@ha
778     assert(Subtarget->isPPC64() && "Not supported for 32-bit PowerPC");
779     const MachineOperand &MO = MI->getOperand(2);
780     const GlobalValue *GValue = MO.getGlobal();
781     MCSymbol *MOSymbol = getSymbol(GValue);
782     const MCExpr *SymGotTprel =
783       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_HA,
784                               OutContext);
785     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
786                                  .addReg(MI->getOperand(0).getReg())
787                                  .addReg(MI->getOperand(1).getReg())
788                                  .addExpr(SymGotTprel));
789     return;
790   }
791   case PPC::LDgotTprelL:
792   case PPC::LDgotTprelL32: {
793     // Transform %Xd = LDgotTprelL <ga:@sym>, %Xs
794     LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
795 
796     // Change the opcode to LD.
797     TmpInst.setOpcode(isPPC64 ? PPC::LD : PPC::LWZ);
798     const MachineOperand &MO = MI->getOperand(1);
799     const GlobalValue *GValue = MO.getGlobal();
800     MCSymbol *MOSymbol = getSymbol(GValue);
801     const MCExpr *Exp =
802       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TPREL_LO,
803                               OutContext);
804     TmpInst.getOperand(1) = MCOperand::createExpr(Exp);
805     EmitToStreamer(*OutStreamer, TmpInst);
806     return;
807   }
808 
809   case PPC::PPC32PICGOT: {
810     MCSymbol *GOTSymbol = OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
811     MCSymbol *GOTRef = OutContext.createTempSymbol();
812     MCSymbol *NextInstr = OutContext.createTempSymbol();
813 
814     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::BL)
815       // FIXME: We would like an efficient form for this, so we don't have to do
816       // a lot of extra uniquing.
817       .addExpr(MCSymbolRefExpr::create(NextInstr, OutContext)));
818     const MCExpr *OffsExpr =
819       MCBinaryExpr::createSub(MCSymbolRefExpr::create(GOTSymbol, OutContext),
820                                 MCSymbolRefExpr::create(GOTRef, OutContext),
821         OutContext);
822     OutStreamer->EmitLabel(GOTRef);
823     OutStreamer->EmitValue(OffsExpr, 4);
824     OutStreamer->EmitLabel(NextInstr);
825     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::MFLR)
826                                  .addReg(MI->getOperand(0).getReg()));
827     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LWZ)
828                                  .addReg(MI->getOperand(1).getReg())
829                                  .addImm(0)
830                                  .addReg(MI->getOperand(0).getReg()));
831     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD4)
832                                  .addReg(MI->getOperand(0).getReg())
833                                  .addReg(MI->getOperand(1).getReg())
834                                  .addReg(MI->getOperand(0).getReg()));
835     return;
836   }
837   case PPC::PPC32GOT: {
838     MCSymbol *GOTSymbol =
839         OutContext.getOrCreateSymbol(StringRef("_GLOBAL_OFFSET_TABLE_"));
840     const MCExpr *SymGotTlsL = MCSymbolRefExpr::create(
841         GOTSymbol, MCSymbolRefExpr::VK_PPC_LO, OutContext);
842     const MCExpr *SymGotTlsHA = MCSymbolRefExpr::create(
843         GOTSymbol, MCSymbolRefExpr::VK_PPC_HA, OutContext);
844     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LI)
845                                  .addReg(MI->getOperand(0).getReg())
846                                  .addExpr(SymGotTlsL));
847     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
848                                  .addReg(MI->getOperand(0).getReg())
849                                  .addReg(MI->getOperand(0).getReg())
850                                  .addExpr(SymGotTlsHA));
851     return;
852   }
853   case PPC::ADDIStlsgdHA: {
854     // Transform: %Xd = ADDIStlsgdHA %X2, <ga:@sym>
855     // Into:      %Xd = ADDIS8 %X2, sym@got@tlsgd@ha
856     assert(Subtarget->isPPC64() && "Not supported for 32-bit PowerPC");
857     const MachineOperand &MO = MI->getOperand(2);
858     const GlobalValue *GValue = MO.getGlobal();
859     MCSymbol *MOSymbol = getSymbol(GValue);
860     const MCExpr *SymGotTlsGD =
861       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSGD_HA,
862                               OutContext);
863     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
864                                  .addReg(MI->getOperand(0).getReg())
865                                  .addReg(MI->getOperand(1).getReg())
866                                  .addExpr(SymGotTlsGD));
867     return;
868   }
869   case PPC::ADDItlsgdL:
870     // Transform: %Xd = ADDItlsgdL %Xs, <ga:@sym>
871     // Into:      %Xd = ADDI8 %Xs, sym@got@tlsgd@l
872   case PPC::ADDItlsgdL32: {
873     // Transform: %Rd = ADDItlsgdL32 %Rs, <ga:@sym>
874     // Into:      %Rd = ADDI %Rs, sym@got@tlsgd
875     const MachineOperand &MO = MI->getOperand(2);
876     const GlobalValue *GValue = MO.getGlobal();
877     MCSymbol *MOSymbol = getSymbol(GValue);
878     const MCExpr *SymGotTlsGD = MCSymbolRefExpr::create(
879         MOSymbol, Subtarget->isPPC64() ? MCSymbolRefExpr::VK_PPC_GOT_TLSGD_LO
880                                        : MCSymbolRefExpr::VK_PPC_GOT_TLSGD,
881         OutContext);
882     EmitToStreamer(*OutStreamer,
883                    MCInstBuilder(Subtarget->isPPC64() ? PPC::ADDI8 : PPC::ADDI)
884                    .addReg(MI->getOperand(0).getReg())
885                    .addReg(MI->getOperand(1).getReg())
886                    .addExpr(SymGotTlsGD));
887     return;
888   }
889   case PPC::GETtlsADDR:
890     // Transform: %X3 = GETtlsADDR %X3, <ga:@sym>
891     // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsgd)
892   case PPC::GETtlsADDR32: {
893     // Transform: %R3 = GETtlsADDR32 %R3, <ga:@sym>
894     // Into: BL_TLS __tls_get_addr(sym at tlsgd)@PLT
895     EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSGD);
896     return;
897   }
898   case PPC::ADDIStlsldHA: {
899     // Transform: %Xd = ADDIStlsldHA %X2, <ga:@sym>
900     // Into:      %Xd = ADDIS8 %X2, sym@got@tlsld@ha
901     assert(Subtarget->isPPC64() && "Not supported for 32-bit PowerPC");
902     const MachineOperand &MO = MI->getOperand(2);
903     const GlobalValue *GValue = MO.getGlobal();
904     MCSymbol *MOSymbol = getSymbol(GValue);
905     const MCExpr *SymGotTlsLD =
906       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_GOT_TLSLD_HA,
907                               OutContext);
908     EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS8)
909                                  .addReg(MI->getOperand(0).getReg())
910                                  .addReg(MI->getOperand(1).getReg())
911                                  .addExpr(SymGotTlsLD));
912     return;
913   }
914   case PPC::ADDItlsldL:
915     // Transform: %Xd = ADDItlsldL %Xs, <ga:@sym>
916     // Into:      %Xd = ADDI8 %Xs, sym@got@tlsld@l
917   case PPC::ADDItlsldL32: {
918     // Transform: %Rd = ADDItlsldL32 %Rs, <ga:@sym>
919     // Into:      %Rd = ADDI %Rs, sym@got@tlsld
920     const MachineOperand &MO = MI->getOperand(2);
921     const GlobalValue *GValue = MO.getGlobal();
922     MCSymbol *MOSymbol = getSymbol(GValue);
923     const MCExpr *SymGotTlsLD = MCSymbolRefExpr::create(
924         MOSymbol, Subtarget->isPPC64() ? MCSymbolRefExpr::VK_PPC_GOT_TLSLD_LO
925                                        : MCSymbolRefExpr::VK_PPC_GOT_TLSLD,
926         OutContext);
927     EmitToStreamer(*OutStreamer,
928                    MCInstBuilder(Subtarget->isPPC64() ? PPC::ADDI8 : PPC::ADDI)
929                        .addReg(MI->getOperand(0).getReg())
930                        .addReg(MI->getOperand(1).getReg())
931                        .addExpr(SymGotTlsLD));
932     return;
933   }
934   case PPC::GETtlsldADDR:
935     // Transform: %X3 = GETtlsldADDR %X3, <ga:@sym>
936     // Into: BL8_NOP_TLS __tls_get_addr(sym at tlsld)
937   case PPC::GETtlsldADDR32: {
938     // Transform: %R3 = GETtlsldADDR32 %R3, <ga:@sym>
939     // Into: BL_TLS __tls_get_addr(sym at tlsld)@PLT
940     EmitTlsCall(MI, MCSymbolRefExpr::VK_PPC_TLSLD);
941     return;
942   }
943   case PPC::ADDISdtprelHA:
944     // Transform: %Xd = ADDISdtprelHA %Xs, <ga:@sym>
945     // Into:      %Xd = ADDIS8 %Xs, sym@dtprel@ha
946   case PPC::ADDISdtprelHA32: {
947     // Transform: %Rd = ADDISdtprelHA32 %Rs, <ga:@sym>
948     // Into:      %Rd = ADDIS %Rs, sym@dtprel@ha
949     const MachineOperand &MO = MI->getOperand(2);
950     const GlobalValue *GValue = MO.getGlobal();
951     MCSymbol *MOSymbol = getSymbol(GValue);
952     const MCExpr *SymDtprel =
953       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_HA,
954                               OutContext);
955     EmitToStreamer(
956         *OutStreamer,
957         MCInstBuilder(Subtarget->isPPC64() ? PPC::ADDIS8 : PPC::ADDIS)
958             .addReg(MI->getOperand(0).getReg())
959             .addReg(MI->getOperand(1).getReg())
960             .addExpr(SymDtprel));
961     return;
962   }
963   case PPC::ADDIdtprelL:
964     // Transform: %Xd = ADDIdtprelL %Xs, <ga:@sym>
965     // Into:      %Xd = ADDI8 %Xs, sym@dtprel@l
966   case PPC::ADDIdtprelL32: {
967     // Transform: %Rd = ADDIdtprelL32 %Rs, <ga:@sym>
968     // Into:      %Rd = ADDI %Rs, sym@dtprel@l
969     const MachineOperand &MO = MI->getOperand(2);
970     const GlobalValue *GValue = MO.getGlobal();
971     MCSymbol *MOSymbol = getSymbol(GValue);
972     const MCExpr *SymDtprel =
973       MCSymbolRefExpr::create(MOSymbol, MCSymbolRefExpr::VK_PPC_DTPREL_LO,
974                               OutContext);
975     EmitToStreamer(*OutStreamer,
976                    MCInstBuilder(Subtarget->isPPC64() ? PPC::ADDI8 : PPC::ADDI)
977                        .addReg(MI->getOperand(0).getReg())
978                        .addReg(MI->getOperand(1).getReg())
979                        .addExpr(SymDtprel));
980     return;
981   }
982   case PPC::MFOCRF:
983   case PPC::MFOCRF8:
984     if (!Subtarget->hasMFOCRF()) {
985       // Transform: %R3 = MFOCRF %CR7
986       // Into:      %R3 = MFCR   ;; cr7
987       unsigned NewOpcode =
988         MI->getOpcode() == PPC::MFOCRF ? PPC::MFCR : PPC::MFCR8;
989       OutStreamer->AddComment(PPCInstPrinter::
990                               getRegisterName(MI->getOperand(1).getReg()));
991       EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
992                                   .addReg(MI->getOperand(0).getReg()));
993       return;
994     }
995     break;
996   case PPC::MTOCRF:
997   case PPC::MTOCRF8:
998     if (!Subtarget->hasMFOCRF()) {
999       // Transform: %CR7 = MTOCRF %R3
1000       // Into:      MTCRF mask, %R3 ;; cr7
1001       unsigned NewOpcode =
1002         MI->getOpcode() == PPC::MTOCRF ? PPC::MTCRF : PPC::MTCRF8;
1003       unsigned Mask = 0x80 >> OutContext.getRegisterInfo()
1004                               ->getEncodingValue(MI->getOperand(0).getReg());
1005       OutStreamer->AddComment(PPCInstPrinter::
1006                               getRegisterName(MI->getOperand(0).getReg()));
1007       EmitToStreamer(*OutStreamer, MCInstBuilder(NewOpcode)
1008                                      .addImm(Mask)
1009                                      .addReg(MI->getOperand(1).getReg()));
1010       return;
1011     }
1012     break;
1013   case PPC::LD:
1014   case PPC::STD:
1015   case PPC::LWA_32:
1016   case PPC::LWA: {
1017     // Verify alignment is legal, so we don't create relocations
1018     // that can't be supported.
1019     // FIXME:  This test is currently disabled for Darwin.  The test
1020     // suite shows a handful of test cases that fail this check for
1021     // Darwin.  Those need to be investigated before this sanity test
1022     // can be enabled for those subtargets.
1023     if (!Subtarget->isDarwin()) {
1024       unsigned OpNum = (MI->getOpcode() == PPC::STD) ? 2 : 1;
1025       const MachineOperand &MO = MI->getOperand(OpNum);
1026       if (MO.isGlobal() && MO.getGlobal()->getAlignment() < 4)
1027         llvm_unreachable("Global must be word-aligned for LD, STD, LWA!");
1028     }
1029     // Now process the instruction normally.
1030     break;
1031   }
1032   }
1033 
1034   LowerPPCMachineInstrToMCInst(MI, TmpInst, *this, isDarwin);
1035   EmitToStreamer(*OutStreamer, TmpInst);
1036 }
1037 
1038 void PPCLinuxAsmPrinter::EmitStartOfAsmFile(Module &M) {
1039   if (static_cast<const PPCTargetMachine &>(TM).isELFv2ABI()) {
1040     PPCTargetStreamer *TS =
1041       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1042 
1043     if (TS)
1044       TS->emitAbiVersion(2);
1045   }
1046 
1047   if (static_cast<const PPCTargetMachine &>(TM).isPPC64() ||
1048       !isPositionIndependent())
1049     return AsmPrinter::EmitStartOfAsmFile(M);
1050 
1051   if (M.getPICLevel() == PICLevel::SmallPIC)
1052     return AsmPrinter::EmitStartOfAsmFile(M);
1053 
1054   OutStreamer->SwitchSection(OutContext.getELFSection(
1055       ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC));
1056 
1057   MCSymbol *TOCSym = OutContext.getOrCreateSymbol(Twine(".LTOC"));
1058   MCSymbol *CurrentPos = OutContext.createTempSymbol();
1059 
1060   OutStreamer->EmitLabel(CurrentPos);
1061 
1062   // The GOT pointer points to the middle of the GOT, in order to reference the
1063   // entire 64kB range.  0x8000 is the midpoint.
1064   const MCExpr *tocExpr =
1065     MCBinaryExpr::createAdd(MCSymbolRefExpr::create(CurrentPos, OutContext),
1066                             MCConstantExpr::create(0x8000, OutContext),
1067                             OutContext);
1068 
1069   OutStreamer->EmitAssignment(TOCSym, tocExpr);
1070 
1071   OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
1072 }
1073 
1074 void PPCLinuxAsmPrinter::EmitFunctionEntryLabel() {
1075   // linux/ppc32 - Normal entry label.
1076   if (!Subtarget->isPPC64() &&
1077       (!isPositionIndependent() ||
1078        MF->getFunction()->getParent()->getPICLevel() == PICLevel::SmallPIC))
1079     return AsmPrinter::EmitFunctionEntryLabel();
1080 
1081   if (!Subtarget->isPPC64()) {
1082     const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1083     if (PPCFI->usesPICBase()) {
1084       MCSymbol *RelocSymbol = PPCFI->getPICOffsetSymbol();
1085       MCSymbol *PICBase = MF->getPICBaseSymbol();
1086       OutStreamer->EmitLabel(RelocSymbol);
1087 
1088       const MCExpr *OffsExpr =
1089         MCBinaryExpr::createSub(
1090           MCSymbolRefExpr::create(OutContext.getOrCreateSymbol(Twine(".LTOC")),
1091                                                                OutContext),
1092                                   MCSymbolRefExpr::create(PICBase, OutContext),
1093           OutContext);
1094       OutStreamer->EmitValue(OffsExpr, 4);
1095       OutStreamer->EmitLabel(CurrentFnSym);
1096       return;
1097     } else
1098       return AsmPrinter::EmitFunctionEntryLabel();
1099   }
1100 
1101   // ELFv2 ABI - Normal entry label.
1102   if (Subtarget->isELFv2ABI()) {
1103     // In the Large code model, we allow arbitrary displacements between
1104     // the text section and its associated TOC section.  We place the
1105     // full 8-byte offset to the TOC in memory immediatedly preceding
1106     // the function global entry point.
1107     if (TM.getCodeModel() == CodeModel::Large
1108         && !MF->getRegInfo().use_empty(PPC::X2)) {
1109       const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1110 
1111       MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1112       MCSymbol *GlobalEPSymbol = PPCFI->getGlobalEPSymbol();
1113       const MCExpr *TOCDeltaExpr =
1114         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1115                                 MCSymbolRefExpr::create(GlobalEPSymbol,
1116                                                         OutContext),
1117                                 OutContext);
1118 
1119       OutStreamer->EmitLabel(PPCFI->getTOCOffsetSymbol());
1120       OutStreamer->EmitValue(TOCDeltaExpr, 8);
1121     }
1122     return AsmPrinter::EmitFunctionEntryLabel();
1123   }
1124 
1125   // Emit an official procedure descriptor.
1126   MCSectionSubPair Current = OutStreamer->getCurrentSection();
1127   MCSectionELF *Section = OutStreamer->getContext().getELFSection(
1128       ".opd", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1129   OutStreamer->SwitchSection(Section);
1130   OutStreamer->EmitLabel(CurrentFnSym);
1131   OutStreamer->EmitValueToAlignment(8);
1132   MCSymbol *Symbol1 = CurrentFnSymForSize;
1133   // Generates a R_PPC64_ADDR64 (from FK_DATA_8) relocation for the function
1134   // entry point.
1135   OutStreamer->EmitValue(MCSymbolRefExpr::create(Symbol1, OutContext),
1136                          8 /*size*/);
1137   MCSymbol *Symbol2 = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1138   // Generates a R_PPC64_TOC relocation for TOC base insertion.
1139   OutStreamer->EmitValue(
1140     MCSymbolRefExpr::create(Symbol2, MCSymbolRefExpr::VK_PPC_TOCBASE, OutContext),
1141     8/*size*/);
1142   // Emit a null environment pointer.
1143   OutStreamer->EmitIntValue(0, 8 /* size */);
1144   OutStreamer->SwitchSection(Current.first, Current.second);
1145 }
1146 
1147 bool PPCLinuxAsmPrinter::doFinalization(Module &M) {
1148   const DataLayout &DL = getDataLayout();
1149 
1150   bool isPPC64 = DL.getPointerSizeInBits() == 64;
1151 
1152   PPCTargetStreamer &TS =
1153       static_cast<PPCTargetStreamer &>(*OutStreamer->getTargetStreamer());
1154 
1155   if (!TOC.empty()) {
1156     MCSectionELF *Section;
1157 
1158     if (isPPC64)
1159       Section = OutStreamer->getContext().getELFSection(
1160           ".toc", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1161         else
1162           Section = OutStreamer->getContext().getELFSection(
1163               ".got2", ELF::SHT_PROGBITS, ELF::SHF_WRITE | ELF::SHF_ALLOC);
1164     OutStreamer->SwitchSection(Section);
1165 
1166     for (MapVector<MCSymbol*, MCSymbol*>::iterator I = TOC.begin(),
1167          E = TOC.end(); I != E; ++I) {
1168       OutStreamer->EmitLabel(I->second);
1169       MCSymbol *S = I->first;
1170       if (isPPC64) {
1171         TS.emitTCEntry(*S);
1172       } else {
1173         OutStreamer->EmitValueToAlignment(4);
1174         OutStreamer->EmitSymbolValue(S, 4);
1175       }
1176     }
1177   }
1178 
1179   return AsmPrinter::doFinalization(M);
1180 }
1181 
1182 /// EmitFunctionBodyStart - Emit a global entry point prefix for ELFv2.
1183 void PPCLinuxAsmPrinter::EmitFunctionBodyStart() {
1184   // In the ELFv2 ABI, in functions that use the TOC register, we need to
1185   // provide two entry points.  The ABI guarantees that when calling the
1186   // local entry point, r2 is set up by the caller to contain the TOC base
1187   // for this function, and when calling the global entry point, r12 is set
1188   // up by the caller to hold the address of the global entry point.  We
1189   // thus emit a prefix sequence along the following lines:
1190   //
1191   // func:
1192   // .Lfunc_gepNN:
1193   //         # global entry point
1194   //         addis r2,r12,(.TOC.-.Lfunc_gepNN)@ha
1195   //         addi  r2,r2,(.TOC.-.Lfunc_gepNN)@l
1196   // .Lfunc_lepNN:
1197   //         .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1198   //         # local entry point, followed by function body
1199   //
1200   // For the Large code model, we create
1201   //
1202   // .Lfunc_tocNN:
1203   //         .quad .TOC.-.Lfunc_gepNN      # done by EmitFunctionEntryLabel
1204   // func:
1205   // .Lfunc_gepNN:
1206   //         # global entry point
1207   //         ld    r2,.Lfunc_tocNN-.Lfunc_gepNN(r12)
1208   //         add   r2,r2,r12
1209   // .Lfunc_lepNN:
1210   //         .localentry func, .Lfunc_lepNN-.Lfunc_gepNN
1211   //         # local entry point, followed by function body
1212   //
1213   // This ensures we have r2 set up correctly while executing the function
1214   // body, no matter which entry point is called.
1215   if (Subtarget->isELFv2ABI()
1216       // Only do all that if the function uses r2 in the first place.
1217       && !MF->getRegInfo().use_empty(PPC::X2)) {
1218     // Note: The logic here must be synchronized with the code in the
1219     // branch-selection pass which sets the offset of the first block in the
1220     // function. This matters because it affects the alignment.
1221     const PPCFunctionInfo *PPCFI = MF->getInfo<PPCFunctionInfo>();
1222 
1223     MCSymbol *GlobalEntryLabel = PPCFI->getGlobalEPSymbol();
1224     OutStreamer->EmitLabel(GlobalEntryLabel);
1225     const MCSymbolRefExpr *GlobalEntryLabelExp =
1226       MCSymbolRefExpr::create(GlobalEntryLabel, OutContext);
1227 
1228     if (TM.getCodeModel() != CodeModel::Large) {
1229       MCSymbol *TOCSymbol = OutContext.getOrCreateSymbol(StringRef(".TOC."));
1230       const MCExpr *TOCDeltaExpr =
1231         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCSymbol, OutContext),
1232                                 GlobalEntryLabelExp, OutContext);
1233 
1234       const MCExpr *TOCDeltaHi =
1235         PPCMCExpr::createHa(TOCDeltaExpr, false, OutContext);
1236       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDIS)
1237                                    .addReg(PPC::X2)
1238                                    .addReg(PPC::X12)
1239                                    .addExpr(TOCDeltaHi));
1240 
1241       const MCExpr *TOCDeltaLo =
1242         PPCMCExpr::createLo(TOCDeltaExpr, false, OutContext);
1243       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADDI)
1244                                    .addReg(PPC::X2)
1245                                    .addReg(PPC::X2)
1246                                    .addExpr(TOCDeltaLo));
1247     } else {
1248       MCSymbol *TOCOffset = PPCFI->getTOCOffsetSymbol();
1249       const MCExpr *TOCOffsetDeltaExpr =
1250         MCBinaryExpr::createSub(MCSymbolRefExpr::create(TOCOffset, OutContext),
1251                                 GlobalEntryLabelExp, OutContext);
1252 
1253       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::LD)
1254                                    .addReg(PPC::X2)
1255                                    .addExpr(TOCOffsetDeltaExpr)
1256                                    .addReg(PPC::X12));
1257       EmitToStreamer(*OutStreamer, MCInstBuilder(PPC::ADD8)
1258                                    .addReg(PPC::X2)
1259                                    .addReg(PPC::X2)
1260                                    .addReg(PPC::X12));
1261     }
1262 
1263     MCSymbol *LocalEntryLabel = PPCFI->getLocalEPSymbol();
1264     OutStreamer->EmitLabel(LocalEntryLabel);
1265     const MCSymbolRefExpr *LocalEntryLabelExp =
1266        MCSymbolRefExpr::create(LocalEntryLabel, OutContext);
1267     const MCExpr *LocalOffsetExp =
1268       MCBinaryExpr::createSub(LocalEntryLabelExp,
1269                               GlobalEntryLabelExp, OutContext);
1270 
1271     PPCTargetStreamer *TS =
1272       static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1273 
1274     if (TS)
1275       TS->emitLocalEntry(cast<MCSymbolELF>(CurrentFnSym), LocalOffsetExp);
1276   }
1277 }
1278 
1279 /// EmitFunctionBodyEnd - Print the traceback table before the .size
1280 /// directive.
1281 ///
1282 void PPCLinuxAsmPrinter::EmitFunctionBodyEnd() {
1283   // Only the 64-bit target requires a traceback table.  For now,
1284   // we only emit the word of zeroes that GDB requires to find
1285   // the end of the function, and zeroes for the eight-byte
1286   // mandatory fields.
1287   // FIXME: We should fill in the eight-byte mandatory fields as described in
1288   // the PPC64 ELF ABI (this is a low-priority item because GDB does not
1289   // currently make use of these fields).
1290   if (Subtarget->isPPC64()) {
1291     OutStreamer->EmitIntValue(0, 4/*size*/);
1292     OutStreamer->EmitIntValue(0, 8/*size*/);
1293   }
1294 }
1295 
1296 void PPCDarwinAsmPrinter::EmitStartOfAsmFile(Module &M) {
1297   static const char *const CPUDirectives[] = {
1298     "",
1299     "ppc",
1300     "ppc440",
1301     "ppc601",
1302     "ppc602",
1303     "ppc603",
1304     "ppc7400",
1305     "ppc750",
1306     "ppc970",
1307     "ppcA2",
1308     "ppce500mc",
1309     "ppce5500",
1310     "power3",
1311     "power4",
1312     "power5",
1313     "power5x",
1314     "power6",
1315     "power6x",
1316     "power7",
1317     // FIXME: why is power8 missing here?
1318     "ppc64",
1319     "ppc64le",
1320     "power9"
1321   };
1322 
1323   // Get the numerically largest directive.
1324   // FIXME: How should we merge darwin directives?
1325   unsigned Directive = PPC::DIR_NONE;
1326   for (const Function &F : M) {
1327     const PPCSubtarget &STI = TM.getSubtarget<PPCSubtarget>(F);
1328     unsigned FDir = STI.getDarwinDirective();
1329     Directive = Directive > FDir ? FDir : STI.getDarwinDirective();
1330     if (STI.hasMFOCRF() && Directive < PPC::DIR_970)
1331       Directive = PPC::DIR_970;
1332     if (STI.hasAltivec() && Directive < PPC::DIR_7400)
1333       Directive = PPC::DIR_7400;
1334     if (STI.isPPC64() && Directive < PPC::DIR_64)
1335       Directive = PPC::DIR_64;
1336   }
1337 
1338   assert(Directive <= PPC::DIR_64 && "Directive out of range.");
1339 
1340   assert(Directive < array_lengthof(CPUDirectives) &&
1341          "CPUDirectives[] might not be up-to-date!");
1342   PPCTargetStreamer &TStreamer =
1343       *static_cast<PPCTargetStreamer *>(OutStreamer->getTargetStreamer());
1344   TStreamer.emitMachine(CPUDirectives[Directive]);
1345 
1346   // Prime text sections so they are adjacent.  This reduces the likelihood a
1347   // large data or debug section causes a branch to exceed 16M limit.
1348   const TargetLoweringObjectFileMachO &TLOFMacho =
1349       static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
1350   OutStreamer->SwitchSection(TLOFMacho.getTextCoalSection());
1351   if (TM.getRelocationModel() == Reloc::PIC_) {
1352     OutStreamer->SwitchSection(
1353            OutContext.getMachOSection("__TEXT", "__picsymbolstub1",
1354                                       MachO::S_SYMBOL_STUBS |
1355                                       MachO::S_ATTR_PURE_INSTRUCTIONS,
1356                                       32, SectionKind::getText()));
1357   } else if (TM.getRelocationModel() == Reloc::DynamicNoPIC) {
1358     OutStreamer->SwitchSection(
1359            OutContext.getMachOSection("__TEXT","__symbol_stub1",
1360                                       MachO::S_SYMBOL_STUBS |
1361                                       MachO::S_ATTR_PURE_INSTRUCTIONS,
1362                                       16, SectionKind::getText()));
1363   }
1364   OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
1365 }
1366 
1367 bool PPCDarwinAsmPrinter::doFinalization(Module &M) {
1368   bool isPPC64 = getDataLayout().getPointerSizeInBits() == 64;
1369 
1370   // Darwin/PPC always uses mach-o.
1371   const TargetLoweringObjectFileMachO &TLOFMacho =
1372       static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
1373   MachineModuleInfoMachO &MMIMacho =
1374       MMI->getObjFileInfo<MachineModuleInfoMachO>();
1375 
1376   if (MAI->doesSupportExceptionHandling() && MMI) {
1377     // Add the (possibly multiple) personalities to the set of global values.
1378     // Only referenced functions get into the Personalities list.
1379     for (const Function *Personality : MMI->getPersonalities()) {
1380       if (Personality) {
1381         MCSymbol *NLPSym =
1382             getSymbolWithGlobalValueBase(Personality, "$non_lazy_ptr");
1383         MachineModuleInfoImpl::StubValueTy &StubSym =
1384             MMIMacho.getGVStubEntry(NLPSym);
1385         StubSym =
1386             MachineModuleInfoImpl::StubValueTy(getSymbol(Personality), true);
1387       }
1388     }
1389   }
1390 
1391   // Output stubs for dynamically-linked functions.
1392   MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetGVStubList();
1393 
1394   // Output macho stubs for external and common global variables.
1395   if (!Stubs.empty()) {
1396     // Switch with ".non_lazy_symbol_pointer" directive.
1397     OutStreamer->SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1398     EmitAlignment(isPPC64 ? 3 : 2);
1399 
1400     for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
1401       // L_foo$stub:
1402       OutStreamer->EmitLabel(Stubs[i].first);
1403       //   .indirect_symbol _foo
1404       MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
1405       OutStreamer->EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
1406 
1407       if (MCSym.getInt())
1408         // External to current translation unit.
1409         OutStreamer->EmitIntValue(0, isPPC64 ? 8 : 4/*size*/);
1410       else
1411         // Internal to current translation unit.
1412         //
1413         // When we place the LSDA into the TEXT section, the type info pointers
1414         // need to be indirect and pc-rel. We accomplish this by using NLPs.
1415         // However, sometimes the types are local to the file. So we need to
1416         // fill in the value for the NLP in those cases.
1417         OutStreamer->EmitValue(MCSymbolRefExpr::create(MCSym.getPointer(),
1418                                                        OutContext),
1419                               isPPC64 ? 8 : 4/*size*/);
1420     }
1421 
1422     Stubs.clear();
1423     OutStreamer->AddBlankLine();
1424   }
1425 
1426   // Funny Darwin hack: This flag tells the linker that no global symbols
1427   // contain code that falls through to other global symbols (e.g. the obvious
1428   // implementation of multiple entry points).  If this doesn't occur, the
1429   // linker can safely perform dead code stripping.  Since LLVM never generates
1430   // code that does this, it is always safe to set.
1431   OutStreamer->EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
1432 
1433   return AsmPrinter::doFinalization(M);
1434 }
1435 
1436 /// createPPCAsmPrinterPass - Returns a pass that prints the PPC assembly code
1437 /// for a MachineFunction to the given output stream, in a format that the
1438 /// Darwin assembler can deal with.
1439 ///
1440 static AsmPrinter *
1441 createPPCAsmPrinterPass(TargetMachine &tm,
1442                         std::unique_ptr<MCStreamer> &&Streamer) {
1443   if (tm.getTargetTriple().isMacOSX())
1444     return new PPCDarwinAsmPrinter(tm, std::move(Streamer));
1445   return new PPCLinuxAsmPrinter(tm, std::move(Streamer));
1446 }
1447 
1448 // Force static initialization.
1449 extern "C" void LLVMInitializePowerPCAsmPrinter() {
1450   TargetRegistry::RegisterAsmPrinter(getThePPC32Target(),
1451                                      createPPCAsmPrinterPass);
1452   TargetRegistry::RegisterAsmPrinter(getThePPC64Target(),
1453                                      createPPCAsmPrinterPass);
1454   TargetRegistry::RegisterAsmPrinter(getThePPC64LETarget(),
1455                                      createPPCAsmPrinterPass);
1456 }
1457