Move EmitValue to MCObjectStreamer.
[oota-llvm.git] / lib / MC / WinCOFFStreamer.cpp
1 //===-- llvm/MC/WinCOFFStreamer.cpp -----------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains an implementation of a Win32 COFF object file streamer.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "WinCOFFStreamer"
15
16 #include "llvm/MC/MCObjectStreamer.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCSection.h"
19 #include "llvm/MC/MCSymbol.h"
20 #include "llvm/MC/MCExpr.h"
21 #include "llvm/MC/MCValue.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCAsmLayout.h"
24 #include "llvm/MC/MCCodeEmitter.h"
25 #include "llvm/MC/MCSectionCOFF.h"
26 #include "llvm/Target/TargetRegistry.h"
27 #include "llvm/Target/TargetAsmBackend.h"
28 #include "llvm/ADT/StringMap.h"
29
30 #include "llvm/Support/COFF.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 using namespace llvm;
35
36 namespace {
37 class WinCOFFStreamer : public MCObjectStreamer {
38 public:
39   MCSymbol const *CurSymbol;
40
41   WinCOFFStreamer(MCContext &Context,
42                   TargetAsmBackend &TAB,
43                   MCCodeEmitter &CE,
44                   raw_ostream &OS);
45
46   void AddCommonSymbol(MCSymbol *Symbol, uint64_t Size,
47                        unsigned ByteAlignment, bool External);
48
49   // MCStreamer interface
50
51   virtual void InitSections();
52   virtual void EmitLabel(MCSymbol *Symbol);
53   virtual void EmitAssemblerFlag(MCAssemblerFlag Flag);
54   virtual void EmitThumbFunc(MCSymbol *Func);
55   virtual void EmitAssignment(MCSymbol *Symbol, const MCExpr *Value);
56   virtual void EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute);
57   virtual void EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue);
58   virtual void BeginCOFFSymbolDef(MCSymbol const *Symbol);
59   virtual void EmitCOFFSymbolStorageClass(int StorageClass);
60   virtual void EmitCOFFSymbolType(int Type);
61   virtual void EndCOFFSymbolDef();
62   virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value);
63   virtual void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
64                                 unsigned ByteAlignment);
65   virtual void EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size);
66   virtual void EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
67                             unsigned Size,unsigned ByteAlignment);
68   virtual void EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
69                               uint64_t Size, unsigned ByteAlignment);
70   virtual void EmitBytes(StringRef Data, unsigned AddrSpace);
71   virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value,
72                                    unsigned ValueSize, unsigned MaxBytesToEmit);
73   virtual void EmitCodeAlignment(unsigned ByteAlignment,
74                                  unsigned MaxBytesToEmit);
75   virtual void EmitValueToOffset(const MCExpr *Offset, unsigned char Value);
76   virtual void EmitFileDirective(StringRef Filename);
77   virtual void EmitInstruction(const MCInst &Instruction);
78   virtual void Finish();
79
80 private:
81   virtual void EmitInstToFragment(const MCInst &Inst) {
82     llvm_unreachable("Not used by WinCOFF.");
83   }
84   virtual void EmitInstToData(const MCInst &Inst) {
85     llvm_unreachable("Not used by WinCOFF.");
86   }
87
88   void SetSection(StringRef Section,
89                   unsigned Characteristics,
90                   SectionKind Kind) {
91     SwitchSection(getContext().getCOFFSection(Section, Characteristics, Kind));
92   }
93
94   void SetSectionText() {
95     SetSection(".text",
96                COFF::IMAGE_SCN_CNT_CODE
97              | COFF::IMAGE_SCN_MEM_EXECUTE
98              | COFF::IMAGE_SCN_MEM_READ,
99                SectionKind::getText());
100     EmitCodeAlignment(4, 0);
101   }
102
103   void SetSectionData() {
104     SetSection(".data",
105                COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
106              | COFF::IMAGE_SCN_MEM_READ
107              | COFF::IMAGE_SCN_MEM_WRITE,
108                SectionKind::getDataRel());
109     EmitCodeAlignment(4, 0);
110   }
111
112   void SetSectionBSS() {
113     SetSection(".bss",
114                COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA
115              | COFF::IMAGE_SCN_MEM_READ
116              | COFF::IMAGE_SCN_MEM_WRITE,
117                SectionKind::getBSS());
118     EmitCodeAlignment(4, 0);
119   }
120
121 };
122 } // end anonymous namespace.
123
124 WinCOFFStreamer::WinCOFFStreamer(MCContext &Context,
125                                  TargetAsmBackend &TAB,
126                                  MCCodeEmitter &CE,
127                                  raw_ostream &OS)
128     : MCObjectStreamer(Context, TAB, OS, &CE, true)
129     , CurSymbol(NULL) {
130 }
131
132 void WinCOFFStreamer::AddCommonSymbol(MCSymbol *Symbol, uint64_t Size,
133                                       unsigned ByteAlignment, bool External) {
134   assert(!Symbol->isInSection() && "Symbol must not already have a section!");
135
136   std::string SectionName(".bss$linkonce");
137   SectionName.append(Symbol->getName().begin(), Symbol->getName().end());
138
139   MCSymbolData &SymbolData = getAssembler().getOrCreateSymbolData(*Symbol);
140
141   unsigned Characteristics =
142     COFF::IMAGE_SCN_LNK_COMDAT |
143     COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
144     COFF::IMAGE_SCN_MEM_READ |
145     COFF::IMAGE_SCN_MEM_WRITE;
146
147   int Selection = COFF::IMAGE_COMDAT_SELECT_LARGEST;
148
149   const MCSection *Section = MCStreamer::getContext().getCOFFSection(
150     SectionName, Characteristics, Selection, SectionKind::getBSS());
151
152   MCSectionData &SectionData = getAssembler().getOrCreateSectionData(*Section);
153
154   if (SectionData.getAlignment() < ByteAlignment)
155     SectionData.setAlignment(ByteAlignment);
156
157   SymbolData.setExternal(External);
158
159   Symbol->setSection(*Section);
160
161   if (ByteAlignment != 1)
162       new MCAlignFragment(ByteAlignment, 0, 0, ByteAlignment, &SectionData);
163
164   SymbolData.setFragment(new MCFillFragment(0, 0, Size, &SectionData));
165 }
166
167 // MCStreamer interface
168
169 void WinCOFFStreamer::InitSections() {
170   SetSectionText();
171   SetSectionData();
172   SetSectionBSS();
173   SetSectionText();
174 }
175
176 void WinCOFFStreamer::EmitLabel(MCSymbol *Symbol) {
177   assert(Symbol->isUndefined() && "Cannot define a symbol twice!");
178   MCObjectStreamer::EmitLabel(Symbol);
179 }
180
181 void WinCOFFStreamer::EmitAssemblerFlag(MCAssemblerFlag Flag) {
182   llvm_unreachable("not implemented");
183 }
184
185 void WinCOFFStreamer::EmitThumbFunc(MCSymbol *Func) {
186   llvm_unreachable("not implemented");
187 }
188
189 void WinCOFFStreamer::EmitAssignment(MCSymbol *Symbol, const MCExpr *Value) {
190   assert((Symbol->isInSection()
191          ? Symbol->getSection().getVariant() == MCSection::SV_COFF
192          : true) && "Got non COFF section in the COFF backend!");
193   // FIXME: This is all very ugly and depressing. What needs to happen here
194   // depends on quite a few things that are all part of relaxation, which we
195   // don't really even do.
196
197   if (Value->getKind() != MCExpr::SymbolRef) {
198     // TODO: This is exactly the same as MachOStreamer. Consider merging into
199     // MCObjectStreamer.
200     getAssembler().getOrCreateSymbolData(*Symbol);
201     AddValueSymbols(Value);
202     Symbol->setVariableValue(Value);
203   } else {
204     // FIXME: This is a horrible way to do this :(. This should really be
205     // handled after we are done with the MC* objects and immediately before
206     // writing out the object file when we know exactly what the symbol should
207     // look like in the coff symbol table. I'm not doing that now because the
208     // COFF object writer doesn't have a clearly defined separation between MC
209     // data structures, the object writers data structures, and the raw, POD,
210     // data structures that get written to disk.
211
212     // Copy over the aliased data.
213     MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
214     const MCSymbolData &RealSD = getAssembler().getOrCreateSymbolData(
215       dyn_cast<const MCSymbolRefExpr>(Value)->getSymbol());
216
217     // FIXME: This is particularly nasty because it breaks as soon as any data
218     // members of MCSymbolData change.
219     SD.CommonAlign     = RealSD.CommonAlign;
220     SD.CommonSize      = RealSD.CommonSize;
221     SD.Flags           = RealSD.Flags;
222     SD.Fragment        = RealSD.Fragment;
223     SD.Index           = RealSD.Index;
224     SD.IsExternal      = RealSD.IsExternal;
225     SD.IsPrivateExtern = RealSD.IsPrivateExtern;
226     SD.Offset          = RealSD.Offset;
227     SD.SymbolSize      = RealSD.SymbolSize;
228   }
229 }
230
231 void WinCOFFStreamer::EmitSymbolAttribute(MCSymbol *Symbol,
232                                           MCSymbolAttr Attribute) {
233   assert(Symbol && "Symbol must be non-null!");
234   assert((Symbol->isInSection()
235          ? Symbol->getSection().getVariant() == MCSection::SV_COFF
236          : true) && "Got non COFF section in the COFF backend!");
237   switch (Attribute) {
238   case MCSA_WeakReference:
239   case MCSA_Weak: {
240       MCSymbolData &SD = getAssembler().getOrCreateSymbolData(*Symbol);
241       SD.modifyFlags(COFF::SF_WeakExternal, COFF::SF_WeakExternal);
242       SD.setExternal(true);
243     }
244     break;
245
246   case MCSA_Global:
247     getAssembler().getOrCreateSymbolData(*Symbol).setExternal(true);
248     break;
249
250   default:
251     llvm_unreachable("unsupported attribute");
252     break;
253   }
254 }
255
256 void WinCOFFStreamer::EmitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
257   llvm_unreachable("not implemented");
258 }
259
260 void WinCOFFStreamer::BeginCOFFSymbolDef(MCSymbol const *Symbol) {
261   assert((Symbol->isInSection()
262          ? Symbol->getSection().getVariant() == MCSection::SV_COFF
263          : true) && "Got non COFF section in the COFF backend!");
264   assert(CurSymbol == NULL && "EndCOFFSymbolDef must be called between calls "
265                               "to BeginCOFFSymbolDef!");
266   CurSymbol = Symbol;
267 }
268
269 void WinCOFFStreamer::EmitCOFFSymbolStorageClass(int StorageClass) {
270   assert(CurSymbol != NULL && "BeginCOFFSymbolDef must be called first!");
271   assert((StorageClass & ~0xFF) == 0 && "StorageClass must only have data in "
272                                         "the first byte!");
273
274   getAssembler().getOrCreateSymbolData(*CurSymbol).modifyFlags(
275     StorageClass << COFF::SF_ClassShift,
276     COFF::SF_ClassMask);
277 }
278
279 void WinCOFFStreamer::EmitCOFFSymbolType(int Type) {
280   assert(CurSymbol != NULL && "BeginCOFFSymbolDef must be called first!");
281   assert((Type & ~0xFFFF) == 0 && "Type must only have data in the first 2 "
282                                   "bytes");
283
284   getAssembler().getOrCreateSymbolData(*CurSymbol).modifyFlags(
285     Type << COFF::SF_TypeShift,
286     COFF::SF_TypeMask);
287 }
288
289 void WinCOFFStreamer::EndCOFFSymbolDef() {
290   assert(CurSymbol != NULL && "BeginCOFFSymbolDef must be called first!");
291   CurSymbol = NULL;
292 }
293
294 void WinCOFFStreamer::EmitELFSize(MCSymbol *Symbol, const MCExpr *Value) {
295   llvm_unreachable("not implemented");
296 }
297
298 void WinCOFFStreamer::EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
299                                        unsigned ByteAlignment) {
300   assert((Symbol->isInSection()
301          ? Symbol->getSection().getVariant() == MCSection::SV_COFF
302          : true) && "Got non COFF section in the COFF backend!");
303   AddCommonSymbol(Symbol, Size, ByteAlignment, true);
304 }
305
306 void WinCOFFStreamer::EmitLocalCommonSymbol(MCSymbol *Symbol, uint64_t Size) {
307   assert((Symbol->isInSection()
308          ? Symbol->getSection().getVariant() == MCSection::SV_COFF
309          : true) && "Got non COFF section in the COFF backend!");
310   AddCommonSymbol(Symbol, Size, 1, false);
311 }
312
313 void WinCOFFStreamer::EmitZerofill(const MCSection *Section, MCSymbol *Symbol,
314                                    unsigned Size,unsigned ByteAlignment) {
315   llvm_unreachable("not implemented");
316 }
317
318 void WinCOFFStreamer::EmitTBSSSymbol(const MCSection *Section, MCSymbol *Symbol,
319                                      uint64_t Size, unsigned ByteAlignment) {
320   llvm_unreachable("not implemented");
321 }
322
323 void WinCOFFStreamer::EmitBytes(StringRef Data, unsigned AddrSpace) {
324   // TODO: This is copied exactly from the MachOStreamer. Consider merging into
325   // MCObjectStreamer?
326   getOrCreateDataFragment()->getContents().append(Data.begin(), Data.end());
327 }
328
329 void WinCOFFStreamer::EmitValueToAlignment(unsigned ByteAlignment,
330                                            int64_t Value,
331                                            unsigned ValueSize,
332                                            unsigned MaxBytesToEmit) {
333   // TODO: This is copied exactly from the MachOStreamer. Consider merging into
334   // MCObjectStreamer?
335   if (MaxBytesToEmit == 0)
336     MaxBytesToEmit = ByteAlignment;
337   new MCAlignFragment(ByteAlignment, Value, ValueSize, MaxBytesToEmit,
338                       getCurrentSectionData());
339
340   // Update the maximum alignment on the current section if necessary.
341   if (ByteAlignment > getCurrentSectionData()->getAlignment())
342     getCurrentSectionData()->setAlignment(ByteAlignment);
343 }
344
345 void WinCOFFStreamer::EmitCodeAlignment(unsigned ByteAlignment,
346                                         unsigned MaxBytesToEmit) {
347   // TODO: This is copied exactly from the MachOStreamer. Consider merging into
348   // MCObjectStreamer?
349   if (MaxBytesToEmit == 0)
350     MaxBytesToEmit = ByteAlignment;
351   MCAlignFragment *F = new MCAlignFragment(ByteAlignment, 0, 1, MaxBytesToEmit,
352                                            getCurrentSectionData());
353   F->setEmitNops(true);
354
355   // Update the maximum alignment on the current section if necessary.
356   if (ByteAlignment > getCurrentSectionData()->getAlignment())
357     getCurrentSectionData()->setAlignment(ByteAlignment);
358 }
359
360 void WinCOFFStreamer::EmitValueToOffset(const MCExpr *Offset,
361                                         unsigned char Value) {
362   llvm_unreachable("not implemented");
363 }
364
365 void WinCOFFStreamer::EmitFileDirective(StringRef Filename) {
366   // Ignore for now, linkers don't care, and proper debug
367   // info will be a much large effort.
368 }
369
370 void WinCOFFStreamer::EmitInstruction(const MCInst &Instruction) {
371   for (unsigned i = 0, e = Instruction.getNumOperands(); i != e; ++i)
372     if (Instruction.getOperand(i).isExpr())
373       AddValueSymbols(Instruction.getOperand(i).getExpr());
374
375   getCurrentSectionData()->setHasInstructions(true);
376
377   MCInstFragment *Fragment =
378     new MCInstFragment(Instruction, getCurrentSectionData());
379
380   raw_svector_ostream VecOS(Fragment->getCode());
381
382   getAssembler().getEmitter().EncodeInstruction(Instruction, VecOS,
383                                                 Fragment->getFixups());
384 }
385
386 void WinCOFFStreamer::Finish() {
387   MCObjectStreamer::Finish();
388 }
389
390 namespace llvm
391 {
392   MCStreamer *createWinCOFFStreamer(MCContext &Context,
393                                     TargetAsmBackend &TAB,
394                                     MCCodeEmitter &CE,
395                                     raw_ostream &OS,
396                                     bool RelaxAll) {
397     WinCOFFStreamer *S = new WinCOFFStreamer(Context, TAB, CE, OS);
398     S->getAssembler().setRelaxAll(RelaxAll);
399     return S;
400   }
401 }