LLVM API Documentation

DataLayout.cpp
Go to the documentation of this file.
00001 //===-- DataLayout.cpp - Data size & alignment routines --------------------==//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines layout properties related to datatype size/offset/alignment
00011 // information.
00012 //
00013 // This structure should be created once, filled in if the defaults are not
00014 // correct and then passed around by const&.  None of the members functions
00015 // require modification to the object.
00016 //
00017 //===----------------------------------------------------------------------===//
00018 
00019 #include "llvm/IR/DataLayout.h"
00020 #include "llvm/ADT/DenseMap.h"
00021 #include "llvm/ADT/STLExtras.h"
00022 #include "llvm/ADT/Triple.h"
00023 #include "llvm/IR/Constants.h"
00024 #include "llvm/IR/DerivedTypes.h"
00025 #include "llvm/IR/GetElementPtrTypeIterator.h"
00026 #include "llvm/IR/Module.h"
00027 #include "llvm/Support/ErrorHandling.h"
00028 #include "llvm/Support/ManagedStatic.h"
00029 #include "llvm/Support/MathExtras.h"
00030 #include "llvm/Support/Mutex.h"
00031 #include "llvm/Support/raw_ostream.h"
00032 #include <algorithm>
00033 #include <cstdlib>
00034 using namespace llvm;
00035 
00036 //===----------------------------------------------------------------------===//
00037 // Support for StructLayout
00038 //===----------------------------------------------------------------------===//
00039 
00040 StructLayout::StructLayout(StructType *ST, const DataLayout &DL) {
00041   assert(!ST->isOpaque() && "Cannot get layout of opaque structs");
00042   StructAlignment = 0;
00043   StructSize = 0;
00044   NumElements = ST->getNumElements();
00045 
00046   // Loop over each of the elements, placing them in memory.
00047   for (unsigned i = 0, e = NumElements; i != e; ++i) {
00048     Type *Ty = ST->getElementType(i);
00049     unsigned TyAlign = ST->isPacked() ? 1 : DL.getABITypeAlignment(Ty);
00050 
00051     // Add padding if necessary to align the data element properly.
00052     if ((StructSize & (TyAlign-1)) != 0)
00053       StructSize = RoundUpToAlignment(StructSize, TyAlign);
00054 
00055     // Keep track of maximum alignment constraint.
00056     StructAlignment = std::max(TyAlign, StructAlignment);
00057 
00058     MemberOffsets[i] = StructSize;
00059     StructSize += DL.getTypeAllocSize(Ty); // Consume space for this data item
00060   }
00061 
00062   // Empty structures have alignment of 1 byte.
00063   if (StructAlignment == 0) StructAlignment = 1;
00064 
00065   // Add padding to the end of the struct so that it could be put in an array
00066   // and all array elements would be aligned correctly.
00067   if ((StructSize & (StructAlignment-1)) != 0)
00068     StructSize = RoundUpToAlignment(StructSize, StructAlignment);
00069 }
00070 
00071 
00072 /// getElementContainingOffset - Given a valid offset into the structure,
00073 /// return the structure index that contains it.
00074 unsigned StructLayout::getElementContainingOffset(uint64_t Offset) const {
00075   const uint64_t *SI =
00076     std::upper_bound(&MemberOffsets[0], &MemberOffsets[NumElements], Offset);
00077   assert(SI != &MemberOffsets[0] && "Offset not in structure type!");
00078   --SI;
00079   assert(*SI <= Offset && "upper_bound didn't work");
00080   assert((SI == &MemberOffsets[0] || *(SI-1) <= Offset) &&
00081          (SI+1 == &MemberOffsets[NumElements] || *(SI+1) > Offset) &&
00082          "Upper bound didn't work!");
00083 
00084   // Multiple fields can have the same offset if any of them are zero sized.
00085   // For example, in { i32, [0 x i32], i32 }, searching for offset 4 will stop
00086   // at the i32 element, because it is the last element at that offset.  This is
00087   // the right one to return, because anything after it will have a higher
00088   // offset, implying that this element is non-empty.
00089   return SI-&MemberOffsets[0];
00090 }
00091 
00092 //===----------------------------------------------------------------------===//
00093 // LayoutAlignElem, LayoutAlign support
00094 //===----------------------------------------------------------------------===//
00095 
00096 LayoutAlignElem
00097 LayoutAlignElem::get(AlignTypeEnum align_type, unsigned abi_align,
00098                      unsigned pref_align, uint32_t bit_width) {
00099   assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
00100   LayoutAlignElem retval;
00101   retval.AlignType = align_type;
00102   retval.ABIAlign = abi_align;
00103   retval.PrefAlign = pref_align;
00104   retval.TypeBitWidth = bit_width;
00105   return retval;
00106 }
00107 
00108 bool
00109 LayoutAlignElem::operator==(const LayoutAlignElem &rhs) const {
00110   return (AlignType == rhs.AlignType
00111           && ABIAlign == rhs.ABIAlign
00112           && PrefAlign == rhs.PrefAlign
00113           && TypeBitWidth == rhs.TypeBitWidth);
00114 }
00115 
00116 const LayoutAlignElem
00117 DataLayout::InvalidAlignmentElem = { INVALID_ALIGN, 0, 0, 0 };
00118 
00119 //===----------------------------------------------------------------------===//
00120 // PointerAlignElem, PointerAlign support
00121 //===----------------------------------------------------------------------===//
00122 
00123 PointerAlignElem
00124 PointerAlignElem::get(uint32_t AddressSpace, unsigned ABIAlign,
00125                       unsigned PrefAlign, uint32_t TypeByteWidth) {
00126   assert(ABIAlign <= PrefAlign && "Preferred alignment worse than ABI!");
00127   PointerAlignElem retval;
00128   retval.AddressSpace = AddressSpace;
00129   retval.ABIAlign = ABIAlign;
00130   retval.PrefAlign = PrefAlign;
00131   retval.TypeByteWidth = TypeByteWidth;
00132   return retval;
00133 }
00134 
00135 bool
00136 PointerAlignElem::operator==(const PointerAlignElem &rhs) const {
00137   return (ABIAlign == rhs.ABIAlign
00138           && AddressSpace == rhs.AddressSpace
00139           && PrefAlign == rhs.PrefAlign
00140           && TypeByteWidth == rhs.TypeByteWidth);
00141 }
00142 
00143 const PointerAlignElem
00144 DataLayout::InvalidPointerElem = { 0U, 0U, 0U, ~0U };
00145 
00146 //===----------------------------------------------------------------------===//
00147 //                       DataLayout Class Implementation
00148 //===----------------------------------------------------------------------===//
00149 
00150 const char *DataLayout::getManglingComponent(const Triple &T) {
00151   if (T.isOSBinFormatMachO())
00152     return "-m:o";
00153   if (T.isOSWindows() && T.getArch() == Triple::x86 && T.isOSBinFormatCOFF())
00154     return "-m:w";
00155   return "-m:e";
00156 }
00157 
00158 static const LayoutAlignElem DefaultAlignments[] = {
00159   { INTEGER_ALIGN, 1, 1, 1 },    // i1
00160   { INTEGER_ALIGN, 8, 1, 1 },    // i8
00161   { INTEGER_ALIGN, 16, 2, 2 },   // i16
00162   { INTEGER_ALIGN, 32, 4, 4 },   // i32
00163   { INTEGER_ALIGN, 64, 4, 8 },   // i64
00164   { FLOAT_ALIGN, 16, 2, 2 },     // half
00165   { FLOAT_ALIGN, 32, 4, 4 },     // float
00166   { FLOAT_ALIGN, 64, 8, 8 },     // double
00167   { FLOAT_ALIGN, 128, 16, 16 },  // ppcf128, quad, ...
00168   { VECTOR_ALIGN, 64, 8, 8 },    // v2i32, v1i64, ...
00169   { VECTOR_ALIGN, 128, 16, 16 }, // v16i8, v8i16, v4i32, ...
00170   { AGGREGATE_ALIGN, 0, 0, 8 }   // struct
00171 };
00172 
00173 void DataLayout::reset(StringRef Desc) {
00174   clear();
00175 
00176   LayoutMap = nullptr;
00177   BigEndian = false;
00178   StackNaturalAlign = 0;
00179   ManglingMode = MM_None;
00180 
00181   // Default alignments
00182   for (const LayoutAlignElem &E : DefaultAlignments) {
00183     setAlignment((AlignTypeEnum)E.AlignType, E.ABIAlign, E.PrefAlign,
00184                  E.TypeBitWidth);
00185   }
00186   setPointerAlignment(0, 8, 8, 8);
00187 
00188   parseSpecifier(Desc);
00189 }
00190 
00191 /// Checked version of split, to ensure mandatory subparts.
00192 static std::pair<StringRef, StringRef> split(StringRef Str, char Separator) {
00193   assert(!Str.empty() && "parse error, string can't be empty here");
00194   std::pair<StringRef, StringRef> Split = Str.split(Separator);
00195   if (Split.second.empty() && Split.first != Str)
00196     report_fatal_error("Trailing separator in datalayout string");
00197   if (!Split.second.empty() && Split.first.empty())
00198     report_fatal_error("Expected token before separator in datalayout string");
00199   return Split;
00200 }
00201 
00202 /// Get an unsigned integer, including error checks.
00203 static unsigned getInt(StringRef R) {
00204   unsigned Result;
00205   bool error = R.getAsInteger(10, Result); (void)error;
00206   if (error)
00207     report_fatal_error("not a number, or does not fit in an unsigned int");
00208   return Result;
00209 }
00210 
00211 /// Convert bits into bytes. Assert if not a byte width multiple.
00212 static unsigned inBytes(unsigned Bits) {
00213   if (Bits % 8)
00214     report_fatal_error("number of bits must be a byte width multiple");
00215   return Bits / 8;
00216 }
00217 
00218 void DataLayout::parseSpecifier(StringRef Desc) {
00219   StringRepresentation = Desc;
00220   while (!Desc.empty()) {
00221     // Split at '-'.
00222     std::pair<StringRef, StringRef> Split = split(Desc, '-');
00223     Desc = Split.second;
00224 
00225     // Split at ':'.
00226     Split = split(Split.first, ':');
00227 
00228     // Aliases used below.
00229     StringRef &Tok  = Split.first;  // Current token.
00230     StringRef &Rest = Split.second; // The rest of the string.
00231 
00232     char Specifier = Tok.front();
00233     Tok = Tok.substr(1);
00234 
00235     switch (Specifier) {
00236     case 's':
00237       // Ignored for backward compatibility.
00238       // FIXME: remove this on LLVM 4.0.
00239       break;
00240     case 'E':
00241       BigEndian = true;
00242       break;
00243     case 'e':
00244       BigEndian = false;
00245       break;
00246     case 'p': {
00247       // Address space.
00248       unsigned AddrSpace = Tok.empty() ? 0 : getInt(Tok);
00249       if (!isUInt<24>(AddrSpace))
00250         report_fatal_error("Invalid address space, must be a 24bit integer");
00251 
00252       // Size.
00253       if (Rest.empty())
00254         report_fatal_error(
00255             "Missing size specification for pointer in datalayout string");
00256       Split = split(Rest, ':');
00257       unsigned PointerMemSize = inBytes(getInt(Tok));
00258       if (!PointerMemSize)
00259         report_fatal_error("Invalid pointer size of 0 bytes");
00260 
00261       // ABI alignment.
00262       if (Rest.empty())
00263         report_fatal_error(
00264             "Missing alignment specification for pointer in datalayout string");
00265       Split = split(Rest, ':');
00266       unsigned PointerABIAlign = inBytes(getInt(Tok));
00267       if (!isPowerOf2_64(PointerABIAlign))
00268         report_fatal_error(
00269             "Pointer ABI alignment must be a power of 2");
00270 
00271       // Preferred alignment.
00272       unsigned PointerPrefAlign = PointerABIAlign;
00273       if (!Rest.empty()) {
00274         Split = split(Rest, ':');
00275         PointerPrefAlign = inBytes(getInt(Tok));
00276         if (!isPowerOf2_64(PointerPrefAlign))
00277           report_fatal_error(
00278             "Pointer preferred alignment must be a power of 2");
00279       }
00280 
00281       setPointerAlignment(AddrSpace, PointerABIAlign, PointerPrefAlign,
00282                           PointerMemSize);
00283       break;
00284     }
00285     case 'i':
00286     case 'v':
00287     case 'f':
00288     case 'a': {
00289       AlignTypeEnum AlignType;
00290       switch (Specifier) {
00291       default:
00292       case 'i': AlignType = INTEGER_ALIGN; break;
00293       case 'v': AlignType = VECTOR_ALIGN; break;
00294       case 'f': AlignType = FLOAT_ALIGN; break;
00295       case 'a': AlignType = AGGREGATE_ALIGN; break;
00296       }
00297 
00298       // Bit size.
00299       unsigned Size = Tok.empty() ? 0 : getInt(Tok);
00300 
00301       if (AlignType == AGGREGATE_ALIGN && Size != 0)
00302         report_fatal_error(
00303             "Sized aggregate specification in datalayout string");
00304 
00305       // ABI alignment.
00306       if (Rest.empty())
00307         report_fatal_error(
00308             "Missing alignment specification in datalayout string");
00309       Split = split(Rest, ':');
00310       unsigned ABIAlign = inBytes(getInt(Tok));
00311       if (AlignType != AGGREGATE_ALIGN && !ABIAlign)
00312         report_fatal_error(
00313             "ABI alignment specification must be >0 for non-aggregate types");
00314 
00315       // Preferred alignment.
00316       unsigned PrefAlign = ABIAlign;
00317       if (!Rest.empty()) {
00318         Split = split(Rest, ':');
00319         PrefAlign = inBytes(getInt(Tok));
00320       }
00321 
00322       setAlignment(AlignType, ABIAlign, PrefAlign, Size);
00323 
00324       break;
00325     }
00326     case 'n':  // Native integer types.
00327       for (;;) {
00328         unsigned Width = getInt(Tok);
00329         if (Width == 0)
00330           report_fatal_error(
00331               "Zero width native integer type in datalayout string");
00332         LegalIntWidths.push_back(Width);
00333         if (Rest.empty())
00334           break;
00335         Split = split(Rest, ':');
00336       }
00337       break;
00338     case 'S': { // Stack natural alignment.
00339       StackNaturalAlign = inBytes(getInt(Tok));
00340       break;
00341     }
00342     case 'm':
00343       if (!Tok.empty())
00344         report_fatal_error("Unexpected trailing characters after mangling specifier in datalayout string");
00345       if (Rest.empty())
00346         report_fatal_error("Expected mangling specifier in datalayout string");
00347       if (Rest.size() > 1)
00348         report_fatal_error("Unknown mangling specifier in datalayout string");
00349       switch(Rest[0]) {
00350       default:
00351         report_fatal_error("Unknown mangling in datalayout string");
00352       case 'e':
00353         ManglingMode = MM_ELF;
00354         break;
00355       case 'o':
00356         ManglingMode = MM_MachO;
00357         break;
00358       case 'm':
00359         ManglingMode = MM_Mips;
00360         break;
00361       case 'w':
00362         ManglingMode = MM_WINCOFF;
00363         break;
00364       }
00365       break;
00366     default:
00367       report_fatal_error("Unknown specifier in datalayout string");
00368       break;
00369     }
00370   }
00371 }
00372 
00373 DataLayout::DataLayout(const Module *M) : LayoutMap(nullptr) {
00374   init(M);
00375 }
00376 
00377 void DataLayout::init(const Module *M) { *this = M->getDataLayout(); }
00378 
00379 bool DataLayout::operator==(const DataLayout &Other) const {
00380   bool Ret = BigEndian == Other.BigEndian &&
00381              StackNaturalAlign == Other.StackNaturalAlign &&
00382              ManglingMode == Other.ManglingMode &&
00383              LegalIntWidths == Other.LegalIntWidths &&
00384              Alignments == Other.Alignments && Pointers == Other.Pointers;
00385   // Note: getStringRepresentation() might differs, it is not canonicalized
00386   return Ret;
00387 }
00388 
00389 void
00390 DataLayout::setAlignment(AlignTypeEnum align_type, unsigned abi_align,
00391                          unsigned pref_align, uint32_t bit_width) {
00392   if (!isUInt<24>(bit_width))
00393     report_fatal_error("Invalid bit width, must be a 24bit integer");
00394   if (!isUInt<16>(abi_align))
00395     report_fatal_error("Invalid ABI alignment, must be a 16bit integer");
00396   if (!isUInt<16>(pref_align))
00397     report_fatal_error("Invalid preferred alignment, must be a 16bit integer");
00398   if (abi_align != 0 && !isPowerOf2_64(abi_align))
00399     report_fatal_error("Invalid ABI alignment, must be a power of 2");
00400   if (pref_align != 0 && !isPowerOf2_64(pref_align))
00401     report_fatal_error("Invalid preferred alignment, must be a power of 2");
00402 
00403   if (pref_align < abi_align)
00404     report_fatal_error(
00405         "Preferred alignment cannot be less than the ABI alignment");
00406 
00407   for (LayoutAlignElem &Elem : Alignments) {
00408     if (Elem.AlignType == (unsigned)align_type &&
00409         Elem.TypeBitWidth == bit_width) {
00410       // Update the abi, preferred alignments.
00411       Elem.ABIAlign = abi_align;
00412       Elem.PrefAlign = pref_align;
00413       return;
00414     }
00415   }
00416 
00417   Alignments.push_back(LayoutAlignElem::get(align_type, abi_align,
00418                                             pref_align, bit_width));
00419 }
00420 
00421 DataLayout::PointersTy::iterator
00422 DataLayout::findPointerLowerBound(uint32_t AddressSpace) {
00423   return std::lower_bound(Pointers.begin(), Pointers.end(), AddressSpace,
00424                           [](const PointerAlignElem &A, uint32_t AddressSpace) {
00425     return A.AddressSpace < AddressSpace;
00426   });
00427 }
00428 
00429 void DataLayout::setPointerAlignment(uint32_t AddrSpace, unsigned ABIAlign,
00430                                      unsigned PrefAlign,
00431                                      uint32_t TypeByteWidth) {
00432   if (PrefAlign < ABIAlign)
00433     report_fatal_error(
00434         "Preferred alignment cannot be less than the ABI alignment");
00435 
00436   PointersTy::iterator I = findPointerLowerBound(AddrSpace);
00437   if (I == Pointers.end() || I->AddressSpace != AddrSpace) {
00438     Pointers.insert(I, PointerAlignElem::get(AddrSpace, ABIAlign, PrefAlign,
00439                                              TypeByteWidth));
00440   } else {
00441     I->ABIAlign = ABIAlign;
00442     I->PrefAlign = PrefAlign;
00443     I->TypeByteWidth = TypeByteWidth;
00444   }
00445 }
00446 
00447 /// getAlignmentInfo - Return the alignment (either ABI if ABIInfo = true or
00448 /// preferred if ABIInfo = false) the layout wants for the specified datatype.
00449 unsigned DataLayout::getAlignmentInfo(AlignTypeEnum AlignType,
00450                                       uint32_t BitWidth, bool ABIInfo,
00451                                       Type *Ty) const {
00452   // Check to see if we have an exact match and remember the best match we see.
00453   int BestMatchIdx = -1;
00454   int LargestInt = -1;
00455   for (unsigned i = 0, e = Alignments.size(); i != e; ++i) {
00456     if (Alignments[i].AlignType == (unsigned)AlignType &&
00457         Alignments[i].TypeBitWidth == BitWidth)
00458       return ABIInfo ? Alignments[i].ABIAlign : Alignments[i].PrefAlign;
00459 
00460     // The best match so far depends on what we're looking for.
00461      if (AlignType == INTEGER_ALIGN &&
00462          Alignments[i].AlignType == INTEGER_ALIGN) {
00463       // The "best match" for integers is the smallest size that is larger than
00464       // the BitWidth requested.
00465       if (Alignments[i].TypeBitWidth > BitWidth && (BestMatchIdx == -1 ||
00466           Alignments[i].TypeBitWidth < Alignments[BestMatchIdx].TypeBitWidth))
00467         BestMatchIdx = i;
00468       // However, if there isn't one that's larger, then we must use the
00469       // largest one we have (see below)
00470       if (LargestInt == -1 ||
00471           Alignments[i].TypeBitWidth > Alignments[LargestInt].TypeBitWidth)
00472         LargestInt = i;
00473     }
00474   }
00475 
00476   // Okay, we didn't find an exact solution.  Fall back here depending on what
00477   // is being looked for.
00478   if (BestMatchIdx == -1) {
00479     // If we didn't find an integer alignment, fall back on most conservative.
00480     if (AlignType == INTEGER_ALIGN) {
00481       BestMatchIdx = LargestInt;
00482     } else {
00483       assert(AlignType == VECTOR_ALIGN && "Unknown alignment type!");
00484 
00485       // By default, use natural alignment for vector types. This is consistent
00486       // with what clang and llvm-gcc do.
00487       unsigned Align = getTypeAllocSize(cast<VectorType>(Ty)->getElementType());
00488       Align *= cast<VectorType>(Ty)->getNumElements();
00489       // If the alignment is not a power of 2, round up to the next power of 2.
00490       // This happens for non-power-of-2 length vectors.
00491       if (Align & (Align-1))
00492         Align = NextPowerOf2(Align);
00493       return Align;
00494     }
00495   }
00496 
00497   // Since we got a "best match" index, just return it.
00498   return ABIInfo ? Alignments[BestMatchIdx].ABIAlign
00499                  : Alignments[BestMatchIdx].PrefAlign;
00500 }
00501 
00502 namespace {
00503 
00504 class StructLayoutMap {
00505   typedef DenseMap<StructType*, StructLayout*> LayoutInfoTy;
00506   LayoutInfoTy LayoutInfo;
00507 
00508 public:
00509   ~StructLayoutMap() {
00510     // Remove any layouts.
00511     for (const auto &I : LayoutInfo) {
00512       StructLayout *Value = I.second;
00513       Value->~StructLayout();
00514       free(Value);
00515     }
00516   }
00517 
00518   StructLayout *&operator[](StructType *STy) {
00519     return LayoutInfo[STy];
00520   }
00521 };
00522 
00523 } // end anonymous namespace
00524 
00525 void DataLayout::clear() {
00526   LegalIntWidths.clear();
00527   Alignments.clear();
00528   Pointers.clear();
00529   delete static_cast<StructLayoutMap *>(LayoutMap);
00530   LayoutMap = nullptr;
00531 }
00532 
00533 DataLayout::~DataLayout() {
00534   clear();
00535 }
00536 
00537 const StructLayout *DataLayout::getStructLayout(StructType *Ty) const {
00538   if (!LayoutMap)
00539     LayoutMap = new StructLayoutMap();
00540 
00541   StructLayoutMap *STM = static_cast<StructLayoutMap*>(LayoutMap);
00542   StructLayout *&SL = (*STM)[Ty];
00543   if (SL) return SL;
00544 
00545   // Otherwise, create the struct layout.  Because it is variable length, we
00546   // malloc it, then use placement new.
00547   int NumElts = Ty->getNumElements();
00548   StructLayout *L =
00549     (StructLayout *)malloc(sizeof(StructLayout)+(NumElts-1) * sizeof(uint64_t));
00550 
00551   // Set SL before calling StructLayout's ctor.  The ctor could cause other
00552   // entries to be added to TheMap, invalidating our reference.
00553   SL = L;
00554 
00555   new (L) StructLayout(Ty, *this);
00556 
00557   return L;
00558 }
00559 
00560 
00561 unsigned DataLayout::getPointerABIAlignment(unsigned AS) const {
00562   PointersTy::const_iterator I = findPointerLowerBound(AS);
00563   if (I == Pointers.end() || I->AddressSpace != AS) {
00564     I = findPointerLowerBound(0);
00565     assert(I->AddressSpace == 0);
00566   }
00567   return I->ABIAlign;
00568 }
00569 
00570 unsigned DataLayout::getPointerPrefAlignment(unsigned AS) const {
00571   PointersTy::const_iterator I = findPointerLowerBound(AS);
00572   if (I == Pointers.end() || I->AddressSpace != AS) {
00573     I = findPointerLowerBound(0);
00574     assert(I->AddressSpace == 0);
00575   }
00576   return I->PrefAlign;
00577 }
00578 
00579 unsigned DataLayout::getPointerSize(unsigned AS) const {
00580   PointersTy::const_iterator I = findPointerLowerBound(AS);
00581   if (I == Pointers.end() || I->AddressSpace != AS) {
00582     I = findPointerLowerBound(0);
00583     assert(I->AddressSpace == 0);
00584   }
00585   return I->TypeByteWidth;
00586 }
00587 
00588 unsigned DataLayout::getPointerTypeSizeInBits(Type *Ty) const {
00589   assert(Ty->isPtrOrPtrVectorTy() &&
00590          "This should only be called with a pointer or pointer vector type");
00591 
00592   if (Ty->isPointerTy())
00593     return getTypeSizeInBits(Ty);
00594 
00595   return getTypeSizeInBits(Ty->getScalarType());
00596 }
00597 
00598 /*!
00599   \param abi_or_pref Flag that determines which alignment is returned. true
00600   returns the ABI alignment, false returns the preferred alignment.
00601   \param Ty The underlying type for which alignment is determined.
00602 
00603   Get the ABI (\a abi_or_pref == true) or preferred alignment (\a abi_or_pref
00604   == false) for the requested type \a Ty.
00605  */
00606 unsigned DataLayout::getAlignment(Type *Ty, bool abi_or_pref) const {
00607   int AlignType = -1;
00608 
00609   assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
00610   switch (Ty->getTypeID()) {
00611   // Early escape for the non-numeric types.
00612   case Type::LabelTyID:
00613     return (abi_or_pref
00614             ? getPointerABIAlignment(0)
00615             : getPointerPrefAlignment(0));
00616   case Type::PointerTyID: {
00617     unsigned AS = cast<PointerType>(Ty)->getAddressSpace();
00618     return (abi_or_pref
00619             ? getPointerABIAlignment(AS)
00620             : getPointerPrefAlignment(AS));
00621     }
00622   case Type::ArrayTyID:
00623     return getAlignment(cast<ArrayType>(Ty)->getElementType(), abi_or_pref);
00624 
00625   case Type::StructTyID: {
00626     // Packed structure types always have an ABI alignment of one.
00627     if (cast<StructType>(Ty)->isPacked() && abi_or_pref)
00628       return 1;
00629 
00630     // Get the layout annotation... which is lazily created on demand.
00631     const StructLayout *Layout = getStructLayout(cast<StructType>(Ty));
00632     unsigned Align = getAlignmentInfo(AGGREGATE_ALIGN, 0, abi_or_pref, Ty);
00633     return std::max(Align, Layout->getAlignment());
00634   }
00635   case Type::IntegerTyID:
00636     AlignType = INTEGER_ALIGN;
00637     break;
00638   case Type::HalfTyID:
00639   case Type::FloatTyID:
00640   case Type::DoubleTyID:
00641   // PPC_FP128TyID and FP128TyID have different data contents, but the
00642   // same size and alignment, so they look the same here.
00643   case Type::PPC_FP128TyID:
00644   case Type::FP128TyID:
00645   case Type::X86_FP80TyID:
00646     AlignType = FLOAT_ALIGN;
00647     break;
00648   case Type::X86_MMXTyID:
00649   case Type::VectorTyID:
00650     AlignType = VECTOR_ALIGN;
00651     break;
00652   default:
00653     llvm_unreachable("Bad type for getAlignment!!!");
00654   }
00655 
00656   return getAlignmentInfo((AlignTypeEnum)AlignType, getTypeSizeInBits(Ty),
00657                           abi_or_pref, Ty);
00658 }
00659 
00660 unsigned DataLayout::getABITypeAlignment(Type *Ty) const {
00661   return getAlignment(Ty, true);
00662 }
00663 
00664 /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
00665 /// an integer type of the specified bitwidth.
00666 unsigned DataLayout::getABIIntegerTypeAlignment(unsigned BitWidth) const {
00667   return getAlignmentInfo(INTEGER_ALIGN, BitWidth, true, nullptr);
00668 }
00669 
00670 unsigned DataLayout::getPrefTypeAlignment(Type *Ty) const {
00671   return getAlignment(Ty, false);
00672 }
00673 
00674 unsigned DataLayout::getPreferredTypeAlignmentShift(Type *Ty) const {
00675   unsigned Align = getPrefTypeAlignment(Ty);
00676   assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
00677   return Log2_32(Align);
00678 }
00679 
00680 IntegerType *DataLayout::getIntPtrType(LLVMContext &C,
00681                                        unsigned AddressSpace) const {
00682   return IntegerType::get(C, getPointerSizeInBits(AddressSpace));
00683 }
00684 
00685 Type *DataLayout::getIntPtrType(Type *Ty) const {
00686   assert(Ty->isPtrOrPtrVectorTy() &&
00687          "Expected a pointer or pointer vector type.");
00688   unsigned NumBits = getPointerTypeSizeInBits(Ty);
00689   IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
00690   if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
00691     return VectorType::get(IntTy, VecTy->getNumElements());
00692   return IntTy;
00693 }
00694 
00695 Type *DataLayout::getSmallestLegalIntType(LLVMContext &C, unsigned Width) const {
00696   for (unsigned LegalIntWidth : LegalIntWidths)
00697     if (Width <= LegalIntWidth)
00698       return Type::getIntNTy(C, LegalIntWidth);
00699   return nullptr;
00700 }
00701 
00702 unsigned DataLayout::getLargestLegalIntTypeSize() const {
00703   auto Max = std::max_element(LegalIntWidths.begin(), LegalIntWidths.end());
00704   return Max != LegalIntWidths.end() ? *Max : 0;
00705 }
00706 
00707 uint64_t DataLayout::getIndexedOffset(Type *ptrTy,
00708                                       ArrayRef<Value *> Indices) const {
00709   Type *Ty = ptrTy;
00710   assert(Ty->isPointerTy() && "Illegal argument for getIndexedOffset()");
00711   uint64_t Result = 0;
00712 
00713   generic_gep_type_iterator<Value* const*>
00714     TI = gep_type_begin(ptrTy, Indices);
00715   for (unsigned CurIDX = 0, EndIDX = Indices.size(); CurIDX != EndIDX;
00716        ++CurIDX, ++TI) {
00717     if (StructType *STy = dyn_cast<StructType>(*TI)) {
00718       assert(Indices[CurIDX]->getType() ==
00719              Type::getInt32Ty(ptrTy->getContext()) &&
00720              "Illegal struct idx");
00721       unsigned FieldNo = cast<ConstantInt>(Indices[CurIDX])->getZExtValue();
00722 
00723       // Get structure layout information...
00724       const StructLayout *Layout = getStructLayout(STy);
00725 
00726       // Add in the offset, as calculated by the structure layout info...
00727       Result += Layout->getElementOffset(FieldNo);
00728 
00729       // Update Ty to refer to current element
00730       Ty = STy->getElementType(FieldNo);
00731     } else {
00732       // Update Ty to refer to current element
00733       Ty = cast<SequentialType>(Ty)->getElementType();
00734 
00735       // Get the array index and the size of each array element.
00736       if (int64_t arrayIdx = cast<ConstantInt>(Indices[CurIDX])->getSExtValue())
00737         Result += (uint64_t)arrayIdx * getTypeAllocSize(Ty);
00738     }
00739   }
00740 
00741   return Result;
00742 }
00743 
00744 /// getPreferredAlignment - Return the preferred alignment of the specified
00745 /// global.  This includes an explicitly requested alignment (if the global
00746 /// has one).
00747 unsigned DataLayout::getPreferredAlignment(const GlobalVariable *GV) const {
00748   Type *ElemType = GV->getType()->getElementType();
00749   unsigned Alignment = getPrefTypeAlignment(ElemType);
00750   unsigned GVAlignment = GV->getAlignment();
00751   if (GVAlignment >= Alignment) {
00752     Alignment = GVAlignment;
00753   } else if (GVAlignment != 0) {
00754     Alignment = std::max(GVAlignment, getABITypeAlignment(ElemType));
00755   }
00756 
00757   if (GV->hasInitializer() && GVAlignment == 0) {
00758     if (Alignment < 16) {
00759       // If the global is not external, see if it is large.  If so, give it a
00760       // larger alignment.
00761       if (getTypeSizeInBits(ElemType) > 128)
00762         Alignment = 16;    // 16-byte alignment.
00763     }
00764   }
00765   return Alignment;
00766 }
00767 
00768 /// getPreferredAlignmentLog - Return the preferred alignment of the
00769 /// specified global, returned in log form.  This includes an explicitly
00770 /// requested alignment (if the global has one).
00771 unsigned DataLayout::getPreferredAlignmentLog(const GlobalVariable *GV) const {
00772   return Log2_32(getPreferredAlignment(GV));
00773 }
00774