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