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