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:
896     return MCSymbolRefExpr::VK_None;
897   case ARMCP::TLSGD:
898     return MCSymbolRefExpr::VK_TLSGD;
899   case ARMCP::TPOFF:
900     return MCSymbolRefExpr::VK_TPOFF;
901   case ARMCP::GOTTPOFF:
902     return MCSymbolRefExpr::VK_GOTTPOFF;
903   case ARMCP::GOT_PREL:
904     return MCSymbolRefExpr::VK_ARM_GOT_PREL;
905   case ARMCP::SECREL:
906     return MCSymbolRefExpr::VK_SECREL;
907   }
908   llvm_unreachable("Invalid ARMCPModifier!");
909 }
910 
911 MCSymbol *ARMAsmPrinter::GetARMGVSymbol(const GlobalValue *GV,
912                                         unsigned char TargetFlags) {
913   if (Subtarget->isTargetMachO()) {
914     bool IsIndirect = (TargetFlags & ARMII::MO_NONLAZY) &&
915       Subtarget->GVIsIndirectSymbol(GV, TM.getRelocationModel());
916 
917     if (!IsIndirect)
918       return getSymbol(GV);
919 
920     // FIXME: Remove this when Darwin transition to @GOT like syntax.
921     MCSymbol *MCSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
922     MachineModuleInfoMachO &MMIMachO =
923       MMI->getObjFileInfo<MachineModuleInfoMachO>();
924     MachineModuleInfoImpl::StubValueTy &StubSym =
925         GV->isThreadLocal() ? MMIMachO.getThreadLocalGVStubEntry(MCSym)
926                             : MMIMachO.getGVStubEntry(MCSym);
927 
928     if (!StubSym.getPointer())
929       StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV),
930                                                    !GV->hasInternalLinkage());
931     return MCSym;
932   } else if (Subtarget->isTargetCOFF()) {
933     assert(Subtarget->isTargetWindows() &&
934            "Windows is the only supported COFF target");
935 
936     bool IsIndirect = (TargetFlags & ARMII::MO_DLLIMPORT);
937     if (!IsIndirect)
938       return getSymbol(GV);
939 
940     SmallString<128> Name;
941     Name = "__imp_";
942     getNameWithPrefix(Name, GV);
943 
944     return OutContext.getOrCreateSymbol(Name);
945   } else if (Subtarget->isTargetELF()) {
946     return getSymbol(GV);
947   }
948   llvm_unreachable("unexpected target");
949 }
950 
951 void ARMAsmPrinter::
952 EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
953   const DataLayout &DL = getDataLayout();
954   int Size = DL.getTypeAllocSize(MCPV->getType());
955 
956   ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
957 
958   MCSymbol *MCSym;
959   if (ACPV->isLSDA()) {
960     MCSym = getCurExceptionSym();
961   } else if (ACPV->isBlockAddress()) {
962     const BlockAddress *BA =
963       cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress();
964     MCSym = GetBlockAddressSymbol(BA);
965   } else if (ACPV->isGlobalValue()) {
966     const GlobalValue *GV = cast<ARMConstantPoolConstant>(ACPV)->getGV();
967 
968     // On Darwin, const-pool entries may get the "FOO$non_lazy_ptr" mangling, so
969     // flag the global as MO_NONLAZY.
970     unsigned char TF = Subtarget->isTargetMachO() ? ARMII::MO_NONLAZY : 0;
971     MCSym = GetARMGVSymbol(GV, TF);
972   } else if (ACPV->isMachineBasicBlock()) {
973     const MachineBasicBlock *MBB = cast<ARMConstantPoolMBB>(ACPV)->getMBB();
974     MCSym = MBB->getSymbol();
975   } else {
976     assert(ACPV->isExtSymbol() && "unrecognized constant pool value");
977     const char *Sym = cast<ARMConstantPoolSymbol>(ACPV)->getSymbol();
978     MCSym = GetExternalSymbolSymbol(Sym);
979   }
980 
981   // Create an MCSymbol for the reference.
982   const MCExpr *Expr =
983     MCSymbolRefExpr::create(MCSym, getModifierVariantKind(ACPV->getModifier()),
984                             OutContext);
985 
986   if (ACPV->getPCAdjustment()) {
987     MCSymbol *PCLabel =
988         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
989                     ACPV->getLabelId(), OutContext);
990     const MCExpr *PCRelExpr = MCSymbolRefExpr::create(PCLabel, OutContext);
991     PCRelExpr =
992       MCBinaryExpr::createAdd(PCRelExpr,
993                               MCConstantExpr::create(ACPV->getPCAdjustment(),
994                                                      OutContext),
995                               OutContext);
996     if (ACPV->mustAddCurrentAddress()) {
997       // We want "(<expr> - .)", but MC doesn't have a concept of the '.'
998       // label, so just emit a local label end reference that instead.
999       MCSymbol *DotSym = OutContext.createTempSymbol();
1000       OutStreamer->EmitLabel(DotSym);
1001       const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
1002       PCRelExpr = MCBinaryExpr::createSub(PCRelExpr, DotExpr, OutContext);
1003     }
1004     Expr = MCBinaryExpr::createSub(Expr, PCRelExpr, OutContext);
1005   }
1006   OutStreamer->EmitValue(Expr, Size);
1007 }
1008 
1009 void ARMAsmPrinter::EmitJumpTableAddrs(const MachineInstr *MI) {
1010   const MachineOperand &MO1 = MI->getOperand(1);
1011   unsigned JTI = MO1.getIndex();
1012 
1013   // Make sure the Thumb jump table is 4-byte aligned. This will be a nop for
1014   // ARM mode tables.
1015   EmitAlignment(2);
1016 
1017   // Emit a label for the jump table.
1018   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
1019   OutStreamer->EmitLabel(JTISymbol);
1020 
1021   // Mark the jump table as data-in-code.
1022   OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
1023 
1024   // Emit each entry of the table.
1025   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1026   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1027   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1028 
1029   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
1030     MachineBasicBlock *MBB = JTBBs[i];
1031     // Construct an MCExpr for the entry. We want a value of the form:
1032     // (BasicBlockAddr - TableBeginAddr)
1033     //
1034     // For example, a table with entries jumping to basic blocks BB0 and BB1
1035     // would look like:
1036     // LJTI_0_0:
1037     //    .word (LBB0 - LJTI_0_0)
1038     //    .word (LBB1 - LJTI_0_0)
1039     const MCExpr *Expr = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1040 
1041     if (TM.getRelocationModel() == Reloc::PIC_)
1042       Expr = MCBinaryExpr::createSub(Expr, MCSymbolRefExpr::create(JTISymbol,
1043                                                                    OutContext),
1044                                      OutContext);
1045     // If we're generating a table of Thumb addresses in static relocation
1046     // model, we need to add one to keep interworking correctly.
1047     else if (AFI->isThumbFunction())
1048       Expr = MCBinaryExpr::createAdd(Expr, MCConstantExpr::create(1,OutContext),
1049                                      OutContext);
1050     OutStreamer->EmitValue(Expr, 4);
1051   }
1052   // Mark the end of jump table data-in-code region.
1053   OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1054 }
1055 
1056 void ARMAsmPrinter::EmitJumpTableInsts(const MachineInstr *MI) {
1057   const MachineOperand &MO1 = MI->getOperand(1);
1058   unsigned JTI = MO1.getIndex();
1059 
1060   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
1061   OutStreamer->EmitLabel(JTISymbol);
1062 
1063   // Emit each entry of the table.
1064   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1065   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1066   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1067 
1068   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
1069     MachineBasicBlock *MBB = JTBBs[i];
1070     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
1071                                                           OutContext);
1072     // If this isn't a TBB or TBH, the entries are direct branch instructions.
1073     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2B)
1074         .addExpr(MBBSymbolExpr)
1075         .addImm(ARMCC::AL)
1076         .addReg(0));
1077   }
1078 }
1079 
1080 void ARMAsmPrinter::EmitJumpTableTBInst(const MachineInstr *MI,
1081                                         unsigned OffsetWidth) {
1082   assert((OffsetWidth == 1 || OffsetWidth == 2) && "invalid tbb/tbh width");
1083   const MachineOperand &MO1 = MI->getOperand(1);
1084   unsigned JTI = MO1.getIndex();
1085 
1086   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
1087   OutStreamer->EmitLabel(JTISymbol);
1088 
1089   // Emit each entry of the table.
1090   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1091   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1092   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1093 
1094   // Mark the jump table as data-in-code.
1095   OutStreamer->EmitDataRegion(OffsetWidth == 1 ? MCDR_DataRegionJT8
1096                                                : MCDR_DataRegionJT16);
1097 
1098   for (auto MBB : JTBBs) {
1099     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
1100                                                           OutContext);
1101     // Otherwise it's an offset from the dispatch instruction. Construct an
1102     // MCExpr for the entry. We want a value of the form:
1103     // (BasicBlockAddr - TBBInstAddr + 4) / 2
1104     //
1105     // For example, a TBB table with entries jumping to basic blocks BB0 and BB1
1106     // would look like:
1107     // LJTI_0_0:
1108     //    .byte (LBB0 - (LCPI0_0 + 4)) / 2
1109     //    .byte (LBB1 - (LCPI0_0 + 4)) / 2
1110     // where LCPI0_0 is a label defined just before the TBB instruction using
1111     // this table.
1112     MCSymbol *TBInstPC = GetCPISymbol(MI->getOperand(0).getImm());
1113     const MCExpr *Expr = MCBinaryExpr::createAdd(
1114         MCSymbolRefExpr::create(TBInstPC, OutContext),
1115         MCConstantExpr::create(4, OutContext), OutContext);
1116     Expr = MCBinaryExpr::createSub(MBBSymbolExpr, Expr, OutContext);
1117     Expr = MCBinaryExpr::createDiv(Expr, MCConstantExpr::create(2, OutContext),
1118                                    OutContext);
1119     OutStreamer->EmitValue(Expr, OffsetWidth);
1120   }
1121   // Mark the end of jump table data-in-code region. 32-bit offsets use
1122   // actual branch instructions here, so we don't mark those as a data-region
1123   // at all.
1124   OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1125 
1126   // Make sure the next instruction is 2-byte aligned.
1127   EmitAlignment(1);
1128 }
1129 
1130 void ARMAsmPrinter::EmitUnwindingInstruction(const MachineInstr *MI) {
1131   assert(MI->getFlag(MachineInstr::FrameSetup) &&
1132       "Only instruction which are involved into frame setup code are allowed");
1133 
1134   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
1135   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1136   const MachineFunction &MF = *MI->getParent()->getParent();
1137   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
1138   const ARMFunctionInfo &AFI = *MF.getInfo<ARMFunctionInfo>();
1139 
1140   unsigned FramePtr = RegInfo->getFrameRegister(MF);
1141   unsigned Opc = MI->getOpcode();
1142   unsigned SrcReg, DstReg;
1143 
1144   if (Opc == ARM::tPUSH || Opc == ARM::tLDRpci) {
1145     // Two special cases:
1146     // 1) tPUSH does not have src/dst regs.
1147     // 2) for Thumb1 code we sometimes materialize the constant via constpool
1148     // load. Yes, this is pretty fragile, but for now I don't see better
1149     // way... :(
1150     SrcReg = DstReg = ARM::SP;
1151   } else {
1152     SrcReg = MI->getOperand(1).getReg();
1153     DstReg = MI->getOperand(0).getReg();
1154   }
1155 
1156   // Try to figure out the unwinding opcode out of src / dst regs.
1157   if (MI->mayStore()) {
1158     // Register saves.
1159     assert(DstReg == ARM::SP &&
1160            "Only stack pointer as a destination reg is supported");
1161 
1162     SmallVector<unsigned, 4> RegList;
1163     // Skip src & dst reg, and pred ops.
1164     unsigned StartOp = 2 + 2;
1165     // Use all the operands.
1166     unsigned NumOffset = 0;
1167 
1168     switch (Opc) {
1169     default:
1170       MI->dump();
1171       llvm_unreachable("Unsupported opcode for unwinding information");
1172     case ARM::tPUSH:
1173       // Special case here: no src & dst reg, but two extra imp ops.
1174       StartOp = 2; NumOffset = 2;
1175     case ARM::STMDB_UPD:
1176     case ARM::t2STMDB_UPD:
1177     case ARM::VSTMDDB_UPD:
1178       assert(SrcReg == ARM::SP &&
1179              "Only stack pointer as a source reg is supported");
1180       for (unsigned i = StartOp, NumOps = MI->getNumOperands() - NumOffset;
1181            i != NumOps; ++i) {
1182         const MachineOperand &MO = MI->getOperand(i);
1183         // Actually, there should never be any impdef stuff here. Skip it
1184         // temporary to workaround PR11902.
1185         if (MO.isImplicit())
1186           continue;
1187         RegList.push_back(MO.getReg());
1188       }
1189       break;
1190     case ARM::STR_PRE_IMM:
1191     case ARM::STR_PRE_REG:
1192     case ARM::t2STR_PRE:
1193       assert(MI->getOperand(2).getReg() == ARM::SP &&
1194              "Only stack pointer as a source reg is supported");
1195       RegList.push_back(SrcReg);
1196       break;
1197     }
1198     if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM)
1199       ATS.emitRegSave(RegList, Opc == ARM::VSTMDDB_UPD);
1200   } else {
1201     // Changes of stack / frame pointer.
1202     if (SrcReg == ARM::SP) {
1203       int64_t Offset = 0;
1204       switch (Opc) {
1205       default:
1206         MI->dump();
1207         llvm_unreachable("Unsupported opcode for unwinding information");
1208       case ARM::MOVr:
1209       case ARM::tMOVr:
1210         Offset = 0;
1211         break;
1212       case ARM::ADDri:
1213       case ARM::t2ADDri:
1214         Offset = -MI->getOperand(2).getImm();
1215         break;
1216       case ARM::SUBri:
1217       case ARM::t2SUBri:
1218         Offset = MI->getOperand(2).getImm();
1219         break;
1220       case ARM::tSUBspi:
1221         Offset = MI->getOperand(2).getImm()*4;
1222         break;
1223       case ARM::tADDspi:
1224       case ARM::tADDrSPi:
1225         Offset = -MI->getOperand(2).getImm()*4;
1226         break;
1227       case ARM::tLDRpci: {
1228         // Grab the constpool index and check, whether it corresponds to
1229         // original or cloned constpool entry.
1230         unsigned CPI = MI->getOperand(1).getIndex();
1231         const MachineConstantPool *MCP = MF.getConstantPool();
1232         if (CPI >= MCP->getConstants().size())
1233           CPI = AFI.getOriginalCPIdx(CPI);
1234         assert(CPI != -1U && "Invalid constpool index");
1235 
1236         // Derive the actual offset.
1237         const MachineConstantPoolEntry &CPE = MCP->getConstants()[CPI];
1238         assert(!CPE.isMachineConstantPoolEntry() && "Invalid constpool entry");
1239         // FIXME: Check for user, it should be "add" instruction!
1240         Offset = -cast<ConstantInt>(CPE.Val.ConstVal)->getSExtValue();
1241         break;
1242       }
1243       }
1244 
1245       if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM) {
1246         if (DstReg == FramePtr && FramePtr != ARM::SP)
1247           // Set-up of the frame pointer. Positive values correspond to "add"
1248           // instruction.
1249           ATS.emitSetFP(FramePtr, ARM::SP, -Offset);
1250         else if (DstReg == ARM::SP) {
1251           // Change of SP by an offset. Positive values correspond to "sub"
1252           // instruction.
1253           ATS.emitPad(Offset);
1254         } else {
1255           // Move of SP to a register.  Positive values correspond to an "add"
1256           // instruction.
1257           ATS.emitMovSP(DstReg, -Offset);
1258         }
1259       }
1260     } else if (DstReg == ARM::SP) {
1261       MI->dump();
1262       llvm_unreachable("Unsupported opcode for unwinding information");
1263     }
1264     else {
1265       MI->dump();
1266       llvm_unreachable("Unsupported opcode for unwinding information");
1267     }
1268   }
1269 }
1270 
1271 // Simple pseudo-instructions have their lowering (with expansion to real
1272 // instructions) auto-generated.
1273 #include "ARMGenMCPseudoLowering.inc"
1274 
1275 void ARMAsmPrinter::EmitInstruction(const MachineInstr *MI) {
1276   const DataLayout &DL = getDataLayout();
1277   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
1278   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1279 
1280   // If we just ended a constant pool, mark it as such.
1281   if (InConstantPool && MI->getOpcode() != ARM::CONSTPOOL_ENTRY) {
1282     OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
1283     InConstantPool = false;
1284   }
1285 
1286   // Emit unwinding stuff for frame-related instructions
1287   if (Subtarget->isTargetEHABICompatible() &&
1288        MI->getFlag(MachineInstr::FrameSetup))
1289     EmitUnwindingInstruction(MI);
1290 
1291   // Do any auto-generated pseudo lowerings.
1292   if (emitPseudoExpansionLowering(*OutStreamer, MI))
1293     return;
1294 
1295   assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
1296          "Pseudo flag setting opcode should be expanded early");
1297 
1298   // Check for manual lowerings.
1299   unsigned Opc = MI->getOpcode();
1300   switch (Opc) {
1301   case ARM::t2MOVi32imm: llvm_unreachable("Should be lowered by thumb2it pass");
1302   case ARM::DBG_VALUE: llvm_unreachable("Should be handled by generic printing");
1303   case ARM::LEApcrel:
1304   case ARM::tLEApcrel:
1305   case ARM::t2LEApcrel: {
1306     // FIXME: Need to also handle globals and externals
1307     MCSymbol *CPISymbol = GetCPISymbol(MI->getOperand(1).getIndex());
1308     EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
1309                                                ARM::t2LEApcrel ? ARM::t2ADR
1310                   : (MI->getOpcode() == ARM::tLEApcrel ? ARM::tADR
1311                      : ARM::ADR))
1312       .addReg(MI->getOperand(0).getReg())
1313       .addExpr(MCSymbolRefExpr::create(CPISymbol, OutContext))
1314       // Add predicate operands.
1315       .addImm(MI->getOperand(2).getImm())
1316       .addReg(MI->getOperand(3).getReg()));
1317     return;
1318   }
1319   case ARM::LEApcrelJT:
1320   case ARM::tLEApcrelJT:
1321   case ARM::t2LEApcrelJT: {
1322     MCSymbol *JTIPICSymbol =
1323       GetARMJTIPICJumpTableLabel(MI->getOperand(1).getIndex());
1324     EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
1325                                                ARM::t2LEApcrelJT ? ARM::t2ADR
1326                   : (MI->getOpcode() == ARM::tLEApcrelJT ? ARM::tADR
1327                      : ARM::ADR))
1328       .addReg(MI->getOperand(0).getReg())
1329       .addExpr(MCSymbolRefExpr::create(JTIPICSymbol, OutContext))
1330       // Add predicate operands.
1331       .addImm(MI->getOperand(2).getImm())
1332       .addReg(MI->getOperand(3).getReg()));
1333     return;
1334   }
1335   // Darwin call instructions are just normal call instructions with different
1336   // clobber semantics (they clobber R9).
1337   case ARM::BX_CALL: {
1338     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1339       .addReg(ARM::LR)
1340       .addReg(ARM::PC)
1341       // Add predicate operands.
1342       .addImm(ARMCC::AL)
1343       .addReg(0)
1344       // Add 's' bit operand (always reg0 for this)
1345       .addReg(0));
1346 
1347     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
1348       .addReg(MI->getOperand(0).getReg()));
1349     return;
1350   }
1351   case ARM::tBX_CALL: {
1352     if (Subtarget->hasV5TOps())
1353       llvm_unreachable("Expected BLX to be selected for v5t+");
1354 
1355     // On ARM v4t, when doing a call from thumb mode, we need to ensure
1356     // that the saved lr has its LSB set correctly (the arch doesn't
1357     // have blx).
1358     // So here we generate a bl to a small jump pad that does bx rN.
1359     // The jump pads are emitted after the function body.
1360 
1361     unsigned TReg = MI->getOperand(0).getReg();
1362     MCSymbol *TRegSym = nullptr;
1363     for (unsigned i = 0, e = ThumbIndirectPads.size(); i < e; i++) {
1364       if (ThumbIndirectPads[i].first == TReg) {
1365         TRegSym = ThumbIndirectPads[i].second;
1366         break;
1367       }
1368     }
1369 
1370     if (!TRegSym) {
1371       TRegSym = OutContext.createTempSymbol();
1372       ThumbIndirectPads.push_back(std::make_pair(TReg, TRegSym));
1373     }
1374 
1375     // Create a link-saving branch to the Reg Indirect Jump Pad.
1376     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBL)
1377         // Predicate comes first here.
1378         .addImm(ARMCC::AL).addReg(0)
1379         .addExpr(MCSymbolRefExpr::create(TRegSym, OutContext)));
1380     return;
1381   }
1382   case ARM::BMOVPCRX_CALL: {
1383     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1384       .addReg(ARM::LR)
1385       .addReg(ARM::PC)
1386       // Add predicate operands.
1387       .addImm(ARMCC::AL)
1388       .addReg(0)
1389       // Add 's' bit operand (always reg0 for this)
1390       .addReg(0));
1391 
1392     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1393       .addReg(ARM::PC)
1394       .addReg(MI->getOperand(0).getReg())
1395       // Add predicate operands.
1396       .addImm(ARMCC::AL)
1397       .addReg(0)
1398       // Add 's' bit operand (always reg0 for this)
1399       .addReg(0));
1400     return;
1401   }
1402   case ARM::BMOVPCB_CALL: {
1403     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1404       .addReg(ARM::LR)
1405       .addReg(ARM::PC)
1406       // Add predicate operands.
1407       .addImm(ARMCC::AL)
1408       .addReg(0)
1409       // Add 's' bit operand (always reg0 for this)
1410       .addReg(0));
1411 
1412     const MachineOperand &Op = MI->getOperand(0);
1413     const GlobalValue *GV = Op.getGlobal();
1414     const unsigned TF = Op.getTargetFlags();
1415     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1416     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1417     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::Bcc)
1418       .addExpr(GVSymExpr)
1419       // Add predicate operands.
1420       .addImm(ARMCC::AL)
1421       .addReg(0));
1422     return;
1423   }
1424   case ARM::MOVi16_ga_pcrel:
1425   case ARM::t2MOVi16_ga_pcrel: {
1426     MCInst TmpInst;
1427     TmpInst.setOpcode(Opc == ARM::MOVi16_ga_pcrel? ARM::MOVi16 : ARM::t2MOVi16);
1428     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1429 
1430     unsigned TF = MI->getOperand(1).getTargetFlags();
1431     const GlobalValue *GV = MI->getOperand(1).getGlobal();
1432     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1433     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1434 
1435     MCSymbol *LabelSym =
1436         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1437                     MI->getOperand(2).getImm(), OutContext);
1438     const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
1439     unsigned PCAdj = (Opc == ARM::MOVi16_ga_pcrel) ? 8 : 4;
1440     const MCExpr *PCRelExpr =
1441       ARMMCExpr::createLower16(MCBinaryExpr::createSub(GVSymExpr,
1442                                       MCBinaryExpr::createAdd(LabelSymExpr,
1443                                       MCConstantExpr::create(PCAdj, OutContext),
1444                                       OutContext), OutContext), OutContext);
1445       TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
1446 
1447     // Add predicate operands.
1448     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1449     TmpInst.addOperand(MCOperand::createReg(0));
1450     // Add 's' bit operand (always reg0 for this)
1451     TmpInst.addOperand(MCOperand::createReg(0));
1452     EmitToStreamer(*OutStreamer, TmpInst);
1453     return;
1454   }
1455   case ARM::MOVTi16_ga_pcrel:
1456   case ARM::t2MOVTi16_ga_pcrel: {
1457     MCInst TmpInst;
1458     TmpInst.setOpcode(Opc == ARM::MOVTi16_ga_pcrel
1459                       ? ARM::MOVTi16 : ARM::t2MOVTi16);
1460     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1461     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
1462 
1463     unsigned TF = MI->getOperand(2).getTargetFlags();
1464     const GlobalValue *GV = MI->getOperand(2).getGlobal();
1465     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1466     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1467 
1468     MCSymbol *LabelSym =
1469         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1470                     MI->getOperand(3).getImm(), OutContext);
1471     const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
1472     unsigned PCAdj = (Opc == ARM::MOVTi16_ga_pcrel) ? 8 : 4;
1473     const MCExpr *PCRelExpr =
1474         ARMMCExpr::createUpper16(MCBinaryExpr::createSub(GVSymExpr,
1475                                    MCBinaryExpr::createAdd(LabelSymExpr,
1476                                       MCConstantExpr::create(PCAdj, OutContext),
1477                                           OutContext), OutContext), OutContext);
1478       TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
1479     // Add predicate operands.
1480     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1481     TmpInst.addOperand(MCOperand::createReg(0));
1482     // Add 's' bit operand (always reg0 for this)
1483     TmpInst.addOperand(MCOperand::createReg(0));
1484     EmitToStreamer(*OutStreamer, TmpInst);
1485     return;
1486   }
1487   case ARM::tPICADD: {
1488     // This is a pseudo op for a label + instruction sequence, which looks like:
1489     // LPC0:
1490     //     add r0, pc
1491     // This adds the address of LPC0 to r0.
1492 
1493     // Emit the label.
1494     OutStreamer->EmitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1495                                        getFunctionNumber(),
1496                                        MI->getOperand(2).getImm(), OutContext));
1497 
1498     // Form and emit the add.
1499     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1500       .addReg(MI->getOperand(0).getReg())
1501       .addReg(MI->getOperand(0).getReg())
1502       .addReg(ARM::PC)
1503       // Add predicate operands.
1504       .addImm(ARMCC::AL)
1505       .addReg(0));
1506     return;
1507   }
1508   case ARM::PICADD: {
1509     // This is a pseudo op for a label + instruction sequence, which looks like:
1510     // LPC0:
1511     //     add r0, pc, r0
1512     // This adds the address of LPC0 to r0.
1513 
1514     // Emit the label.
1515     OutStreamer->EmitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1516                                        getFunctionNumber(),
1517                                        MI->getOperand(2).getImm(), OutContext));
1518 
1519     // Form and emit the add.
1520     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
1521       .addReg(MI->getOperand(0).getReg())
1522       .addReg(ARM::PC)
1523       .addReg(MI->getOperand(1).getReg())
1524       // Add predicate operands.
1525       .addImm(MI->getOperand(3).getImm())
1526       .addReg(MI->getOperand(4).getReg())
1527       // Add 's' bit operand (always reg0 for this)
1528       .addReg(0));
1529     return;
1530   }
1531   case ARM::PICSTR:
1532   case ARM::PICSTRB:
1533   case ARM::PICSTRH:
1534   case ARM::PICLDR:
1535   case ARM::PICLDRB:
1536   case ARM::PICLDRH:
1537   case ARM::PICLDRSB:
1538   case ARM::PICLDRSH: {
1539     // This is a pseudo op for a label + instruction sequence, which looks like:
1540     // LPC0:
1541     //     OP r0, [pc, r0]
1542     // The LCP0 label is referenced by a constant pool entry in order to get
1543     // a PC-relative address at the ldr instruction.
1544 
1545     // Emit the label.
1546     OutStreamer->EmitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1547                                        getFunctionNumber(),
1548                                        MI->getOperand(2).getImm(), OutContext));
1549 
1550     // Form and emit the load
1551     unsigned Opcode;
1552     switch (MI->getOpcode()) {
1553     default:
1554       llvm_unreachable("Unexpected opcode!");
1555     case ARM::PICSTR:   Opcode = ARM::STRrs; break;
1556     case ARM::PICSTRB:  Opcode = ARM::STRBrs; break;
1557     case ARM::PICSTRH:  Opcode = ARM::STRH; break;
1558     case ARM::PICLDR:   Opcode = ARM::LDRrs; break;
1559     case ARM::PICLDRB:  Opcode = ARM::LDRBrs; break;
1560     case ARM::PICLDRH:  Opcode = ARM::LDRH; break;
1561     case ARM::PICLDRSB: Opcode = ARM::LDRSB; break;
1562     case ARM::PICLDRSH: Opcode = ARM::LDRSH; break;
1563     }
1564     EmitToStreamer(*OutStreamer, MCInstBuilder(Opcode)
1565       .addReg(MI->getOperand(0).getReg())
1566       .addReg(ARM::PC)
1567       .addReg(MI->getOperand(1).getReg())
1568       .addImm(0)
1569       // Add predicate operands.
1570       .addImm(MI->getOperand(3).getImm())
1571       .addReg(MI->getOperand(4).getReg()));
1572 
1573     return;
1574   }
1575   case ARM::CONSTPOOL_ENTRY: {
1576     /// CONSTPOOL_ENTRY - This instruction represents a floating constant pool
1577     /// in the function.  The first operand is the ID# for this instruction, the
1578     /// second is the index into the MachineConstantPool that this is, the third
1579     /// is the size in bytes of this constant pool entry.
1580     /// The required alignment is specified on the basic block holding this MI.
1581     unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
1582     unsigned CPIdx   = (unsigned)MI->getOperand(1).getIndex();
1583 
1584     // If this is the first entry of the pool, mark it.
1585     if (!InConstantPool) {
1586       OutStreamer->EmitDataRegion(MCDR_DataRegion);
1587       InConstantPool = true;
1588     }
1589 
1590     OutStreamer->EmitLabel(GetCPISymbol(LabelId));
1591 
1592     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
1593     if (MCPE.isMachineConstantPoolEntry())
1594       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
1595     else
1596       EmitGlobalConstant(DL, MCPE.Val.ConstVal);
1597     return;
1598   }
1599   case ARM::JUMPTABLE_ADDRS:
1600     EmitJumpTableAddrs(MI);
1601     return;
1602   case ARM::JUMPTABLE_INSTS:
1603     EmitJumpTableInsts(MI);
1604     return;
1605   case ARM::JUMPTABLE_TBB:
1606   case ARM::JUMPTABLE_TBH:
1607     EmitJumpTableTBInst(MI, MI->getOpcode() == ARM::JUMPTABLE_TBB ? 1 : 2);
1608     return;
1609   case ARM::t2BR_JT: {
1610     // Lower and emit the instruction itself, then the jump table following it.
1611     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1612       .addReg(ARM::PC)
1613       .addReg(MI->getOperand(0).getReg())
1614       // Add predicate operands.
1615       .addImm(ARMCC::AL)
1616       .addReg(0));
1617     return;
1618   }
1619   case ARM::t2TBB_JT:
1620   case ARM::t2TBH_JT: {
1621     unsigned Opc = MI->getOpcode() == ARM::t2TBB_JT ? ARM::t2TBB : ARM::t2TBH;
1622     // Lower and emit the PC label, then the instruction itself.
1623     OutStreamer->EmitLabel(GetCPISymbol(MI->getOperand(3).getImm()));
1624     EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1625                                      .addReg(MI->getOperand(0).getReg())
1626                                      .addReg(MI->getOperand(1).getReg())
1627                                      // Add predicate operands.
1628                                      .addImm(ARMCC::AL)
1629                                      .addReg(0));
1630     return;
1631   }
1632   case ARM::tBR_JTr:
1633   case ARM::BR_JTr: {
1634     // Lower and emit the instruction itself, then the jump table following it.
1635     // mov pc, target
1636     MCInst TmpInst;
1637     unsigned Opc = MI->getOpcode() == ARM::BR_JTr ?
1638       ARM::MOVr : ARM::tMOVr;
1639     TmpInst.setOpcode(Opc);
1640     TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1641     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1642     // Add predicate operands.
1643     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1644     TmpInst.addOperand(MCOperand::createReg(0));
1645     // Add 's' bit operand (always reg0 for this)
1646     if (Opc == ARM::MOVr)
1647       TmpInst.addOperand(MCOperand::createReg(0));
1648     EmitToStreamer(*OutStreamer, TmpInst);
1649     return;
1650   }
1651   case ARM::BR_JTm: {
1652     // Lower and emit the instruction itself, then the jump table following it.
1653     // ldr pc, target
1654     MCInst TmpInst;
1655     if (MI->getOperand(1).getReg() == 0) {
1656       // literal offset
1657       TmpInst.setOpcode(ARM::LDRi12);
1658       TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1659       TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1660       TmpInst.addOperand(MCOperand::createImm(MI->getOperand(2).getImm()));
1661     } else {
1662       TmpInst.setOpcode(ARM::LDRrs);
1663       TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1664       TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1665       TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
1666       TmpInst.addOperand(MCOperand::createImm(0));
1667     }
1668     // Add predicate operands.
1669     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1670     TmpInst.addOperand(MCOperand::createReg(0));
1671     EmitToStreamer(*OutStreamer, TmpInst);
1672     return;
1673   }
1674   case ARM::BR_JTadd: {
1675     // Lower and emit the instruction itself, then the jump table following it.
1676     // add pc, target, idx
1677     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
1678       .addReg(ARM::PC)
1679       .addReg(MI->getOperand(0).getReg())
1680       .addReg(MI->getOperand(1).getReg())
1681       // Add predicate operands.
1682       .addImm(ARMCC::AL)
1683       .addReg(0)
1684       // Add 's' bit operand (always reg0 for this)
1685       .addReg(0));
1686     return;
1687   }
1688   case ARM::SPACE:
1689     OutStreamer->EmitZeros(MI->getOperand(1).getImm());
1690     return;
1691   case ARM::TRAP: {
1692     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1693     // FIXME: Remove this special case when they do.
1694     if (!Subtarget->isTargetMachO()) {
1695       uint32_t Val = 0xe7ffdefeUL;
1696       OutStreamer->AddComment("trap");
1697       ATS.emitInst(Val);
1698       return;
1699     }
1700     break;
1701   }
1702   case ARM::TRAPNaCl: {
1703     uint32_t Val = 0xe7fedef0UL;
1704     OutStreamer->AddComment("trap");
1705     ATS.emitInst(Val);
1706     return;
1707   }
1708   case ARM::tTRAP: {
1709     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1710     // FIXME: Remove this special case when they do.
1711     if (!Subtarget->isTargetMachO()) {
1712       uint16_t Val = 0xdefe;
1713       OutStreamer->AddComment("trap");
1714       ATS.emitInst(Val, 'n');
1715       return;
1716     }
1717     break;
1718   }
1719   case ARM::t2Int_eh_sjlj_setjmp:
1720   case ARM::t2Int_eh_sjlj_setjmp_nofp:
1721   case ARM::tInt_eh_sjlj_setjmp: {
1722     // Two incoming args: GPR:$src, GPR:$val
1723     // mov $val, pc
1724     // adds $val, #7
1725     // str $val, [$src, #4]
1726     // movs r0, #0
1727     // b LSJLJEH
1728     // movs r0, #1
1729     // LSJLJEH:
1730     unsigned SrcReg = MI->getOperand(0).getReg();
1731     unsigned ValReg = MI->getOperand(1).getReg();
1732     MCSymbol *Label = OutContext.createTempSymbol("SJLJEH", false, true);
1733     OutStreamer->AddComment("eh_setjmp begin");
1734     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1735       .addReg(ValReg)
1736       .addReg(ARM::PC)
1737       // Predicate.
1738       .addImm(ARMCC::AL)
1739       .addReg(0));
1740 
1741     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDi3)
1742       .addReg(ValReg)
1743       // 's' bit operand
1744       .addReg(ARM::CPSR)
1745       .addReg(ValReg)
1746       .addImm(7)
1747       // Predicate.
1748       .addImm(ARMCC::AL)
1749       .addReg(0));
1750 
1751     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tSTRi)
1752       .addReg(ValReg)
1753       .addReg(SrcReg)
1754       // The offset immediate is #4. The operand value is scaled by 4 for the
1755       // tSTR instruction.
1756       .addImm(1)
1757       // Predicate.
1758       .addImm(ARMCC::AL)
1759       .addReg(0));
1760 
1761     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
1762       .addReg(ARM::R0)
1763       .addReg(ARM::CPSR)
1764       .addImm(0)
1765       // Predicate.
1766       .addImm(ARMCC::AL)
1767       .addReg(0));
1768 
1769     const MCExpr *SymbolExpr = MCSymbolRefExpr::create(Label, OutContext);
1770     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tB)
1771       .addExpr(SymbolExpr)
1772       .addImm(ARMCC::AL)
1773       .addReg(0));
1774 
1775     OutStreamer->AddComment("eh_setjmp end");
1776     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
1777       .addReg(ARM::R0)
1778       .addReg(ARM::CPSR)
1779       .addImm(1)
1780       // Predicate.
1781       .addImm(ARMCC::AL)
1782       .addReg(0));
1783 
1784     OutStreamer->EmitLabel(Label);
1785     return;
1786   }
1787 
1788   case ARM::Int_eh_sjlj_setjmp_nofp:
1789   case ARM::Int_eh_sjlj_setjmp: {
1790     // Two incoming args: GPR:$src, GPR:$val
1791     // add $val, pc, #8
1792     // str $val, [$src, #+4]
1793     // mov r0, #0
1794     // add pc, pc, #0
1795     // mov r0, #1
1796     unsigned SrcReg = MI->getOperand(0).getReg();
1797     unsigned ValReg = MI->getOperand(1).getReg();
1798 
1799     OutStreamer->AddComment("eh_setjmp begin");
1800     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
1801       .addReg(ValReg)
1802       .addReg(ARM::PC)
1803       .addImm(8)
1804       // Predicate.
1805       .addImm(ARMCC::AL)
1806       .addReg(0)
1807       // 's' bit operand (always reg0 for this).
1808       .addReg(0));
1809 
1810     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::STRi12)
1811       .addReg(ValReg)
1812       .addReg(SrcReg)
1813       .addImm(4)
1814       // Predicate.
1815       .addImm(ARMCC::AL)
1816       .addReg(0));
1817 
1818     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
1819       .addReg(ARM::R0)
1820       .addImm(0)
1821       // Predicate.
1822       .addImm(ARMCC::AL)
1823       .addReg(0)
1824       // 's' bit operand (always reg0 for this).
1825       .addReg(0));
1826 
1827     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
1828       .addReg(ARM::PC)
1829       .addReg(ARM::PC)
1830       .addImm(0)
1831       // Predicate.
1832       .addImm(ARMCC::AL)
1833       .addReg(0)
1834       // 's' bit operand (always reg0 for this).
1835       .addReg(0));
1836 
1837     OutStreamer->AddComment("eh_setjmp end");
1838     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
1839       .addReg(ARM::R0)
1840       .addImm(1)
1841       // Predicate.
1842       .addImm(ARMCC::AL)
1843       .addReg(0)
1844       // 's' bit operand (always reg0 for this).
1845       .addReg(0));
1846     return;
1847   }
1848   case ARM::Int_eh_sjlj_longjmp: {
1849     // ldr sp, [$src, #8]
1850     // ldr $scratch, [$src, #4]
1851     // ldr r7, [$src]
1852     // bx $scratch
1853     unsigned SrcReg = MI->getOperand(0).getReg();
1854     unsigned ScratchReg = MI->getOperand(1).getReg();
1855     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1856       .addReg(ARM::SP)
1857       .addReg(SrcReg)
1858       .addImm(8)
1859       // Predicate.
1860       .addImm(ARMCC::AL)
1861       .addReg(0));
1862 
1863     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1864       .addReg(ScratchReg)
1865       .addReg(SrcReg)
1866       .addImm(4)
1867       // Predicate.
1868       .addImm(ARMCC::AL)
1869       .addReg(0));
1870 
1871     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1872       .addReg(ARM::R7)
1873       .addReg(SrcReg)
1874       .addImm(0)
1875       // Predicate.
1876       .addImm(ARMCC::AL)
1877       .addReg(0));
1878 
1879     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
1880       .addReg(ScratchReg)
1881       // Predicate.
1882       .addImm(ARMCC::AL)
1883       .addReg(0));
1884     return;
1885   }
1886   case ARM::tInt_eh_sjlj_longjmp:
1887   case ARM::tInt_WIN_eh_sjlj_longjmp: {
1888     // ldr $scratch, [$src, #8]
1889     // mov sp, $scratch
1890     // ldr $scratch, [$src, #4]
1891     // ldr r7, [$src]
1892     // bx $scratch
1893     unsigned SrcReg = MI->getOperand(0).getReg();
1894     unsigned ScratchReg = MI->getOperand(1).getReg();
1895 
1896     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
1897       .addReg(ScratchReg)
1898       .addReg(SrcReg)
1899       // The offset immediate is #8. The operand value is scaled by 4 for the
1900       // tLDR instruction.
1901       .addImm(2)
1902       // Predicate.
1903       .addImm(ARMCC::AL)
1904       .addReg(0));
1905 
1906     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1907       .addReg(ARM::SP)
1908       .addReg(ScratchReg)
1909       // Predicate.
1910       .addImm(ARMCC::AL)
1911       .addReg(0));
1912 
1913     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
1914       .addReg(ScratchReg)
1915       .addReg(SrcReg)
1916       .addImm(1)
1917       // Predicate.
1918       .addImm(ARMCC::AL)
1919       .addReg(0));
1920 
1921     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
1922       .addReg(Opc == ARM::tInt_WIN_eh_sjlj_longjmp ? ARM::R11 : ARM::R7)
1923       .addReg(SrcReg)
1924       .addImm(0)
1925       // Predicate.
1926       .addImm(ARMCC::AL)
1927       .addReg(0));
1928 
1929     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBX)
1930       .addReg(ScratchReg)
1931       // Predicate.
1932       .addImm(ARMCC::AL)
1933       .addReg(0));
1934     return;
1935   }
1936   }
1937 
1938   MCInst TmpInst;
1939   LowerARMMachineInstrToMCInst(MI, TmpInst, *this);
1940 
1941   EmitToStreamer(*OutStreamer, TmpInst);
1942 }
1943 
1944 //===----------------------------------------------------------------------===//
1945 // Target Registry Stuff
1946 //===----------------------------------------------------------------------===//
1947 
1948 // Force static initialization.
1949 extern "C" void LLVMInitializeARMAsmPrinter() {
1950   RegisterAsmPrinter<ARMAsmPrinter> X(TheARMLETarget);
1951   RegisterAsmPrinter<ARMAsmPrinter> Y(TheARMBETarget);
1952   RegisterAsmPrinter<ARMAsmPrinter> A(TheThumbLETarget);
1953   RegisterAsmPrinter<ARMAsmPrinter> B(TheThumbBETarget);
1954 }
1955