MC: Move the backend section and symbol data maps to MCAssembler.
[oota-llvm.git] / lib / MC / MCMachOStreamer.cpp
index b53a82e95863645462baef72c96ff66fa410fc8f..a35aae29a8ce3685a98699f0f3b423c6cd4698a8 100644 (file)
@@ -12,6 +12,7 @@
 #include "llvm/MC/MCAssembler.h"
 #include "llvm/MC/MCContext.h"
 #include "llvm/MC/MCCodeEmitter.h"
+#include "llvm/MC/MCExpr.h"
 #include "llvm/MC/MCInst.h"
 #include "llvm/MC/MCSection.h"
 #include "llvm/MC/MCSymbol.h"
@@ -44,15 +45,9 @@ class MCMachOStreamer : public MCStreamer {
 
 private:
   MCAssembler Assembler;
-
   MCCodeEmitter *Emitter;
-
   MCSectionData *CurSectionData;
 
-  DenseMap<const MCSection*, MCSectionData*> SectionMap;
-  
-  DenseMap<const MCSymbol*, MCSymbolData*> SymbolMap;
-
 private:
   MCFragment *getCurrentFragment() const {
     assert(CurSectionData && "No current section!");
@@ -63,35 +58,35 @@ private:
     return 0;
   }
 
-  MCSectionData &getSectionData(const MCSection &Section) {
-    MCSectionData *&Entry = SectionMap[&Section];
-
-    if (!Entry)
-      Entry = new MCSectionData(Section, &Assembler);
-
-    return *Entry;
-  }
-
-  MCSymbolData &getSymbolData(MCSymbol &Symbol) {
-    MCSymbolData *&Entry = SymbolMap[&Symbol];
-
-    if (!Entry)
-      Entry = new MCSymbolData(Symbol, 0, 0, &Assembler);
-
-    return *Entry;
-  }
-
 public:
   MCMachOStreamer(MCContext &Context, raw_ostream &_OS, MCCodeEmitter *_Emitter)
-    : MCStreamer(Context), Assembler(_OS), Emitter(_Emitter),
+    : MCStreamer(Context), Assembler(Context, _OS), Emitter(_Emitter),
       CurSectionData(0) {}
   ~MCMachOStreamer() {}
 
-  const MCValue &AddValueSymbols(const MCValue &Value) {
-    if (Value.getSymA())
-      getSymbolData(*const_cast<MCSymbol*>(Value.getSymA()));
-    if (Value.getSymB())
-      getSymbolData(*const_cast<MCSymbol*>(Value.getSymB()));
+  const MCExpr *AddValueSymbols(const MCExpr *Value) {
+    switch (Value->getKind()) {
+    case MCExpr::Target: assert(0 && "Can't handle target exprs yet!");
+    case MCExpr::Constant:
+      break;
+
+    case MCExpr::Binary: {
+      const MCBinaryExpr *BE = cast<MCBinaryExpr>(Value);
+      AddValueSymbols(BE->getLHS());
+      AddValueSymbols(BE->getRHS());
+      break;
+    }
+
+    case MCExpr::SymbolRef:
+      Assembler.getOrCreateSymbolData(
+        cast<MCSymbolRefExpr>(Value)->getSymbol());
+      break;
+
+    case MCExpr::Unary:
+      AddValueSymbols(cast<MCUnaryExpr>(Value)->getSubExpr());
+      break;
+    }
+
     return Value;
   }
 
@@ -99,39 +94,42 @@ public:
   /// @{
 
   virtual void SwitchSection(const MCSection *Section);
-
   virtual void EmitLabel(MCSymbol *Symbol);
-
-  virtual void EmitAssemblerFlag(AssemblerFlag Flag);
-
-  virtual void EmitAssignment(MCSymbol *Symbol, const MCValue &Value,
-                              bool MakeAbsolute = false);
-
-  virtual void EmitSymbolAttribute(MCSymbol *Symbol, SymbolAttr Attribute);
-
+  virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
+  virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
+  virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
-
-  virtual void EmitLocalSymbol(MCSymbol *Symbol, const MCValue &Value);
-
-  virtual void EmitCommonSymbol(MCSymbol *Symbol, unsigned Size,
-                                unsigned Pow2Alignment);
-
+  virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
+                                unsigned ByteAlignment);
+  virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
+    assert(0 && "macho doesn't support this directive");
+  }
+  virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
+    assert(0 && "macho doesn't support this directive");
+  }
   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol = 0,
