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