LLVM API Documentation

ARMAsmPrinter.cpp
Go to the documentation of this file.
00001 //===-- ARMAsmPrinter.cpp - Print machine code to an ARM .s file ----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains a printer that converts from our internal representation
00011 // of machine-dependent LLVM code to GAS-format ARM assembly language.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "ARMAsmPrinter.h"
00016 #include "ARM.h"
00017 #include "ARMConstantPoolValue.h"
00018 #include "ARMFPUName.h"
00019 #include "ARMArchExtName.h"
00020 #include "ARMMachineFunctionInfo.h"
00021 #include "ARMTargetMachine.h"
00022 #include "ARMTargetObjectFile.h"
00023 #include "InstPrinter/ARMInstPrinter.h"
00024 #include "MCTargetDesc/ARMAddressingModes.h"
00025 #include "MCTargetDesc/ARMMCExpr.h"
00026 #include "llvm/ADT/SetVector.h"
00027 #include "llvm/ADT/SmallString.h"
00028 #include "llvm/CodeGen/MachineFunctionPass.h"
00029 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00030 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
00031 #include "llvm/IR/Constants.h"
00032 #include "llvm/IR/DataLayout.h"
00033 #include "llvm/IR/DebugInfo.h"
00034 #include "llvm/IR/Mangler.h"
00035 #include "llvm/IR/Module.h"
00036 #include "llvm/IR/Type.h"
00037 #include "llvm/MC/MCAsmInfo.h"
00038 #include "llvm/MC/MCAssembler.h"
00039 #include "llvm/MC/MCContext.h"
00040 #include "llvm/MC/MCELFStreamer.h"
00041 #include "llvm/MC/MCInst.h"
00042 #include "llvm/MC/MCInstBuilder.h"
00043 #include "llvm/MC/MCObjectStreamer.h"
00044 #include "llvm/MC/MCSectionMachO.h"
00045 #include "llvm/MC/MCStreamer.h"
00046 #include "llvm/MC/MCSymbol.h"
00047 #include "llvm/Support/ARMBuildAttributes.h"
00048 #include "llvm/Support/COFF.h"
00049 #include "llvm/Support/CommandLine.h"
00050 #include "llvm/Support/Debug.h"
00051 #include "llvm/Support/ELF.h"
00052 #include "llvm/Support/ErrorHandling.h"
00053 #include "llvm/Support/TargetRegistry.h"
00054 #include "llvm/Support/raw_ostream.h"
00055 #include "llvm/Target/TargetMachine.h"
00056 #include <cctype>
00057 using namespace llvm;
00058 
00059 #define DEBUG_TYPE "asm-printer"
00060 
00061 ARMAsmPrinter::ARMAsmPrinter(TargetMachine &TM,
00062                              std::unique_ptr<MCStreamer> Streamer)
00063     : AsmPrinter(TM, std::move(Streamer)), AFI(nullptr), MCP(nullptr),
00064       InConstantPool(false) {}
00065 
00066 void ARMAsmPrinter::EmitFunctionBodyEnd() {
00067   // Make sure to terminate any constant pools that were at the end
00068   // of the function.
00069   if (!InConstantPool)
00070     return;
00071   InConstantPool = false;
00072   OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
00073 }
00074 
00075 void ARMAsmPrinter::EmitFunctionEntryLabel() {
00076   if (AFI->isThumbFunction()) {
00077     OutStreamer.EmitAssemblerFlag(MCAF_Code16);
00078     OutStreamer.EmitThumbFunc(CurrentFnSym);
00079   }
00080 
00081   OutStreamer.EmitLabel(CurrentFnSym);
00082 }
00083 
00084 void ARMAsmPrinter::EmitXXStructor(const Constant *CV) {
00085   uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType());
00086   assert(Size && "C++ constructor pointer had zero size!");
00087 
00088   const GlobalValue *GV = dyn_cast<GlobalValue>(CV->stripPointerCasts());
00089   assert(GV && "C++ constructor pointer was not a GlobalValue!");
00090 
00091   const MCExpr *E = MCSymbolRefExpr::Create(GetARMGVSymbol(GV,
00092                                                            ARMII::MO_NO_FLAG),
00093                                             (Subtarget->isTargetELF()
00094                                              ? MCSymbolRefExpr::VK_ARM_TARGET1
00095                                              : MCSymbolRefExpr::VK_None),
00096                                             OutContext);
00097 
00098   OutStreamer.EmitValue(E, Size);
00099 }
00100 
00101 /// runOnMachineFunction - This uses the EmitInstruction()
00102 /// method to print assembly for each instruction.
00103 ///
00104 bool ARMAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
00105   AFI = MF.getInfo<ARMFunctionInfo>();
00106   MCP = MF.getConstantPool();
00107   Subtarget = &MF.getSubtarget<ARMSubtarget>();
00108 
00109   SetupMachineFunction(MF);
00110 
00111   if (Subtarget->isTargetCOFF()) {
00112     bool Internal = MF.getFunction()->hasInternalLinkage();
00113     COFF::SymbolStorageClass Scl = Internal ? COFF::IMAGE_SYM_CLASS_STATIC
00114                                             : COFF::IMAGE_SYM_CLASS_EXTERNAL;
00115     int Type = COFF::IMAGE_SYM_DTYPE_FUNCTION << COFF::SCT_COMPLEX_TYPE_SHIFT;
00116 
00117     OutStreamer.BeginCOFFSymbolDef(CurrentFnSym);
00118     OutStreamer.EmitCOFFSymbolStorageClass(Scl);
00119     OutStreamer.EmitCOFFSymbolType(Type);
00120     OutStreamer.EndCOFFSymbolDef();
00121   }
00122 
00123   // Have common code print out the function header with linkage info etc.
00124   EmitFunctionHeader();
00125 
00126   // Emit the rest of the function body.
00127   EmitFunctionBody();
00128 
00129   // If we need V4T thumb mode Register Indirect Jump pads, emit them.
00130   // These are created per function, rather than per TU, since it's
00131   // relatively easy to exceed the thumb branch range within a TU.
00132   if (! ThumbIndirectPads.empty()) {
00133     OutStreamer.EmitAssemblerFlag(MCAF_Code16);
00134     EmitAlignment(1);
00135     for (unsigned i = 0, e = ThumbIndirectPads.size(); i < e; i++) {
00136       OutStreamer.EmitLabel(ThumbIndirectPads[i].second);
00137       EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tBX)
00138         .addReg(ThumbIndirectPads[i].first)
00139         // Add predicate operands.
00140         .addImm(ARMCC::AL)
00141         .addReg(0));
00142     }
00143     ThumbIndirectPads.clear();
00144   }
00145 
00146   // We didn't modify anything.
00147   return false;
00148 }
00149 
00150 void ARMAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
00151                                  raw_ostream &O, const char *Modifier) {
00152   const MachineOperand &MO = MI->getOperand(OpNum);
00153   unsigned TF = MO.getTargetFlags();
00154 
00155   switch (MO.getType()) {
00156   default: llvm_unreachable("<unknown operand type>");
00157   case MachineOperand::MO_Register: {
00158     unsigned Reg = MO.getReg();
00159     assert(TargetRegisterInfo::isPhysicalRegister(Reg));
00160     assert(!MO.getSubReg() && "Subregs should be eliminated!");
00161     if(ARM::GPRPairRegClass.contains(Reg)) {
00162       const MachineFunction &MF = *MI->getParent()->getParent();
00163       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
00164       Reg = TRI->getSubReg(Reg, ARM::gsub_0);
00165     }
00166     O << ARMInstPrinter::getRegisterName(Reg);
00167     break;
00168   }
00169   case MachineOperand::MO_Immediate: {
00170     int64_t Imm = MO.getImm();
00171     O << '#';
00172     if ((Modifier && strcmp(Modifier, "lo16") == 0) ||
00173         (TF == ARMII::MO_LO16))
00174       O << ":lower16:";
00175     else if ((Modifier && strcmp(Modifier, "hi16") == 0) ||
00176              (TF == ARMII::MO_HI16))
00177       O << ":upper16:";
00178     O << Imm;
00179     break;
00180   }
00181   case MachineOperand::MO_MachineBasicBlock:
00182     O << *MO.getMBB()->getSymbol();
00183     return;
00184   case MachineOperand::MO_GlobalAddress: {
00185     const GlobalValue *GV = MO.getGlobal();
00186     if ((Modifier && strcmp(Modifier, "lo16") == 0) ||
00187         (TF & ARMII::MO_LO16))
00188       O << ":lower16:";
00189     else if ((Modifier && strcmp(Modifier, "hi16") == 0) ||
00190              (TF & ARMII::MO_HI16))
00191       O << ":upper16:";
00192     O << *GetARMGVSymbol(GV, TF);
00193 
00194     printOffset(MO.getOffset(), O);
00195     if (TF == ARMII::MO_PLT)
00196       O << "(PLT)";
00197     break;
00198   }
00199   case MachineOperand::MO_ConstantPoolIndex:
00200     O << *GetCPISymbol(MO.getIndex());
00201     break;
00202   }
00203 }
00204 
00205 //===--------------------------------------------------------------------===//
00206 
00207 MCSymbol *ARMAsmPrinter::
00208 GetARMJTIPICJumpTableLabel2(unsigned uid, unsigned uid2) const {
00209   const DataLayout *DL = TM.getDataLayout();
00210   SmallString<60> Name;
00211   raw_svector_ostream(Name) << DL->getPrivateGlobalPrefix() << "JTI"
00212     << getFunctionNumber() << '_' << uid << '_' << uid2;
00213   return OutContext.GetOrCreateSymbol(Name.str());
00214 }
00215 
00216 
00217 MCSymbol *ARMAsmPrinter::GetARMSJLJEHLabel() const {
00218   const DataLayout *DL = TM.getDataLayout();
00219   SmallString<60> Name;
00220   raw_svector_ostream(Name) << DL->getPrivateGlobalPrefix() << "SJLJEH"
00221     << getFunctionNumber();
00222   return OutContext.GetOrCreateSymbol(Name.str());
00223 }
00224 
00225 bool ARMAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
00226                                     unsigned AsmVariant, const char *ExtraCode,
00227                                     raw_ostream &O) {
00228   // Does this asm operand have a single letter operand modifier?
00229   if (ExtraCode && ExtraCode[0]) {
00230     if (ExtraCode[1] != 0) return true; // Unknown modifier.
00231 
00232     switch (ExtraCode[0]) {
00233     default:
00234       // See if this is a generic print operand
00235       return AsmPrinter::PrintAsmOperand(MI, OpNum, AsmVariant, ExtraCode, O);
00236     case 'a': // Print as a memory address.
00237       if (MI->getOperand(OpNum).isReg()) {
00238         O << "["
00239           << ARMInstPrinter::getRegisterName(MI->getOperand(OpNum).getReg())
00240           << "]";
00241         return false;
00242       }
00243       // Fallthrough
00244     case 'c': // Don't print "#" before an immediate operand.
00245       if (!MI->getOperand(OpNum).isImm())
00246         return true;
00247       O << MI->getOperand(OpNum).getImm();
00248       return false;
00249     case 'P': // Print a VFP double precision register.
00250     case 'q': // Print a NEON quad precision register.
00251       printOperand(MI, OpNum, O);
00252       return false;
00253     case 'y': // Print a VFP single precision register as indexed double.
00254       if (MI->getOperand(OpNum).isReg()) {
00255         unsigned Reg = MI->getOperand(OpNum).getReg();
00256         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
00257         // Find the 'd' register that has this 's' register as a sub-register,
00258         // and determine the lane number.
00259         for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) {
00260           if (!ARM::DPRRegClass.contains(*SR))
00261             continue;
00262           bool Lane0 = TRI->getSubReg(*SR, ARM::ssub_0) == Reg;
00263           O << ARMInstPrinter::getRegisterName(*SR) << (Lane0 ? "[0]" : "[1]");
00264           return false;
00265         }
00266       }
00267       return true;
00268     case 'B': // Bitwise inverse of integer or symbol without a preceding #.
00269       if (!MI->getOperand(OpNum).isImm())
00270         return true;
00271       O << ~(MI->getOperand(OpNum).getImm());
00272       return false;
00273     case 'L': // The low 16 bits of an immediate constant.
00274       if (!MI->getOperand(OpNum).isImm())
00275         return true;
00276       O << (MI->getOperand(OpNum).getImm() & 0xffff);
00277       return false;
00278     case 'M': { // A register range suitable for LDM/STM.
00279       if (!MI->getOperand(OpNum).isReg())
00280         return true;
00281       const MachineOperand &MO = MI->getOperand(OpNum);
00282       unsigned RegBegin = MO.getReg();
00283       // This takes advantage of the 2 operand-ness of ldm/stm and that we've
00284       // already got the operands in registers that are operands to the
00285       // inline asm statement.
00286       O << "{";
00287       if (ARM::GPRPairRegClass.contains(RegBegin)) {
00288         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
00289         unsigned Reg0 = TRI->getSubReg(RegBegin, ARM::gsub_0);
00290         O << ARMInstPrinter::getRegisterName(Reg0) << ", ";
00291         RegBegin = TRI->getSubReg(RegBegin, ARM::gsub_1);
00292       }
00293       O << ARMInstPrinter::getRegisterName(RegBegin);
00294 
00295       // FIXME: The register allocator not only may not have given us the
00296       // registers in sequence, but may not be in ascending registers. This
00297       // will require changes in the register allocator that'll need to be
00298       // propagated down here if the operands change.
00299       unsigned RegOps = OpNum + 1;
00300       while (MI->getOperand(RegOps).isReg()) {
00301         O << ", "
00302           << ARMInstPrinter::getRegisterName(MI->getOperand(RegOps).getReg());
00303         RegOps++;
00304       }
00305 
00306       O << "}";
00307 
00308       return false;
00309     }
00310     case 'R': // The most significant register of a pair.
00311     case 'Q': { // The least significant register of a pair.
00312       if (OpNum == 0)
00313         return true;
00314       const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
00315       if (!FlagsOP.isImm())
00316         return true;
00317       unsigned Flags = FlagsOP.getImm();
00318 
00319       // This operand may not be the one that actually provides the register. If
00320       // it's tied to a previous one then we should refer instead to that one
00321       // for registers and their classes.
00322       unsigned TiedIdx;
00323       if (InlineAsm::isUseOperandTiedToDef(Flags, TiedIdx)) {
00324         for (OpNum = InlineAsm::MIOp_FirstOperand; TiedIdx; --TiedIdx) {
00325           unsigned OpFlags = MI->getOperand(OpNum).getImm();
00326           OpNum += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
00327         }
00328         Flags = MI->getOperand(OpNum).getImm();
00329 
00330         // Later code expects OpNum to be pointing at the register rather than
00331         // the flags.
00332         OpNum += 1;
00333       }
00334 
00335       unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
00336       unsigned RC;
00337       InlineAsm::hasRegClassConstraint(Flags, RC);
00338       if (RC == ARM::GPRPairRegClassID) {
00339         if (NumVals != 1)
00340           return true;
00341         const MachineOperand &MO = MI->getOperand(OpNum);
00342         if (!MO.isReg())
00343           return true;
00344         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
00345         unsigned Reg = TRI->getSubReg(MO.getReg(), ExtraCode[0] == 'Q' ?
00346             ARM::gsub_0 : ARM::gsub_1);
00347         O << ARMInstPrinter::getRegisterName(Reg);
00348         return false;
00349       }
00350       if (NumVals != 2)
00351         return true;
00352       unsigned RegOp = ExtraCode[0] == 'Q' ? OpNum : OpNum + 1;
00353       if (RegOp >= MI->getNumOperands())
00354         return true;
00355       const MachineOperand &MO = MI->getOperand(RegOp);
00356       if (!MO.isReg())
00357         return true;
00358       unsigned Reg = MO.getReg();
00359       O << ARMInstPrinter::getRegisterName(Reg);
00360       return false;
00361     }
00362 
00363     case 'e': // The low doubleword register of a NEON quad register.
00364     case 'f': { // The high doubleword register of a NEON quad register.
00365       if (!MI->getOperand(OpNum).isReg())
00366         return true;
00367       unsigned Reg = MI->getOperand(OpNum).getReg();
00368       if (!ARM::QPRRegClass.contains(Reg))
00369         return true;
00370       const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
00371       unsigned SubReg = TRI->getSubReg(Reg, ExtraCode[0] == 'e' ?
00372                                        ARM::dsub_0 : ARM::dsub_1);
00373       O << ARMInstPrinter::getRegisterName(SubReg);
00374       return false;
00375     }
00376 
00377     // This modifier is not yet supported.
00378     case 'h': // A range of VFP/NEON registers suitable for VLD1/VST1.
00379       return true;
00380     case 'H': { // The highest-numbered register of a pair.
00381       const MachineOperand &MO = MI->getOperand(OpNum);
00382       if (!MO.isReg())
00383         return true;
00384       const MachineFunction &MF = *MI->getParent()->getParent();
00385       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
00386       unsigned Reg = MO.getReg();
00387       if(!ARM::GPRPairRegClass.contains(Reg))
00388         return false;
00389       Reg = TRI->getSubReg(Reg, ARM::gsub_1);
00390       O << ARMInstPrinter::getRegisterName(Reg);
00391       return false;
00392     }
00393     }
00394   }
00395 
00396   printOperand(MI, OpNum, O);
00397   return false;
00398 }
00399 
00400 bool ARMAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
00401                                           unsigned OpNum, unsigned AsmVariant,
00402                                           const char *ExtraCode,
00403                                           raw_ostream &O) {
00404   // Does this asm operand have a single letter operand modifier?
00405   if (ExtraCode && ExtraCode[0]) {
00406     if (ExtraCode[1] != 0) return true; // Unknown modifier.
00407 
00408     switch (ExtraCode[0]) {
00409       case 'A': // A memory operand for a VLD1/VST1 instruction.
00410       default: return true;  // Unknown modifier.
00411       case 'm': // The base register of a memory operand.
00412         if (!MI->getOperand(OpNum).isReg())
00413           return true;
00414         O << ARMInstPrinter::getRegisterName(MI->getOperand(OpNum).getReg());
00415         return false;
00416     }
00417   }
00418 
00419   const MachineOperand &MO = MI->getOperand(OpNum);
00420   assert(MO.isReg() && "unexpected inline asm memory operand");
00421   O << "[" << ARMInstPrinter::getRegisterName(MO.getReg()) << "]";
00422   return false;
00423 }
00424 
00425 static bool isThumb(const MCSubtargetInfo& STI) {
00426   return (STI.getFeatureBits() & ARM::ModeThumb) != 0;
00427 }
00428 
00429 void ARMAsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
00430                                      const MCSubtargetInfo *EndInfo) const {
00431   // If either end mode is unknown (EndInfo == NULL) or different than
00432   // the start mode, then restore the start mode.
00433   const bool WasThumb = isThumb(StartInfo);
00434   if (!EndInfo || WasThumb != isThumb(*EndInfo)) {
00435     OutStreamer.EmitAssemblerFlag(WasThumb ? MCAF_Code16 : MCAF_Code32);
00436   }
00437 }
00438 
00439 void ARMAsmPrinter::EmitStartOfAsmFile(Module &M) {
00440   Triple TT(TM.getTargetTriple());
00441   if (TT.isOSBinFormatMachO()) {
00442     Reloc::Model RelocM = TM.getRelocationModel();
00443     if (RelocM == Reloc::PIC_ || RelocM == Reloc::DynamicNoPIC) {
00444       // Declare all the text sections up front (before the DWARF sections
00445       // emitted by AsmPrinter::doInitialization) so the assembler will keep
00446       // them together at the beginning of the object file.  This helps
00447       // avoid out-of-range branches that are due a fundamental limitation of
00448       // the way symbol offsets are encoded with the current Darwin ARM
00449       // relocations.
00450       const TargetLoweringObjectFileMachO &TLOFMacho =
00451         static_cast<const TargetLoweringObjectFileMachO &>(
00452           getObjFileLowering());
00453 
00454       // Collect the set of sections our functions will go into.
00455       SetVector<const MCSection *, SmallVector<const MCSection *, 8>,
00456         SmallPtrSet<const MCSection *, 8> > TextSections;
00457       // Default text section comes first.
00458       TextSections.insert(TLOFMacho.getTextSection());
00459       // Now any user defined text sections from function attributes.
00460       for (Module::iterator F = M.begin(), e = M.end(); F != e; ++F)
00461         if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage())
00462           TextSections.insert(TLOFMacho.SectionForGlobal(F, *Mang, TM));
00463       // Now the coalescable sections.
00464       TextSections.insert(TLOFMacho.getTextCoalSection());
00465       TextSections.insert(TLOFMacho.getConstTextCoalSection());
00466 
00467       // Emit the sections in the .s file header to fix the order.
00468       for (unsigned i = 0, e = TextSections.size(); i != e; ++i)
00469         OutStreamer.SwitchSection(TextSections[i]);
00470 
00471       if (RelocM == Reloc::DynamicNoPIC) {
00472         const MCSection *sect =
00473           OutContext.getMachOSection("__TEXT", "__symbol_stub4",
00474                                      MachO::S_SYMBOL_STUBS,
00475                                      12, SectionKind::getText());
00476         OutStreamer.SwitchSection(sect);
00477       } else {
00478         const MCSection *sect =
00479           OutContext.getMachOSection("__TEXT", "__picsymbolstub4",
00480                                      MachO::S_SYMBOL_STUBS,
00481                                      16, SectionKind::getText());
00482         OutStreamer.SwitchSection(sect);
00483       }
00484       const MCSection *StaticInitSect =
00485         OutContext.getMachOSection("__TEXT", "__StaticInit",
00486                                    MachO::S_REGULAR |
00487                                    MachO::S_ATTR_PURE_INSTRUCTIONS,
00488                                    SectionKind::getText());
00489       OutStreamer.SwitchSection(StaticInitSect);
00490     }
00491 
00492     // Compiling with debug info should not affect the code
00493     // generation.  Ensure the cstring section comes before the
00494     // optional __DWARF secion. Otherwise, PC-relative loads would
00495     // have to use different instruction sequences at "-g" in order to
00496     // reach global data in the same object file.
00497     OutStreamer.SwitchSection(getObjFileLowering().getCStringSection());
00498   }
00499 
00500   // Use unified assembler syntax.
00501   OutStreamer.EmitAssemblerFlag(MCAF_SyntaxUnified);
00502 
00503   // Emit ARM Build Attributes
00504   if (TT.isOSBinFormatELF())
00505     emitAttributes();
00506 
00507   // Use the triple's architecture and subarchitecture to determine
00508   // if we're thumb for the purposes of the top level code16 assembler
00509   // flag.
00510   bool isThumb = TT.getArch() == Triple::thumb ||
00511                  TT.getArch() == Triple::thumbeb ||
00512                  TT.getSubArch() == Triple::ARMSubArch_v7m ||
00513                  TT.getSubArch() == Triple::ARMSubArch_v6m;
00514   if (!M.getModuleInlineAsm().empty() && isThumb)
00515     OutStreamer.EmitAssemblerFlag(MCAF_Code16);
00516 }
00517 
00518 static void
00519 emitNonLazySymbolPointer(MCStreamer &OutStreamer, MCSymbol *StubLabel,
00520                          MachineModuleInfoImpl::StubValueTy &MCSym) {
00521   // L_foo$stub:
00522   OutStreamer.EmitLabel(StubLabel);
00523   //   .indirect_symbol _foo
00524   OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
00525 
00526   if (MCSym.getInt())
00527     // External to current translation unit.
00528     OutStreamer.EmitIntValue(0, 4/*size*/);
00529   else
00530     // Internal to current translation unit.
00531     //
00532     // When we place the LSDA into the TEXT section, the type info
00533     // pointers need to be indirect and pc-rel. We accomplish this by
00534     // using NLPs; however, sometimes the types are local to the file.
00535     // We need to fill in the value for the NLP in those cases.
00536     OutStreamer.EmitValue(
00537         MCSymbolRefExpr::Create(MCSym.getPointer(), OutStreamer.getContext()),
00538         4 /*size*/);
00539 }
00540 
00541 
00542 void ARMAsmPrinter::EmitEndOfAsmFile(Module &M) {
00543   Triple TT(TM.getTargetTriple());
00544   if (TT.isOSBinFormatMachO()) {
00545     // All darwin targets use mach-o.
00546     const TargetLoweringObjectFileMachO &TLOFMacho =
00547       static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
00548     MachineModuleInfoMachO &MMIMacho =
00549       MMI->getObjFileInfo<MachineModuleInfoMachO>();
00550 
00551     // Output non-lazy-pointers for external and common global variables.
00552     MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetGVStubList();
00553 
00554     if (!Stubs.empty()) {
00555       // Switch with ".non_lazy_symbol_pointer" directive.
00556       OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
00557       EmitAlignment(2);
00558 
00559       for (auto &Stub : Stubs)
00560         emitNonLazySymbolPointer(OutStreamer, Stub.first, Stub.second);
00561 
00562       Stubs.clear();
00563       OutStreamer.AddBlankLine();
00564     }
00565 
00566     Stubs = MMIMacho.GetHiddenGVStubList();
00567     if (!Stubs.empty()) {
00568       OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
00569       EmitAlignment(2);
00570 
00571       for (auto &Stub : Stubs)
00572         emitNonLazySymbolPointer(OutStreamer, Stub.first, Stub.second);
00573 
00574       Stubs.clear();
00575       OutStreamer.AddBlankLine();
00576     }
00577 
00578     // Funny Darwin hack: This flag tells the linker that no global symbols
00579     // contain code that falls through to other global symbols (e.g. the obvious
00580     // implementation of multiple entry points).  If this doesn't occur, the
00581     // linker can safely perform dead code stripping.  Since LLVM never
00582     // generates code that does this, it is always safe to set.
00583     OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
00584   }
00585 
00586   // Emit a .data.rel section containing any stubs that were created.
00587   if (TT.isOSBinFormatELF()) {
00588     const TargetLoweringObjectFileELF &TLOFELF =
00589       static_cast<const TargetLoweringObjectFileELF &>(getObjFileLowering());
00590 
00591     MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
00592 
00593     // Output stubs for external and common global variables.
00594     MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
00595     if (!Stubs.empty()) {
00596       OutStreamer.SwitchSection(TLOFELF.getDataRelSection());
00597       const DataLayout *TD = TM.getDataLayout();
00598 
00599       for (auto &stub: Stubs) {
00600         OutStreamer.EmitLabel(stub.first);
00601         OutStreamer.EmitSymbolValue(stub.second.getPointer(),
00602                                     TD->getPointerSize(0));
00603       }
00604       Stubs.clear();
00605     }
00606   }
00607 }
00608 
00609 //===----------------------------------------------------------------------===//
00610 // Helper routines for EmitStartOfAsmFile() and EmitEndOfAsmFile()
00611 // FIXME:
00612 // The following seem like one-off assembler flags, but they actually need
00613 // to appear in the .ARM.attributes section in ELF.
00614 // Instead of subclassing the MCELFStreamer, we do the work here.
00615 
00616 static ARMBuildAttrs::CPUArch getArchForCPU(StringRef CPU,
00617                                             const ARMSubtarget *Subtarget) {
00618   if (CPU == "xscale")
00619     return ARMBuildAttrs::v5TEJ;
00620 
00621   if (Subtarget->hasV8Ops())
00622     return ARMBuildAttrs::v8;
00623   else if (Subtarget->hasV7Ops()) {
00624     if (Subtarget->isMClass() && Subtarget->hasThumb2DSP())
00625       return ARMBuildAttrs::v7E_M;
00626     return ARMBuildAttrs::v7;
00627   } else if (Subtarget->hasV6T2Ops())
00628     return ARMBuildAttrs::v6T2;
00629   else if (Subtarget->hasV6MOps())
00630     return ARMBuildAttrs::v6S_M;
00631   else if (Subtarget->hasV6Ops())
00632     return ARMBuildAttrs::v6;
00633   else if (Subtarget->hasV5TEOps())
00634     return ARMBuildAttrs::v5TE;
00635   else if (Subtarget->hasV5TOps())
00636     return ARMBuildAttrs::v5T;
00637   else if (Subtarget->hasV4TOps())
00638     return ARMBuildAttrs::v4T;
00639   else
00640     return ARMBuildAttrs::v4;
00641 }
00642 
00643 void ARMAsmPrinter::emitAttributes() {
00644   MCTargetStreamer &TS = *OutStreamer.getTargetStreamer();
00645   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
00646 
00647   ATS.emitTextAttribute(ARMBuildAttrs::conformance, "2.09");
00648 
00649   ATS.switchVendor("aeabi");
00650 
00651   // Compute ARM ELF Attributes based on the default subtarget that
00652   // we'd have constructed. The existing ARM behavior isn't LTO clean
00653   // anyhow.
00654   // FIXME: For ifunc related functions we could iterate over and look
00655   // for a feature string that doesn't match the default one.
00656   StringRef TT = TM.getTargetTriple();
00657   StringRef CPU = TM.getTargetCPU();
00658   StringRef FS = TM.getTargetFeatureString();
00659   std::string ArchFS = ARM_MC::ParseARMTriple(TT, CPU);
00660   if (!FS.empty()) {
00661     if (!ArchFS.empty())
00662       ArchFS = ArchFS + "," + FS.str();
00663     else
00664       ArchFS = FS;
00665   }
00666   const ARMBaseTargetMachine &ATM =
00667       static_cast<const ARMBaseTargetMachine &>(TM);
00668   const ARMSubtarget STI(TT, CPU, ArchFS, ATM, ATM.isLittleEndian());
00669 
00670   std::string CPUString = STI.getCPUString();
00671 
00672   if (CPUString != "generic") {
00673     // FIXME: remove krait check when GNU tools support krait cpu
00674     if (STI.isKrait()) {
00675       ATS.emitTextAttribute(ARMBuildAttrs::CPU_name, "cortex-a9");
00676       // We consider krait as a "cortex-a9" + hwdiv CPU
00677       // Enable hwdiv through ".arch_extension idiv"
00678       if (STI.hasDivide() || STI.hasDivideInARMMode())
00679         ATS.emitArchExtension(ARM::HWDIV);
00680     } else
00681       ATS.emitTextAttribute(ARMBuildAttrs::CPU_name, CPUString);
00682   }
00683 
00684   ATS.emitAttribute(ARMBuildAttrs::CPU_arch, getArchForCPU(CPUString, &STI));
00685 
00686   // Tag_CPU_arch_profile must have the default value of 0 when "Architecture
00687   // profile is not applicable (e.g. pre v7, or cross-profile code)".
00688   if (STI.hasV7Ops()) {
00689     if (STI.isAClass()) {
00690       ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
00691                         ARMBuildAttrs::ApplicationProfile);
00692     } else if (STI.isRClass()) {
00693       ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
00694                         ARMBuildAttrs::RealTimeProfile);
00695     } else if (STI.isMClass()) {
00696       ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
00697                         ARMBuildAttrs::MicroControllerProfile);
00698     }
00699   }
00700 
00701   ATS.emitAttribute(ARMBuildAttrs::ARM_ISA_use,
00702                     STI.hasARMOps() ? ARMBuildAttrs::Allowed
00703                                     : ARMBuildAttrs::Not_Allowed);
00704   if (STI.isThumb1Only()) {
00705     ATS.emitAttribute(ARMBuildAttrs::THUMB_ISA_use, ARMBuildAttrs::Allowed);
00706   } else if (STI.hasThumb2()) {
00707     ATS.emitAttribute(ARMBuildAttrs::THUMB_ISA_use,
00708                       ARMBuildAttrs::AllowThumb32);
00709   }
00710 
00711   if (STI.hasNEON()) {
00712     /* NEON is not exactly a VFP architecture, but GAS emit one of
00713      * neon/neon-fp-armv8/neon-vfpv4/vfpv3/vfpv2 for .fpu parameters */
00714     if (STI.hasFPARMv8()) {
00715       if (STI.hasCrypto())
00716         ATS.emitFPU(ARM::CRYPTO_NEON_FP_ARMV8);
00717       else
00718         ATS.emitFPU(ARM::NEON_FP_ARMV8);
00719     } else if (STI.hasVFP4())
00720       ATS.emitFPU(ARM::NEON_VFPV4);
00721     else
00722       ATS.emitFPU(ARM::NEON);
00723     // Emit Tag_Advanced_SIMD_arch for ARMv8 architecture
00724     if (STI.hasV8Ops())
00725       ATS.emitAttribute(ARMBuildAttrs::Advanced_SIMD_arch,
00726                         ARMBuildAttrs::AllowNeonARMv8);
00727   } else {
00728     if (STI.hasFPARMv8())
00729       // FPv5 and FP-ARMv8 have the same instructions, so are modeled as one
00730       // FPU, but there are two different names for it depending on the CPU.
00731       ATS.emitFPU(STI.hasD16() ? ARM::FPV5_D16 : ARM::FP_ARMV8);
00732     else if (STI.hasVFP4())
00733       ATS.emitFPU(STI.hasD16() ? ARM::VFPV4_D16 : ARM::VFPV4);
00734     else if (STI.hasVFP3())
00735       ATS.emitFPU(STI.hasD16() ? ARM::VFPV3_D16 : ARM::VFPV3);
00736     else if (STI.hasVFP2())
00737       ATS.emitFPU(ARM::VFPV2);
00738   }
00739 
00740   if (TM.getRelocationModel() == Reloc::PIC_) {
00741     // PIC specific attributes.
00742     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RW_data,
00743                       ARMBuildAttrs::AddressRWPCRel);
00744     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RO_data,
00745                       ARMBuildAttrs::AddressROPCRel);
00746     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
00747                       ARMBuildAttrs::AddressGOT);
00748   } else {
00749     // Allow direct addressing of imported data for all other relocation models.
00750     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
00751                       ARMBuildAttrs::AddressDirect);
00752   }
00753 
00754   // Signal various FP modes.
00755   if (!TM.Options.UnsafeFPMath) {
00756     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
00757                       ARMBuildAttrs::IEEEDenormals);
00758     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_exceptions, ARMBuildAttrs::Allowed);
00759 
00760     // If the user has permitted this code to choose the IEEE 754
00761     // rounding at run-time, emit the rounding attribute.
00762     if (TM.Options.HonorSignDependentRoundingFPMathOption)
00763       ATS.emitAttribute(ARMBuildAttrs::ABI_FP_rounding, ARMBuildAttrs::Allowed);
00764   } else {
00765     if (!STI.hasVFP2()) {
00766       // When the target doesn't have an FPU (by design or
00767       // intention), the assumptions made on the software support
00768       // mirror that of the equivalent hardware support *if it
00769       // existed*. For v7 and better we indicate that denormals are
00770       // flushed preserving sign, and for V6 we indicate that
00771       // denormals are flushed to positive zero.
00772       if (STI.hasV7Ops())
00773         ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
00774                           ARMBuildAttrs::PreserveFPSign);
00775     } else if (STI.hasVFP3()) {
00776       // In VFPv4, VFPv4U, VFPv3, or VFPv3U, it is preserved. That is,
00777       // the sign bit of the zero matches the sign bit of the input or
00778       // result that is being flushed to zero.
00779       ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
00780                         ARMBuildAttrs::PreserveFPSign);
00781     }
00782     // For VFPv2 implementations it is implementation defined as
00783     // to whether denormals are flushed to positive zero or to
00784     // whatever the sign of zero is (ARM v7AR ARM 2.7.5). Historically
00785     // LLVM has chosen to flush this to positive zero (most likely for
00786     // GCC compatibility), so that's the chosen value here (the
00787     // absence of its emission implies zero).
00788   }
00789 
00790   // TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath is the
00791   // equivalent of GCC's -ffinite-math-only flag.
00792   if (TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath)
00793     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
00794                       ARMBuildAttrs::Allowed);
00795   else
00796     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
00797                       ARMBuildAttrs::AllowIEE754);
00798 
00799   if (STI.allowsUnalignedMem())
00800     ATS.emitAttribute(ARMBuildAttrs::CPU_unaligned_access,
00801                       ARMBuildAttrs::Allowed);
00802   else
00803     ATS.emitAttribute(ARMBuildAttrs::CPU_unaligned_access,
00804                       ARMBuildAttrs::Not_Allowed);
00805 
00806   // FIXME: add more flags to ARMBuildAttributes.h
00807   // 8-bytes alignment stuff.
00808   ATS.emitAttribute(ARMBuildAttrs::ABI_align_needed, 1);
00809   ATS.emitAttribute(ARMBuildAttrs::ABI_align_preserved, 1);
00810 
00811   // ABI_HardFP_use attribute to indicate single precision FP.
00812   if (STI.isFPOnlySP())
00813     ATS.emitAttribute(ARMBuildAttrs::ABI_HardFP_use,
00814                       ARMBuildAttrs::HardFPSinglePrecision);
00815 
00816   // Hard float.  Use both S and D registers and conform to AAPCS-VFP.
00817   if (STI.isAAPCS_ABI() && TM.Options.FloatABIType == FloatABI::Hard)
00818     ATS.emitAttribute(ARMBuildAttrs::ABI_VFP_args, ARMBuildAttrs::HardFPAAPCS);
00819 
00820   // FIXME: Should we signal R9 usage?
00821 
00822   if (STI.hasFP16())
00823     ATS.emitAttribute(ARMBuildAttrs::FP_HP_extension, ARMBuildAttrs::AllowHPFP);
00824 
00825   // FIXME: To support emitting this build attribute as GCC does, the
00826   // -mfp16-format option and associated plumbing must be
00827   // supported. For now the __fp16 type is exposed by default, so this
00828   // attribute should be emitted with value 1.
00829   ATS.emitAttribute(ARMBuildAttrs::ABI_FP_16bit_format,
00830                     ARMBuildAttrs::FP16FormatIEEE);
00831 
00832   if (STI.hasMPExtension())
00833     ATS.emitAttribute(ARMBuildAttrs::MPextension_use, ARMBuildAttrs::AllowMP);
00834 
00835   // Hardware divide in ARM mode is part of base arch, starting from ARMv8.
00836   // If only Thumb hwdiv is present, it must also be in base arch (ARMv7-R/M).
00837   // It is not possible to produce DisallowDIV: if hwdiv is present in the base
00838   // arch, supplying -hwdiv downgrades the effective arch, via ClearImpliedBits.
00839   // AllowDIVExt is only emitted if hwdiv isn't available in the base arch;
00840   // otherwise, the default value (AllowDIVIfExists) applies.
00841   if (STI.hasDivideInARMMode() && !STI.hasV8Ops())
00842     ATS.emitAttribute(ARMBuildAttrs::DIV_use, ARMBuildAttrs::AllowDIVExt);
00843 
00844   if (MMI) {
00845     if (const Module *SourceModule = MMI->getModule()) {
00846       // ABI_PCS_wchar_t to indicate wchar_t width
00847       // FIXME: There is no way to emit value 0 (wchar_t prohibited).
00848       if (auto WCharWidthValue = mdconst::extract_or_null<ConstantInt>(
00849               SourceModule->getModuleFlag("wchar_size"))) {
00850         int WCharWidth = WCharWidthValue->getZExtValue();
00851         assert((WCharWidth == 2 || WCharWidth == 4) &&
00852                "wchar_t width must be 2 or 4 bytes");
00853         ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_wchar_t, WCharWidth);
00854       }
00855 
00856       // ABI_enum_size to indicate enum width
00857       // FIXME: There is no way to emit value 0 (enums prohibited) or value 3
00858       //        (all enums contain a value needing 32 bits to encode).
00859       if (auto EnumWidthValue = mdconst::extract_or_null<ConstantInt>(
00860               SourceModule->getModuleFlag("min_enum_size"))) {
00861         int EnumWidth = EnumWidthValue->getZExtValue();
00862         assert((EnumWidth == 1 || EnumWidth == 4) &&
00863                "Minimum enum width must be 1 or 4 bytes");
00864         int EnumBuildAttr = EnumWidth == 1 ? 1 : 2;
00865         ATS.emitAttribute(ARMBuildAttrs::ABI_enum_size, EnumBuildAttr);
00866       }
00867     }
00868   }
00869 
00870   // TODO: We currently only support either reserving the register, or treating
00871   // it as another callee-saved register, but not as SB or a TLS pointer; It
00872   // would instead be nicer to push this from the frontend as metadata, as we do
00873   // for the wchar and enum size tags
00874   if (STI.isR9Reserved())
00875     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use, ARMBuildAttrs::R9Reserved);
00876   else
00877     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use, ARMBuildAttrs::R9IsGPR);
00878 
00879   if (STI.hasTrustZone() && STI.hasVirtualization())
00880     ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
00881                       ARMBuildAttrs::AllowTZVirtualization);
00882   else if (STI.hasTrustZone())
00883     ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
00884                       ARMBuildAttrs::AllowTZ);
00885   else if (STI.hasVirtualization())
00886     ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
00887                       ARMBuildAttrs::AllowVirtualization);
00888 
00889   ATS.finishAttributeSection();
00890 }
00891 
00892 //===----------------------------------------------------------------------===//
00893 
00894 static MCSymbol *getPICLabel(const char *Prefix, unsigned FunctionNumber,
00895                              unsigned LabelId, MCContext &Ctx) {
00896 
00897   MCSymbol *Label = Ctx.GetOrCreateSymbol(Twine(Prefix)
00898                        + "PC" + Twine(FunctionNumber) + "_" + Twine(LabelId));
00899   return Label;
00900 }
00901 
00902 static MCSymbolRefExpr::VariantKind
00903 getModifierVariantKind(ARMCP::ARMCPModifier Modifier) {
00904   switch (Modifier) {
00905   case ARMCP::no_modifier: return MCSymbolRefExpr::VK_None;
00906   case ARMCP::TLSGD:       return MCSymbolRefExpr::VK_TLSGD;
00907   case ARMCP::TPOFF:       return MCSymbolRefExpr::VK_TPOFF;
00908   case ARMCP::GOTTPOFF:    return MCSymbolRefExpr::VK_GOTTPOFF;
00909   case ARMCP::GOT:         return MCSymbolRefExpr::VK_GOT;
00910   case ARMCP::GOTOFF:      return MCSymbolRefExpr::VK_GOTOFF;
00911   }
00912   llvm_unreachable("Invalid ARMCPModifier!");
00913 }
00914 
00915 MCSymbol *ARMAsmPrinter::GetARMGVSymbol(const GlobalValue *GV,
00916                                         unsigned char TargetFlags) {
00917   if (Subtarget->isTargetMachO()) {
00918     bool IsIndirect = (TargetFlags & ARMII::MO_NONLAZY) &&
00919       Subtarget->GVIsIndirectSymbol(GV, TM.getRelocationModel());
00920 
00921     if (!IsIndirect)
00922       return getSymbol(GV);
00923 
00924     // FIXME: Remove this when Darwin transition to @GOT like syntax.
00925     MCSymbol *MCSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
00926     MachineModuleInfoMachO &MMIMachO =
00927       MMI->getObjFileInfo<MachineModuleInfoMachO>();
00928     MachineModuleInfoImpl::StubValueTy &StubSym =
00929       GV->hasHiddenVisibility() ? MMIMachO.getHiddenGVStubEntry(MCSym)
00930                                 : MMIMachO.getGVStubEntry(MCSym);
00931     if (!StubSym.getPointer())
00932       StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV),
00933                                                    !GV->hasInternalLinkage());
00934     return MCSym;
00935   } else if (Subtarget->isTargetCOFF()) {
00936     assert(Subtarget->isTargetWindows() &&
00937            "Windows is the only supported COFF target");
00938 
00939     bool IsIndirect = (TargetFlags & ARMII::MO_DLLIMPORT);
00940     if (!IsIndirect)
00941       return getSymbol(GV);
00942 
00943     SmallString<128> Name;
00944     Name = "__imp_";
00945     getNameWithPrefix(Name, GV);
00946 
00947     return OutContext.GetOrCreateSymbol(Name);
00948   } else if (Subtarget->isTargetELF()) {
00949     return getSymbol(GV);
00950   }
00951   llvm_unreachable("unexpected target");
00952 }
00953 
00954 void ARMAsmPrinter::
00955 EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
00956   const DataLayout *DL = TM.getDataLayout();
00957   int Size = TM.getDataLayout()->getTypeAllocSize(MCPV->getType());
00958 
00959   ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
00960 
00961   MCSymbol *MCSym;
00962   if (ACPV->isLSDA()) {
00963     SmallString<128> Str;
00964     raw_svector_ostream OS(Str);
00965     OS << DL->getPrivateGlobalPrefix() << "_LSDA_" << getFunctionNumber();
00966     MCSym = OutContext.GetOrCreateSymbol(OS.str());
00967   } else if (ACPV->isBlockAddress()) {
00968     const BlockAddress *BA =
00969       cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress();
00970     MCSym = GetBlockAddressSymbol(BA);
00971   } else if (ACPV->isGlobalValue()) {
00972     const GlobalValue *GV = cast<ARMConstantPoolConstant>(ACPV)->getGV();
00973 
00974     // On Darwin, const-pool entries may get the "FOO$non_lazy_ptr" mangling, so
00975     // flag the global as MO_NONLAZY.
00976     unsigned char TF = Subtarget->isTargetMachO() ? ARMII::MO_NONLAZY : 0;
00977     MCSym = GetARMGVSymbol(GV, TF);
00978   } else if (ACPV->isMachineBasicBlock()) {
00979     const MachineBasicBlock *MBB = cast<ARMConstantPoolMBB>(ACPV)->getMBB();
00980     MCSym = MBB->getSymbol();
00981   } else {
00982     assert(ACPV->isExtSymbol() && "unrecognized constant pool value");
00983     const char *Sym = cast<ARMConstantPoolSymbol>(ACPV)->getSymbol();
00984     MCSym = GetExternalSymbolSymbol(Sym);
00985   }
00986 
00987   // Create an MCSymbol for the reference.
00988   const MCExpr *Expr =
00989     MCSymbolRefExpr::Create(MCSym, getModifierVariantKind(ACPV->getModifier()),
00990                             OutContext);
00991 
00992   if (ACPV->getPCAdjustment()) {
00993     MCSymbol *PCLabel = getPICLabel(DL->getPrivateGlobalPrefix(),
00994                                     getFunctionNumber(),
00995                                     ACPV->getLabelId(),
00996                                     OutContext);
00997     const MCExpr *PCRelExpr = MCSymbolRefExpr::Create(PCLabel, OutContext);
00998     PCRelExpr =
00999       MCBinaryExpr::CreateAdd(PCRelExpr,
01000                               MCConstantExpr::Create(ACPV->getPCAdjustment(),
01001                                                      OutContext),
01002                               OutContext);
01003     if (ACPV->mustAddCurrentAddress()) {
01004       // We want "(<expr> - .)", but MC doesn't have a concept of the '.'
01005       // label, so just emit a local label end reference that instead.
01006       MCSymbol *DotSym = OutContext.CreateTempSymbol();
01007       OutStreamer.EmitLabel(DotSym);
01008       const MCExpr *DotExpr = MCSymbolRefExpr::Create(DotSym, OutContext);
01009       PCRelExpr = MCBinaryExpr::CreateSub(PCRelExpr, DotExpr, OutContext);
01010     }
01011     Expr = MCBinaryExpr::CreateSub(Expr, PCRelExpr, OutContext);
01012   }
01013   OutStreamer.EmitValue(Expr, Size);
01014 }
01015 
01016 void ARMAsmPrinter::EmitJumpTable(const MachineInstr *MI) {
01017   unsigned Opcode = MI->getOpcode();
01018   int OpNum = 1;
01019   if (Opcode == ARM::BR_JTadd)
01020     OpNum = 2;
01021   else if (Opcode == ARM::BR_JTm)
01022     OpNum = 3;
01023 
01024   const MachineOperand &MO1 = MI->getOperand(OpNum);
01025   const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
01026   unsigned JTI = MO1.getIndex();
01027 
01028   // Emit a label for the jump table.
01029   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel2(JTI, MO2.getImm());
01030   OutStreamer.EmitLabel(JTISymbol);
01031 
01032   // Mark the jump table as data-in-code.
01033   OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
01034 
01035   // Emit each entry of the table.
01036   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
01037   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
01038   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
01039 
01040   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
01041     MachineBasicBlock *MBB = JTBBs[i];
01042     // Construct an MCExpr for the entry. We want a value of the form:
01043     // (BasicBlockAddr - TableBeginAddr)
01044     //
01045     // For example, a table with entries jumping to basic blocks BB0 and BB1
01046     // would look like:
01047     // LJTI_0_0:
01048     //    .word (LBB0 - LJTI_0_0)
01049     //    .word (LBB1 - LJTI_0_0)
01050     const MCExpr *Expr = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
01051 
01052     if (TM.getRelocationModel() == Reloc::PIC_)
01053       Expr = MCBinaryExpr::CreateSub(Expr, MCSymbolRefExpr::Create(JTISymbol,
01054                                                                    OutContext),
01055                                      OutContext);
01056     // If we're generating a table of Thumb addresses in static relocation
01057     // model, we need to add one to keep interworking correctly.
01058     else if (AFI->isThumbFunction())
01059       Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(1,OutContext),
01060                                      OutContext);
01061     OutStreamer.EmitValue(Expr, 4);
01062   }
01063   // Mark the end of jump table data-in-code region.
01064   OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
01065 }
01066 
01067 void ARMAsmPrinter::EmitJump2Table(const MachineInstr *MI) {
01068   unsigned Opcode = MI->getOpcode();
01069   int OpNum = (Opcode == ARM::t2BR_JT) ? 2 : 1;
01070   const MachineOperand &MO1 = MI->getOperand(OpNum);
01071   const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
01072   unsigned JTI = MO1.getIndex();
01073 
01074   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel2(JTI, MO2.getImm());
01075   OutStreamer.EmitLabel(JTISymbol);
01076 
01077   // Emit each entry of the table.
01078   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
01079   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
01080   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
01081   unsigned OffsetWidth = 4;
01082   if (MI->getOpcode() == ARM::t2TBB_JT) {
01083     OffsetWidth = 1;
01084     // Mark the jump table as data-in-code.
01085     OutStreamer.EmitDataRegion(MCDR_DataRegionJT8);
01086   } else if (MI->getOpcode() == ARM::t2TBH_JT) {
01087     OffsetWidth = 2;
01088     // Mark the jump table as data-in-code.
01089     OutStreamer.EmitDataRegion(MCDR_DataRegionJT16);
01090   }
01091 
01092   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
01093     MachineBasicBlock *MBB = JTBBs[i];
01094     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::Create(MBB->getSymbol(),
01095                                                           OutContext);
01096     // If this isn't a TBB or TBH, the entries are direct branch instructions.
01097     if (OffsetWidth == 4) {
01098       EmitToStreamer(OutStreamer, MCInstBuilder(ARM::t2B)
01099         .addExpr(MBBSymbolExpr)
01100         .addImm(ARMCC::AL)
01101         .addReg(0));
01102       continue;
01103     }
01104     // Otherwise it's an offset from the dispatch instruction. Construct an
01105     // MCExpr for the entry. We want a value of the form:
01106     // (BasicBlockAddr - TableBeginAddr) / 2
01107     //
01108     // For example, a TBB table with entries jumping to basic blocks BB0 and BB1
01109     // would look like:
01110     // LJTI_0_0:
01111     //    .byte (LBB0 - LJTI_0_0) / 2
01112     //    .byte (LBB1 - LJTI_0_0) / 2
01113     const MCExpr *Expr =
01114       MCBinaryExpr::CreateSub(MBBSymbolExpr,
01115                               MCSymbolRefExpr::Create(JTISymbol, OutContext),
01116                               OutContext);
01117     Expr = MCBinaryExpr::CreateDiv(Expr, MCConstantExpr::Create(2, OutContext),
01118                                    OutContext);
01119     OutStreamer.EmitValue(Expr, OffsetWidth);
01120   }
01121   // Mark the end of jump table data-in-code region. 32-bit offsets use
01122   // actual branch instructions here, so we don't mark those as a data-region
01123   // at all.
01124   if (OffsetWidth != 4)
01125     OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
01126 }
01127 
01128 void ARMAsmPrinter::EmitUnwindingInstruction(const MachineInstr *MI) {
01129   assert(MI->getFlag(MachineInstr::FrameSetup) &&
01130       "Only instruction which are involved into frame setup code are allowed");
01131 
01132   MCTargetStreamer &TS = *OutStreamer.getTargetStreamer();
01133   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
01134   const MachineFunction &MF = *MI->getParent()->getParent();
01135   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
01136   const ARMFunctionInfo &AFI = *MF.getInfo<ARMFunctionInfo>();
01137 
01138   unsigned FramePtr = RegInfo->getFrameRegister(MF);
01139   unsigned Opc = MI->getOpcode();
01140   unsigned SrcReg, DstReg;
01141 
01142   if (Opc == ARM::tPUSH || Opc == ARM::tLDRpci) {
01143     // Two special cases:
01144     // 1) tPUSH does not have src/dst regs.
01145     // 2) for Thumb1 code we sometimes materialize the constant via constpool
01146     // load. Yes, this is pretty fragile, but for now I don't see better
01147     // way... :(
01148     SrcReg = DstReg = ARM::SP;
01149   } else {
01150     SrcReg = MI->getOperand(1).getReg();
01151     DstReg = MI->getOperand(0).getReg();
01152   }
01153 
01154   // Try to figure out the unwinding opcode out of src / dst regs.
01155   if (MI->mayStore()) {
01156     // Register saves.
01157     assert(DstReg == ARM::SP &&
01158            "Only stack pointer as a destination reg is supported");
01159 
01160     SmallVector<unsigned, 4> RegList;
01161     // Skip src & dst reg, and pred ops.
01162     unsigned StartOp = 2 + 2;
01163     // Use all the operands.
01164     unsigned NumOffset = 0;
01165 
01166     switch (Opc) {
01167     default:
01168       MI->dump();
01169       llvm_unreachable("Unsupported opcode for unwinding information");
01170     case ARM::tPUSH:
01171       // Special case here: no src & dst reg, but two extra imp ops.
01172       StartOp = 2; NumOffset = 2;
01173     case ARM::STMDB_UPD:
01174     case ARM::t2STMDB_UPD:
01175     case ARM::VSTMDDB_UPD:
01176       assert(SrcReg == ARM::SP &&
01177              "Only stack pointer as a source reg is supported");
01178       for (unsigned i = StartOp, NumOps = MI->getNumOperands() - NumOffset;
01179            i != NumOps; ++i) {
01180         const MachineOperand &MO = MI->getOperand(i);
01181         // Actually, there should never be any impdef stuff here. Skip it
01182         // temporary to workaround PR11902.
01183         if (MO.isImplicit())
01184           continue;
01185         RegList.push_back(MO.getReg());
01186       }
01187       break;
01188     case ARM::STR_PRE_IMM:
01189     case ARM::STR_PRE_REG:
01190     case ARM::t2STR_PRE:
01191       assert(MI->getOperand(2).getReg() == ARM::SP &&
01192              "Only stack pointer as a source reg is supported");
01193       RegList.push_back(SrcReg);
01194       break;
01195     }
01196     if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM)
01197       ATS.emitRegSave(RegList, Opc == ARM::VSTMDDB_UPD);
01198   } else {
01199     // Changes of stack / frame pointer.
01200     if (SrcReg == ARM::SP) {
01201       int64_t Offset = 0;
01202       switch (Opc) {
01203       default:
01204         MI->dump();
01205         llvm_unreachable("Unsupported opcode for unwinding information");
01206       case ARM::MOVr:
01207       case ARM::tMOVr:
01208         Offset = 0;
01209         break;
01210       case ARM::ADDri:
01211         Offset = -MI->getOperand(2).getImm();
01212         break;
01213       case ARM::SUBri:
01214       case ARM::t2SUBri:
01215         Offset = MI->getOperand(2).getImm();
01216         break;
01217       case ARM::tSUBspi:
01218         Offset = MI->getOperand(2).getImm()*4;
01219         break;
01220       case ARM::tADDspi:
01221       case ARM::tADDrSPi:
01222         Offset = -MI->getOperand(2).getImm()*4;
01223         break;
01224       case ARM::tLDRpci: {
01225         // Grab the constpool index and check, whether it corresponds to
01226         // original or cloned constpool entry.
01227         unsigned CPI = MI->getOperand(1).getIndex();
01228         const MachineConstantPool *MCP = MF.getConstantPool();
01229         if (CPI >= MCP->getConstants().size())
01230           CPI = AFI.getOriginalCPIdx(CPI);
01231         assert(CPI != -1U && "Invalid constpool index");
01232 
01233         // Derive the actual offset.
01234         const MachineConstantPoolEntry &CPE = MCP->getConstants()[CPI];
01235         assert(!CPE.isMachineConstantPoolEntry() && "Invalid constpool entry");
01236         // FIXME: Check for user, it should be "add" instruction!
01237         Offset = -cast<ConstantInt>(CPE.Val.ConstVal)->getSExtValue();
01238         break;
01239       }
01240       }
01241 
01242       if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM) {
01243         if (DstReg == FramePtr && FramePtr != ARM::SP)
01244           // Set-up of the frame pointer. Positive values correspond to "add"
01245           // instruction.
01246           ATS.emitSetFP(FramePtr, ARM::SP, -Offset);
01247         else if (DstReg == ARM::SP) {
01248           // Change of SP by an offset. Positive values correspond to "sub"
01249           // instruction.
01250           ATS.emitPad(Offset);
01251         } else {
01252           // Move of SP to a register.  Positive values correspond to an "add"
01253           // instruction.
01254           ATS.emitMovSP(DstReg, -Offset);
01255         }
01256       }
01257     } else if (DstReg == ARM::SP) {
01258       MI->dump();
01259       llvm_unreachable("Unsupported opcode for unwinding information");
01260     }
01261     else {
01262       MI->dump();
01263       llvm_unreachable("Unsupported opcode for unwinding information");
01264     }
01265   }
01266 }
01267 
01268 // Simple pseudo-instructions have their lowering (with expansion to real
01269 // instructions) auto-generated.
01270 #include "ARMGenMCPseudoLowering.inc"
01271 
01272 void ARMAsmPrinter::EmitInstruction(const MachineInstr *MI) {
01273   const DataLayout *DL = TM.getDataLayout();
01274 
01275   // If we just ended a constant pool, mark it as such.
01276   if (InConstantPool && MI->getOpcode() != ARM::CONSTPOOL_ENTRY) {
01277     OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
01278     InConstantPool = false;
01279   }
01280 
01281   // Emit unwinding stuff for frame-related instructions
01282   if (Subtarget->isTargetEHABICompatible() &&
01283        MI->getFlag(MachineInstr::FrameSetup))
01284     EmitUnwindingInstruction(MI);
01285 
01286   // Do any auto-generated pseudo lowerings.
01287   if (emitPseudoExpansionLowering(OutStreamer, MI))
01288     return;
01289 
01290   assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
01291          "Pseudo flag setting opcode should be expanded early");
01292 
01293   // Check for manual lowerings.
01294   unsigned Opc = MI->getOpcode();
01295   switch (Opc) {
01296   case ARM::t2MOVi32imm: llvm_unreachable("Should be lowered by thumb2it pass");
01297   case ARM::DBG_VALUE: llvm_unreachable("Should be handled by generic printing");
01298   case ARM::LEApcrel:
01299   case ARM::tLEApcrel:
01300   case ARM::t2LEApcrel: {
01301     // FIXME: Need to also handle globals and externals
01302     MCSymbol *CPISymbol = GetCPISymbol(MI->getOperand(1).getIndex());
01303     EmitToStreamer(OutStreamer, MCInstBuilder(MI->getOpcode() ==
01304                                               ARM::t2LEApcrel ? ARM::t2ADR
01305                   : (MI->getOpcode() == ARM::tLEApcrel ? ARM::tADR
01306                      : ARM::ADR))
01307       .addReg(MI->getOperand(0).getReg())
01308       .addExpr(MCSymbolRefExpr::Create(CPISymbol, OutContext))
01309       // Add predicate operands.
01310       .addImm(MI->getOperand(2).getImm())
01311       .addReg(MI->getOperand(3).getReg()));
01312     return;
01313   }
01314   case ARM::LEApcrelJT:
01315   case ARM::tLEApcrelJT:
01316   case ARM::t2LEApcrelJT: {
01317     MCSymbol *JTIPICSymbol =
01318       GetARMJTIPICJumpTableLabel2(MI->getOperand(1).getIndex(),
01319                                   MI->getOperand(2).getImm());
01320     EmitToStreamer(OutStreamer, MCInstBuilder(MI->getOpcode() ==
01321                                               ARM::t2LEApcrelJT ? ARM::t2ADR
01322                   : (MI->getOpcode() == ARM::tLEApcrelJT ? ARM::tADR
01323                      : ARM::ADR))
01324       .addReg(MI->getOperand(0).getReg())
01325       .addExpr(MCSymbolRefExpr::Create(JTIPICSymbol, OutContext))
01326       // Add predicate operands.
01327       .addImm(MI->getOperand(3).getImm())
01328       .addReg(MI->getOperand(4).getReg()));
01329     return;
01330   }
01331   // Darwin call instructions are just normal call instructions with different
01332   // clobber semantics (they clobber R9).
01333   case ARM::BX_CALL: {
01334     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVr)
01335       .addReg(ARM::LR)
01336       .addReg(ARM::PC)
01337       // Add predicate operands.
01338       .addImm(ARMCC::AL)
01339       .addReg(0)
01340       // Add 's' bit operand (always reg0 for this)
01341       .addReg(0));
01342 
01343     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::BX)
01344       .addReg(MI->getOperand(0).getReg()));
01345     return;
01346   }
01347   case ARM::tBX_CALL: {
01348     if (Subtarget->hasV5TOps())
01349       llvm_unreachable("Expected BLX to be selected for v5t+");
01350 
01351     // On ARM v4t, when doing a call from thumb mode, we need to ensure
01352     // that the saved lr has its LSB set correctly (the arch doesn't
01353     // have blx).
01354     // So here we generate a bl to a small jump pad that does bx rN.
01355     // The jump pads are emitted after the function body.
01356 
01357     unsigned TReg = MI->getOperand(0).getReg();
01358     MCSymbol *TRegSym = nullptr;
01359     for (unsigned i = 0, e = ThumbIndirectPads.size(); i < e; i++) {
01360       if (ThumbIndirectPads[i].first == TReg) {
01361         TRegSym = ThumbIndirectPads[i].second;
01362         break;
01363       }
01364     }
01365 
01366     if (!TRegSym) {
01367       TRegSym = OutContext.CreateTempSymbol();
01368       ThumbIndirectPads.push_back(std::make_pair(TReg, TRegSym));
01369     }
01370 
01371     // Create a link-saving branch to the Reg Indirect Jump Pad.
01372     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tBL)
01373         // Predicate comes first here.
01374         .addImm(ARMCC::AL).addReg(0)
01375         .addExpr(MCSymbolRefExpr::Create(TRegSym, OutContext)));
01376     return;
01377   }
01378   case ARM::BMOVPCRX_CALL: {
01379     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVr)
01380       .addReg(ARM::LR)
01381       .addReg(ARM::PC)
01382       // Add predicate operands.
01383       .addImm(ARMCC::AL)
01384       .addReg(0)
01385       // Add 's' bit operand (always reg0 for this)
01386       .addReg(0));
01387 
01388     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVr)
01389       .addReg(ARM::PC)
01390       .addReg(MI->getOperand(0).getReg())
01391       // Add predicate operands.
01392       .addImm(ARMCC::AL)
01393       .addReg(0)
01394       // Add 's' bit operand (always reg0 for this)
01395       .addReg(0));
01396     return;
01397   }
01398   case ARM::BMOVPCB_CALL: {
01399     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVr)
01400       .addReg(ARM::LR)
01401       .addReg(ARM::PC)
01402       // Add predicate operands.
01403       .addImm(ARMCC::AL)
01404       .addReg(0)
01405       // Add 's' bit operand (always reg0 for this)
01406       .addReg(0));
01407 
01408     const MachineOperand &Op = MI->getOperand(0);
01409     const GlobalValue *GV = Op.getGlobal();
01410     const unsigned TF = Op.getTargetFlags();
01411     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
01412     const MCExpr *GVSymExpr = MCSymbolRefExpr::Create(GVSym, OutContext);
01413     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::Bcc)
01414       .addExpr(GVSymExpr)
01415       // Add predicate operands.
01416       .addImm(ARMCC::AL)
01417       .addReg(0));
01418     return;
01419   }
01420   case ARM::MOVi16_ga_pcrel:
01421   case ARM::t2MOVi16_ga_pcrel: {
01422     MCInst TmpInst;
01423     TmpInst.setOpcode(Opc == ARM::MOVi16_ga_pcrel? ARM::MOVi16 : ARM::t2MOVi16);
01424     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
01425 
01426     unsigned TF = MI->getOperand(1).getTargetFlags();
01427     const GlobalValue *GV = MI->getOperand(1).getGlobal();
01428     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
01429     const MCExpr *GVSymExpr = MCSymbolRefExpr::Create(GVSym, OutContext);
01430 
01431     MCSymbol *LabelSym = getPICLabel(DL->getPrivateGlobalPrefix(),
01432                                      getFunctionNumber(),
01433                                      MI->getOperand(2).getImm(), OutContext);
01434     const MCExpr *LabelSymExpr= MCSymbolRefExpr::Create(LabelSym, OutContext);
01435     unsigned PCAdj = (Opc == ARM::MOVi16_ga_pcrel) ? 8 : 4;
01436     const MCExpr *PCRelExpr =
01437       ARMMCExpr::CreateLower16(MCBinaryExpr::CreateSub(GVSymExpr,
01438                                       MCBinaryExpr::CreateAdd(LabelSymExpr,
01439                                       MCConstantExpr::Create(PCAdj, OutContext),
01440                                       OutContext), OutContext), OutContext);
01441       TmpInst.addOperand(MCOperand::CreateExpr(PCRelExpr));
01442 
01443     // Add predicate operands.
01444     TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
01445     TmpInst.addOperand(MCOperand::CreateReg(0));
01446     // Add 's' bit operand (always reg0 for this)
01447     TmpInst.addOperand(MCOperand::CreateReg(0));
01448     EmitToStreamer(OutStreamer, TmpInst);
01449     return;
01450   }
01451   case ARM::MOVTi16_ga_pcrel:
01452   case ARM::t2MOVTi16_ga_pcrel: {
01453     MCInst TmpInst;
01454     TmpInst.setOpcode(Opc == ARM::MOVTi16_ga_pcrel
01455                       ? ARM::MOVTi16 : ARM::t2MOVTi16);
01456     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
01457     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(1).getReg()));
01458 
01459     unsigned TF = MI->getOperand(2).getTargetFlags();
01460     const GlobalValue *GV = MI->getOperand(2).getGlobal();
01461     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
01462     const MCExpr *GVSymExpr = MCSymbolRefExpr::Create(GVSym, OutContext);
01463 
01464     MCSymbol *LabelSym = getPICLabel(DL->getPrivateGlobalPrefix(),
01465                                      getFunctionNumber(),
01466                                      MI->getOperand(3).getImm(), OutContext);
01467     const MCExpr *LabelSymExpr= MCSymbolRefExpr::Create(LabelSym, OutContext);
01468     unsigned PCAdj = (Opc == ARM::MOVTi16_ga_pcrel) ? 8 : 4;
01469     const MCExpr *PCRelExpr =
01470         ARMMCExpr::CreateUpper16(MCBinaryExpr::CreateSub(GVSymExpr,
01471                                    MCBinaryExpr::CreateAdd(LabelSymExpr,
01472                                       MCConstantExpr::Create(PCAdj, OutContext),
01473                                           OutContext), OutContext), OutContext);
01474       TmpInst.addOperand(MCOperand::CreateExpr(PCRelExpr));
01475     // Add predicate operands.
01476     TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
01477     TmpInst.addOperand(MCOperand::CreateReg(0));
01478     // Add 's' bit operand (always reg0 for this)
01479     TmpInst.addOperand(MCOperand::CreateReg(0));
01480     EmitToStreamer(OutStreamer, TmpInst);
01481     return;
01482   }
01483   case ARM::tPICADD: {
01484     // This is a pseudo op for a label + instruction sequence, which looks like:
01485     // LPC0:
01486     //     add r0, pc
01487     // This adds the address of LPC0 to r0.
01488 
01489     // Emit the label.
01490     OutStreamer.EmitLabel(getPICLabel(DL->getPrivateGlobalPrefix(),
01491                           getFunctionNumber(), MI->getOperand(2).getImm(),
01492                           OutContext));
01493 
01494     // Form and emit the add.
01495     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tADDhirr)
01496       .addReg(MI->getOperand(0).getReg())
01497       .addReg(MI->getOperand(0).getReg())
01498       .addReg(ARM::PC)
01499       // Add predicate operands.
01500       .addImm(ARMCC::AL)
01501       .addReg(0));
01502     return;
01503   }
01504   case ARM::PICADD: {
01505     // This is a pseudo op for a label + instruction sequence, which looks like:
01506     // LPC0:
01507     //     add r0, pc, r0
01508     // This adds the address of LPC0 to r0.
01509 
01510     // Emit the label.
01511     OutStreamer.EmitLabel(getPICLabel(DL->getPrivateGlobalPrefix(),
01512                           getFunctionNumber(), MI->getOperand(2).getImm(),
01513                           OutContext));
01514 
01515     // Form and emit the add.
01516     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::ADDrr)
01517       .addReg(MI->getOperand(0).getReg())
01518       .addReg(ARM::PC)
01519       .addReg(MI->getOperand(1).getReg())
01520       // Add predicate operands.
01521       .addImm(MI->getOperand(3).getImm())
01522       .addReg(MI->getOperand(4).getReg())
01523       // Add 's' bit operand (always reg0 for this)
01524       .addReg(0));
01525     return;
01526   }
01527   case ARM::PICSTR:
01528   case ARM::PICSTRB:
01529   case ARM::PICSTRH:
01530   case ARM::PICLDR:
01531   case ARM::PICLDRB:
01532   case ARM::PICLDRH:
01533   case ARM::PICLDRSB:
01534   case ARM::PICLDRSH: {
01535     // This is a pseudo op for a label + instruction sequence, which looks like:
01536     // LPC0:
01537     //     OP r0, [pc, r0]
01538     // The LCP0 label is referenced by a constant pool entry in order to get
01539     // a PC-relative address at the ldr instruction.
01540 
01541     // Emit the label.
01542     OutStreamer.EmitLabel(getPICLabel(DL->getPrivateGlobalPrefix(),
01543                           getFunctionNumber(), MI->getOperand(2).getImm(),
01544                           OutContext));
01545 
01546     // Form and emit the load
01547     unsigned Opcode;
01548     switch (MI->getOpcode()) {
01549     default:
01550       llvm_unreachable("Unexpected opcode!");
01551     case ARM::PICSTR:   Opcode = ARM::STRrs; break;
01552     case ARM::PICSTRB:  Opcode = ARM::STRBrs; break;
01553     case ARM::PICSTRH:  Opcode = ARM::STRH; break;
01554     case ARM::PICLDR:   Opcode = ARM::LDRrs; break;
01555     case ARM::PICLDRB:  Opcode = ARM::LDRBrs; break;
01556     case ARM::PICLDRH:  Opcode = ARM::LDRH; break;
01557     case ARM::PICLDRSB: Opcode = ARM::LDRSB; break;
01558     case ARM::PICLDRSH: Opcode = ARM::LDRSH; break;
01559     }
01560     EmitToStreamer(OutStreamer, MCInstBuilder(Opcode)
01561       .addReg(MI->getOperand(0).getReg())
01562       .addReg(ARM::PC)
01563       .addReg(MI->getOperand(1).getReg())
01564       .addImm(0)
01565       // Add predicate operands.
01566       .addImm(MI->getOperand(3).getImm())
01567       .addReg(MI->getOperand(4).getReg()));
01568 
01569     return;
01570   }
01571   case ARM::CONSTPOOL_ENTRY: {
01572     /// CONSTPOOL_ENTRY - This instruction represents a floating constant pool
01573     /// in the function.  The first operand is the ID# for this instruction, the
01574     /// second is the index into the MachineConstantPool that this is, the third
01575     /// is the size in bytes of this constant pool entry.
01576     /// The required alignment is specified on the basic block holding this MI.
01577     unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
01578     unsigned CPIdx   = (unsigned)MI->getOperand(1).getIndex();
01579 
01580     // If this is the first entry of the pool, mark it.
01581     if (!InConstantPool) {
01582       OutStreamer.EmitDataRegion(MCDR_DataRegion);
01583       InConstantPool = true;
01584     }
01585 
01586     OutStreamer.EmitLabel(GetCPISymbol(LabelId));
01587 
01588     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
01589     if (MCPE.isMachineConstantPoolEntry())
01590       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
01591     else
01592       EmitGlobalConstant(MCPE.Val.ConstVal);
01593     return;
01594   }
01595   case ARM::t2BR_JT: {
01596     // Lower and emit the instruction itself, then the jump table following it.
01597     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVr)
01598       .addReg(ARM::PC)
01599       .addReg(MI->getOperand(0).getReg())
01600       // Add predicate operands.
01601       .addImm(ARMCC::AL)
01602       .addReg(0));
01603 
01604     // Output the data for the jump table itself
01605     EmitJump2Table(MI);
01606     return;
01607   }
01608   case ARM::t2TBB_JT: {
01609     // Lower and emit the instruction itself, then the jump table following it.
01610     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::t2TBB)
01611       .addReg(ARM::PC)
01612       .addReg(MI->getOperand(0).getReg())
01613       // Add predicate operands.
01614       .addImm(ARMCC::AL)
01615       .addReg(0));
01616 
01617     // Output the data for the jump table itself
01618     EmitJump2Table(MI);
01619     // Make sure the next instruction is 2-byte aligned.
01620     EmitAlignment(1);
01621     return;
01622   }
01623   case ARM::t2TBH_JT: {
01624     // Lower and emit the instruction itself, then the jump table following it.
01625     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::t2TBH)
01626       .addReg(ARM::PC)
01627       .addReg(MI->getOperand(0).getReg())
01628       // Add predicate operands.
01629       .addImm(ARMCC::AL)
01630       .addReg(0));
01631 
01632     // Output the data for the jump table itself
01633     EmitJump2Table(MI);
01634     return;
01635   }
01636   case ARM::tBR_JTr:
01637   case ARM::BR_JTr: {
01638     // Lower and emit the instruction itself, then the jump table following it.
01639     // mov pc, target
01640     MCInst TmpInst;
01641     unsigned Opc = MI->getOpcode() == ARM::BR_JTr ?
01642       ARM::MOVr : ARM::tMOVr;
01643     TmpInst.setOpcode(Opc);
01644     TmpInst.addOperand(MCOperand::CreateReg(ARM::PC));
01645     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
01646     // Add predicate operands.
01647     TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
01648     TmpInst.addOperand(MCOperand::CreateReg(0));
01649     // Add 's' bit operand (always reg0 for this)
01650     if (Opc == ARM::MOVr)
01651       TmpInst.addOperand(MCOperand::CreateReg(0));
01652     EmitToStreamer(OutStreamer, TmpInst);
01653 
01654     // Make sure the Thumb jump table is 4-byte aligned.
01655     if (Opc == ARM::tMOVr)
01656       EmitAlignment(2);
01657 
01658     // Output the data for the jump table itself
01659     EmitJumpTable(MI);
01660     return;
01661   }
01662   case ARM::BR_JTm: {
01663     // Lower and emit the instruction itself, then the jump table following it.
01664     // ldr pc, target
01665     MCInst TmpInst;
01666     if (MI->getOperand(1).getReg() == 0) {
01667       // literal offset
01668       TmpInst.setOpcode(ARM::LDRi12);
01669       TmpInst.addOperand(MCOperand::CreateReg(ARM::PC));
01670       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
01671       TmpInst.addOperand(MCOperand::CreateImm(MI->getOperand(2).getImm()));
01672     } else {
01673       TmpInst.setOpcode(ARM::LDRrs);
01674       TmpInst.addOperand(MCOperand::CreateReg(ARM::PC));
01675       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
01676       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(1).getReg()));
01677       TmpInst.addOperand(MCOperand::CreateImm(0));
01678     }
01679     // Add predicate operands.
01680     TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
01681     TmpInst.addOperand(MCOperand::CreateReg(0));
01682     EmitToStreamer(OutStreamer, TmpInst);
01683 
01684     // Output the data for the jump table itself
01685     EmitJumpTable(MI);
01686     return;
01687   }
01688   case ARM::BR_JTadd: {
01689     // Lower and emit the instruction itself, then the jump table following it.
01690     // add pc, target, idx
01691     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::ADDrr)
01692       .addReg(ARM::PC)
01693       .addReg(MI->getOperand(0).getReg())
01694       .addReg(MI->getOperand(1).getReg())
01695       // Add predicate operands.
01696       .addImm(ARMCC::AL)
01697       .addReg(0)
01698       // Add 's' bit operand (always reg0 for this)
01699       .addReg(0));
01700 
01701     // Output the data for the jump table itself
01702     EmitJumpTable(MI);
01703     return;
01704   }
01705   case ARM::SPACE:
01706     OutStreamer.EmitZeros(MI->getOperand(1).getImm());
01707     return;
01708   case ARM::TRAP: {
01709     // Non-Darwin binutils don't yet support the "trap" mnemonic.
01710     // FIXME: Remove this special case when they do.
01711     if (!Subtarget->isTargetMachO()) {
01712       //.long 0xe7ffdefe @ trap
01713       uint32_t Val = 0xe7ffdefeUL;
01714       OutStreamer.AddComment("trap");
01715       OutStreamer.EmitIntValue(Val, 4);
01716       return;
01717     }
01718     break;
01719   }
01720   case ARM::TRAPNaCl: {
01721     //.long 0xe7fedef0 @ trap
01722     uint32_t Val = 0xe7fedef0UL;
01723     OutStreamer.AddComment("trap");
01724     OutStreamer.EmitIntValue(Val, 4);
01725     return;
01726   }
01727   case ARM::tTRAP: {
01728     // Non-Darwin binutils don't yet support the "trap" mnemonic.
01729     // FIXME: Remove this special case when they do.
01730     if (!Subtarget->isTargetMachO()) {
01731       //.short 57086 @ trap
01732       uint16_t Val = 0xdefe;
01733       OutStreamer.AddComment("trap");
01734       OutStreamer.EmitIntValue(Val, 2);
01735       return;
01736     }
01737     break;
01738   }
01739   case ARM::t2Int_eh_sjlj_setjmp:
01740   case ARM::t2Int_eh_sjlj_setjmp_nofp:
01741   case ARM::tInt_eh_sjlj_setjmp: {
01742     // Two incoming args: GPR:$src, GPR:$val
01743     // mov $val, pc
01744     // adds $val, #7
01745     // str $val, [$src, #4]
01746     // movs r0, #0
01747     // b 1f
01748     // movs r0, #1
01749     // 1:
01750     unsigned SrcReg = MI->getOperand(0).getReg();
01751     unsigned ValReg = MI->getOperand(1).getReg();
01752     MCSymbol *Label = GetARMSJLJEHLabel();
01753     OutStreamer.AddComment("eh_setjmp begin");
01754     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVr)
01755       .addReg(ValReg)
01756       .addReg(ARM::PC)
01757       // Predicate.
01758       .addImm(ARMCC::AL)
01759       .addReg(0));
01760 
01761     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tADDi3)
01762       .addReg(ValReg)
01763       // 's' bit operand
01764       .addReg(ARM::CPSR)
01765       .addReg(ValReg)
01766       .addImm(7)
01767       // Predicate.
01768       .addImm(ARMCC::AL)
01769       .addReg(0));
01770 
01771     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tSTRi)
01772       .addReg(ValReg)
01773       .addReg(SrcReg)
01774       // The offset immediate is #4. The operand value is scaled by 4 for the
01775       // tSTR instruction.
01776       .addImm(1)
01777       // Predicate.
01778       .addImm(ARMCC::AL)
01779       .addReg(0));
01780 
01781     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVi8)
01782       .addReg(ARM::R0)
01783       .addReg(ARM::CPSR)
01784       .addImm(0)
01785       // Predicate.
01786       .addImm(ARMCC::AL)
01787       .addReg(0));
01788 
01789     const MCExpr *SymbolExpr = MCSymbolRefExpr::Create(Label, OutContext);
01790     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tB)
01791       .addExpr(SymbolExpr)
01792       .addImm(ARMCC::AL)
01793       .addReg(0));
01794 
01795     OutStreamer.AddComment("eh_setjmp end");
01796     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVi8)
01797       .addReg(ARM::R0)
01798       .addReg(ARM::CPSR)
01799       .addImm(1)
01800       // Predicate.
01801       .addImm(ARMCC::AL)
01802       .addReg(0));
01803 
01804     OutStreamer.EmitLabel(Label);
01805     return;
01806   }
01807 
01808   case ARM::Int_eh_sjlj_setjmp_nofp:
01809   case ARM::Int_eh_sjlj_setjmp: {
01810     // Two incoming args: GPR:$src, GPR:$val
01811     // add $val, pc, #8
01812     // str $val, [$src, #+4]
01813     // mov r0, #0
01814     // add pc, pc, #0
01815     // mov r0, #1
01816     unsigned SrcReg = MI->getOperand(0).getReg();
01817     unsigned ValReg = MI->getOperand(1).getReg();
01818 
01819     OutStreamer.AddComment("eh_setjmp begin");
01820     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::ADDri)
01821       .addReg(ValReg)
01822       .addReg(ARM::PC)
01823       .addImm(8)
01824       // Predicate.
01825       .addImm(ARMCC::AL)
01826       .addReg(0)
01827       // 's' bit operand (always reg0 for this).
01828       .addReg(0));
01829 
01830     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::STRi12)
01831       .addReg(ValReg)
01832       .addReg(SrcReg)
01833       .addImm(4)
01834       // Predicate.
01835       .addImm(ARMCC::AL)
01836       .addReg(0));
01837 
01838     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVi)
01839       .addReg(ARM::R0)
01840       .addImm(0)
01841       // Predicate.
01842       .addImm(ARMCC::AL)
01843       .addReg(0)
01844       // 's' bit operand (always reg0 for this).
01845       .addReg(0));
01846 
01847     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::ADDri)
01848       .addReg(ARM::PC)
01849       .addReg(ARM::PC)
01850       .addImm(0)
01851       // Predicate.
01852       .addImm(ARMCC::AL)
01853       .addReg(0)
01854       // 's' bit operand (always reg0 for this).
01855       .addReg(0));
01856 
01857     OutStreamer.AddComment("eh_setjmp end");
01858     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVi)
01859       .addReg(ARM::R0)
01860       .addImm(1)
01861       // Predicate.
01862       .addImm(ARMCC::AL)
01863       .addReg(0)
01864       // 's' bit operand (always reg0 for this).
01865       .addReg(0));
01866     return;
01867   }
01868   case ARM::Int_eh_sjlj_longjmp: {
01869     // ldr sp, [$src, #8]
01870     // ldr $scratch, [$src, #4]
01871     // ldr r7, [$src]
01872     // bx $scratch
01873     unsigned SrcReg = MI->getOperand(0).getReg();
01874     unsigned ScratchReg = MI->getOperand(1).getReg();
01875     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::LDRi12)
01876       .addReg(ARM::SP)
01877       .addReg(SrcReg)
01878       .addImm(8)
01879       // Predicate.
01880       .addImm(ARMCC::AL)
01881       .addReg(0));
01882 
01883     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::LDRi12)
01884       .addReg(ScratchReg)
01885       .addReg(SrcReg)
01886       .addImm(4)
01887       // Predicate.
01888       .addImm(ARMCC::AL)
01889       .addReg(0));
01890 
01891     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::LDRi12)
01892       .addReg(ARM::R7)
01893       .addReg(SrcReg)
01894       .addImm(0)
01895       // Predicate.
01896       .addImm(ARMCC::AL)
01897       .addReg(0));
01898 
01899     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::BX)
01900       .addReg(ScratchReg)
01901       // Predicate.
01902       .addImm(ARMCC::AL)
01903       .addReg(0));
01904     return;
01905   }
01906   case ARM::tInt_eh_sjlj_longjmp: {
01907     // ldr $scratch, [$src, #8]
01908     // mov sp, $scratch
01909     // ldr $scratch, [$src, #4]
01910     // ldr r7, [$src]
01911     // bx $scratch
01912     unsigned SrcReg = MI->getOperand(0).getReg();
01913     unsigned ScratchReg = MI->getOperand(1).getReg();
01914     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tLDRi)
01915       .addReg(ScratchReg)
01916       .addReg(SrcReg)
01917       // The offset immediate is #8. The operand value is scaled by 4 for the
01918       // tLDR instruction.
01919       .addImm(2)
01920       // Predicate.
01921       .addImm(ARMCC::AL)
01922       .addReg(0));
01923 
01924     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVr)
01925       .addReg(ARM::SP)
01926       .addReg(ScratchReg)
01927       // Predicate.
01928       .addImm(ARMCC::AL)
01929       .addReg(0));
01930 
01931     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tLDRi)
01932       .addReg(ScratchReg)
01933       .addReg(SrcReg)
01934       .addImm(1)
01935       // Predicate.
01936       .addImm(ARMCC::AL)
01937       .addReg(0));
01938 
01939     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tLDRi)
01940       .addReg(ARM::R7)
01941       .addReg(SrcReg)
01942       .addImm(0)
01943       // Predicate.
01944       .addImm(ARMCC::AL)
01945       .addReg(0));
01946 
01947     EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tBX)
01948       .addReg(ScratchReg)
01949       // Predicate.
01950       .addImm(ARMCC::AL)
01951       .addReg(0));
01952     return;
01953   }
01954   }
01955 
01956   MCInst TmpInst;
01957   LowerARMMachineInstrToMCInst(MI, TmpInst, *this);
01958 
01959   EmitToStreamer(OutStreamer, TmpInst);
01960 }
01961 
01962 //===----------------------------------------------------------------------===//
01963 // Target Registry Stuff
01964 //===----------------------------------------------------------------------===//
01965 
01966 // Force static initialization.
01967 extern "C" void LLVMInitializeARMAsmPrinter() {
01968   RegisterAsmPrinter<ARMAsmPrinter> X(TheARMLETarget);
01969   RegisterAsmPrinter<ARMAsmPrinter> Y(TheARMBETarget);
01970   RegisterAsmPrinter<ARMAsmPrinter> A(TheThumbLETarget);
01971   RegisterAsmPrinter<ARMAsmPrinter> B(TheThumbBETarget);
01972 }