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