0ef72928926e07a4a6432f73bc67a71e17f2fa40
[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   if (!M.getModuleInlineAsm().empty() && Subtarget->isThumb())
483     OutStreamer.EmitAssemblerFlag(MCAF_Code16);
484 }
485
486 static void
487 emitNonLazySymbolPointer(MCStreamer &OutStreamer, MCSymbol *StubLabel,
488                          MachineModuleInfoImpl::StubValueTy &MCSym) {
489   // L_foo$stub:
490   OutStreamer.EmitLabel(StubLabel);
491   //   .indirect_symbol _foo
492   OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
493
494   if (MCSym.getInt())
495     // External to current translation unit.
496     OutStreamer.EmitIntValue(0, 4/*size*/);
497   else
498     // Internal to current translation unit.
499     //
500     // When we place the LSDA into the TEXT section, the type info
501     // pointers need to be indirect and pc-rel. We accomplish this by
502     // using NLPs; however, sometimes the types are local to the file.
503     // We need to fill in the value for the NLP in those cases.
504     OutStreamer.EmitValue(
505         MCSymbolRefExpr::Create(MCSym.getPointer(), OutStreamer.getContext()),
506         4 /*size*/);
507 }
508
509
510 void ARMAsmPrinter::EmitEndOfAsmFile(Module &M) {
511   if (Subtarget->isTargetMachO()) {
512     // All darwin targets use mach-o.
513     const TargetLoweringObjectFileMachO &TLOFMacho =
514       static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
515     MachineModuleInfoMachO &MMIMacho =
516       MMI->getObjFileInfo<MachineModuleInfoMachO>();
517
518     // Output non-lazy-pointers for external and common global variables.
519     MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetGVStubList();
520
521     if (!Stubs.empty()) {
522       // Switch with ".non_lazy_symbol_pointer" directive.
523       OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
524       EmitAlignment(2);
525
526       for (auto &Stub : Stubs)
527         emitNonLazySymbolPointer(OutStreamer, Stub.first, Stub.second);
528
529       Stubs.clear();
530       OutStreamer.AddBlankLine();
531     }
532
533     Stubs = MMIMacho.GetHiddenGVStubList();
534     if (!Stubs.empty()) {
535       OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
536       EmitAlignment(2);
537
538       for (auto &Stub : Stubs)
539         emitNonLazySymbolPointer(OutStreamer, Stub.first, Stub.second);
540
541       Stubs.clear();
542       OutStreamer.AddBlankLine();
543     }
544
545     // Funny Darwin hack: This flag tells the linker that no global symbols
546     // contain code that falls through to other global symbols (e.g. the obvious
547     // implementation of multiple entry points).  If this doesn't occur, the
548     // linker can safely perform dead code stripping.  Since LLVM never
549     // generates code that does this, it is always safe to set.
550     OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
551   }
552
553   // Emit a .data.rel section containing any stubs that were created.
554   if (Subtarget->isTargetELF()) {
555     const TargetLoweringObjectFileELF &TLOFELF =
556       static_cast<const TargetLoweringObjectFileELF &>(getObjFileLowering());
557
558     MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
559
560     // Output stubs for external and common global variables.
561     MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
562     if (!Stubs.empty()) {
563       OutStreamer.SwitchSection(TLOFELF.getDataRelSection());
564       const DataLayout *TD = TM.getDataLayout();
565
566       for (auto &stub: Stubs) {
567         OutStreamer.EmitLabel(stub.first);
568         OutStreamer.EmitSymbolValue(stub.second.getPointer(),
569                                     TD->getPointerSize(0));
570       }
571       Stubs.clear();
572     }
573   }
574 }
575
576 //===----------------------------------------------------------------------===//
577 // Helper routines for EmitStartOfAsmFile() and EmitEndOfAsmFile()
578 // FIXME:
579 // The following seem like one-off assembler flags, but they actually need
580 // to appear in the .ARM.attributes section in ELF.
581 // Instead of subclassing the MCELFStreamer, we do the work here.
582
583 static ARMBuildAttrs::CPUArch getArchForCPU(StringRef CPU,
584                                             const ARMSubtarget *Subtarget) {
585   if (CPU == "xscale")
586     return ARMBuildAttrs::v5TEJ;
587
588   if (Subtarget->hasV8Ops())
589     return ARMBuildAttrs::v8;
590   else if (Subtarget->hasV7Ops()) {
591     if (Subtarget->isMClass() && Subtarget->hasThumb2DSP())
592       return ARMBuildAttrs::v7E_M;
593     return ARMBuildAttrs::v7;
594   } else if (Subtarget->hasV6T2Ops())
595     return ARMBuildAttrs::v6T2;
596   else if (Subtarget->hasV6MOps())
597     return ARMBuildAttrs::v6S_M;
598   else if (Subtarget->hasV6Ops())
599     return ARMBuildAttrs::v6;
600   else if (Subtarget->hasV5TEOps())
601     return ARMBuildAttrs::v5TE;
602   else if (Subtarget->hasV5TOps())
603     return ARMBuildAttrs::v5T;
604   else if (Subtarget->hasV4TOps())
605     return ARMBuildAttrs::v4T;
606   else
607     return ARMBuildAttrs::v4;
608 }
609
610 void ARMAsmPrinter::emitAttributes() {
611   MCTargetStreamer &TS = *OutStreamer.getTargetStreamer();
612   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
613
614   ATS.switchVendor("aeabi");
615
616   std::string CPUString = Subtarget->getCPUString();
617
618   // FIXME: remove krait check when GNU tools support krait cpu
619   if (CPUString != "generic" && CPUString != "krait")
620     ATS.emitTextAttribute(ARMBuildAttrs::CPU_name, CPUString);
621
622   ATS.emitAttribute(ARMBuildAttrs::CPU_arch,
623                     getArchForCPU(CPUString, Subtarget));
624
625   // Tag_CPU_arch_profile must have the default value of 0 when "Architecture
626   // profile is not applicable (e.g. pre v7, or cross-profile code)".
627   if (Subtarget->hasV7Ops()) {
628     if (Subtarget->isAClass()) {
629       ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
630                         ARMBuildAttrs::ApplicationProfile);
631     } else if (Subtarget->isRClass()) {
632       ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
633                         ARMBuildAttrs::RealTimeProfile);
634     } else if (Subtarget->isMClass()) {
635       ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
636                         ARMBuildAttrs::MicroControllerProfile);
637     }
638   }
639
640   ATS.emitAttribute(ARMBuildAttrs::ARM_ISA_use, Subtarget->hasARMOps() ?
641                       ARMBuildAttrs::Allowed : ARMBuildAttrs::Not_Allowed);
642   if (Subtarget->isThumb1Only()) {
643     ATS.emitAttribute(ARMBuildAttrs::THUMB_ISA_use,
644                       ARMBuildAttrs::Allowed);
645   } else if (Subtarget->hasThumb2()) {
646     ATS.emitAttribute(ARMBuildAttrs::THUMB_ISA_use,
647                       ARMBuildAttrs::AllowThumb32);
648   }
649
650   if (Subtarget->hasNEON()) {
651     /* NEON is not exactly a VFP architecture, but GAS emit one of
652      * neon/neon-fp-armv8/neon-vfpv4/vfpv3/vfpv2 for .fpu parameters */
653     if (Subtarget->hasFPARMv8()) {
654       if (Subtarget->hasCrypto())
655         ATS.emitFPU(ARM::CRYPTO_NEON_FP_ARMV8);
656       else
657         ATS.emitFPU(ARM::NEON_FP_ARMV8);
658     }
659     else if (Subtarget->hasVFP4())
660       ATS.emitFPU(ARM::NEON_VFPV4);
661     else
662       ATS.emitFPU(ARM::NEON);
663     // Emit Tag_Advanced_SIMD_arch for ARMv8 architecture
664     if (Subtarget->hasV8Ops())
665       ATS.emitAttribute(ARMBuildAttrs::Advanced_SIMD_arch,
666                         ARMBuildAttrs::AllowNeonARMv8);
667   } else {
668     if (Subtarget->hasFPARMv8())
669       ATS.emitFPU(ARM::FP_ARMV8);
670     else if (Subtarget->hasVFP4())
671       ATS.emitFPU(Subtarget->hasD16() ? ARM::VFPV4_D16 : ARM::VFPV4);
672     else if (Subtarget->hasVFP3())
673       ATS.emitFPU(Subtarget->hasD16() ? ARM::VFPV3_D16 : ARM::VFPV3);
674     else if (Subtarget->hasVFP2())
675       ATS.emitFPU(ARM::VFPV2);
676   }
677
678   if (TM.getRelocationModel() == Reloc::PIC_) {
679     // PIC specific attributes.
680     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RW_data,
681                       ARMBuildAttrs::AddressRWPCRel);
682     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RO_data,
683                       ARMBuildAttrs::AddressROPCRel);
684     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
685                       ARMBuildAttrs::AddressGOT);
686   } else {
687     // Allow direct addressing of imported data for all other relocation models.
688     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
689                       ARMBuildAttrs::AddressDirect);
690   }
691
692   // Signal various FP modes.
693   if (!TM.Options.UnsafeFPMath) {
694     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal, ARMBuildAttrs::Allowed);
695     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_exceptions,
696                       ARMBuildAttrs::Allowed);
697   }
698
699   if (TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath)
700     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
701                       ARMBuildAttrs::Allowed);
702   else
703     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
704                       ARMBuildAttrs::AllowIEE754);
705
706   // FIXME: add more flags to ARMBuildAttributes.h
707   // 8-bytes alignment stuff.
708   ATS.emitAttribute(ARMBuildAttrs::ABI_align_needed, 1);
709   ATS.emitAttribute(ARMBuildAttrs::ABI_align_preserved, 1);
710
711   // ABI_HardFP_use attribute to indicate single precision FP.
712   if (Subtarget->isFPOnlySP())
713     ATS.emitAttribute(ARMBuildAttrs::ABI_HardFP_use,
714                       ARMBuildAttrs::HardFPSinglePrecision);
715
716   // Hard float.  Use both S and D registers and conform to AAPCS-VFP.
717   if (Subtarget->isAAPCS_ABI() && TM.Options.FloatABIType == FloatABI::Hard)
718     ATS.emitAttribute(ARMBuildAttrs::ABI_VFP_args, ARMBuildAttrs::HardFPAAPCS);
719
720   // FIXME: Should we signal R9 usage?
721
722   if (Subtarget->hasFP16())
723       ATS.emitAttribute(ARMBuildAttrs::FP_HP_extension, ARMBuildAttrs::AllowHPFP);
724
725   if (Subtarget->hasMPExtension())
726       ATS.emitAttribute(ARMBuildAttrs::MPextension_use, ARMBuildAttrs::AllowMP);
727
728   // Hardware divide in ARM mode is part of base arch, starting from ARMv8.
729   // If only Thumb hwdiv is present, it must also be in base arch (ARMv7-R/M).
730   // It is not possible to produce DisallowDIV: if hwdiv is present in the base
731   // arch, supplying -hwdiv downgrades the effective arch, via ClearImpliedBits.
732   // AllowDIVExt is only emitted if hwdiv isn't available in the base arch;
733   // otherwise, the default value (AllowDIVIfExists) applies.
734   if (Subtarget->hasDivideInARMMode() && !Subtarget->hasV8Ops())
735       ATS.emitAttribute(ARMBuildAttrs::DIV_use, ARMBuildAttrs::AllowDIVExt);
736
737   if (MMI) {
738     if (const Module *SourceModule = MMI->getModule()) {
739       // ABI_PCS_wchar_t to indicate wchar_t width
740       // FIXME: There is no way to emit value 0 (wchar_t prohibited).
741       if (auto WCharWidthValue = cast_or_null<ConstantInt>(
742               SourceModule->getModuleFlag("wchar_size"))) {
743         int WCharWidth = WCharWidthValue->getZExtValue();
744         assert((WCharWidth == 2 || WCharWidth == 4) &&
745                "wchar_t width must be 2 or 4 bytes");
746         ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_wchar_t, WCharWidth);
747       }
748
749       // ABI_enum_size to indicate enum width
750       // FIXME: There is no way to emit value 0 (enums prohibited) or value 3
751       //        (all enums contain a value needing 32 bits to encode).
752       if (auto EnumWidthValue = cast_or_null<ConstantInt>(
753               SourceModule->getModuleFlag("min_enum_size"))) {
754         int EnumWidth = EnumWidthValue->getZExtValue();
755         assert((EnumWidth == 1 || EnumWidth == 4) &&
756                "Minimum enum width must be 1 or 4 bytes");
757         int EnumBuildAttr = EnumWidth == 1 ? 1 : 2;
758         ATS.emitAttribute(ARMBuildAttrs::ABI_enum_size, EnumBuildAttr);
759       }
760     }
761   }
762
763   // TODO: We currently only support either reserving the register, or treating
764   // it as another callee-saved register, but not as SB or a TLS pointer; It
765   // would instead be nicer to push this from the frontend as metadata, as we do
766   // for the wchar and enum size tags
767   if (Subtarget->isR9Reserved())
768       ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
769                         ARMBuildAttrs::R9Reserved);
770   else
771       ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
772                         ARMBuildAttrs::R9IsGPR);
773
774   if (Subtarget->hasTrustZone() && Subtarget->hasVirtualization())
775       ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
776                         ARMBuildAttrs::AllowTZVirtualization);
777   else if (Subtarget->hasTrustZone())
778       ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
779                         ARMBuildAttrs::AllowTZ);
780   else if (Subtarget->hasVirtualization())
781       ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
782                         ARMBuildAttrs::AllowVirtualization);
783
784   ATS.finishAttributeSection();
785 }
786
787 //===----------------------------------------------------------------------===//
788
789 static MCSymbol *getPICLabel(const char *Prefix, unsigned FunctionNumber,
790                              unsigned LabelId, MCContext &Ctx) {
791
792   MCSymbol *Label = Ctx.GetOrCreateSymbol(Twine(Prefix)
793                        + "PC" + Twine(FunctionNumber) + "_" + Twine(LabelId));
794   return Label;
795 }
796
797 static MCSymbolRefExpr::VariantKind
798 getModifierVariantKind(ARMCP::ARMCPModifier Modifier) {
799   switch (Modifier) {
800   case ARMCP::no_modifier: return MCSymbolRefExpr::VK_None;
801   case ARMCP::TLSGD:       return MCSymbolRefExpr::VK_TLSGD;
802   case ARMCP::TPOFF:       return MCSymbolRefExpr::VK_TPOFF;
803   case ARMCP::GOTTPOFF:    return MCSymbolRefExpr::VK_GOTTPOFF;
804   case ARMCP::GOT:         return MCSymbolRefExpr::VK_GOT;
805   case ARMCP::GOTOFF:      return MCSymbolRefExpr::VK_GOTOFF;
806   }
807   llvm_unreachable("Invalid ARMCPModifier!");
808 }
809
810 MCSymbol *ARMAsmPrinter::GetARMGVSymbol(const GlobalValue *GV,
811                                         unsigned char TargetFlags) {
812   if (Subtarget->isTargetMachO()) {
813     bool IsIndirect = (TargetFlags & ARMII::MO_NONLAZY) &&
814       Subtarget->GVIsIndirectSymbol(GV, TM.getRelocationModel());
815
816     if (!IsIndirect)
817       return getSymbol(GV);
818
819     // FIXME: Remove this when Darwin transition to @GOT like syntax.
820     MCSymbol *MCSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
821     MachineModuleInfoMachO &MMIMachO =
822       MMI->getObjFileInfo<MachineModuleInfoMachO>();
823     MachineModuleInfoImpl::StubValueTy &StubSym =
824       GV->hasHiddenVisibility() ? MMIMachO.getHiddenGVStubEntry(MCSym)
825                                 : MMIMachO.getGVStubEntry(MCSym);
826     if (!StubSym.getPointer())
827       StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV),
828                                                    !GV->hasInternalLinkage());
829     return MCSym;
830   } else if (Subtarget->isTargetCOFF()) {
831     assert(Subtarget->isTargetWindows() &&
832            "Windows is the only supported COFF target");
833
834     bool IsIndirect = (TargetFlags & ARMII::MO_DLLIMPORT);
835     if (!IsIndirect)
836       return getSymbol(GV);
837
838     SmallString<128> Name;
839     Name = "__imp_";
840     getNameWithPrefix(Name, GV);
841
842     return OutContext.GetOrCreateSymbol(Name);
843   } else if (Subtarget->isTargetELF()) {
844     return getSymbol(GV);
845   }
846   llvm_unreachable("unexpected target");
847 }
848
849 void ARMAsmPrinter::
850 EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
851   const DataLayout *DL = TM.getDataLayout();
852   int Size = TM.getDataLayout()->getTypeAllocSize(MCPV->getType());
853
854   ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
855
856   MCSymbol *MCSym;
857   if (ACPV->isLSDA()) {
858     SmallString<128> Str;
859     raw_svector_ostream OS(Str);
860     OS << DL->getPrivateGlobalPrefix() << "_LSDA_" << getFunctionNumber();
861     MCSym = OutContext.GetOrCreateSymbol(OS.str());
862   } else if (ACPV->isBlockAddress()) {
863     const BlockAddress *BA =
864       cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress();
865     MCSym = GetBlockAddressSymbol(BA);
866   } else if (ACPV->isGlobalValue()) {
867     const GlobalValue *GV = cast<ARMConstantPoolConstant>(ACPV)->getGV();
868
869     // On Darwin, const-pool entries may get the "FOO$non_lazy_ptr" mangling, so
870     // flag the global as MO_NONLAZY.
871     unsigned char TF = Subtarget->isTargetMachO() ? ARMII::MO_NONLAZY : 0;
872     MCSym = GetARMGVSymbol(GV, TF);
873   } else if (ACPV->isMachineBasicBlock()) {
874     const MachineBasicBlock *MBB = cast<ARMConstantPoolMBB>(ACPV)->getMBB();
875     MCSym = MBB->getSymbol();
876   } else {
877     assert(ACPV->isExtSymbol() && "unrecognized constant pool value");
878     const char *Sym = cast<ARMConstantPoolSymbol>(ACPV)->getSymbol();
879     MCSym = GetExternalSymbolSymbol(Sym);
880   }
881
882   // Create an MCSymbol for the reference.
883   const MCExpr *Expr =
884     MCSymbolRefExpr::Create(MCSym, getModifierVariantKind(ACPV->getModifier()),
885                             OutContext);
886
887   if (ACPV->getPCAdjustment()) {
888     MCSymbol *PCLabel = getPICLabel(DL->getPrivateGlobalPrefix(),
889                                     getFunctionNumber(),
890                                     ACPV->getLabelId(),
891                                     OutContext);
892     const MCExpr *PCRelExpr = MCSymbolRefExpr::Create(PCLabel, OutContext);
893     PCRelExpr =
894       MCBinaryExpr::CreateAdd(PCRelExpr,
895                               MCConstantExpr::Create(ACPV->getPCAdjustment(),
896                                                      OutContext),
897                               OutContext);
898     if (ACPV->mustAddCurrentAddress()) {
899       // We want "(<expr> - .)", but MC doesn't have a concept of the '.'
900       // label, so just emit a local label end reference that instead.
901       MCSymbol *DotSym = OutContext.CreateTempSymbol();
902       OutStreamer.EmitLabel(DotSym);
903       const MCExpr *DotExpr = MCSymbolRefExpr::Create(DotSym, OutContext);
904       PCRelExpr = MCBinaryExpr::CreateSub(PCRelExpr, DotExpr, OutContext);
905     }
906     Expr = MCBinaryExpr::CreateSub(Expr, PCRelExpr, OutContext);
907   }
908   OutStreamer.EmitValue(Expr, Size);
909 }
910
911 void ARMAsmPrinter::EmitJumpTable(const MachineInstr *MI) {
912   unsigned Opcode = MI->getOpcode();
913   int OpNum = 1;
914   if (Opcode == ARM::BR_JTadd)
915     OpNum = 2;
916   else if (Opcode == ARM::BR_JTm)
917     OpNum = 3;
918
919   const MachineOperand &MO1 = MI->getOperand(OpNum);
920   const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
921   unsigned JTI = MO1.getIndex();
922
923   // Emit a label for the jump table.
924   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel2(JTI, MO2.getImm());
925   OutStreamer.EmitLabel(JTISymbol);
926
927   // Mark the jump table as data-in-code.
928   OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
929
930   // Emit each entry of the table.
931   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
932   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
933   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
934
935   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
936     MachineBasicBlock *MBB = JTBBs[i];
937     // Construct an MCExpr for the entry. We want a value of the form:
938     // (BasicBlockAddr - TableBeginAddr)
939     //
940     // For example, a table with entries jumping to basic blocks BB0 and BB1
941     // would look like:
942     // LJTI_0_0:
943     //    .word (LBB0 - LJTI_0_0)
944     //    .word (LBB1 - LJTI_0_0)
945     const MCExpr *Expr = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
946
947     if (TM.getRelocationModel() == Reloc::PIC_)
948       Expr = MCBinaryExpr::CreateSub(Expr, MCSymbolRefExpr::Create(JTISymbol,
949                                                                    OutContext),
950                                      OutContext);
951     // If we're generating a table of Thumb addresses in static relocation
952     // model, we need to add one to keep interworking correctly.
953     else if (AFI->isThumbFunction())
954       Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(1,OutContext),
955                                      OutContext);
956     OutStreamer.EmitValue(Expr, 4);
957   }
958   // Mark the end of jump table data-in-code region.
959   OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
960 }
961
962 void ARMAsmPrinter::EmitJump2Table(const MachineInstr *MI) {
963   unsigned Opcode = MI->getOpcode();
964   int OpNum = (Opcode == ARM::t2BR_JT) ? 2 : 1;
965   const MachineOperand &MO1 = MI->getOperand(OpNum);
966   const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
967   unsigned JTI = MO1.getIndex();
968
969   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel2(JTI, MO2.getImm());
970   OutStreamer.EmitLabel(JTISymbol);
971
972   // Emit each entry of the table.
973   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
974   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
975   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
976   unsigned OffsetWidth = 4;
977   if (MI->getOpcode() == ARM::t2TBB_JT) {
978     OffsetWidth = 1;
979     // Mark the jump table as data-in-code.
980     OutStreamer.EmitDataRegion(MCDR_DataRegionJT8);
981   } else if (MI->getOpcode() == ARM::t2TBH_JT) {
982     OffsetWidth = 2;
983     // Mark the jump table as data-in-code.
984     OutStreamer.EmitDataRegion(MCDR_DataRegionJT16);
985   }
986
987   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
988     MachineBasicBlock *MBB = JTBBs[i];
989     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::Create(MBB->getSymbol(),
990                                                           OutContext);
991     // If this isn't a TBB or TBH, the entries are direct branch instructions.
992     if (OffsetWidth == 4) {
993       EmitToStreamer(OutStreamer, MCInstBuilder(ARM::t2B)
994         .addExpr(MBBSymbolExpr)
995         .addImm(ARMCC::AL)
996         .addReg(0));
997       continue;
998     }
999     // Otherwise it's an offset from the dispatch instruction. Construct an
1000     // MCExpr for the entry. We want a value of the form:
1001     // (BasicBlockAddr - TableBeginAddr) / 2
1002     //
1003     // For example, a TBB table with entries jumping to basic blocks BB0 and BB1
1004     // would look like:
1005     // LJTI_0_0:
1006     //    .byte (LBB0 - LJTI_0_0) / 2
1007     //    .byte (LBB1 - LJTI_0_0) / 2
1008     const MCExpr *Expr =
1009       MCBinaryExpr::CreateSub(MBBSymbolExpr,
1010                               MCSymbolRefExpr::Create(JTISymbol, OutContext),
1011                               OutContext);
1012     Expr = MCBinaryExpr::CreateDiv(Expr, MCConstantExpr::Create(2, OutContext),
1013                                    OutContext);
1014     OutStreamer.EmitValue(Expr, OffsetWidth);
1015   }
1016   // Mark the end of jump table data-in-code region. 32-bit offsets use
1017   // actual branch instructions here, so we don't mark those as a data-region
1018   // at all.
1019   if (OffsetWidth != 4)
1020     OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1021 }
1022
1023 void ARMAsmPrinter::EmitUnwindingInstruction(const MachineInstr *MI) {
1024   assert(MI->getFlag(MachineInstr::FrameSetup) &&
1025       "Only instruction which are involved into frame setup code are allowed");
1026
1027   MCTargetStreamer &TS = *OutStreamer.getTargetStreamer();
1028   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1029   const MachineFunction &MF = *MI->getParent()->getParent();
1030   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
1031   const ARMFunctionInfo &AFI = *MF.getInfo<ARMFunctionInfo>();
1032
1033   unsigned FramePtr = RegInfo->getFrameRegister(MF);
1034   unsigned Opc = MI->getOpcode();
1035   unsigned SrcReg, DstReg;
1036
1037   if (Opc == ARM::tPUSH || Opc == ARM::tLDRpci) {
1038     // Two special cases:
1039     // 1) tPUSH does not have src/dst regs.
1040     // 2) for Thumb1 code we sometimes materialize the constant via constpool
1041     // load. Yes, this is pretty fragile, but for now I don't see better
1042     // way... :(
1043     SrcReg = DstReg = ARM::SP;
1044   } else {
1045     SrcReg = MI->getOperand(1).getReg();
1046     DstReg = MI->getOperand(0).getReg();
1047   }
1048
1049   // Try to figure out the unwinding opcode out of src / dst regs.
1050   if (MI->mayStore()) {
1051     // Register saves.
1052     assert(DstReg == ARM::SP &&
1053            "Only stack pointer as a destination reg is supported");
1054
1055     SmallVector<unsigned, 4> RegList;
1056     // Skip src & dst reg, and pred ops.
1057     unsigned StartOp = 2 + 2;
1058     // Use all the operands.
1059     unsigned NumOffset = 0;
1060
1061     switch (Opc) {
1062     default:
1063       MI->dump();
1064       llvm_unreachable("Unsupported opcode for unwinding information");
1065     case ARM::tPUSH:
1066       // Special case here: no src & dst reg, but two extra imp ops.
1067       StartOp = 2; NumOffset = 2;
1068     case ARM::STMDB_UPD:
1069     case ARM::t2STMDB_UPD:
1070     case ARM::VSTMDDB_UPD:
1071       assert(SrcReg == ARM::SP &&
1072              "Only stack pointer as a source reg is supported");
1073       for (unsigned i = StartOp, NumOps = MI->getNumOperands() - NumOffset;
1074            i != NumOps; ++i) {
1075         const MachineOperand &MO = MI->getOperand(i);
1076         // Actually, there should never be any impdef stuff here. Skip it
1077         // temporary to workaround PR11902.
1078         if (MO.isImplicit())
1079           continue;
1080         RegList.push_back(MO.getReg());
1081       }
1082       break;
1083     case ARM::STR_PRE_IMM:
1084     case ARM::STR_PRE_REG:
1085     case ARM::t2STR_PRE:
1086       assert(MI->getOperand(2).getReg() == ARM::SP &&
1087              "Only stack pointer as a source reg is supported");
1088       RegList.push_back(SrcReg);
1089       break;
1090     }
1091     if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM)
1092       ATS.emitRegSave(RegList, Opc == ARM::VSTMDDB_UPD);
1093   } else {
1094     // Changes of stack / frame pointer.
1095     if (SrcReg == ARM::SP) {
1096       int64_t Offset = 0;
1097       switch (Opc) {
1098       default:
1099         MI->dump();
1100         llvm_unreachable("Unsupported opcode for unwinding information");
1101       case ARM::MOVr:
1102       case ARM::tMOVr:
1103         Offset = 0;
1104         break;
1105       case ARM::ADDri:
1106         Offset = -MI->getOperand(2).getImm();
1107         break;
1108       case ARM::SUBri:
1109       case ARM::t2SUBri:
1110         Offset = MI->getOperand(2).getImm();
1111         break;
1112       case ARM::tSUBspi:
1113         Offset = MI->getOperand(2).getImm()*4;
1114         break;
1115       case ARM::tADDspi:
1116       case ARM::tADDrSPi:
1117         Offset = -MI->getOperand(2).getImm()*4;
1118         break;
1119       case ARM::tLDRpci: {
1120         // Grab the constpool index and check, whether it corresponds to
1121         // original or cloned constpool entry.
1122         unsigned CPI = MI->getOperand(1).getIndex();
1123         const MachineConstantPool *MCP = MF.getConstantPool();
1124         if (CPI >= MCP->getConstants().size())
1125           CPI = AFI.getOriginalCPIdx(CPI);
1126         assert(CPI != -1U && "Invalid constpool index");
1127
1128         // Derive the actual offset.
1129         const MachineConstantPoolEntry &CPE = MCP->getConstants()[CPI];
1130         assert(!CPE.isMachineConstantPoolEntry() && "Invalid constpool entry");
1131         // FIXME: Check for user, it should be "add" instruction!
1132         Offset = -cast<ConstantInt>(CPE.Val.ConstVal)->getSExtValue();
1133         break;
1134       }
1135       }
1136
1137       if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM) {
1138         if (DstReg == FramePtr && FramePtr != ARM::SP)
1139           // Set-up of the frame pointer. Positive values correspond to "add"
1140           // instruction.
1141           ATS.emitSetFP(FramePtr, ARM::SP, -Offset);
1142         else if (DstReg == ARM::SP) {
1143           // Change of SP by an offset. Positive values correspond to "sub"
1144           // instruction.
1145           ATS.emitPad(Offset);
1146         } else {
1147           // Move of SP to a register.  Positive values correspond to an "add"
1148           // instruction.
1149           ATS.emitMovSP(DstReg, -Offset);
1150         }
1151       }
1152     } else if (DstReg == ARM::SP) {
1153       MI->dump();
1154       llvm_unreachable("Unsupported opcode for unwinding information");
1155     }
1156     else {
1157       MI->dump();
1158       llvm_unreachable("Unsupported opcode for unwinding information");
1159     }
1160   }
1161 }
1162
1163 // Simple pseudo-instructions have their lowering (with expansion to real
1164 // instructions) auto-generated.
1165 #include "ARMGenMCPseudoLowering.inc"
1166
1167 void ARMAsmPrinter::EmitInstruction(const MachineInstr *MI) {
1168   const DataLayout *DL = TM.getDataLayout();
1169
1170   // If we just ended a constant pool, mark it as such.
1171   if (InConstantPool && MI->getOpcode() != ARM::CONSTPOOL_ENTRY) {
1172     OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1173     InConstantPool = false;
1174   }
1175
1176   // Emit unwinding stuff for frame-related instructions
1177   if (Subtarget->isTargetEHABICompatible() &&
1178        MI->getFlag(MachineInstr::FrameSetup))
1179     EmitUnwindingInstruction(MI);
1180
1181   // Do any auto-generated pseudo lowerings.
1182   if (emitPseudoExpansionLowering(OutStreamer, MI))
1183     return;
1184
1185   assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
1186          "Pseudo flag setting opcode should be expanded early");
1187
1188   // Check for manual lowerings.
1189   unsigned Opc = MI->getOpcode();
1190   switch (Opc) {
1191   case ARM::t2MOVi32imm: llvm_unreachable("Should be lowered by thumb2it pass");
1192   case ARM::DBG_VALUE: llvm_unreachable("Should be handled by generic printing");
1193   case ARM::LEApcrel:
1194   case ARM::tLEApcrel:
1195   case ARM::t2LEApcrel: {
1196     // FIXME: Need to also handle globals and externals
1197     MCSymbol *CPISymbol = GetCPISymbol(MI->getOperand(1).getIndex());
1198     EmitToStreamer(OutStreamer, MCInstBuilder(MI->getOpcode() ==
1199                                               ARM::t2LEApcrel ? ARM::t2ADR
1200                   : (MI->getOpcode() == ARM::tLEApcrel ? ARM::tADR
1201                      : ARM::ADR))
1202       .addReg(MI->getOperand(0).getReg())
1203       .addExpr(MCSymbolRefExpr::Create(CPISymbol, OutContext))
1204       // Add predicate operands.
1205       .addImm(MI->getOperand(2).getImm())
1206       .addReg(MI->getOperand(3).getReg()));
1207     return;
1208   }
1209   case ARM::LEApcrelJT:
1210   case ARM::tLEApcrelJT:
1211   case ARM::t2LEApcrelJT: {
1212     MCSymbol *JTIPICSymbol =
1213       GetARMJTIPICJumpTableLabel2(MI->getOperand(1).getIndex(),
1214                                   MI->getOperand(2).getImm());
1215     EmitToStreamer(OutStreamer, MCInstBuilder(MI->getOpcode() ==
1216                                               ARM::t2LEApcrelJT ? ARM::t2ADR
1217                   : (MI->getOpcode() == ARM::tLEApcrelJT ? ARM::tADR
1218                      : ARM::ADR))
1219       .addReg(MI->getOperand(0).getReg())
1220       .addExpr(MCSymbolRefExpr::Create(JTIPICSymbol, OutContext))
1221       // Add predicate operands.
1222       .addImm(MI->getOperand(3).getImm())
1223       .addReg(MI->getOperand(4).getReg()));
1224     return;
1225   }
1226   // Darwin call instructions are just normal call instructions with different
1227   // clobber semantics (they clobber R9).
1228   case ARM::BX_CALL: {
1229     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVr)
1230       .addReg(ARM::LR)
1231       .addReg(ARM::PC)
1232       // Add predicate operands.
1233       .addImm(ARMCC::AL)
1234       .addReg(0)
1235       // Add 's' bit operand (always reg0 for this)
1236       .addReg(0));
1237
1238     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::BX)
1239       .addReg(MI->getOperand(0).getReg()));
1240     return;
1241   }
1242   case ARM::tBX_CALL: {
1243     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVr)
1244       .addReg(ARM::LR)
1245       .addReg(ARM::PC)
1246       // Add predicate operands.
1247       .addImm(ARMCC::AL)
1248       .addReg(0));
1249
1250     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tBX)
1251       .addReg(MI->getOperand(0).getReg())
1252       // Add predicate operands.
1253       .addImm(ARMCC::AL)
1254       .addReg(0));
1255     return;
1256   }
1257   case ARM::BMOVPCRX_CALL: {
1258     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVr)
1259       .addReg(ARM::LR)
1260       .addReg(ARM::PC)
1261       // Add predicate operands.
1262       .addImm(ARMCC::AL)
1263       .addReg(0)
1264       // Add 's' bit operand (always reg0 for this)
1265       .addReg(0));
1266
1267     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVr)
1268       .addReg(ARM::PC)
1269       .addReg(MI->getOperand(0).getReg())
1270       // Add predicate operands.
1271       .addImm(ARMCC::AL)
1272       .addReg(0)
1273       // Add 's' bit operand (always reg0 for this)
1274       .addReg(0));
1275     return;
1276   }
1277   case ARM::BMOVPCB_CALL: {
1278     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVr)
1279       .addReg(ARM::LR)
1280       .addReg(ARM::PC)
1281       // Add predicate operands.
1282       .addImm(ARMCC::AL)
1283       .addReg(0)
1284       // Add 's' bit operand (always reg0 for this)
1285       .addReg(0));
1286
1287     const MachineOperand &Op = MI->getOperand(0);
1288     const GlobalValue *GV = Op.getGlobal();
1289     const unsigned TF = Op.getTargetFlags();
1290     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1291     const MCExpr *GVSymExpr = MCSymbolRefExpr::Create(GVSym, OutContext);
1292     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::Bcc)
1293       .addExpr(GVSymExpr)
1294       // Add predicate operands.
1295       .addImm(ARMCC::AL)
1296       .addReg(0));
1297     return;
1298   }
1299   case ARM::MOVi16_ga_pcrel:
1300   case ARM::t2MOVi16_ga_pcrel: {
1301     MCInst TmpInst;
1302     TmpInst.setOpcode(Opc == ARM::MOVi16_ga_pcrel? ARM::MOVi16 : ARM::t2MOVi16);
1303     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1304
1305     unsigned TF = MI->getOperand(1).getTargetFlags();
1306     const GlobalValue *GV = MI->getOperand(1).getGlobal();
1307     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1308     const MCExpr *GVSymExpr = MCSymbolRefExpr::Create(GVSym, OutContext);
1309
1310     MCSymbol *LabelSym = getPICLabel(DL->getPrivateGlobalPrefix(),
1311                                      getFunctionNumber(),
1312                                      MI->getOperand(2).getImm(), OutContext);
1313     const MCExpr *LabelSymExpr= MCSymbolRefExpr::Create(LabelSym, OutContext);
1314     unsigned PCAdj = (Opc == ARM::MOVi16_ga_pcrel) ? 8 : 4;
1315     const MCExpr *PCRelExpr =
1316       ARMMCExpr::CreateLower16(MCBinaryExpr::CreateSub(GVSymExpr,
1317                                       MCBinaryExpr::CreateAdd(LabelSymExpr,
1318                                       MCConstantExpr::Create(PCAdj, OutContext),
1319                                       OutContext), OutContext), OutContext);
1320       TmpInst.addOperand(MCOperand::CreateExpr(PCRelExpr));
1321
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::MOVTi16_ga_pcrel:
1331   case ARM::t2MOVTi16_ga_pcrel: {
1332     MCInst TmpInst;
1333     TmpInst.setOpcode(Opc == ARM::MOVTi16_ga_pcrel
1334                       ? ARM::MOVTi16 : ARM::t2MOVTi16);
1335     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1336     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(1).getReg()));
1337
1338     unsigned TF = MI->getOperand(2).getTargetFlags();
1339     const GlobalValue *GV = MI->getOperand(2).getGlobal();
1340     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1341     const MCExpr *GVSymExpr = MCSymbolRefExpr::Create(GVSym, OutContext);
1342
1343     MCSymbol *LabelSym = getPICLabel(DL->getPrivateGlobalPrefix(),
1344                                      getFunctionNumber(),
1345                                      MI->getOperand(3).getImm(), OutContext);
1346     const MCExpr *LabelSymExpr= MCSymbolRefExpr::Create(LabelSym, OutContext);
1347     unsigned PCAdj = (Opc == ARM::MOVTi16_ga_pcrel) ? 8 : 4;
1348     const MCExpr *PCRelExpr =
1349         ARMMCExpr::CreateUpper16(MCBinaryExpr::CreateSub(GVSymExpr,
1350                                    MCBinaryExpr::CreateAdd(LabelSymExpr,
1351                                       MCConstantExpr::Create(PCAdj, OutContext),
1352                                           OutContext), OutContext), OutContext);
1353       TmpInst.addOperand(MCOperand::CreateExpr(PCRelExpr));
1354     // Add predicate operands.
1355     TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
1356     TmpInst.addOperand(MCOperand::CreateReg(0));
1357     // Add 's' bit operand (always reg0 for this)
1358     TmpInst.addOperand(MCOperand::CreateReg(0));
1359     EmitToStreamer(OutStreamer, TmpInst);
1360     return;
1361   }
1362   case ARM::tPICADD: {
1363     // This is a pseudo op for a label + instruction sequence, which looks like:
1364     // LPC0:
1365     //     add r0, pc
1366     // This adds the address of LPC0 to r0.
1367
1368     // Emit the label.
1369     OutStreamer.EmitLabel(getPICLabel(DL->getPrivateGlobalPrefix(),
1370                           getFunctionNumber(), MI->getOperand(2).getImm(),
1371                           OutContext));
1372
1373     // Form and emit the add.
1374     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tADDhirr)
1375       .addReg(MI->getOperand(0).getReg())
1376       .addReg(MI->getOperand(0).getReg())
1377       .addReg(ARM::PC)
1378       // Add predicate operands.
1379       .addImm(ARMCC::AL)
1380       .addReg(0));
1381     return;
1382   }
1383   case ARM::PICADD: {
1384     // This is a pseudo op for a label + instruction sequence, which looks like:
1385     // LPC0:
1386     //     add r0, pc, r0
1387     // This adds the address of LPC0 to r0.
1388
1389     // Emit the label.
1390     OutStreamer.EmitLabel(getPICLabel(DL->getPrivateGlobalPrefix(),
1391                           getFunctionNumber(), MI->getOperand(2).getImm(),
1392                           OutContext));
1393
1394     // Form and emit the add.
1395     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::ADDrr)
1396       .addReg(MI->getOperand(0).getReg())
1397       .addReg(ARM::PC)
1398       .addReg(MI->getOperand(1).getReg())
1399       // Add predicate operands.
1400       .addImm(MI->getOperand(3).getImm())
1401       .addReg(MI->getOperand(4).getReg())
1402       // Add 's' bit operand (always reg0 for this)
1403       .addReg(0));
1404     return;
1405   }
1406   case ARM::PICSTR:
1407   case ARM::PICSTRB:
1408   case ARM::PICSTRH:
1409   case ARM::PICLDR:
1410   case ARM::PICLDRB:
1411   case ARM::PICLDRH:
1412   case ARM::PICLDRSB:
1413   case ARM::PICLDRSH: {
1414     // This is a pseudo op for a label + instruction sequence, which looks like:
1415     // LPC0:
1416     //     OP r0, [pc, r0]
1417     // The LCP0 label is referenced by a constant pool entry in order to get
1418     // a PC-relative address at the ldr instruction.
1419
1420     // Emit the label.
1421     OutStreamer.EmitLabel(getPICLabel(DL->getPrivateGlobalPrefix(),
1422                           getFunctionNumber(), MI->getOperand(2).getImm(),
1423                           OutContext));
1424
1425     // Form and emit the load
1426     unsigned Opcode;
1427     switch (MI->getOpcode()) {
1428     default:
1429       llvm_unreachable("Unexpected opcode!");
1430     case ARM::PICSTR:   Opcode = ARM::STRrs; break;
1431     case ARM::PICSTRB:  Opcode = ARM::STRBrs; break;
1432     case ARM::PICSTRH:  Opcode = ARM::STRH; break;
1433     case ARM::PICLDR:   Opcode = ARM::LDRrs; break;
1434     case ARM::PICLDRB:  Opcode = ARM::LDRBrs; break;
1435     case ARM::PICLDRH:  Opcode = ARM::LDRH; break;
1436     case ARM::PICLDRSB: Opcode = ARM::LDRSB; break;
1437     case ARM::PICLDRSH: Opcode = ARM::LDRSH; break;
1438     }
1439     EmitToStreamer(OutStreamer, MCInstBuilder(Opcode)
1440       .addReg(MI->getOperand(0).getReg())
1441       .addReg(ARM::PC)
1442       .addReg(MI->getOperand(1).getReg())
1443       .addImm(0)
1444       // Add predicate operands.
1445       .addImm(MI->getOperand(3).getImm())
1446       .addReg(MI->getOperand(4).getReg()));
1447
1448     return;
1449   }
1450   case ARM::CONSTPOOL_ENTRY: {
1451     /// CONSTPOOL_ENTRY - This instruction represents a floating constant pool
1452     /// in the function.  The first operand is the ID# for this instruction, the
1453     /// second is the index into the MachineConstantPool that this is, the third
1454     /// is the size in bytes of this constant pool entry.
1455     /// The required alignment is specified on the basic block holding this MI.
1456     unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
1457     unsigned CPIdx   = (unsigned)MI->getOperand(1).getIndex();
1458
1459     // If this is the first entry of the pool, mark it.
1460     if (!InConstantPool) {
1461       OutStreamer.EmitDataRegion(MCDR_DataRegion);
1462       InConstantPool = true;
1463     }
1464
1465     OutStreamer.EmitLabel(GetCPISymbol(LabelId));
1466
1467     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
1468     if (MCPE.isMachineConstantPoolEntry())
1469       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
1470     else
1471       EmitGlobalConstant(MCPE.Val.ConstVal);
1472     return;
1473   }
1474   case ARM::t2BR_JT: {
1475     // Lower and emit the instruction itself, then the jump table following it.
1476     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVr)
1477       .addReg(ARM::PC)
1478       .addReg(MI->getOperand(0).getReg())
1479       // Add predicate operands.
1480       .addImm(ARMCC::AL)
1481       .addReg(0));
1482
1483     // Output the data for the jump table itself
1484     EmitJump2Table(MI);
1485     return;
1486   }
1487   case ARM::t2TBB_JT: {
1488     // Lower and emit the instruction itself, then the jump table following it.
1489     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::t2TBB)
1490       .addReg(ARM::PC)
1491       .addReg(MI->getOperand(0).getReg())
1492       // Add predicate operands.
1493       .addImm(ARMCC::AL)
1494       .addReg(0));
1495
1496     // Output the data for the jump table itself
1497     EmitJump2Table(MI);
1498     // Make sure the next instruction is 2-byte aligned.
1499     EmitAlignment(1);
1500     return;
1501   }
1502   case ARM::t2TBH_JT: {
1503     // Lower and emit the instruction itself, then the jump table following it.
1504     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::t2TBH)
1505       .addReg(ARM::PC)
1506       .addReg(MI->getOperand(0).getReg())
1507       // Add predicate operands.
1508       .addImm(ARMCC::AL)
1509       .addReg(0));
1510
1511     // Output the data for the jump table itself
1512     EmitJump2Table(MI);
1513     return;
1514   }
1515   case ARM::tBR_JTr:
1516   case ARM::BR_JTr: {
1517     // Lower and emit the instruction itself, then the jump table following it.
1518     // mov pc, target
1519     MCInst TmpInst;
1520     unsigned Opc = MI->getOpcode() == ARM::BR_JTr ?
1521       ARM::MOVr : ARM::tMOVr;
1522     TmpInst.setOpcode(Opc);
1523     TmpInst.addOperand(MCOperand::CreateReg(ARM::PC));
1524     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1525     // Add predicate operands.
1526     TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
1527     TmpInst.addOperand(MCOperand::CreateReg(0));
1528     // Add 's' bit operand (always reg0 for this)
1529     if (Opc == ARM::MOVr)
1530       TmpInst.addOperand(MCOperand::CreateReg(0));
1531     EmitToStreamer(OutStreamer, TmpInst);
1532
1533     // Make sure the Thumb jump table is 4-byte aligned.
1534     if (Opc == ARM::tMOVr)
1535       EmitAlignment(2);
1536
1537     // Output the data for the jump table itself
1538     EmitJumpTable(MI);
1539     return;
1540   }
1541   case ARM::BR_JTm: {
1542     // Lower and emit the instruction itself, then the jump table following it.
1543     // ldr pc, target
1544     MCInst TmpInst;
1545     if (MI->getOperand(1).getReg() == 0) {
1546       // literal offset
1547       TmpInst.setOpcode(ARM::LDRi12);
1548       TmpInst.addOperand(MCOperand::CreateReg(ARM::PC));
1549       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1550       TmpInst.addOperand(MCOperand::CreateImm(MI->getOperand(2).getImm()));
1551     } else {
1552       TmpInst.setOpcode(ARM::LDRrs);
1553       TmpInst.addOperand(MCOperand::CreateReg(ARM::PC));
1554       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1555       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(1).getReg()));
1556       TmpInst.addOperand(MCOperand::CreateImm(0));
1557     }
1558     // Add predicate operands.
1559     TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
1560     TmpInst.addOperand(MCOperand::CreateReg(0));
1561     EmitToStreamer(OutStreamer, TmpInst);
1562
1563     // Output the data for the jump table itself
1564     EmitJumpTable(MI);
1565     return;
1566   }
1567   case ARM::BR_JTadd: {
1568     // Lower and emit the instruction itself, then the jump table following it.
1569     // add pc, target, idx
1570     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::ADDrr)
1571       .addReg(ARM::PC)
1572       .addReg(MI->getOperand(0).getReg())
1573       .addReg(MI->getOperand(1).getReg())
1574       // Add predicate operands.
1575       .addImm(ARMCC::AL)
1576       .addReg(0)
1577       // Add 's' bit operand (always reg0 for this)
1578       .addReg(0));
1579
1580     // Output the data for the jump table itself
1581     EmitJumpTable(MI);
1582     return;
1583   }
1584   case ARM::TRAP: {
1585     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1586     // FIXME: Remove this special case when they do.
1587     if (!Subtarget->isTargetMachO()) {
1588       //.long 0xe7ffdefe @ trap
1589       uint32_t Val = 0xe7ffdefeUL;
1590       OutStreamer.AddComment("trap");
1591       OutStreamer.EmitIntValue(Val, 4);
1592       return;
1593     }
1594     break;
1595   }
1596   case ARM::TRAPNaCl: {
1597     //.long 0xe7fedef0 @ trap
1598     uint32_t Val = 0xe7fedef0UL;
1599     OutStreamer.AddComment("trap");
1600     OutStreamer.EmitIntValue(Val, 4);
1601     return;
1602   }
1603   case ARM::tTRAP: {
1604     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1605     // FIXME: Remove this special case when they do.
1606     if (!Subtarget->isTargetMachO()) {
1607       //.short 57086 @ trap
1608       uint16_t Val = 0xdefe;
1609       OutStreamer.AddComment("trap");
1610       OutStreamer.EmitIntValue(Val, 2);
1611       return;
1612     }
1613     break;
1614   }
1615   case ARM::t2Int_eh_sjlj_setjmp:
1616   case ARM::t2Int_eh_sjlj_setjmp_nofp:
1617   case ARM::tInt_eh_sjlj_setjmp: {
1618     // Two incoming args: GPR:$src, GPR:$val
1619     // mov $val, pc
1620     // adds $val, #7
1621     // str $val, [$src, #4]
1622     // movs r0, #0
1623     // b 1f
1624     // movs r0, #1
1625     // 1:
1626     unsigned SrcReg = MI->getOperand(0).getReg();
1627     unsigned ValReg = MI->getOperand(1).getReg();
1628     MCSymbol *Label = GetARMSJLJEHLabel();
1629     OutStreamer.AddComment("eh_setjmp begin");
1630     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVr)
1631       .addReg(ValReg)
1632       .addReg(ARM::PC)
1633       // Predicate.
1634       .addImm(ARMCC::AL)
1635       .addReg(0));
1636
1637     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tADDi3)
1638       .addReg(ValReg)
1639       // 's' bit operand
1640       .addReg(ARM::CPSR)
1641       .addReg(ValReg)
1642       .addImm(7)
1643       // Predicate.
1644       .addImm(ARMCC::AL)
1645       .addReg(0));
1646
1647     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tSTRi)
1648       .addReg(ValReg)
1649       .addReg(SrcReg)
1650       // The offset immediate is #4. The operand value is scaled by 4 for the
1651       // tSTR instruction.
1652       .addImm(1)
1653       // Predicate.
1654       .addImm(ARMCC::AL)
1655       .addReg(0));
1656
1657     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVi8)
1658       .addReg(ARM::R0)
1659       .addReg(ARM::CPSR)
1660       .addImm(0)
1661       // Predicate.
1662       .addImm(ARMCC::AL)
1663       .addReg(0));
1664
1665     const MCExpr *SymbolExpr = MCSymbolRefExpr::Create(Label, OutContext);
1666     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tB)
1667       .addExpr(SymbolExpr)
1668       .addImm(ARMCC::AL)
1669       .addReg(0));
1670
1671     OutStreamer.AddComment("eh_setjmp end");
1672     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVi8)
1673       .addReg(ARM::R0)
1674       .addReg(ARM::CPSR)
1675       .addImm(1)
1676       // Predicate.
1677       .addImm(ARMCC::AL)
1678       .addReg(0));
1679
1680     OutStreamer.EmitLabel(Label);
1681     return;
1682   }
1683
1684   case ARM::Int_eh_sjlj_setjmp_nofp:
1685   case ARM::Int_eh_sjlj_setjmp: {
1686     // Two incoming args: GPR:$src, GPR:$val
1687     // add $val, pc, #8
1688     // str $val, [$src, #+4]
1689     // mov r0, #0
1690     // add pc, pc, #0
1691     // mov r0, #1
1692     unsigned SrcReg = MI->getOperand(0).getReg();
1693     unsigned ValReg = MI->getOperand(1).getReg();
1694
1695     OutStreamer.AddComment("eh_setjmp begin");
1696     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::ADDri)
1697       .addReg(ValReg)
1698       .addReg(ARM::PC)
1699       .addImm(8)
1700       // Predicate.
1701       .addImm(ARMCC::AL)
1702       .addReg(0)
1703       // 's' bit operand (always reg0 for this).
1704       .addReg(0));
1705
1706     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::STRi12)
1707       .addReg(ValReg)
1708       .addReg(SrcReg)
1709       .addImm(4)
1710       // Predicate.
1711       .addImm(ARMCC::AL)
1712       .addReg(0));
1713
1714     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVi)
1715       .addReg(ARM::R0)
1716       .addImm(0)
1717       // Predicate.
1718       .addImm(ARMCC::AL)
1719       .addReg(0)
1720       // 's' bit operand (always reg0 for this).
1721       .addReg(0));
1722
1723     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::ADDri)
1724       .addReg(ARM::PC)
1725       .addReg(ARM::PC)
1726       .addImm(0)
1727       // Predicate.
1728       .addImm(ARMCC::AL)
1729       .addReg(0)
1730       // 's' bit operand (always reg0 for this).
1731       .addReg(0));
1732
1733     OutStreamer.AddComment("eh_setjmp end");
1734     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVi)
1735       .addReg(ARM::R0)
1736       .addImm(1)
1737       // Predicate.
1738       .addImm(ARMCC::AL)
1739       .addReg(0)
1740       // 's' bit operand (always reg0 for this).
1741       .addReg(0));
1742     return;
1743   }
1744   case ARM::Int_eh_sjlj_longjmp: {
1745     // ldr sp, [$src, #8]
1746     // ldr $scratch, [$src, #4]
1747     // ldr r7, [$src]
1748     // bx $scratch
1749     unsigned SrcReg = MI->getOperand(0).getReg();
1750     unsigned ScratchReg = MI->getOperand(1).getReg();
1751     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::LDRi12)
1752       .addReg(ARM::SP)
1753       .addReg(SrcReg)
1754       .addImm(8)
1755       // Predicate.
1756       .addImm(ARMCC::AL)
1757       .addReg(0));
1758
1759     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::LDRi12)
1760       .addReg(ScratchReg)
1761       .addReg(SrcReg)
1762       .addImm(4)
1763       // Predicate.
1764       .addImm(ARMCC::AL)
1765       .addReg(0));
1766
1767     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::LDRi12)
1768       .addReg(ARM::R7)
1769       .addReg(SrcReg)
1770       .addImm(0)
1771       // Predicate.
1772       .addImm(ARMCC::AL)
1773       .addReg(0));
1774
1775     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::BX)
1776       .addReg(ScratchReg)
1777       // Predicate.
1778       .addImm(ARMCC::AL)
1779       .addReg(0));
1780     return;
1781   }
1782   case ARM::tInt_eh_sjlj_longjmp: {
1783     // ldr $scratch, [$src, #8]
1784     // mov sp, $scratch
1785     // ldr $scratch, [$src, #4]
1786     // ldr r7, [$src]
1787     // bx $scratch
1788     unsigned SrcReg = MI->getOperand(0).getReg();
1789     unsigned ScratchReg = MI->getOperand(1).getReg();
1790     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tLDRi)
1791       .addReg(ScratchReg)
1792       .addReg(SrcReg)
1793       // The offset immediate is #8. The operand value is scaled by 4 for the
1794       // tLDR instruction.
1795       .addImm(2)
1796       // Predicate.
1797       .addImm(ARMCC::AL)
1798       .addReg(0));
1799
1800     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVr)
1801       .addReg(ARM::SP)
1802       .addReg(ScratchReg)
1803       // Predicate.
1804       .addImm(ARMCC::AL)
1805       .addReg(0));
1806
1807     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tLDRi)
1808       .addReg(ScratchReg)
1809       .addReg(SrcReg)
1810       .addImm(1)
1811       // Predicate.
1812       .addImm(ARMCC::AL)
1813       .addReg(0));
1814
1815     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tLDRi)
1816       .addReg(ARM::R7)
1817       .addReg(SrcReg)
1818       .addImm(0)
1819       // Predicate.
1820       .addImm(ARMCC::AL)
1821       .addReg(0));
1822
1823     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tBX)
1824       .addReg(ScratchReg)
1825       // Predicate.
1826       .addImm(ARMCC::AL)
1827       .addReg(0));
1828     return;
1829   }
1830   }
1831
1832   MCInst TmpInst;
1833   LowerARMMachineInstrToMCInst(MI, TmpInst, *this);
1834
1835   EmitToStreamer(OutStreamer, TmpInst);
1836 }
1837
1838 //===----------------------------------------------------------------------===//
1839 // Target Registry Stuff
1840 //===----------------------------------------------------------------------===//
1841
1842 // Force static initialization.
1843 extern "C" void LLVMInitializeARMAsmPrinter() {
1844   RegisterAsmPrinter<ARMAsmPrinter> X(TheARMLETarget);
1845   RegisterAsmPrinter<ARMAsmPrinter> Y(TheARMBETarget);
1846   RegisterAsmPrinter<ARMAsmPrinter> A(TheThumbLETarget);
1847   RegisterAsmPrinter<ARMAsmPrinter> B(TheThumbBETarget);
1848 }