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