Completely rewrite ELFObjectWriter::RecordRelocation.
[oota-llvm.git] / include / llvm / MC / MCAssembler.h
1 //===- MCAssembler.h - Object File Generation -------------------*- 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 #ifndef LLVM_MC_MCASSEMBLER_H
11 #define LLVM_MC_MCASSEMBLER_H
12
13 #include "llvm/ADT/DenseMap.h"
14 #include "llvm/ADT/SmallPtrSet.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/ilist.h"
17 #include "llvm/ADT/ilist_node.h"
18 #include "llvm/MC/MCDirectives.h"
19 #include "llvm/MC/MCFixup.h"
20 #include "llvm/MC/MCInst.h"
21 #include "llvm/MC/MCSubtargetInfo.h"
22 #include "llvm/Support/Casting.h"
23 #include "llvm/Support/DataTypes.h"
24 #include <algorithm>
25 #include <vector> // FIXME: Shouldn't be needed.
26
27 namespace llvm {
28 class raw_ostream;
29 class MCAsmLayout;
30 class MCAssembler;
31 class MCContext;
32 class MCCodeEmitter;
33 class MCExpr;
34 class MCFragment;
35 class MCObjectWriter;
36 class MCSection;
37 class MCSectionData;
38 class MCSubtargetInfo;
39 class MCSymbol;
40 class MCSymbolData;
41 class MCValue;
42 class MCAsmBackend;
43
44 class MCFragment : public ilist_node<MCFragment> {
45   friend class MCAsmLayout;
46
47   MCFragment(const MCFragment&) LLVM_DELETED_FUNCTION;
48   void operator=(const MCFragment&) LLVM_DELETED_FUNCTION;
49
50 public:
51   enum FragmentType {
52     FT_Align,
53     FT_Data,
54     FT_Compressed,
55     FT_CompactEncodedInst,
56     FT_Fill,
57     FT_Relaxable,
58     FT_Org,
59     FT_Dwarf,
60     FT_DwarfFrame,
61     FT_LEB
62   };
63
64 private:
65   FragmentType Kind;
66
67   /// Parent - The data for the section this fragment is in.
68   MCSectionData *Parent;
69
70   /// Atom - The atom this fragment is in, as represented by it's defining
71   /// symbol.
72   MCSymbolData *Atom;
73
74   /// @name Assembler Backend Data
75   /// @{
76   //
77   // FIXME: This could all be kept private to the assembler implementation.
78
79   /// Offset - The offset of this fragment in its section. This is ~0 until
80   /// initialized.
81   uint64_t Offset;
82
83   /// LayoutOrder - The layout order of this fragment.
84   unsigned LayoutOrder;
85
86   /// @}
87
88 protected:
89   MCFragment(FragmentType _Kind, MCSectionData *_Parent = 0);
90
91 public:
92   // Only for sentinel.
93   MCFragment();
94   virtual ~MCFragment();
95
96   FragmentType getKind() const { return Kind; }
97
98   MCSectionData *getParent() const { return Parent; }
99   void setParent(MCSectionData *Value) { Parent = Value; }
100
101   MCSymbolData *getAtom() const { return Atom; }
102   void setAtom(MCSymbolData *Value) { Atom = Value; }
103
104   unsigned getLayoutOrder() const { return LayoutOrder; }
105   void setLayoutOrder(unsigned Value) { LayoutOrder = Value; }
106
107   /// \brief Does this fragment have instructions emitted into it? By default
108   /// this is false, but specific fragment types may set it to true.
109   virtual bool hasInstructions() const { return false; }
110
111   /// \brief Should this fragment be placed at the end of an aligned bundle?
112   virtual bool alignToBundleEnd() const { return false; }
113   virtual void setAlignToBundleEnd(bool V) { }
114
115   /// \brief Get the padding size that must be inserted before this fragment.
116   /// Used for bundling. By default, no padding is inserted.
117   /// Note that padding size is restricted to 8 bits. This is an optimization
118   /// to reduce the amount of space used for each fragment. In practice, larger
119   /// padding should never be required.
120   virtual uint8_t getBundlePadding() const {
121     return 0;
122   }
123
124   /// \brief Set the padding size for this fragment. By default it's a no-op,
125   /// and only some fragments have a meaningful implementation.
126   virtual void setBundlePadding(uint8_t N) {
127   }
128
129   void dump();
130 };
131
132 /// Interface implemented by fragments that contain encoded instructions and/or
133 /// data.
134 ///
135 class MCEncodedFragment : public MCFragment {
136   virtual void anchor();
137
138   uint8_t BundlePadding;
139 public:
140   MCEncodedFragment(MCFragment::FragmentType FType, MCSectionData *SD = 0)
141     : MCFragment(FType, SD), BundlePadding(0)
142   {
143   }
144   virtual ~MCEncodedFragment();
145
146   virtual SmallVectorImpl<char> &getContents() = 0;
147   virtual const SmallVectorImpl<char> &getContents() const = 0;
148
149   uint8_t getBundlePadding() const override {
150     return BundlePadding;
151   }
152
153   void setBundlePadding(uint8_t N) override {
154     BundlePadding = N;
155   }
156
157   static bool classof(const MCFragment *F) {
158     MCFragment::FragmentType Kind = F->getKind();
159     switch (Kind) {
160       default:
161         return false;
162       case MCFragment::FT_Relaxable:
163       case MCFragment::FT_CompactEncodedInst:
164       case MCFragment::FT_Compressed:
165       case MCFragment::FT_Data:
166         return true;
167     }
168   }
169 };
170
171 /// Interface implemented by fragments that contain encoded instructions and/or
172 /// data and also have fixups registered.
173 ///
174 class MCEncodedFragmentWithFixups : public MCEncodedFragment {
175   void anchor() override;
176
177 public:
178   MCEncodedFragmentWithFixups(MCFragment::FragmentType FType,
179                               MCSectionData *SD = 0)
180     : MCEncodedFragment(FType, SD)
181   {
182   }
183
184   virtual ~MCEncodedFragmentWithFixups();
185
186   typedef SmallVectorImpl<MCFixup>::const_iterator const_fixup_iterator;
187   typedef SmallVectorImpl<MCFixup>::iterator fixup_iterator;
188
189   virtual SmallVectorImpl<MCFixup> &getFixups() = 0;
190   virtual const SmallVectorImpl<MCFixup> &getFixups() const = 0;
191
192   virtual fixup_iterator fixup_begin() = 0;
193   virtual const_fixup_iterator fixup_begin() const  = 0;
194   virtual fixup_iterator fixup_end() = 0;
195   virtual const_fixup_iterator fixup_end() const = 0;
196
197   static bool classof(const MCFragment *F) {
198     MCFragment::FragmentType Kind = F->getKind();
199     return Kind == MCFragment::FT_Relaxable || Kind == MCFragment::FT_Data ||
200            Kind == MCFragment::FT_Compressed;
201   }
202 };
203
204 /// Fragment for data and encoded instructions.
205 ///
206 class MCDataFragment : public MCEncodedFragmentWithFixups {
207   void anchor() override;
208
209   /// \brief Does this fragment contain encoded instructions anywhere in it?
210   bool HasInstructions;
211
212   /// \brief Should this fragment be aligned to the end of a bundle?
213   bool AlignToBundleEnd;
214
215   SmallVector<char, 32> Contents;
216
217   /// Fixups - The list of fixups in this fragment.
218   SmallVector<MCFixup, 4> Fixups;
219 protected:
220   MCDataFragment(MCFragment::FragmentType FType, MCSectionData *SD = 0)
221       : MCEncodedFragmentWithFixups(FType, SD), HasInstructions(false),
222         AlignToBundleEnd(false) {}
223
224 public:
225   MCDataFragment(MCSectionData *SD = 0)
226     : MCEncodedFragmentWithFixups(FT_Data, SD),
227       HasInstructions(false), AlignToBundleEnd(false)
228   {
229   }
230
231   SmallVectorImpl<char> &getContents() override { return Contents; }
232   const SmallVectorImpl<char> &getContents() const override {
233     return Contents;
234   }
235
236   SmallVectorImpl<MCFixup> &getFixups() override {
237     return Fixups;
238   }
239
240   const SmallVectorImpl<MCFixup> &getFixups() const override {
241     return Fixups;
242   }
243
244   bool hasInstructions() const override { return HasInstructions; }
245   virtual void setHasInstructions(bool V) { HasInstructions = V; }
246
247   bool alignToBundleEnd() const override { return AlignToBundleEnd; }
248   void setAlignToBundleEnd(bool V) override { AlignToBundleEnd = V; }
249
250   fixup_iterator fixup_begin() override { return Fixups.begin(); }
251   const_fixup_iterator fixup_begin() const override { return Fixups.begin(); }
252
253   fixup_iterator fixup_end() override {return Fixups.end();}
254   const_fixup_iterator fixup_end() const override {return Fixups.end();}
255
256   static bool classof(const MCFragment *F) {
257     return F->getKind() == MCFragment::FT_Data ||
258            F->getKind() == MCFragment::FT_Compressed;
259   }
260 };
261
262 class MCCompressedFragment: public MCDataFragment {
263   mutable SmallVector<char, 32> CompressedContents;
264 public:
265   MCCompressedFragment(MCSectionData *SD = nullptr)
266       : MCDataFragment(FT_Compressed, SD) {}
267   const SmallVectorImpl<char> &getCompressedContents() const;
268   using MCDataFragment::getContents;
269   SmallVectorImpl<char> &getContents() override;
270 };
271
272 /// This is a compact (memory-size-wise) fragment for holding an encoded
273 /// instruction (non-relaxable) that has no fixups registered. When applicable,
274 /// it can be used instead of MCDataFragment and lead to lower memory
275 /// consumption.
276 ///
277 class MCCompactEncodedInstFragment : public MCEncodedFragment {
278   void anchor() override;
279
280   /// \brief Should this fragment be aligned to the end of a bundle?
281   bool AlignToBundleEnd;
282
283   SmallVector<char, 4> Contents;
284 public:
285   MCCompactEncodedInstFragment(MCSectionData *SD = 0)
286     : MCEncodedFragment(FT_CompactEncodedInst, SD), AlignToBundleEnd(false)
287   {
288   }
289
290   bool hasInstructions() const override {
291     return true;
292   }
293
294   SmallVectorImpl<char> &getContents() override { return Contents; }
295   const SmallVectorImpl<char> &getContents() const override { return Contents; }
296
297   bool alignToBundleEnd() const override { return AlignToBundleEnd; }
298   void setAlignToBundleEnd(bool V) override { AlignToBundleEnd = V; }
299
300   static bool classof(const MCFragment *F) {
301     return F->getKind() == MCFragment::FT_CompactEncodedInst;
302   }
303 };
304
305 /// A relaxable fragment holds on to its MCInst, since it may need to be
306 /// relaxed during the assembler layout and relaxation stage.
307 ///
308 class MCRelaxableFragment : public MCEncodedFragmentWithFixups {
309   void anchor() override;
310
311   /// Inst - The instruction this is a fragment for.
312   MCInst Inst;
313
314   /// STI - The MCSubtargetInfo in effect when the instruction was encoded.
315   /// Keep a copy instead of a reference to make sure that updates to STI
316   /// in the assembler are not seen here.
317   const MCSubtargetInfo STI;
318
319   /// Contents - Binary data for the currently encoded instruction.
320   SmallVector<char, 8> Contents;
321
322   /// Fixups - The list of fixups in this fragment.
323   SmallVector<MCFixup, 1> Fixups;
324
325 public:
326   MCRelaxableFragment(const MCInst &_Inst,
327                       const MCSubtargetInfo &_STI,
328                       MCSectionData *SD = 0)
329     : MCEncodedFragmentWithFixups(FT_Relaxable, SD), Inst(_Inst), STI(_STI) {
330   }
331
332   SmallVectorImpl<char> &getContents() override { return Contents; }
333   const SmallVectorImpl<char> &getContents() const override { return Contents; }
334
335   const MCInst &getInst() const { return Inst; }
336   void setInst(const MCInst& Value) { Inst = Value; }
337
338   const MCSubtargetInfo &getSubtargetInfo() { return STI; }
339
340   SmallVectorImpl<MCFixup> &getFixups() override {
341     return Fixups;
342   }
343
344   const SmallVectorImpl<MCFixup> &getFixups() const override {
345     return Fixups;
346   }
347
348   bool hasInstructions() const override { return true; }
349
350   fixup_iterator fixup_begin() override { return Fixups.begin(); }
351   const_fixup_iterator fixup_begin() const override { return Fixups.begin(); }
352
353   fixup_iterator fixup_end() override {return Fixups.end();}
354   const_fixup_iterator fixup_end() const override {return Fixups.end();}
355
356   static bool classof(const MCFragment *F) {
357     return F->getKind() == MCFragment::FT_Relaxable;
358   }
359 };
360
361 class MCAlignFragment : public MCFragment {
362   virtual void anchor();
363
364   /// Alignment - The alignment to ensure, in bytes.
365   unsigned Alignment;
366
367   /// Value - Value to use for filling padding bytes.
368   int64_t Value;
369
370   /// ValueSize - The size of the integer (in bytes) of \p Value.
371   unsigned ValueSize;
372
373   /// MaxBytesToEmit - The maximum number of bytes to emit; if the alignment
374   /// cannot be satisfied in this width then this fragment is ignored.
375   unsigned MaxBytesToEmit;
376
377   /// EmitNops - Flag to indicate that (optimal) NOPs should be emitted instead
378   /// of using the provided value. The exact interpretation of this flag is
379   /// target dependent.
380   bool EmitNops : 1;
381
382 public:
383   MCAlignFragment(unsigned _Alignment, int64_t _Value, unsigned _ValueSize,
384                   unsigned _MaxBytesToEmit, MCSectionData *SD = 0)
385     : MCFragment(FT_Align, SD), Alignment(_Alignment),
386       Value(_Value),ValueSize(_ValueSize),
387       MaxBytesToEmit(_MaxBytesToEmit), EmitNops(false) {}
388
389   /// @name Accessors
390   /// @{
391
392   unsigned getAlignment() const { return Alignment; }
393
394   int64_t getValue() const { return Value; }
395
396   unsigned getValueSize() const { return ValueSize; }
397
398   unsigned getMaxBytesToEmit() const { return MaxBytesToEmit; }
399
400   bool hasEmitNops() const { return EmitNops; }
401   void setEmitNops(bool Value) { EmitNops = Value; }
402
403   /// @}
404
405   static bool classof(const MCFragment *F) {
406     return F->getKind() == MCFragment::FT_Align;
407   }
408 };
409
410 class MCFillFragment : public MCFragment {
411   virtual void anchor();
412
413   /// Value - Value to use for filling bytes.
414   int64_t Value;
415
416   /// ValueSize - The size (in bytes) of \p Value to use when filling, or 0 if
417   /// this is a virtual fill fragment.
418   unsigned ValueSize;
419
420   /// Size - The number of bytes to insert.
421   uint64_t Size;
422
423 public:
424   MCFillFragment(int64_t _Value, unsigned _ValueSize, uint64_t _Size,
425                  MCSectionData *SD = 0)
426     : MCFragment(FT_Fill, SD),
427       Value(_Value), ValueSize(_ValueSize), Size(_Size) {
428     assert((!ValueSize || (Size % ValueSize) == 0) &&
429            "Fill size must be a multiple of the value size!");
430   }
431
432   /// @name Accessors
433   /// @{
434
435   int64_t getValue() const { return Value; }
436
437   unsigned getValueSize() const { return ValueSize; }
438
439   uint64_t getSize() const { return Size; }
440
441   /// @}
442
443   static bool classof(const MCFragment *F) {
444     return F->getKind() == MCFragment::FT_Fill;
445   }
446 };
447
448 class MCOrgFragment : public MCFragment {
449   virtual void anchor();
450
451   /// Offset - The offset this fragment should start at.
452   const MCExpr *Offset;
453
454   /// Value - Value to use for filling bytes.
455   int8_t Value;
456
457 public:
458   MCOrgFragment(const MCExpr &_Offset, int8_t _Value, MCSectionData *SD = 0)
459     : MCFragment(FT_Org, SD),
460       Offset(&_Offset), Value(_Value) {}
461
462   /// @name Accessors
463   /// @{
464
465   const MCExpr &getOffset() const { return *Offset; }
466
467   uint8_t getValue() const { return Value; }
468
469   /// @}
470
471   static bool classof(const MCFragment *F) {
472     return F->getKind() == MCFragment::FT_Org;
473   }
474 };
475
476 class MCLEBFragment : public MCFragment {
477   virtual void anchor();
478
479   /// Value - The value this fragment should contain.
480   const MCExpr *Value;
481
482   /// IsSigned - True if this is a sleb128, false if uleb128.
483   bool IsSigned;
484
485   SmallString<8> Contents;
486 public:
487   MCLEBFragment(const MCExpr &Value_, bool IsSigned_, MCSectionData *SD = 0)
488     : MCFragment(FT_LEB, SD),
489       Value(&Value_), IsSigned(IsSigned_) { Contents.push_back(0); }
490
491   /// @name Accessors
492   /// @{
493
494   const MCExpr &getValue() const { return *Value; }
495
496   bool isSigned() const { return IsSigned; }
497
498   SmallString<8> &getContents() { return Contents; }
499   const SmallString<8> &getContents() const { return Contents; }
500
501   /// @}
502
503   static bool classof(const MCFragment *F) {
504     return F->getKind() == MCFragment::FT_LEB;
505   }
506 };
507
508 class MCDwarfLineAddrFragment : public MCFragment {
509   virtual void anchor();
510
511   /// LineDelta - the value of the difference between the two line numbers
512   /// between two .loc dwarf directives.
513   int64_t LineDelta;
514
515   /// AddrDelta - The expression for the difference of the two symbols that
516   /// make up the address delta between two .loc dwarf directives.
517   const MCExpr *AddrDelta;
518
519   SmallString<8> Contents;
520
521 public:
522   MCDwarfLineAddrFragment(int64_t _LineDelta, const MCExpr &_AddrDelta,
523                       MCSectionData *SD = 0)
524     : MCFragment(FT_Dwarf, SD),
525       LineDelta(_LineDelta), AddrDelta(&_AddrDelta) { Contents.push_back(0); }
526
527   /// @name Accessors
528   /// @{
529
530   int64_t getLineDelta() const { return LineDelta; }
531
532   const MCExpr &getAddrDelta() const { return *AddrDelta; }
533
534   SmallString<8> &getContents() { return Contents; }
535   const SmallString<8> &getContents() const { return Contents; }
536
537   /// @}
538
539   static bool classof(const MCFragment *F) {
540     return F->getKind() == MCFragment::FT_Dwarf;
541   }
542 };
543
544 class MCDwarfCallFrameFragment : public MCFragment {
545   virtual void anchor();
546
547   /// AddrDelta - The expression for the difference of the two symbols that
548   /// make up the address delta between two .cfi_* dwarf directives.
549   const MCExpr *AddrDelta;
550
551   SmallString<8> Contents;
552
553 public:
554   MCDwarfCallFrameFragment(const MCExpr &_AddrDelta,  MCSectionData *SD = 0)
555     : MCFragment(FT_DwarfFrame, SD),
556       AddrDelta(&_AddrDelta) { Contents.push_back(0); }
557
558   /// @name Accessors
559   /// @{
560
561   const MCExpr &getAddrDelta() const { return *AddrDelta; }
562
563   SmallString<8> &getContents() { return Contents; }
564   const SmallString<8> &getContents() const { return Contents; }
565
566   /// @}
567
568   static bool classof(const MCFragment *F) {
569     return F->getKind() == MCFragment::FT_DwarfFrame;
570   }
571 };
572
573 // FIXME: Should this be a separate class, or just merged into MCSection? Since
574 // we anticipate the fast path being through an MCAssembler, the only reason to
575 // keep it out is for API abstraction.
576 class MCSectionData : public ilist_node<MCSectionData> {
577   friend class MCAsmLayout;
578
579   MCSectionData(const MCSectionData&) LLVM_DELETED_FUNCTION;
580   void operator=(const MCSectionData&) LLVM_DELETED_FUNCTION;
581
582 public:
583   typedef iplist<MCFragment> FragmentListType;
584
585   typedef FragmentListType::const_iterator const_iterator;
586   typedef FragmentListType::iterator iterator;
587
588   typedef FragmentListType::const_reverse_iterator const_reverse_iterator;
589   typedef FragmentListType::reverse_iterator reverse_iterator;
590
591   /// \brief Express the state of bundle locked groups while emitting code.
592   enum BundleLockStateType {
593     NotBundleLocked,
594     BundleLocked,
595     BundleLockedAlignToEnd
596   };
597 private:
598   FragmentListType Fragments;
599   const MCSection *Section;
600
601   /// Ordinal - The section index in the assemblers section list.
602   unsigned Ordinal;
603
604   /// LayoutOrder - The index of this section in the layout order.
605   unsigned LayoutOrder;
606
607   /// Alignment - The maximum alignment seen in this section.
608   unsigned Alignment;
609
610   /// \brief Keeping track of bundle-locked state.
611   BundleLockStateType BundleLockState; 
612
613   /// \brief We've seen a bundle_lock directive but not its first instruction
614   /// yet.
615   bool BundleGroupBeforeFirstInst;
616
617   /// @name Assembler Backend Data
618   /// @{
619   //
620   // FIXME: This could all be kept private to the assembler implementation.
621
622   /// HasInstructions - Whether this section has had instructions emitted into
623   /// it.
624   unsigned HasInstructions : 1;
625
626   /// Mapping from subsection number to insertion point for subsection numbers
627   /// below that number.
628   SmallVector<std::pair<unsigned, MCFragment *>, 1> SubsectionFragmentMap;
629
630   /// @}
631
632 public:
633   // Only for use as sentinel.
634   MCSectionData();
635   MCSectionData(const MCSection &Section, MCAssembler *A = 0);
636
637   const MCSection &getSection() const { return *Section; }
638
639   unsigned getAlignment() const { return Alignment; }
640   void setAlignment(unsigned Value) { Alignment = Value; }
641
642   bool hasInstructions() const { return HasInstructions; }
643   void setHasInstructions(bool Value) { HasInstructions = Value; }
644
645   unsigned getOrdinal() const { return Ordinal; }
646   void setOrdinal(unsigned Value) { Ordinal = Value; }
647
648   unsigned getLayoutOrder() const { return LayoutOrder; }
649   void setLayoutOrder(unsigned Value) { LayoutOrder = Value; }
650
651   /// @name Fragment Access
652   /// @{
653
654   const FragmentListType &getFragmentList() const { return Fragments; }
655   FragmentListType &getFragmentList() { return Fragments; }
656
657   iterator begin() { return Fragments.begin(); }
658   const_iterator begin() const { return Fragments.begin(); }
659
660   iterator end() { return Fragments.end(); }
661   const_iterator end() const { return Fragments.end(); }
662
663   reverse_iterator rbegin() { return Fragments.rbegin(); }
664   const_reverse_iterator rbegin() const { return Fragments.rbegin(); }
665
666   reverse_iterator rend() { return Fragments.rend(); }
667   const_reverse_iterator rend() const { return Fragments.rend(); }
668
669   size_t size() const { return Fragments.size(); }
670
671   bool empty() const { return Fragments.empty(); }
672
673   iterator getSubsectionInsertionPoint(unsigned Subsection);
674
675   bool isBundleLocked() const {
676     return BundleLockState != NotBundleLocked;
677   }
678
679   BundleLockStateType getBundleLockState() const {
680     return BundleLockState;
681   }
682
683   void setBundleLockState(BundleLockStateType NewState) {
684     BundleLockState = NewState;
685   }
686
687   bool isBundleGroupBeforeFirstInst() const {
688     return BundleGroupBeforeFirstInst;
689   }
690
691   void setBundleGroupBeforeFirstInst(bool IsFirst) {
692     BundleGroupBeforeFirstInst = IsFirst;
693   }
694
695   void dump();
696
697   /// @}
698 };
699
700 // FIXME: Same concerns as with SectionData.
701 class MCSymbolData : public ilist_node<MCSymbolData> {
702 public:
703   const MCSymbol *Symbol;
704
705   /// Fragment - The fragment this symbol's value is relative to, if any.
706   MCFragment *Fragment;
707
708   /// Offset - The offset to apply to the fragment address to form this symbol's
709   /// value.
710   uint64_t Offset;
711
712   /// IsExternal - True if this symbol is visible outside this translation
713   /// unit.
714   unsigned IsExternal : 1;
715
716   /// IsPrivateExtern - True if this symbol is private extern.
717   unsigned IsPrivateExtern : 1;
718
719   /// CommonSize - The size of the symbol, if it is 'common', or 0.
720   //
721   // FIXME: Pack this in with other fields? We could put it in offset, since a
722   // common symbol can never get a definition.
723   uint64_t CommonSize;
724
725   /// SymbolSize - An expression describing how to calculate the size of
726   /// a symbol. If a symbol has no size this field will be NULL.
727   const MCExpr *SymbolSize;
728
729   /// CommonAlign - The alignment of the symbol, if it is 'common'.
730   //
731   // FIXME: Pack this in with other fields?
732   unsigned CommonAlign;
733
734   /// Flags - The Flags field is used by object file implementations to store
735   /// additional per symbol information which is not easily classified.
736   uint32_t Flags;
737
738   /// Index - Index field, for use by the object file implementation.
739   uint64_t Index;
740
741 public:
742   // Only for use as sentinel.
743   MCSymbolData();
744   MCSymbolData(const MCSymbol &_Symbol, MCFragment *_Fragment, uint64_t _Offset,
745                MCAssembler *A = 0);
746
747   /// @name Accessors
748   /// @{
749
750   const MCSymbol &getSymbol() const { return *Symbol; }
751
752   MCFragment *getFragment() const { return Fragment; }
753   void setFragment(MCFragment *Value) { Fragment = Value; }
754
755   uint64_t getOffset() const { return Offset; }
756   void setOffset(uint64_t Value) { Offset = Value; }
757
758   /// @}
759   /// @name Symbol Attributes
760   /// @{
761
762   bool isExternal() const { return IsExternal; }
763   void setExternal(bool Value) { IsExternal = Value; }
764
765   bool isPrivateExtern() const { return IsPrivateExtern; }
766   void setPrivateExtern(bool Value) { IsPrivateExtern = Value; }
767
768   /// isCommon - Is this a 'common' symbol.
769   bool isCommon() const { return CommonSize != 0; }
770
771   /// setCommon - Mark this symbol as being 'common'.
772   ///
773   /// \param Size - The size of the symbol.
774   /// \param Align - The alignment of the symbol.
775   void setCommon(uint64_t Size, unsigned Align) {
776     CommonSize = Size;
777     CommonAlign = Align;
778   }
779
780   /// getCommonSize - Return the size of a 'common' symbol.
781   uint64_t getCommonSize() const {
782     assert(isCommon() && "Not a 'common' symbol!");
783     return CommonSize;
784   }
785
786   void setSize(const MCExpr *SS) {
787     SymbolSize = SS;
788   }
789
790   const MCExpr *getSize() const {
791     return SymbolSize;
792   }
793
794
795   /// getCommonAlignment - Return the alignment of a 'common' symbol.
796   unsigned getCommonAlignment() const {
797     assert(isCommon() && "Not a 'common' symbol!");
798     return CommonAlign;
799   }
800
801   /// getFlags - Get the (implementation defined) symbol flags.
802   uint32_t getFlags() const { return Flags; }
803
804   /// setFlags - Set the (implementation defined) symbol flags.
805   void setFlags(uint32_t Value) { Flags = Value; }
806
807   /// modifyFlags - Modify the flags via a mask
808   void modifyFlags(uint32_t Value, uint32_t Mask) {
809     Flags = (Flags & ~Mask) | Value;
810   }
811
812   /// getIndex - Get the (implementation defined) index.
813   uint64_t getIndex() const { return Index; }
814
815   /// setIndex - Set the (implementation defined) index.
816   void setIndex(uint64_t Value) { Index = Value; }
817
818   /// @}
819
820   void dump();
821 };
822
823 // FIXME: This really doesn't belong here. See comments below.
824 struct IndirectSymbolData {
825   MCSymbol *Symbol;
826   MCSectionData *SectionData;
827 };
828
829 // FIXME: Ditto this. Purely so the Streamer and the ObjectWriter can talk
830 // to one another.
831 struct DataRegionData {
832   // This enum should be kept in sync w/ the mach-o definition in
833   // llvm/Object/MachOFormat.h.
834   enum KindTy { Data = 1, JumpTable8, JumpTable16, JumpTable32 } Kind;
835   MCSymbol *Start;
836   MCSymbol *End;
837 };
838
839 class MCAssembler {
840   friend class MCAsmLayout;
841
842 public:
843   typedef iplist<MCSectionData> SectionDataListType;
844   typedef iplist<MCSymbolData> SymbolDataListType;
845
846   typedef SectionDataListType::const_iterator const_iterator;
847   typedef SectionDataListType::iterator iterator;
848
849   typedef SymbolDataListType::const_iterator const_symbol_iterator;
850   typedef SymbolDataListType::iterator symbol_iterator;
851
852   typedef std::vector<std::string> FileNameVectorType;
853   typedef FileNameVectorType::const_iterator const_file_name_iterator;
854
855   typedef std::vector<IndirectSymbolData>::const_iterator
856     const_indirect_symbol_iterator;
857   typedef std::vector<IndirectSymbolData>::iterator indirect_symbol_iterator;
858
859   typedef std::vector<DataRegionData>::const_iterator
860     const_data_region_iterator;
861   typedef std::vector<DataRegionData>::iterator data_region_iterator;
862
863   /// MachO specific deployment target version info.
864   // A Major version of 0 indicates that no version information was supplied
865   // and so the corresponding load command should not be emitted.
866   typedef struct {
867     MCVersionMinType Kind;
868     unsigned Major;
869     unsigned Minor;
870     unsigned Update;
871   } VersionMinInfoType;
872 private:
873   MCAssembler(const MCAssembler&) LLVM_DELETED_FUNCTION;
874   void operator=(const MCAssembler&) LLVM_DELETED_FUNCTION;
875
876   MCContext &Context;
877
878   MCAsmBackend &Backend;
879
880   MCCodeEmitter &Emitter;
881
882   MCObjectWriter &Writer;
883
884   raw_ostream &OS;
885
886   iplist<MCSectionData> Sections;
887
888   iplist<MCSymbolData> Symbols;
889
890   /// The map of sections to their associated assembler backend data.
891   //
892   // FIXME: Avoid this indirection?
893   DenseMap<const MCSection*, MCSectionData*> SectionMap;
894
895   /// The map of symbols to their associated assembler backend data.
896   //
897   // FIXME: Avoid this indirection?
898   DenseMap<const MCSymbol*, MCSymbolData*> SymbolMap;
899
900   std::vector<IndirectSymbolData> IndirectSymbols;
901
902   std::vector<DataRegionData> DataRegions;
903
904   /// The list of linker options to propagate into the object file.
905   std::vector<std::vector<std::string> > LinkerOptions;
906
907   /// List of declared file names
908   FileNameVectorType FileNames;
909
910   /// The set of function symbols for which a .thumb_func directive has
911   /// been seen.
912   //
913   // FIXME: We really would like this in target specific code rather than
914   // here. Maybe when the relocation stuff moves to target specific,
915   // this can go with it? The streamer would need some target specific
916   // refactoring too.
917   SmallPtrSet<const MCSymbol*, 64> ThumbFuncs;
918
919   /// \brief The bundle alignment size currently set in the assembler.
920   ///
921   /// By default it's 0, which means bundling is disabled.
922   unsigned BundleAlignSize;
923
924   unsigned RelaxAll : 1;
925   unsigned NoExecStack : 1;
926   unsigned SubsectionsViaSymbols : 1;
927
928   /// ELF specific e_header flags
929   // It would be good if there were an MCELFAssembler class to hold this.
930   // ELF header flags are used both by the integrated and standalone assemblers.
931   // Access to the flags is necessary in cases where assembler directives affect
932   // which flags to be set.
933   unsigned ELFHeaderEFlags;
934
935   VersionMinInfoType VersionMinInfo;
936 private:
937   /// Evaluate a fixup to a relocatable expression and the value which should be
938   /// placed into the fixup.
939   ///
940   /// \param Layout The layout to use for evaluation.
941   /// \param Fixup The fixup to evaluate.
942   /// \param DF The fragment the fixup is inside.
943   /// \param Target [out] On return, the relocatable expression the fixup
944   /// evaluates to.
945   /// \param Value [out] On return, the value of the fixup as currently laid
946   /// out.
947   /// \return Whether the fixup value was fully resolved. This is true if the
948   /// \p Value result is fixed, otherwise the value may change due to
949   /// relocation.
950   bool evaluateFixup(const MCAsmLayout &Layout,
951                      const MCFixup &Fixup, const MCFragment *DF,
952                      MCValue &Target, uint64_t &Value) const;
953
954   /// Check whether a fixup can be satisfied, or whether it needs to be relaxed
955   /// (increased in size, in order to hold its value correctly).
956   bool fixupNeedsRelaxation(const MCFixup &Fixup, const MCRelaxableFragment *DF,
957                             const MCAsmLayout &Layout) const;
958
959   /// Check whether the given fragment needs relaxation.
960   bool fragmentNeedsRelaxation(const MCRelaxableFragment *IF,
961                                const MCAsmLayout &Layout) const;
962
963   /// \brief Perform one layout iteration and return true if any offsets
964   /// were adjusted.
965   bool layoutOnce(MCAsmLayout &Layout);
966
967   /// \brief Perform one layout iteration of the given section and return true
968   /// if any offsets were adjusted.
969   bool layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD);
970
971   bool relaxInstruction(MCAsmLayout &Layout, MCRelaxableFragment &IF);
972
973   bool relaxLEB(MCAsmLayout &Layout, MCLEBFragment &IF);
974
975   bool relaxDwarfLineAddr(MCAsmLayout &Layout, MCDwarfLineAddrFragment &DF);
976   bool relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
977                                    MCDwarfCallFrameFragment &DF);
978
979   /// finishLayout - Finalize a layout, including fragment lowering.
980   void finishLayout(MCAsmLayout &Layout);
981
982   std::pair<uint64_t, bool> handleFixup(const MCAsmLayout &Layout,
983                                         MCFragment &F, const MCFixup &Fixup);
984
985 public:
986   /// Compute the effective fragment size assuming it is laid out at the given
987   /// \p SectionAddress and \p FragmentOffset.
988   uint64_t computeFragmentSize(const MCAsmLayout &Layout,
989                                const MCFragment &F) const;
990
991   /// Find the symbol which defines the atom containing the given symbol, or
992   /// null if there is no such symbol.
993   const MCSymbolData *getAtom(const MCSymbolData *Symbol) const;
994
995   /// Check whether a particular symbol is visible to the linker and is required
996   /// in the symbol table, or whether it can be discarded by the assembler. This
997   /// also effects whether the assembler treats the label as potentially
998   /// defining a separate atom.
999   bool isSymbolLinkerVisible(const MCSymbol &SD) const;
1000
1001   /// Emit the section contents using the given object writer.
1002   void writeSectionData(const MCSectionData *Section,
1003                         const MCAsmLayout &Layout) const;
1004
1005   /// Check whether a given symbol has been flagged with .thumb_func.
1006   bool isThumbFunc(const MCSymbol *Func) const {
1007     return ThumbFuncs.count(Func);
1008   }
1009
1010   /// Flag a function symbol as the target of a .thumb_func directive.
1011   void setIsThumbFunc(const MCSymbol *Func) { ThumbFuncs.insert(Func); }
1012
1013   /// ELF e_header flags
1014   unsigned getELFHeaderEFlags() const {return ELFHeaderEFlags;}
1015   void setELFHeaderEFlags(unsigned Flags) { ELFHeaderEFlags = Flags;}
1016
1017   /// MachO deployment target version information.
1018   const VersionMinInfoType &getVersionMinInfo() const { return VersionMinInfo; }
1019   void setVersionMinInfo(MCVersionMinType Kind, unsigned Major, unsigned Minor,
1020                          unsigned Update) {
1021     VersionMinInfo.Kind = Kind;
1022     VersionMinInfo.Major = Major;
1023     VersionMinInfo.Minor = Minor;
1024     VersionMinInfo.Update = Update;
1025   }
1026
1027 public:
1028   /// Construct a new assembler instance.
1029   ///
1030   /// \param OS The stream to output to.
1031   //
1032   // FIXME: How are we going to parameterize this? Two obvious options are stay
1033   // concrete and require clients to pass in a target like object. The other
1034   // option is to make this abstract, and have targets provide concrete
1035   // implementations as we do with AsmParser.
1036   MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
1037               MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
1038               raw_ostream &OS);
1039   ~MCAssembler();
1040
1041   /// Reuse an assembler instance
1042   ///
1043   void reset();
1044
1045   MCContext &getContext() const { return Context; }
1046
1047   MCAsmBackend &getBackend() const { return Backend; }
1048
1049   MCCodeEmitter &getEmitter() const { return Emitter; }
1050
1051   MCObjectWriter &getWriter() const { return Writer; }
1052
1053   /// Finish - Do final processing and write the object to the output stream.
1054   /// \p Writer is used for custom object writer (as the MCJIT does),
1055   /// if not specified it is automatically created from backend.
1056   void Finish();
1057
1058   // FIXME: This does not belong here.
1059   bool getSubsectionsViaSymbols() const {
1060     return SubsectionsViaSymbols;
1061   }
1062   void setSubsectionsViaSymbols(bool Value) {
1063     SubsectionsViaSymbols = Value;
1064   }
1065
1066   bool getRelaxAll() const { return RelaxAll; }
1067   void setRelaxAll(bool Value) { RelaxAll = Value; }
1068
1069   bool getNoExecStack() const { return NoExecStack; }
1070   void setNoExecStack(bool Value) { NoExecStack = Value; }
1071
1072   bool isBundlingEnabled() const {
1073     return BundleAlignSize != 0;
1074   }
1075
1076   unsigned getBundleAlignSize() const {
1077     return BundleAlignSize;
1078   }
1079
1080   void setBundleAlignSize(unsigned Size) {
1081     assert((Size == 0 || !(Size & (Size - 1))) && 
1082            "Expect a power-of-two bundle align size");
1083     BundleAlignSize = Size;
1084   }
1085
1086   /// @name Section List Access
1087   /// @{
1088
1089   const SectionDataListType &getSectionList() const { return Sections; }
1090   SectionDataListType &getSectionList() { return Sections; }
1091
1092   iterator begin() { return Sections.begin(); }
1093   const_iterator begin() const { return Sections.begin(); }
1094
1095   iterator end() { return Sections.end(); }
1096   const_iterator end() const { return Sections.end(); }
1097
1098   size_t size() const { return Sections.size(); }
1099
1100   /// @}
1101   /// @name Symbol List Access
1102   /// @{
1103
1104   const SymbolDataListType &getSymbolList() const { return Symbols; }
1105   SymbolDataListType &getSymbolList() { return Symbols; }
1106
1107   symbol_iterator symbol_begin() { return Symbols.begin(); }
1108   const_symbol_iterator symbol_begin() const { return Symbols.begin(); }
1109
1110   symbol_iterator symbol_end() { return Symbols.end(); }
1111   const_symbol_iterator symbol_end() const { return Symbols.end(); }
1112
1113   size_t symbol_size() const { return Symbols.size(); }
1114
1115   /// @}
1116   /// @name Indirect Symbol List Access
1117   /// @{
1118
1119   // FIXME: This is a total hack, this should not be here. Once things are
1120   // factored so that the streamer has direct access to the .o writer, it can
1121   // disappear.
1122   std::vector<IndirectSymbolData> &getIndirectSymbols() {
1123     return IndirectSymbols;
1124   }
1125
1126   indirect_symbol_iterator indirect_symbol_begin() {
1127     return IndirectSymbols.begin();
1128   }
1129   const_indirect_symbol_iterator indirect_symbol_begin() const {
1130     return IndirectSymbols.begin();
1131   }
1132
1133   indirect_symbol_iterator indirect_symbol_end() {
1134     return IndirectSymbols.end();
1135   }
1136   const_indirect_symbol_iterator indirect_symbol_end() const {
1137     return IndirectSymbols.end();
1138   }
1139
1140   size_t indirect_symbol_size() const { return IndirectSymbols.size(); }
1141
1142   /// @}
1143   /// @name Linker Option List Access
1144   /// @{
1145
1146   std::vector<std::vector<std::string> > &getLinkerOptions() {
1147     return LinkerOptions;
1148   }
1149
1150   /// @}
1151   /// @name Data Region List Access
1152   /// @{
1153
1154   // FIXME: This is a total hack, this should not be here. Once things are
1155   // factored so that the streamer has direct access to the .o writer, it can
1156   // disappear.
1157   std::vector<DataRegionData> &getDataRegions() {
1158     return DataRegions;
1159   }
1160
1161   data_region_iterator data_region_begin() {
1162     return DataRegions.begin();
1163   }
1164   const_data_region_iterator data_region_begin() const {
1165     return DataRegions.begin();
1166   }
1167
1168   data_region_iterator data_region_end() {
1169     return DataRegions.end();
1170   }
1171   const_data_region_iterator data_region_end() const {
1172     return DataRegions.end();
1173   }
1174
1175   size_t data_region_size() const { return DataRegions.size(); }
1176
1177   /// @}
1178   /// @name Backend Data Access
1179   /// @{
1180
1181   MCSectionData &getSectionData(const MCSection &Section) const {
1182     MCSectionData *Entry = SectionMap.lookup(&Section);
1183     assert(Entry && "Missing section data!");
1184     return *Entry;
1185   }
1186
1187   MCSectionData &getOrCreateSectionData(const MCSection &Section,
1188                                         bool *Created = 0) {
1189     MCSectionData *&Entry = SectionMap[&Section];
1190
1191     if (Created) *Created = !Entry;
1192     if (!Entry)
1193       Entry = new MCSectionData(Section, this);
1194
1195     return *Entry;
1196   }
1197
1198   bool hasSymbolData(const MCSymbol &Symbol) const {
1199     return SymbolMap.lookup(&Symbol) != 0;
1200   }
1201
1202   MCSymbolData &getSymbolData(const MCSymbol &Symbol) const {
1203     MCSymbolData *Entry = SymbolMap.lookup(&Symbol);
1204     assert(Entry && "Missing symbol data!");
1205     return *Entry;
1206   }
1207
1208   MCSymbolData &getOrCreateSymbolData(const MCSymbol &Symbol,
1209                                       bool *Created = 0) {
1210     MCSymbolData *&Entry = SymbolMap[&Symbol];
1211
1212     if (Created) *Created = !Entry;
1213     if (!Entry)
1214       Entry = new MCSymbolData(Symbol, 0, 0, this);
1215
1216     return *Entry;
1217   }
1218
1219   const_file_name_iterator file_names_begin() const {
1220     return FileNames.begin();
1221   }
1222
1223   const_file_name_iterator file_names_end() const {
1224     return FileNames.end();
1225   }
1226
1227   void addFileName(StringRef FileName) {
1228     if (std::find(file_names_begin(), file_names_end(), FileName) ==
1229         file_names_end())
1230       FileNames.push_back(FileName);
1231   }
1232
1233   /// @}
1234
1235   void dump();
1236 };
1237
1238 } // end namespace llvm
1239
1240 #endif