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