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