LLVM API Documentation

ARMELFStreamer.cpp
Go to the documentation of this file.
00001 //===- lib/MC/ARMELFStreamer.cpp - ELF Object Output for ARM --------------===//
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 assembles .s files and emits ARM ELF .o object files. Different
00011 // from generic ELF streamer in emitting mapping symbols ($a, $t and $d) to
00012 // delimit regions of data and code.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "ARMArchName.h"
00017 #include "ARMFPUName.h"
00018 #include "ARMRegisterInfo.h"
00019 #include "ARMUnwindOpAsm.h"
00020 #include "llvm/ADT/StringExtras.h"
00021 #include "llvm/ADT/Twine.h"
00022 #include "llvm/MC/MCAsmBackend.h"
00023 #include "llvm/MC/MCAsmInfo.h"
00024 #include "llvm/MC/MCAssembler.h"
00025 #include "llvm/MC/MCCodeEmitter.h"
00026 #include "llvm/MC/MCContext.h"
00027 #include "llvm/MC/MCELF.h"
00028 #include "llvm/MC/MCELFStreamer.h"
00029 #include "llvm/MC/MCELFSymbolFlags.h"
00030 #include "llvm/MC/MCExpr.h"
00031 #include "llvm/MC/MCInst.h"
00032 #include "llvm/MC/MCInstPrinter.h"
00033 #include "llvm/MC/MCObjectFileInfo.h"
00034 #include "llvm/MC/MCObjectStreamer.h"
00035 #include "llvm/MC/MCRegisterInfo.h"
00036 #include "llvm/MC/MCSection.h"
00037 #include "llvm/MC/MCSectionELF.h"
00038 #include "llvm/MC/MCStreamer.h"
00039 #include "llvm/MC/MCSymbol.h"
00040 #include "llvm/MC/MCValue.h"
00041 #include "llvm/Support/ARMBuildAttributes.h"
00042 #include "llvm/Support/ARMEHABI.h"
00043 #include "llvm/Support/Debug.h"
00044 #include "llvm/Support/ELF.h"
00045 #include "llvm/Support/FormattedStream.h"
00046 #include "llvm/Support/LEB128.h"
00047 #include "llvm/Support/raw_ostream.h"
00048 #include <algorithm>
00049 
00050 using namespace llvm;
00051 
00052 static std::string GetAEABIUnwindPersonalityName(unsigned Index) {
00053   assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX &&
00054          "Invalid personality index");
00055   return (Twine("__aeabi_unwind_cpp_pr") + Twine(Index)).str();
00056 }
00057 
00058 static const char *GetFPUName(unsigned ID) {
00059   switch (ID) {
00060   default:
00061     llvm_unreachable("Unknown FPU kind");
00062     break;
00063 #define ARM_FPU_NAME(NAME, ID) case ARM::ID: return NAME;
00064 #include "ARMFPUName.def"
00065   }
00066   return nullptr;
00067 }
00068 
00069 static const char *GetArchName(unsigned ID) {
00070   switch (ID) {
00071   default:
00072     llvm_unreachable("Unknown ARCH kind");
00073     break;
00074 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
00075   case ARM::ID: return NAME;
00076 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
00077 #include "ARMArchName.def"
00078   }
00079   return nullptr;
00080 }
00081 
00082 static const char *GetArchDefaultCPUName(unsigned ID) {
00083   switch (ID) {
00084   default:
00085     llvm_unreachable("Unknown ARCH kind");
00086     break;
00087 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
00088   case ARM::ID: return DEFAULT_CPU_NAME;
00089 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
00090 #include "ARMArchName.def"
00091   }
00092   return nullptr;
00093 }
00094 
00095 static unsigned GetArchDefaultCPUArch(unsigned ID) {
00096   switch (ID) {
00097   default:
00098     llvm_unreachable("Unknown ARCH kind");
00099     break;
00100 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
00101   case ARM::ID: return ARMBuildAttrs::DEFAULT_CPU_ARCH;
00102 #define ARM_ARCH_ALIAS(NAME, ID) /* empty */
00103 #include "ARMArchName.def"
00104   }
00105   return 0;
00106 }
00107 
00108 namespace {
00109 
00110 class ARMELFStreamer;
00111 
00112 class ARMTargetAsmStreamer : public ARMTargetStreamer {
00113   formatted_raw_ostream &OS;
00114   MCInstPrinter &InstPrinter;
00115   bool IsVerboseAsm;
00116 
00117   void emitFnStart() override;
00118   void emitFnEnd() override;
00119   void emitCantUnwind() override;
00120   void emitPersonality(const MCSymbol *Personality) override;
00121   void emitPersonalityIndex(unsigned Index) override;
00122   void emitHandlerData() override;
00123   void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0) override;
00124   void emitMovSP(unsigned Reg, int64_t Offset = 0) override;
00125   void emitPad(int64_t Offset) override;
00126   void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
00127                    bool isVector) override;
00128   void emitUnwindRaw(int64_t Offset,
00129                      const SmallVectorImpl<uint8_t> &Opcodes) override;
00130 
00131   void switchVendor(StringRef Vendor) override;
00132   void emitAttribute(unsigned Attribute, unsigned Value) override;
00133   void emitTextAttribute(unsigned Attribute, StringRef String) override;
00134   void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
00135                             StringRef StrinValue) override;
00136   void emitArch(unsigned Arch) override;
00137   void emitObjectArch(unsigned Arch) override;
00138   void emitFPU(unsigned FPU) override;
00139   void emitInst(uint32_t Inst, char Suffix = '\0') override;
00140   void finishAttributeSection() override;
00141 
00142   void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE) override;
00143   void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) override;
00144 
00145 public:
00146   ARMTargetAsmStreamer(MCStreamer &S, formatted_raw_ostream &OS,
00147                        MCInstPrinter &InstPrinter, bool VerboseAsm);
00148 };
00149 
00150 ARMTargetAsmStreamer::ARMTargetAsmStreamer(MCStreamer &S,
00151                                            formatted_raw_ostream &OS,
00152                                            MCInstPrinter &InstPrinter,
00153                                            bool VerboseAsm)
00154     : ARMTargetStreamer(S), OS(OS), InstPrinter(InstPrinter),
00155       IsVerboseAsm(VerboseAsm) {}
00156 void ARMTargetAsmStreamer::emitFnStart() { OS << "\t.fnstart\n"; }
00157 void ARMTargetAsmStreamer::emitFnEnd() { OS << "\t.fnend\n"; }
00158 void ARMTargetAsmStreamer::emitCantUnwind() { OS << "\t.cantunwind\n"; }
00159 void ARMTargetAsmStreamer::emitPersonality(const MCSymbol *Personality) {
00160   OS << "\t.personality " << Personality->getName() << '\n';
00161 }
00162 void ARMTargetAsmStreamer::emitPersonalityIndex(unsigned Index) {
00163   OS << "\t.personalityindex " << Index << '\n';
00164 }
00165 void ARMTargetAsmStreamer::emitHandlerData() { OS << "\t.handlerdata\n"; }
00166 void ARMTargetAsmStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
00167                                      int64_t Offset) {
00168   OS << "\t.setfp\t";
00169   InstPrinter.printRegName(OS, FpReg);
00170   OS << ", ";
00171   InstPrinter.printRegName(OS, SpReg);
00172   if (Offset)
00173     OS << ", #" << Offset;
00174   OS << '\n';
00175 }
00176 void ARMTargetAsmStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
00177   assert((Reg != ARM::SP && Reg != ARM::PC) &&
00178          "the operand of .movsp cannot be either sp or pc");
00179 
00180   OS << "\t.movsp\t";
00181   InstPrinter.printRegName(OS, Reg);
00182   if (Offset)
00183     OS << ", #" << Offset;
00184   OS << '\n';
00185 }
00186 void ARMTargetAsmStreamer::emitPad(int64_t Offset) {
00187   OS << "\t.pad\t#" << Offset << '\n';
00188 }
00189 void ARMTargetAsmStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
00190                                        bool isVector) {
00191   assert(RegList.size() && "RegList should not be empty");
00192   if (isVector)
00193     OS << "\t.vsave\t{";
00194   else
00195     OS << "\t.save\t{";
00196 
00197   InstPrinter.printRegName(OS, RegList[0]);
00198 
00199   for (unsigned i = 1, e = RegList.size(); i != e; ++i) {
00200     OS << ", ";
00201     InstPrinter.printRegName(OS, RegList[i]);
00202   }
00203 
00204   OS << "}\n";
00205 }
00206 void ARMTargetAsmStreamer::switchVendor(StringRef Vendor) {
00207 }
00208 void ARMTargetAsmStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
00209   OS << "\t.eabi_attribute\t" << Attribute << ", " << Twine(Value);
00210   if (IsVerboseAsm) {
00211     StringRef Name = ARMBuildAttrs::AttrTypeAsString(Attribute);
00212     if (!Name.empty())
00213       OS << "\t@ " << Name;
00214   }
00215   OS << "\n";
00216 }
00217 void ARMTargetAsmStreamer::emitTextAttribute(unsigned Attribute,
00218                                              StringRef String) {
00219   switch (Attribute) {
00220   case ARMBuildAttrs::CPU_name:
00221     OS << "\t.cpu\t" << String.lower();
00222     break;
00223   default:
00224     OS << "\t.eabi_attribute\t" << Attribute << ", \"" << String << "\"";
00225     if (IsVerboseAsm) {
00226       StringRef Name = ARMBuildAttrs::AttrTypeAsString(Attribute);
00227       if (!Name.empty())
00228         OS << "\t@ " << Name;
00229     }
00230     break;
00231   }
00232   OS << "\n";
00233 }
00234 void ARMTargetAsmStreamer::emitIntTextAttribute(unsigned Attribute,
00235                                                 unsigned IntValue,
00236                                                 StringRef StringValue) {
00237   switch (Attribute) {
00238   default: llvm_unreachable("unsupported multi-value attribute in asm mode");
00239   case ARMBuildAttrs::compatibility:
00240     OS << "\t.eabi_attribute\t" << Attribute << ", " << IntValue;
00241     if (!StringValue.empty())
00242       OS << ", \"" << StringValue << "\"";
00243     if (IsVerboseAsm)
00244       OS << "\t@ " << ARMBuildAttrs::AttrTypeAsString(Attribute);
00245     break;
00246   }
00247   OS << "\n";
00248 }
00249 void ARMTargetAsmStreamer::emitArch(unsigned Arch) {
00250   OS << "\t.arch\t" << GetArchName(Arch) << "\n";
00251 }
00252 void ARMTargetAsmStreamer::emitObjectArch(unsigned Arch) {
00253   OS << "\t.object_arch\t" << GetArchName(Arch) << '\n';
00254 }
00255 void ARMTargetAsmStreamer::emitFPU(unsigned FPU) {
00256   OS << "\t.fpu\t" << GetFPUName(FPU) << "\n";
00257 }
00258 void ARMTargetAsmStreamer::finishAttributeSection() {
00259 }
00260 void
00261 ARMTargetAsmStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
00262   OS << "\t.tlsdescseq\t" << S->getSymbol().getName();
00263 }
00264 
00265 void ARMTargetAsmStreamer::emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) {
00266   OS << "\t.thumb_set\t" << *Symbol << ", " << *Value << '\n';
00267 }
00268 
00269 void ARMTargetAsmStreamer::emitInst(uint32_t Inst, char Suffix) {
00270   OS << "\t.inst";
00271   if (Suffix)
00272     OS << "." << Suffix;
00273   OS << "\t0x" << utohexstr(Inst) << "\n";
00274 }
00275 
00276 void ARMTargetAsmStreamer::emitUnwindRaw(int64_t Offset,
00277                                       const SmallVectorImpl<uint8_t> &Opcodes) {
00278   OS << "\t.unwind_raw " << Offset;
00279   for (SmallVectorImpl<uint8_t>::const_iterator OCI = Opcodes.begin(),
00280                                                 OCE = Opcodes.end();
00281        OCI != OCE; ++OCI)
00282     OS << ", 0x" << utohexstr(*OCI);
00283   OS << '\n';
00284 }
00285 
00286 class ARMTargetELFStreamer : public ARMTargetStreamer {
00287 private:
00288   // This structure holds all attributes, accounting for
00289   // their string/numeric value, so we can later emmit them
00290   // in declaration order, keeping all in the same vector
00291   struct AttributeItem {
00292     enum {
00293       HiddenAttribute = 0,
00294       NumericAttribute,
00295       TextAttribute,
00296       NumericAndTextAttributes
00297     } Type;
00298     unsigned Tag;
00299     unsigned IntValue;
00300     StringRef StringValue;
00301 
00302     static bool LessTag(const AttributeItem &LHS, const AttributeItem &RHS) {
00303       return (LHS.Tag < RHS.Tag);
00304     }
00305   };
00306 
00307   StringRef CurrentVendor;
00308   unsigned FPU;
00309   unsigned Arch;
00310   unsigned EmittedArch;
00311   SmallVector<AttributeItem, 64> Contents;
00312 
00313   const MCSection *AttributeSection;
00314 
00315   AttributeItem *getAttributeItem(unsigned Attribute) {
00316     for (size_t i = 0; i < Contents.size(); ++i)
00317       if (Contents[i].Tag == Attribute)
00318         return &Contents[i];
00319     return nullptr;
00320   }
00321 
00322   void setAttributeItem(unsigned Attribute, unsigned Value,
00323                         bool OverwriteExisting) {
00324     // Look for existing attribute item
00325     if (AttributeItem *Item = getAttributeItem(Attribute)) {
00326       if (!OverwriteExisting)
00327         return;
00328       Item->Type = AttributeItem::NumericAttribute;
00329       Item->IntValue = Value;
00330       return;
00331     }
00332 
00333     // Create new attribute item
00334     AttributeItem Item = {
00335       AttributeItem::NumericAttribute,
00336       Attribute,
00337       Value,
00338       StringRef("")
00339     };
00340     Contents.push_back(Item);
00341   }
00342 
00343   void setAttributeItem(unsigned Attribute, StringRef Value,
00344                         bool OverwriteExisting) {
00345     // Look for existing attribute item
00346     if (AttributeItem *Item = getAttributeItem(Attribute)) {
00347       if (!OverwriteExisting)
00348         return;
00349       Item->Type = AttributeItem::TextAttribute;
00350       Item->StringValue = Value;
00351       return;
00352     }
00353 
00354     // Create new attribute item
00355     AttributeItem Item = {
00356       AttributeItem::TextAttribute,
00357       Attribute,
00358       0,
00359       Value
00360     };
00361     Contents.push_back(Item);
00362   }
00363 
00364   void setAttributeItems(unsigned Attribute, unsigned IntValue,
00365                          StringRef StringValue, bool OverwriteExisting) {
00366     // Look for existing attribute item
00367     if (AttributeItem *Item = getAttributeItem(Attribute)) {
00368       if (!OverwriteExisting)
00369         return;
00370       Item->Type = AttributeItem::NumericAndTextAttributes;
00371       Item->IntValue = IntValue;
00372       Item->StringValue = StringValue;
00373       return;
00374     }
00375 
00376     // Create new attribute item
00377     AttributeItem Item = {
00378       AttributeItem::NumericAndTextAttributes,
00379       Attribute,
00380       IntValue,
00381       StringValue
00382     };
00383     Contents.push_back(Item);
00384   }
00385 
00386   void emitArchDefaultAttributes();
00387   void emitFPUDefaultAttributes();
00388 
00389   ARMELFStreamer &getStreamer();
00390 
00391   void emitFnStart() override;
00392   void emitFnEnd() override;
00393   void emitCantUnwind() override;
00394   void emitPersonality(const MCSymbol *Personality) override;
00395   void emitPersonalityIndex(unsigned Index) override;
00396   void emitHandlerData() override;
00397   void emitSetFP(unsigned FpReg, unsigned SpReg, int64_t Offset = 0) override;
00398   void emitMovSP(unsigned Reg, int64_t Offset = 0) override;
00399   void emitPad(int64_t Offset) override;
00400   void emitRegSave(const SmallVectorImpl<unsigned> &RegList,
00401                    bool isVector) override;
00402   void emitUnwindRaw(int64_t Offset,
00403                      const SmallVectorImpl<uint8_t> &Opcodes) override;
00404 
00405   void switchVendor(StringRef Vendor) override;
00406   void emitAttribute(unsigned Attribute, unsigned Value) override;
00407   void emitTextAttribute(unsigned Attribute, StringRef String) override;
00408   void emitIntTextAttribute(unsigned Attribute, unsigned IntValue,
00409                             StringRef StringValue) override;
00410   void emitArch(unsigned Arch) override;
00411   void emitObjectArch(unsigned Arch) override;
00412   void emitFPU(unsigned FPU) override;
00413   void emitInst(uint32_t Inst, char Suffix = '\0') override;
00414   void finishAttributeSection() override;
00415   void emitLabel(MCSymbol *Symbol) override;
00416 
00417   void AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *SRE) override;
00418   void emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) override;
00419 
00420   size_t calculateContentSize() const;
00421 
00422 public:
00423   ARMTargetELFStreamer(MCStreamer &S)
00424     : ARMTargetStreamer(S), CurrentVendor("aeabi"), FPU(ARM::INVALID_FPU),
00425       Arch(ARM::INVALID_ARCH), EmittedArch(ARM::INVALID_ARCH),
00426       AttributeSection(nullptr) {}
00427 };
00428 
00429 /// Extend the generic ELFStreamer class so that it can emit mapping symbols at
00430 /// the appropriate points in the object files. These symbols are defined in the
00431 /// ARM ELF ABI: infocenter.arm.com/help/topic/com.arm.../IHI0044D_aaelf.pdf.
00432 ///
00433 /// In brief: $a, $t or $d should be emitted at the start of each contiguous
00434 /// region of ARM code, Thumb code or data in a section. In practice, this
00435 /// emission does not rely on explicit assembler directives but on inherent
00436 /// properties of the directives doing the emission (e.g. ".byte" is data, "add
00437 /// r0, r0, r0" an instruction).
00438 ///
00439 /// As a result this system is orthogonal to the DataRegion infrastructure used
00440 /// by MachO. Beware!
00441 class ARMELFStreamer : public MCELFStreamer {
00442 public:
00443   friend class ARMTargetELFStreamer;
00444 
00445   ARMELFStreamer(MCContext &Context, MCAsmBackend &TAB, raw_ostream &OS,
00446                  MCCodeEmitter *Emitter, bool IsThumb)
00447       : MCELFStreamer(Context, TAB, OS, Emitter), IsThumb(IsThumb),
00448         MappingSymbolCounter(0), LastEMS(EMS_None) {
00449     Reset();
00450   }
00451 
00452   ~ARMELFStreamer() {}
00453 
00454   void FinishImpl() override;
00455 
00456   // ARM exception handling directives
00457   void emitFnStart();
00458   void emitFnEnd();
00459   void emitCantUnwind();
00460   void emitPersonality(const MCSymbol *Per);
00461   void emitPersonalityIndex(unsigned index);
00462   void emitHandlerData();
00463   void emitSetFP(unsigned NewFpReg, unsigned NewSpReg, int64_t Offset = 0);
00464   void emitMovSP(unsigned Reg, int64_t Offset = 0);
00465   void emitPad(int64_t Offset);
00466   void emitRegSave(const SmallVectorImpl<unsigned> &RegList, bool isVector);
00467   void emitUnwindRaw(int64_t Offset, const SmallVectorImpl<uint8_t> &Opcodes);
00468 
00469   void ChangeSection(const MCSection *Section,
00470                      const MCExpr *Subsection) override {
00471     // We have to keep track of the mapping symbol state of any sections we
00472     // use. Each one should start off as EMS_None, which is provided as the
00473     // default constructor by DenseMap::lookup.
00474     LastMappingSymbols[getPreviousSection().first] = LastEMS;
00475     LastEMS = LastMappingSymbols.lookup(Section);
00476 
00477     MCELFStreamer::ChangeSection(Section, Subsection);
00478   }
00479 
00480   /// This function is the one used to emit instruction data into the ELF
00481   /// streamer. We override it to add the appropriate mapping symbol if
00482   /// necessary.
00483   void EmitInstruction(const MCInst& Inst,
00484                        const MCSubtargetInfo &STI) override {
00485     if (IsThumb)
00486       EmitThumbMappingSymbol();
00487     else
00488       EmitARMMappingSymbol();
00489 
00490     MCELFStreamer::EmitInstruction(Inst, STI);
00491   }
00492 
00493   void emitInst(uint32_t Inst, char Suffix) {
00494     unsigned Size;
00495     char Buffer[4];
00496     const bool LittleEndian = getContext().getAsmInfo()->isLittleEndian();
00497 
00498     switch (Suffix) {
00499     case '\0':
00500       Size = 4;
00501 
00502       assert(!IsThumb);
00503       EmitARMMappingSymbol();
00504       for (unsigned II = 0, IE = Size; II != IE; II++) {
00505         const unsigned I = LittleEndian ? (Size - II - 1) : II;
00506         Buffer[Size - II - 1] = uint8_t(Inst >> I * CHAR_BIT);
00507       }
00508 
00509       break;
00510     case 'n':
00511     case 'w':
00512       Size = (Suffix == 'n' ? 2 : 4);
00513 
00514       assert(IsThumb);
00515       EmitThumbMappingSymbol();
00516       for (unsigned II = 0, IE = Size; II != IE; II = II + 2) {
00517         const unsigned I0 = LittleEndian ? II + 0 : (Size - II - 1);
00518         const unsigned I1 = LittleEndian ? II + 1 : (Size - II - 2);
00519         Buffer[Size - II - 2] = uint8_t(Inst >> I0 * CHAR_BIT);
00520         Buffer[Size - II - 1] = uint8_t(Inst >> I1 * CHAR_BIT);
00521       }
00522 
00523       break;
00524     default:
00525       llvm_unreachable("Invalid Suffix");
00526     }
00527 
00528     MCELFStreamer::EmitBytes(StringRef(Buffer, Size));
00529   }
00530 
00531   /// This is one of the functions used to emit data into an ELF section, so the
00532   /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
00533   /// necessary.
00534   void EmitBytes(StringRef Data) override {
00535     EmitDataMappingSymbol();
00536     MCELFStreamer::EmitBytes(Data);
00537   }
00538 
00539   /// This is one of the functions used to emit data into an ELF section, so the
00540   /// ARM streamer overrides it to add the appropriate mapping symbol ($d) if
00541   /// necessary.
00542   void EmitValueImpl(const MCExpr *Value, unsigned Size,
00543                      const SMLoc &Loc) override {
00544     EmitDataMappingSymbol();
00545     MCELFStreamer::EmitValueImpl(Value, Size);
00546   }
00547 
00548   void EmitAssemblerFlag(MCAssemblerFlag Flag) override {
00549     MCELFStreamer::EmitAssemblerFlag(Flag);
00550 
00551     switch (Flag) {
00552     case MCAF_SyntaxUnified:
00553       return; // no-op here.
00554     case MCAF_Code16:
00555       IsThumb = true;
00556       return; // Change to Thumb mode
00557     case MCAF_Code32:
00558       IsThumb = false;
00559       return; // Change to ARM mode
00560     case MCAF_Code64:
00561       return;
00562     case MCAF_SubsectionsViaSymbols:
00563       return;
00564     }
00565   }
00566 
00567 private:
00568   enum ElfMappingSymbol {
00569     EMS_None,
00570     EMS_ARM,
00571     EMS_Thumb,
00572     EMS_Data
00573   };
00574 
00575   void EmitDataMappingSymbol() {
00576     if (LastEMS == EMS_Data) return;
00577     EmitMappingSymbol("$d");
00578     LastEMS = EMS_Data;
00579   }
00580 
00581   void EmitThumbMappingSymbol() {
00582     if (LastEMS == EMS_Thumb) return;
00583     EmitMappingSymbol("$t");
00584     LastEMS = EMS_Thumb;
00585   }
00586 
00587   void EmitARMMappingSymbol() {
00588     if (LastEMS == EMS_ARM) return;
00589     EmitMappingSymbol("$a");
00590     LastEMS = EMS_ARM;
00591   }
00592 
00593   void EmitMappingSymbol(StringRef Name) {
00594     MCSymbol *Start = getContext().CreateTempSymbol();
00595     EmitLabel(Start);
00596 
00597     MCSymbol *Symbol =
00598       getContext().GetOrCreateSymbol(Name + "." +
00599                                      Twine(MappingSymbolCounter++));
00600 
00601     MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
00602     MCELF::SetType(SD, ELF::STT_NOTYPE);
00603     MCELF::SetBinding(SD, ELF::STB_LOCAL);
00604     SD.setExternal(false);
00605     AssignSection(Symbol, getCurrentSection().first);
00606 
00607     const MCExpr *Value = MCSymbolRefExpr::Create(Start, getContext());
00608     Symbol->setVariableValue(Value);
00609   }
00610 
00611   void EmitThumbFunc(MCSymbol *Func) override {
00612     getAssembler().setIsThumbFunc(Func);
00613     EmitSymbolAttribute(Func, MCSA_ELF_TypeFunction);
00614   }
00615 
00616   // Helper functions for ARM exception handling directives
00617   void Reset();
00618 
00619   void EmitPersonalityFixup(StringRef Name);
00620   void FlushPendingOffset();
00621   void FlushUnwindOpcodes(bool NoHandlerData);
00622 
00623   void SwitchToEHSection(const char *Prefix, unsigned Type, unsigned Flags,
00624                          SectionKind Kind, const MCSymbol &Fn);
00625   void SwitchToExTabSection(const MCSymbol &FnStart);
00626   void SwitchToExIdxSection(const MCSymbol &FnStart);
00627 
00628   void EmitFixup(const MCExpr *Expr, MCFixupKind Kind);
00629 
00630   bool IsThumb;
00631   int64_t MappingSymbolCounter;
00632 
00633   DenseMap<const MCSection *, ElfMappingSymbol> LastMappingSymbols;
00634   ElfMappingSymbol LastEMS;
00635 
00636   // ARM Exception Handling Frame Information
00637   MCSymbol *ExTab;
00638   MCSymbol *FnStart;
00639   const MCSymbol *Personality;
00640   unsigned PersonalityIndex;
00641   unsigned FPReg; // Frame pointer register
00642   int64_t FPOffset; // Offset: (final frame pointer) - (initial $sp)
00643   int64_t SPOffset; // Offset: (final $sp) - (initial $sp)
00644   int64_t PendingOffset; // Offset: (final $sp) - (emitted $sp)
00645   bool UsedFP;
00646   bool CantUnwind;
00647   SmallVector<uint8_t, 64> Opcodes;
00648   UnwindOpcodeAssembler UnwindOpAsm;
00649 };
00650 } // end anonymous namespace
00651 
00652 ARMELFStreamer &ARMTargetELFStreamer::getStreamer() {
00653   return static_cast<ARMELFStreamer &>(Streamer);
00654 }
00655 
00656 void ARMTargetELFStreamer::emitFnStart() { getStreamer().emitFnStart(); }
00657 void ARMTargetELFStreamer::emitFnEnd() { getStreamer().emitFnEnd(); }
00658 void ARMTargetELFStreamer::emitCantUnwind() { getStreamer().emitCantUnwind(); }
00659 void ARMTargetELFStreamer::emitPersonality(const MCSymbol *Personality) {
00660   getStreamer().emitPersonality(Personality);
00661 }
00662 void ARMTargetELFStreamer::emitPersonalityIndex(unsigned Index) {
00663   getStreamer().emitPersonalityIndex(Index);
00664 }
00665 void ARMTargetELFStreamer::emitHandlerData() {
00666   getStreamer().emitHandlerData();
00667 }
00668 void ARMTargetELFStreamer::emitSetFP(unsigned FpReg, unsigned SpReg,
00669                                      int64_t Offset) {
00670   getStreamer().emitSetFP(FpReg, SpReg, Offset);
00671 }
00672 void ARMTargetELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
00673   getStreamer().emitMovSP(Reg, Offset);
00674 }
00675 void ARMTargetELFStreamer::emitPad(int64_t Offset) {
00676   getStreamer().emitPad(Offset);
00677 }
00678 void ARMTargetELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
00679                                        bool isVector) {
00680   getStreamer().emitRegSave(RegList, isVector);
00681 }
00682 void ARMTargetELFStreamer::emitUnwindRaw(int64_t Offset,
00683                                       const SmallVectorImpl<uint8_t> &Opcodes) {
00684   getStreamer().emitUnwindRaw(Offset, Opcodes);
00685 }
00686 void ARMTargetELFStreamer::switchVendor(StringRef Vendor) {
00687   assert(!Vendor.empty() && "Vendor cannot be empty.");
00688 
00689   if (CurrentVendor == Vendor)
00690     return;
00691 
00692   if (!CurrentVendor.empty())
00693     finishAttributeSection();
00694 
00695   assert(Contents.empty() &&
00696          ".ARM.attributes should be flushed before changing vendor");
00697   CurrentVendor = Vendor;
00698 
00699 }
00700 void ARMTargetELFStreamer::emitAttribute(unsigned Attribute, unsigned Value) {
00701   setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
00702 }
00703 void ARMTargetELFStreamer::emitTextAttribute(unsigned Attribute,
00704                                              StringRef Value) {
00705   setAttributeItem(Attribute, Value, /* OverwriteExisting= */ true);
00706 }
00707 void ARMTargetELFStreamer::emitIntTextAttribute(unsigned Attribute,
00708                                                 unsigned IntValue,
00709                                                 StringRef StringValue) {
00710   setAttributeItems(Attribute, IntValue, StringValue,
00711                     /* OverwriteExisting= */ true);
00712 }
00713 void ARMTargetELFStreamer::emitArch(unsigned Value) {
00714   Arch = Value;
00715 }
00716 void ARMTargetELFStreamer::emitObjectArch(unsigned Value) {
00717   EmittedArch = Value;
00718 }
00719 void ARMTargetELFStreamer::emitArchDefaultAttributes() {
00720   using namespace ARMBuildAttrs;
00721 
00722   setAttributeItem(CPU_name, GetArchDefaultCPUName(Arch), false);
00723   if (EmittedArch == ARM::INVALID_ARCH)
00724     setAttributeItem(CPU_arch, GetArchDefaultCPUArch(Arch), false);
00725   else
00726     setAttributeItem(CPU_arch, GetArchDefaultCPUArch(EmittedArch), false);
00727 
00728   switch (Arch) {
00729   case ARM::ARMV2:
00730   case ARM::ARMV2A:
00731   case ARM::ARMV3:
00732   case ARM::ARMV3M:
00733   case ARM::ARMV4:
00734   case ARM::ARMV5:
00735     setAttributeItem(ARM_ISA_use, Allowed, false);
00736     break;
00737 
00738   case ARM::ARMV4T:
00739   case ARM::ARMV5T:
00740   case ARM::ARMV5TE:
00741   case ARM::ARMV6:
00742   case ARM::ARMV6J:
00743     setAttributeItem(ARM_ISA_use, Allowed, false);
00744     setAttributeItem(THUMB_ISA_use, Allowed, false);
00745     break;
00746 
00747   case ARM::ARMV6T2:
00748     setAttributeItem(ARM_ISA_use, Allowed, false);
00749     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
00750     break;
00751 
00752   case ARM::ARMV6Z:
00753   case ARM::ARMV6ZK:
00754     setAttributeItem(ARM_ISA_use, Allowed, false);
00755     setAttributeItem(THUMB_ISA_use, Allowed, false);
00756     setAttributeItem(Virtualization_use, AllowTZ, false);
00757     break;
00758 
00759   case ARM::ARMV6M:
00760     setAttributeItem(THUMB_ISA_use, Allowed, false);
00761     break;
00762 
00763   case ARM::ARMV7:
00764     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
00765     break;
00766 
00767   case ARM::ARMV7A:
00768     setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
00769     setAttributeItem(ARM_ISA_use, Allowed, false);
00770     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
00771     break;
00772 
00773   case ARM::ARMV7R:
00774     setAttributeItem(CPU_arch_profile, RealTimeProfile, false);
00775     setAttributeItem(ARM_ISA_use, Allowed, false);
00776     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
00777     break;
00778 
00779   case ARM::ARMV7M:
00780     setAttributeItem(CPU_arch_profile, MicroControllerProfile, false);
00781     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
00782     break;
00783 
00784   case ARM::ARMV8A:
00785     setAttributeItem(CPU_arch_profile, ApplicationProfile, false);
00786     setAttributeItem(ARM_ISA_use, Allowed, false);
00787     setAttributeItem(THUMB_ISA_use, AllowThumb32, false);
00788     setAttributeItem(MPextension_use, Allowed, false);
00789     setAttributeItem(Virtualization_use, AllowTZVirtualization, false);
00790     break;
00791 
00792   case ARM::IWMMXT:
00793     setAttributeItem(ARM_ISA_use, Allowed, false);
00794     setAttributeItem(THUMB_ISA_use, Allowed, false);
00795     setAttributeItem(WMMX_arch, AllowWMMXv1, false);
00796     break;
00797 
00798   case ARM::IWMMXT2:
00799     setAttributeItem(ARM_ISA_use, Allowed, false);
00800     setAttributeItem(THUMB_ISA_use, Allowed, false);
00801     setAttributeItem(WMMX_arch, AllowWMMXv2, false);
00802     break;
00803 
00804   default:
00805     report_fatal_error("Unknown Arch: " + Twine(Arch));
00806     break;
00807   }
00808 }
00809 void ARMTargetELFStreamer::emitFPU(unsigned Value) {
00810   FPU = Value;
00811 }
00812 void ARMTargetELFStreamer::emitFPUDefaultAttributes() {
00813   switch (FPU) {
00814   case ARM::VFP:
00815   case ARM::VFPV2:
00816     setAttributeItem(ARMBuildAttrs::FP_arch,
00817                      ARMBuildAttrs::AllowFPv2,
00818                      /* OverwriteExisting= */ false);
00819     break;
00820 
00821   case ARM::VFPV3:
00822     setAttributeItem(ARMBuildAttrs::FP_arch,
00823                      ARMBuildAttrs::AllowFPv3A,
00824                      /* OverwriteExisting= */ false);
00825     break;
00826 
00827   case ARM::VFPV3_D16:
00828     setAttributeItem(ARMBuildAttrs::FP_arch,
00829                      ARMBuildAttrs::AllowFPv3B,
00830                      /* OverwriteExisting= */ false);
00831     break;
00832 
00833   case ARM::VFPV4:
00834     setAttributeItem(ARMBuildAttrs::FP_arch,
00835                      ARMBuildAttrs::AllowFPv4A,
00836                      /* OverwriteExisting= */ false);
00837     break;
00838 
00839   case ARM::VFPV4_D16:
00840     setAttributeItem(ARMBuildAttrs::FP_arch,
00841                      ARMBuildAttrs::AllowFPv4B,
00842                      /* OverwriteExisting= */ false);
00843     break;
00844 
00845   case ARM::FP_ARMV8:
00846     setAttributeItem(ARMBuildAttrs::FP_arch,
00847                      ARMBuildAttrs::AllowFPARMv8A,
00848                      /* OverwriteExisting= */ false);
00849     break;
00850 
00851   case ARM::NEON:
00852     setAttributeItem(ARMBuildAttrs::FP_arch,
00853                      ARMBuildAttrs::AllowFPv3A,
00854                      /* OverwriteExisting= */ false);
00855     setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
00856                      ARMBuildAttrs::AllowNeon,
00857                      /* OverwriteExisting= */ false);
00858     break;
00859 
00860   case ARM::NEON_VFPV4:
00861     setAttributeItem(ARMBuildAttrs::FP_arch,
00862                      ARMBuildAttrs::AllowFPv4A,
00863                      /* OverwriteExisting= */ false);
00864     setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
00865                      ARMBuildAttrs::AllowNeon2,
00866                      /* OverwriteExisting= */ false);
00867     break;
00868 
00869   case ARM::NEON_FP_ARMV8:
00870   case ARM::CRYPTO_NEON_FP_ARMV8:
00871     setAttributeItem(ARMBuildAttrs::FP_arch,
00872                      ARMBuildAttrs::AllowFPARMv8A,
00873                      /* OverwriteExisting= */ false);
00874     setAttributeItem(ARMBuildAttrs::Advanced_SIMD_arch,
00875                      ARMBuildAttrs::AllowNeonARMv8,
00876                      /* OverwriteExisting= */ false);
00877     break;
00878 
00879   case ARM::SOFTVFP:
00880     break;
00881 
00882   default:
00883     report_fatal_error("Unknown FPU: " + Twine(FPU));
00884     break;
00885   }
00886 }
00887 size_t ARMTargetELFStreamer::calculateContentSize() const {
00888   size_t Result = 0;
00889   for (size_t i = 0; i < Contents.size(); ++i) {
00890     AttributeItem item = Contents[i];
00891     switch (item.Type) {
00892     case AttributeItem::HiddenAttribute:
00893       break;
00894     case AttributeItem::NumericAttribute:
00895       Result += getULEB128Size(item.Tag);
00896       Result += getULEB128Size(item.IntValue);
00897       break;
00898     case AttributeItem::TextAttribute:
00899       Result += getULEB128Size(item.Tag);
00900       Result += item.StringValue.size() + 1; // string + '\0'
00901       break;
00902     case AttributeItem::NumericAndTextAttributes:
00903       Result += getULEB128Size(item.Tag);
00904       Result += getULEB128Size(item.IntValue);
00905       Result += item.StringValue.size() + 1; // string + '\0';
00906       break;
00907     }
00908   }
00909   return Result;
00910 }
00911 void ARMTargetELFStreamer::finishAttributeSection() {
00912   // <format-version>
00913   // [ <section-length> "vendor-name"
00914   // [ <file-tag> <size> <attribute>*
00915   //   | <section-tag> <size> <section-number>* 0 <attribute>*
00916   //   | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
00917   //   ]+
00918   // ]*
00919 
00920   if (FPU != ARM::INVALID_FPU)
00921     emitFPUDefaultAttributes();
00922 
00923   if (Arch != ARM::INVALID_ARCH)
00924     emitArchDefaultAttributes();
00925 
00926   if (Contents.empty())
00927     return;
00928 
00929   std::sort(Contents.begin(), Contents.end(), AttributeItem::LessTag);
00930 
00931   ARMELFStreamer &Streamer = getStreamer();
00932 
00933   // Switch to .ARM.attributes section
00934   if (AttributeSection) {
00935     Streamer.SwitchSection(AttributeSection);
00936   } else {
00937     AttributeSection =
00938       Streamer.getContext().getELFSection(".ARM.attributes",
00939                                           ELF::SHT_ARM_ATTRIBUTES,
00940                                           0,
00941                                           SectionKind::getMetadata());
00942     Streamer.SwitchSection(AttributeSection);
00943 
00944     // Format version
00945     Streamer.EmitIntValue(0x41, 1);
00946   }
00947 
00948   // Vendor size + Vendor name + '\0'
00949   const size_t VendorHeaderSize = 4 + CurrentVendor.size() + 1;
00950 
00951   // Tag + Tag Size
00952   const size_t TagHeaderSize = 1 + 4;
00953 
00954   const size_t ContentsSize = calculateContentSize();
00955 
00956   Streamer.EmitIntValue(VendorHeaderSize + TagHeaderSize + ContentsSize, 4);
00957   Streamer.EmitBytes(CurrentVendor);
00958   Streamer.EmitIntValue(0, 1); // '\0'
00959 
00960   Streamer.EmitIntValue(ARMBuildAttrs::File, 1);
00961   Streamer.EmitIntValue(TagHeaderSize + ContentsSize, 4);
00962 
00963   // Size should have been accounted for already, now
00964   // emit each field as its type (ULEB or String)
00965   for (size_t i = 0; i < Contents.size(); ++i) {
00966     AttributeItem item = Contents[i];
00967     Streamer.EmitULEB128IntValue(item.Tag);
00968     switch (item.Type) {
00969     default: llvm_unreachable("Invalid attribute type");
00970     case AttributeItem::NumericAttribute:
00971       Streamer.EmitULEB128IntValue(item.IntValue);
00972       break;
00973     case AttributeItem::TextAttribute:
00974       Streamer.EmitBytes(item.StringValue.upper());
00975       Streamer.EmitIntValue(0, 1); // '\0'
00976       break;
00977     case AttributeItem::NumericAndTextAttributes:
00978       Streamer.EmitULEB128IntValue(item.IntValue);
00979       Streamer.EmitBytes(item.StringValue.upper());
00980       Streamer.EmitIntValue(0, 1); // '\0'
00981       break;
00982     }
00983   }
00984 
00985   Contents.clear();
00986   FPU = ARM::INVALID_FPU;
00987 }
00988 
00989 void ARMTargetELFStreamer::emitLabel(MCSymbol *Symbol) {
00990   ARMELFStreamer &Streamer = getStreamer();
00991   if (!Streamer.IsThumb)
00992     return;
00993 
00994   const MCSymbolData &SD = Streamer.getOrCreateSymbolData(Symbol);
00995   unsigned Type = MCELF::GetType(SD);
00996   if (Type == ELF_STT_Func || Type == ELF_STT_GnuIFunc)
00997     Streamer.EmitThumbFunc(Symbol);
00998 }
00999 
01000 void
01001 ARMTargetELFStreamer::AnnotateTLSDescriptorSequence(const MCSymbolRefExpr *S) {
01002   getStreamer().EmitFixup(S, FK_Data_4);
01003 }
01004 
01005 void ARMTargetELFStreamer::emitThumbSet(MCSymbol *Symbol, const MCExpr *Value) {
01006   if (const MCSymbolRefExpr *SRE = dyn_cast<MCSymbolRefExpr>(Value)) {
01007     const MCSymbol &Sym = SRE->getSymbol();
01008     if (!Sym.isDefined()) {
01009       getStreamer().EmitAssignment(Symbol, Value);
01010       return;
01011     }
01012   }
01013 
01014   getStreamer().EmitThumbFunc(Symbol);
01015   getStreamer().EmitAssignment(Symbol, Value);
01016 }
01017 
01018 void ARMTargetELFStreamer::emitInst(uint32_t Inst, char Suffix) {
01019   getStreamer().emitInst(Inst, Suffix);
01020 }
01021 
01022 void ARMELFStreamer::FinishImpl() {
01023   MCTargetStreamer &TS = *getTargetStreamer();
01024   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
01025   ATS.finishAttributeSection();
01026 
01027   MCELFStreamer::FinishImpl();
01028 }
01029 
01030 inline void ARMELFStreamer::SwitchToEHSection(const char *Prefix,
01031                                               unsigned Type,
01032                                               unsigned Flags,
01033                                               SectionKind Kind,
01034                                               const MCSymbol &Fn) {
01035   const MCSectionELF &FnSection =
01036     static_cast<const MCSectionELF &>(Fn.getSection());
01037 
01038   // Create the name for new section
01039   StringRef FnSecName(FnSection.getSectionName());
01040   SmallString<128> EHSecName(Prefix);
01041   if (FnSecName != ".text") {
01042     EHSecName += FnSecName;
01043   }
01044 
01045   // Get .ARM.extab or .ARM.exidx section
01046   const MCSectionELF *EHSection = nullptr;
01047   if (const MCSymbol *Group = FnSection.getGroup()) {
01048     EHSection = getContext().getELFSection(
01049       EHSecName, Type, Flags | ELF::SHF_GROUP, Kind,
01050       FnSection.getEntrySize(), Group->getName());
01051   } else {
01052     EHSection = getContext().getELFSection(EHSecName, Type, Flags, Kind);
01053   }
01054   assert(EHSection && "Failed to get the required EH section");
01055 
01056   // Switch to .ARM.extab or .ARM.exidx section
01057   SwitchSection(EHSection);
01058   EmitCodeAlignment(4);
01059 }
01060 
01061 inline void ARMELFStreamer::SwitchToExTabSection(const MCSymbol &FnStart) {
01062   SwitchToEHSection(".ARM.extab",
01063                     ELF::SHT_PROGBITS,
01064                     ELF::SHF_ALLOC,
01065                     SectionKind::getDataRel(),
01066                     FnStart);
01067 }
01068 
01069 inline void ARMELFStreamer::SwitchToExIdxSection(const MCSymbol &FnStart) {
01070   SwitchToEHSection(".ARM.exidx",
01071                     ELF::SHT_ARM_EXIDX,
01072                     ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER,
01073                     SectionKind::getDataRel(),
01074                     FnStart);
01075 }
01076 void ARMELFStreamer::EmitFixup(const MCExpr *Expr, MCFixupKind Kind) {
01077   MCDataFragment *Frag = getOrCreateDataFragment();
01078   Frag->getFixups().push_back(MCFixup::Create(Frag->getContents().size(), Expr,
01079                                               Kind));
01080 }
01081 
01082 void ARMELFStreamer::Reset() {
01083   ExTab = nullptr;
01084   FnStart = nullptr;
01085   Personality = nullptr;
01086   PersonalityIndex = ARM::EHABI::NUM_PERSONALITY_INDEX;
01087   FPReg = ARM::SP;
01088   FPOffset = 0;
01089   SPOffset = 0;
01090   PendingOffset = 0;
01091   UsedFP = false;
01092   CantUnwind = false;
01093 
01094   Opcodes.clear();
01095   UnwindOpAsm.Reset();
01096 }
01097 
01098 void ARMELFStreamer::emitFnStart() {
01099   assert(FnStart == nullptr);
01100   FnStart = getContext().CreateTempSymbol();
01101   EmitLabel(FnStart);
01102 }
01103 
01104 void ARMELFStreamer::emitFnEnd() {
01105   assert(FnStart && ".fnstart must precedes .fnend");
01106 
01107   // Emit unwind opcodes if there is no .handlerdata directive
01108   if (!ExTab && !CantUnwind)
01109     FlushUnwindOpcodes(true);
01110 
01111   // Emit the exception index table entry
01112   SwitchToExIdxSection(*FnStart);
01113 
01114   if (PersonalityIndex < ARM::EHABI::NUM_PERSONALITY_INDEX)
01115     EmitPersonalityFixup(GetAEABIUnwindPersonalityName(PersonalityIndex));
01116 
01117   const MCSymbolRefExpr *FnStartRef =
01118     MCSymbolRefExpr::Create(FnStart,
01119                             MCSymbolRefExpr::VK_ARM_PREL31,
01120                             getContext());
01121 
01122   EmitValue(FnStartRef, 4);
01123 
01124   if (CantUnwind) {
01125     EmitIntValue(ARM::EHABI::EXIDX_CANTUNWIND, 4);
01126   } else if (ExTab) {
01127     // Emit a reference to the unwind opcodes in the ".ARM.extab" section.
01128     const MCSymbolRefExpr *ExTabEntryRef =
01129       MCSymbolRefExpr::Create(ExTab,
01130                               MCSymbolRefExpr::VK_ARM_PREL31,
01131                               getContext());
01132     EmitValue(ExTabEntryRef, 4);
01133   } else {
01134     // For the __aeabi_unwind_cpp_pr0, we have to emit the unwind opcodes in
01135     // the second word of exception index table entry.  The size of the unwind
01136     // opcodes should always be 4 bytes.
01137     assert(PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0 &&
01138            "Compact model must use __aeabi_unwind_cpp_pr0 as personality");
01139     assert(Opcodes.size() == 4u &&
01140            "Unwind opcode size for __aeabi_unwind_cpp_pr0 must be equal to 4");
01141     uint64_t Intval = Opcodes[0] |
01142                       Opcodes[1] << 8 |
01143                       Opcodes[2] << 16 |
01144                       Opcodes[3] << 24;
01145     EmitIntValue(Intval, Opcodes.size());
01146   }
01147 
01148   // Switch to the section containing FnStart
01149   SwitchSection(&FnStart->getSection());
01150 
01151   // Clean exception handling frame information
01152   Reset();
01153 }
01154 
01155 void ARMELFStreamer::emitCantUnwind() { CantUnwind = true; }
01156 
01157 // Add the R_ARM_NONE fixup at the same position
01158 void ARMELFStreamer::EmitPersonalityFixup(StringRef Name) {
01159   const MCSymbol *PersonalitySym = getContext().GetOrCreateSymbol(Name);
01160 
01161   const MCSymbolRefExpr *PersonalityRef = MCSymbolRefExpr::Create(
01162       PersonalitySym, MCSymbolRefExpr::VK_ARM_NONE, getContext());
01163 
01164   visitUsedExpr(*PersonalityRef);
01165   MCDataFragment *DF = getOrCreateDataFragment();
01166   DF->getFixups().push_back(MCFixup::Create(DF->getContents().size(),
01167                                             PersonalityRef,
01168                                             MCFixup::getKindForSize(4, false)));
01169 }
01170 
01171 void ARMELFStreamer::FlushPendingOffset() {
01172   if (PendingOffset != 0) {
01173     UnwindOpAsm.EmitSPOffset(-PendingOffset);
01174     PendingOffset = 0;
01175   }
01176 }
01177 
01178 void ARMELFStreamer::FlushUnwindOpcodes(bool NoHandlerData) {
01179   // Emit the unwind opcode to restore $sp.
01180   if (UsedFP) {
01181     const MCRegisterInfo *MRI = getContext().getRegisterInfo();
01182     int64_t LastRegSaveSPOffset = SPOffset - PendingOffset;
01183     UnwindOpAsm.EmitSPOffset(LastRegSaveSPOffset - FPOffset);
01184     UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
01185   } else {
01186     FlushPendingOffset();
01187   }
01188 
01189   // Finalize the unwind opcode sequence
01190   UnwindOpAsm.Finalize(PersonalityIndex, Opcodes);
01191 
01192   // For compact model 0, we have to emit the unwind opcodes in the .ARM.exidx
01193   // section.  Thus, we don't have to create an entry in the .ARM.extab
01194   // section.
01195   if (NoHandlerData && PersonalityIndex == ARM::EHABI::AEABI_UNWIND_CPP_PR0)
01196     return;
01197 
01198   // Switch to .ARM.extab section.
01199   SwitchToExTabSection(*FnStart);
01200 
01201   // Create .ARM.extab label for offset in .ARM.exidx
01202   assert(!ExTab);
01203   ExTab = getContext().CreateTempSymbol();
01204   EmitLabel(ExTab);
01205 
01206   // Emit personality
01207   if (Personality) {
01208     const MCSymbolRefExpr *PersonalityRef =
01209       MCSymbolRefExpr::Create(Personality,
01210                               MCSymbolRefExpr::VK_ARM_PREL31,
01211                               getContext());
01212 
01213     EmitValue(PersonalityRef, 4);
01214   }
01215 
01216   // Emit unwind opcodes
01217   assert((Opcodes.size() % 4) == 0 &&
01218          "Unwind opcode size for __aeabi_cpp_unwind_pr0 must be multiple of 4");
01219   for (unsigned I = 0; I != Opcodes.size(); I += 4) {
01220     uint64_t Intval = Opcodes[I] |
01221                       Opcodes[I + 1] << 8 |
01222                       Opcodes[I + 2] << 16 |
01223                       Opcodes[I + 3] << 24;
01224     EmitIntValue(Intval, 4);
01225   }
01226 
01227   // According to ARM EHABI section 9.2, if the __aeabi_unwind_cpp_pr1() or
01228   // __aeabi_unwind_cpp_pr2() is used, then the handler data must be emitted
01229   // after the unwind opcodes.  The handler data consists of several 32-bit
01230   // words, and should be terminated by zero.
01231   //
01232   // In case that the .handlerdata directive is not specified by the
01233   // programmer, we should emit zero to terminate the handler data.
01234   if (NoHandlerData && !Personality)
01235     EmitIntValue(0, 4);
01236 }
01237 
01238 void ARMELFStreamer::emitHandlerData() { FlushUnwindOpcodes(false); }
01239 
01240 void ARMELFStreamer::emitPersonality(const MCSymbol *Per) {
01241   Personality = Per;
01242   UnwindOpAsm.setPersonality(Per);
01243 }
01244 
01245 void ARMELFStreamer::emitPersonalityIndex(unsigned Index) {
01246   assert(Index < ARM::EHABI::NUM_PERSONALITY_INDEX && "invalid index");
01247   PersonalityIndex = Index;
01248 }
01249 
01250 void ARMELFStreamer::emitSetFP(unsigned NewFPReg, unsigned NewSPReg,
01251                                int64_t Offset) {
01252   assert((NewSPReg == ARM::SP || NewSPReg == FPReg) &&
01253          "the operand of .setfp directive should be either $sp or $fp");
01254 
01255   UsedFP = true;
01256   FPReg = NewFPReg;
01257 
01258   if (NewSPReg == ARM::SP)
01259     FPOffset = SPOffset + Offset;
01260   else
01261     FPOffset += Offset;
01262 }
01263 
01264 void ARMELFStreamer::emitMovSP(unsigned Reg, int64_t Offset) {
01265   assert((Reg != ARM::SP && Reg != ARM::PC) &&
01266          "the operand of .movsp cannot be either sp or pc");
01267   assert(FPReg == ARM::SP && "current FP must be SP");
01268 
01269   FlushPendingOffset();
01270 
01271   FPReg = Reg;
01272   FPOffset = SPOffset + Offset;
01273 
01274   const MCRegisterInfo *MRI = getContext().getRegisterInfo();
01275   UnwindOpAsm.EmitSetSP(MRI->getEncodingValue(FPReg));
01276 }
01277 
01278 void ARMELFStreamer::emitPad(int64_t Offset) {
01279   // Track the change of the $sp offset
01280   SPOffset -= Offset;
01281 
01282   // To squash multiple .pad directives, we should delay the unwind opcode
01283   // until the .save, .vsave, .handlerdata, or .fnend directives.
01284   PendingOffset -= Offset;
01285 }
01286 
01287 void ARMELFStreamer::emitRegSave(const SmallVectorImpl<unsigned> &RegList,
01288                                  bool IsVector) {
01289   // Collect the registers in the register list
01290   unsigned Count = 0;
01291   uint32_t Mask = 0;
01292   const MCRegisterInfo *MRI = getContext().getRegisterInfo();
01293   for (size_t i = 0; i < RegList.size(); ++i) {
01294     unsigned Reg = MRI->getEncodingValue(RegList[i]);
01295     assert(Reg < (IsVector ? 32U : 16U) && "Register out of range");
01296     unsigned Bit = (1u << Reg);
01297     if ((Mask & Bit) == 0) {
01298       Mask |= Bit;
01299       ++Count;
01300     }
01301   }
01302 
01303   // Track the change the $sp offset: For the .save directive, the
01304   // corresponding push instruction will decrease the $sp by (4 * Count).
01305   // For the .vsave directive, the corresponding vpush instruction will
01306   // decrease $sp by (8 * Count).
01307   SPOffset -= Count * (IsVector ? 8 : 4);
01308 
01309   // Emit the opcode
01310   FlushPendingOffset();
01311   if (IsVector)
01312     UnwindOpAsm.EmitVFPRegSave(Mask);
01313   else
01314     UnwindOpAsm.EmitRegSave(Mask);
01315 }
01316 
01317 void ARMELFStreamer::emitUnwindRaw(int64_t Offset,
01318                                    const SmallVectorImpl<uint8_t> &Opcodes) {
01319   FlushPendingOffset();
01320   SPOffset = SPOffset - Offset;
01321   UnwindOpAsm.EmitRaw(Opcodes);
01322 }
01323 
01324 namespace llvm {
01325 
01326 MCStreamer *createMCAsmStreamer(MCContext &Ctx, formatted_raw_ostream &OS,
01327                                 bool isVerboseAsm, bool useDwarfDirectory,
01328                                 MCInstPrinter *InstPrint, MCCodeEmitter *CE,
01329                                 MCAsmBackend *TAB, bool ShowInst) {
01330   MCStreamer *S = llvm::createAsmStreamer(
01331       Ctx, OS, isVerboseAsm, useDwarfDirectory, InstPrint, CE, TAB, ShowInst);
01332   new ARMTargetAsmStreamer(*S, OS, *InstPrint, isVerboseAsm);
01333   return S;
01334 }
01335 
01336 MCStreamer *createARMNullStreamer(MCContext &Ctx) {
01337   MCStreamer *S = llvm::createNullStreamer(Ctx);
01338   new ARMTargetStreamer(*S);
01339   return S;
01340 }
01341 
01342   MCELFStreamer* createARMELFStreamer(MCContext &Context, MCAsmBackend &TAB,
01343                                       raw_ostream &OS, MCCodeEmitter *Emitter,
01344                                       bool RelaxAll, bool NoExecStack,
01345                                       bool IsThumb) {
01346     ARMELFStreamer *S = new ARMELFStreamer(Context, TAB, OS, Emitter, IsThumb);
01347     new ARMTargetELFStreamer(*S);
01348     // FIXME: This should eventually end up somewhere else where more
01349     // intelligent flag decisions can be made. For now we are just maintaining
01350     // the status quo for ARM and setting EF_ARM_EABI_VER5 as the default.
01351     S->getAssembler().setELFHeaderEFlags(ELF::EF_ARM_EABI_VER5);
01352 
01353     if (RelaxAll)
01354       S->getAssembler().setRelaxAll(true);
01355     if (NoExecStack)
01356       S->getAssembler().setNoExecStack(true);
01357     return S;
01358   }
01359 
01360 }
01361 
01362