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