-                            unsigned Size = 0, unsigned Pow2Alignment = 0);
-
-  virtual void EmitBytes(const StringRef &Data);
-
-  virtual void EmitValue(const MCValue &Value, unsigned Size);
-
+                            unsigned Size = 0, unsigned ByteAlignment = 0);
+  virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
+  virtual void EmitValue(const MCExpr *Value, unsigned Size,unsigned AddrSpace);
+  virtual void EmitGPRel32Value(const MCExpr *Value) {
+    assert(0 && "macho doesn't support this directive");
+  }
   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value = 0,
                                     unsigned ValueSize = 1,
                                     unsigned MaxBytesToEmit = 0);
-
-  virtual void EmitValueToOffset(const MCValue &Offset,
+  virtual void EmitCodeAlignment(unsigned ByteAlignment,
+                                 unsigned MaxBytesToEmit = 0);
+  virtual void EmitValueToOffset(const MCExpr *Offset,
                                  unsigned char Value = 0);
-
+  
+  virtual void EmitFileDirective(StringRef Filename) {
+    errs() << "FIXME: MCMachoStreamer:EmitFileDirective not implemented\n";
+  }
+  virtual void EmitDwarfFileDirective(unsigned FileNo, StringRef Filename) {
+    errs() << "FIXME: MCMachoStreamer:EmitDwarfFileDirective not implemented\n";
+  }
+  
   virtual void EmitInstruction(const MCInst &Inst);
-
   virtual void Finish();
 
   /// @}
@@ -146,7 +144,7 @@ void MCMachOStreamer::SwitchSection(const MCSection *Section) {
   if (Section == CurSection) return;
 
   CurSection = Section;
-  CurSectionData = &getSectionData(*Section);
+  CurSectionData = &Assembler.getOrCreateSectionData(*Section);
 }
 
 void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
@@ -157,7 +155,7 @@ void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
   if (!F)
     F = new MCDataFragment(CurSectionData);
 
-  MCSymbolData &SD = getSymbolData(*Symbol);
+  MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
   assert(!SD.getFragment() && "Unexpected fragment on symbol data!");
   SD.setFragment(F);
   SD.setOffset(F->getContents().size());
@@ -168,32 +166,31 @@ void MCMachOStreamer::EmitLabel(MCSymbol *Symbol) {
   Symbol->setSection(*CurSection);
 }
 
-void MCMachOStreamer::EmitAssemblerFlag(AssemblerFlag Flag) {
+void MCMachOStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
   switch (Flag) {
-  default:
-    llvm_unreachable("FIXME: Not yet implemented!");
-
-  case SubsectionsViaSymbols:
+  case MCAF_SubsectionsViaSymbols:
     Assembler.setSubsectionsViaSymbols(true);
-    break;
+    return;
   }
+
+  assert(0 && "invalid assembler flag!");
 }
 
-void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol,
-                                     const MCValue &Value,
-                                     bool MakeAbsolute) {
+void MCMachOStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
   // Only absolute symbols can be redefined.
   assert((Symbol->isUndefined() || Symbol->isAbsolute()) &&
          "Cannot define a symbol twice!");
 
-  llvm_unreachable("FIXME: Not yet implemented!");
+  // FIXME: Lift context changes into super class.
+  // FIXME: Set associated section.
+  Symbol->setValue(Value);
 }
 
 void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
