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