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