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