1 //===-- ARMAsmPrinter.cpp - Print machine code to an ARM .s file ----------===//
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 GAS-format ARM assembly language.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "ARMAsmPrinter.h"
15 #include "ARM.h"
16 #include "ARMConstantPoolValue.h"
17 #include "ARMMachineFunctionInfo.h"
18 #include "ARMTargetMachine.h"
19 #include "ARMTargetObjectFile.h"
20 #include "MCTargetDesc/ARMAddressingModes.h"
21 #include "MCTargetDesc/ARMInstPrinter.h"
22 #include "MCTargetDesc/ARMMCExpr.h"
23 #include "TargetInfo/ARMTargetInfo.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/BinaryFormat/COFF.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunctionPass.h"
29 #include "llvm/CodeGen/MachineJumpTableInfo.h"
30 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Mangler.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCAssembler.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCELFStreamer.h"
40 #include "llvm/MC/MCInst.h"
41 #include "llvm/MC/MCInstBuilder.h"
42 #include "llvm/MC/MCObjectStreamer.h"
43 #include "llvm/MC/MCStreamer.h"
44 #include "llvm/MC/MCSymbol.h"
45 #include "llvm/MC/TargetRegistry.h"
46 #include "llvm/Support/ARMBuildAttributes.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/TargetParser.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/Target/TargetMachine.h"
52 using namespace llvm;
53 
54 #define DEBUG_TYPE "asm-printer"
55 
56 ARMAsmPrinter::ARMAsmPrinter(TargetMachine &TM,
57                              std::unique_ptr<MCStreamer> Streamer)
58     : AsmPrinter(TM, std::move(Streamer)), Subtarget(nullptr), AFI(nullptr),
59       MCP(nullptr), InConstantPool(false), OptimizationGoals(-1) {}
60 
61 void ARMAsmPrinter::emitFunctionBodyEnd() {
62   // Make sure to terminate any constant pools that were at the end
63   // of the function.
64   if (!InConstantPool)
65     return;
66   InConstantPool = false;
67   OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
68 }
69 
70 void ARMAsmPrinter::emitFunctionEntryLabel() {
71   if (AFI->isThumbFunction()) {
72     OutStreamer->emitAssemblerFlag(MCAF_Code16);
73     OutStreamer->emitThumbFunc(CurrentFnSym);
74   } else {
75     OutStreamer->emitAssemblerFlag(MCAF_Code32);
76   }
77 
78   // Emit symbol for CMSE non-secure entry point
79   if (AFI->isCmseNSEntryFunction()) {
80     MCSymbol *S =
81         OutContext.getOrCreateSymbol("__acle_se_" + CurrentFnSym->getName());
82     emitLinkage(&MF->getFunction(), S);
83     OutStreamer->emitSymbolAttribute(S, MCSA_ELF_TypeFunction);
84     OutStreamer->emitLabel(S);
85   }
86 
87   OutStreamer->emitLabel(CurrentFnSym);
88 }
89 
90 void ARMAsmPrinter::emitXXStructor(const DataLayout &DL, const Constant *CV) {
91   uint64_t Size = getDataLayout().getTypeAllocSize(CV->getType());
92   assert(Size && "C++ constructor pointer had zero size!");
93 
94   const GlobalValue *GV = dyn_cast<GlobalValue>(CV->stripPointerCasts());
95   assert(GV && "C++ constructor pointer was not a GlobalValue!");
96 
97   const MCExpr *E = MCSymbolRefExpr::create(GetARMGVSymbol(GV,
98                                                            ARMII::MO_NO_FLAG),
99                                             (Subtarget->isTargetELF()
100                                              ? MCSymbolRefExpr::VK_ARM_TARGET1
101                                              : MCSymbolRefExpr::VK_None),
102                                             OutContext);
103 
104   OutStreamer->emitValue(E, Size);
105 }
106 
107 void ARMAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
108   if (PromotedGlobals.count(GV))
109     // The global was promoted into a constant pool. It should not be emitted.
110     return;
111   AsmPrinter::emitGlobalVariable(GV);
112 }
113 
114 /// runOnMachineFunction - This uses the emitInstruction()
115 /// method to print assembly for each instruction.
116 ///
117 bool ARMAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
118   AFI = MF.getInfo<ARMFunctionInfo>();
119   MCP = MF.getConstantPool();
120   Subtarget = &MF.getSubtarget<ARMSubtarget>();
121 
122   SetupMachineFunction(MF);
123   const Function &F = MF.getFunction();
124   const TargetMachine& TM = MF.getTarget();
125 
126   // Collect all globals that had their storage promoted to a constant pool.
127   // Functions are emitted before variables, so this accumulates promoted
128   // globals from all functions in PromotedGlobals.
129   for (auto *GV : AFI->getGlobalsPromotedToConstantPool())
130     PromotedGlobals.insert(GV);
131 
132   // Calculate this function's optimization goal.
133   unsigned OptimizationGoal;
134   if (F.hasOptNone())
135     // For best debugging illusion, speed and small size sacrificed
136     OptimizationGoal = 6;
137   else if (F.hasMinSize())
138     // Aggressively for small size, speed and debug illusion sacrificed
139     OptimizationGoal = 4;
140   else if (F.hasOptSize())
141     // For small size, but speed and debugging illusion preserved
142     OptimizationGoal = 3;
143   else if (TM.getOptLevel() == CodeGenOpt::Aggressive)
144     // Aggressively for speed, small size and debug illusion sacrificed
145     OptimizationGoal = 2;
146   else if (TM.getOptLevel() > CodeGenOpt::None)
147     // For speed, but small size and good debug illusion preserved
148     OptimizationGoal = 1;
149   else // TM.getOptLevel() == CodeGenOpt::None
150     // For good debugging, but speed and small size preserved
151     OptimizationGoal = 5;
152 
153   // Combine a new optimization goal with existing ones.
154   if (OptimizationGoals == -1) // uninitialized goals
155     OptimizationGoals = OptimizationGoal;
156   else if (OptimizationGoals != (int)OptimizationGoal) // conflicting goals
157     OptimizationGoals = 0;
158 
159   if (Subtarget->isTargetCOFF()) {
160     bool Internal = F.hasInternalLinkage();
161     COFF::SymbolStorageClass Scl = Internal ? COFF::IMAGE_SYM_CLASS_STATIC
162                                             : COFF::IMAGE_SYM_CLASS_EXTERNAL;
163     int Type = COFF::IMAGE_SYM_DTYPE_FUNCTION << COFF::SCT_COMPLEX_TYPE_SHIFT;
164 
165     OutStreamer->BeginCOFFSymbolDef(CurrentFnSym);
166     OutStreamer->EmitCOFFSymbolStorageClass(Scl);
167     OutStreamer->EmitCOFFSymbolType(Type);
168     OutStreamer->EndCOFFSymbolDef();
169   }
170 
171   // Emit the rest of the function body.
172   emitFunctionBody();
173 
174   // Emit the XRay table for this function.
175   emitXRayTable();
176 
177   // If we need V4T thumb mode Register Indirect Jump pads, emit them.
178   // These are created per function, rather than per TU, since it's
179   // relatively easy to exceed the thumb branch range within a TU.
180   if (! ThumbIndirectPads.empty()) {
181     OutStreamer->emitAssemblerFlag(MCAF_Code16);
182     emitAlignment(Align(2));
183     for (std::pair<unsigned, MCSymbol *> &TIP : ThumbIndirectPads) {
184       OutStreamer->emitLabel(TIP.second);
185       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBX)
186         .addReg(TIP.first)
187         // Add predicate operands.
188         .addImm(ARMCC::AL)
189         .addReg(0));
190     }
191     ThumbIndirectPads.clear();
192   }
193 
194   // We didn't modify anything.
195   return false;
196 }
197 
198 void ARMAsmPrinter::PrintSymbolOperand(const MachineOperand &MO,
199                                        raw_ostream &O) {
200   assert(MO.isGlobal() && "caller should check MO.isGlobal");
201   unsigned TF = MO.getTargetFlags();
202   if (TF & ARMII::MO_LO16)
203     O << ":lower16:";
204   else if (TF & ARMII::MO_HI16)
205     O << ":upper16:";
206   GetARMGVSymbol(MO.getGlobal(), TF)->print(O, MAI);
207   printOffset(MO.getOffset(), O);
208 }
209 
210 void ARMAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
211                                  raw_ostream &O) {
212   const MachineOperand &MO = MI->getOperand(OpNum);
213 
214   switch (MO.getType()) {
215   default: llvm_unreachable("<unknown operand type>");
216   case MachineOperand::MO_Register: {
217     Register Reg = MO.getReg();
218     assert(Register::isPhysicalRegister(Reg));
219     assert(!MO.getSubReg() && "Subregs should be eliminated!");
220     if(ARM::GPRPairRegClass.contains(Reg)) {
221       const MachineFunction &MF = *MI->getParent()->getParent();
222       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
223       Reg = TRI->getSubReg(Reg, ARM::gsub_0);
224     }
225     O << ARMInstPrinter::getRegisterName(Reg);
226     break;
227   }
228   case MachineOperand::MO_Immediate: {
229     O << '#';
230     unsigned TF = MO.getTargetFlags();
231     if (TF == ARMII::MO_LO16)
232       O << ":lower16:";
233     else if (TF == ARMII::MO_HI16)
234       O << ":upper16:";
235     O << MO.getImm();
236     break;
237   }
238   case MachineOperand::MO_MachineBasicBlock:
239     MO.getMBB()->getSymbol()->print(O, MAI);
240     return;
241   case MachineOperand::MO_GlobalAddress: {
242     PrintSymbolOperand(MO, O);
243     break;
244   }
245   case MachineOperand::MO_ConstantPoolIndex:
246     if (Subtarget->genExecuteOnly())
247       llvm_unreachable("execute-only should not generate constant pools");
248     GetCPISymbol(MO.getIndex())->print(O, MAI);
249     break;
250   }
251 }
252 
253 MCSymbol *ARMAsmPrinter::GetCPISymbol(unsigned CPID) const {
254   // The AsmPrinter::GetCPISymbol superclass method tries to use CPID as
255   // indexes in MachineConstantPool, which isn't in sync with indexes used here.
256   const DataLayout &DL = getDataLayout();
257   return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
258                                       "CPI" + Twine(getFunctionNumber()) + "_" +
259                                       Twine(CPID));
260 }
261 
262 //===--------------------------------------------------------------------===//
263 
264 MCSymbol *ARMAsmPrinter::
265 GetARMJTIPICJumpTableLabel(unsigned uid) const {
266   const DataLayout &DL = getDataLayout();
267   SmallString<60> Name;
268   raw_svector_ostream(Name) << DL.getPrivateGlobalPrefix() << "JTI"
269                             << getFunctionNumber() << '_' << uid;
270   return OutContext.getOrCreateSymbol(Name);
271 }
272 
273 bool ARMAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
274                                     const char *ExtraCode, raw_ostream &O) {
275   // Does this asm operand have a single letter operand modifier?
276   if (ExtraCode && ExtraCode[0]) {
277     if (ExtraCode[1] != 0) return true; // Unknown modifier.
278 
279     switch (ExtraCode[0]) {
280     default:
281       // See if this is a generic print operand
282       return AsmPrinter::PrintAsmOperand(MI, OpNum, ExtraCode, O);
283     case 'P': // Print a VFP double precision register.
284     case 'q': // Print a NEON quad precision register.
285       printOperand(MI, OpNum, O);
286       return false;
287     case 'y': // Print a VFP single precision register as indexed double.
288       if (MI->getOperand(OpNum).isReg()) {
289         MCRegister Reg = MI->getOperand(OpNum).getReg().asMCReg();
290         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
291         // Find the 'd' register that has this 's' register as a sub-register,
292         // and determine the lane number.
293         for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) {
294           if (!ARM::DPRRegClass.contains(*SR))
295             continue;
296           bool Lane0 = TRI->getSubReg(*SR, ARM::ssub_0) == Reg;
297           O << ARMInstPrinter::getRegisterName(*SR) << (Lane0 ? "[0]" : "[1]");
298           return false;
299         }
300       }
301       return true;
302     case 'B': // Bitwise inverse of integer or symbol without a preceding #.
303       if (!MI->getOperand(OpNum).isImm())
304         return true;
305       O << ~(MI->getOperand(OpNum).getImm());
306       return false;
307     case 'L': // The low 16 bits of an immediate constant.
308       if (!MI->getOperand(OpNum).isImm())
309         return true;
310       O << (MI->getOperand(OpNum).getImm() & 0xffff);
311       return false;
312     case 'M': { // A register range suitable for LDM/STM.
313       if (!MI->getOperand(OpNum).isReg())
314         return true;
315       const MachineOperand &MO = MI->getOperand(OpNum);
316       Register RegBegin = MO.getReg();
317       // This takes advantage of the 2 operand-ness of ldm/stm and that we've
318       // already got the operands in registers that are operands to the
319       // inline asm statement.
320       O << "{";
321       if (ARM::GPRPairRegClass.contains(RegBegin)) {
322         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
323         Register Reg0 = TRI->getSubReg(RegBegin, ARM::gsub_0);
324         O << ARMInstPrinter::getRegisterName(Reg0) << ", ";
325         RegBegin = TRI->getSubReg(RegBegin, ARM::gsub_1);
326       }
327       O << ARMInstPrinter::getRegisterName(RegBegin);
328 
329       // FIXME: The register allocator not only may not have given us the
330       // registers in sequence, but may not be in ascending registers. This
331       // will require changes in the register allocator that'll need to be
332       // propagated down here if the operands change.
333       unsigned RegOps = OpNum + 1;
334       while (MI->getOperand(RegOps).isReg()) {
335         O << ", "
336           << ARMInstPrinter::getRegisterName(MI->getOperand(RegOps).getReg());
337         RegOps++;
338       }
339 
340       O << "}";
341 
342       return false;
343     }
344     case 'R': // The most significant register of a pair.
345     case 'Q': { // The least significant register of a pair.
346       if (OpNum == 0)
347         return true;
348       const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
349       if (!FlagsOP.isImm())
350         return true;
351       unsigned Flags = FlagsOP.getImm();
352 
353       // This operand may not be the one that actually provides the register. If
354       // it's tied to a previous one then we should refer instead to that one
355       // for registers and their classes.
356       unsigned TiedIdx;
357       if (InlineAsm::isUseOperandTiedToDef(Flags, TiedIdx)) {
358         for (OpNum = InlineAsm::MIOp_FirstOperand; TiedIdx; --TiedIdx) {
359           unsigned OpFlags = MI->getOperand(OpNum).getImm();
360           OpNum += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
361         }
362         Flags = MI->getOperand(OpNum).getImm();
363 
364         // Later code expects OpNum to be pointing at the register rather than
365         // the flags.
366         OpNum += 1;
367       }
368 
369       unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
370       unsigned RC;
371       bool FirstHalf;
372       const ARMBaseTargetMachine &ATM =
373         static_cast<const ARMBaseTargetMachine &>(TM);
374 
375       // 'Q' should correspond to the low order register and 'R' to the high
376       // order register.  Whether this corresponds to the upper or lower half
377       // depends on the endianess mode.
378       if (ExtraCode[0] == 'Q')
379         FirstHalf = ATM.isLittleEndian();
380       else
381         // ExtraCode[0] == 'R'.
382         FirstHalf = !ATM.isLittleEndian();
383       const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
384       if (InlineAsm::hasRegClassConstraint(Flags, RC) &&
385           ARM::GPRPairRegClass.hasSubClassEq(TRI->getRegClass(RC))) {
386         if (NumVals != 1)
387           return true;
388         const MachineOperand &MO = MI->getOperand(OpNum);
389         if (!MO.isReg())
390           return true;
391         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
392         Register Reg =
393             TRI->getSubReg(MO.getReg(), FirstHalf ? ARM::gsub_0 : ARM::gsub_1);
394         O << ARMInstPrinter::getRegisterName(Reg);
395         return false;
396       }
397       if (NumVals != 2)
398         return true;
399       unsigned RegOp = FirstHalf ? OpNum : OpNum + 1;
400       if (RegOp >= MI->getNumOperands())
401         return true;
402       const MachineOperand &MO = MI->getOperand(RegOp);
403       if (!MO.isReg())
404         return true;
405       Register Reg = MO.getReg();
406       O << ARMInstPrinter::getRegisterName(Reg);
407       return false;
408     }
409 
410     case 'e': // The low doubleword register of a NEON quad register.
411     case 'f': { // The high doubleword register of a NEON quad register.
412       if (!MI->getOperand(OpNum).isReg())
413         return true;
414       Register Reg = MI->getOperand(OpNum).getReg();
415       if (!ARM::QPRRegClass.contains(Reg))
416         return true;
417       const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
418       Register SubReg =
419           TRI->getSubReg(Reg, ExtraCode[0] == 'e' ? ARM::dsub_0 : ARM::dsub_1);
420       O << ARMInstPrinter::getRegisterName(SubReg);
421       return false;
422     }
423 
424     // This modifier is not yet supported.
425     case 'h': // A range of VFP/NEON registers suitable for VLD1/VST1.
426       return true;
427     case 'H': { // The highest-numbered register of a pair.
428       const MachineOperand &MO = MI->getOperand(OpNum);
429       if (!MO.isReg())
430         return true;
431       const MachineFunction &MF = *MI->getParent()->getParent();
432       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
433       Register Reg = MO.getReg();
434       if(!ARM::GPRPairRegClass.contains(Reg))
435         return false;
436       Reg = TRI->getSubReg(Reg, ARM::gsub_1);
437       O << ARMInstPrinter::getRegisterName(Reg);
438       return false;
439     }
440     }
441   }
442 
443   printOperand(MI, OpNum, O);
444   return false;
445 }
446 
447 bool ARMAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
448                                           unsigned OpNum, const char *ExtraCode,
449                                           raw_ostream &O) {
450   // Does this asm operand have a single letter operand modifier?
451   if (ExtraCode && ExtraCode[0]) {
452     if (ExtraCode[1] != 0) return true; // Unknown modifier.
453 
454     switch (ExtraCode[0]) {
455       case 'A': // A memory operand for a VLD1/VST1 instruction.
456       default: return true;  // Unknown modifier.
457       case 'm': // The base register of a memory operand.
458         if (!MI->getOperand(OpNum).isReg())
459           return true;
460         O << ARMInstPrinter::getRegisterName(MI->getOperand(OpNum).getReg());
461         return false;
462     }
463   }
464 
465   const MachineOperand &MO = MI->getOperand(OpNum);
466   assert(MO.isReg() && "unexpected inline asm memory operand");
467   O << "[" << ARMInstPrinter::getRegisterName(MO.getReg()) << "]";
468   return false;
469 }
470 
471 static bool isThumb(const MCSubtargetInfo& STI) {
472   return STI.getFeatureBits()[ARM::ModeThumb];
473 }
474 
475 void ARMAsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
476                                      const MCSubtargetInfo *EndInfo) const {
477   // If either end mode is unknown (EndInfo == NULL) or different than
478   // the start mode, then restore the start mode.
479   const bool WasThumb = isThumb(StartInfo);
480   if (!EndInfo || WasThumb != isThumb(*EndInfo)) {
481     OutStreamer->emitAssemblerFlag(WasThumb ? MCAF_Code16 : MCAF_Code32);
482   }
483 }
484 
485 void ARMAsmPrinter::emitStartOfAsmFile(Module &M) {
486   const Triple &TT = TM.getTargetTriple();
487   // Use unified assembler syntax.
488   OutStreamer->emitAssemblerFlag(MCAF_SyntaxUnified);
489 
490   // Emit ARM Build Attributes
491   if (TT.isOSBinFormatELF())
492     emitAttributes();
493 
494   // Use the triple's architecture and subarchitecture to determine
495   // if we're thumb for the purposes of the top level code16 assembler
496   // flag.
497   if (!M.getModuleInlineAsm().empty() && TT.isThumb())
498     OutStreamer->emitAssemblerFlag(MCAF_Code16);
499 }
500 
501 static void
502 emitNonLazySymbolPointer(MCStreamer &OutStreamer, MCSymbol *StubLabel,
503                          MachineModuleInfoImpl::StubValueTy &MCSym) {
504   // L_foo$stub:
505   OutStreamer.emitLabel(StubLabel);
506   //   .indirect_symbol _foo
507   OutStreamer.emitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
508 
509   if (MCSym.getInt())
510     // External to current translation unit.
511     OutStreamer.emitIntValue(0, 4/*size*/);
512   else
513     // Internal to current translation unit.
514     //
515     // When we place the LSDA into the TEXT section, the type info
516     // pointers need to be indirect and pc-rel. We accomplish this by
517     // using NLPs; however, sometimes the types are local to the file.
518     // We need to fill in the value for the NLP in those cases.
519     OutStreamer.emitValue(
520         MCSymbolRefExpr::create(MCSym.getPointer(), OutStreamer.getContext()),
521         4 /*size*/);
522 }
523 
524 
525 void ARMAsmPrinter::emitEndOfAsmFile(Module &M) {
526   const Triple &TT = TM.getTargetTriple();
527   if (TT.isOSBinFormatMachO()) {
528     // All darwin targets use mach-o.
529     const TargetLoweringObjectFileMachO &TLOFMacho =
530       static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
531     MachineModuleInfoMachO &MMIMacho =
532       MMI->getObjFileInfo<MachineModuleInfoMachO>();
533 
534     // Output non-lazy-pointers for external and common global variables.
535     MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetGVStubList();
536 
537     if (!Stubs.empty()) {
538       // Switch with ".non_lazy_symbol_pointer" directive.
539       OutStreamer->SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
540       emitAlignment(Align(4));
541 
542       for (auto &Stub : Stubs)
543         emitNonLazySymbolPointer(*OutStreamer, Stub.first, Stub.second);
544 
545       Stubs.clear();
546       OutStreamer->AddBlankLine();
547     }
548 
549     Stubs = MMIMacho.GetThreadLocalGVStubList();
550     if (!Stubs.empty()) {
551       // Switch with ".non_lazy_symbol_pointer" directive.
552       OutStreamer->SwitchSection(TLOFMacho.getThreadLocalPointerSection());
553       emitAlignment(Align(4));
554 
555       for (auto &Stub : Stubs)
556         emitNonLazySymbolPointer(*OutStreamer, Stub.first, Stub.second);
557 
558       Stubs.clear();
559       OutStreamer->AddBlankLine();
560     }
561 
562     // Funny Darwin hack: This flag tells the linker that no global symbols
563     // contain code that falls through to other global symbols (e.g. the obvious
564     // implementation of multiple entry points).  If this doesn't occur, the
565     // linker can safely perform dead code stripping.  Since LLVM never
566     // generates code that does this, it is always safe to set.
567     OutStreamer->emitAssemblerFlag(MCAF_SubsectionsViaSymbols);
568   }
569 
570   // The last attribute to be emitted is ABI_optimization_goals
571   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
572   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
573 
574   if (OptimizationGoals > 0 &&
575       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
576        Subtarget->isTargetMuslAEABI()))
577     ATS.emitAttribute(ARMBuildAttrs::ABI_optimization_goals, OptimizationGoals);
578   OptimizationGoals = -1;
579 
580   ATS.finishAttributeSection();
581 }
582 
583 //===----------------------------------------------------------------------===//
584 // Helper routines for emitStartOfAsmFile() and emitEndOfAsmFile()
585 // FIXME:
586 // The following seem like one-off assembler flags, but they actually need
587 // to appear in the .ARM.attributes section in ELF.
588 // Instead of subclassing the MCELFStreamer, we do the work here.
589 
590  // Returns true if all functions have the same function attribute value.
591  // It also returns true when the module has no functions.
592 static bool checkFunctionsAttributeConsistency(const Module &M, StringRef Attr,
593                                                StringRef Value) {
594    return !any_of(M, [&](const Function &F) {
595        return F.getFnAttribute(Attr).getValueAsString() != Value;
596    });
597 }
598 // Returns true if all functions have the same denormal mode.
599 // It also returns true when the module has no functions.
600 static bool checkDenormalAttributeConsistency(const Module &M,
601                                               StringRef Attr,
602                                               DenormalMode Value) {
603   return !any_of(M, [&](const Function &F) {
604     StringRef AttrVal = F.getFnAttribute(Attr).getValueAsString();
605     return parseDenormalFPAttribute(AttrVal) != Value;
606   });
607 }
608 
609 void ARMAsmPrinter::emitAttributes() {
610   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
611   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
612 
613   ATS.emitTextAttribute(ARMBuildAttrs::conformance, "2.09");
614 
615   ATS.switchVendor("aeabi");
616 
617   // Compute ARM ELF Attributes based on the default subtarget that
618   // we'd have constructed. The existing ARM behavior isn't LTO clean
619   // anyhow.
620   // FIXME: For ifunc related functions we could iterate over and look
621   // for a feature string that doesn't match the default one.
622   const Triple &TT = TM.getTargetTriple();
623   StringRef CPU = TM.getTargetCPU();
624   StringRef FS = TM.getTargetFeatureString();
625   std::string ArchFS = ARM_MC::ParseARMTriple(TT, CPU);
626   if (!FS.empty()) {
627     if (!ArchFS.empty())
628       ArchFS = (Twine(ArchFS) + "," + FS).str();
629     else
630       ArchFS = std::string(FS);
631   }
632   const ARMBaseTargetMachine &ATM =
633       static_cast<const ARMBaseTargetMachine &>(TM);
634   const ARMSubtarget STI(TT, std::string(CPU), ArchFS, ATM,
635                          ATM.isLittleEndian());
636 
637   // Emit build attributes for the available hardware.
638   ATS.emitTargetAttributes(STI);
639 
640   // RW data addressing.
641   if (isPositionIndependent()) {
642     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RW_data,
643                       ARMBuildAttrs::AddressRWPCRel);
644   } else if (STI.isRWPI()) {
645     // RWPI specific attributes.
646     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RW_data,
647                       ARMBuildAttrs::AddressRWSBRel);
648   }
649 
650   // RO data addressing.
651   if (isPositionIndependent() || STI.isROPI()) {
652     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RO_data,
653                       ARMBuildAttrs::AddressROPCRel);
654   }
655 
656   // GOT use.
657   if (isPositionIndependent()) {
658     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
659                       ARMBuildAttrs::AddressGOT);
660   } else {
661     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
662                       ARMBuildAttrs::AddressDirect);
663   }
664 
665   // Set FP Denormals.
666   if (checkDenormalAttributeConsistency(*MMI->getModule(), "denormal-fp-math",
667                                         DenormalMode::getPreserveSign()))
668     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
669                       ARMBuildAttrs::PreserveFPSign);
670   else if (checkDenormalAttributeConsistency(*MMI->getModule(),
671                                              "denormal-fp-math",
672                                              DenormalMode::getPositiveZero()))
673     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
674                       ARMBuildAttrs::PositiveZero);
675   else if (!TM.Options.UnsafeFPMath)
676     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
677                       ARMBuildAttrs::IEEEDenormals);
678   else {
679     if (!STI.hasVFP2Base()) {
680       // When the target doesn't have an FPU (by design or
681       // intention), the assumptions made on the software support
682       // mirror that of the equivalent hardware support *if it
683       // existed*. For v7 and better we indicate that denormals are
684       // flushed preserving sign, and for V6 we indicate that
685       // denormals are flushed to positive zero.
686       if (STI.hasV7Ops())
687         ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
688                           ARMBuildAttrs::PreserveFPSign);
689     } else if (STI.hasVFP3Base()) {
690       // In VFPv4, VFPv4U, VFPv3, or VFPv3U, it is preserved. That is,
691       // the sign bit of the zero matches the sign bit of the input or
692       // result that is being flushed to zero.
693       ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
694                         ARMBuildAttrs::PreserveFPSign);
695     }
696     // For VFPv2 implementations it is implementation defined as
697     // to whether denormals are flushed to positive zero or to
698     // whatever the sign of zero is (ARM v7AR ARM 2.7.5). Historically
699     // LLVM has chosen to flush this to positive zero (most likely for
700     // GCC compatibility), so that's the chosen value here (the
701     // absence of its emission implies zero).
702   }
703 
704   // Set FP exceptions and rounding
705   if (checkFunctionsAttributeConsistency(*MMI->getModule(),
706                                          "no-trapping-math", "true") ||
707       TM.Options.NoTrappingFPMath)
708     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_exceptions,
709                       ARMBuildAttrs::Not_Allowed);
710   else if (!TM.Options.UnsafeFPMath) {
711     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_exceptions, ARMBuildAttrs::Allowed);
712 
713     // If the user has permitted this code to choose the IEEE 754
714     // rounding at run-time, emit the rounding attribute.
715     if (TM.Options.HonorSignDependentRoundingFPMathOption)
716       ATS.emitAttribute(ARMBuildAttrs::ABI_FP_rounding, ARMBuildAttrs::Allowed);
717   }
718 
719   // TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath is the
720   // equivalent of GCC's -ffinite-math-only flag.
721   if (TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath)
722     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
723                       ARMBuildAttrs::Allowed);
724   else
725     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
726                       ARMBuildAttrs::AllowIEEE754);
727 
728   // FIXME: add more flags to ARMBuildAttributes.h
729   // 8-bytes alignment stuff.
730   ATS.emitAttribute(ARMBuildAttrs::ABI_align_needed, 1);
731   ATS.emitAttribute(ARMBuildAttrs::ABI_align_preserved, 1);
732 
733   // Hard float.  Use both S and D registers and conform to AAPCS-VFP.
734   if (STI.isAAPCS_ABI() && TM.Options.FloatABIType == FloatABI::Hard)
735     ATS.emitAttribute(ARMBuildAttrs::ABI_VFP_args, ARMBuildAttrs::HardFPAAPCS);
736 
737   // FIXME: To support emitting this build attribute as GCC does, the
738   // -mfp16-format option and associated plumbing must be
739   // supported. For now the __fp16 type is exposed by default, so this
740   // attribute should be emitted with value 1.
741   ATS.emitAttribute(ARMBuildAttrs::ABI_FP_16bit_format,
742                     ARMBuildAttrs::FP16FormatIEEE);
743 
744   if (const Module *SourceModule = MMI->getModule()) {
745     // ABI_PCS_wchar_t to indicate wchar_t width
746     // FIXME: There is no way to emit value 0 (wchar_t prohibited).
747     if (auto WCharWidthValue = mdconst::extract_or_null<ConstantInt>(
748             SourceModule->getModuleFlag("wchar_size"))) {
749       int WCharWidth = WCharWidthValue->getZExtValue();
750       assert((WCharWidth == 2 || WCharWidth == 4) &&
751              "wchar_t width must be 2 or 4 bytes");
752       ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_wchar_t, WCharWidth);
753     }
754 
755     // ABI_enum_size to indicate enum width
756     // FIXME: There is no way to emit value 0 (enums prohibited) or value 3
757     //        (all enums contain a value needing 32 bits to encode).
758     if (auto EnumWidthValue = mdconst::extract_or_null<ConstantInt>(
759             SourceModule->getModuleFlag("min_enum_size"))) {
760       int EnumWidth = EnumWidthValue->getZExtValue();
761       assert((EnumWidth == 1 || EnumWidth == 4) &&
762              "Minimum enum width must be 1 or 4 bytes");
763       int EnumBuildAttr = EnumWidth == 1 ? 1 : 2;
764       ATS.emitAttribute(ARMBuildAttrs::ABI_enum_size, EnumBuildAttr);
765     }
766 
767     auto *PACValue = mdconst::extract_or_null<ConstantInt>(
768         SourceModule->getModuleFlag("sign-return-address"));
769     if (PACValue && PACValue->getZExtValue() == 1) {
770       // If "+pacbti" is used as an architecture extension,
771       // Tag_PAC_extension is emitted in
772       // ARMTargetStreamer::emitTargetAttributes().
773       if (!STI.hasPACBTI()) {
774         ATS.emitAttribute(ARMBuildAttrs::PAC_extension,
775                           ARMBuildAttrs::AllowPACInNOPSpace);
776       }
777       ATS.emitAttribute(ARMBuildAttrs::PACRET_use, ARMBuildAttrs::PACRETUsed);
778     }
779 
780     auto *BTIValue = mdconst::extract_or_null<ConstantInt>(
781         SourceModule->getModuleFlag("branch-target-enforcement"));
782     if (BTIValue && BTIValue->getZExtValue() == 1) {
783       // If "+pacbti" is used as an architecture extension,
784       // Tag_BTI_extension is emitted in
785       // ARMTargetStreamer::emitTargetAttributes().
786       if (!STI.hasPACBTI()) {
787         ATS.emitAttribute(ARMBuildAttrs::BTI_extension,
788                           ARMBuildAttrs::AllowBTIInNOPSpace);
789       }
790       ATS.emitAttribute(ARMBuildAttrs::BTI_use, ARMBuildAttrs::BTIUsed);
791     }
792   }
793 
794   // We currently do not support using R9 as the TLS pointer.
795   if (STI.isRWPI())
796     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
797                       ARMBuildAttrs::R9IsSB);
798   else if (STI.isR9Reserved())
799     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
800                       ARMBuildAttrs::R9Reserved);
801   else
802     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
803                       ARMBuildAttrs::R9IsGPR);
804 }
805 
806 //===----------------------------------------------------------------------===//
807 
808 static MCSymbol *getBFLabel(StringRef Prefix, unsigned FunctionNumber,
809                              unsigned LabelId, MCContext &Ctx) {
810 
811   MCSymbol *Label = Ctx.getOrCreateSymbol(Twine(Prefix)
812                        + "BF" + Twine(FunctionNumber) + "_" + Twine(LabelId));
813   return Label;
814 }
815 
816 static MCSymbol *getPICLabel(StringRef Prefix, unsigned FunctionNumber,
817                              unsigned LabelId, MCContext &Ctx) {
818 
819   MCSymbol *Label = Ctx.getOrCreateSymbol(Twine(Prefix)
820                        + "PC" + Twine(FunctionNumber) + "_" + Twine(LabelId));
821   return Label;
822 }
823 
824 static MCSymbolRefExpr::VariantKind
825 getModifierVariantKind(ARMCP::ARMCPModifier Modifier) {
826   switch (Modifier) {
827   case ARMCP::no_modifier:
828     return MCSymbolRefExpr::VK_None;
829   case ARMCP::TLSGD:
830     return MCSymbolRefExpr::VK_TLSGD;
831   case ARMCP::TPOFF:
832     return MCSymbolRefExpr::VK_TPOFF;
833   case ARMCP::GOTTPOFF:
834     return MCSymbolRefExpr::VK_GOTTPOFF;
835   case ARMCP::SBREL:
836     return MCSymbolRefExpr::VK_ARM_SBREL;
837   case ARMCP::GOT_PREL:
838     return MCSymbolRefExpr::VK_ARM_GOT_PREL;
839   case ARMCP::SECREL:
840     return MCSymbolRefExpr::VK_SECREL;
841   }
842   llvm_unreachable("Invalid ARMCPModifier!");
843 }
844 
845 MCSymbol *ARMAsmPrinter::GetARMGVSymbol(const GlobalValue *GV,
846                                         unsigned char TargetFlags) {
847   if (Subtarget->isTargetMachO()) {
848     bool IsIndirect =
849         (TargetFlags & ARMII::MO_NONLAZY) && Subtarget->isGVIndirectSymbol(GV);
850 
851     if (!IsIndirect)
852       return getSymbol(GV);
853 
854     // FIXME: Remove this when Darwin transition to @GOT like syntax.
855     MCSymbol *MCSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
856     MachineModuleInfoMachO &MMIMachO =
857       MMI->getObjFileInfo<MachineModuleInfoMachO>();
858     MachineModuleInfoImpl::StubValueTy &StubSym =
859         GV->isThreadLocal() ? MMIMachO.getThreadLocalGVStubEntry(MCSym)
860                             : MMIMachO.getGVStubEntry(MCSym);
861 
862     if (!StubSym.getPointer())
863       StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV),
864                                                    !GV->hasInternalLinkage());
865     return MCSym;
866   } else if (Subtarget->isTargetCOFF()) {
867     assert(Subtarget->isTargetWindows() &&
868            "Windows is the only supported COFF target");
869 
870     bool IsIndirect =
871         (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB));
872     if (!IsIndirect)
873       return getSymbol(GV);
874 
875     SmallString<128> Name;
876     if (TargetFlags & ARMII::MO_DLLIMPORT)
877       Name = "__imp_";
878     else if (TargetFlags & ARMII::MO_COFFSTUB)
879       Name = ".refptr.";
880     getNameWithPrefix(Name, GV);
881 
882     MCSymbol *MCSym = OutContext.getOrCreateSymbol(Name);
883 
884     if (TargetFlags & ARMII::MO_COFFSTUB) {
885       MachineModuleInfoCOFF &MMICOFF =
886           MMI->getObjFileInfo<MachineModuleInfoCOFF>();
887       MachineModuleInfoImpl::StubValueTy &StubSym =
888           MMICOFF.getGVStubEntry(MCSym);
889 
890       if (!StubSym.getPointer())
891         StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV), true);
892     }
893 
894     return MCSym;
895   } else if (Subtarget->isTargetELF()) {
896     return getSymbol(GV);
897   }
898   llvm_unreachable("unexpected target");
899 }
900 
901 void ARMAsmPrinter::emitMachineConstantPoolValue(
902     MachineConstantPoolValue *MCPV) {
903   const DataLayout &DL = getDataLayout();
904   int Size = DL.getTypeAllocSize(MCPV->getType());
905 
906   ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
907 
908   if (ACPV->isPromotedGlobal()) {
909     // This constant pool entry is actually a global whose storage has been
910     // promoted into the constant pool. This global may be referenced still
911     // by debug information, and due to the way AsmPrinter is set up, the debug
912     // info is immutable by the time we decide to promote globals to constant
913     // pools. Because of this, we need to ensure we emit a symbol for the global
914     // with private linkage (the default) so debug info can refer to it.
915     //
916     // However, if this global is promoted into several functions we must ensure
917     // we don't try and emit duplicate symbols!
918     auto *ACPC = cast<ARMConstantPoolConstant>(ACPV);
919     for (const auto *GV : ACPC->promotedGlobals()) {
920       if (!EmittedPromotedGlobalLabels.count(GV)) {
921         MCSymbol *GVSym = getSymbol(GV);
922         OutStreamer->emitLabel(GVSym);
923         EmittedPromotedGlobalLabels.insert(GV);
924       }
925     }
926     return emitGlobalConstant(DL, ACPC->getPromotedGlobalInit());
927   }
928 
929   MCSymbol *MCSym;
930   if (ACPV->isLSDA()) {
931     MCSym = getMBBExceptionSym(MF->front());
932   } else if (ACPV->isBlockAddress()) {
933     const BlockAddress *BA =
934       cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress();
935     MCSym = GetBlockAddressSymbol(BA);
936   } else if (ACPV->isGlobalValue()) {
937     const GlobalValue *GV = cast<ARMConstantPoolConstant>(ACPV)->getGV();
938 
939     // On Darwin, const-pool entries may get the "FOO$non_lazy_ptr" mangling, so
940     // flag the global as MO_NONLAZY.
941     unsigned char TF = Subtarget->isTargetMachO() ? ARMII::MO_NONLAZY : 0;
942     MCSym = GetARMGVSymbol(GV, TF);
943   } else if (ACPV->isMachineBasicBlock()) {
944     const MachineBasicBlock *MBB = cast<ARMConstantPoolMBB>(ACPV)->getMBB();
945     MCSym = MBB->getSymbol();
946   } else {
947     assert(ACPV->isExtSymbol() && "unrecognized constant pool value");
948     auto Sym = cast<ARMConstantPoolSymbol>(ACPV)->getSymbol();
949     MCSym = GetExternalSymbolSymbol(Sym);
950   }
951 
952   // Create an MCSymbol for the reference.
953   const MCExpr *Expr =
954     MCSymbolRefExpr::create(MCSym, getModifierVariantKind(ACPV->getModifier()),
955                             OutContext);
956 
957   if (ACPV->getPCAdjustment()) {
958     MCSymbol *PCLabel =
959         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
960                     ACPV->getLabelId(), OutContext);
961     const MCExpr *PCRelExpr = MCSymbolRefExpr::create(PCLabel, OutContext);
962     PCRelExpr =
963       MCBinaryExpr::createAdd(PCRelExpr,
964                               MCConstantExpr::create(ACPV->getPCAdjustment(),
965                                                      OutContext),
966                               OutContext);
967     if (ACPV->mustAddCurrentAddress()) {
968       // We want "(<expr> - .)", but MC doesn't have a concept of the '.'
969       // label, so just emit a local label end reference that instead.
970       MCSymbol *DotSym = OutContext.createTempSymbol();
971       OutStreamer->emitLabel(DotSym);
972       const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
973       PCRelExpr = MCBinaryExpr::createSub(PCRelExpr, DotExpr, OutContext);
974     }
975     Expr = MCBinaryExpr::createSub(Expr, PCRelExpr, OutContext);
976   }
977   OutStreamer->emitValue(Expr, Size);
978 }
979 
980 void ARMAsmPrinter::emitJumpTableAddrs(const MachineInstr *MI) {
981   const MachineOperand &MO1 = MI->getOperand(1);
982   unsigned JTI = MO1.getIndex();
983 
984   // Make sure the Thumb jump table is 4-byte aligned. This will be a nop for
985   // ARM mode tables.
986   emitAlignment(Align(4));
987 
988   // Emit a label for the jump table.
989   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
990   OutStreamer->emitLabel(JTISymbol);
991 
992   // Mark the jump table as data-in-code.
993   OutStreamer->emitDataRegion(MCDR_DataRegionJT32);
994 
995   // Emit each entry of the table.
996   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
997   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
998   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
999 
1000   for (MachineBasicBlock *MBB : JTBBs) {
1001     // Construct an MCExpr for the entry. We want a value of the form:
1002     // (BasicBlockAddr - TableBeginAddr)
1003     //
1004     // For example, a table with entries jumping to basic blocks BB0 and BB1
1005     // would look like:
1006     // LJTI_0_0:
1007     //    .word (LBB0 - LJTI_0_0)
1008     //    .word (LBB1 - LJTI_0_0)
1009     const MCExpr *Expr = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1010 
1011     if (isPositionIndependent() || Subtarget->isROPI())
1012       Expr = MCBinaryExpr::createSub(Expr, MCSymbolRefExpr::create(JTISymbol,
1013                                                                    OutContext),
1014                                      OutContext);
1015     // If we're generating a table of Thumb addresses in static relocation
1016     // model, we need to add one to keep interworking correctly.
1017     else if (AFI->isThumbFunction())
1018       Expr = MCBinaryExpr::createAdd(Expr, MCConstantExpr::create(1,OutContext),
1019                                      OutContext);
1020     OutStreamer->emitValue(Expr, 4);
1021   }
1022   // Mark the end of jump table data-in-code region.
1023   OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
1024 }
1025 
1026 void ARMAsmPrinter::emitJumpTableInsts(const MachineInstr *MI) {
1027   const MachineOperand &MO1 = MI->getOperand(1);
1028   unsigned JTI = MO1.getIndex();
1029 
1030   // Make sure the Thumb jump table is 4-byte aligned. This will be a nop for
1031   // ARM mode tables.
1032   emitAlignment(Align(4));
1033 
1034   // Emit a label for the jump table.
1035   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
1036   OutStreamer->emitLabel(JTISymbol);
1037 
1038   // Emit each entry of the table.
1039   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1040   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1041   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1042 
1043   for (MachineBasicBlock *MBB : JTBBs) {
1044     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
1045                                                           OutContext);
1046     // If this isn't a TBB or TBH, the entries are direct branch instructions.
1047     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2B)
1048         .addExpr(MBBSymbolExpr)
1049         .addImm(ARMCC::AL)
1050         .addReg(0));
1051   }
1052 }
1053 
1054 void ARMAsmPrinter::emitJumpTableTBInst(const MachineInstr *MI,
1055                                         unsigned OffsetWidth) {
1056   assert((OffsetWidth == 1 || OffsetWidth == 2) && "invalid tbb/tbh width");
1057   const MachineOperand &MO1 = MI->getOperand(1);
1058   unsigned JTI = MO1.getIndex();
1059 
1060   if (Subtarget->isThumb1Only())
1061     emitAlignment(Align(4));
1062 
1063   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
1064   OutStreamer->emitLabel(JTISymbol);
1065 
1066   // Emit each entry of the table.
1067   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1068   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1069   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1070 
1071   // Mark the jump table as data-in-code.
1072   OutStreamer->emitDataRegion(OffsetWidth == 1 ? MCDR_DataRegionJT8
1073                                                : MCDR_DataRegionJT16);
1074 
1075   for (auto MBB : JTBBs) {
1076     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
1077                                                           OutContext);
1078     // Otherwise it's an offset from the dispatch instruction. Construct an
1079     // MCExpr for the entry. We want a value of the form:
1080     // (BasicBlockAddr - TBBInstAddr + 4) / 2
1081     //
1082     // For example, a TBB table with entries jumping to basic blocks BB0 and BB1
1083     // would look like:
1084     // LJTI_0_0:
1085     //    .byte (LBB0 - (LCPI0_0 + 4)) / 2
1086     //    .byte (LBB1 - (LCPI0_0 + 4)) / 2
1087     // where LCPI0_0 is a label defined just before the TBB instruction using
1088     // this table.
1089     MCSymbol *TBInstPC = GetCPISymbol(MI->getOperand(0).getImm());
1090     const MCExpr *Expr = MCBinaryExpr::createAdd(
1091         MCSymbolRefExpr::create(TBInstPC, OutContext),
1092         MCConstantExpr::create(4, OutContext), OutContext);
1093     Expr = MCBinaryExpr::createSub(MBBSymbolExpr, Expr, OutContext);
1094     Expr = MCBinaryExpr::createDiv(Expr, MCConstantExpr::create(2, OutContext),
1095                                    OutContext);
1096     OutStreamer->emitValue(Expr, OffsetWidth);
1097   }
1098   // Mark the end of jump table data-in-code region. 32-bit offsets use
1099   // actual branch instructions here, so we don't mark those as a data-region
1100   // at all.
1101   OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
1102 
1103   // Make sure the next instruction is 2-byte aligned.
1104   emitAlignment(Align(2));
1105 }
1106 
1107 void ARMAsmPrinter::EmitUnwindingInstruction(const MachineInstr *MI) {
1108   assert(MI->getFlag(MachineInstr::FrameSetup) &&
1109       "Only instruction which are involved into frame setup code are allowed");
1110 
1111   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
1112   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1113   const MachineFunction &MF = *MI->getParent()->getParent();
1114   const TargetRegisterInfo *TargetRegInfo =
1115     MF.getSubtarget().getRegisterInfo();
1116   const MachineRegisterInfo &MachineRegInfo = MF.getRegInfo();
1117 
1118   Register FramePtr = TargetRegInfo->getFrameRegister(MF);
1119   unsigned Opc = MI->getOpcode();
1120   unsigned SrcReg, DstReg;
1121 
1122   switch (Opc) {
1123   case ARM::tPUSH:
1124     // special case: tPUSH does not have src/dst regs.
1125     SrcReg = DstReg = ARM::SP;
1126     break;
1127   case ARM::tLDRpci:
1128   case ARM::t2MOVi16:
1129   case ARM::t2MOVTi16:
1130     // special cases:
1131     // 1) for Thumb1 code we sometimes materialize the constant via constpool
1132     //    load.
1133     // 2) for Thumb2 execute only code we materialize the constant via
1134     //    immediate constants in 2 separate instructions (MOVW/MOVT).
1135     SrcReg = ~0U;
1136     DstReg = MI->getOperand(0).getReg();
1137     break;
1138   default:
1139     SrcReg = MI->getOperand(1).getReg();
1140     DstReg = MI->getOperand(0).getReg();
1141     break;
1142   }
1143 
1144   // Try to figure out the unwinding opcode out of src / dst regs.
1145   if (MI->mayStore()) {
1146     // Register saves.
1147     assert(DstReg == ARM::SP &&
1148            "Only stack pointer as a destination reg is supported");
1149 
1150     SmallVector<unsigned, 4> RegList;
1151     // Skip src & dst reg, and pred ops.
1152     unsigned StartOp = 2 + 2;
1153     // Use all the operands.
1154     unsigned NumOffset = 0;
1155     // Amount of SP adjustment folded into a push, before the
1156     // registers are stored (pad at higher addresses).
1157     unsigned PadBefore = 0;
1158     // Amount of SP adjustment folded into a push, after the
1159     // registers are stored (pad at lower addresses).
1160     unsigned PadAfter = 0;
1161 
1162     switch (Opc) {
1163     default:
1164       MI->print(errs());
1165       llvm_unreachable("Unsupported opcode for unwinding information");
1166     case ARM::tPUSH:
1167       // Special case here: no src & dst reg, but two extra imp ops.
1168       StartOp = 2; NumOffset = 2;
1169       LLVM_FALLTHROUGH;
1170     case ARM::STMDB_UPD:
1171     case ARM::t2STMDB_UPD:
1172     case ARM::VSTMDDB_UPD:
1173       assert(SrcReg == ARM::SP &&
1174              "Only stack pointer as a source reg is supported");
1175       for (unsigned i = StartOp, NumOps = MI->getNumOperands() - NumOffset;
1176            i != NumOps; ++i) {
1177         const MachineOperand &MO = MI->getOperand(i);
1178         // Actually, there should never be any impdef stuff here. Skip it
1179         // temporary to workaround PR11902.
1180         if (MO.isImplicit())
1181           continue;
1182         // Registers, pushed as a part of folding an SP update into the
1183         // push instruction are marked as undef and should not be
1184         // restored when unwinding, because the function can modify the
1185         // corresponding stack slots.
1186         if (MO.isUndef()) {
1187           assert(RegList.empty() &&
1188                  "Pad registers must come before restored ones");
1189           unsigned Width =
1190             TargetRegInfo->getRegSizeInBits(MO.getReg(), MachineRegInfo) / 8;
1191           PadAfter += Width;
1192           continue;
1193         }
1194         // Check for registers that are remapped (for a Thumb1 prologue that
1195         // saves high registers).
1196         Register Reg = MO.getReg();
1197         if (unsigned RemappedReg = AFI->EHPrologueRemappedRegs.lookup(Reg))
1198           Reg = RemappedReg;
1199         RegList.push_back(Reg);
1200       }
1201       break;
1202     case ARM::STR_PRE_IMM:
1203     case ARM::STR_PRE_REG:
1204     case ARM::t2STR_PRE:
1205       assert(MI->getOperand(2).getReg() == ARM::SP &&
1206              "Only stack pointer as a source reg is supported");
1207       if (unsigned RemappedReg = AFI->EHPrologueRemappedRegs.lookup(SrcReg))
1208         SrcReg = RemappedReg;
1209 
1210       RegList.push_back(SrcReg);
1211       break;
1212     case ARM::t2STRD_PRE:
1213       assert(MI->getOperand(3).getReg() == ARM::SP &&
1214              "Only stack pointer as a source reg is supported");
1215       SrcReg = MI->getOperand(1).getReg();
1216       if (unsigned RemappedReg = AFI->EHPrologueRemappedRegs.lookup(SrcReg))
1217         SrcReg = RemappedReg;
1218       RegList.push_back(SrcReg);
1219       SrcReg = MI->getOperand(2).getReg();
1220       if (unsigned RemappedReg = AFI->EHPrologueRemappedRegs.lookup(SrcReg))
1221         SrcReg = RemappedReg;
1222       RegList.push_back(SrcReg);
1223       PadBefore = -MI->getOperand(4).getImm() - 8;
1224       break;
1225     }
1226     if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM) {
1227       if (PadBefore)
1228         ATS.emitPad(PadBefore);
1229       ATS.emitRegSave(RegList, Opc == ARM::VSTMDDB_UPD);
1230       // Account for the SP adjustment, folded into the push.
1231       if (PadAfter)
1232         ATS.emitPad(PadAfter);
1233     }
1234   } else {
1235     // Changes of stack / frame pointer.
1236     if (SrcReg == ARM::SP) {
1237       int64_t Offset = 0;
1238       switch (Opc) {
1239       default:
1240         MI->print(errs());
1241         llvm_unreachable("Unsupported opcode for unwinding information");
1242       case ARM::MOVr:
1243       case ARM::tMOVr:
1244         Offset = 0;
1245         break;
1246       case ARM::ADDri:
1247       case ARM::t2ADDri:
1248       case ARM::t2ADDri12:
1249       case ARM::t2ADDspImm:
1250       case ARM::t2ADDspImm12:
1251         Offset = -MI->getOperand(2).getImm();
1252         break;
1253       case ARM::SUBri:
1254       case ARM::t2SUBri:
1255       case ARM::t2SUBri12:
1256       case ARM::t2SUBspImm:
1257       case ARM::t2SUBspImm12:
1258         Offset = MI->getOperand(2).getImm();
1259         break;
1260       case ARM::tSUBspi:
1261         Offset = MI->getOperand(2).getImm()*4;
1262         break;
1263       case ARM::tADDspi:
1264       case ARM::tADDrSPi:
1265         Offset = -MI->getOperand(2).getImm()*4;
1266         break;
1267       case ARM::tADDhirr:
1268         Offset =
1269             -AFI->EHPrologueOffsetInRegs.lookup(MI->getOperand(2).getReg());
1270         break;
1271       }
1272 
1273       if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM) {
1274         if (DstReg == FramePtr && FramePtr != ARM::SP)
1275           // Set-up of the frame pointer. Positive values correspond to "add"
1276           // instruction.
1277           ATS.emitSetFP(FramePtr, ARM::SP, -Offset);
1278         else if (DstReg == ARM::SP) {
1279           // Change of SP by an offset. Positive values correspond to "sub"
1280           // instruction.
1281           ATS.emitPad(Offset);
1282         } else {
1283           // Move of SP to a register.  Positive values correspond to an "add"
1284           // instruction.
1285           ATS.emitMovSP(DstReg, -Offset);
1286         }
1287       }
1288     } else if (DstReg == ARM::SP) {
1289       MI->print(errs());
1290       llvm_unreachable("Unsupported opcode for unwinding information");
1291     } else {
1292       int64_t Offset = 0;
1293       switch (Opc) {
1294       case ARM::tMOVr:
1295         // If a Thumb1 function spills r8-r11, we copy the values to low
1296         // registers before pushing them. Record the copy so we can emit the
1297         // correct ".save" later.
1298         AFI->EHPrologueRemappedRegs[DstReg] = SrcReg;
1299         break;
1300       case ARM::tLDRpci: {
1301         // Grab the constpool index and check, whether it corresponds to
1302         // original or cloned constpool entry.
1303         unsigned CPI = MI->getOperand(1).getIndex();
1304         const MachineConstantPool *MCP = MF.getConstantPool();
1305         if (CPI >= MCP->getConstants().size())
1306           CPI = AFI->getOriginalCPIdx(CPI);
1307         assert(CPI != -1U && "Invalid constpool index");
1308 
1309         // Derive the actual offset.
1310         const MachineConstantPoolEntry &CPE = MCP->getConstants()[CPI];
1311         assert(!CPE.isMachineConstantPoolEntry() && "Invalid constpool entry");
1312         Offset = cast<ConstantInt>(CPE.Val.ConstVal)->getSExtValue();
1313         AFI->EHPrologueOffsetInRegs[DstReg] = Offset;
1314         break;
1315       }
1316       case ARM::t2MOVi16:
1317         Offset = MI->getOperand(1).getImm();
1318         AFI->EHPrologueOffsetInRegs[DstReg] = Offset;
1319         break;
1320       case ARM::t2MOVTi16:
1321         Offset = MI->getOperand(2).getImm();
1322         AFI->EHPrologueOffsetInRegs[DstReg] |= (Offset << 16);
1323         break;
1324       case ARM::t2PAC:
1325       case ARM::t2PACBTI:
1326         AFI->EHPrologueRemappedRegs[ARM::R12] = ARM::RA_AUTH_CODE;
1327         break;
1328       default:
1329         MI->print(errs());
1330         llvm_unreachable("Unsupported opcode for unwinding information");
1331       }
1332     }
1333   }
1334 }
1335 
1336 // Simple pseudo-instructions have their lowering (with expansion to real
1337 // instructions) auto-generated.
1338 #include "ARMGenMCPseudoLowering.inc"
1339 
1340 void ARMAsmPrinter::emitInstruction(const MachineInstr *MI) {
1341   const DataLayout &DL = getDataLayout();
1342   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
1343   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1344 
1345   // If we just ended a constant pool, mark it as such.
1346   if (InConstantPool && MI->getOpcode() != ARM::CONSTPOOL_ENTRY) {
1347     OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
1348     InConstantPool = false;
1349   }
1350 
1351   // Emit unwinding stuff for frame-related instructions
1352   if (Subtarget->isTargetEHABICompatible() &&
1353        MI->getFlag(MachineInstr::FrameSetup))
1354     EmitUnwindingInstruction(MI);
1355 
1356   // Do any auto-generated pseudo lowerings.
1357   if (emitPseudoExpansionLowering(*OutStreamer, MI))
1358     return;
1359 
1360   assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
1361          "Pseudo flag setting opcode should be expanded early");
1362 
1363   // Check for manual lowerings.
1364   unsigned Opc = MI->getOpcode();
1365   switch (Opc) {
1366   case ARM::t2MOVi32imm: llvm_unreachable("Should be lowered by thumb2it pass");
1367   case ARM::DBG_VALUE: llvm_unreachable("Should be handled by generic printing");
1368   case ARM::LEApcrel:
1369   case ARM::tLEApcrel:
1370   case ARM::t2LEApcrel: {
1371     // FIXME: Need to also handle globals and externals
1372     MCSymbol *CPISymbol = GetCPISymbol(MI->getOperand(1).getIndex());
1373     EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
1374                                                ARM::t2LEApcrel ? ARM::t2ADR
1375                   : (MI->getOpcode() == ARM::tLEApcrel ? ARM::tADR
1376                      : ARM::ADR))
1377       .addReg(MI->getOperand(0).getReg())
1378       .addExpr(MCSymbolRefExpr::create(CPISymbol, OutContext))
1379       // Add predicate operands.
1380       .addImm(MI->getOperand(2).getImm())
1381       .addReg(MI->getOperand(3).getReg()));
1382     return;
1383   }
1384   case ARM::LEApcrelJT:
1385   case ARM::tLEApcrelJT:
1386   case ARM::t2LEApcrelJT: {
1387     MCSymbol *JTIPICSymbol =
1388       GetARMJTIPICJumpTableLabel(MI->getOperand(1).getIndex());
1389     EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
1390                                                ARM::t2LEApcrelJT ? ARM::t2ADR
1391                   : (MI->getOpcode() == ARM::tLEApcrelJT ? ARM::tADR
1392                      : ARM::ADR))
1393       .addReg(MI->getOperand(0).getReg())
1394       .addExpr(MCSymbolRefExpr::create(JTIPICSymbol, OutContext))
1395       // Add predicate operands.
1396       .addImm(MI->getOperand(2).getImm())
1397       .addReg(MI->getOperand(3).getReg()));
1398     return;
1399   }
1400   // Darwin call instructions are just normal call instructions with different
1401   // clobber semantics (they clobber R9).
1402   case ARM::BX_CALL: {
1403     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1404       .addReg(ARM::LR)
1405       .addReg(ARM::PC)
1406       // Add predicate operands.
1407       .addImm(ARMCC::AL)
1408       .addReg(0)
1409       // Add 's' bit operand (always reg0 for this)
1410       .addReg(0));
1411 
1412     assert(Subtarget->hasV4TOps());
1413     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
1414       .addReg(MI->getOperand(0).getReg()));
1415     return;
1416   }
1417   case ARM::tBX_CALL: {
1418     if (Subtarget->hasV5TOps())
1419       llvm_unreachable("Expected BLX to be selected for v5t+");
1420 
1421     // On ARM v4t, when doing a call from thumb mode, we need to ensure
1422     // that the saved lr has its LSB set correctly (the arch doesn't
1423     // have blx).
1424     // So here we generate a bl to a small jump pad that does bx rN.
1425     // The jump pads are emitted after the function body.
1426 
1427     Register TReg = MI->getOperand(0).getReg();
1428     MCSymbol *TRegSym = nullptr;
1429     for (std::pair<unsigned, MCSymbol *> &TIP : ThumbIndirectPads) {
1430       if (TIP.first == TReg) {
1431         TRegSym = TIP.second;
1432         break;
1433       }
1434     }
1435 
1436     if (!TRegSym) {
1437       TRegSym = OutContext.createTempSymbol();
1438       ThumbIndirectPads.push_back(std::make_pair(TReg, TRegSym));
1439     }
1440 
1441     // Create a link-saving branch to the Reg Indirect Jump Pad.
1442     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBL)
1443         // Predicate comes first here.
1444         .addImm(ARMCC::AL).addReg(0)
1445         .addExpr(MCSymbolRefExpr::create(TRegSym, OutContext)));
1446     return;
1447   }
1448   case ARM::BMOVPCRX_CALL: {
1449     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1450       .addReg(ARM::LR)
1451       .addReg(ARM::PC)
1452       // Add predicate operands.
1453       .addImm(ARMCC::AL)
1454       .addReg(0)
1455       // Add 's' bit operand (always reg0 for this)
1456       .addReg(0));
1457 
1458     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1459       .addReg(ARM::PC)
1460       .addReg(MI->getOperand(0).getReg())
1461       // Add predicate operands.
1462       .addImm(ARMCC::AL)
1463       .addReg(0)
1464       // Add 's' bit operand (always reg0 for this)
1465       .addReg(0));
1466     return;
1467   }
1468   case ARM::BMOVPCB_CALL: {
1469     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1470       .addReg(ARM::LR)
1471       .addReg(ARM::PC)
1472       // Add predicate operands.
1473       .addImm(ARMCC::AL)
1474       .addReg(0)
1475       // Add 's' bit operand (always reg0 for this)
1476       .addReg(0));
1477 
1478     const MachineOperand &Op = MI->getOperand(0);
1479     const GlobalValue *GV = Op.getGlobal();
1480     const unsigned TF = Op.getTargetFlags();
1481     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1482     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1483     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::Bcc)
1484       .addExpr(GVSymExpr)
1485       // Add predicate operands.
1486       .addImm(ARMCC::AL)
1487       .addReg(0));
1488     return;
1489   }
1490   case ARM::MOVi16_ga_pcrel:
1491   case ARM::t2MOVi16_ga_pcrel: {
1492     MCInst TmpInst;
1493     TmpInst.setOpcode(Opc == ARM::MOVi16_ga_pcrel? ARM::MOVi16 : ARM::t2MOVi16);
1494     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1495 
1496     unsigned TF = MI->getOperand(1).getTargetFlags();
1497     const GlobalValue *GV = MI->getOperand(1).getGlobal();
1498     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1499     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1500 
1501     MCSymbol *LabelSym =
1502         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1503                     MI->getOperand(2).getImm(), OutContext);
1504     const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
1505     unsigned PCAdj = (Opc == ARM::MOVi16_ga_pcrel) ? 8 : 4;
1506     const MCExpr *PCRelExpr =
1507       ARMMCExpr::createLower16(MCBinaryExpr::createSub(GVSymExpr,
1508                                       MCBinaryExpr::createAdd(LabelSymExpr,
1509                                       MCConstantExpr::create(PCAdj, OutContext),
1510                                       OutContext), OutContext), OutContext);
1511       TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
1512 
1513     // Add predicate operands.
1514     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1515     TmpInst.addOperand(MCOperand::createReg(0));
1516     // Add 's' bit operand (always reg0 for this)
1517     TmpInst.addOperand(MCOperand::createReg(0));
1518     EmitToStreamer(*OutStreamer, TmpInst);
1519     return;
1520   }
1521   case ARM::MOVTi16_ga_pcrel:
1522   case ARM::t2MOVTi16_ga_pcrel: {
1523     MCInst TmpInst;
1524     TmpInst.setOpcode(Opc == ARM::MOVTi16_ga_pcrel
1525                       ? ARM::MOVTi16 : ARM::t2MOVTi16);
1526     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1527     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
1528 
1529     unsigned TF = MI->getOperand(2).getTargetFlags();
1530     const GlobalValue *GV = MI->getOperand(2).getGlobal();
1531     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1532     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1533 
1534     MCSymbol *LabelSym =
1535         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1536                     MI->getOperand(3).getImm(), OutContext);
1537     const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
1538     unsigned PCAdj = (Opc == ARM::MOVTi16_ga_pcrel) ? 8 : 4;
1539     const MCExpr *PCRelExpr =
1540         ARMMCExpr::createUpper16(MCBinaryExpr::createSub(GVSymExpr,
1541                                    MCBinaryExpr::createAdd(LabelSymExpr,
1542                                       MCConstantExpr::create(PCAdj, OutContext),
1543                                           OutContext), OutContext), OutContext);
1544       TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
1545     // Add predicate operands.
1546     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1547     TmpInst.addOperand(MCOperand::createReg(0));
1548     // Add 's' bit operand (always reg0 for this)
1549     TmpInst.addOperand(MCOperand::createReg(0));
1550     EmitToStreamer(*OutStreamer, TmpInst);
1551     return;
1552   }
1553   case ARM::t2BFi:
1554   case ARM::t2BFic:
1555   case ARM::t2BFLi:
1556   case ARM::t2BFr:
1557   case ARM::t2BFLr: {
1558     // This is a Branch Future instruction.
1559 
1560     const MCExpr *BranchLabel = MCSymbolRefExpr::create(
1561         getBFLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1562                    MI->getOperand(0).getIndex(), OutContext),
1563         OutContext);
1564 
1565     auto MCInst = MCInstBuilder(Opc).addExpr(BranchLabel);
1566     if (MI->getOperand(1).isReg()) {
1567       // For BFr/BFLr
1568       MCInst.addReg(MI->getOperand(1).getReg());
1569     } else {
1570       // For BFi/BFLi/BFic
1571       const MCExpr *BranchTarget;
1572       if (MI->getOperand(1).isMBB())
1573         BranchTarget = MCSymbolRefExpr::create(
1574             MI->getOperand(1).getMBB()->getSymbol(), OutContext);
1575       else if (MI->getOperand(1).isGlobal()) {
1576         const GlobalValue *GV = MI->getOperand(1).getGlobal();
1577         BranchTarget = MCSymbolRefExpr::create(
1578             GetARMGVSymbol(GV, MI->getOperand(1).getTargetFlags()), OutContext);
1579       } else if (MI->getOperand(1).isSymbol()) {
1580         BranchTarget = MCSymbolRefExpr::create(
1581             GetExternalSymbolSymbol(MI->getOperand(1).getSymbolName()),
1582             OutContext);
1583       } else
1584         llvm_unreachable("Unhandled operand kind in Branch Future instruction");
1585 
1586       MCInst.addExpr(BranchTarget);
1587     }
1588 
1589     if (Opc == ARM::t2BFic) {
1590       const MCExpr *ElseLabel = MCSymbolRefExpr::create(
1591           getBFLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1592                      MI->getOperand(2).getIndex(), OutContext),
1593           OutContext);
1594       MCInst.addExpr(ElseLabel);
1595       MCInst.addImm(MI->getOperand(3).getImm());
1596     } else {
1597       MCInst.addImm(MI->getOperand(2).getImm())
1598           .addReg(MI->getOperand(3).getReg());
1599     }
1600 
1601     EmitToStreamer(*OutStreamer, MCInst);
1602     return;
1603   }
1604   case ARM::t2BF_LabelPseudo: {
1605     // This is a pseudo op for a label used by a branch future instruction
1606 
1607     // Emit the label.
1608     OutStreamer->emitLabel(getBFLabel(DL.getPrivateGlobalPrefix(),
1609                                        getFunctionNumber(),
1610                                        MI->getOperand(0).getIndex(), OutContext));
1611     return;
1612   }
1613   case ARM::tPICADD: {
1614     // This is a pseudo op for a label + instruction sequence, which looks like:
1615     // LPC0:
1616     //     add r0, pc
1617     // This adds the address of LPC0 to r0.
1618 
1619     // Emit the label.
1620     OutStreamer->emitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1621                                        getFunctionNumber(),
1622                                        MI->getOperand(2).getImm(), OutContext));
1623 
1624     // Form and emit the add.
1625     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1626       .addReg(MI->getOperand(0).getReg())
1627       .addReg(MI->getOperand(0).getReg())
1628       .addReg(ARM::PC)
1629       // Add predicate operands.
1630       .addImm(ARMCC::AL)
1631       .addReg(0));
1632     return;
1633   }
1634   case ARM::PICADD: {
1635     // This is a pseudo op for a label + instruction sequence, which looks like:
1636     // LPC0:
1637     //     add r0, pc, r0
1638     // This adds the address of LPC0 to r0.
1639 
1640     // Emit the label.
1641     OutStreamer->emitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1642                                        getFunctionNumber(),
1643                                        MI->getOperand(2).getImm(), OutContext));
1644 
1645     // Form and emit the add.
1646     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
1647       .addReg(MI->getOperand(0).getReg())
1648       .addReg(ARM::PC)
1649       .addReg(MI->getOperand(1).getReg())
1650       // Add predicate operands.
1651       .addImm(MI->getOperand(3).getImm())
1652       .addReg(MI->getOperand(4).getReg())
1653       // Add 's' bit operand (always reg0 for this)
1654       .addReg(0));
1655     return;
1656   }
1657   case ARM::PICSTR:
1658   case ARM::PICSTRB:
1659   case ARM::PICSTRH:
1660   case ARM::PICLDR:
1661   case ARM::PICLDRB:
1662   case ARM::PICLDRH:
1663   case ARM::PICLDRSB:
1664   case ARM::PICLDRSH: {
1665     // This is a pseudo op for a label + instruction sequence, which looks like:
1666     // LPC0:
1667     //     OP r0, [pc, r0]
1668     // The LCP0 label is referenced by a constant pool entry in order to get
1669     // a PC-relative address at the ldr instruction.
1670 
1671     // Emit the label.
1672     OutStreamer->emitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1673                                        getFunctionNumber(),
1674                                        MI->getOperand(2).getImm(), OutContext));
1675 
1676     // Form and emit the load
1677     unsigned Opcode;
1678     switch (MI->getOpcode()) {
1679     default:
1680       llvm_unreachable("Unexpected opcode!");
1681     case ARM::PICSTR:   Opcode = ARM::STRrs; break;
1682     case ARM::PICSTRB:  Opcode = ARM::STRBrs; break;
1683     case ARM::PICSTRH:  Opcode = ARM::STRH; break;
1684     case ARM::PICLDR:   Opcode = ARM::LDRrs; break;
1685     case ARM::PICLDRB:  Opcode = ARM::LDRBrs; break;
1686     case ARM::PICLDRH:  Opcode = ARM::LDRH; break;
1687     case ARM::PICLDRSB: Opcode = ARM::LDRSB; break;
1688     case ARM::PICLDRSH: Opcode = ARM::LDRSH; break;
1689     }
1690     EmitToStreamer(*OutStreamer, MCInstBuilder(Opcode)
1691       .addReg(MI->getOperand(0).getReg())
1692       .addReg(ARM::PC)
1693       .addReg(MI->getOperand(1).getReg())
1694       .addImm(0)
1695       // Add predicate operands.
1696       .addImm(MI->getOperand(3).getImm())
1697       .addReg(MI->getOperand(4).getReg()));
1698 
1699     return;
1700   }
1701   case ARM::CONSTPOOL_ENTRY: {
1702     if (Subtarget->genExecuteOnly())
1703       llvm_unreachable("execute-only should not generate constant pools");
1704 
1705     /// CONSTPOOL_ENTRY - This instruction represents a floating constant pool
1706     /// in the function.  The first operand is the ID# for this instruction, the
1707     /// second is the index into the MachineConstantPool that this is, the third
1708     /// is the size in bytes of this constant pool entry.
1709     /// The required alignment is specified on the basic block holding this MI.
1710     unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
1711     unsigned CPIdx   = (unsigned)MI->getOperand(1).getIndex();
1712 
1713     // If this is the first entry of the pool, mark it.
1714     if (!InConstantPool) {
1715       OutStreamer->emitDataRegion(MCDR_DataRegion);
1716       InConstantPool = true;
1717     }
1718 
1719     OutStreamer->emitLabel(GetCPISymbol(LabelId));
1720 
1721     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
1722     if (MCPE.isMachineConstantPoolEntry())
1723       emitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
1724     else
1725       emitGlobalConstant(DL, MCPE.Val.ConstVal);
1726     return;
1727   }
1728   case ARM::JUMPTABLE_ADDRS:
1729     emitJumpTableAddrs(MI);
1730     return;
1731   case ARM::JUMPTABLE_INSTS:
1732     emitJumpTableInsts(MI);
1733     return;
1734   case ARM::JUMPTABLE_TBB:
1735   case ARM::JUMPTABLE_TBH:
1736     emitJumpTableTBInst(MI, MI->getOpcode() == ARM::JUMPTABLE_TBB ? 1 : 2);
1737     return;
1738   case ARM::t2BR_JT: {
1739     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1740       .addReg(ARM::PC)
1741       .addReg(MI->getOperand(0).getReg())
1742       // Add predicate operands.
1743       .addImm(ARMCC::AL)
1744       .addReg(0));
1745     return;
1746   }
1747   case ARM::t2TBB_JT:
1748   case ARM::t2TBH_JT: {
1749     unsigned Opc = MI->getOpcode() == ARM::t2TBB_JT ? ARM::t2TBB : ARM::t2TBH;
1750     // Lower and emit the PC label, then the instruction itself.
1751     OutStreamer->emitLabel(GetCPISymbol(MI->getOperand(3).getImm()));
1752     EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1753                                      .addReg(MI->getOperand(0).getReg())
1754                                      .addReg(MI->getOperand(1).getReg())
1755                                      // Add predicate operands.
1756                                      .addImm(ARMCC::AL)
1757                                      .addReg(0));
1758     return;
1759   }
1760   case ARM::tTBB_JT:
1761   case ARM::tTBH_JT: {
1762 
1763     bool Is8Bit = MI->getOpcode() == ARM::tTBB_JT;
1764     Register Base = MI->getOperand(0).getReg();
1765     Register Idx = MI->getOperand(1).getReg();
1766     assert(MI->getOperand(1).isKill() && "We need the index register as scratch!");
1767 
1768     // Multiply up idx if necessary.
1769     if (!Is8Bit)
1770       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLSLri)
1771                                        .addReg(Idx)
1772                                        .addReg(ARM::CPSR)
1773                                        .addReg(Idx)
1774                                        .addImm(1)
1775                                        // Add predicate operands.
1776                                        .addImm(ARMCC::AL)
1777                                        .addReg(0));
1778 
1779     if (Base == ARM::PC) {
1780       // TBB [base, idx] =
1781       //    ADDS idx, idx, base
1782       //    LDRB idx, [idx, #4] ; or LDRH if TBH
1783       //    LSLS idx, #1
1784       //    ADDS pc, pc, idx
1785 
1786       // When using PC as the base, it's important that there is no padding
1787       // between the last ADDS and the start of the jump table. The jump table
1788       // is 4-byte aligned, so we ensure we're 4 byte aligned here too.
1789       //
1790       // FIXME: Ideally we could vary the LDRB index based on the padding
1791       // between the sequence and jump table, however that relies on MCExprs
1792       // for load indexes which are currently not supported.
1793       OutStreamer->emitCodeAlignment(4, &getSubtargetInfo());
1794       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1795                                        .addReg(Idx)
1796                                        .addReg(Idx)
1797                                        .addReg(Base)
1798                                        // Add predicate operands.
1799                                        .addImm(ARMCC::AL)
1800                                        .addReg(0));
1801 
1802       unsigned Opc = Is8Bit ? ARM::tLDRBi : ARM::tLDRHi;
1803       EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1804                                        .addReg(Idx)
1805                                        .addReg(Idx)
1806                                        .addImm(Is8Bit ? 4 : 2)
1807                                        // Add predicate operands.
1808                                        .addImm(ARMCC::AL)
1809                                        .addReg(0));
1810     } else {
1811       // TBB [base, idx] =
1812       //    LDRB idx, [base, idx] ; or LDRH if TBH
1813       //    LSLS idx, #1
1814       //    ADDS pc, pc, idx
1815 
1816       unsigned Opc = Is8Bit ? ARM::tLDRBr : ARM::tLDRHr;
1817       EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1818                                        .addReg(Idx)
1819                                        .addReg(Base)
1820                                        .addReg(Idx)
1821                                        // Add predicate operands.
1822                                        .addImm(ARMCC::AL)
1823                                        .addReg(0));
1824     }
1825 
1826     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLSLri)
1827                                      .addReg(Idx)
1828                                      .addReg(ARM::CPSR)
1829                                      .addReg(Idx)
1830                                      .addImm(1)
1831                                      // Add predicate operands.
1832                                      .addImm(ARMCC::AL)
1833                                      .addReg(0));
1834 
1835     OutStreamer->emitLabel(GetCPISymbol(MI->getOperand(3).getImm()));
1836     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1837                                      .addReg(ARM::PC)
1838                                      .addReg(ARM::PC)
1839                                      .addReg(Idx)
1840                                      // Add predicate operands.
1841                                      .addImm(ARMCC::AL)
1842                                      .addReg(0));
1843     return;
1844   }
1845   case ARM::tBR_JTr:
1846   case ARM::BR_JTr: {
1847     // mov pc, target
1848     MCInst TmpInst;
1849     unsigned Opc = MI->getOpcode() == ARM::BR_JTr ?
1850       ARM::MOVr : ARM::tMOVr;
1851     TmpInst.setOpcode(Opc);
1852     TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1853     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1854     // Add predicate operands.
1855     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1856     TmpInst.addOperand(MCOperand::createReg(0));
1857     // Add 's' bit operand (always reg0 for this)
1858     if (Opc == ARM::MOVr)
1859       TmpInst.addOperand(MCOperand::createReg(0));
1860     EmitToStreamer(*OutStreamer, TmpInst);
1861     return;
1862   }
1863   case ARM::BR_JTm_i12: {
1864     // ldr pc, target
1865     MCInst TmpInst;
1866     TmpInst.setOpcode(ARM::LDRi12);
1867     TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1868     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1869     TmpInst.addOperand(MCOperand::createImm(MI->getOperand(2).getImm()));
1870     // Add predicate operands.
1871     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1872     TmpInst.addOperand(MCOperand::createReg(0));
1873     EmitToStreamer(*OutStreamer, TmpInst);
1874     return;
1875   }
1876   case ARM::BR_JTm_rs: {
1877     // ldr pc, target
1878     MCInst TmpInst;
1879     TmpInst.setOpcode(ARM::LDRrs);
1880     TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1881     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1882     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
1883     TmpInst.addOperand(MCOperand::createImm(MI->getOperand(2).getImm()));
1884     // Add predicate operands.
1885     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1886     TmpInst.addOperand(MCOperand::createReg(0));
1887     EmitToStreamer(*OutStreamer, TmpInst);
1888     return;
1889   }
1890   case ARM::BR_JTadd: {
1891     // add pc, target, idx
1892     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
1893       .addReg(ARM::PC)
1894       .addReg(MI->getOperand(0).getReg())
1895       .addReg(MI->getOperand(1).getReg())
1896       // Add predicate operands.
1897       .addImm(ARMCC::AL)
1898       .addReg(0)
1899       // Add 's' bit operand (always reg0 for this)
1900       .addReg(0));
1901     return;
1902   }
1903   case ARM::SPACE:
1904     OutStreamer->emitZeros(MI->getOperand(1).getImm());
1905     return;
1906   case ARM::TRAP: {
1907     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1908     // FIXME: Remove this special case when they do.
1909     if (!Subtarget->isTargetMachO()) {
1910       uint32_t Val = 0xe7ffdefeUL;
1911       OutStreamer->AddComment("trap");
1912       ATS.emitInst(Val);
1913       return;
1914     }
1915     break;
1916   }
1917   case ARM::TRAPNaCl: {
1918     uint32_t Val = 0xe7fedef0UL;
1919     OutStreamer->AddComment("trap");
1920     ATS.emitInst(Val);
1921     return;
1922   }
1923   case ARM::tTRAP: {
1924     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1925     // FIXME: Remove this special case when they do.
1926     if (!Subtarget->isTargetMachO()) {
1927       uint16_t Val = 0xdefe;
1928       OutStreamer->AddComment("trap");
1929       ATS.emitInst(Val, 'n');
1930       return;
1931     }
1932     break;
1933   }
1934   case ARM::t2Int_eh_sjlj_setjmp:
1935   case ARM::t2Int_eh_sjlj_setjmp_nofp:
1936   case ARM::tInt_eh_sjlj_setjmp: {
1937     // Two incoming args: GPR:$src, GPR:$val
1938     // mov $val, pc
1939     // adds $val, #7
1940     // str $val, [$src, #4]
1941     // movs r0, #0
1942     // b LSJLJEH
1943     // movs r0, #1
1944     // LSJLJEH:
1945     Register SrcReg = MI->getOperand(0).getReg();
1946     Register ValReg = MI->getOperand(1).getReg();
1947     MCSymbol *Label = OutContext.createTempSymbol("SJLJEH");
1948     OutStreamer->AddComment("eh_setjmp begin");
1949     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1950       .addReg(ValReg)
1951       .addReg(ARM::PC)
1952       // Predicate.
1953       .addImm(ARMCC::AL)
1954       .addReg(0));
1955 
1956     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDi3)
1957       .addReg(ValReg)
1958       // 's' bit operand
1959       .addReg(ARM::CPSR)
1960       .addReg(ValReg)
1961       .addImm(7)
1962       // Predicate.
1963       .addImm(ARMCC::AL)
1964       .addReg(0));
1965 
1966     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tSTRi)
1967       .addReg(ValReg)
1968       .addReg(SrcReg)
1969       // The offset immediate is #4. The operand value is scaled by 4 for the
1970       // tSTR instruction.
1971       .addImm(1)
1972       // Predicate.
1973       .addImm(ARMCC::AL)
1974       .addReg(0));
1975 
1976     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
1977       .addReg(ARM::R0)
1978       .addReg(ARM::CPSR)
1979       .addImm(0)
1980       // Predicate.
1981       .addImm(ARMCC::AL)
1982       .addReg(0));
1983 
1984     const MCExpr *SymbolExpr = MCSymbolRefExpr::create(Label, OutContext);
1985     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tB)
1986       .addExpr(SymbolExpr)
1987       .addImm(ARMCC::AL)
1988       .addReg(0));
1989 
1990     OutStreamer->AddComment("eh_setjmp end");
1991     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
1992       .addReg(ARM::R0)
1993       .addReg(ARM::CPSR)
1994       .addImm(1)
1995       // Predicate.
1996       .addImm(ARMCC::AL)
1997       .addReg(0));
1998 
1999     OutStreamer->emitLabel(Label);
2000     return;
2001   }
2002 
2003   case ARM::Int_eh_sjlj_setjmp_nofp:
2004   case ARM::Int_eh_sjlj_setjmp: {
2005     // Two incoming args: GPR:$src, GPR:$val
2006     // add $val, pc, #8
2007     // str $val, [$src, #+4]
2008     // mov r0, #0
2009     // add pc, pc, #0
2010     // mov r0, #1
2011     Register SrcReg = MI->getOperand(0).getReg();
2012     Register ValReg = MI->getOperand(1).getReg();
2013 
2014     OutStreamer->AddComment("eh_setjmp begin");
2015     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
2016       .addReg(ValReg)
2017       .addReg(ARM::PC)
2018       .addImm(8)
2019       // Predicate.
2020       .addImm(ARMCC::AL)
2021       .addReg(0)
2022       // 's' bit operand (always reg0 for this).
2023       .addReg(0));
2024 
2025     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::STRi12)
2026       .addReg(ValReg)
2027       .addReg(SrcReg)
2028       .addImm(4)
2029       // Predicate.
2030       .addImm(ARMCC::AL)
2031       .addReg(0));
2032 
2033     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
2034       .addReg(ARM::R0)
2035       .addImm(0)
2036       // Predicate.
2037       .addImm(ARMCC::AL)
2038       .addReg(0)
2039       // 's' bit operand (always reg0 for this).
2040       .addReg(0));
2041 
2042     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
2043       .addReg(ARM::PC)
2044       .addReg(ARM::PC)
2045       .addImm(0)
2046       // Predicate.
2047       .addImm(ARMCC::AL)
2048       .addReg(0)
2049       // 's' bit operand (always reg0 for this).
2050       .addReg(0));
2051 
2052     OutStreamer->AddComment("eh_setjmp end");
2053     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
2054       .addReg(ARM::R0)
2055       .addImm(1)
2056       // Predicate.
2057       .addImm(ARMCC::AL)
2058       .addReg(0)
2059       // 's' bit operand (always reg0 for this).
2060       .addReg(0));
2061     return;
2062   }
2063   case ARM::Int_eh_sjlj_longjmp: {
2064     // ldr sp, [$src, #8]
2065     // ldr $scratch, [$src, #4]
2066     // ldr r7, [$src]
2067     // bx $scratch
2068     Register SrcReg = MI->getOperand(0).getReg();
2069     Register ScratchReg = MI->getOperand(1).getReg();
2070     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
2071       .addReg(ARM::SP)
2072       .addReg(SrcReg)
2073       .addImm(8)
2074       // Predicate.
2075       .addImm(ARMCC::AL)
2076       .addReg(0));
2077 
2078     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
2079       .addReg(ScratchReg)
2080       .addReg(SrcReg)
2081       .addImm(4)
2082       // Predicate.
2083       .addImm(ARMCC::AL)
2084       .addReg(0));
2085 
2086     const MachineFunction &MF = *MI->getParent()->getParent();
2087     const ARMSubtarget &STI = MF.getSubtarget<ARMSubtarget>();
2088 
2089     if (STI.isTargetDarwin() || STI.isTargetWindows()) {
2090       // These platforms always use the same frame register
2091       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
2092                                        .addReg(STI.getFramePointerReg())
2093                                        .addReg(SrcReg)
2094                                        .addImm(0)
2095                                        // Predicate.
2096                                        .addImm(ARMCC::AL)
2097                                        .addReg(0));
2098     } else {
2099       // If the calling code might use either R7 or R11 as
2100       // frame pointer register, restore it into both.
2101       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
2102         .addReg(ARM::R7)
2103         .addReg(SrcReg)
2104         .addImm(0)
2105         // Predicate.
2106         .addImm(ARMCC::AL)
2107         .addReg(0));
2108       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
2109         .addReg(ARM::R11)
2110         .addReg(SrcReg)
2111         .addImm(0)
2112         // Predicate.
2113         .addImm(ARMCC::AL)
2114         .addReg(0));
2115     }
2116 
2117     assert(Subtarget->hasV4TOps());
2118     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
2119       .addReg(ScratchReg)
2120       // Predicate.
2121       .addImm(ARMCC::AL)
2122       .addReg(0));
2123     return;
2124   }
2125   case ARM::tInt_eh_sjlj_longjmp: {
2126     // ldr $scratch, [$src, #8]
2127     // mov sp, $scratch
2128     // ldr $scratch, [$src, #4]
2129     // ldr r7, [$src]
2130     // bx $scratch
2131     Register SrcReg = MI->getOperand(0).getReg();
2132     Register ScratchReg = MI->getOperand(1).getReg();
2133 
2134     const MachineFunction &MF = *MI->getParent()->getParent();
2135     const ARMSubtarget &STI = MF.getSubtarget<ARMSubtarget>();
2136 
2137     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
2138       .addReg(ScratchReg)
2139       .addReg(SrcReg)
2140       // The offset immediate is #8. The operand value is scaled by 4 for the
2141       // tLDR instruction.
2142       .addImm(2)
2143       // Predicate.
2144       .addImm(ARMCC::AL)
2145       .addReg(0));
2146 
2147     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
2148       .addReg(ARM::SP)
2149       .addReg(ScratchReg)
2150       // Predicate.
2151       .addImm(ARMCC::AL)
2152       .addReg(0));
2153 
2154     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
2155       .addReg(ScratchReg)
2156       .addReg(SrcReg)
2157       .addImm(1)
2158       // Predicate.
2159       .addImm(ARMCC::AL)
2160       .addReg(0));
2161 
2162     if (STI.isTargetDarwin() || STI.isTargetWindows()) {
2163       // These platforms always use the same frame register
2164       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
2165                                        .addReg(STI.getFramePointerReg())
2166                                        .addReg(SrcReg)
2167                                        .addImm(0)
2168                                        // Predicate.
2169                                        .addImm(ARMCC::AL)
2170                                        .addReg(0));
2171     } else {
2172       // If the calling code might use either R7 or R11 as
2173       // frame pointer register, restore it into both.
2174       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
2175         .addReg(ARM::R7)
2176         .addReg(SrcReg)
2177         .addImm(0)
2178         // Predicate.
2179         .addImm(ARMCC::AL)
2180         .addReg(0));
2181       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
2182         .addReg(ARM::R11)
2183         .addReg(SrcReg)
2184         .addImm(0)
2185         // Predicate.
2186         .addImm(ARMCC::AL)
2187         .addReg(0));
2188     }
2189 
2190     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBX)
2191       .addReg(ScratchReg)
2192       // Predicate.
2193       .addImm(ARMCC::AL)
2194       .addReg(0));
2195     return;
2196   }
2197   case ARM::tInt_WIN_eh_sjlj_longjmp: {
2198     // ldr.w r11, [$src, #0]
2199     // ldr.w  sp, [$src, #8]
2200     // ldr.w  pc, [$src, #4]
2201 
2202     Register SrcReg = MI->getOperand(0).getReg();
2203 
2204     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
2205                                      .addReg(ARM::R11)
2206                                      .addReg(SrcReg)
2207                                      .addImm(0)
2208                                      // Predicate
2209                                      .addImm(ARMCC::AL)
2210                                      .addReg(0));
2211     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
2212                                      .addReg(ARM::SP)
2213                                      .addReg(SrcReg)
2214                                      .addImm(8)
2215                                      // Predicate
2216                                      .addImm(ARMCC::AL)
2217                                      .addReg(0));
2218     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
2219                                      .addReg(ARM::PC)
2220                                      .addReg(SrcReg)
2221                                      .addImm(4)
2222                                      // Predicate
2223                                      .addImm(ARMCC::AL)
2224                                      .addReg(0));
2225     return;
2226   }
2227   case ARM::PATCHABLE_FUNCTION_ENTER:
2228     LowerPATCHABLE_FUNCTION_ENTER(*MI);
2229     return;
2230   case ARM::PATCHABLE_FUNCTION_EXIT:
2231     LowerPATCHABLE_FUNCTION_EXIT(*MI);
2232     return;
2233   case ARM::PATCHABLE_TAIL_CALL:
2234     LowerPATCHABLE_TAIL_CALL(*MI);
2235     return;
2236   case ARM::SpeculationBarrierISBDSBEndBB: {
2237     // Print DSB SYS + ISB
2238     MCInst TmpInstDSB;
2239     TmpInstDSB.setOpcode(ARM::DSB);
2240     TmpInstDSB.addOperand(MCOperand::createImm(0xf));
2241     EmitToStreamer(*OutStreamer, TmpInstDSB);
2242     MCInst TmpInstISB;
2243     TmpInstISB.setOpcode(ARM::ISB);
2244     TmpInstISB.addOperand(MCOperand::createImm(0xf));
2245     EmitToStreamer(*OutStreamer, TmpInstISB);
2246     return;
2247   }
2248   case ARM::t2SpeculationBarrierISBDSBEndBB: {
2249     // Print DSB SYS + ISB
2250     MCInst TmpInstDSB;
2251     TmpInstDSB.setOpcode(ARM::t2DSB);
2252     TmpInstDSB.addOperand(MCOperand::createImm(0xf));
2253     TmpInstDSB.addOperand(MCOperand::createImm(ARMCC::AL));
2254     TmpInstDSB.addOperand(MCOperand::createReg(0));
2255     EmitToStreamer(*OutStreamer, TmpInstDSB);
2256     MCInst TmpInstISB;
2257     TmpInstISB.setOpcode(ARM::t2ISB);
2258     TmpInstISB.addOperand(MCOperand::createImm(0xf));
2259     TmpInstISB.addOperand(MCOperand::createImm(ARMCC::AL));
2260     TmpInstISB.addOperand(MCOperand::createReg(0));
2261     EmitToStreamer(*OutStreamer, TmpInstISB);
2262     return;
2263   }
2264   case ARM::SpeculationBarrierSBEndBB: {
2265     // Print SB
2266     MCInst TmpInstSB;
2267     TmpInstSB.setOpcode(ARM::SB);
2268     EmitToStreamer(*OutStreamer, TmpInstSB);
2269     return;
2270   }
2271   case ARM::t2SpeculationBarrierSBEndBB: {
2272     // Print SB
2273     MCInst TmpInstSB;
2274     TmpInstSB.setOpcode(ARM::t2SB);
2275     EmitToStreamer(*OutStreamer, TmpInstSB);
2276     return;
2277   }
2278   }
2279 
2280   MCInst TmpInst;
2281   LowerARMMachineInstrToMCInst(MI, TmpInst, *this);
2282 
2283   EmitToStreamer(*OutStreamer, TmpInst);
2284 }
2285 
2286 //===----------------------------------------------------------------------===//
2287 // Target Registry Stuff
2288 //===----------------------------------------------------------------------===//
2289 
2290 // Force static initialization.
2291 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeARMAsmPrinter() {
2292   RegisterAsmPrinter<ARMAsmPrinter> X(getTheARMLETarget());
2293   RegisterAsmPrinter<ARMAsmPrinter> Y(getTheARMBETarget());
2294   RegisterAsmPrinter<ARMAsmPrinter> A(getTheThumbLETarget());
2295   RegisterAsmPrinter<ARMAsmPrinter> B(getTheThumbBETarget());
2296 }
2297