]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/ARM/ARMAsmPrinter.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ 3.9.1 release
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Target / ARM / ARMAsmPrinter.cpp
1 //===-- ARMAsmPrinter.cpp - Print machine code to an ARM .s file ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to GAS-format ARM assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARMAsmPrinter.h"
16 #include "ARM.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMTargetMachine.h"
20 #include "ARMTargetObjectFile.h"
21 #include "InstPrinter/ARMInstPrinter.h"
22 #include "MCTargetDesc/ARMAddressingModes.h"
23 #include "MCTargetDesc/ARMMCExpr.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/Mangler.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCAssembler.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/MCELFStreamer.h"
39 #include "llvm/MC/MCInst.h"
40 #include "llvm/MC/MCInstBuilder.h"
41 #include "llvm/MC/MCObjectStreamer.h"
42 #include "llvm/MC/MCSectionMachO.h"
43 #include "llvm/MC/MCStreamer.h"
44 #include "llvm/MC/MCSymbol.h"
45 #include "llvm/Support/ARMBuildAttributes.h"
46 #include "llvm/Support/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   if (isPositionIndependent()) {
729     // PIC specific attributes.
730     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RW_data,
731                       ARMBuildAttrs::AddressRWPCRel);
732     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RO_data,
733                       ARMBuildAttrs::AddressROPCRel);
734     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
735                       ARMBuildAttrs::AddressGOT);
736   } else {
737     // Allow direct addressing of imported data for all other relocation models.
738     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
739                       ARMBuildAttrs::AddressDirect);
740   }
741
742   // Signal various FP modes.
743   if (!TM.Options.UnsafeFPMath) {
744     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
745                       ARMBuildAttrs::IEEEDenormals);
746     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_exceptions, ARMBuildAttrs::Allowed);
747
748     // If the user has permitted this code to choose the IEEE 754
749     // rounding at run-time, emit the rounding attribute.
750     if (TM.Options.HonorSignDependentRoundingFPMathOption)
751       ATS.emitAttribute(ARMBuildAttrs::ABI_FP_rounding, ARMBuildAttrs::Allowed);
752   } else {
753     if (!STI.hasVFP2()) {
754       // When the target doesn't have an FPU (by design or
755       // intention), the assumptions made on the software support
756       // mirror that of the equivalent hardware support *if it
757       // existed*. For v7 and better we indicate that denormals are
758       // flushed preserving sign, and for V6 we indicate that
759       // denormals are flushed to positive zero.
760       if (STI.hasV7Ops())
761         ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
762                           ARMBuildAttrs::PreserveFPSign);
763     } else if (STI.hasVFP3()) {
764       // In VFPv4, VFPv4U, VFPv3, or VFPv3U, it is preserved. That is,
765       // the sign bit of the zero matches the sign bit of the input or
766       // result that is being flushed to zero.
767       ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
768                         ARMBuildAttrs::PreserveFPSign);
769     }
770     // For VFPv2 implementations it is implementation defined as
771     // to whether denormals are flushed to positive zero or to
772     // whatever the sign of zero is (ARM v7AR ARM 2.7.5). Historically
773     // LLVM has chosen to flush this to positive zero (most likely for
774     // GCC compatibility), so that's the chosen value here (the
775     // absence of its emission implies zero).
776   }
777
778   // TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath is the
779   // equivalent of GCC's -ffinite-math-only flag.
780   if (TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath)
781     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
782                       ARMBuildAttrs::Allowed);
783   else
784     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
785                       ARMBuildAttrs::AllowIEE754);
786
787   if (STI.allowsUnalignedMem())
788     ATS.emitAttribute(ARMBuildAttrs::CPU_unaligned_access,
789                       ARMBuildAttrs::Allowed);
790   else
791     ATS.emitAttribute(ARMBuildAttrs::CPU_unaligned_access,
792                       ARMBuildAttrs::Not_Allowed);
793
794   // FIXME: add more flags to ARMBuildAttributes.h
795   // 8-bytes alignment stuff.
796   ATS.emitAttribute(ARMBuildAttrs::ABI_align_needed, 1);
797   ATS.emitAttribute(ARMBuildAttrs::ABI_align_preserved, 1);
798
799   // ABI_HardFP_use attribute to indicate single precision FP.
800   if (STI.isFPOnlySP())
801     ATS.emitAttribute(ARMBuildAttrs::ABI_HardFP_use,
802                       ARMBuildAttrs::HardFPSinglePrecision);
803
804   // Hard float.  Use both S and D registers and conform to AAPCS-VFP.
805   if (STI.isAAPCS_ABI() && TM.Options.FloatABIType == FloatABI::Hard)
806     ATS.emitAttribute(ARMBuildAttrs::ABI_VFP_args, ARMBuildAttrs::HardFPAAPCS);
807
808   // FIXME: Should we signal R9 usage?
809
810   if (STI.hasFP16())
811     ATS.emitAttribute(ARMBuildAttrs::FP_HP_extension, ARMBuildAttrs::AllowHPFP);
812
813   // FIXME: To support emitting this build attribute as GCC does, the
814   // -mfp16-format option and associated plumbing must be
815   // supported. For now the __fp16 type is exposed by default, so this
816   // attribute should be emitted with value 1.
817   ATS.emitAttribute(ARMBuildAttrs::ABI_FP_16bit_format,
818                     ARMBuildAttrs::FP16FormatIEEE);
819
820   if (STI.hasMPExtension())
821     ATS.emitAttribute(ARMBuildAttrs::MPextension_use, ARMBuildAttrs::AllowMP);
822
823   // Hardware divide in ARM mode is part of base arch, starting from ARMv8.
824   // If only Thumb hwdiv is present, it must also be in base arch (ARMv7-R/M).
825   // It is not possible to produce DisallowDIV: if hwdiv is present in the base
826   // arch, supplying -hwdiv downgrades the effective arch, via ClearImpliedBits.
827   // AllowDIVExt is only emitted if hwdiv isn't available in the base arch;
828   // otherwise, the default value (AllowDIVIfExists) applies.
829   if (STI.hasDivideInARMMode() && !STI.hasV8Ops())
830     ATS.emitAttribute(ARMBuildAttrs::DIV_use, ARMBuildAttrs::AllowDIVExt);
831
832   if (STI.hasDSP() && isV8M(&STI))
833     ATS.emitAttribute(ARMBuildAttrs::DSP_extension, ARMBuildAttrs::Allowed);
834
835   if (MMI) {
836     if (const Module *SourceModule = MMI->getModule()) {
837       // ABI_PCS_wchar_t to indicate wchar_t width
838       // FIXME: There is no way to emit value 0 (wchar_t prohibited).
839       if (auto WCharWidthValue = mdconst::extract_or_null<ConstantInt>(
840               SourceModule->getModuleFlag("wchar_size"))) {
841         int WCharWidth = WCharWidthValue->getZExtValue();
842         assert((WCharWidth == 2 || WCharWidth == 4) &&
843                "wchar_t width must be 2 or 4 bytes");
844         ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_wchar_t, WCharWidth);
845       }
846
847       // ABI_enum_size to indicate enum width
848       // FIXME: There is no way to emit value 0 (enums prohibited) or value 3
849       //        (all enums contain a value needing 32 bits to encode).
850       if (auto EnumWidthValue = mdconst::extract_or_null<ConstantInt>(
851               SourceModule->getModuleFlag("min_enum_size"))) {
852         int EnumWidth = EnumWidthValue->getZExtValue();
853         assert((EnumWidth == 1 || EnumWidth == 4) &&
854                "Minimum enum width must be 1 or 4 bytes");
855         int EnumBuildAttr = EnumWidth == 1 ? 1 : 2;
856         ATS.emitAttribute(ARMBuildAttrs::ABI_enum_size, EnumBuildAttr);
857       }
858     }
859   }
860
861   // TODO: We currently only support either reserving the register, or treating
862   // it as another callee-saved register, but not as SB or a TLS pointer; It
863   // would instead be nicer to push this from the frontend as metadata, as we do
864   // for the wchar and enum size tags
865   if (STI.isR9Reserved())
866     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use, ARMBuildAttrs::R9Reserved);
867   else
868     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use, ARMBuildAttrs::R9IsGPR);
869
870   if (STI.hasTrustZone() && STI.hasVirtualization())
871     ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
872                       ARMBuildAttrs::AllowTZVirtualization);
873   else if (STI.hasTrustZone())
874     ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
875                       ARMBuildAttrs::AllowTZ);
876   else if (STI.hasVirtualization())
877     ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
878                       ARMBuildAttrs::AllowVirtualization);
879 }
880
881 //===----------------------------------------------------------------------===//
882
883 static MCSymbol *getPICLabel(const char *Prefix, unsigned FunctionNumber,
884                              unsigned LabelId, MCContext &Ctx) {
885
886   MCSymbol *Label = Ctx.getOrCreateSymbol(Twine(Prefix)
887                        + "PC" + Twine(FunctionNumber) + "_" + Twine(LabelId));
888   return Label;
889 }
890
891 static MCSymbolRefExpr::VariantKind
892 getModifierVariantKind(ARMCP::ARMCPModifier Modifier) {
893   switch (Modifier) {
894   case ARMCP::no_modifier:
895     return MCSymbolRefExpr::VK_None;
896   case ARMCP::TLSGD:
897     return MCSymbolRefExpr::VK_TLSGD;
898   case ARMCP::TPOFF:
899     return MCSymbolRefExpr::VK_TPOFF;
900   case ARMCP::GOTTPOFF:
901     return MCSymbolRefExpr::VK_GOTTPOFF;
902   case ARMCP::GOT_PREL:
903     return MCSymbolRefExpr::VK_ARM_GOT_PREL;
904   case ARMCP::SECREL:
905     return MCSymbolRefExpr::VK_SECREL;
906   }
907   llvm_unreachable("Invalid ARMCPModifier!");
908 }
909
910 MCSymbol *ARMAsmPrinter::GetARMGVSymbol(const GlobalValue *GV,
911                                         unsigned char TargetFlags) {
912   if (Subtarget->isTargetMachO()) {
913     bool IsIndirect =
914         (TargetFlags & ARMII::MO_NONLAZY) && Subtarget->isGVIndirectSymbol(GV);
915
916     if (!IsIndirect)
917       return getSymbol(GV);
918
919     // FIXME: Remove this when Darwin transition to @GOT like syntax.
920     MCSymbol *MCSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
921     MachineModuleInfoMachO &MMIMachO =
922       MMI->getObjFileInfo<MachineModuleInfoMachO>();
923     MachineModuleInfoImpl::StubValueTy &StubSym =
924         GV->isThreadLocal() ? MMIMachO.getThreadLocalGVStubEntry(MCSym)
925                             : MMIMachO.getGVStubEntry(MCSym);
926
927     if (!StubSym.getPointer())
928       StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV),
929                                                    !GV->hasInternalLinkage());
930     return MCSym;
931   } else if (Subtarget->isTargetCOFF()) {
932     assert(Subtarget->isTargetWindows() &&
933            "Windows is the only supported COFF target");
934
935     bool IsIndirect = (TargetFlags & ARMII::MO_DLLIMPORT);
936     if (!IsIndirect)
937       return getSymbol(GV);
938
939     SmallString<128> Name;
940     Name = "__imp_";
941     getNameWithPrefix(Name, GV);
942
943     return OutContext.getOrCreateSymbol(Name);
944   } else if (Subtarget->isTargetELF()) {
945     return getSymbol(GV);
946   }
947   llvm_unreachable("unexpected target");
948 }
949
950 void ARMAsmPrinter::
951 EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
952   const DataLayout &DL = getDataLayout();
953   int Size = DL.getTypeAllocSize(MCPV->getType());
954
955   ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
956
957   MCSymbol *MCSym;
958   if (ACPV->isLSDA()) {
959     MCSym = getCurExceptionSym();
960   } else if (ACPV->isBlockAddress()) {
961     const BlockAddress *BA =
962       cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress();
963     MCSym = GetBlockAddressSymbol(BA);
964   } else if (ACPV->isGlobalValue()) {
965     const GlobalValue *GV = cast<ARMConstantPoolConstant>(ACPV)->getGV();
966
967     // On Darwin, const-pool entries may get the "FOO$non_lazy_ptr" mangling, so
968     // flag the global as MO_NONLAZY.
969     unsigned char TF = Subtarget->isTargetMachO() ? ARMII::MO_NONLAZY : 0;
970     MCSym = GetARMGVSymbol(GV, TF);
971   } else if (ACPV->isMachineBasicBlock()) {
972     const MachineBasicBlock *MBB = cast<ARMConstantPoolMBB>(ACPV)->getMBB();
973     MCSym = MBB->getSymbol();
974   } else {
975     assert(ACPV->isExtSymbol() && "unrecognized constant pool value");
976     const char *Sym = cast<ARMConstantPoolSymbol>(ACPV)->getSymbol();
977     MCSym = GetExternalSymbolSymbol(Sym);
978   }
979
980   // Create an MCSymbol for the reference.
981   const MCExpr *Expr =
982     MCSymbolRefExpr::create(MCSym, getModifierVariantKind(ACPV->getModifier()),
983                             OutContext);
984
985   if (ACPV->getPCAdjustment()) {
986     MCSymbol *PCLabel =
987         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
988                     ACPV->getLabelId(), OutContext);
989     const MCExpr *PCRelExpr = MCSymbolRefExpr::create(PCLabel, OutContext);
990     PCRelExpr =
991       MCBinaryExpr::createAdd(PCRelExpr,
992                               MCConstantExpr::create(ACPV->getPCAdjustment(),
993                                                      OutContext),
994                               OutContext);
995     if (ACPV->mustAddCurrentAddress()) {
996       // We want "(<expr> - .)", but MC doesn't have a concept of the '.'
997       // label, so just emit a local label end reference that instead.
998       MCSymbol *DotSym = OutContext.createTempSymbol();
999       OutStreamer->EmitLabel(DotSym);
1000       const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
1001       PCRelExpr = MCBinaryExpr::createSub(PCRelExpr, DotExpr, OutContext);
1002     }
1003     Expr = MCBinaryExpr::createSub(Expr, PCRelExpr, OutContext);
1004   }
1005   OutStreamer->EmitValue(Expr, Size);
1006 }
1007
1008 void ARMAsmPrinter::EmitJumpTableAddrs(const MachineInstr *MI) {
1009   const MachineOperand &MO1 = MI->getOperand(1);
1010   unsigned JTI = MO1.getIndex();
1011
1012   // Make sure the Thumb jump table is 4-byte aligned. This will be a nop for
1013   // ARM mode tables.
1014   EmitAlignment(2);
1015
1016   // Emit a label for the jump table.
1017   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
1018   OutStreamer->EmitLabel(JTISymbol);
1019
1020   // Mark the jump table as data-in-code.
1021   OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
1022
1023   // Emit each entry of the table.
1024   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1025   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1026   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1027
1028   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
1029     MachineBasicBlock *MBB = JTBBs[i];
1030     // Construct an MCExpr for the entry. We want a value of the form:
1031     // (BasicBlockAddr - TableBeginAddr)
1032     //
1033     // For example, a table with entries jumping to basic blocks BB0 and BB1
1034     // would look like:
1035     // LJTI_0_0:
1036     //    .word (LBB0 - LJTI_0_0)
1037     //    .word (LBB1 - LJTI_0_0)
1038     const MCExpr *Expr = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1039
1040     if (isPositionIndependent())
1041       Expr = MCBinaryExpr::createSub(Expr, MCSymbolRefExpr::create(JTISymbol,
1042                                                                    OutContext),
1043                                      OutContext);
1044     // If we're generating a table of Thumb addresses in static relocation
1045     // model, we need to add one to keep interworking correctly.
1046     else if (AFI->isThumbFunction())
1047       Expr = MCBinaryExpr::createAdd(Expr, MCConstantExpr::create(1,OutContext),
1048                                      OutContext);
1049     OutStreamer->EmitValue(Expr, 4);
1050   }
1051   // Mark the end of jump table data-in-code region.
1052   OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1053 }
1054
1055 void ARMAsmPrinter::EmitJumpTableInsts(const MachineInstr *MI) {
1056   const MachineOperand &MO1 = MI->getOperand(1);
1057   unsigned JTI = MO1.getIndex();
1058
1059   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
1060   OutStreamer->EmitLabel(JTISymbol);
1061
1062   // Emit each entry of the table.
1063   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1064   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1065   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1066
1067   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
1068     MachineBasicBlock *MBB = JTBBs[i];
1069     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
1070                                                           OutContext);
1071     // If this isn't a TBB or TBH, the entries are direct branch instructions.
1072     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2B)
1073         .addExpr(MBBSymbolExpr)
1074         .addImm(ARMCC::AL)
1075         .addReg(0));
1076   }
1077 }
1078
1079 void ARMAsmPrinter::EmitJumpTableTBInst(const MachineInstr *MI,
1080                                         unsigned OffsetWidth) {
1081   assert((OffsetWidth == 1 || OffsetWidth == 2) && "invalid tbb/tbh width");
1082   const MachineOperand &MO1 = MI->getOperand(1);
1083   unsigned JTI = MO1.getIndex();
1084
1085   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
1086   OutStreamer->EmitLabel(JTISymbol);
1087
1088   // Emit each entry of the table.
1089   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1090   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1091   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1092
1093   // Mark the jump table as data-in-code.
1094   OutStreamer->EmitDataRegion(OffsetWidth == 1 ? MCDR_DataRegionJT8
1095                                                : MCDR_DataRegionJT16);
1096
1097   for (auto MBB : JTBBs) {
1098     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
1099                                                           OutContext);
1100     // Otherwise it's an offset from the dispatch instruction. Construct an
1101     // MCExpr for the entry. We want a value of the form:
1102     // (BasicBlockAddr - TBBInstAddr + 4) / 2
1103     //
1104     // For example, a TBB table with entries jumping to basic blocks BB0 and BB1
1105     // would look like:
1106     // LJTI_0_0:
1107     //    .byte (LBB0 - (LCPI0_0 + 4)) / 2
1108     //    .byte (LBB1 - (LCPI0_0 + 4)) / 2
1109     // where LCPI0_0 is a label defined just before the TBB instruction using
1110     // this table.
1111     MCSymbol *TBInstPC = GetCPISymbol(MI->getOperand(0).getImm());
1112     const MCExpr *Expr = MCBinaryExpr::createAdd(
1113         MCSymbolRefExpr::create(TBInstPC, OutContext),
1114         MCConstantExpr::create(4, OutContext), OutContext);
1115     Expr = MCBinaryExpr::createSub(MBBSymbolExpr, Expr, OutContext);
1116     Expr = MCBinaryExpr::createDiv(Expr, MCConstantExpr::create(2, OutContext),
1117                                    OutContext);
1118     OutStreamer->EmitValue(Expr, OffsetWidth);
1119   }
1120   // Mark the end of jump table data-in-code region. 32-bit offsets use
1121   // actual branch instructions here, so we don't mark those as a data-region
1122   // at all.
1123   OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1124
1125   // Make sure the next instruction is 2-byte aligned.
1126   EmitAlignment(1);
1127 }
1128
1129 void ARMAsmPrinter::EmitUnwindingInstruction(const MachineInstr *MI) {
1130   assert(MI->getFlag(MachineInstr::FrameSetup) &&
1131       "Only instruction which are involved into frame setup code are allowed");
1132
1133   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
1134   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1135   const MachineFunction &MF = *MI->getParent()->getParent();
1136   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
1137   const ARMFunctionInfo &AFI = *MF.getInfo<ARMFunctionInfo>();
1138
1139   unsigned FramePtr = RegInfo->getFrameRegister(MF);
1140   unsigned Opc = MI->getOpcode();
1141   unsigned SrcReg, DstReg;
1142
1143   if (Opc == ARM::tPUSH || Opc == ARM::tLDRpci) {
1144     // Two special cases:
1145     // 1) tPUSH does not have src/dst regs.
1146     // 2) for Thumb1 code we sometimes materialize the constant via constpool
1147     // load. Yes, this is pretty fragile, but for now I don't see better
1148     // way... :(
1149     SrcReg = DstReg = ARM::SP;
1150   } else {
1151     SrcReg = MI->getOperand(1).getReg();
1152     DstReg = MI->getOperand(0).getReg();
1153   }
1154
1155   // Try to figure out the unwinding opcode out of src / dst regs.
1156   if (MI->mayStore()) {
1157     // Register saves.
1158     assert(DstReg == ARM::SP &&
1159            "Only stack pointer as a destination reg is supported");
1160
1161     SmallVector<unsigned, 4> RegList;
1162     // Skip src & dst reg, and pred ops.
1163     unsigned StartOp = 2 + 2;
1164     // Use all the operands.
1165     unsigned NumOffset = 0;
1166
1167     switch (Opc) {
1168     default:
1169       MI->dump();
1170       llvm_unreachable("Unsupported opcode for unwinding information");
1171     case ARM::tPUSH:
1172       // Special case here: no src & dst reg, but two extra imp ops.
1173       StartOp = 2; NumOffset = 2;
1174     case ARM::STMDB_UPD:
1175     case ARM::t2STMDB_UPD:
1176     case ARM::VSTMDDB_UPD:
1177       assert(SrcReg == ARM::SP &&
1178              "Only stack pointer as a source reg is supported");
1179       for (unsigned i = StartOp, NumOps = MI->getNumOperands() - NumOffset;
1180            i != NumOps; ++i) {
1181         const MachineOperand &MO = MI->getOperand(i);
1182         // Actually, there should never be any impdef stuff here. Skip it
1183         // temporary to workaround PR11902.
1184         if (MO.isImplicit())
1185           continue;
1186         RegList.push_back(MO.getReg());
1187       }
1188       break;
1189     case ARM::STR_PRE_IMM:
1190     case ARM::STR_PRE_REG:
1191     case ARM::t2STR_PRE:
1192       assert(MI->getOperand(2).getReg() == ARM::SP &&
1193              "Only stack pointer as a source reg is supported");
1194       RegList.push_back(SrcReg);
1195       break;
1196     }
1197     if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM)
1198       ATS.emitRegSave(RegList, Opc == ARM::VSTMDDB_UPD);
1199   } else {
1200     // Changes of stack / frame pointer.
1201     if (SrcReg == ARM::SP) {
1202       int64_t Offset = 0;
1203       switch (Opc) {
1204       default:
1205         MI->dump();
1206         llvm_unreachable("Unsupported opcode for unwinding information");
1207       case ARM::MOVr:
1208       case ARM::tMOVr:
1209         Offset = 0;
1210         break;
1211       case ARM::ADDri:
1212       case ARM::t2ADDri:
1213         Offset = -MI->getOperand(2).getImm();
1214         break;
1215       case ARM::SUBri:
1216       case ARM::t2SUBri:
1217         Offset = MI->getOperand(2).getImm();
1218         break;
1219       case ARM::tSUBspi:
1220         Offset = MI->getOperand(2).getImm()*4;
1221         break;
1222       case ARM::tADDspi:
1223       case ARM::tADDrSPi:
1224         Offset = -MI->getOperand(2).getImm()*4;
1225         break;
1226       case ARM::tLDRpci: {
1227         // Grab the constpool index and check, whether it corresponds to
1228         // original or cloned constpool entry.
1229         unsigned CPI = MI->getOperand(1).getIndex();
1230         const MachineConstantPool *MCP = MF.getConstantPool();
1231         if (CPI >= MCP->getConstants().size())
1232           CPI = AFI.getOriginalCPIdx(CPI);
1233         assert(CPI != -1U && "Invalid constpool index");
1234
1235         // Derive the actual offset.
1236         const MachineConstantPoolEntry &CPE = MCP->getConstants()[CPI];
1237         assert(!CPE.isMachineConstantPoolEntry() && "Invalid constpool entry");
1238         // FIXME: Check for user, it should be "add" instruction!
1239         Offset = -cast<ConstantInt>(CPE.Val.ConstVal)->getSExtValue();
1240         break;
1241       }
1242       }
1243
1244       if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM) {
1245         if (DstReg == FramePtr && FramePtr != ARM::SP)
1246           // Set-up of the frame pointer. Positive values correspond to "add"
1247           // instruction.
1248           ATS.emitSetFP(FramePtr, ARM::SP, -Offset);
1249         else if (DstReg == ARM::SP) {
1250           // Change of SP by an offset. Positive values correspond to "sub"
1251           // instruction.
1252           ATS.emitPad(Offset);
1253         } else {
1254           // Move of SP to a register.  Positive values correspond to an "add"
1255           // instruction.
1256           ATS.emitMovSP(DstReg, -Offset);
1257         }
1258       }
1259     } else if (DstReg == ARM::SP) {
1260       MI->dump();
1261       llvm_unreachable("Unsupported opcode for unwinding information");
1262     }
1263     else {
1264       MI->dump();
1265       llvm_unreachable("Unsupported opcode for unwinding information");
1266     }
1267   }
1268 }
1269
1270 // Simple pseudo-instructions have their lowering (with expansion to real
1271 // instructions) auto-generated.
1272 #include "ARMGenMCPseudoLowering.inc"
1273
1274 void ARMAsmPrinter::EmitInstruction(const MachineInstr *MI) {
1275   const DataLayout &DL = getDataLayout();
1276   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
1277   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1278
1279   // If we just ended a constant pool, mark it as such.
1280   if (InConstantPool && MI->getOpcode() != ARM::CONSTPOOL_ENTRY) {
1281     OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1282     InConstantPool = false;
1283   }
1284
1285   // Emit unwinding stuff for frame-related instructions
1286   if (Subtarget->isTargetEHABICompatible() &&
1287        MI->getFlag(MachineInstr::FrameSetup))
1288     EmitUnwindingInstruction(MI);
1289
1290   // Do any auto-generated pseudo lowerings.
1291   if (emitPseudoExpansionLowering(*OutStreamer, MI))
1292     return;
1293
1294   assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
1295          "Pseudo flag setting opcode should be expanded early");
1296
1297   // Check for manual lowerings.
1298   unsigned Opc = MI->getOpcode();
1299   switch (Opc) {
1300   case ARM::t2MOVi32imm: llvm_unreachable("Should be lowered by thumb2it pass");
1301   case ARM::DBG_VALUE: llvm_unreachable("Should be handled by generic printing");
1302   case ARM::LEApcrel:
1303   case ARM::tLEApcrel:
1304   case ARM::t2LEApcrel: {
1305     // FIXME: Need to also handle globals and externals
1306     MCSymbol *CPISymbol = GetCPISymbol(MI->getOperand(1).getIndex());
1307     EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
1308                                                ARM::t2LEApcrel ? ARM::t2ADR
1309                   : (MI->getOpcode() == ARM::tLEApcrel ? ARM::tADR
1310                      : ARM::ADR))
1311       .addReg(MI->getOperand(0).getReg())
1312       .addExpr(MCSymbolRefExpr::create(CPISymbol, OutContext))
1313       // Add predicate operands.
1314       .addImm(MI->getOperand(2).getImm())
1315       .addReg(MI->getOperand(3).getReg()));
1316     return;
1317   }
1318   case ARM::LEApcrelJT:
1319   case ARM::tLEApcrelJT:
1320   case ARM::t2LEApcrelJT: {
1321     MCSymbol *JTIPICSymbol =
1322       GetARMJTIPICJumpTableLabel(MI->getOperand(1).getIndex());
1323     EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
1324                                                ARM::t2LEApcrelJT ? ARM::t2ADR
1325                   : (MI->getOpcode() == ARM::tLEApcrelJT ? ARM::tADR
1326                      : ARM::ADR))
1327       .addReg(MI->getOperand(0).getReg())
1328       .addExpr(MCSymbolRefExpr::create(JTIPICSymbol, OutContext))
1329       // Add predicate operands.
1330       .addImm(MI->getOperand(2).getImm())
1331       .addReg(MI->getOperand(3).getReg()));
1332     return;
1333   }
1334   // Darwin call instructions are just normal call instructions with different
1335   // clobber semantics (they clobber R9).
1336   case ARM::BX_CALL: {
1337     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1338       .addReg(ARM::LR)
1339       .addReg(ARM::PC)
1340       // Add predicate operands.
1341       .addImm(ARMCC::AL)
1342       .addReg(0)
1343       // Add 's' bit operand (always reg0 for this)
1344       .addReg(0));
1345
1346     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
1347       .addReg(MI->getOperand(0).getReg()));
1348     return;
1349   }
1350   case ARM::tBX_CALL: {
1351     if (Subtarget->hasV5TOps())
1352       llvm_unreachable("Expected BLX to be selected for v5t+");
1353
1354     // On ARM v4t, when doing a call from thumb mode, we need to ensure
1355     // that the saved lr has its LSB set correctly (the arch doesn't
1356     // have blx).
1357     // So here we generate a bl to a small jump pad that does bx rN.
1358     // The jump pads are emitted after the function body.
1359
1360     unsigned TReg = MI->getOperand(0).getReg();
1361     MCSymbol *TRegSym = nullptr;
1362     for (unsigned i = 0, e = ThumbIndirectPads.size(); i < e; i++) {
1363       if (ThumbIndirectPads[i].first == TReg) {
1364         TRegSym = ThumbIndirectPads[i].second;
1365         break;
1366       }
1367     }
1368
1369     if (!TRegSym) {
1370       TRegSym = OutContext.createTempSymbol();
1371       ThumbIndirectPads.push_back(std::make_pair(TReg, TRegSym));
1372     }
1373
1374     // Create a link-saving branch to the Reg Indirect Jump Pad.
1375     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBL)
1376         // Predicate comes first here.
1377         .addImm(ARMCC::AL).addReg(0)
1378         .addExpr(MCSymbolRefExpr::create(TRegSym, OutContext)));
1379     return;
1380   }
1381   case ARM::BMOVPCRX_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::MOVr)
1392       .addReg(ARM::PC)
1393       .addReg(MI->getOperand(0).getReg())
1394       // Add predicate operands.
1395       .addImm(ARMCC::AL)
1396       .addReg(0)
1397       // Add 's' bit operand (always reg0 for this)
1398       .addReg(0));
1399     return;
1400   }
1401   case ARM::BMOVPCB_CALL: {
1402     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1403       .addReg(ARM::LR)
1404       .addReg(ARM::PC)
1405       // Add predicate operands.
1406       .addImm(ARMCC::AL)
1407       .addReg(0)
1408       // Add 's' bit operand (always reg0 for this)
1409       .addReg(0));
1410
1411     const MachineOperand &Op = MI->getOperand(0);
1412     const GlobalValue *GV = Op.getGlobal();
1413     const unsigned TF = Op.getTargetFlags();
1414     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1415     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1416     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::Bcc)
1417       .addExpr(GVSymExpr)
1418       // Add predicate operands.
1419       .addImm(ARMCC::AL)
1420       .addReg(0));
1421     return;
1422   }
1423   case ARM::MOVi16_ga_pcrel:
1424   case ARM::t2MOVi16_ga_pcrel: {
1425     MCInst TmpInst;
1426     TmpInst.setOpcode(Opc == ARM::MOVi16_ga_pcrel? ARM::MOVi16 : ARM::t2MOVi16);
1427     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1428
1429     unsigned TF = MI->getOperand(1).getTargetFlags();
1430     const GlobalValue *GV = MI->getOperand(1).getGlobal();
1431     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1432     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1433
1434     MCSymbol *LabelSym =
1435         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1436                     MI->getOperand(2).getImm(), OutContext);
1437     const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
1438     unsigned PCAdj = (Opc == ARM::MOVi16_ga_pcrel) ? 8 : 4;
1439     const MCExpr *PCRelExpr =
1440       ARMMCExpr::createLower16(MCBinaryExpr::createSub(GVSymExpr,
1441                                       MCBinaryExpr::createAdd(LabelSymExpr,
1442                                       MCConstantExpr::create(PCAdj, OutContext),
1443                                       OutContext), OutContext), OutContext);
1444       TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
1445
1446     // Add predicate operands.
1447     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1448     TmpInst.addOperand(MCOperand::createReg(0));
1449     // Add 's' bit operand (always reg0 for this)
1450     TmpInst.addOperand(MCOperand::createReg(0));
1451     EmitToStreamer(*OutStreamer, TmpInst);
1452     return;
1453   }
1454   case ARM::MOVTi16_ga_pcrel:
1455   case ARM::t2MOVTi16_ga_pcrel: {
1456     MCInst TmpInst;
1457     TmpInst.setOpcode(Opc == ARM::MOVTi16_ga_pcrel
1458                       ? ARM::MOVTi16 : ARM::t2MOVTi16);
1459     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1460     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
1461
1462     unsigned TF = MI->getOperand(2).getTargetFlags();
1463     const GlobalValue *GV = MI->getOperand(2).getGlobal();
1464     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1465     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1466
1467     MCSymbol *LabelSym =
1468         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1469                     MI->getOperand(3).getImm(), OutContext);
1470     const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
1471     unsigned PCAdj = (Opc == ARM::MOVTi16_ga_pcrel) ? 8 : 4;
1472     const MCExpr *PCRelExpr =
1473         ARMMCExpr::createUpper16(MCBinaryExpr::createSub(GVSymExpr,
1474                                    MCBinaryExpr::createAdd(LabelSymExpr,
1475                                       MCConstantExpr::create(PCAdj, OutContext),
1476                                           OutContext), OutContext), OutContext);
1477       TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
1478     // Add predicate operands.
1479     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1480     TmpInst.addOperand(MCOperand::createReg(0));
1481     // Add 's' bit operand (always reg0 for this)
1482     TmpInst.addOperand(MCOperand::createReg(0));
1483     EmitToStreamer(*OutStreamer, TmpInst);
1484     return;
1485   }
1486   case ARM::tPICADD: {
1487     // This is a pseudo op for a label + instruction sequence, which looks like:
1488     // LPC0:
1489     //     add r0, pc
1490     // This adds the address of LPC0 to r0.
1491
1492     // Emit the label.
1493     OutStreamer->EmitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1494                                        getFunctionNumber(),
1495                                        MI->getOperand(2).getImm(), OutContext));
1496
1497     // Form and emit the add.
1498     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1499       .addReg(MI->getOperand(0).getReg())
1500       .addReg(MI->getOperand(0).getReg())
1501       .addReg(ARM::PC)
1502       // Add predicate operands.
1503       .addImm(ARMCC::AL)
1504       .addReg(0));
1505     return;
1506   }
1507   case ARM::PICADD: {
1508     // This is a pseudo op for a label + instruction sequence, which looks like:
1509     // LPC0:
1510     //     add r0, pc, r0
1511     // This adds the address of LPC0 to r0.
1512
1513     // Emit the label.
1514     OutStreamer->EmitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1515                                        getFunctionNumber(),
1516                                        MI->getOperand(2).getImm(), OutContext));
1517
1518     // Form and emit the add.
1519     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
1520       .addReg(MI->getOperand(0).getReg())
1521       .addReg(ARM::PC)
1522       .addReg(MI->getOperand(1).getReg())
1523       // Add predicate operands.
1524       .addImm(MI->getOperand(3).getImm())
1525       .addReg(MI->getOperand(4).getReg())
1526       // Add 's' bit operand (always reg0 for this)
1527       .addReg(0));
1528     return;
1529   }
1530   case ARM::PICSTR:
1531   case ARM::PICSTRB:
1532   case ARM::PICSTRH:
1533   case ARM::PICLDR:
1534   case ARM::PICLDRB:
1535   case ARM::PICLDRH:
1536   case ARM::PICLDRSB:
1537   case ARM::PICLDRSH: {
1538     // This is a pseudo op for a label + instruction sequence, which looks like:
1539     // LPC0:
1540     //     OP r0, [pc, r0]
1541     // The LCP0 label is referenced by a constant pool entry in order to get
1542     // a PC-relative address at the ldr instruction.
1543
1544     // Emit the label.
1545     OutStreamer->EmitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1546                                        getFunctionNumber(),
1547                                        MI->getOperand(2).getImm(), OutContext));
1548
1549     // Form and emit the load
1550     unsigned Opcode;
1551     switch (MI->getOpcode()) {
1552     default:
1553       llvm_unreachable("Unexpected opcode!");
1554     case ARM::PICSTR:   Opcode = ARM::STRrs; break;
1555     case ARM::PICSTRB:  Opcode = ARM::STRBrs; break;
1556     case ARM::PICSTRH:  Opcode = ARM::STRH; break;
1557     case ARM::PICLDR:   Opcode = ARM::LDRrs; break;
1558     case ARM::PICLDRB:  Opcode = ARM::LDRBrs; break;
1559     case ARM::PICLDRH:  Opcode = ARM::LDRH; break;
1560     case ARM::PICLDRSB: Opcode = ARM::LDRSB; break;
1561     case ARM::PICLDRSH: Opcode = ARM::LDRSH; break;
1562     }
1563     EmitToStreamer(*OutStreamer, MCInstBuilder(Opcode)
1564       .addReg(MI->getOperand(0).getReg())
1565       .addReg(ARM::PC)
1566       .addReg(MI->getOperand(1).getReg())
1567       .addImm(0)
1568       // Add predicate operands.
1569       .addImm(MI->getOperand(3).getImm())
1570       .addReg(MI->getOperand(4).getReg()));
1571
1572     return;
1573   }
1574   case ARM::CONSTPOOL_ENTRY: {
1575     /// CONSTPOOL_ENTRY - This instruction represents a floating constant pool
1576     /// in the function.  The first operand is the ID# for this instruction, the
1577     /// second is the index into the MachineConstantPool that this is, the third
1578     /// is the size in bytes of this constant pool entry.
1579     /// The required alignment is specified on the basic block holding this MI.
1580     unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
1581     unsigned CPIdx   = (unsigned)MI->getOperand(1).getIndex();
1582
1583     // If this is the first entry of the pool, mark it.
1584     if (!InConstantPool) {
1585       OutStreamer->EmitDataRegion(MCDR_DataRegion);
1586       InConstantPool = true;
1587     }
1588
1589     OutStreamer->EmitLabel(GetCPISymbol(LabelId));
1590
1591     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
1592     if (MCPE.isMachineConstantPoolEntry())
1593       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
1594     else
1595       EmitGlobalConstant(DL, MCPE.Val.ConstVal);
1596     return;
1597   }
1598   case ARM::JUMPTABLE_ADDRS:
1599     EmitJumpTableAddrs(MI);
1600     return;
1601   case ARM::JUMPTABLE_INSTS:
1602     EmitJumpTableInsts(MI);
1603     return;
1604   case ARM::JUMPTABLE_TBB:
1605   case ARM::JUMPTABLE_TBH:
1606     EmitJumpTableTBInst(MI, MI->getOpcode() == ARM::JUMPTABLE_TBB ? 1 : 2);
1607     return;
1608   case ARM::t2BR_JT: {
1609     // Lower and emit the instruction itself, then the jump table following it.
1610     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1611       .addReg(ARM::PC)
1612       .addReg(MI->getOperand(0).getReg())
1613       // Add predicate operands.
1614       .addImm(ARMCC::AL)
1615       .addReg(0));
1616     return;
1617   }
1618   case ARM::t2TBB_JT:
1619   case ARM::t2TBH_JT: {
1620     unsigned Opc = MI->getOpcode() == ARM::t2TBB_JT ? ARM::t2TBB : ARM::t2TBH;
1621     // Lower and emit the PC label, then the instruction itself.
1622     OutStreamer->EmitLabel(GetCPISymbol(MI->getOperand(3).getImm()));
1623     EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1624                                      .addReg(MI->getOperand(0).getReg())
1625                                      .addReg(MI->getOperand(1).getReg())
1626                                      // Add predicate operands.
1627                                      .addImm(ARMCC::AL)
1628                                      .addReg(0));
1629     return;
1630   }
1631   case ARM::tBR_JTr:
1632   case ARM::BR_JTr: {
1633     // Lower and emit the instruction itself, then the jump table following it.
1634     // mov pc, target
1635     MCInst TmpInst;
1636     unsigned Opc = MI->getOpcode() == ARM::BR_JTr ?
1637       ARM::MOVr : ARM::tMOVr;
1638     TmpInst.setOpcode(Opc);
1639     TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1640     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1641     // Add predicate operands.
1642     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1643     TmpInst.addOperand(MCOperand::createReg(0));
1644     // Add 's' bit operand (always reg0 for this)
1645     if (Opc == ARM::MOVr)
1646       TmpInst.addOperand(MCOperand::createReg(0));
1647     EmitToStreamer(*OutStreamer, TmpInst);
1648     return;
1649   }
1650   case ARM::BR_JTm: {
1651     // Lower and emit the instruction itself, then the jump table following it.
1652     // ldr pc, target
1653     MCInst TmpInst;
1654     if (MI->getOperand(1).getReg() == 0) {
1655       // literal offset
1656       TmpInst.setOpcode(ARM::LDRi12);
1657       TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1658       TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1659       TmpInst.addOperand(MCOperand::createImm(MI->getOperand(2).getImm()));
1660     } else {
1661       TmpInst.setOpcode(ARM::LDRrs);
1662       TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1663       TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1664       TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
1665       TmpInst.addOperand(MCOperand::createImm(0));
1666     }
1667     // Add predicate operands.
1668     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1669     TmpInst.addOperand(MCOperand::createReg(0));
1670     EmitToStreamer(*OutStreamer, TmpInst);
1671     return;
1672   }
1673   case ARM::BR_JTadd: {
1674     // Lower and emit the instruction itself, then the jump table following it.
1675     // add pc, target, idx
1676     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
1677       .addReg(ARM::PC)
1678       .addReg(MI->getOperand(0).getReg())
1679       .addReg(MI->getOperand(1).getReg())
1680       // Add predicate operands.
1681       .addImm(ARMCC::AL)
1682       .addReg(0)
1683       // Add 's' bit operand (always reg0 for this)
1684       .addReg(0));
1685     return;
1686   }
1687   case ARM::SPACE:
1688     OutStreamer->EmitZeros(MI->getOperand(1).getImm());
1689     return;
1690   case ARM::TRAP: {
1691     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1692     // FIXME: Remove this special case when they do.
1693     if (!Subtarget->isTargetMachO()) {
1694       uint32_t Val = 0xe7ffdefeUL;
1695       OutStreamer->AddComment("trap");
1696       ATS.emitInst(Val);
1697       return;
1698     }
1699     break;
1700   }
1701   case ARM::TRAPNaCl: {
1702     uint32_t Val = 0xe7fedef0UL;
1703     OutStreamer->AddComment("trap");
1704     ATS.emitInst(Val);
1705     return;
1706   }
1707   case ARM::tTRAP: {
1708     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1709     // FIXME: Remove this special case when they do.
1710     if (!Subtarget->isTargetMachO()) {
1711       uint16_t Val = 0xdefe;
1712       OutStreamer->AddComment("trap");
1713       ATS.emitInst(Val, 'n');
1714       return;
1715     }
1716     break;
1717   }
1718   case ARM::t2Int_eh_sjlj_setjmp:
1719   case ARM::t2Int_eh_sjlj_setjmp_nofp:
1720   case ARM::tInt_eh_sjlj_setjmp: {
1721     // Two incoming args: GPR:$src, GPR:$val
1722     // mov $val, pc
1723     // adds $val, #7
1724     // str $val, [$src, #4]
1725     // movs r0, #0
1726     // b LSJLJEH
1727     // movs r0, #1
1728     // LSJLJEH:
1729     unsigned SrcReg = MI->getOperand(0).getReg();
1730     unsigned ValReg = MI->getOperand(1).getReg();
1731     MCSymbol *Label = OutContext.createTempSymbol("SJLJEH", false, true);
1732     OutStreamer->AddComment("eh_setjmp begin");
1733     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1734       .addReg(ValReg)
1735       .addReg(ARM::PC)
1736       // Predicate.
1737       .addImm(ARMCC::AL)
1738       .addReg(0));
1739
1740     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDi3)
1741       .addReg(ValReg)
1742       // 's' bit operand
1743       .addReg(ARM::CPSR)
1744       .addReg(ValReg)
1745       .addImm(7)
1746       // Predicate.
1747       .addImm(ARMCC::AL)
1748       .addReg(0));
1749
1750     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tSTRi)
1751       .addReg(ValReg)
1752       .addReg(SrcReg)
1753       // The offset immediate is #4. The operand value is scaled by 4 for the
1754       // tSTR instruction.
1755       .addImm(1)
1756       // Predicate.
1757       .addImm(ARMCC::AL)
1758       .addReg(0));
1759
1760     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
1761       .addReg(ARM::R0)
1762       .addReg(ARM::CPSR)
1763       .addImm(0)
1764       // Predicate.
1765       .addImm(ARMCC::AL)
1766       .addReg(0));
1767
1768     const MCExpr *SymbolExpr = MCSymbolRefExpr::create(Label, OutContext);
1769     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tB)
1770       .addExpr(SymbolExpr)
1771       .addImm(ARMCC::AL)
1772       .addReg(0));
1773
1774     OutStreamer->AddComment("eh_setjmp end");
1775     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
1776       .addReg(ARM::R0)
1777       .addReg(ARM::CPSR)
1778       .addImm(1)
1779       // Predicate.
1780       .addImm(ARMCC::AL)
1781       .addReg(0));
1782
1783     OutStreamer->EmitLabel(Label);
1784     return;
1785   }
1786
1787   case ARM::Int_eh_sjlj_setjmp_nofp:
1788   case ARM::Int_eh_sjlj_setjmp: {
1789     // Two incoming args: GPR:$src, GPR:$val
1790     // add $val, pc, #8
1791     // str $val, [$src, #+4]
1792     // mov r0, #0
1793     // add pc, pc, #0
1794     // mov r0, #1
1795     unsigned SrcReg = MI->getOperand(0).getReg();
1796     unsigned ValReg = MI->getOperand(1).getReg();
1797
1798     OutStreamer->AddComment("eh_setjmp begin");
1799     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
1800       .addReg(ValReg)
1801       .addReg(ARM::PC)
1802       .addImm(8)
1803       // Predicate.
1804       .addImm(ARMCC::AL)
1805       .addReg(0)
1806       // 's' bit operand (always reg0 for this).
1807       .addReg(0));
1808
1809     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::STRi12)
1810       .addReg(ValReg)
1811       .addReg(SrcReg)
1812       .addImm(4)
1813       // Predicate.
1814       .addImm(ARMCC::AL)
1815       .addReg(0));
1816
1817     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
1818       .addReg(ARM::R0)
1819       .addImm(0)
1820       // Predicate.
1821       .addImm(ARMCC::AL)
1822       .addReg(0)
1823       // 's' bit operand (always reg0 for this).
1824       .addReg(0));
1825
1826     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
1827       .addReg(ARM::PC)
1828       .addReg(ARM::PC)
1829       .addImm(0)
1830       // Predicate.
1831       .addImm(ARMCC::AL)
1832       .addReg(0)
1833       // 's' bit operand (always reg0 for this).
1834       .addReg(0));
1835
1836     OutStreamer->AddComment("eh_setjmp end");
1837     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
1838       .addReg(ARM::R0)
1839       .addImm(1)
1840       // Predicate.
1841       .addImm(ARMCC::AL)
1842       .addReg(0)
1843       // 's' bit operand (always reg0 for this).
1844       .addReg(0));
1845     return;
1846   }
1847   case ARM::Int_eh_sjlj_longjmp: {
1848     // ldr sp, [$src, #8]
1849     // ldr $scratch, [$src, #4]
1850     // ldr r7, [$src]
1851     // bx $scratch
1852     unsigned SrcReg = MI->getOperand(0).getReg();
1853     unsigned ScratchReg = MI->getOperand(1).getReg();
1854     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1855       .addReg(ARM::SP)
1856       .addReg(SrcReg)
1857       .addImm(8)
1858       // Predicate.
1859       .addImm(ARMCC::AL)
1860       .addReg(0));
1861
1862     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1863       .addReg(ScratchReg)
1864       .addReg(SrcReg)
1865       .addImm(4)
1866       // Predicate.
1867       .addImm(ARMCC::AL)
1868       .addReg(0));
1869
1870     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1871       .addReg(ARM::R7)
1872       .addReg(SrcReg)
1873       .addImm(0)
1874       // Predicate.
1875       .addImm(ARMCC::AL)
1876       .addReg(0));
1877
1878     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
1879       .addReg(ScratchReg)
1880       // Predicate.
1881       .addImm(ARMCC::AL)
1882       .addReg(0));
1883     return;
1884   }
1885   case ARM::tInt_eh_sjlj_longjmp: {
1886     // ldr $scratch, [$src, #8]
1887     // mov sp, $scratch
1888     // ldr $scratch, [$src, #4]
1889     // ldr r7, [$src]
1890     // bx $scratch
1891     unsigned SrcReg = MI->getOperand(0).getReg();
1892     unsigned ScratchReg = MI->getOperand(1).getReg();
1893
1894     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
1895       .addReg(ScratchReg)
1896       .addReg(SrcReg)
1897       // The offset immediate is #8. The operand value is scaled by 4 for the
1898       // tLDR instruction.
1899       .addImm(2)
1900       // Predicate.
1901       .addImm(ARMCC::AL)
1902       .addReg(0));
1903
1904     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1905       .addReg(ARM::SP)
1906       .addReg(ScratchReg)
1907       // Predicate.
1908       .addImm(ARMCC::AL)
1909       .addReg(0));
1910
1911     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
1912       .addReg(ScratchReg)
1913       .addReg(SrcReg)
1914       .addImm(1)
1915       // Predicate.
1916       .addImm(ARMCC::AL)
1917       .addReg(0));
1918
1919     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
1920       .addReg(ARM::R7)
1921       .addReg(SrcReg)
1922       .addImm(0)
1923       // Predicate.
1924       .addImm(ARMCC::AL)
1925       .addReg(0));
1926
1927     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBX)
1928       .addReg(ScratchReg)
1929       // Predicate.
1930       .addImm(ARMCC::AL)
1931       .addReg(0));
1932     return;
1933   }
1934   case ARM::tInt_WIN_eh_sjlj_longjmp: {
1935     // ldr.w r11, [$src, #0]
1936     // ldr.w  sp, [$src, #8]
1937     // ldr.w  pc, [$src, #4]
1938
1939     unsigned SrcReg = MI->getOperand(0).getReg();
1940
1941     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
1942                                      .addReg(ARM::R11)
1943                                      .addReg(SrcReg)
1944                                      .addImm(0)
1945                                      // Predicate
1946                                      .addImm(ARMCC::AL)
1947                                      .addReg(0));
1948     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
1949                                      .addReg(ARM::SP)
1950                                      .addReg(SrcReg)
1951                                      .addImm(8)
1952                                      // Predicate
1953                                      .addImm(ARMCC::AL)
1954                                      .addReg(0));
1955     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
1956                                      .addReg(ARM::PC)
1957                                      .addReg(SrcReg)
1958                                      .addImm(4)
1959                                      // Predicate
1960                                      .addImm(ARMCC::AL)
1961                                      .addReg(0));
1962     return;
1963   }
1964   }
1965
1966   MCInst TmpInst;
1967   LowerARMMachineInstrToMCInst(MI, TmpInst, *this);
1968
1969   EmitToStreamer(*OutStreamer, TmpInst);
1970 }
1971
1972 //===----------------------------------------------------------------------===//
1973 // Target Registry Stuff
1974 //===----------------------------------------------------------------------===//
1975
1976 // Force static initialization.
1977 extern "C" void LLVMInitializeARMAsmPrinter() {
1978   RegisterAsmPrinter<ARMAsmPrinter> X(TheARMLETarget);
1979   RegisterAsmPrinter<ARMAsmPrinter> Y(TheARMBETarget);
1980   RegisterAsmPrinter<ARMAsmPrinter> A(TheThumbLETarget);
1981   RegisterAsmPrinter<ARMAsmPrinter> B(TheThumbBETarget);
1982 }