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