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   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
1170   OutStreamer->EmitLabel(JTISymbol);
1171 
1172   // Emit each entry of the table.
1173   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1174   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1175   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1176 
1177   // Mark the jump table as data-in-code.
1178   OutStreamer->EmitDataRegion(OffsetWidth == 1 ? MCDR_DataRegionJT8
1179                                                : MCDR_DataRegionJT16);
1180 
1181   for (auto MBB : JTBBs) {
1182     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
1183                                                           OutContext);
1184     // Otherwise it's an offset from the dispatch instruction. Construct an
1185     // MCExpr for the entry. We want a value of the form:
1186     // (BasicBlockAddr - TBBInstAddr + 4) / 2
1187     //
1188     // For example, a TBB table with entries jumping to basic blocks BB0 and BB1
1189     // would look like:
1190     // LJTI_0_0:
1191     //    .byte (LBB0 - (LCPI0_0 + 4)) / 2
1192     //    .byte (LBB1 - (LCPI0_0 + 4)) / 2
1193     // where LCPI0_0 is a label defined just before the TBB instruction using
1194     // this table.
1195     MCSymbol *TBInstPC = GetCPISymbol(MI->getOperand(0).getImm());
1196     const MCExpr *Expr = MCBinaryExpr::createAdd(
1197         MCSymbolRefExpr::create(TBInstPC, OutContext),
1198         MCConstantExpr::create(4, OutContext), OutContext);
1199     Expr = MCBinaryExpr::createSub(MBBSymbolExpr, Expr, OutContext);
1200     Expr = MCBinaryExpr::createDiv(Expr, MCConstantExpr::create(2, OutContext),
1201                                    OutContext);
1202     OutStreamer->EmitValue(Expr, OffsetWidth);
1203   }
1204   // Mark the end of jump table data-in-code region. 32-bit offsets use
1205   // actual branch instructions here, so we don't mark those as a data-region
1206   // at all.
1207   OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1208 
1209   // Make sure the next instruction is 2-byte aligned.
1210   EmitAlignment(1);
1211 }
1212 
1213 void ARMAsmPrinter::EmitUnwindingInstruction(const MachineInstr *MI) {
1214   assert(MI->getFlag(MachineInstr::FrameSetup) &&
1215       "Only instruction which are involved into frame setup code are allowed");
1216 
1217   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
1218   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1219   const MachineFunction &MF = *MI->getParent()->getParent();
1220   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
1221   const ARMFunctionInfo &AFI = *MF.getInfo<ARMFunctionInfo>();
1222 
1223   unsigned FramePtr = RegInfo->getFrameRegister(MF);
1224   unsigned Opc = MI->getOpcode();
1225   unsigned SrcReg, DstReg;
1226 
1227   if (Opc == ARM::tPUSH || Opc == ARM::tLDRpci) {
1228     // Two special cases:
1229     // 1) tPUSH does not have src/dst regs.
1230     // 2) for Thumb1 code we sometimes materialize the constant via constpool
1231     // load. Yes, this is pretty fragile, but for now I don't see better
1232     // way... :(
1233     SrcReg = DstReg = ARM::SP;
1234   } else {
1235     SrcReg = MI->getOperand(1).getReg();
1236     DstReg = MI->getOperand(0).getReg();
1237   }
1238 
1239   // Try to figure out the unwinding opcode out of src / dst regs.
1240   if (MI->mayStore()) {
1241     // Register saves.
1242     assert(DstReg == ARM::SP &&
1243            "Only stack pointer as a destination reg is supported");
1244 
1245     SmallVector<unsigned, 4> RegList;
1246     // Skip src & dst reg, and pred ops.
1247     unsigned StartOp = 2 + 2;
1248     // Use all the operands.
1249     unsigned NumOffset = 0;
1250 
1251     switch (Opc) {
1252     default:
1253       MI->dump();
1254       llvm_unreachable("Unsupported opcode for unwinding information");
1255     case ARM::tPUSH:
1256       // Special case here: no src & dst reg, but two extra imp ops.
1257       StartOp = 2; NumOffset = 2;
1258     case ARM::STMDB_UPD:
1259     case ARM::t2STMDB_UPD:
1260     case ARM::VSTMDDB_UPD:
1261       assert(SrcReg == ARM::SP &&
1262              "Only stack pointer as a source reg is supported");
1263       for (unsigned i = StartOp, NumOps = MI->getNumOperands() - NumOffset;
1264            i != NumOps; ++i) {
1265         const MachineOperand &MO = MI->getOperand(i);
1266         // Actually, there should never be any impdef stuff here. Skip it
1267         // temporary to workaround PR11902.
1268         if (MO.isImplicit())
1269           continue;
1270         RegList.push_back(MO.getReg());
1271       }
1272       break;
1273     case ARM::STR_PRE_IMM:
1274     case ARM::STR_PRE_REG:
1275     case ARM::t2STR_PRE:
1276       assert(MI->getOperand(2).getReg() == ARM::SP &&
1277              "Only stack pointer as a source reg is supported");
1278       RegList.push_back(SrcReg);
1279       break;
1280     }
1281     if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM)
1282       ATS.emitRegSave(RegList, Opc == ARM::VSTMDDB_UPD);
1283   } else {
1284     // Changes of stack / frame pointer.
1285     if (SrcReg == ARM::SP) {
1286       int64_t Offset = 0;
1287       switch (Opc) {
1288       default:
1289         MI->dump();
1290         llvm_unreachable("Unsupported opcode for unwinding information");
1291       case ARM::MOVr:
1292       case ARM::tMOVr:
1293         Offset = 0;
1294         break;
1295       case ARM::ADDri:
1296       case ARM::t2ADDri:
1297         Offset = -MI->getOperand(2).getImm();
1298         break;
1299       case ARM::SUBri:
1300       case ARM::t2SUBri:
1301         Offset = MI->getOperand(2).getImm();
1302         break;
1303       case ARM::tSUBspi:
1304         Offset = MI->getOperand(2).getImm()*4;
1305         break;
1306       case ARM::tADDspi:
1307       case ARM::tADDrSPi:
1308         Offset = -MI->getOperand(2).getImm()*4;
1309         break;
1310       case ARM::tLDRpci: {
1311         // Grab the constpool index and check, whether it corresponds to
1312         // original or cloned constpool entry.
1313         unsigned CPI = MI->getOperand(1).getIndex();
1314         const MachineConstantPool *MCP = MF.getConstantPool();
1315         if (CPI >= MCP->getConstants().size())
1316           CPI = AFI.getOriginalCPIdx(CPI);
1317         assert(CPI != -1U && "Invalid constpool index");
1318 
1319         // Derive the actual offset.
1320         const MachineConstantPoolEntry &CPE = MCP->getConstants()[CPI];
1321         assert(!CPE.isMachineConstantPoolEntry() && "Invalid constpool entry");
1322         // FIXME: Check for user, it should be "add" instruction!
1323         Offset = -cast<ConstantInt>(CPE.Val.ConstVal)->getSExtValue();
1324         break;
1325       }
1326       }
1327 
1328       if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM) {
1329         if (DstReg == FramePtr && FramePtr != ARM::SP)
1330           // Set-up of the frame pointer. Positive values correspond to "add"
1331           // instruction.
1332           ATS.emitSetFP(FramePtr, ARM::SP, -Offset);
1333         else if (DstReg == ARM::SP) {
1334           // Change of SP by an offset. Positive values correspond to "sub"
1335           // instruction.
1336           ATS.emitPad(Offset);
1337         } else {
1338           // Move of SP to a register.  Positive values correspond to an "add"
1339           // instruction.
1340           ATS.emitMovSP(DstReg, -Offset);
1341         }
1342       }
1343     } else if (DstReg == ARM::SP) {
1344       MI->dump();
1345       llvm_unreachable("Unsupported opcode for unwinding information");
1346     }
1347     else {
1348       MI->dump();
1349       llvm_unreachable("Unsupported opcode for unwinding information");
1350     }
1351   }
1352 }
1353 
1354 // Simple pseudo-instructions have their lowering (with expansion to real
1355 // instructions) auto-generated.
1356 #include "ARMGenMCPseudoLowering.inc"
1357 
1358 void ARMAsmPrinter::EmitInstruction(const MachineInstr *MI) {
1359   const DataLayout &DL = getDataLayout();
1360   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
1361   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1362 
1363   // If we just ended a constant pool, mark it as such.
1364   if (InConstantPool && MI->getOpcode() != ARM::CONSTPOOL_ENTRY) {
1365     OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1366     InConstantPool = false;
1367   }
1368 
1369   // Emit unwinding stuff for frame-related instructions
1370   if (Subtarget->isTargetEHABICompatible() &&
1371        MI->getFlag(MachineInstr::FrameSetup))
1372     EmitUnwindingInstruction(MI);
1373 
1374   // Do any auto-generated pseudo lowerings.
1375   if (emitPseudoExpansionLowering(*OutStreamer, MI))
1376     return;
1377 
1378   assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
1379          "Pseudo flag setting opcode should be expanded early");
1380 
1381   // Check for manual lowerings.
1382   unsigned Opc = MI->getOpcode();
1383   switch (Opc) {
1384   case ARM::t2MOVi32imm: llvm_unreachable("Should be lowered by thumb2it pass");
1385   case ARM::DBG_VALUE: llvm_unreachable("Should be handled by generic printing");
1386   case ARM::LEApcrel:
1387   case ARM::tLEApcrel:
1388   case ARM::t2LEApcrel: {
1389     // FIXME: Need to also handle globals and externals
1390     MCSymbol *CPISymbol = GetCPISymbol(MI->getOperand(1).getIndex());
1391     EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
1392                                                ARM::t2LEApcrel ? ARM::t2ADR
1393                   : (MI->getOpcode() == ARM::tLEApcrel ? ARM::tADR
1394                      : ARM::ADR))
1395       .addReg(MI->getOperand(0).getReg())
1396       .addExpr(MCSymbolRefExpr::create(CPISymbol, OutContext))
1397       // Add predicate operands.
1398       .addImm(MI->getOperand(2).getImm())
1399       .addReg(MI->getOperand(3).getReg()));
1400     return;
1401   }
1402   case ARM::LEApcrelJT:
1403   case ARM::tLEApcrelJT:
1404   case ARM::t2LEApcrelJT: {
1405     MCSymbol *JTIPICSymbol =
1406       GetARMJTIPICJumpTableLabel(MI->getOperand(1).getIndex());
1407     EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
1408                                                ARM::t2LEApcrelJT ? ARM::t2ADR
1409                   : (MI->getOpcode() == ARM::tLEApcrelJT ? ARM::tADR
1410                      : ARM::ADR))
1411       .addReg(MI->getOperand(0).getReg())
1412       .addExpr(MCSymbolRefExpr::create(JTIPICSymbol, OutContext))
1413       // Add predicate operands.
1414       .addImm(MI->getOperand(2).getImm())
1415       .addReg(MI->getOperand(3).getReg()));
1416     return;
1417   }
1418   // Darwin call instructions are just normal call instructions with different
1419   // clobber semantics (they clobber R9).
1420   case ARM::BX_CALL: {
1421     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1422       .addReg(ARM::LR)
1423       .addReg(ARM::PC)
1424       // Add predicate operands.
1425       .addImm(ARMCC::AL)
1426       .addReg(0)
1427       // Add 's' bit operand (always reg0 for this)
1428       .addReg(0));
1429 
1430     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
1431       .addReg(MI->getOperand(0).getReg()));
1432     return;
1433   }
1434   case ARM::tBX_CALL: {
1435     if (Subtarget->hasV5TOps())
1436       llvm_unreachable("Expected BLX to be selected for v5t+");
1437 
1438     // On ARM v4t, when doing a call from thumb mode, we need to ensure
1439     // that the saved lr has its LSB set correctly (the arch doesn't
1440     // have blx).
1441     // So here we generate a bl to a small jump pad that does bx rN.
1442     // The jump pads are emitted after the function body.
1443 
1444     unsigned TReg = MI->getOperand(0).getReg();
1445     MCSymbol *TRegSym = nullptr;
1446     for (unsigned i = 0, e = ThumbIndirectPads.size(); i < e; i++) {
1447       if (ThumbIndirectPads[i].first == TReg) {
1448         TRegSym = ThumbIndirectPads[i].second;
1449         break;
1450       }
1451     }
1452 
1453     if (!TRegSym) {
1454       TRegSym = OutContext.createTempSymbol();
1455       ThumbIndirectPads.push_back(std::make_pair(TReg, TRegSym));
1456     }
1457 
1458     // Create a link-saving branch to the Reg Indirect Jump Pad.
1459     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBL)
1460         // Predicate comes first here.
1461         .addImm(ARMCC::AL).addReg(0)
1462         .addExpr(MCSymbolRefExpr::create(TRegSym, OutContext)));
1463     return;
1464   }
1465   case ARM::BMOVPCRX_CALL: {
1466     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1467       .addReg(ARM::LR)
1468       .addReg(ARM::PC)
1469       // Add predicate operands.
1470       .addImm(ARMCC::AL)
1471       .addReg(0)
1472       // Add 's' bit operand (always reg0 for this)
1473       .addReg(0));
1474 
1475     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1476       .addReg(ARM::PC)
1477       .addReg(MI->getOperand(0).getReg())
1478       // Add predicate operands.
1479       .addImm(ARMCC::AL)
1480       .addReg(0)
1481       // Add 's' bit operand (always reg0 for this)
1482       .addReg(0));
1483     return;
1484   }
1485   case ARM::BMOVPCB_CALL: {
1486     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1487       .addReg(ARM::LR)
1488       .addReg(ARM::PC)
1489       // Add predicate operands.
1490       .addImm(ARMCC::AL)
1491       .addReg(0)
1492       // Add 's' bit operand (always reg0 for this)
1493       .addReg(0));
1494 
1495     const MachineOperand &Op = MI->getOperand(0);
1496     const GlobalValue *GV = Op.getGlobal();
1497     const unsigned TF = Op.getTargetFlags();
1498     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1499     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1500     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::Bcc)
1501       .addExpr(GVSymExpr)
1502       // Add predicate operands.
1503       .addImm(ARMCC::AL)
1504       .addReg(0));
1505     return;
1506   }
1507   case ARM::MOVi16_ga_pcrel:
1508   case ARM::t2MOVi16_ga_pcrel: {
1509     MCInst TmpInst;
1510     TmpInst.setOpcode(Opc == ARM::MOVi16_ga_pcrel? ARM::MOVi16 : ARM::t2MOVi16);
1511     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1512 
1513     unsigned TF = MI->getOperand(1).getTargetFlags();
1514     const GlobalValue *GV = MI->getOperand(1).getGlobal();
1515     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1516     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1517 
1518     MCSymbol *LabelSym =
1519         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1520                     MI->getOperand(2).getImm(), OutContext);
1521     const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
1522     unsigned PCAdj = (Opc == ARM::MOVi16_ga_pcrel) ? 8 : 4;
1523     const MCExpr *PCRelExpr =
1524       ARMMCExpr::createLower16(MCBinaryExpr::createSub(GVSymExpr,
1525                                       MCBinaryExpr::createAdd(LabelSymExpr,
1526                                       MCConstantExpr::create(PCAdj, OutContext),
1527                                       OutContext), OutContext), OutContext);
1528       TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
1529 
1530     // Add predicate operands.
1531     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1532     TmpInst.addOperand(MCOperand::createReg(0));
1533     // Add 's' bit operand (always reg0 for this)
1534     TmpInst.addOperand(MCOperand::createReg(0));
1535     EmitToStreamer(*OutStreamer, TmpInst);
1536     return;
1537   }
1538   case ARM::MOVTi16_ga_pcrel:
1539   case ARM::t2MOVTi16_ga_pcrel: {
1540     MCInst TmpInst;
1541     TmpInst.setOpcode(Opc == ARM::MOVTi16_ga_pcrel
1542                       ? ARM::MOVTi16 : ARM::t2MOVTi16);
1543     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1544     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
1545 
1546     unsigned TF = MI->getOperand(2).getTargetFlags();
1547     const GlobalValue *GV = MI->getOperand(2).getGlobal();
1548     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1549     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1550 
1551     MCSymbol *LabelSym =
1552         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1553                     MI->getOperand(3).getImm(), OutContext);
1554     const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
1555     unsigned PCAdj = (Opc == ARM::MOVTi16_ga_pcrel) ? 8 : 4;
1556     const MCExpr *PCRelExpr =
1557         ARMMCExpr::createUpper16(MCBinaryExpr::createSub(GVSymExpr,
1558                                    MCBinaryExpr::createAdd(LabelSymExpr,
1559                                       MCConstantExpr::create(PCAdj, OutContext),
1560                                           OutContext), OutContext), OutContext);
1561       TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
1562     // Add predicate operands.
1563     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1564     TmpInst.addOperand(MCOperand::createReg(0));
1565     // Add 's' bit operand (always reg0 for this)
1566     TmpInst.addOperand(MCOperand::createReg(0));
1567     EmitToStreamer(*OutStreamer, TmpInst);
1568     return;
1569   }
1570   case ARM::tPICADD: {
1571     // This is a pseudo op for a label + instruction sequence, which looks like:
1572     // LPC0:
1573     //     add r0, pc
1574     // This adds the address of LPC0 to r0.
1575 
1576     // Emit the label.
1577     OutStreamer->EmitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1578                                        getFunctionNumber(),
1579                                        MI->getOperand(2).getImm(), OutContext));
1580 
1581     // Form and emit the add.
1582     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1583       .addReg(MI->getOperand(0).getReg())
1584       .addReg(MI->getOperand(0).getReg())
1585       .addReg(ARM::PC)
1586       // Add predicate operands.
1587       .addImm(ARMCC::AL)
1588       .addReg(0));
1589     return;
1590   }
1591   case ARM::PICADD: {
1592     // This is a pseudo op for a label + instruction sequence, which looks like:
1593     // LPC0:
1594     //     add r0, pc, r0
1595     // This adds the address of LPC0 to r0.
1596 
1597     // Emit the label.
1598     OutStreamer->EmitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1599                                        getFunctionNumber(),
1600                                        MI->getOperand(2).getImm(), OutContext));
1601 
1602     // Form and emit the add.
1603     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
1604       .addReg(MI->getOperand(0).getReg())
1605       .addReg(ARM::PC)
1606       .addReg(MI->getOperand(1).getReg())
1607       // Add predicate operands.
1608       .addImm(MI->getOperand(3).getImm())
1609       .addReg(MI->getOperand(4).getReg())
1610       // Add 's' bit operand (always reg0 for this)
1611       .addReg(0));
1612     return;
1613   }
1614   case ARM::PICSTR:
1615   case ARM::PICSTRB:
1616   case ARM::PICSTRH:
1617   case ARM::PICLDR:
1618   case ARM::PICLDRB:
1619   case ARM::PICLDRH:
1620   case ARM::PICLDRSB:
1621   case ARM::PICLDRSH: {
1622     // This is a pseudo op for a label + instruction sequence, which looks like:
1623     // LPC0:
1624     //     OP r0, [pc, r0]
1625     // The LCP0 label is referenced by a constant pool entry in order to get
1626     // a PC-relative address at the ldr instruction.
1627 
1628     // Emit the label.
1629     OutStreamer->EmitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1630                                        getFunctionNumber(),
1631                                        MI->getOperand(2).getImm(), OutContext));
1632 
1633     // Form and emit the load
1634     unsigned Opcode;
1635     switch (MI->getOpcode()) {
1636     default:
1637       llvm_unreachable("Unexpected opcode!");
1638     case ARM::PICSTR:   Opcode = ARM::STRrs; break;
1639     case ARM::PICSTRB:  Opcode = ARM::STRBrs; break;
1640     case ARM::PICSTRH:  Opcode = ARM::STRH; break;
1641     case ARM::PICLDR:   Opcode = ARM::LDRrs; break;
1642     case ARM::PICLDRB:  Opcode = ARM::LDRBrs; break;
1643     case ARM::PICLDRH:  Opcode = ARM::LDRH; break;
1644     case ARM::PICLDRSB: Opcode = ARM::LDRSB; break;
1645     case ARM::PICLDRSH: Opcode = ARM::LDRSH; break;
1646     }
1647     EmitToStreamer(*OutStreamer, MCInstBuilder(Opcode)
1648       .addReg(MI->getOperand(0).getReg())
1649       .addReg(ARM::PC)
1650       .addReg(MI->getOperand(1).getReg())
1651       .addImm(0)
1652       // Add predicate operands.
1653       .addImm(MI->getOperand(3).getImm())
1654       .addReg(MI->getOperand(4).getReg()));
1655 
1656     return;
1657   }
1658   case ARM::CONSTPOOL_ENTRY: {
1659     /// CONSTPOOL_ENTRY - This instruction represents a floating constant pool
1660     /// in the function.  The first operand is the ID# for this instruction, the
1661     /// second is the index into the MachineConstantPool that this is, the third
1662     /// is the size in bytes of this constant pool entry.
1663     /// The required alignment is specified on the basic block holding this MI.
1664     unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
1665     unsigned CPIdx   = (unsigned)MI->getOperand(1).getIndex();
1666 
1667     // If this is the first entry of the pool, mark it.
1668     if (!InConstantPool) {
1669       OutStreamer->EmitDataRegion(MCDR_DataRegion);
1670       InConstantPool = true;
1671     }
1672 
1673     OutStreamer->EmitLabel(GetCPISymbol(LabelId));
1674 
1675     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
1676     if (MCPE.isMachineConstantPoolEntry())
1677       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
1678     else
1679       EmitGlobalConstant(DL, MCPE.Val.ConstVal);
1680     return;
1681   }
1682   case ARM::JUMPTABLE_ADDRS:
1683     EmitJumpTableAddrs(MI);
1684     return;
1685   case ARM::JUMPTABLE_INSTS:
1686     EmitJumpTableInsts(MI);
1687     return;
1688   case ARM::JUMPTABLE_TBB:
1689   case ARM::JUMPTABLE_TBH:
1690     EmitJumpTableTBInst(MI, MI->getOpcode() == ARM::JUMPTABLE_TBB ? 1 : 2);
1691     return;
1692   case ARM::t2BR_JT: {
1693     // Lower and emit the instruction itself, then the jump table following it.
1694     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1695       .addReg(ARM::PC)
1696       .addReg(MI->getOperand(0).getReg())
1697       // Add predicate operands.
1698       .addImm(ARMCC::AL)
1699       .addReg(0));
1700     return;
1701   }
1702   case ARM::t2TBB_JT:
1703   case ARM::t2TBH_JT: {
1704     unsigned Opc = MI->getOpcode() == ARM::t2TBB_JT ? ARM::t2TBB : ARM::t2TBH;
1705     // Lower and emit the PC label, then the instruction itself.
1706     OutStreamer->EmitLabel(GetCPISymbol(MI->getOperand(3).getImm()));
1707     EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1708                                      .addReg(MI->getOperand(0).getReg())
1709                                      .addReg(MI->getOperand(1).getReg())
1710                                      // Add predicate operands.
1711                                      .addImm(ARMCC::AL)
1712                                      .addReg(0));
1713     return;
1714   }
1715   case ARM::tTBB_JT:
1716   case ARM::tTBH_JT: {
1717 
1718     bool Is8Bit = MI->getOpcode() == ARM::tTBB_JT;
1719     unsigned Base = MI->getOperand(0).getReg();
1720     unsigned Idx = MI->getOperand(1).getReg();
1721     assert(MI->getOperand(1).isKill() && "We need the index register as scratch!");
1722 
1723     // Multiply up idx if necessary.
1724     if (!Is8Bit)
1725       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLSLri)
1726                                        .addReg(Idx)
1727                                        .addReg(ARM::CPSR)
1728                                        .addReg(Idx)
1729                                        .addImm(1)
1730                                        // Add predicate operands.
1731                                        .addImm(ARMCC::AL)
1732                                        .addReg(0));
1733 
1734     if (Base == ARM::PC) {
1735       // TBB [base, idx] =
1736       //    ADDS idx, idx, base
1737       //    LDRB idx, [idx, #4] ; or LDRH if TBH
1738       //    LSLS idx, #1
1739       //    ADDS pc, pc, idx
1740 
1741       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1742                                        .addReg(Idx)
1743                                        .addReg(Idx)
1744                                        .addReg(Base)
1745                                        // Add predicate operands.
1746                                        .addImm(ARMCC::AL)
1747                                        .addReg(0));
1748 
1749       unsigned Opc = Is8Bit ? ARM::tLDRBi : ARM::tLDRHi;
1750       EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1751                                        .addReg(Idx)
1752                                        .addReg(Idx)
1753                                        .addImm(Is8Bit ? 4 : 2)
1754                                        // Add predicate operands.
1755                                        .addImm(ARMCC::AL)
1756                                        .addReg(0));
1757     } else {
1758       // TBB [base, idx] =
1759       //    LDRB idx, [base, idx] ; or LDRH if TBH
1760       //    LSLS idx, #1
1761       //    ADDS pc, pc, idx
1762 
1763       unsigned Opc = Is8Bit ? ARM::tLDRBr : ARM::tLDRHr;
1764       EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1765                                        .addReg(Idx)
1766                                        .addReg(Base)
1767                                        .addReg(Idx)
1768                                        // Add predicate operands.
1769                                        .addImm(ARMCC::AL)
1770                                        .addReg(0));
1771     }
1772 
1773     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLSLri)
1774                                      .addReg(Idx)
1775                                      .addReg(ARM::CPSR)
1776                                      .addReg(Idx)
1777                                      .addImm(1)
1778                                      // Add predicate operands.
1779                                      .addImm(ARMCC::AL)
1780                                      .addReg(0));
1781 
1782     OutStreamer->EmitLabel(GetCPISymbol(MI->getOperand(3).getImm()));
1783     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1784                                      .addReg(ARM::PC)
1785                                      .addReg(ARM::PC)
1786                                      .addReg(Idx)
1787                                      // Add predicate operands.
1788                                      .addImm(ARMCC::AL)
1789                                      .addReg(0));
1790     return;
1791   }
1792   case ARM::tBR_JTr:
1793   case ARM::BR_JTr: {
1794     // Lower and emit the instruction itself, then the jump table following it.
1795     // mov pc, target
1796     MCInst TmpInst;
1797     unsigned Opc = MI->getOpcode() == ARM::BR_JTr ?
1798       ARM::MOVr : ARM::tMOVr;
1799     TmpInst.setOpcode(Opc);
1800     TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1801     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1802     // Add predicate operands.
1803     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1804     TmpInst.addOperand(MCOperand::createReg(0));
1805     // Add 's' bit operand (always reg0 for this)
1806     if (Opc == ARM::MOVr)
1807       TmpInst.addOperand(MCOperand::createReg(0));
1808     EmitToStreamer(*OutStreamer, TmpInst);
1809     return;
1810   }
1811   case ARM::BR_JTm: {
1812     // Lower and emit the instruction itself, then the jump table following it.
1813     // ldr pc, target
1814     MCInst TmpInst;
1815     if (MI->getOperand(1).getReg() == 0) {
1816       // literal offset
1817       TmpInst.setOpcode(ARM::LDRi12);
1818       TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1819       TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1820       TmpInst.addOperand(MCOperand::createImm(MI->getOperand(2).getImm()));
1821     } else {
1822       TmpInst.setOpcode(ARM::LDRrs);
1823       TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1824       TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1825       TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
1826       TmpInst.addOperand(MCOperand::createImm(0));
1827     }
1828     // Add predicate operands.
1829     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1830     TmpInst.addOperand(MCOperand::createReg(0));
1831     EmitToStreamer(*OutStreamer, TmpInst);
1832     return;
1833   }
1834   case ARM::BR_JTadd: {
1835     // Lower and emit the instruction itself, then the jump table following it.
1836     // add pc, target, idx
1837     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
1838       .addReg(ARM::PC)
1839       .addReg(MI->getOperand(0).getReg())
1840       .addReg(MI->getOperand(1).getReg())
1841       // Add predicate operands.
1842       .addImm(ARMCC::AL)
1843       .addReg(0)
1844       // Add 's' bit operand (always reg0 for this)
1845       .addReg(0));
1846     return;
1847   }
1848   case ARM::SPACE:
1849     OutStreamer->EmitZeros(MI->getOperand(1).getImm());
1850     return;
1851   case ARM::TRAP: {
1852     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1853     // FIXME: Remove this special case when they do.
1854     if (!Subtarget->isTargetMachO()) {
1855       uint32_t Val = 0xe7ffdefeUL;
1856       OutStreamer->AddComment("trap");
1857       ATS.emitInst(Val);
1858       return;
1859     }
1860     break;
1861   }
1862   case ARM::TRAPNaCl: {
1863     uint32_t Val = 0xe7fedef0UL;
1864     OutStreamer->AddComment("trap");
1865     ATS.emitInst(Val);
1866     return;
1867   }
1868   case ARM::tTRAP: {
1869     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1870     // FIXME: Remove this special case when they do.
1871     if (!Subtarget->isTargetMachO()) {
1872       uint16_t Val = 0xdefe;
1873       OutStreamer->AddComment("trap");
1874       ATS.emitInst(Val, 'n');
1875       return;
1876     }
1877     break;
1878   }
1879   case ARM::t2Int_eh_sjlj_setjmp:
1880   case ARM::t2Int_eh_sjlj_setjmp_nofp:
1881   case ARM::tInt_eh_sjlj_setjmp: {
1882     // Two incoming args: GPR:$src, GPR:$val
1883     // mov $val, pc
1884     // adds $val, #7
1885     // str $val, [$src, #4]
1886     // movs r0, #0
1887     // b LSJLJEH
1888     // movs r0, #1
1889     // LSJLJEH:
1890     unsigned SrcReg = MI->getOperand(0).getReg();
1891     unsigned ValReg = MI->getOperand(1).getReg();
1892     MCSymbol *Label = OutContext.createTempSymbol("SJLJEH", false, true);
1893     OutStreamer->AddComment("eh_setjmp begin");
1894     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1895       .addReg(ValReg)
1896       .addReg(ARM::PC)
1897       // Predicate.
1898       .addImm(ARMCC::AL)
1899       .addReg(0));
1900 
1901     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDi3)
1902       .addReg(ValReg)
1903       // 's' bit operand
1904       .addReg(ARM::CPSR)
1905       .addReg(ValReg)
1906       .addImm(7)
1907       // Predicate.
1908       .addImm(ARMCC::AL)
1909       .addReg(0));
1910 
1911     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tSTRi)
1912       .addReg(ValReg)
1913       .addReg(SrcReg)
1914       // The offset immediate is #4. The operand value is scaled by 4 for the
1915       // tSTR instruction.
1916       .addImm(1)
1917       // Predicate.
1918       .addImm(ARMCC::AL)
1919       .addReg(0));
1920 
1921     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
1922       .addReg(ARM::R0)
1923       .addReg(ARM::CPSR)
1924       .addImm(0)
1925       // Predicate.
1926       .addImm(ARMCC::AL)
1927       .addReg(0));
1928 
1929     const MCExpr *SymbolExpr = MCSymbolRefExpr::create(Label, OutContext);
1930     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tB)
1931       .addExpr(SymbolExpr)
1932       .addImm(ARMCC::AL)
1933       .addReg(0));
1934 
1935     OutStreamer->AddComment("eh_setjmp end");
1936     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
1937       .addReg(ARM::R0)
1938       .addReg(ARM::CPSR)
1939       .addImm(1)
1940       // Predicate.
1941       .addImm(ARMCC::AL)
1942       .addReg(0));
1943 
1944     OutStreamer->EmitLabel(Label);
1945     return;
1946   }
1947 
1948   case ARM::Int_eh_sjlj_setjmp_nofp:
1949   case ARM::Int_eh_sjlj_setjmp: {
1950     // Two incoming args: GPR:$src, GPR:$val
1951     // add $val, pc, #8
1952     // str $val, [$src, #+4]
1953     // mov r0, #0
1954     // add pc, pc, #0
1955     // mov r0, #1
1956     unsigned SrcReg = MI->getOperand(0).getReg();
1957     unsigned ValReg = MI->getOperand(1).getReg();
1958 
1959     OutStreamer->AddComment("eh_setjmp begin");
1960     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
1961       .addReg(ValReg)
1962       .addReg(ARM::PC)
1963       .addImm(8)
1964       // Predicate.
1965       .addImm(ARMCC::AL)
1966       .addReg(0)
1967       // 's' bit operand (always reg0 for this).
1968       .addReg(0));
1969 
1970     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::STRi12)
1971       .addReg(ValReg)
1972       .addReg(SrcReg)
1973       .addImm(4)
1974       // Predicate.
1975       .addImm(ARMCC::AL)
1976       .addReg(0));
1977 
1978     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
1979       .addReg(ARM::R0)
1980       .addImm(0)
1981       // Predicate.
1982       .addImm(ARMCC::AL)
1983       .addReg(0)
1984       // 's' bit operand (always reg0 for this).
1985       .addReg(0));
1986 
1987     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
1988       .addReg(ARM::PC)
1989       .addReg(ARM::PC)
1990       .addImm(0)
1991       // Predicate.
1992       .addImm(ARMCC::AL)
1993       .addReg(0)
1994       // 's' bit operand (always reg0 for this).
1995       .addReg(0));
1996 
1997     OutStreamer->AddComment("eh_setjmp end");
1998     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
1999       .addReg(ARM::R0)
2000       .addImm(1)
2001       // Predicate.
2002       .addImm(ARMCC::AL)
2003       .addReg(0)
2004       // 's' bit operand (always reg0 for this).
2005       .addReg(0));
2006     return;
2007   }
2008   case ARM::Int_eh_sjlj_longjmp: {
2009     // ldr sp, [$src, #8]
2010     // ldr $scratch, [$src, #4]
2011     // ldr r7, [$src]
2012     // bx $scratch
2013     unsigned SrcReg = MI->getOperand(0).getReg();
2014     unsigned ScratchReg = MI->getOperand(1).getReg();
2015     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
2016       .addReg(ARM::SP)
2017       .addReg(SrcReg)
2018       .addImm(8)
2019       // Predicate.
2020       .addImm(ARMCC::AL)
2021       .addReg(0));
2022 
2023     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
2024       .addReg(ScratchReg)
2025       .addReg(SrcReg)
2026       .addImm(4)
2027       // Predicate.
2028       .addImm(ARMCC::AL)
2029       .addReg(0));
2030 
2031     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
2032       .addReg(ARM::R7)
2033       .addReg(SrcReg)
2034       .addImm(0)
2035       // Predicate.
2036       .addImm(ARMCC::AL)
2037       .addReg(0));
2038 
2039     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
2040       .addReg(ScratchReg)
2041       // Predicate.
2042       .addImm(ARMCC::AL)
2043       .addReg(0));
2044     return;
2045   }
2046   case ARM::tInt_eh_sjlj_longjmp: {
2047     // ldr $scratch, [$src, #8]
2048     // mov sp, $scratch
2049     // ldr $scratch, [$src, #4]
2050     // ldr r7, [$src]
2051     // bx $scratch
2052     unsigned SrcReg = MI->getOperand(0).getReg();
2053     unsigned ScratchReg = MI->getOperand(1).getReg();
2054 
2055     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
2056       .addReg(ScratchReg)
2057       .addReg(SrcReg)
2058       // The offset immediate is #8. The operand value is scaled by 4 for the
2059       // tLDR instruction.
2060       .addImm(2)
2061       // Predicate.
2062       .addImm(ARMCC::AL)
2063       .addReg(0));
2064 
2065     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
2066       .addReg(ARM::SP)
2067       .addReg(ScratchReg)
2068       // Predicate.
2069       .addImm(ARMCC::AL)
2070       .addReg(0));
2071 
2072     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
2073       .addReg(ScratchReg)
2074       .addReg(SrcReg)
2075       .addImm(1)
2076       // Predicate.
2077       .addImm(ARMCC::AL)
2078       .addReg(0));
2079 
2080     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
2081       .addReg(ARM::R7)
2082       .addReg(SrcReg)
2083       .addImm(0)
2084       // Predicate.
2085       .addImm(ARMCC::AL)
2086       .addReg(0));
2087 
2088     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBX)
2089       .addReg(ScratchReg)
2090       // Predicate.
2091       .addImm(ARMCC::AL)
2092       .addReg(0));
2093     return;
2094   }
2095   case ARM::tInt_WIN_eh_sjlj_longjmp: {
2096     // ldr.w r11, [$src, #0]
2097     // ldr.w  sp, [$src, #8]
2098     // ldr.w  pc, [$src, #4]
2099 
2100     unsigned SrcReg = MI->getOperand(0).getReg();
2101 
2102     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
2103                                      .addReg(ARM::R11)
2104                                      .addReg(SrcReg)
2105                                      .addImm(0)
2106                                      // Predicate
2107                                      .addImm(ARMCC::AL)
2108                                      .addReg(0));
2109     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
2110                                      .addReg(ARM::SP)
2111                                      .addReg(SrcReg)
2112                                      .addImm(8)
2113                                      // Predicate
2114                                      .addImm(ARMCC::AL)
2115                                      .addReg(0));
2116     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
2117                                      .addReg(ARM::PC)
2118                                      .addReg(SrcReg)
2119                                      .addImm(4)
2120                                      // Predicate
2121                                      .addImm(ARMCC::AL)
2122                                      .addReg(0));
2123     return;
2124   }
2125   case ARM::PATCHABLE_FUNCTION_ENTER:
2126     LowerPATCHABLE_FUNCTION_ENTER(*MI);
2127     return;
2128   case ARM::PATCHABLE_FUNCTION_EXIT:
2129     LowerPATCHABLE_FUNCTION_EXIT(*MI);
2130     return;
2131   case ARM::PATCHABLE_TAIL_CALL:
2132     LowerPATCHABLE_TAIL_CALL(*MI);
2133     return;
2134   }
2135 
2136   MCInst TmpInst;
2137   LowerARMMachineInstrToMCInst(MI, TmpInst, *this);
2138 
2139   EmitToStreamer(*OutStreamer, TmpInst);
2140 }
2141 
2142 //===----------------------------------------------------------------------===//
2143 // Target Registry Stuff
2144 //===----------------------------------------------------------------------===//
2145 
2146 // Force static initialization.
2147 extern "C" void LLVMInitializeARMAsmPrinter() {
2148   RegisterAsmPrinter<ARMAsmPrinter> X(getTheARMLETarget());
2149   RegisterAsmPrinter<ARMAsmPrinter> Y(getTheARMBETarget());
2150   RegisterAsmPrinter<ARMAsmPrinter> A(getTheThumbLETarget());
2151   RegisterAsmPrinter<ARMAsmPrinter> B(getTheThumbBETarget());
2152 }
2153