Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

477 lines
18 KiB

  1. //===--------- llvm/DataLayout.h - Data size & alignment info ---*- 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. // This file defines layout properties related to datatype size/offset/alignment
  11. // information. It uses lazy annotations to cache information about how
  12. // structure types are laid out and used.
  13. //
  14. // This structure should be created once, filled in if the defaults are not
  15. // correct and then passed around by const&. None of the members functions
  16. // require modification to the object.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #ifndef LLVM_IR_DATALAYOUT_H
  20. #define LLVM_IR_DATALAYOUT_H
  21. #include "llvm/ADT/DenseMap.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include "llvm/IR/DerivedTypes.h"
  24. #include "llvm/IR/Type.h"
  25. #include "llvm/Pass.h"
  26. #include "llvm/Support/DataTypes.h"
  27. namespace llvm {
  28. class Value;
  29. class Type;
  30. class IntegerType;
  31. class StructType;
  32. class StructLayout;
  33. class GlobalVariable;
  34. class LLVMContext;
  35. template<typename T>
  36. class ArrayRef;
  37. /// Enum used to categorize the alignment types stored by LayoutAlignElem
  38. enum AlignTypeEnum {
  39. INVALID_ALIGN = 0, ///< An invalid alignment
  40. INTEGER_ALIGN = 'i', ///< Integer type alignment
  41. VECTOR_ALIGN = 'v', ///< Vector type alignment
  42. FLOAT_ALIGN = 'f', ///< Floating point type alignment
  43. AGGREGATE_ALIGN = 'a', ///< Aggregate alignment
  44. STACK_ALIGN = 's' ///< Stack objects alignment
  45. };
  46. /// Layout alignment element.
  47. ///
  48. /// Stores the alignment data associated with a given alignment type (integer,
  49. /// vector, float) and type bit width.
  50. ///
  51. /// @note The unusual order of elements in the structure attempts to reduce
  52. /// padding and make the structure slightly more cache friendly.
  53. struct LayoutAlignElem {
  54. unsigned AlignType : 8; ///< Alignment type (AlignTypeEnum)
  55. unsigned TypeBitWidth : 24; ///< Type bit width
  56. unsigned ABIAlign : 16; ///< ABI alignment for this type/bitw
  57. unsigned PrefAlign : 16; ///< Pref. alignment for this type/bitw
  58. /// Initializer
  59. static LayoutAlignElem get(AlignTypeEnum align_type, unsigned abi_align,
  60. unsigned pref_align, uint32_t bit_width);
  61. /// Equality predicate
  62. bool operator==(const LayoutAlignElem &rhs) const;
  63. };
  64. /// Layout pointer alignment element.
  65. ///
  66. /// Stores the alignment data associated with a given pointer and address space.
  67. ///
  68. /// @note The unusual order of elements in the structure attempts to reduce
  69. /// padding and make the structure slightly more cache friendly.
  70. struct PointerAlignElem {
  71. unsigned ABIAlign; ///< ABI alignment for this type/bitw
  72. unsigned PrefAlign; ///< Pref. alignment for this type/bitw
  73. uint32_t TypeBitWidth; ///< Type bit width
  74. uint32_t AddressSpace; ///< Address space for the pointer type
  75. /// Initializer
  76. static PointerAlignElem get(uint32_t addr_space, unsigned abi_align,
  77. unsigned pref_align, uint32_t bit_width);
  78. /// Equality predicate
  79. bool operator==(const PointerAlignElem &rhs) const;
  80. };
  81. /// DataLayout - This class holds a parsed version of the target data layout
  82. /// string in a module and provides methods for querying it. The target data
  83. /// layout string is specified *by the target* - a frontend generating LLVM IR
  84. /// is required to generate the right target data for the target being codegen'd
  85. /// to. If some measure of portability is desired, an empty string may be
  86. /// specified in the module.
  87. class DataLayout : public ImmutablePass {
  88. private:
  89. bool LittleEndian; ///< Defaults to false
  90. unsigned StackNaturalAlign; ///< Stack natural alignment
  91. SmallVector<unsigned char, 8> LegalIntWidths; ///< Legal Integers.
  92. /// Alignments - Where the primitive type alignment data is stored.
  93. ///
  94. /// @sa init().
  95. /// @note Could support multiple size pointer alignments, e.g., 32-bit
  96. /// pointers vs. 64-bit pointers by extending LayoutAlignment, but for now,
  97. /// we don't.
  98. SmallVector<LayoutAlignElem, 16> Alignments;
  99. DenseMap<unsigned, PointerAlignElem> Pointers;
  100. /// InvalidAlignmentElem - This member is a signal that a requested alignment
  101. /// type and bit width were not found in the SmallVector.
  102. static const LayoutAlignElem InvalidAlignmentElem;
  103. /// InvalidPointerElem - This member is a signal that a requested pointer
  104. /// type and bit width were not found in the DenseSet.
  105. static const PointerAlignElem InvalidPointerElem;
  106. // The StructType -> StructLayout map.
  107. mutable void *LayoutMap;
  108. //! Set/initialize target alignments
  109. void setAlignment(AlignTypeEnum align_type, unsigned abi_align,
  110. unsigned pref_align, uint32_t bit_width);
  111. unsigned getAlignmentInfo(AlignTypeEnum align_type, uint32_t bit_width,
  112. bool ABIAlign, Type *Ty) const;
  113. //! Set/initialize pointer alignments
  114. void setPointerAlignment(uint32_t addr_space, unsigned abi_align,
  115. unsigned pref_align, uint32_t bit_width);
  116. //! Internal helper method that returns requested alignment for type.
  117. unsigned getAlignment(Type *Ty, bool abi_or_pref) const;
  118. /// Valid alignment predicate.
  119. ///
  120. /// Predicate that tests a LayoutAlignElem reference returned by get() against
  121. /// InvalidAlignmentElem.
  122. bool validAlignment(const LayoutAlignElem &align) const {
  123. return &align != &InvalidAlignmentElem;
  124. }
  125. /// Valid pointer predicate.
  126. ///
  127. /// Predicate that tests a PointerAlignElem reference returned by get() against
  128. /// InvalidPointerElem.
  129. bool validPointer(const PointerAlignElem &align) const {
  130. return &align != &InvalidPointerElem;
  131. }
  132. /// Parses a target data specification string. Assert if the string is
  133. /// malformed.
  134. void parseSpecifier(StringRef LayoutDescription);
  135. public:
  136. /// Default ctor.
  137. ///
  138. /// @note This has to exist, because this is a pass, but it should never be
  139. /// used.
  140. DataLayout();
  141. /// Constructs a DataLayout from a specification string. See init().
  142. explicit DataLayout(StringRef LayoutDescription)
  143. : ImmutablePass(ID) {
  144. init(LayoutDescription);
  145. }
  146. /// Initialize target data from properties stored in the module.
  147. explicit DataLayout(const Module *M);
  148. DataLayout(const DataLayout &DL) :
  149. ImmutablePass(ID),
  150. LittleEndian(DL.isLittleEndian()),
  151. StackNaturalAlign(DL.StackNaturalAlign),
  152. LegalIntWidths(DL.LegalIntWidths),
  153. Alignments(DL.Alignments),
  154. Pointers(DL.Pointers),
  155. LayoutMap(0)
  156. { }
  157. ~DataLayout(); // Not virtual, do not subclass this class
  158. /// DataLayout is an immutable pass, but holds state. This allows the pass
  159. /// manager to clear its mutable state.
  160. bool doFinalization(Module &M);
  161. /// Parse a data layout string (with fallback to default values). Ensure that
  162. /// the data layout pass is registered.
  163. void init(StringRef LayoutDescription);
  164. /// Layout endianness...
  165. bool isLittleEndian() const { return LittleEndian; }
  166. bool isBigEndian() const { return !LittleEndian; }
  167. /// getStringRepresentation - Return the string representation of the
  168. /// DataLayout. This representation is in the same format accepted by the
  169. /// string constructor above.
  170. std::string getStringRepresentation() const;
  171. /// isLegalInteger - This function returns true if the specified type is
  172. /// known to be a native integer type supported by the CPU. For example,
  173. /// i64 is not native on most 32-bit CPUs and i37 is not native on any known
  174. /// one. This returns false if the integer width is not legal.
  175. ///
  176. /// The width is specified in bits.
  177. ///
  178. bool isLegalInteger(unsigned Width) const {
  179. for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
  180. if (LegalIntWidths[i] == Width)
  181. return true;
  182. return false;
  183. }
  184. bool isIllegalInteger(unsigned Width) const {
  185. return !isLegalInteger(Width);
  186. }
  187. /// Returns true if the given alignment exceeds the natural stack alignment.
  188. bool exceedsNaturalStackAlignment(unsigned Align) const {
  189. return (StackNaturalAlign != 0) && (Align > StackNaturalAlign);
  190. }
  191. /// fitsInLegalInteger - This function returns true if the specified type fits
  192. /// in a native integer type supported by the CPU. For example, if the CPU
  193. /// only supports i32 as a native integer type, then i27 fits in a legal
  194. // integer type but i45 does not.
  195. bool fitsInLegalInteger(unsigned Width) const {
  196. for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
  197. if (Width <= LegalIntWidths[i])
  198. return true;
  199. return false;
  200. }
  201. /// Layout pointer alignment
  202. /// FIXME: The defaults need to be removed once all of
  203. /// the backends/clients are updated.
  204. unsigned getPointerABIAlignment(unsigned AS = 0) const {
  205. DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
  206. if (val == Pointers.end()) {
  207. val = Pointers.find(0);
  208. }
  209. return val->second.ABIAlign;
  210. }
  211. /// Return target's alignment for stack-based pointers
  212. /// FIXME: The defaults need to be removed once all of
  213. /// the backends/clients are updated.
  214. unsigned getPointerPrefAlignment(unsigned AS = 0) const {
  215. DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
  216. if (val == Pointers.end()) {
  217. val = Pointers.find(0);
  218. }
  219. return val->second.PrefAlign;
  220. }
  221. /// Layout pointer size
  222. /// FIXME: The defaults need to be removed once all of
  223. /// the backends/clients are updated.
  224. unsigned getPointerSize(unsigned AS = 0) const {
  225. DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
  226. if (val == Pointers.end()) {
  227. val = Pointers.find(0);
  228. }
  229. return val->second.TypeBitWidth;
  230. }
  231. /// Layout pointer size, in bits
  232. /// FIXME: The defaults need to be removed once all of
  233. /// the backends/clients are updated.
  234. unsigned getPointerSizeInBits(unsigned AS = 0) const {
  235. return getPointerSize(AS) * 8;
  236. }
  237. /// Size examples:
  238. ///
  239. /// Type SizeInBits StoreSizeInBits AllocSizeInBits[*]
  240. /// ---- ---------- --------------- ---------------
  241. /// i1 1 8 8
  242. /// i8 8 8 8
  243. /// i19 19 24 32
  244. /// i32 32 32 32
  245. /// i100 100 104 128
  246. /// i128 128 128 128
  247. /// Float 32 32 32
  248. /// Double 64 64 64
  249. /// X86_FP80 80 80 96
  250. ///
  251. /// [*] The alloc size depends on the alignment, and thus on the target.
  252. /// These values are for x86-32 linux.
  253. /// getTypeSizeInBits - Return the number of bits necessary to hold the
  254. /// specified type. For example, returns 36 for i36 and 80 for x86_fp80.
  255. /// The type passed must have a size (Type::isSized() must return true).
  256. uint64_t getTypeSizeInBits(Type *Ty) const;
  257. /// getTypeStoreSize - Return the maximum number of bytes that may be
  258. /// overwritten by storing the specified type. For example, returns 5
  259. /// for i36 and 10 for x86_fp80.
  260. uint64_t getTypeStoreSize(Type *Ty) const {
  261. return (getTypeSizeInBits(Ty)+7)/8;
  262. }
  263. /// getTypeStoreSizeInBits - Return the maximum number of bits that may be
  264. /// overwritten by storing the specified type; always a multiple of 8. For
  265. /// example, returns 40 for i36 and 80 for x86_fp80.
  266. uint64_t getTypeStoreSizeInBits(Type *Ty) const {
  267. return 8*getTypeStoreSize(Ty);
  268. }
  269. /// getTypeAllocSize - Return the offset in bytes between successive objects
  270. /// of the specified type, including alignment padding. This is the amount
  271. /// that alloca reserves for this type. For example, returns 12 or 16 for
  272. /// x86_fp80, depending on alignment.
  273. uint64_t getTypeAllocSize(Type *Ty) const {
  274. // Round up to the next alignment boundary.
  275. return RoundUpAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
  276. }
  277. /// getTypeAllocSizeInBits - Return the offset in bits between successive
  278. /// objects of the specified type, including alignment padding; always a
  279. /// multiple of 8. This is the amount that alloca reserves for this type.
  280. /// For example, returns 96 or 128 for x86_fp80, depending on alignment.
  281. uint64_t getTypeAllocSizeInBits(Type *Ty) const {
  282. return 8*getTypeAllocSize(Ty);
  283. }
  284. /// getABITypeAlignment - Return the minimum ABI-required alignment for the
  285. /// specified type.
  286. unsigned getABITypeAlignment(Type *Ty) const;
  287. /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
  288. /// an integer type of the specified bitwidth.
  289. unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const;
  290. /// getCallFrameTypeAlignment - Return the minimum ABI-required alignment
  291. /// for the specified type when it is part of a call frame.
  292. unsigned getCallFrameTypeAlignment(Type *Ty) const;
  293. /// getPrefTypeAlignment - Return the preferred stack/global alignment for
  294. /// the specified type. This is always at least as good as the ABI alignment.
  295. unsigned getPrefTypeAlignment(Type *Ty) const;
  296. /// getPreferredTypeAlignmentShift - Return the preferred alignment for the
  297. /// specified type, returned as log2 of the value (a shift amount).
  298. unsigned getPreferredTypeAlignmentShift(Type *Ty) const;
  299. /// getIntPtrType - Return an integer type with size at least as big as that
  300. /// of a pointer in the given address space.
  301. IntegerType *getIntPtrType(LLVMContext &C, unsigned AddressSpace = 0) const;
  302. /// getIntPtrType - Return an integer (vector of integer) type with size at
  303. /// least as big as that of a pointer of the given pointer (vector of pointer)
  304. /// type.
  305. Type *getIntPtrType(Type *) const;
  306. /// getSmallestLegalIntType - Return the smallest integer type with size at
  307. /// least as big as Width bits.
  308. Type *getSmallestLegalIntType(LLVMContext &C, unsigned Width = 0) const;
  309. /// getIndexedOffset - return the offset from the beginning of the type for
  310. /// the specified indices. This is used to implement getelementptr.
  311. uint64_t getIndexedOffset(Type *Ty, ArrayRef<Value *> Indices) const;
  312. /// getStructLayout - Return a StructLayout object, indicating the alignment
  313. /// of the struct, its size, and the offsets of its fields. Note that this
  314. /// information is lazily cached.
  315. const StructLayout *getStructLayout(StructType *Ty) const;
  316. /// getPreferredAlignment - Return the preferred alignment of the specified
  317. /// global. This includes an explicitly requested alignment (if the global
  318. /// has one).
  319. unsigned getPreferredAlignment(const GlobalVariable *GV) const;
  320. /// getPreferredAlignmentLog - Return the preferred alignment of the
  321. /// specified global, returned in log form. This includes an explicitly
  322. /// requested alignment (if the global has one).
  323. unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
  324. /// RoundUpAlignment - Round the specified value up to the next alignment
  325. /// boundary specified by Alignment. For example, 7 rounded up to an
  326. /// alignment boundary of 4 is 8. 8 rounded up to the alignment boundary of 4
  327. /// is 8 because it is already aligned.
  328. template <typename UIntTy>
  329. static UIntTy RoundUpAlignment(UIntTy Val, unsigned Alignment) {
  330. assert((Alignment & (Alignment-1)) == 0 && "Alignment must be power of 2!");
  331. return (Val + (Alignment-1)) & ~UIntTy(Alignment-1);
  332. }
  333. static char ID; // Pass identification, replacement for typeid
  334. };
  335. /// StructLayout - used to lazily calculate structure layout information for a
  336. /// target machine, based on the DataLayout structure.
  337. ///
  338. class StructLayout {
  339. uint64_t StructSize;
  340. unsigned StructAlignment;
  341. unsigned NumElements;
  342. uint64_t MemberOffsets[1]; // variable sized array!
  343. public:
  344. uint64_t getSizeInBytes() const {
  345. return StructSize;
  346. }
  347. uint64_t getSizeInBits() const {
  348. return 8*StructSize;
  349. }
  350. unsigned getAlignment() const {
  351. return StructAlignment;
  352. }
  353. /// getElementContainingOffset - Given a valid byte offset into the structure,
  354. /// return the structure index that contains it.
  355. ///
  356. unsigned getElementContainingOffset(uint64_t Offset) const;
  357. uint64_t getElementOffset(unsigned Idx) const {
  358. assert(Idx < NumElements && "Invalid element idx!");
  359. return MemberOffsets[Idx];
  360. }
  361. uint64_t getElementOffsetInBits(unsigned Idx) const {
  362. return getElementOffset(Idx)*8;
  363. }
  364. private:
  365. friend class DataLayout; // Only DataLayout can create this class
  366. StructLayout(StructType *ST, const DataLayout &DL);
  367. };
  368. // The implementation of this method is provided inline as it is particularly
  369. // well suited to constant folding when called on a specific Type subclass.
  370. inline uint64_t DataLayout::getTypeSizeInBits(Type *Ty) const {
  371. assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
  372. switch (Ty->getTypeID()) {
  373. case Type::LabelTyID:
  374. return getPointerSizeInBits(0);
  375. case Type::PointerTyID:
  376. return getPointerSizeInBits(cast<PointerType>(Ty)->getAddressSpace());
  377. case Type::ArrayTyID: {
  378. ArrayType *ATy = cast<ArrayType>(Ty);
  379. return ATy->getNumElements() *
  380. getTypeAllocSizeInBits(ATy->getElementType());
  381. }
  382. case Type::StructTyID:
  383. // Get the layout annotation... which is lazily created on demand.
  384. return getStructLayout(cast<StructType>(Ty))->getSizeInBits();
  385. case Type::IntegerTyID:
  386. return cast<IntegerType>(Ty)->getBitWidth();
  387. case Type::HalfTyID:
  388. return 16;
  389. case Type::FloatTyID:
  390. return 32;
  391. case Type::DoubleTyID:
  392. case Type::X86_MMXTyID:
  393. return 64;
  394. case Type::PPC_FP128TyID:
  395. case Type::FP128TyID:
  396. return 128;
  397. // In memory objects this is always aligned to a higher boundary, but
  398. // only 80 bits contain information.
  399. case Type::X86_FP80TyID:
  400. return 80;
  401. case Type::VectorTyID: {
  402. VectorType *VTy = cast<VectorType>(Ty);
  403. return VTy->getNumElements() * getTypeSizeInBits(VTy->getElementType());
  404. }
  405. default:
  406. llvm_unreachable("DataLayout::getTypeSizeInBits(): Unsupported type");
  407. }
  408. }
  409. } // End llvm namespace
  410. #endif