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