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