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