-                                          SymbolAttr Attribute) {
+                                          MCSymbolAttr Attribute) {
   // Indirect symbols are handled differently, to match how 'as' handles
   // them. This makes writing matching .o files easier.
-  if (Attribute == MCStreamer::IndirectSymbol) {
+  if (Attribute == MCSA_IndirectSymbol) {
     // Note that we intentionally cannot use the symbol data here; this is
     // important for matching the string table that 'as' generates.
     IndirectSymbolData ISD;
@@ -204,9 +201,9 @@ void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
   }
 
   // Adding a symbol attribute always introduces the symbol, note that an
-  // important side effect of calling getSymbolData here is to register the
-  // symbol with the assembler.
-  MCSymbolData &SD = getSymbolData(*Symbol);
+  // important side effect of calling getOrCreateSymbolData here is to register
+  // the symbol with the assembler.
+  MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
 
   // The implementation of symbol attributes is designed to match 'as', but it
   // leaves much to desired. It doesn't really make sense to arbitrarily add and
@@ -215,19 +212,27 @@ void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
   // In the future it might be worth trying to make these operations more well
   // defined.
   switch (Attribute) {
-  case MCStreamer::IndirectSymbol:
-  case MCStreamer::Hidden:
-  case MCStreamer::Internal:
-  case MCStreamer::Protected:
-  case MCStreamer::Weak:
+  case MCSA_Invalid:
+  case MCSA_ELF_TypeFunction:
+  case MCSA_ELF_TypeIndFunction:
+  case MCSA_ELF_TypeObject:
+  case MCSA_ELF_TypeTLS:
+  case MCSA_ELF_TypeCommon:
+  case MCSA_ELF_TypeNoType:
+  case MCSA_IndirectSymbol:
+  case MCSA_Hidden:
+  case MCSA_Internal:
+  case MCSA_Protected:
+  case MCSA_Weak:
+  case MCSA_Local:
     assert(0 && "Invalid symbol attribute for Mach-O!");
     break;
 
-  case MCStreamer::Global:
-    getSymbolData(*Symbol).setExternal(true);
+  case MCSA_Global:
+    SD.setExternal(true);
     break;
 
-  case MCStreamer::LazyReference:
+  case MCSA_LazyReference:
     // FIXME: This requires -dynamic.
     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
     if (Symbol->isUndefined())
@@ -236,23 +241,23 @@ void MCMachOStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
 
     // Since .reference sets the no dead strip bit, it is equivalent to
     // .no_dead_strip in practice.
-  case MCStreamer::Reference:
-  case MCStreamer::NoDeadStrip:
+  case MCSA_Reference:
+  case MCSA_NoDeadStrip:
     SD.setFlags(SD.getFlags() | SF_NoDeadStrip);
     break;
 
-  case MCStreamer::PrivateExtern:
+  case MCSA_PrivateExtern:
     SD.setExternal(true);
     SD.setPrivateExtern(true);
     break;
 
-  case MCStreamer::WeakReference:
+  case MCSA_WeakReference:
     // FIXME: This requires -dynamic.
     if (Symbol->isUndefined())
       SD.setFlags(SD.getFlags() | SF_WeakReference);
     break;
 
-  case MCStreamer::WeakDefinition:
+  case MCSA_WeakDefinition:
     // FIXME: 'as' enforces that this is defined and global. The manual claims
     // it has to be in a coalesced section, but this isn't enforced.
     SD.setFlags(SD.getFlags() | SF_WeakDefinition);
@@ -264,22 +269,22 @@ void MCMachOStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
   // Encode the 'desc' value into the lowest implementation defined bits.
   assert(DescValue == (DescValue & SF_DescFlagsMask) && 
          "Invalid .desc value!");
-  getSymbolData(*Symbol).setFlags(DescValue & SF_DescFlagsMask);
+  Assembler.getOrCreateSymbolData(*Symbol).setFlags(DescValue&SF_DescFlagsMask);
 }
 
-void MCMachOStreamer::EmitLocalSymbol(MCSymbol *Symbol, const MCValue &Value) {
-  llvm_unreachable("FIXME: Not yet implemented!");
-}
+void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
+                                       unsigned ByteAlignment) {
+  // FIXME: Darwin 'as' does appear to allow redef of a .comm by itself.
+  assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
 
-void MCMachOStreamer::EmitCommonSymbol(MCSymbol *Symbol, unsigned Size,
-                                       unsigned Pow2Alignment) {
-  llvm_unreachable("FIXME: Not yet implemented!");
+  MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
+  SD.setExternal(true);
+  SD.setCommon(Size, ByteAlignment);
 }
 
 void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
-                                   unsigned Size, unsigned Pow2Alignment) {
-  unsigned ByteAlignment = 1 << Pow2Alignment;
-  MCSectionData &SectData = getSectionData(*Section);
+                                   unsigned Size, unsigned ByteAlignment) {
+  MCSectionData &SectData = Assembler.getOrCreateSectionData(*Section);
 
   // The symbol may not be present, which only creates the section.
   if (!Symbol)
@@ -289,9 +294,9 @@ void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
 
   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
 
-  MCSymbolData &SD = getSymbolData(*Symbol);
+  MCSymbolData &SD = Assembler.getOrCreateSymbolData(*Symbol);
 
-  MCFragment *F = new MCZeroFillFragment(Size, 1 << Pow2Alignment, &SectData);
+  MCFragment *F = new MCZeroFillFragment(Size, ByteAlignment, &SectData);
   SD.setFragment(F);
 
   Symbol->setSection(*Section);
@@ -301,15 +306,31 @@ void MCMachOStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
     SectData.setAlignment(ByteAlignment);
 }
 
-void MCMachOStreamer::EmitBytes(const StringRef &Data) {
+void MCMachOStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
   MCDataFragment *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
   if (!DF)
     DF = new MCDataFragment(CurSectionData);
   DF->getContents().append(Data.begin(), Data.end());
 }
 
-void MCMachOStreamer::EmitValue(const MCValue &Value, unsigned Size) {
-  new MCFillFragment(AddValueSymbols(Value), Size, 1, CurSectionData);
+void MCMachOStreamer::EmitValue(const MCExpr *Value, unsigned Size,
+                                unsigned AddrSpace) {
+  MCDataFragment *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
+  if (!DF)
+    DF = new MCDataFragment(CurSectionData);
+
+  // Avoid fixups when possible.
+  int64_t AbsValue;
+  if (AddValueSymbols(Value)->EvaluateAsAbsolute(AbsValue)) {
+    // FIXME: Endianness assumption.
+    for (unsigned i = 0; i != Size; ++i)
+      DF->getContents().push_back(uint8_t(AbsValue >> (i * 8)));
+  } else {
+    DF->getFixups().push_back(MCAsmFixup(DF->getContents().size(),
+                                         *AddValueSymbols(Value),
+                                         MCFixup::getKindForSize(Size)));
+    DF->getContents().resize(DF->getContents().size() + Size, 0);
+  }
 }
 
 void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
@@ -318,32 +339,59 @@ void MCMachOStreamer::EmitValueToAlignment(unsigned ByteAlignment,
   if (MaxBytesToEmit == 0)
     MaxBytesToEmit = ByteAlignment;
   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
-                      CurSectionData);
+                      false /* EmitNops */, CurSectionData);
 
   // Update the maximum alignment on the current section if necessary.
   if (ByteAlignment > CurSectionData->getAlignment())
     CurSectionData->setAlignment(ByteAlignment);
 }
 
