DebugInfo: PR14763/r183329 correct the location of indirect parameters
[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 (CPUString == "generic") {
753     // For a generic CPU, we assume a standard v7a architecture in Subtarget.
754     AttrEmitter->EmitAttribute(ARMBuildAttrs::CPU_arch, ARMBuildAttrs::v7);
755     AttrEmitter->EmitAttribute(ARMBuildAttrs::CPU_arch_profile,
756                                ARMBuildAttrs::ApplicationProfile);
757     AttrEmitter->EmitAttribute(ARMBuildAttrs::ARM_ISA_use,
758                                ARMBuildAttrs::Allowed);
759     AttrEmitter->EmitAttribute(ARMBuildAttrs::THUMB_ISA_use,
760                                ARMBuildAttrs::AllowThumb32);
761   } else if (Subtarget->hasV7Ops()) {
762     AttrEmitter->EmitAttribute(ARMBuildAttrs::CPU_arch, ARMBuildAttrs::v7);
763     AttrEmitter->EmitAttribute(ARMBuildAttrs::THUMB_ISA_use,
764                                ARMBuildAttrs::AllowThumb32);
765   } else if (Subtarget->hasV6T2Ops())
766     AttrEmitter->EmitAttribute(ARMBuildAttrs::CPU_arch, ARMBuildAttrs::v6T2);
767   else if (Subtarget->hasV6Ops())
768     AttrEmitter->EmitAttribute(ARMBuildAttrs::CPU_arch, ARMBuildAttrs::v6);
769   else if (Subtarget->hasV5TEOps())
770     AttrEmitter->EmitAttribute(ARMBuildAttrs::CPU_arch, ARMBuildAttrs::v5TE);
771   else if (Subtarget->hasV5TOps())
772     AttrEmitter->EmitAttribute(ARMBuildAttrs::CPU_arch, ARMBuildAttrs::v5T);
773   else if (Subtarget->hasV4TOps())
774     AttrEmitter->EmitAttribute(ARMBuildAttrs::CPU_arch, ARMBuildAttrs::v4T);
775
776   if (Subtarget->hasNEON() && emitFPU) {
777     /* NEON is not exactly a VFP architecture, but GAS emit one of
778      * neon/neon-vfpv4/vfpv3/vfpv2 for .fpu parameters */
779     if (Subtarget->hasVFP4())
780       AttrEmitter->EmitTextAttribute(ARMBuildAttrs::Advanced_SIMD_arch,
781                                      "neon-vfpv4");
782     else
783       AttrEmitter->EmitTextAttribute(ARMBuildAttrs::Advanced_SIMD_arch, "neon");
784     /* If emitted for NEON, omit from VFP below, since you can have both
785      * NEON and VFP in build attributes but only one .fpu */
786     emitFPU = false;
787   }
788
789   /* VFPv4 + .fpu */
790   if (Subtarget->hasVFP4()) {
791     AttrEmitter->EmitAttribute(ARMBuildAttrs::VFP_arch,
792                                ARMBuildAttrs::AllowFPv4A);
793     if (emitFPU)
794       AttrEmitter->EmitTextAttribute(ARMBuildAttrs::VFP_arch, "vfpv4");
795
796   /* VFPv3 + .fpu */
797   } else if (Subtarget->hasVFP3()) {
798     AttrEmitter->EmitAttribute(ARMBuildAttrs::VFP_arch,
799                                ARMBuildAttrs::AllowFPv3A);
800     if (emitFPU)
801       AttrEmitter->EmitTextAttribute(ARMBuildAttrs::VFP_arch, "vfpv3");
802
803   /* VFPv2 + .fpu */
804   } else if (Subtarget->hasVFP2()) {
805     AttrEmitter->EmitAttribute(ARMBuildAttrs::VFP_arch,
806                                ARMBuildAttrs::AllowFPv2);
807     if (emitFPU)
808       AttrEmitter->EmitTextAttribute(ARMBuildAttrs::VFP_arch, "vfpv2");
809   }
810
811   /* TODO: ARMBuildAttrs::Allowed is not completely accurate,
812    * since NEON can have 1 (allowed) or 2 (MAC operations) */
813   if (Subtarget->hasNEON()) {
814     AttrEmitter->EmitAttribute(ARMBuildAttrs::Advanced_SIMD_arch,
815                                ARMBuildAttrs::Allowed);
816   }
817
818   // Signal various FP modes.
819   if (!TM.Options.UnsafeFPMath) {
820     AttrEmitter->EmitAttribute(ARMBuildAttrs::ABI_FP_denormal,
821                                ARMBuildAttrs::Allowed);
822     AttrEmitter->EmitAttribute(ARMBuildAttrs::ABI_FP_exceptions,
823                                ARMBuildAttrs::Allowed);
824   }
825
826   if (TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath)
827     AttrEmitter->EmitAttribute(ARMBuildAttrs::ABI_FP_number_model,
828                                ARMBuildAttrs::Allowed);
829   else
830     AttrEmitter->EmitAttribute(ARMBuildAttrs::ABI_FP_number_model,
831                                ARMBuildAttrs::AllowIEE754);
832
833   // FIXME: add more flags to ARMBuildAttrs.h
834   // 8-bytes alignment stuff.
835   AttrEmitter->EmitAttribute(ARMBuildAttrs::ABI_align8_needed, 1);
836   AttrEmitter->EmitAttribute(ARMBuildAttrs::ABI_align8_preserved, 1);
837
838   // Hard float.  Use both S and D registers and conform to AAPCS-VFP.
839   if (Subtarget->isAAPCS_ABI() && TM.Options.FloatABIType == FloatABI::Hard) {
840     AttrEmitter->EmitAttribute(ARMBuildAttrs::ABI_HardFP_use, 3);
841     AttrEmitter->EmitAttribute(ARMBuildAttrs::ABI_VFP_args, 1);
842   }
843   // FIXME: Should we signal R9 usage?
844
845   if (Subtarget->hasDivide())
846     AttrEmitter->EmitAttribute(ARMBuildAttrs::DIV_use, 1);
847
848   AttrEmitter->Finish();
849   delete AttrEmitter;
850 }
851
852 void ARMAsmPrinter::emitARMAttributeSection() {
853   // <format-version>
854   // [ <section-length> "vendor-name"
855   // [ <file-tag> <size> <attribute>*
856   //   | <section-tag> <size> <section-number>* 0 <attribute>*
857   //   | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
858   //   ]+
859   // ]*
860
861   if (OutStreamer.hasRawTextSupport())
862     return;
863
864   const ARMElfTargetObjectFile &TLOFELF =
865     static_cast<const ARMElfTargetObjectFile &>
866     (getObjFileLowering());
867
868   OutStreamer.SwitchSection(TLOFELF.getAttributesSection());
869
870   // Format version
871   OutStreamer.EmitIntValue(0x41, 1);
872 }
873
874 //===----------------------------------------------------------------------===//
875
876 static MCSymbol *getPICLabel(const char *Prefix, unsigned FunctionNumber,
877                              unsigned LabelId, MCContext &Ctx) {
878
879   MCSymbol *Label = Ctx.GetOrCreateSymbol(Twine(Prefix)
880                        + "PC" + Twine(FunctionNumber) + "_" + Twine(LabelId));
881   return Label;
882 }
883
884 static MCSymbolRefExpr::VariantKind
885 getModifierVariantKind(ARMCP::ARMCPModifier Modifier) {
886   switch (Modifier) {
887   case ARMCP::no_modifier: return MCSymbolRefExpr::VK_None;
888   case ARMCP::TLSGD:       return MCSymbolRefExpr::VK_ARM_TLSGD;
889   case ARMCP::TPOFF:       return MCSymbolRefExpr::VK_ARM_TPOFF;
890   case ARMCP::GOTTPOFF:    return MCSymbolRefExpr::VK_ARM_GOTTPOFF;
891   case ARMCP::GOT:         return MCSymbolRefExpr::VK_ARM_GOT;
892   case ARMCP::GOTOFF:      return MCSymbolRefExpr::VK_ARM_GOTOFF;
893   }
894   llvm_unreachable("Invalid ARMCPModifier!");
895 }
896
897 MCSymbol *ARMAsmPrinter::GetARMGVSymbol(const GlobalValue *GV) {
898   bool isIndirect = Subtarget->isTargetDarwin() &&
899     Subtarget->GVIsIndirectSymbol(GV, TM.getRelocationModel());
900   if (!isIndirect)
901     return Mang->getSymbol(GV);
902
903   // FIXME: Remove this when Darwin transition to @GOT like syntax.
904   MCSymbol *MCSym = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
905   MachineModuleInfoMachO &MMIMachO =
906     MMI->getObjFileInfo<MachineModuleInfoMachO>();
907   MachineModuleInfoImpl::StubValueTy &StubSym =
908     GV->hasHiddenVisibility() ? MMIMachO.getHiddenGVStubEntry(MCSym) :
909     MMIMachO.getGVStubEntry(MCSym);
910   if (StubSym.getPointer() == 0)
911     StubSym = MachineModuleInfoImpl::
912       StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
913   return MCSym;
914 }
915
916 void ARMAsmPrinter::
917 EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
918   int Size = TM.getDataLayout()->getTypeAllocSize(MCPV->getType());
919
920   ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
921
922   MCSymbol *MCSym;
923   if (ACPV->isLSDA()) {
924     SmallString<128> Str;
925     raw_svector_ostream OS(Str);
926     OS << MAI->getPrivateGlobalPrefix() << "_LSDA_" << getFunctionNumber();
927     MCSym = OutContext.GetOrCreateSymbol(OS.str());
928   } else if (ACPV->isBlockAddress()) {
929     const BlockAddress *BA =
930       cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress();
931     MCSym = GetBlockAddressSymbol(BA);
932   } else if (ACPV->isGlobalValue()) {
933     const GlobalValue *GV = cast<ARMConstantPoolConstant>(ACPV)->getGV();
934     MCSym = GetARMGVSymbol(GV);
935   } else if (ACPV->isMachineBasicBlock()) {
936     const MachineBasicBlock *MBB = cast<ARMConstantPoolMBB>(ACPV)->getMBB();
937     MCSym = MBB->getSymbol();
938   } else {
939     assert(ACPV->isExtSymbol() && "unrecognized constant pool value");
940     const char *Sym = cast<ARMConstantPoolSymbol>(ACPV)->getSymbol();
941     MCSym = GetExternalSymbolSymbol(Sym);
942   }
943
944   // Create an MCSymbol for the reference.
945   const MCExpr *Expr =
946     MCSymbolRefExpr::Create(MCSym, getModifierVariantKind(ACPV->getModifier()),
947                             OutContext);
948
949   if (ACPV->getPCAdjustment()) {
950     MCSymbol *PCLabel = getPICLabel(MAI->getPrivateGlobalPrefix(),
951                                     getFunctionNumber(),
952                                     ACPV->getLabelId(),
953                                     OutContext);
954     const MCExpr *PCRelExpr = MCSymbolRefExpr::Create(PCLabel, OutContext);
955     PCRelExpr =
956       MCBinaryExpr::CreateAdd(PCRelExpr,
957                               MCConstantExpr::Create(ACPV->getPCAdjustment(),
958                                                      OutContext),
959                               OutContext);
960     if (ACPV->mustAddCurrentAddress()) {
961       // We want "(<expr> - .)", but MC doesn't have a concept of the '.'
962       // label, so just emit a local label end reference that instead.
963       MCSymbol *DotSym = OutContext.CreateTempSymbol();
964       OutStreamer.EmitLabel(DotSym);
965       const MCExpr *DotExpr = MCSymbolRefExpr::Create(DotSym, OutContext);
966       PCRelExpr = MCBinaryExpr::CreateSub(PCRelExpr, DotExpr, OutContext);
967     }
968     Expr = MCBinaryExpr::CreateSub(Expr, PCRelExpr, OutContext);
969   }
970   OutStreamer.EmitValue(Expr, Size);
971 }
972
973 void ARMAsmPrinter::EmitJumpTable(const MachineInstr *MI) {
974   unsigned Opcode = MI->getOpcode();
975   int OpNum = 1;
976   if (Opcode == ARM::BR_JTadd)
977     OpNum = 2;
978   else if (Opcode == ARM::BR_JTm)
979     OpNum = 3;
980
981   const MachineOperand &MO1 = MI->getOperand(OpNum);
982   const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
983   unsigned JTI = MO1.getIndex();
984
985   // Emit a label for the jump table.
986   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel2(JTI, MO2.getImm());
987   OutStreamer.EmitLabel(JTISymbol);
988
989   // Mark the jump table as data-in-code.
990   OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
991
992   // Emit each entry of the table.
993   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
994   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
995   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
996
997   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
998     MachineBasicBlock *MBB = JTBBs[i];
999     // Construct an MCExpr for the entry. We want a value of the form:
1000     // (BasicBlockAddr - TableBeginAddr)
1001     //
1002     // For example, a table with entries jumping to basic blocks BB0 and BB1
1003     // would look like:
1004     // LJTI_0_0:
1005     //    .word (LBB0 - LJTI_0_0)
1006     //    .word (LBB1 - LJTI_0_0)
1007     const MCExpr *Expr = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1008
1009     if (TM.getRelocationModel() == Reloc::PIC_)
1010       Expr = MCBinaryExpr::CreateSub(Expr, MCSymbolRefExpr::Create(JTISymbol,
1011                                                                    OutContext),
1012                                      OutContext);
1013     // If we're generating a table of Thumb addresses in static relocation
1014     // model, we need to add one to keep interworking correctly.
1015     else if (AFI->isThumbFunction())
1016       Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(1,OutContext),
1017                                      OutContext);
1018     OutStreamer.EmitValue(Expr, 4);
1019   }
1020   // Mark the end of jump table data-in-code region.
1021   OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1022 }
1023
1024 void ARMAsmPrinter::EmitJump2Table(const MachineInstr *MI) {
1025   unsigned Opcode = MI->getOpcode();
1026   int OpNum = (Opcode == ARM::t2BR_JT) ? 2 : 1;
1027   const MachineOperand &MO1 = MI->getOperand(OpNum);
1028   const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
1029   unsigned JTI = MO1.getIndex();
1030
1031   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel2(JTI, MO2.getImm());
1032   OutStreamer.EmitLabel(JTISymbol);
1033
1034   // Emit each entry of the table.
1035   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1036   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1037   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1038   unsigned OffsetWidth = 4;
1039   if (MI->getOpcode() == ARM::t2TBB_JT) {
1040     OffsetWidth = 1;
1041     // Mark the jump table as data-in-code.
1042     OutStreamer.EmitDataRegion(MCDR_DataRegionJT8);
1043   } else if (MI->getOpcode() == ARM::t2TBH_JT) {
1044     OffsetWidth = 2;
1045     // Mark the jump table as data-in-code.
1046     OutStreamer.EmitDataRegion(MCDR_DataRegionJT16);
1047   }
1048
1049   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
1050     MachineBasicBlock *MBB = JTBBs[i];
1051     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::Create(MBB->getSymbol(),
1052                                                       OutContext);
1053     // If this isn't a TBB or TBH, the entries are direct branch instructions.
1054     if (OffsetWidth == 4) {
1055       OutStreamer.EmitInstruction(MCInstBuilder(ARM::t2B)
1056         .addExpr(MBBSymbolExpr)
1057         .addImm(ARMCC::AL)
1058         .addReg(0));
1059       continue;
1060     }
1061     // Otherwise it's an offset from the dispatch instruction. Construct an
1062     // MCExpr for the entry. We want a value of the form:
1063     // (BasicBlockAddr - TableBeginAddr) / 2
1064     //
1065     // For example, a TBB table with entries jumping to basic blocks BB0 and BB1
1066     // would look like:
1067     // LJTI_0_0:
1068     //    .byte (LBB0 - LJTI_0_0) / 2
1069     //    .byte (LBB1 - LJTI_0_0) / 2
1070     const MCExpr *Expr =
1071       MCBinaryExpr::CreateSub(MBBSymbolExpr,
1072                               MCSymbolRefExpr::Create(JTISymbol, OutContext),
1073                               OutContext);
1074     Expr = MCBinaryExpr::CreateDiv(Expr, MCConstantExpr::Create(2, OutContext),
1075                                    OutContext);
1076     OutStreamer.EmitValue(Expr, OffsetWidth);
1077   }
1078   // Mark the end of jump table data-in-code region. 32-bit offsets use
1079   // actual branch instructions here, so we don't mark those as a data-region
1080   // at all.
1081   if (OffsetWidth != 4)
1082     OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1083 }
1084
1085 void ARMAsmPrinter::EmitUnwindingInstruction(const MachineInstr *MI) {
1086   assert(MI->getFlag(MachineInstr::FrameSetup) &&
1087       "Only instruction which are involved into frame setup code are allowed");
1088
1089   const MachineFunction &MF = *MI->getParent()->getParent();
1090   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
1091   const ARMFunctionInfo &AFI = *MF.getInfo<ARMFunctionInfo>();
1092
1093   unsigned FramePtr = RegInfo->getFrameRegister(MF);
1094   unsigned Opc = MI->getOpcode();
1095   unsigned SrcReg, DstReg;
1096
1097   if (Opc == ARM::tPUSH || Opc == ARM::tLDRpci) {
1098     // Two special cases:
1099     // 1) tPUSH does not have src/dst regs.
1100     // 2) for Thumb1 code we sometimes materialize the constant via constpool
1101     // load. Yes, this is pretty fragile, but for now I don't see better
1102     // way... :(
1103     SrcReg = DstReg = ARM::SP;
1104   } else {
1105     SrcReg = MI->getOperand(1).getReg();
1106     DstReg = MI->getOperand(0).getReg();
1107   }
1108
1109   // Try to figure out the unwinding opcode out of src / dst regs.
1110   if (MI->mayStore()) {
1111     // Register saves.
1112     assert(DstReg == ARM::SP &&
1113            "Only stack pointer as a destination reg is supported");
1114
1115     SmallVector<unsigned, 4> RegList;
1116     // Skip src & dst reg, and pred ops.
1117     unsigned StartOp = 2 + 2;
1118     // Use all the operands.
1119     unsigned NumOffset = 0;
1120
1121     switch (Opc) {
1122     default:
1123       MI->dump();
1124       llvm_unreachable("Unsupported opcode for unwinding information");
1125     case ARM::tPUSH:
1126       // Special case here: no src & dst reg, but two extra imp ops.
1127       StartOp = 2; NumOffset = 2;
1128     case ARM::STMDB_UPD:
1129     case ARM::t2STMDB_UPD:
1130     case ARM::VSTMDDB_UPD:
1131       assert(SrcReg == ARM::SP &&
1132              "Only stack pointer as a source reg is supported");
1133       for (unsigned i = StartOp, NumOps = MI->getNumOperands() - NumOffset;
1134            i != NumOps; ++i) {
1135         const MachineOperand &MO = MI->getOperand(i);
1136         // Actually, there should never be any impdef stuff here. Skip it
1137         // temporary to workaround PR11902.
1138         if (MO.isImplicit())
1139           continue;
1140         RegList.push_back(MO.getReg());
1141       }
1142       break;
1143     case ARM::STR_PRE_IMM:
1144     case ARM::STR_PRE_REG:
1145     case ARM::t2STR_PRE:
1146       assert(MI->getOperand(2).getReg() == ARM::SP &&
1147              "Only stack pointer as a source reg is supported");
1148       RegList.push_back(SrcReg);
1149       break;
1150     }
1151     OutStreamer.EmitRegSave(RegList, Opc == ARM::VSTMDDB_UPD);
1152   } else {
1153     // Changes of stack / frame pointer.
1154     if (SrcReg == ARM::SP) {
1155       int64_t Offset = 0;
1156       switch (Opc) {
1157       default:
1158         MI->dump();
1159         llvm_unreachable("Unsupported opcode for unwinding information");
1160       case ARM::MOVr:
1161       case ARM::tMOVr:
1162         Offset = 0;
1163         break;
1164       case ARM::ADDri:
1165         Offset = -MI->getOperand(2).getImm();
1166         break;
1167       case ARM::SUBri:
1168       case ARM::t2SUBri:
1169         Offset = MI->getOperand(2).getImm();
1170         break;
1171       case ARM::tSUBspi:
1172         Offset = MI->getOperand(2).getImm()*4;
1173         break;
1174       case ARM::tADDspi:
1175       case ARM::tADDrSPi:
1176         Offset = -MI->getOperand(2).getImm()*4;
1177         break;
1178       case ARM::tLDRpci: {
1179         // Grab the constpool index and check, whether it corresponds to
1180         // original or cloned constpool entry.
1181         unsigned CPI = MI->getOperand(1).getIndex();
1182         const MachineConstantPool *MCP = MF.getConstantPool();
1183         if (CPI >= MCP->getConstants().size())
1184           CPI = AFI.getOriginalCPIdx(CPI);
1185         assert(CPI != -1U && "Invalid constpool index");
1186
1187         // Derive the actual offset.
1188         const MachineConstantPoolEntry &CPE = MCP->getConstants()[CPI];
1189         assert(!CPE.isMachineConstantPoolEntry() && "Invalid constpool entry");
1190         // FIXME: Check for user, it should be "add" instruction!
1191         Offset = -cast<ConstantInt>(CPE.Val.ConstVal)->getSExtValue();
1192         break;
1193       }
1194       }
1195
1196       if (DstReg == FramePtr && FramePtr != ARM::SP)
1197         // Set-up of the frame pointer. Positive values correspond to "add"
1198         // instruction.
1199         OutStreamer.EmitSetFP(FramePtr, ARM::SP, -Offset);
1200       else if (DstReg == ARM::SP) {
1201         // Change of SP by an offset. Positive values correspond to "sub"
1202         // instruction.
1203         OutStreamer.EmitPad(Offset);
1204       } else {
1205         MI->dump();
1206         llvm_unreachable("Unsupported opcode for unwinding information");
1207       }
1208     } else if (DstReg == ARM::SP) {
1209       // FIXME: .movsp goes here
1210       MI->dump();
1211       llvm_unreachable("Unsupported opcode for unwinding information");
1212     }
1213     else {
1214       MI->dump();
1215       llvm_unreachable("Unsupported opcode for unwinding information");
1216     }
1217   }
1218 }
1219
1220 extern cl::opt<bool> EnableARMEHABI;
1221
1222 // Simple pseudo-instructions have their lowering (with expansion to real
1223 // instructions) auto-generated.
1224 #include "ARMGenMCPseudoLowering.inc"
1225
1226 void ARMAsmPrinter::EmitInstruction(const MachineInstr *MI) {
1227   // If we just ended a constant pool, mark it as such.
1228   if (InConstantPool && MI->getOpcode() != ARM::CONSTPOOL_ENTRY) {
1229     OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1230     InConstantPool = false;
1231   }
1232
1233   // Emit unwinding stuff for frame-related instructions
1234   if (EnableARMEHABI && MI->getFlag(MachineInstr::FrameSetup))
1235     EmitUnwindingInstruction(MI);
1236
1237   // Do any auto-generated pseudo lowerings.
1238   if (emitPseudoExpansionLowering(OutStreamer, MI))
1239     return;
1240
1241   assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
1242          "Pseudo flag setting opcode should be expanded early");
1243
1244   // Check for manual lowerings.
1245   unsigned Opc = MI->getOpcode();
1246   switch (Opc) {
1247   case ARM::t2MOVi32imm: llvm_unreachable("Should be lowered by thumb2it pass");
1248   case ARM::DBG_VALUE: llvm_unreachable("Should be handled by generic printing");
1249   case ARM::LEApcrel:
1250   case ARM::tLEApcrel:
1251   case ARM::t2LEApcrel: {
1252     // FIXME: Need to also handle globals and externals
1253     MCSymbol *CPISymbol = GetCPISymbol(MI->getOperand(1).getIndex());
1254     OutStreamer.EmitInstruction(MCInstBuilder(MI->getOpcode() ==
1255                                               ARM::t2LEApcrel ? ARM::t2ADR
1256                   : (MI->getOpcode() == ARM::tLEApcrel ? ARM::tADR
1257                      : ARM::ADR))
1258       .addReg(MI->getOperand(0).getReg())
1259       .addExpr(MCSymbolRefExpr::Create(CPISymbol, OutContext))
1260       // Add predicate operands.
1261       .addImm(MI->getOperand(2).getImm())
1262       .addReg(MI->getOperand(3).getReg()));
1263     return;
1264   }
1265   case ARM::LEApcrelJT:
1266   case ARM::tLEApcrelJT:
1267   case ARM::t2LEApcrelJT: {
1268     MCSymbol *JTIPICSymbol =
1269       GetARMJTIPICJumpTableLabel2(MI->getOperand(1).getIndex(),
1270                                   MI->getOperand(2).getImm());
1271     OutStreamer.EmitInstruction(MCInstBuilder(MI->getOpcode() ==
1272                                               ARM::t2LEApcrelJT ? ARM::t2ADR
1273                   : (MI->getOpcode() == ARM::tLEApcrelJT ? ARM::tADR
1274                      : ARM::ADR))
1275       .addReg(MI->getOperand(0).getReg())
1276       .addExpr(MCSymbolRefExpr::Create(JTIPICSymbol, OutContext))
1277       // Add predicate operands.
1278       .addImm(MI->getOperand(3).getImm())
1279       .addReg(MI->getOperand(4).getReg()));
1280     return;
1281   }
1282   // Darwin call instructions are just normal call instructions with different
1283   // clobber semantics (they clobber R9).
1284   case ARM::BX_CALL: {
1285     OutStreamer.EmitInstruction(MCInstBuilder(ARM::MOVr)
1286       .addReg(ARM::LR)
1287       .addReg(ARM::PC)
1288       // Add predicate operands.
1289       .addImm(ARMCC::AL)
1290       .addReg(0)
1291       // Add 's' bit operand (always reg0 for this)
1292       .addReg(0));
1293
1294     OutStreamer.EmitInstruction(MCInstBuilder(ARM::BX)
1295       .addReg(MI->getOperand(0).getReg()));
1296     return;
1297   }
1298   case ARM::tBX_CALL: {
1299     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tMOVr)
1300       .addReg(ARM::LR)
1301       .addReg(ARM::PC)
1302       // Add predicate operands.
1303       .addImm(ARMCC::AL)
1304       .addReg(0));
1305
1306     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tBX)
1307       .addReg(MI->getOperand(0).getReg())
1308       // Add predicate operands.
1309       .addImm(ARMCC::AL)
1310       .addReg(0));
1311     return;
1312   }
1313   case ARM::BMOVPCRX_CALL: {
1314     OutStreamer.EmitInstruction(MCInstBuilder(ARM::MOVr)
1315       .addReg(ARM::LR)
1316       .addReg(ARM::PC)
1317       // Add predicate operands.
1318       .addImm(ARMCC::AL)
1319       .addReg(0)
1320       // Add 's' bit operand (always reg0 for this)
1321       .addReg(0));
1322
1323     OutStreamer.EmitInstruction(MCInstBuilder(ARM::MOVr)
1324       .addReg(ARM::PC)
1325       .addReg(MI->getOperand(0).getReg())
1326       // Add predicate operands.
1327       .addImm(ARMCC::AL)
1328       .addReg(0)
1329       // Add 's' bit operand (always reg0 for this)
1330       .addReg(0));
1331     return;
1332   }
1333   case ARM::BMOVPCB_CALL: {
1334     OutStreamer.EmitInstruction(MCInstBuilder(ARM::MOVr)
1335       .addReg(ARM::LR)
1336       .addReg(ARM::PC)
1337       // Add predicate operands.
1338       .addImm(ARMCC::AL)
1339       .addReg(0)
1340       // Add 's' bit operand (always reg0 for this)
1341       .addReg(0));
1342
1343     const GlobalValue *GV = MI->getOperand(0).getGlobal();
1344     MCSymbol *GVSym = Mang->getSymbol(GV);
1345     const MCExpr *GVSymExpr = MCSymbolRefExpr::Create(GVSym, OutContext);
1346     OutStreamer.EmitInstruction(MCInstBuilder(ARM::Bcc)
1347       .addExpr(GVSymExpr)
1348       // Add predicate operands.
1349       .addImm(ARMCC::AL)
1350       .addReg(0));
1351     return;
1352   }
1353   case ARM::MOVi16_ga_pcrel:
1354   case ARM::t2MOVi16_ga_pcrel: {
1355     MCInst TmpInst;
1356     TmpInst.setOpcode(Opc == ARM::MOVi16_ga_pcrel? ARM::MOVi16 : ARM::t2MOVi16);
1357     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1358
1359     unsigned TF = MI->getOperand(1).getTargetFlags();
1360     bool isPIC = TF == ARMII::MO_LO16_NONLAZY_PIC;
1361     const GlobalValue *GV = MI->getOperand(1).getGlobal();
1362     MCSymbol *GVSym = GetARMGVSymbol(GV);
1363     const MCExpr *GVSymExpr = MCSymbolRefExpr::Create(GVSym, OutContext);
1364     if (isPIC) {
1365       MCSymbol *LabelSym = getPICLabel(MAI->getPrivateGlobalPrefix(),
1366                                        getFunctionNumber(),
1367                                        MI->getOperand(2).getImm(), OutContext);
1368       const MCExpr *LabelSymExpr= MCSymbolRefExpr::Create(LabelSym, OutContext);
1369       unsigned PCAdj = (Opc == ARM::MOVi16_ga_pcrel) ? 8 : 4;
1370       const MCExpr *PCRelExpr =
1371         ARMMCExpr::CreateLower16(MCBinaryExpr::CreateSub(GVSymExpr,
1372                                   MCBinaryExpr::CreateAdd(LabelSymExpr,
1373                                       MCConstantExpr::Create(PCAdj, OutContext),
1374                                           OutContext), OutContext), OutContext);
1375       TmpInst.addOperand(MCOperand::CreateExpr(PCRelExpr));
1376     } else {
1377       const MCExpr *RefExpr= ARMMCExpr::CreateLower16(GVSymExpr, OutContext);
1378       TmpInst.addOperand(MCOperand::CreateExpr(RefExpr));
1379     }
1380
1381     // Add predicate operands.
1382     TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
1383     TmpInst.addOperand(MCOperand::CreateReg(0));
1384     // Add 's' bit operand (always reg0 for this)
1385     TmpInst.addOperand(MCOperand::CreateReg(0));
1386     OutStreamer.EmitInstruction(TmpInst);
1387     return;
1388   }
1389   case ARM::MOVTi16_ga_pcrel:
1390   case ARM::t2MOVTi16_ga_pcrel: {
1391     MCInst TmpInst;
1392     TmpInst.setOpcode(Opc == ARM::MOVTi16_ga_pcrel
1393                       ? ARM::MOVTi16 : ARM::t2MOVTi16);
1394     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1395     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(1).getReg()));
1396
1397     unsigned TF = MI->getOperand(2).getTargetFlags();
1398     bool isPIC = TF == ARMII::MO_HI16_NONLAZY_PIC;
1399     const GlobalValue *GV = MI->getOperand(2).getGlobal();
1400     MCSymbol *GVSym = GetARMGVSymbol(GV);
1401     const MCExpr *GVSymExpr = MCSymbolRefExpr::Create(GVSym, OutContext);
1402     if (isPIC) {
1403       MCSymbol *LabelSym = getPICLabel(MAI->getPrivateGlobalPrefix(),
1404                                        getFunctionNumber(),
1405                                        MI->getOperand(3).getImm(), OutContext);
1406       const MCExpr *LabelSymExpr= MCSymbolRefExpr::Create(LabelSym, OutContext);
1407       unsigned PCAdj = (Opc == ARM::MOVTi16_ga_pcrel) ? 8 : 4;
1408       const MCExpr *PCRelExpr =
1409         ARMMCExpr::CreateUpper16(MCBinaryExpr::CreateSub(GVSymExpr,
1410                                    MCBinaryExpr::CreateAdd(LabelSymExpr,
1411                                       MCConstantExpr::Create(PCAdj, OutContext),
1412                                           OutContext), OutContext), OutContext);
1413       TmpInst.addOperand(MCOperand::CreateExpr(PCRelExpr));
1414     } else {
1415       const MCExpr *RefExpr= ARMMCExpr::CreateUpper16(GVSymExpr, OutContext);
1416       TmpInst.addOperand(MCOperand::CreateExpr(RefExpr));
1417     }
1418     // Add predicate operands.
1419     TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
1420     TmpInst.addOperand(MCOperand::CreateReg(0));
1421     // Add 's' bit operand (always reg0 for this)
1422     TmpInst.addOperand(MCOperand::CreateReg(0));
1423     OutStreamer.EmitInstruction(TmpInst);
1424     return;
1425   }
1426   case ARM::tPICADD: {
1427     // This is a pseudo op for a label + instruction sequence, which looks like:
1428     // LPC0:
1429     //     add r0, pc
1430     // This adds the address of LPC0 to r0.
1431
1432     // Emit the label.
1433     OutStreamer.EmitLabel(getPICLabel(MAI->getPrivateGlobalPrefix(),
1434                           getFunctionNumber(), MI->getOperand(2).getImm(),
1435                           OutContext));
1436
1437     // Form and emit the add.
1438     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tADDhirr)
1439       .addReg(MI->getOperand(0).getReg())
1440       .addReg(MI->getOperand(0).getReg())
1441       .addReg(ARM::PC)
1442       // Add predicate operands.
1443       .addImm(ARMCC::AL)
1444       .addReg(0));
1445     return;
1446   }
1447   case ARM::PICADD: {
1448     // This is a pseudo op for a label + instruction sequence, which looks like:
1449     // LPC0:
1450     //     add r0, pc, r0
1451     // This adds the address of LPC0 to r0.
1452
1453     // Emit the label.
1454     OutStreamer.EmitLabel(getPICLabel(MAI->getPrivateGlobalPrefix(),
1455                           getFunctionNumber(), MI->getOperand(2).getImm(),
1456                           OutContext));
1457
1458     // Form and emit the add.
1459     OutStreamer.EmitInstruction(MCInstBuilder(ARM::ADDrr)
1460       .addReg(MI->getOperand(0).getReg())
1461       .addReg(ARM::PC)
1462       .addReg(MI->getOperand(1).getReg())
1463       // Add predicate operands.
1464       .addImm(MI->getOperand(3).getImm())
1465       .addReg(MI->getOperand(4).getReg())
1466       // Add 's' bit operand (always reg0 for this)
1467       .addReg(0));
1468     return;
1469   }
1470   case ARM::PICSTR:
1471   case ARM::PICSTRB:
1472   case ARM::PICSTRH:
1473   case ARM::PICLDR:
1474   case ARM::PICLDRB:
1475   case ARM::PICLDRH:
1476   case ARM::PICLDRSB:
1477   case ARM::PICLDRSH: {
1478     // This is a pseudo op for a label + instruction sequence, which looks like:
1479     // LPC0:
1480     //     OP r0, [pc, r0]
1481     // The LCP0 label is referenced by a constant pool entry in order to get
1482     // a PC-relative address at the ldr instruction.
1483
1484     // Emit the label.
1485     OutStreamer.EmitLabel(getPICLabel(MAI->getPrivateGlobalPrefix(),
1486                           getFunctionNumber(), MI->getOperand(2).getImm(),
1487                           OutContext));
1488
1489     // Form and emit the load
1490     unsigned Opcode;
1491     switch (MI->getOpcode()) {
1492     default:
1493       llvm_unreachable("Unexpected opcode!");
1494     case ARM::PICSTR:   Opcode = ARM::STRrs; break;
1495     case ARM::PICSTRB:  Opcode = ARM::STRBrs; break;
1496     case ARM::PICSTRH:  Opcode = ARM::STRH; break;
1497     case ARM::PICLDR:   Opcode = ARM::LDRrs; break;
1498     case ARM::PICLDRB:  Opcode = ARM::LDRBrs; break;
1499     case ARM::PICLDRH:  Opcode = ARM::LDRH; break;
1500     case ARM::PICLDRSB: Opcode = ARM::LDRSB; break;
1501     case ARM::PICLDRSH: Opcode = ARM::LDRSH; break;
1502     }
1503     OutStreamer.EmitInstruction(MCInstBuilder(Opcode)
1504       .addReg(MI->getOperand(0).getReg())
1505       .addReg(ARM::PC)
1506       .addReg(MI->getOperand(1).getReg())
1507       .addImm(0)
1508       // Add predicate operands.
1509       .addImm(MI->getOperand(3).getImm())
1510       .addReg(MI->getOperand(4).getReg()));
1511
1512     return;
1513   }
1514   case ARM::CONSTPOOL_ENTRY: {
1515     /// CONSTPOOL_ENTRY - This instruction represents a floating constant pool
1516     /// in the function.  The first operand is the ID# for this instruction, the
1517     /// second is the index into the MachineConstantPool that this is, the third
1518     /// is the size in bytes of this constant pool entry.
1519     /// The required alignment is specified on the basic block holding this MI.
1520     unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
1521     unsigned CPIdx   = (unsigned)MI->getOperand(1).getIndex();
1522
1523     // If this is the first entry of the pool, mark it.
1524     if (!InConstantPool) {
1525       OutStreamer.EmitDataRegion(MCDR_DataRegion);
1526       InConstantPool = true;
1527     }
1528
1529     OutStreamer.EmitLabel(GetCPISymbol(LabelId));
1530
1531     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
1532     if (MCPE.isMachineConstantPoolEntry())
1533       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
1534     else
1535       EmitGlobalConstant(MCPE.Val.ConstVal);
1536     return;
1537   }
1538   case ARM::t2BR_JT: {
1539     // Lower and emit the instruction itself, then the jump table following it.
1540     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tMOVr)
1541       .addReg(ARM::PC)
1542       .addReg(MI->getOperand(0).getReg())
1543       // Add predicate operands.
1544       .addImm(ARMCC::AL)
1545       .addReg(0));
1546
1547     // Output the data for the jump table itself
1548     EmitJump2Table(MI);
1549     return;
1550   }
1551   case ARM::t2TBB_JT: {
1552     // Lower and emit the instruction itself, then the jump table following it.
1553     OutStreamer.EmitInstruction(MCInstBuilder(ARM::t2TBB)
1554       .addReg(ARM::PC)
1555       .addReg(MI->getOperand(0).getReg())
1556       // Add predicate operands.
1557       .addImm(ARMCC::AL)
1558       .addReg(0));
1559
1560     // Output the data for the jump table itself
1561     EmitJump2Table(MI);
1562     // Make sure the next instruction is 2-byte aligned.
1563     EmitAlignment(1);
1564     return;
1565   }
1566   case ARM::t2TBH_JT: {
1567     // Lower and emit the instruction itself, then the jump table following it.
1568     OutStreamer.EmitInstruction(MCInstBuilder(ARM::t2TBH)
1569       .addReg(ARM::PC)
1570       .addReg(MI->getOperand(0).getReg())
1571       // Add predicate operands.
1572       .addImm(ARMCC::AL)
1573       .addReg(0));
1574
1575     // Output the data for the jump table itself
1576     EmitJump2Table(MI);
1577     return;
1578   }
1579   case ARM::tBR_JTr:
1580   case ARM::BR_JTr: {
1581     // Lower and emit the instruction itself, then the jump table following it.
1582     // mov pc, target
1583     MCInst TmpInst;
1584     unsigned Opc = MI->getOpcode() == ARM::BR_JTr ?
1585       ARM::MOVr : ARM::tMOVr;
1586     TmpInst.setOpcode(Opc);
1587     TmpInst.addOperand(MCOperand::CreateReg(ARM::PC));
1588     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1589     // Add predicate operands.
1590     TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
1591     TmpInst.addOperand(MCOperand::CreateReg(0));
1592     // Add 's' bit operand (always reg0 for this)
1593     if (Opc == ARM::MOVr)
1594       TmpInst.addOperand(MCOperand::CreateReg(0));
1595     OutStreamer.EmitInstruction(TmpInst);
1596
1597     // Make sure the Thumb jump table is 4-byte aligned.
1598     if (Opc == ARM::tMOVr)
1599       EmitAlignment(2);
1600
1601     // Output the data for the jump table itself
1602     EmitJumpTable(MI);
1603     return;
1604   }
1605   case ARM::BR_JTm: {
1606     // Lower and emit the instruction itself, then the jump table following it.
1607     // ldr pc, target
1608     MCInst TmpInst;
1609     if (MI->getOperand(1).getReg() == 0) {
1610       // literal offset
1611       TmpInst.setOpcode(ARM::LDRi12);
1612       TmpInst.addOperand(MCOperand::CreateReg(ARM::PC));
1613       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1614       TmpInst.addOperand(MCOperand::CreateImm(MI->getOperand(2).getImm()));
1615     } else {
1616       TmpInst.setOpcode(ARM::LDRrs);
1617       TmpInst.addOperand(MCOperand::CreateReg(ARM::PC));
1618       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1619       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(1).getReg()));
1620       TmpInst.addOperand(MCOperand::CreateImm(0));
1621     }
1622     // Add predicate operands.
1623     TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
1624     TmpInst.addOperand(MCOperand::CreateReg(0));
1625     OutStreamer.EmitInstruction(TmpInst);
1626
1627     // Output the data for the jump table itself
1628     EmitJumpTable(MI);
1629     return;
1630   }
1631   case ARM::BR_JTadd: {
1632     // Lower and emit the instruction itself, then the jump table following it.
1633     // add pc, target, idx
1634     OutStreamer.EmitInstruction(MCInstBuilder(ARM::ADDrr)
1635       .addReg(ARM::PC)
1636       .addReg(MI->getOperand(0).getReg())
1637       .addReg(MI->getOperand(1).getReg())
1638       // Add predicate operands.
1639       .addImm(ARMCC::AL)
1640       .addReg(0)
1641       // Add 's' bit operand (always reg0 for this)
1642       .addReg(0));
1643
1644     // Output the data for the jump table itself
1645     EmitJumpTable(MI);
1646     return;
1647   }
1648   case ARM::TRAP: {
1649     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1650     // FIXME: Remove this special case when they do.
1651     if (!Subtarget->isTargetDarwin()) {
1652       //.long 0xe7ffdefe @ trap
1653       uint32_t Val = 0xe7ffdefeUL;
1654       OutStreamer.AddComment("trap");
1655       OutStreamer.EmitIntValue(Val, 4);
1656       return;
1657     }
1658     break;
1659   }
1660   case ARM::TRAPNaCl: {
1661     //.long 0xe7fedef0 @ trap
1662     uint32_t Val = 0xe7fedef0UL;
1663     OutStreamer.AddComment("trap");
1664     OutStreamer.EmitIntValue(Val, 4);
1665     return;
1666   }
1667   case ARM::tTRAP: {
1668     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1669     // FIXME: Remove this special case when they do.
1670     if (!Subtarget->isTargetDarwin()) {
1671       //.short 57086 @ trap
1672       uint16_t Val = 0xdefe;
1673       OutStreamer.AddComment("trap");
1674       OutStreamer.EmitIntValue(Val, 2);
1675       return;
1676     }
1677     break;
1678   }
1679   case ARM::t2Int_eh_sjlj_setjmp:
1680   case ARM::t2Int_eh_sjlj_setjmp_nofp:
1681   case ARM::tInt_eh_sjlj_setjmp: {
1682     // Two incoming args: GPR:$src, GPR:$val
1683     // mov $val, pc
1684     // adds $val, #7
1685     // str $val, [$src, #4]
1686     // movs r0, #0
1687     // b 1f
1688     // movs r0, #1
1689     // 1:
1690     unsigned SrcReg = MI->getOperand(0).getReg();
1691     unsigned ValReg = MI->getOperand(1).getReg();
1692     MCSymbol *Label = GetARMSJLJEHLabel();
1693     OutStreamer.AddComment("eh_setjmp begin");
1694     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tMOVr)
1695       .addReg(ValReg)
1696       .addReg(ARM::PC)
1697       // Predicate.
1698       .addImm(ARMCC::AL)
1699       .addReg(0));
1700
1701     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tADDi3)
1702       .addReg(ValReg)
1703       // 's' bit operand
1704       .addReg(ARM::CPSR)
1705       .addReg(ValReg)
1706       .addImm(7)
1707       // Predicate.
1708       .addImm(ARMCC::AL)
1709       .addReg(0));
1710
1711     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tSTRi)
1712       .addReg(ValReg)
1713       .addReg(SrcReg)
1714       // The offset immediate is #4. The operand value is scaled by 4 for the
1715       // tSTR instruction.
1716       .addImm(1)
1717       // Predicate.
1718       .addImm(ARMCC::AL)
1719       .addReg(0));
1720
1721     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tMOVi8)
1722       .addReg(ARM::R0)
1723       .addReg(ARM::CPSR)
1724       .addImm(0)
1725       // Predicate.
1726       .addImm(ARMCC::AL)
1727       .addReg(0));
1728
1729     const MCExpr *SymbolExpr = MCSymbolRefExpr::Create(Label, OutContext);
1730     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tB)
1731       .addExpr(SymbolExpr)
1732       .addImm(ARMCC::AL)
1733       .addReg(0));
1734
1735     OutStreamer.AddComment("eh_setjmp end");
1736     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tMOVi8)
1737       .addReg(ARM::R0)
1738       .addReg(ARM::CPSR)
1739       .addImm(1)
1740       // Predicate.
1741       .addImm(ARMCC::AL)
1742       .addReg(0));
1743
1744     OutStreamer.EmitLabel(Label);
1745     return;
1746   }
1747
1748   case ARM::Int_eh_sjlj_setjmp_nofp:
1749   case ARM::Int_eh_sjlj_setjmp: {
1750     // Two incoming args: GPR:$src, GPR:$val
1751     // add $val, pc, #8
1752     // str $val, [$src, #+4]
1753     // mov r0, #0
1754     // add pc, pc, #0
1755     // mov r0, #1
1756     unsigned SrcReg = MI->getOperand(0).getReg();
1757     unsigned ValReg = MI->getOperand(1).getReg();
1758
1759     OutStreamer.AddComment("eh_setjmp begin");
1760     OutStreamer.EmitInstruction(MCInstBuilder(ARM::ADDri)
1761       .addReg(ValReg)
1762       .addReg(ARM::PC)
1763       .addImm(8)
1764       // Predicate.
1765       .addImm(ARMCC::AL)
1766       .addReg(0)
1767       // 's' bit operand (always reg0 for this).
1768       .addReg(0));
1769
1770     OutStreamer.EmitInstruction(MCInstBuilder(ARM::STRi12)
1771       .addReg(ValReg)
1772       .addReg(SrcReg)
1773       .addImm(4)
1774       // Predicate.
1775       .addImm(ARMCC::AL)
1776       .addReg(0));
1777
1778     OutStreamer.EmitInstruction(MCInstBuilder(ARM::MOVi)
1779       .addReg(ARM::R0)
1780       .addImm(0)
1781       // Predicate.
1782       .addImm(ARMCC::AL)
1783       .addReg(0)
1784       // 's' bit operand (always reg0 for this).
1785       .addReg(0));
1786
1787     OutStreamer.EmitInstruction(MCInstBuilder(ARM::ADDri)
1788       .addReg(ARM::PC)
1789       .addReg(ARM::PC)
1790       .addImm(0)
1791       // Predicate.
1792       .addImm(ARMCC::AL)
1793       .addReg(0)
1794       // 's' bit operand (always reg0 for this).
1795       .addReg(0));
1796
1797     OutStreamer.AddComment("eh_setjmp end");
1798     OutStreamer.EmitInstruction(MCInstBuilder(ARM::MOVi)
1799       .addReg(ARM::R0)
1800       .addImm(1)
1801       // Predicate.
1802       .addImm(ARMCC::AL)
1803       .addReg(0)
1804       // 's' bit operand (always reg0 for this).
1805       .addReg(0));
1806     return;
1807   }
1808   case ARM::Int_eh_sjlj_longjmp: {
1809     // ldr sp, [$src, #8]
1810     // ldr $scratch, [$src, #4]
1811     // ldr r7, [$src]
1812     // bx $scratch
1813     unsigned SrcReg = MI->getOperand(0).getReg();
1814     unsigned ScratchReg = MI->getOperand(1).getReg();
1815     OutStreamer.EmitInstruction(MCInstBuilder(ARM::LDRi12)
1816       .addReg(ARM::SP)
1817       .addReg(SrcReg)
1818       .addImm(8)
1819       // Predicate.
1820       .addImm(ARMCC::AL)
1821       .addReg(0));
1822
1823     OutStreamer.EmitInstruction(MCInstBuilder(ARM::LDRi12)
1824       .addReg(ScratchReg)
1825       .addReg(SrcReg)
1826       .addImm(4)
1827       // Predicate.
1828       .addImm(ARMCC::AL)
1829       .addReg(0));
1830
1831     OutStreamer.EmitInstruction(MCInstBuilder(ARM::LDRi12)
1832       .addReg(ARM::R7)
1833       .addReg(SrcReg)
1834       .addImm(0)
1835       // Predicate.
1836       .addImm(ARMCC::AL)
1837       .addReg(0));
1838
1839     OutStreamer.EmitInstruction(MCInstBuilder(ARM::BX)
1840       .addReg(ScratchReg)
1841       // Predicate.
1842       .addImm(ARMCC::AL)
1843       .addReg(0));
1844     return;
1845   }
1846   case ARM::tInt_eh_sjlj_longjmp: {
1847     // ldr $scratch, [$src, #8]
1848     // mov sp, $scratch
1849     // ldr $scratch, [$src, #4]
1850     // ldr r7, [$src]
1851     // bx $scratch
1852     unsigned SrcReg = MI->getOperand(0).getReg();
1853     unsigned ScratchReg = MI->getOperand(1).getReg();
1854     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tLDRi)
1855       .addReg(ScratchReg)
1856       .addReg(SrcReg)
1857       // The offset immediate is #8. The operand value is scaled by 4 for the
1858       // tLDR instruction.
1859       .addImm(2)
1860       // Predicate.
1861       .addImm(ARMCC::AL)
1862       .addReg(0));
1863
1864     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tMOVr)
1865       .addReg(ARM::SP)
1866       .addReg(ScratchReg)
1867       // Predicate.
1868       .addImm(ARMCC::AL)
1869       .addReg(0));
1870
1871     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tLDRi)
1872       .addReg(ScratchReg)
1873       .addReg(SrcReg)
1874       .addImm(1)
1875       // Predicate.
1876       .addImm(ARMCC::AL)
1877       .addReg(0));
1878
1879     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tLDRi)
1880       .addReg(ARM::R7)
1881       .addReg(SrcReg)
1882       .addImm(0)
1883       // Predicate.
1884       .addImm(ARMCC::AL)
1885       .addReg(0));
1886
1887     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tBX)
1888       .addReg(ScratchReg)
1889       // Predicate.
1890       .addImm(ARMCC::AL)
1891       .addReg(0));
1892     return;
1893   }
1894   }
1895
1896   MCInst TmpInst;
1897   LowerARMMachineInstrToMCInst(MI, TmpInst, *this);
1898
1899   OutStreamer.EmitInstruction(TmpInst);
1900 }
1901
1902 //===----------------------------------------------------------------------===//
1903 // Target Registry Stuff
1904 //===----------------------------------------------------------------------===//
1905
1906 // Force static initialization.
1907 extern "C" void LLVMInitializeARMAsmPrinter() {
1908   RegisterAsmPrinter<ARMAsmPrinter> X(TheARMTarget);
1909   RegisterAsmPrinter<ARMAsmPrinter> Y(TheThumbTarget);
1910 }