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