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