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