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