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