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