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