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