Simplify handling of --noexecstack by using getNonexecutableStackSection.
[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 SubsectionsViaSymbols : 1;
919
920   /// ELF specific e_header flags
921   // It would be good if there were an MCELFAssembler class to hold this.
922   // ELF header flags are used both by the integrated and standalone assemblers.
923   // Access to the flags is necessary in cases where assembler directives affect
924   // which flags to be set.
925   unsigned ELFHeaderEFlags;
926
927   /// Used to communicate Linker Optimization Hint information between
928   /// the Streamer and the .o writer
929   MCLOHContainer LOHContainer;
930
931   VersionMinInfoType VersionMinInfo;
932 private:
933   /// Evaluate a fixup to a relocatable expression and the value which should be
934   /// placed into the fixup.
935   ///
936   /// \param Layout The layout to use for evaluation.
937   /// \param Fixup The fixup to evaluate.
938   /// \param DF The fragment the fixup is inside.
939   /// \param Target [out] On return, the relocatable expression the fixup
940   /// evaluates to.
941   /// \param Value [out] On return, the value of the fixup as currently laid
942   /// out.
943   /// \return Whether the fixup value was fully resolved. This is true if the
944   /// \p Value result is fixed, otherwise the value may change due to
945   /// relocation.
946   bool evaluateFixup(const MCAsmLayout &Layout,
947                      const MCFixup &Fixup, const MCFragment *DF,
948                      MCValue &Target, uint64_t &Value) const;
949
950   /// Check whether a fixup can be satisfied, or whether it needs to be relaxed
951   /// (increased in size, in order to hold its value correctly).
952   bool fixupNeedsRelaxation(const MCFixup &Fixup, const MCRelaxableFragment *DF,
953                             const MCAsmLayout &Layout) const;
954
955   /// Check whether the given fragment needs relaxation.
956   bool fragmentNeedsRelaxation(const MCRelaxableFragment *IF,
957                                const MCAsmLayout &Layout) const;
958
959   /// \brief Perform one layout iteration and return true if any offsets
960   /// were adjusted.
961   bool layoutOnce(MCAsmLayout &Layout);
962
963   /// \brief Perform one layout iteration of the given section and return true
964   /// if any offsets were adjusted.
965   bool layoutSectionOnce(MCAsmLayout &Layout, MCSectionData &SD);
966
967   bool relaxInstruction(MCAsmLayout &Layout, MCRelaxableFragment &IF);
968
969   bool relaxLEB(MCAsmLayout &Layout, MCLEBFragment &IF);
970
971   bool relaxDwarfLineAddr(MCAsmLayout &Layout, MCDwarfLineAddrFragment &DF);
972   bool relaxDwarfCallFrameFragment(MCAsmLayout &Layout,
973                                    MCDwarfCallFrameFragment &DF);
974
975   /// finishLayout - Finalize a layout, including fragment lowering.
976   void finishLayout(MCAsmLayout &Layout);
977
978   std::pair<uint64_t, bool> handleFixup(const MCAsmLayout &Layout,
979                                         MCFragment &F, const MCFixup &Fixup);
980
981 public:
982   /// Compute the effective fragment size assuming it is laid out at the given
983   /// \p SectionAddress and \p FragmentOffset.
984   uint64_t computeFragmentSize(const MCAsmLayout &Layout,
985                                const MCFragment &F) const;
986
987   /// Find the symbol which defines the atom containing the given symbol, or
988   /// null if there is no such symbol.
989   const MCSymbolData *getAtom(const MCSymbolData *Symbol) const;
990
991   /// Check whether a particular symbol is visible to the linker and is required
992   /// in the symbol table, or whether it can be discarded by the assembler. This
993   /// also effects whether the assembler treats the label as potentially
994   /// defining a separate atom.
995   bool isSymbolLinkerVisible(const MCSymbol &SD) const;
996
997   /// Emit the section contents using the given object writer.
998   void writeSectionData(const MCSectionData *Section,
999                         const MCAsmLayout &Layout) const;
1000
1001   /// Check whether a given symbol has been flagged with .thumb_func.
1002   bool isThumbFunc(const MCSymbol *Func) const;
1003
1004   /// Flag a function symbol as the target of a .thumb_func directive.
1005   void setIsThumbFunc(const MCSymbol *Func) { ThumbFuncs.insert(Func); }
1006
1007   /// ELF e_header flags
1008   unsigned getELFHeaderEFlags() const {return ELFHeaderEFlags;}
1009   void setELFHeaderEFlags(unsigned Flags) { ELFHeaderEFlags = Flags;}
1010
1011   /// MachO deployment target version information.
1012   const VersionMinInfoType &getVersionMinInfo() const { return VersionMinInfo; }
1013   void setVersionMinInfo(MCVersionMinType Kind, unsigned Major, unsigned Minor,
1014                          unsigned Update) {
1015     VersionMinInfo.Kind = Kind;
1016     VersionMinInfo.Major = Major;
1017     VersionMinInfo.Minor = Minor;
1018     VersionMinInfo.Update = Update;
1019   }
1020
1021 public:
1022   /// Construct a new assembler instance.
1023   ///
1024   /// \param OS The stream to output to.
1025   //
1026   // FIXME: How are we going to parameterize this? Two obvious options are stay
1027   // concrete and require clients to pass in a target like object. The other
1028   // option is to make this abstract, and have targets provide concrete
1029   // implementations as we do with AsmParser.
1030   MCAssembler(MCContext &Context_, MCAsmBackend &Backend_,
1031               MCCodeEmitter &Emitter_, MCObjectWriter &Writer_,
1032               raw_ostream &OS);
1033   ~MCAssembler();
1034
1035   /// Reuse an assembler instance
1036   ///
1037   void reset();
1038
1039   MCContext &getContext() const { return Context; }
1040
1041   MCAsmBackend &getBackend() const { return Backend; }
1042
1043   MCCodeEmitter &getEmitter() const { return Emitter; }
1044
1045   MCObjectWriter &getWriter() const { return Writer; }
1046
1047   /// Finish - Do final processing and write the object to the output stream.
1048   /// \p Writer is used for custom object writer (as the MCJIT does),
1049   /// if not specified it is automatically created from backend.
1050   void Finish();
1051
1052   // FIXME: This does not belong here.
1053   bool getSubsectionsViaSymbols() const {
1054     return SubsectionsViaSymbols;
1055   }
1056   void setSubsectionsViaSymbols(bool Value) {
1057     SubsectionsViaSymbols = Value;
1058   }
1059
1060   bool getRelaxAll() const { return RelaxAll; }
1061   void setRelaxAll(bool Value) { RelaxAll = Value; }
1062
1063   bool isBundlingEnabled() const {
1064     return BundleAlignSize != 0;
1065   }
1066
1067   unsigned getBundleAlignSize() const {
1068     return BundleAlignSize;
1069   }
1070
1071   void setBundleAlignSize(unsigned Size) {
1072     assert((Size == 0 || !(Size & (Size - 1))) && 
1073            "Expect a power-of-two bundle align size");
1074     BundleAlignSize = Size;
1075   }
1076
1077   /// @name Section List Access
1078   /// @{
1079
1080   const SectionDataListType &getSectionList() const { return Sections; }
1081   SectionDataListType &getSectionList() { return Sections; }
1082
1083   iterator begin() { return Sections.begin(); }
1084   const_iterator begin() const { return Sections.begin(); }
1085
1086   iterator end() { return Sections.end(); }
1087   const_iterator end() const { return Sections.end(); }
1088
1089   size_t size() const { return Sections.size(); }
1090
1091   /// @}
1092   /// @name Symbol List Access
1093   /// @{
1094
1095   const SymbolDataListType &getSymbolList() const { return Symbols; }
1096   SymbolDataListType &getSymbolList() { return Symbols; }
1097
1098   symbol_iterator symbol_begin() { return Symbols.begin(); }
1099   const_symbol_iterator symbol_begin() const { return Symbols.begin(); }
1100
1101   symbol_iterator symbol_end() { return Symbols.end(); }
1102   const_symbol_iterator symbol_end() const { return Symbols.end(); }
1103
1104   symbol_range symbols() { return make_range(symbol_begin(), symbol_end()); }
1105   const_symbol_range symbols() const { return make_range(symbol_begin(), symbol_end()); }
1106
1107   size_t symbol_size() const { return Symbols.size(); }
1108
1109   /// @}
1110   /// @name Indirect Symbol List Access
1111   /// @{
1112
1113   // FIXME: This is a total hack, this should not be here. Once things are
1114   // factored so that the streamer has direct access to the .o writer, it can
1115   // disappear.
1116   std::vector<IndirectSymbolData> &getIndirectSymbols() {
1117     return IndirectSymbols;
1118   }
1119
1120   indirect_symbol_iterator indirect_symbol_begin() {
1121     return IndirectSymbols.begin();
1122   }
1123   const_indirect_symbol_iterator indirect_symbol_begin() const {
1124     return IndirectSymbols.begin();
1125   }
1126
1127   indirect_symbol_iterator indirect_symbol_end() {
1128     return IndirectSymbols.end();
1129   }
1130   const_indirect_symbol_iterator indirect_symbol_end() const {
1131     return IndirectSymbols.end();
1132   }
1133
1134   size_t indirect_symbol_size() const { return IndirectSymbols.size(); }
1135
1136   /// @}
1137   /// @name Linker Option List Access
1138   /// @{
1139
1140   std::vector<std::vector<std::string> > &getLinkerOptions() {
1141     return LinkerOptions;
1142   }
1143
1144   /// @}
1145   /// @name Data Region List Access
1146   /// @{
1147
1148   // FIXME: This is a total hack, this should not be here. Once things are
1149   // factored so that the streamer has direct access to the .o writer, it can
1150   // disappear.
1151   std::vector<DataRegionData> &getDataRegions() {
1152     return DataRegions;
1153   }
1154
1155   data_region_iterator data_region_begin() {
1156     return DataRegions.begin();
1157   }
1158   const_data_region_iterator data_region_begin() const {
1159     return DataRegions.begin();
1160   }
1161
1162   data_region_iterator data_region_end() {
1163     return DataRegions.end();
1164   }
1165   const_data_region_iterator data_region_end() const {
1166     return DataRegions.end();
1167   }
1168
1169   size_t data_region_size() const { return DataRegions.size(); }
1170
1171   /// @}
1172   /// @name Data Region List Access
1173   /// @{
1174
1175   // FIXME: This is a total hack, this should not be here. Once things are
1176   // factored so that the streamer has direct access to the .o writer, it can
1177   // disappear.
1178   MCLOHContainer & getLOHContainer() {
1179     return LOHContainer;
1180   }
1181   const MCLOHContainer & getLOHContainer() const {
1182     return const_cast<MCAssembler *>(this)->getLOHContainer();
1183   }
1184   /// @}
1185   /// @name Backend Data Access
1186   /// @{
1187
1188   MCSectionData &getSectionData(const MCSection &Section) const {
1189     MCSectionData *Entry = SectionMap.lookup(&Section);
1190     assert(Entry && "Missing section data!");
1191     return *Entry;
1192   }
1193
1194   MCSectionData &getOrCreateSectionData(const MCSection &Section,
1195                                         bool *Created = nullptr) {
1196     MCSectionData *&Entry = SectionMap[&Section];
1197
1198     if (Created) *Created = !Entry;
1199     if (!Entry)
1200       Entry = new MCSectionData(Section, this);
1201
1202     return *Entry;
1203   }
1204
1205   bool hasSymbolData(const MCSymbol &Symbol) const {
1206     return SymbolMap.lookup(&Symbol) != nullptr;
1207   }
1208
1209   MCSymbolData &getSymbolData(const MCSymbol &Symbol) {
1210     return const_cast<MCSymbolData &>(
1211         static_cast<const MCAssembler &>(*this).getSymbolData(Symbol));
1212   }
1213
1214   const MCSymbolData &getSymbolData(const MCSymbol &Symbol) const {
1215     MCSymbolData *Entry = SymbolMap.lookup(&Symbol);
1216     assert(Entry && "Missing symbol data!");
1217     return *Entry;
1218   }
1219
1220   MCSymbolData &getOrCreateSymbolData(const MCSymbol &Symbol,
1221                                       bool *Created = nullptr) {
1222     MCSymbolData *&Entry = SymbolMap[&Symbol];
1223
1224     if (Created) *Created = !Entry;
1225     if (!Entry)
1226       Entry = new MCSymbolData(Symbol, nullptr, 0, this);
1227
1228     return *Entry;
1229   }
1230
1231   const_file_name_iterator file_names_begin() const {
1232     return FileNames.begin();
1233   }
1234
1235   const_file_name_iterator file_names_end() const {
1236     return FileNames.end();
1237   }
1238
1239   void addFileName(StringRef FileName) {
1240     if (std::find(file_names_begin(), file_names_end(), FileName) ==
1241         file_names_end())
1242       FileNames.push_back(FileName);
1243   }
1244
1245   /// @}
1246
1247   void dump();
1248 };
1249
1250 } // end namespace llvm
1251
1252 #endif