-void MCMachOStreamer::EmitValueToOffset(const MCValue &Offset,
+void MCMachOStreamer::EmitCodeAlignment(unsigned ByteAlignment,
+                                        unsigned MaxBytesToEmit) {
+  if (MaxBytesToEmit == 0)
+    MaxBytesToEmit = ByteAlignment;
+  // FIXME the 0x90 is the default x86 1 byte nop opcode.
+  new MCAlignFragment(ByteAlignment, 0x90, 1, MaxBytesToEmit,
+                      true /* EmitNops */, CurSectionData);
+
+  // Update the maximum alignment on the current section if necessary.
+  if (ByteAlignment > CurSectionData->getAlignment())
+    CurSectionData->setAlignment(ByteAlignment);
+}
+
+void MCMachOStreamer::EmitValueToOffset(const MCExpr *Offset,
                                         unsigned char Value) {
-  new MCOrgFragment(AddValueSymbols(Offset), Value, CurSectionData);
+  new MCOrgFragment(*Offset, Value, CurSectionData);
 }
 
 void MCMachOStreamer::EmitInstruction(const MCInst &Inst) {
   // Scan for values.
   for (unsigned i = 0; i != Inst.getNumOperands(); ++i)
-    if (Inst.getOperand(i).isMCValue())
-      AddValueSymbols(Inst.getOperand(i).getMCValue());
+    if (Inst.getOperand(i).isExpr())
+      AddValueSymbols(Inst.getOperand(i).getExpr());
 
   if (!Emitter)
     llvm_unreachable("no code emitter available!");
 
-  // FIXME: Relocations!
+  CurSectionData->setHasInstructions(true);
+
+  SmallVector<MCFixup, 4> Fixups;
   SmallString<256> Code;
   raw_svector_ostream VecOS(Code);
-  Emitter->EncodeInstruction(Inst, VecOS);
-  EmitBytes(VecOS.str());
+  Emitter->EncodeInstruction(Inst, VecOS, Fixups);
+  VecOS.flush();
+
+  // Add the fixups and data.
+  MCDataFragment *DF = dyn_cast_or_null<MCDataFragment>(getCurrentFragment());
+  if (!DF)
+    DF = new MCDataFragment(CurSectionData);
+  for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
+    MCFixup &F = Fixups[i];
+    DF->getFixups().push_back(MCAsmFixup(DF->getContents().size()+F.getOffset(),
+                                         *F.getValue(),
+                                         F.getKind()));
+  }
+  DF->getContents().append(Code.begin(), Code.end());
 }
 
 void MCMachOStreamer::Finish() {