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