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