PageRenderTime 110ms CodeModel.GetById 23ms app.highlight 73ms RepoModel.GetById 0ms app.codeStats 1ms

/3rd_party/llvm/lib/Bitcode/Reader/BitcodeReader.cpp

https://code.google.com/p/softart/
C++ | 3351 lines | 2729 code | 351 blank | 271 comment | 828 complexity | 047c2444de5bfa66801c5f22cbfe7456 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, JSON, MPL-2.0-no-copyleft-exception, GPL-2.0, GPL-3.0, LGPL-3.0, BSD-2-Clause

Large files files are truncated, but you can click here to view the full file

   1//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
   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#include "llvm/Bitcode/ReaderWriter.h"
  11#include "BitcodeReader.h"
  12#include "llvm/ADT/SmallString.h"
  13#include "llvm/ADT/SmallVector.h"
  14#include "llvm/AutoUpgrade.h"
  15#include "llvm/Bitcode/LLVMBitCodes.h"
  16#include "llvm/IR/Constants.h"
  17#include "llvm/IR/DerivedTypes.h"
  18#include "llvm/IR/InlineAsm.h"
  19#include "llvm/IR/IntrinsicInst.h"
  20#include "llvm/IR/LLVMContext.h"
  21#include "llvm/IR/Module.h"
  22#include "llvm/IR/OperandTraits.h"
  23#include "llvm/IR/Operator.h"
  24#include "llvm/Support/DataStream.h"
  25#include "llvm/Support/MathExtras.h"
  26#include "llvm/Support/MemoryBuffer.h"
  27#include "llvm/Support/raw_ostream.h"
  28using namespace llvm;
  29
  30enum {
  31  SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
  32};
  33
  34void BitcodeReader::materializeForwardReferencedFunctions() {
  35  while (!BlockAddrFwdRefs.empty()) {
  36    Function *F = BlockAddrFwdRefs.begin()->first;
  37    F->Materialize();
  38  }
  39}
  40
  41void BitcodeReader::FreeState() {
  42  if (BufferOwned)
  43    delete Buffer;
  44  Buffer = 0;
  45  std::vector<Type*>().swap(TypeList);
  46  ValueList.clear();
  47  MDValueList.clear();
  48
  49  std::vector<AttributeSet>().swap(MAttributes);
  50  std::vector<BasicBlock*>().swap(FunctionBBs);
  51  std::vector<Function*>().swap(FunctionsWithBodies);
  52  DeferredFunctionInfo.clear();
  53  MDKindMap.clear();
  54
  55  assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
  56}
  57
  58//===----------------------------------------------------------------------===//
  59//  Helper functions to implement forward reference resolution, etc.
  60//===----------------------------------------------------------------------===//
  61
  62/// ConvertToString - Convert a string from a record into an std::string, return
  63/// true on failure.
  64template<typename StrTy>
  65static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
  66                            StrTy &Result) {
  67  if (Idx > Record.size())
  68    return true;
  69
  70  for (unsigned i = Idx, e = Record.size(); i != e; ++i)
  71    Result += (char)Record[i];
  72  return false;
  73}
  74
  75static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
  76  switch (Val) {
  77  default: // Map unknown/new linkages to external
  78  case 0:  return GlobalValue::ExternalLinkage;
  79  case 1:  return GlobalValue::WeakAnyLinkage;
  80  case 2:  return GlobalValue::AppendingLinkage;
  81  case 3:  return GlobalValue::InternalLinkage;
  82  case 4:  return GlobalValue::LinkOnceAnyLinkage;
  83  case 5:  return GlobalValue::DLLImportLinkage;
  84  case 6:  return GlobalValue::DLLExportLinkage;
  85  case 7:  return GlobalValue::ExternalWeakLinkage;
  86  case 8:  return GlobalValue::CommonLinkage;
  87  case 9:  return GlobalValue::PrivateLinkage;
  88  case 10: return GlobalValue::WeakODRLinkage;
  89  case 11: return GlobalValue::LinkOnceODRLinkage;
  90  case 12: return GlobalValue::AvailableExternallyLinkage;
  91  case 13: return GlobalValue::LinkerPrivateLinkage;
  92  case 14: return GlobalValue::LinkerPrivateWeakLinkage;
  93  }
  94}
  95
  96static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
  97  switch (Val) {
  98  default: // Map unknown visibilities to default.
  99  case 0: return GlobalValue::DefaultVisibility;
 100  case 1: return GlobalValue::HiddenVisibility;
 101  case 2: return GlobalValue::ProtectedVisibility;
 102  }
 103}
 104
 105static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
 106  switch (Val) {
 107    case 0: return GlobalVariable::NotThreadLocal;
 108    default: // Map unknown non-zero value to general dynamic.
 109    case 1: return GlobalVariable::GeneralDynamicTLSModel;
 110    case 2: return GlobalVariable::LocalDynamicTLSModel;
 111    case 3: return GlobalVariable::InitialExecTLSModel;
 112    case 4: return GlobalVariable::LocalExecTLSModel;
 113  }
 114}
 115
 116static int GetDecodedCastOpcode(unsigned Val) {
 117  switch (Val) {
 118  default: return -1;
 119  case bitc::CAST_TRUNC   : return Instruction::Trunc;
 120  case bitc::CAST_ZEXT    : return Instruction::ZExt;
 121  case bitc::CAST_SEXT    : return Instruction::SExt;
 122  case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
 123  case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
 124  case bitc::CAST_UITOFP  : return Instruction::UIToFP;
 125  case bitc::CAST_SITOFP  : return Instruction::SIToFP;
 126  case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
 127  case bitc::CAST_FPEXT   : return Instruction::FPExt;
 128  case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
 129  case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
 130  case bitc::CAST_BITCAST : return Instruction::BitCast;
 131  case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
 132  }
 133}
 134static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
 135  switch (Val) {
 136  default: return -1;
 137  case bitc::BINOP_ADD:
 138    return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
 139  case bitc::BINOP_SUB:
 140    return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
 141  case bitc::BINOP_MUL:
 142    return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
 143  case bitc::BINOP_UDIV: return Instruction::UDiv;
 144  case bitc::BINOP_SDIV:
 145    return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
 146  case bitc::BINOP_UREM: return Instruction::URem;
 147  case bitc::BINOP_SREM:
 148    return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
 149  case bitc::BINOP_SHL:  return Instruction::Shl;
 150  case bitc::BINOP_LSHR: return Instruction::LShr;
 151  case bitc::BINOP_ASHR: return Instruction::AShr;
 152  case bitc::BINOP_AND:  return Instruction::And;
 153  case bitc::BINOP_OR:   return Instruction::Or;
 154  case bitc::BINOP_XOR:  return Instruction::Xor;
 155  }
 156}
 157
 158static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
 159  switch (Val) {
 160  default: return AtomicRMWInst::BAD_BINOP;
 161  case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
 162  case bitc::RMW_ADD: return AtomicRMWInst::Add;
 163  case bitc::RMW_SUB: return AtomicRMWInst::Sub;
 164  case bitc::RMW_AND: return AtomicRMWInst::And;
 165  case bitc::RMW_NAND: return AtomicRMWInst::Nand;
 166  case bitc::RMW_OR: return AtomicRMWInst::Or;
 167  case bitc::RMW_XOR: return AtomicRMWInst::Xor;
 168  case bitc::RMW_MAX: return AtomicRMWInst::Max;
 169  case bitc::RMW_MIN: return AtomicRMWInst::Min;
 170  case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
 171  case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
 172  }
 173}
 174
 175static AtomicOrdering GetDecodedOrdering(unsigned Val) {
 176  switch (Val) {
 177  case bitc::ORDERING_NOTATOMIC: return NotAtomic;
 178  case bitc::ORDERING_UNORDERED: return Unordered;
 179  case bitc::ORDERING_MONOTONIC: return Monotonic;
 180  case bitc::ORDERING_ACQUIRE: return Acquire;
 181  case bitc::ORDERING_RELEASE: return Release;
 182  case bitc::ORDERING_ACQREL: return AcquireRelease;
 183  default: // Map unknown orderings to sequentially-consistent.
 184  case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
 185  }
 186}
 187
 188static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
 189  switch (Val) {
 190  case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
 191  default: // Map unknown scopes to cross-thread.
 192  case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
 193  }
 194}
 195
 196namespace llvm {
 197namespace {
 198  /// @brief A class for maintaining the slot number definition
 199  /// as a placeholder for the actual definition for forward constants defs.
 200  class ConstantPlaceHolder : public ConstantExpr {
 201    void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
 202  public:
 203    // allocate space for exactly one operand
 204    void *operator new(size_t s) {
 205      return User::operator new(s, 1);
 206    }
 207    explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
 208      : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
 209      Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
 210    }
 211
 212    /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
 213    static bool classof(const Value *V) {
 214      return isa<ConstantExpr>(V) &&
 215             cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
 216    }
 217
 218
 219    /// Provide fast operand accessors
 220    //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
 221  };
 222}
 223
 224// FIXME: can we inherit this from ConstantExpr?
 225template <>
 226struct OperandTraits<ConstantPlaceHolder> :
 227  public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
 228};
 229}
 230
 231
 232void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
 233  if (Idx == size()) {
 234    push_back(V);
 235    return;
 236  }
 237
 238  if (Idx >= size())
 239    resize(Idx+1);
 240
 241  WeakVH &OldV = ValuePtrs[Idx];
 242  if (OldV == 0) {
 243    OldV = V;
 244    return;
 245  }
 246
 247  // Handle constants and non-constants (e.g. instrs) differently for
 248  // efficiency.
 249  if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
 250    ResolveConstants.push_back(std::make_pair(PHC, Idx));
 251    OldV = V;
 252  } else {
 253    // If there was a forward reference to this value, replace it.
 254    Value *PrevVal = OldV;
 255    OldV->replaceAllUsesWith(V);
 256    delete PrevVal;
 257  }
 258}
 259
 260
 261Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
 262                                                    Type *Ty) {
 263  if (Idx >= size())
 264    resize(Idx + 1);
 265
 266  if (Value *V = ValuePtrs[Idx]) {
 267    assert(Ty == V->getType() && "Type mismatch in constant table!");
 268    return cast<Constant>(V);
 269  }
 270
 271  // Create and return a placeholder, which will later be RAUW'd.
 272  Constant *C = new ConstantPlaceHolder(Ty, Context);
 273  ValuePtrs[Idx] = C;
 274  return C;
 275}
 276
 277Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
 278  if (Idx >= size())
 279    resize(Idx + 1);
 280
 281  if (Value *V = ValuePtrs[Idx]) {
 282    assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
 283    return V;
 284  }
 285
 286  // No type specified, must be invalid reference.
 287  if (Ty == 0) return 0;
 288
 289  // Create and return a placeholder, which will later be RAUW'd.
 290  Value *V = new Argument(Ty);
 291  ValuePtrs[Idx] = V;
 292  return V;
 293}
 294
 295/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
 296/// resolves any forward references.  The idea behind this is that we sometimes
 297/// get constants (such as large arrays) which reference *many* forward ref
 298/// constants.  Replacing each of these causes a lot of thrashing when
 299/// building/reuniquing the constant.  Instead of doing this, we look at all the
 300/// uses and rewrite all the place holders at once for any constant that uses
 301/// a placeholder.
 302void BitcodeReaderValueList::ResolveConstantForwardRefs() {
 303  // Sort the values by-pointer so that they are efficient to look up with a
 304  // binary search.
 305  std::sort(ResolveConstants.begin(), ResolveConstants.end());
 306
 307  SmallVector<Constant*, 64> NewOps;
 308
 309  while (!ResolveConstants.empty()) {
 310    Value *RealVal = operator[](ResolveConstants.back().second);
 311    Constant *Placeholder = ResolveConstants.back().first;
 312    ResolveConstants.pop_back();
 313
 314    // Loop over all users of the placeholder, updating them to reference the
 315    // new value.  If they reference more than one placeholder, update them all
 316    // at once.
 317    while (!Placeholder->use_empty()) {
 318      Value::use_iterator UI = Placeholder->use_begin();
 319      User *U = *UI;
 320
 321      // If the using object isn't uniqued, just update the operands.  This
 322      // handles instructions and initializers for global variables.
 323      if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
 324        UI.getUse().set(RealVal);
 325        continue;
 326      }
 327
 328      // Otherwise, we have a constant that uses the placeholder.  Replace that
 329      // constant with a new constant that has *all* placeholder uses updated.
 330      Constant *UserC = cast<Constant>(U);
 331      for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
 332           I != E; ++I) {
 333        Value *NewOp;
 334        if (!isa<ConstantPlaceHolder>(*I)) {
 335          // Not a placeholder reference.
 336          NewOp = *I;
 337        } else if (*I == Placeholder) {
 338          // Common case is that it just references this one placeholder.
 339          NewOp = RealVal;
 340        } else {
 341          // Otherwise, look up the placeholder in ResolveConstants.
 342          ResolveConstantsTy::iterator It =
 343            std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
 344                             std::pair<Constant*, unsigned>(cast<Constant>(*I),
 345                                                            0));
 346          assert(It != ResolveConstants.end() && It->first == *I);
 347          NewOp = operator[](It->second);
 348        }
 349
 350        NewOps.push_back(cast<Constant>(NewOp));
 351      }
 352
 353      // Make the new constant.
 354      Constant *NewC;
 355      if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
 356        NewC = ConstantArray::get(UserCA->getType(), NewOps);
 357      } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
 358        NewC = ConstantStruct::get(UserCS->getType(), NewOps);
 359      } else if (isa<ConstantVector>(UserC)) {
 360        NewC = ConstantVector::get(NewOps);
 361      } else {
 362        assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
 363        NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
 364      }
 365
 366      UserC->replaceAllUsesWith(NewC);
 367      UserC->destroyConstant();
 368      NewOps.clear();
 369    }
 370
 371    // Update all ValueHandles, they should be the only users at this point.
 372    Placeholder->replaceAllUsesWith(RealVal);
 373    delete Placeholder;
 374  }
 375}
 376
 377void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
 378  if (Idx == size()) {
 379    push_back(V);
 380    return;
 381  }
 382
 383  if (Idx >= size())
 384    resize(Idx+1);
 385
 386  WeakVH &OldV = MDValuePtrs[Idx];
 387  if (OldV == 0) {
 388    OldV = V;
 389    return;
 390  }
 391
 392  // If there was a forward reference to this value, replace it.
 393  MDNode *PrevVal = cast<MDNode>(OldV);
 394  OldV->replaceAllUsesWith(V);
 395  MDNode::deleteTemporary(PrevVal);
 396  // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
 397  // value for Idx.
 398  MDValuePtrs[Idx] = V;
 399}
 400
 401Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
 402  if (Idx >= size())
 403    resize(Idx + 1);
 404
 405  if (Value *V = MDValuePtrs[Idx]) {
 406    assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
 407    return V;
 408  }
 409
 410  // Create and return a placeholder, which will later be RAUW'd.
 411  Value *V = MDNode::getTemporary(Context, None);
 412  MDValuePtrs[Idx] = V;
 413  return V;
 414}
 415
 416Type *BitcodeReader::getTypeByID(unsigned ID) {
 417  // The type table size is always specified correctly.
 418  if (ID >= TypeList.size())
 419    return 0;
 420
 421  if (Type *Ty = TypeList[ID])
 422    return Ty;
 423
 424  // If we have a forward reference, the only possible case is when it is to a
 425  // named struct.  Just create a placeholder for now.
 426  return TypeList[ID] = StructType::create(Context);
 427}
 428
 429
 430//===----------------------------------------------------------------------===//
 431//  Functions for parsing blocks from the bitcode file
 432//===----------------------------------------------------------------------===//
 433
 434
 435/// \brief This fills an AttrBuilder object with the LLVM attributes that have
 436/// been decoded from the given integer. This function must stay in sync with
 437/// 'encodeLLVMAttributesForBitcode'.
 438static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
 439                                           uint64_t EncodedAttrs) {
 440  // FIXME: Remove in 4.0.
 441
 442  // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
 443  // the bits above 31 down by 11 bits.
 444  unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
 445  assert((!Alignment || isPowerOf2_32(Alignment)) &&
 446         "Alignment must be a power of two.");
 447
 448  if (Alignment)
 449    B.addAlignmentAttr(Alignment);
 450  B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
 451                (EncodedAttrs & 0xffff));
 452}
 453
 454error_code BitcodeReader::ParseAttributeBlock() {
 455  if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
 456    return Error(InvalidRecord);
 457
 458  if (!MAttributes.empty())
 459    return Error(InvalidMultipleBlocks);
 460
 461  SmallVector<uint64_t, 64> Record;
 462
 463  SmallVector<AttributeSet, 8> Attrs;
 464
 465  // Read all the records.
 466  while (1) {
 467    BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
 468
 469    switch (Entry.Kind) {
 470    case BitstreamEntry::SubBlock: // Handled for us already.
 471    case BitstreamEntry::Error:
 472      return Error(MalformedBlock);
 473    case BitstreamEntry::EndBlock:
 474      return error_code::success();
 475    case BitstreamEntry::Record:
 476      // The interesting case.
 477      break;
 478    }
 479
 480    // Read a record.
 481    Record.clear();
 482    switch (Stream.readRecord(Entry.ID, Record)) {
 483    default:  // Default behavior: ignore.
 484      break;
 485    case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
 486      // FIXME: Remove in 4.0.
 487      if (Record.size() & 1)
 488        return Error(InvalidRecord);
 489
 490      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
 491        AttrBuilder B;
 492        decodeLLVMAttributesForBitcode(B, Record[i+1]);
 493        Attrs.push_back(AttributeSet::get(Context, Record[i], B));
 494      }
 495
 496      MAttributes.push_back(AttributeSet::get(Context, Attrs));
 497      Attrs.clear();
 498      break;
 499    }
 500    case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
 501      for (unsigned i = 0, e = Record.size(); i != e; ++i)
 502        Attrs.push_back(MAttributeGroups[Record[i]]);
 503
 504      MAttributes.push_back(AttributeSet::get(Context, Attrs));
 505      Attrs.clear();
 506      break;
 507    }
 508    }
 509  }
 510}
 511
 512// Returns Attribute::None on unrecognized codes.
 513static Attribute::AttrKind GetAttrFromCode(uint64_t Code) {
 514  switch (Code) {
 515  default:
 516    return Attribute::None;
 517  case bitc::ATTR_KIND_ALIGNMENT:
 518    return Attribute::Alignment;
 519  case bitc::ATTR_KIND_ALWAYS_INLINE:
 520    return Attribute::AlwaysInline;
 521  case bitc::ATTR_KIND_BUILTIN:
 522    return Attribute::Builtin;
 523  case bitc::ATTR_KIND_BY_VAL:
 524    return Attribute::ByVal;
 525  case bitc::ATTR_KIND_COLD:
 526    return Attribute::Cold;
 527  case bitc::ATTR_KIND_INLINE_HINT:
 528    return Attribute::InlineHint;
 529  case bitc::ATTR_KIND_IN_REG:
 530    return Attribute::InReg;
 531  case bitc::ATTR_KIND_MIN_SIZE:
 532    return Attribute::MinSize;
 533  case bitc::ATTR_KIND_NAKED:
 534    return Attribute::Naked;
 535  case bitc::ATTR_KIND_NEST:
 536    return Attribute::Nest;
 537  case bitc::ATTR_KIND_NO_ALIAS:
 538    return Attribute::NoAlias;
 539  case bitc::ATTR_KIND_NO_BUILTIN:
 540    return Attribute::NoBuiltin;
 541  case bitc::ATTR_KIND_NO_CAPTURE:
 542    return Attribute::NoCapture;
 543  case bitc::ATTR_KIND_NO_DUPLICATE:
 544    return Attribute::NoDuplicate;
 545  case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
 546    return Attribute::NoImplicitFloat;
 547  case bitc::ATTR_KIND_NO_INLINE:
 548    return Attribute::NoInline;
 549  case bitc::ATTR_KIND_NON_LAZY_BIND:
 550    return Attribute::NonLazyBind;
 551  case bitc::ATTR_KIND_NO_RED_ZONE:
 552    return Attribute::NoRedZone;
 553  case bitc::ATTR_KIND_NO_RETURN:
 554    return Attribute::NoReturn;
 555  case bitc::ATTR_KIND_NO_UNWIND:
 556    return Attribute::NoUnwind;
 557  case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
 558    return Attribute::OptimizeForSize;
 559  case bitc::ATTR_KIND_OPTIMIZE_NONE:
 560    return Attribute::OptimizeNone;
 561  case bitc::ATTR_KIND_READ_NONE:
 562    return Attribute::ReadNone;
 563  case bitc::ATTR_KIND_READ_ONLY:
 564    return Attribute::ReadOnly;
 565  case bitc::ATTR_KIND_RETURNED:
 566    return Attribute::Returned;
 567  case bitc::ATTR_KIND_RETURNS_TWICE:
 568    return Attribute::ReturnsTwice;
 569  case bitc::ATTR_KIND_S_EXT:
 570    return Attribute::SExt;
 571  case bitc::ATTR_KIND_STACK_ALIGNMENT:
 572    return Attribute::StackAlignment;
 573  case bitc::ATTR_KIND_STACK_PROTECT:
 574    return Attribute::StackProtect;
 575  case bitc::ATTR_KIND_STACK_PROTECT_REQ:
 576    return Attribute::StackProtectReq;
 577  case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
 578    return Attribute::StackProtectStrong;
 579  case bitc::ATTR_KIND_STRUCT_RET:
 580    return Attribute::StructRet;
 581  case bitc::ATTR_KIND_SANITIZE_ADDRESS:
 582    return Attribute::SanitizeAddress;
 583  case bitc::ATTR_KIND_SANITIZE_THREAD:
 584    return Attribute::SanitizeThread;
 585  case bitc::ATTR_KIND_SANITIZE_MEMORY:
 586    return Attribute::SanitizeMemory;
 587  case bitc::ATTR_KIND_UW_TABLE:
 588    return Attribute::UWTable;
 589  case bitc::ATTR_KIND_Z_EXT:
 590    return Attribute::ZExt;
 591  }
 592}
 593
 594error_code BitcodeReader::ParseAttrKind(uint64_t Code,
 595                                        Attribute::AttrKind *Kind) {
 596  *Kind = GetAttrFromCode(Code);
 597  if (*Kind == Attribute::None)
 598    return Error(InvalidValue);
 599  return error_code::success();
 600}
 601
 602error_code BitcodeReader::ParseAttributeGroupBlock() {
 603  if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
 604    return Error(InvalidRecord);
 605
 606  if (!MAttributeGroups.empty())
 607    return Error(InvalidMultipleBlocks);
 608
 609  SmallVector<uint64_t, 64> Record;
 610
 611  // Read all the records.
 612  while (1) {
 613    BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
 614
 615    switch (Entry.Kind) {
 616    case BitstreamEntry::SubBlock: // Handled for us already.
 617    case BitstreamEntry::Error:
 618      return Error(MalformedBlock);
 619    case BitstreamEntry::EndBlock:
 620      return error_code::success();
 621    case BitstreamEntry::Record:
 622      // The interesting case.
 623      break;
 624    }
 625
 626    // Read a record.
 627    Record.clear();
 628    switch (Stream.readRecord(Entry.ID, Record)) {
 629    default:  // Default behavior: ignore.
 630      break;
 631    case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
 632      if (Record.size() < 3)
 633        return Error(InvalidRecord);
 634
 635      uint64_t GrpID = Record[0];
 636      uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
 637
 638      AttrBuilder B;
 639      for (unsigned i = 2, e = Record.size(); i != e; ++i) {
 640        if (Record[i] == 0) {        // Enum attribute
 641          Attribute::AttrKind Kind;
 642          if (error_code EC = ParseAttrKind(Record[++i], &Kind))
 643            return EC;
 644
 645          B.addAttribute(Kind);
 646        } else if (Record[i] == 1) { // Align attribute
 647          Attribute::AttrKind Kind;
 648          if (error_code EC = ParseAttrKind(Record[++i], &Kind))
 649            return EC;
 650          if (Kind == Attribute::Alignment)
 651            B.addAlignmentAttr(Record[++i]);
 652          else
 653            B.addStackAlignmentAttr(Record[++i]);
 654        } else {                     // String attribute
 655          assert((Record[i] == 3 || Record[i] == 4) &&
 656                 "Invalid attribute group entry");
 657          bool HasValue = (Record[i++] == 4);
 658          SmallString<64> KindStr;
 659          SmallString<64> ValStr;
 660
 661          while (Record[i] != 0 && i != e)
 662            KindStr += Record[i++];
 663          assert(Record[i] == 0 && "Kind string not null terminated");
 664
 665          if (HasValue) {
 666            // Has a value associated with it.
 667            ++i; // Skip the '0' that terminates the "kind" string.
 668            while (Record[i] != 0 && i != e)
 669              ValStr += Record[i++];
 670            assert(Record[i] == 0 && "Value string not null terminated");
 671          }
 672
 673          B.addAttribute(KindStr.str(), ValStr.str());
 674        }
 675      }
 676
 677      MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
 678      break;
 679    }
 680    }
 681  }
 682}
 683
 684error_code BitcodeReader::ParseTypeTable() {
 685  if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
 686    return Error(InvalidRecord);
 687
 688  return ParseTypeTableBody();
 689}
 690
 691error_code BitcodeReader::ParseTypeTableBody() {
 692  if (!TypeList.empty())
 693    return Error(InvalidMultipleBlocks);
 694
 695  SmallVector<uint64_t, 64> Record;
 696  unsigned NumRecords = 0;
 697
 698  SmallString<64> TypeName;
 699
 700  // Read all the records for this type table.
 701  while (1) {
 702    BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
 703
 704    switch (Entry.Kind) {
 705    case BitstreamEntry::SubBlock: // Handled for us already.
 706    case BitstreamEntry::Error:
 707      return Error(MalformedBlock);
 708    case BitstreamEntry::EndBlock:
 709      if (NumRecords != TypeList.size())
 710        return Error(MalformedBlock);
 711      return error_code::success();
 712    case BitstreamEntry::Record:
 713      // The interesting case.
 714      break;
 715    }
 716
 717    // Read a record.
 718    Record.clear();
 719    Type *ResultTy = 0;
 720    switch (Stream.readRecord(Entry.ID, Record)) {
 721    default:
 722      return Error(InvalidValue);
 723    case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
 724      // TYPE_CODE_NUMENTRY contains a count of the number of types in the
 725      // type list.  This allows us to reserve space.
 726      if (Record.size() < 1)
 727        return Error(InvalidRecord);
 728      TypeList.resize(Record[0]);
 729      continue;
 730    case bitc::TYPE_CODE_VOID:      // VOID
 731      ResultTy = Type::getVoidTy(Context);
 732      break;
 733    case bitc::TYPE_CODE_HALF:     // HALF
 734      ResultTy = Type::getHalfTy(Context);
 735      break;
 736    case bitc::TYPE_CODE_FLOAT:     // FLOAT
 737      ResultTy = Type::getFloatTy(Context);
 738      break;
 739    case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
 740      ResultTy = Type::getDoubleTy(Context);
 741      break;
 742    case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
 743      ResultTy = Type::getX86_FP80Ty(Context);
 744      break;
 745    case bitc::TYPE_CODE_FP128:     // FP128
 746      ResultTy = Type::getFP128Ty(Context);
 747      break;
 748    case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
 749      ResultTy = Type::getPPC_FP128Ty(Context);
 750      break;
 751    case bitc::TYPE_CODE_LABEL:     // LABEL
 752      ResultTy = Type::getLabelTy(Context);
 753      break;
 754    case bitc::TYPE_CODE_METADATA:  // METADATA
 755      ResultTy = Type::getMetadataTy(Context);
 756      break;
 757    case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
 758      ResultTy = Type::getX86_MMXTy(Context);
 759      break;
 760    case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
 761      if (Record.size() < 1)
 762        return Error(InvalidRecord);
 763
 764      ResultTy = IntegerType::get(Context, Record[0]);
 765      break;
 766    case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
 767                                    //          [pointee type, address space]
 768      if (Record.size() < 1)
 769        return Error(InvalidRecord);
 770      unsigned AddressSpace = 0;
 771      if (Record.size() == 2)
 772        AddressSpace = Record[1];
 773      ResultTy = getTypeByID(Record[0]);
 774      if (ResultTy == 0)
 775        return Error(InvalidType);
 776      ResultTy = PointerType::get(ResultTy, AddressSpace);
 777      break;
 778    }
 779    case bitc::TYPE_CODE_FUNCTION_OLD: {
 780      // FIXME: attrid is dead, remove it in LLVM 4.0
 781      // FUNCTION: [vararg, attrid, retty, paramty x N]
 782      if (Record.size() < 3)
 783        return Error(InvalidRecord);
 784      SmallVector<Type*, 8> ArgTys;
 785      for (unsigned i = 3, e = Record.size(); i != e; ++i) {
 786        if (Type *T = getTypeByID(Record[i]))
 787          ArgTys.push_back(T);
 788        else
 789          break;
 790      }
 791
 792      ResultTy = getTypeByID(Record[2]);
 793      if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
 794        return Error(InvalidType);
 795
 796      ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
 797      break;
 798    }
 799    case bitc::TYPE_CODE_FUNCTION: {
 800      // FUNCTION: [vararg, retty, paramty x N]
 801      if (Record.size() < 2)
 802        return Error(InvalidRecord);
 803      SmallVector<Type*, 8> ArgTys;
 804      for (unsigned i = 2, e = Record.size(); i != e; ++i) {
 805        if (Type *T = getTypeByID(Record[i]))
 806          ArgTys.push_back(T);
 807        else
 808          break;
 809      }
 810
 811      ResultTy = getTypeByID(Record[1]);
 812      if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
 813        return Error(InvalidType);
 814
 815      ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
 816      break;
 817    }
 818    case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
 819      if (Record.size() < 1)
 820        return Error(InvalidRecord);
 821      SmallVector<Type*, 8> EltTys;
 822      for (unsigned i = 1, e = Record.size(); i != e; ++i) {
 823        if (Type *T = getTypeByID(Record[i]))
 824          EltTys.push_back(T);
 825        else
 826          break;
 827      }
 828      if (EltTys.size() != Record.size()-1)
 829        return Error(InvalidType);
 830      ResultTy = StructType::get(Context, EltTys, Record[0]);
 831      break;
 832    }
 833    case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
 834      if (ConvertToString(Record, 0, TypeName))
 835        return Error(InvalidRecord);
 836      continue;
 837
 838    case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
 839      if (Record.size() < 1)
 840        return Error(InvalidRecord);
 841
 842      if (NumRecords >= TypeList.size())
 843        return Error(InvalidTYPETable);
 844
 845      // Check to see if this was forward referenced, if so fill in the temp.
 846      StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
 847      if (Res) {
 848        Res->setName(TypeName);
 849        TypeList[NumRecords] = 0;
 850      } else  // Otherwise, create a new struct.
 851        Res = StructType::create(Context, TypeName);
 852      TypeName.clear();
 853
 854      SmallVector<Type*, 8> EltTys;
 855      for (unsigned i = 1, e = Record.size(); i != e; ++i) {
 856        if (Type *T = getTypeByID(Record[i]))
 857          EltTys.push_back(T);
 858        else
 859          break;
 860      }
 861      if (EltTys.size() != Record.size()-1)
 862        return Error(InvalidRecord);
 863      Res->setBody(EltTys, Record[0]);
 864      ResultTy = Res;
 865      break;
 866    }
 867    case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
 868      if (Record.size() != 1)
 869        return Error(InvalidRecord);
 870
 871      if (NumRecords >= TypeList.size())
 872        return Error(InvalidTYPETable);
 873
 874      // Check to see if this was forward referenced, if so fill in the temp.
 875      StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
 876      if (Res) {
 877        Res->setName(TypeName);
 878        TypeList[NumRecords] = 0;
 879      } else  // Otherwise, create a new struct with no body.
 880        Res = StructType::create(Context, TypeName);
 881      TypeName.clear();
 882      ResultTy = Res;
 883      break;
 884    }
 885    case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
 886      if (Record.size() < 2)
 887        return Error(InvalidRecord);
 888      if ((ResultTy = getTypeByID(Record[1])))
 889        ResultTy = ArrayType::get(ResultTy, Record[0]);
 890      else
 891        return Error(InvalidType);
 892      break;
 893    case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
 894      if (Record.size() < 2)
 895        return Error(InvalidRecord);
 896      if ((ResultTy = getTypeByID(Record[1])))
 897        ResultTy = VectorType::get(ResultTy, Record[0]);
 898      else
 899        return Error(InvalidType);
 900      break;
 901    }
 902
 903    if (NumRecords >= TypeList.size())
 904      return Error(InvalidTYPETable);
 905    assert(ResultTy && "Didn't read a type?");
 906    assert(TypeList[NumRecords] == 0 && "Already read type?");
 907    TypeList[NumRecords++] = ResultTy;
 908  }
 909}
 910
 911error_code BitcodeReader::ParseValueSymbolTable() {
 912  if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
 913    return Error(InvalidRecord);
 914
 915  SmallVector<uint64_t, 64> Record;
 916
 917  // Read all the records for this value table.
 918  SmallString<128> ValueName;
 919  while (1) {
 920    BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
 921
 922    switch (Entry.Kind) {
 923    case BitstreamEntry::SubBlock: // Handled for us already.
 924    case BitstreamEntry::Error:
 925      return Error(MalformedBlock);
 926    case BitstreamEntry::EndBlock:
 927      return error_code::success();
 928    case BitstreamEntry::Record:
 929      // The interesting case.
 930      break;
 931    }
 932
 933    // Read a record.
 934    Record.clear();
 935    switch (Stream.readRecord(Entry.ID, Record)) {
 936    default:  // Default behavior: unknown type.
 937      break;
 938    case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
 939      if (ConvertToString(Record, 1, ValueName))
 940        return Error(InvalidRecord);
 941      unsigned ValueID = Record[0];
 942      if (ValueID >= ValueList.size())
 943        return Error(InvalidRecord);
 944      Value *V = ValueList[ValueID];
 945
 946      V->setName(StringRef(ValueName.data(), ValueName.size()));
 947      ValueName.clear();
 948      break;
 949    }
 950    case bitc::VST_CODE_BBENTRY: {
 951      if (ConvertToString(Record, 1, ValueName))
 952        return Error(InvalidRecord);
 953      BasicBlock *BB = getBasicBlock(Record[0]);
 954      if (BB == 0)
 955        return Error(InvalidRecord);
 956
 957      BB->setName(StringRef(ValueName.data(), ValueName.size()));
 958      ValueName.clear();
 959      break;
 960    }
 961    }
 962  }
 963}
 964
 965error_code BitcodeReader::ParseMetadata() {
 966  unsigned NextMDValueNo = MDValueList.size();
 967
 968  if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
 969    return Error(InvalidRecord);
 970
 971  SmallVector<uint64_t, 64> Record;
 972
 973  // Read all the records.
 974  while (1) {
 975    BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
 976
 977    switch (Entry.Kind) {
 978    case BitstreamEntry::SubBlock: // Handled for us already.
 979    case BitstreamEntry::Error:
 980      return Error(MalformedBlock);
 981    case BitstreamEntry::EndBlock:
 982      return error_code::success();
 983    case BitstreamEntry::Record:
 984      // The interesting case.
 985      break;
 986    }
 987
 988    bool IsFunctionLocal = false;
 989    // Read a record.
 990    Record.clear();
 991    unsigned Code = Stream.readRecord(Entry.ID, Record);
 992    switch (Code) {
 993    default:  // Default behavior: ignore.
 994      break;
 995    case bitc::METADATA_NAME: {
 996      // Read name of the named metadata.
 997      SmallString<8> Name(Record.begin(), Record.end());
 998      Record.clear();
 999      Code = Stream.ReadCode();
1000
1001      // METADATA_NAME is always followed by METADATA_NAMED_NODE.
1002      unsigned NextBitCode = Stream.readRecord(Code, Record);
1003      assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
1004
1005      // Read named metadata elements.
1006      unsigned Size = Record.size();
1007      NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
1008      for (unsigned i = 0; i != Size; ++i) {
1009        MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
1010        if (MD == 0)
1011          return Error(InvalidRecord);
1012        NMD->addOperand(MD);
1013      }
1014      break;
1015    }
1016    case bitc::METADATA_FN_NODE:
1017      IsFunctionLocal = true;
1018      // fall-through
1019    case bitc::METADATA_NODE: {
1020      if (Record.size() % 2 == 1)
1021        return Error(InvalidRecord);
1022
1023      unsigned Size = Record.size();
1024      SmallVector<Value*, 8> Elts;
1025      for (unsigned i = 0; i != Size; i += 2) {
1026        Type *Ty = getTypeByID(Record[i]);
1027        if (!Ty)
1028          return Error(InvalidRecord);
1029        if (Ty->isMetadataTy())
1030          Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
1031        else if (!Ty->isVoidTy())
1032          Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
1033        else
1034          Elts.push_back(NULL);
1035      }
1036      Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
1037      IsFunctionLocal = false;
1038      MDValueList.AssignValue(V, NextMDValueNo++);
1039      break;
1040    }
1041    case bitc::METADATA_STRING: {
1042      SmallString<8> String(Record.begin(), Record.end());
1043      Value *V = MDString::get(Context, String);
1044      MDValueList.AssignValue(V, NextMDValueNo++);
1045      break;
1046    }
1047    case bitc::METADATA_KIND: {
1048      if (Record.size() < 2)
1049        return Error(InvalidRecord);
1050
1051      unsigned Kind = Record[0];
1052      SmallString<8> Name(Record.begin()+1, Record.end());
1053
1054      unsigned NewKind = TheModule->getMDKindID(Name.str());
1055      if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
1056        return Error(ConflictingMETADATA_KINDRecords);
1057      break;
1058    }
1059    }
1060  }
1061}
1062
1063/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
1064/// the LSB for dense VBR encoding.
1065uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
1066  if ((V & 1) == 0)
1067    return V >> 1;
1068  if (V != 1)
1069    return -(V >> 1);
1070  // There is no such thing as -0 with integers.  "-0" really means MININT.
1071  return 1ULL << 63;
1072}
1073
1074/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
1075/// values and aliases that we can.
1076error_code BitcodeReader::ResolveGlobalAndAliasInits() {
1077  std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
1078  std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
1079  std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
1080
1081  GlobalInitWorklist.swap(GlobalInits);
1082  AliasInitWorklist.swap(AliasInits);
1083  FunctionPrefixWorklist.swap(FunctionPrefixes);
1084
1085  while (!GlobalInitWorklist.empty()) {
1086    unsigned ValID = GlobalInitWorklist.back().second;
1087    if (ValID >= ValueList.size()) {
1088      // Not ready to resolve this yet, it requires something later in the file.
1089      GlobalInits.push_back(GlobalInitWorklist.back());
1090    } else {
1091      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1092        GlobalInitWorklist.back().first->setInitializer(C);
1093      else
1094        return Error(ExpectedConstant);
1095    }
1096    GlobalInitWorklist.pop_back();
1097  }
1098
1099  while (!AliasInitWorklist.empty()) {
1100    unsigned ValID = AliasInitWorklist.back().second;
1101    if (ValID >= ValueList.size()) {
1102      AliasInits.push_back(AliasInitWorklist.back());
1103    } else {
1104      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1105        AliasInitWorklist.back().first->setAliasee(C);
1106      else
1107        return Error(ExpectedConstant);
1108    }
1109    AliasInitWorklist.pop_back();
1110  }
1111
1112  while (!FunctionPrefixWorklist.empty()) {
1113    unsigned ValID = FunctionPrefixWorklist.back().second;
1114    if (ValID >= ValueList.size()) {
1115      FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
1116    } else {
1117      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
1118        FunctionPrefixWorklist.back().first->setPrefixData(C);
1119      else
1120        return Error(ExpectedConstant);
1121    }
1122    FunctionPrefixWorklist.pop_back();
1123  }
1124
1125  return error_code::success();
1126}
1127
1128static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
1129  SmallVector<uint64_t, 8> Words(Vals.size());
1130  std::transform(Vals.begin(), Vals.end(), Words.begin(),
1131                 BitcodeReader::decodeSignRotatedValue);
1132
1133  return APInt(TypeBits, Words);
1134}
1135
1136error_code BitcodeReader::ParseConstants() {
1137  if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
1138    return Error(InvalidRecord);
1139
1140  SmallVector<uint64_t, 64> Record;
1141
1142  // Read all the records for this value table.
1143  Type *CurTy = Type::getInt32Ty(Context);
1144  unsigned NextCstNo = ValueList.size();
1145  while (1) {
1146    BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
1147
1148    switch (Entry.Kind) {
1149    case BitstreamEntry::SubBlock: // Handled for us already.
1150    case BitstreamEntry::Error:
1151      return Error(MalformedBlock);
1152    case BitstreamEntry::EndBlock:
1153      if (NextCstNo != ValueList.size())
1154        return Error(InvalidConstantReference);
1155
1156      // Once all the constants have been read, go through and resolve forward
1157      // references.
1158      ValueList.ResolveConstantForwardRefs();
1159      return error_code::success();
1160    case BitstreamEntry::Record:
1161      // The interesting case.
1162      break;
1163    }
1164
1165    // Read a record.
1166    Record.clear();
1167    Value *V = 0;
1168    unsigned BitCode = Stream.readRecord(Entry.ID, Record);
1169    switch (BitCode) {
1170    default:  // Default behavior: unknown constant
1171    case bitc::CST_CODE_UNDEF:     // UNDEF
1172      V = UndefValue::get(CurTy);
1173      break;
1174    case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
1175      if (Record.empty())
1176        return Error(InvalidRecord);
1177      if (Record[0] >= TypeList.size())
1178        return Error(InvalidRecord);
1179      CurTy = TypeList[Record[0]];
1180      continue;  // Skip the ValueList manipulation.
1181    case bitc::CST_CODE_NULL:      // NULL
1182      V = Constant::getNullValue(CurTy);
1183      break;
1184    case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
1185      if (!CurTy->isIntegerTy() || Record.empty())
1186        return Error(InvalidRecord);
1187      V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1188      break;
1189    case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1190      if (!CurTy->isIntegerTy() || Record.empty())
1191        return Error(InvalidRecord);
1192
1193      APInt VInt = ReadWideAPInt(Record,
1194                                 cast<IntegerType>(CurTy)->getBitWidth());
1195      V = ConstantInt::get(Context, VInt);
1196
1197      break;
1198    }
1199    case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
1200      if (Record.empty())
1201        return Error(InvalidRecord);
1202      if (CurTy->isHalfTy())
1203        V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
1204                                             APInt(16, (uint16_t)Record[0])));
1205      else if (CurTy->isFloatTy())
1206        V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
1207                                             APInt(32, (uint32_t)Record[0])));
1208      else if (CurTy->isDoubleTy())
1209        V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
1210                                             APInt(64, Record[0])));
1211      else if (CurTy->isX86_FP80Ty()) {
1212        // Bits are not stored the same way as a normal i80 APInt, compensate.
1213        uint64_t Rearrange[2];
1214        Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1215        Rearrange[1] = Record[0] >> 48;
1216        V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
1217                                             APInt(80, Rearrange)));
1218      } else if (CurTy->isFP128Ty())
1219        V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
1220                                             APInt(128, Record)));
1221      else if (CurTy->isPPC_FP128Ty())
1222        V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
1223                                             APInt(128, Record)));
1224      else
1225        V = UndefValue::get(CurTy);
1226      break;
1227    }
1228
1229    case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1230      if (Record.empty())
1231        return Error(InvalidRecord);
1232
1233      unsigned Size = Record.size();
1234      SmallVector<Constant*, 16> Elts;
1235
1236      if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1237        for (unsigned i = 0; i != Size; ++i)
1238          Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1239                                                     STy->getElementType(i)));
1240        V = ConstantStruct::get(STy, Elts);
1241      } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1242        Type *EltTy = ATy->getElementType();
1243        for (unsigned i = 0; i != Size; ++i)
1244          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1245        V = ConstantArray::get(ATy, Elts);
1246      } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1247        Type *EltTy = VTy->getElementType();
1248        for (unsigned i = 0; i != Size; ++i)
1249          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1250        V = ConstantVector::get(Elts);
1251      } else {
1252        V = UndefValue::get(CurTy);
1253      }
1254      break;
1255    }
1256    case bitc::CST_CODE_STRING:    // STRING: [values]
1257    case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1258      if (Record.empty())
1259        return Error(InvalidRecord);
1260
1261      SmallString<16> Elts(Record.begin(), Record.end());
1262      V = ConstantDataArray::getString(Context, Elts,
1263                                       BitCode == bitc::CST_CODE_CSTRING);
1264      break;
1265    }
1266    case bitc::CST_CODE_DATA: {// DATA: [n x value]
1267      if (Record.empty())
1268        return Error(InvalidRecord);
1269
1270      Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1271      unsigned Size = Record.size();
1272
1273      if (EltTy->isIntegerTy(8)) {
1274        SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1275        if (isa<VectorType>(CurTy))
1276          V = ConstantDataVector::get(Context, Elts);
1277        else
1278          V = ConstantDataArray::get(Context, Elts);
1279      } else if (EltTy->isIntegerTy(16)) {
1280        SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1281        if (isa<VectorType>(CurTy))
1282          V = ConstantDataVector::get(Context, Elts);
1283        else
1284          V = ConstantDataArray::get(Context, Elts);
1285      } else if (EltTy->isIntegerTy(32)) {
1286        SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1287        if (isa<VectorType>(CurTy))
1288          V = ConstantDataVector::get(Context, Elts);
1289        else
1290          V = ConstantDataArray::get(Context, Elts);
1291      } else if (EltTy->isIntegerTy(64)) {
1292        SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1293        if (isa<VectorType>(CurTy))
1294          V = ConstantDataVector::get(Context, Elts);
1295        else
1296          V = ConstantDataArray::get(Context, Elts);
1297      } else if (EltTy->isFloatTy()) {
1298        SmallVector<float, 16> Elts(Size);
1299        std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1300        if (isa<VectorType>(CurTy))
1301          V = ConstantDataVector::get(Context, Elts);
1302        else
1303          V = ConstantDataArray::get(Context, Elts);
1304      } else if (EltTy->isDoubleTy()) {
1305        SmallVector<double, 16> Elts(Size);
1306        std::transform(Record.begin(), Record.end(), Elts.begin(),
1307                       BitsToDouble);
1308        if (isa<VectorType>(CurTy))
1309          V = ConstantDataVector::get(Context, Elts);
1310        else
1311          V = ConstantDataArray::get(Context, Elts);
1312      } else {
1313        return Error(InvalidTypeForValue);
1314      }
1315      break;
1316    }
1317
1318    case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
1319      if (Record.size() < 3)
1320        return Error(InvalidRecord);
1321      int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1322      if (Opc < 0) {
1323        V = UndefValue::get(CurTy);  // Unknown binop.
1324      } else {
1325        Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1326        Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1327        unsigned Flags = 0;
1328        if (Record.size() >= 4) {
1329          if (Opc == Instruction::Add ||
1330              Opc == Instruction::Sub ||
1331              Opc == Instruction::Mul ||
1332              Opc == Instruction::Shl) {
1333            if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1334              Flags |= OverflowingBinaryOperator::NoSignedWrap;
1335            if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1336              Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1337          } else if (Opc == Instruction::SDiv ||
1338                     Opc == Instruction::UDiv ||
1339                     Opc == Instruction::LShr ||
1340                     Opc == Instruction::AShr) {
1341            if (Record[3] & (1 << bitc::PEO_EXACT))
1342              Flags |= SDivOperator::IsExact;
1343          }
1344        }
1345        V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1346      }
1347      break;
1348    }
1349    case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
1350      if (Record.size() < 3)
1351        return Error(InvalidRecord);
1352      int Opc = GetDecodedCastOpcode(Record[0]);
1353      if (Opc < 0) {
1354        V = UndefValue::get(CurTy);  // Unknown cast.
1355      } else {
1356        Type *OpTy = getTypeByID(Record[1]);
1357        if (!OpTy)
1358          return Error(InvalidRecord);
1359        Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1360        V = UpgradeBitCastExpr(Opc, Op, CurTy);
1361        if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
1362      }
1363      break;
1364    }
1365    case bitc::CST_CODE_CE_INBOUNDS_GEP:
1366    case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
1367      if (Record.size() & 1)
1368        return Error(InvalidRecord);
1369      SmallVector<Constant*, 16> Elts;
1370      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1371        Type *ElTy = getTypeByID(Record[i]);
1372        if (!ElTy)
1373          return Error(InvalidRecord);
1374        Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1375      }
1376      ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1377      V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1378                                         BitCode ==
1379                                           bitc::CST_CODE_CE_INBOUNDS_GEP);
1380      break;
1381    }
1382    case bitc::CST_CODE_CE_SELECT: {  // CE_SELECT: [opval#, opval#, opval#]
1383      if (Record.size() < 3)
1384        return Error(InvalidRecord);
1385
1386      Type *SelectorTy = Type::getInt1Ty(Context);
1387
1388      // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
1389      // vector. Otherwise, it must be a single bit.
1390      if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
1391        SelectorTy = VectorType::get(Type::getInt1Ty(Context),
1392                                     VTy->getNumElements());
1393
1394      V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1395                                                              SelectorTy),
1396                                  ValueList.getConstantFwdRef(Record[1],CurTy),
1397                                  ValueList.getConstantFwdRef(Record[2],CurTy));
1398      break;
1399    }
1400    case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1401      if (Record.size() < 3)
1402        return Error(InvalidRecord);
1403      VectorType *OpTy =
1404        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1405      if (OpTy == 0)
1406        return Error(InvalidRecord);
1407      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1408      Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
1409                                                  Type::getInt32Ty(Context));
1410      V = ConstantExpr::getExtractElement(Op0, Op1);
1411      break;
1412    }
1413    case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1414      VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1415      if (Record.size() < 3 || OpTy == 0)
1416        return Error(InvalidRecord);
1417      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1418      Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1419                                                  OpTy->getElementType());
1420      Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
1421                                                  Type::getInt32Ty(Context));
1422      V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1423      break;
1424    }
1425    case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1426      VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1427      if (Record.size() < 3 || OpTy == 0)
1428        return Error(InvalidRecord);
1429      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1430      Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1431      Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1432                                                 OpTy->getNumElements());
1433      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1434      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1435      break;
1436    }
1437    case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, op…

Large files files are truncated, but you can click here to view the full file