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