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