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