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