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