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