LLVM API Documentation

BitcodeReader.cpp

Go to the documentation of this file.
00001 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
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 header defines the BitcodeReader class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Bitcode/ReaderWriter.h"
00015 #include "BitcodeReader.h"
00016 #include "llvm/Constants.h"
00017 #include "llvm/DerivedTypes.h"
00018 #include "llvm/InlineAsm.h"
00019 #include "llvm/Instructions.h"
00020 #include "llvm/Module.h"
00021 #include "llvm/AutoUpgrade.h"
00022 #include "llvm/ADT/SmallString.h"
00023 #include "llvm/ADT/SmallVector.h"
00024 #include "llvm/Support/MathExtras.h"
00025 #include "llvm/Support/MemoryBuffer.h"
00026 #include "llvm/OperandTraits.h"
00027 using namespace llvm;
00028 
00029 void BitcodeReader::FreeState() {
00030   delete Buffer;
00031   Buffer = 0;
00032   std::vector<PATypeHolder>().swap(TypeList);
00033   ValueList.clear();
00034   
00035   std::vector<AttrListPtr>().swap(MAttributes);
00036   std::vector<BasicBlock*>().swap(FunctionBBs);
00037   std::vector<Function*>().swap(FunctionsWithBodies);
00038   DeferredFunctionInfo.clear();
00039 }
00040 
00041 //===----------------------------------------------------------------------===//
00042 //  Helper functions to implement forward reference resolution, etc.
00043 //===----------------------------------------------------------------------===//
00044 
00045 /// ConvertToString - Convert a string from a record into an std::string, return
00046 /// true on failure.
00047 template<typename StrTy>
00048 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
00049                             StrTy &Result) {
00050   if (Idx > Record.size())
00051     return true;
00052   
00053   for (unsigned i = Idx, e = Record.size(); i != e; ++i)
00054     Result += (char)Record[i];
00055   return false;
00056 }
00057 
00058 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
00059   switch (Val) {
00060   default: // Map unknown/new linkages to external
00061   case 0: return GlobalValue::ExternalLinkage;
00062   case 1: return GlobalValue::WeakLinkage;
00063   case 2: return GlobalValue::AppendingLinkage;
00064   case 3: return GlobalValue::InternalLinkage;
00065   case 4: return GlobalValue::LinkOnceLinkage;
00066   case 5: return GlobalValue::DLLImportLinkage;
00067   case 6: return GlobalValue::DLLExportLinkage;
00068   case 7: return GlobalValue::ExternalWeakLinkage;
00069   case 8: return GlobalValue::CommonLinkage;
00070   case 9: return GlobalValue::PrivateLinkage;
00071   }
00072 }
00073 
00074 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
00075   switch (Val) {
00076   default: // Map unknown visibilities to default.
00077   case 0: return GlobalValue::DefaultVisibility;
00078   case 1: return GlobalValue::HiddenVisibility;
00079   case 2: return GlobalValue::ProtectedVisibility;
00080   }
00081 }
00082 
00083 static int GetDecodedCastOpcode(unsigned Val) {
00084   switch (Val) {
00085   default: return -1;
00086   case bitc::CAST_TRUNC   : return Instruction::Trunc;
00087   case bitc::CAST_ZEXT    : return Instruction::ZExt;
00088   case bitc::CAST_SEXT    : return Instruction::SExt;
00089   case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
00090   case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
00091   case bitc::CAST_UITOFP  : return Instruction::UIToFP;
00092   case bitc::CAST_SITOFP  : return Instruction::SIToFP;
00093   case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
00094   case bitc::CAST_FPEXT   : return Instruction::FPExt;
00095   case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
00096   case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
00097   case bitc::CAST_BITCAST : return Instruction::BitCast;
00098   }
00099 }
00100 static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
00101   switch (Val) {
00102   default: return -1;
00103   case bitc::BINOP_ADD:  return Instruction::Add;
00104   case bitc::BINOP_SUB:  return Instruction::Sub;
00105   case bitc::BINOP_MUL:  return Instruction::Mul;
00106   case bitc::BINOP_UDIV: return Instruction::UDiv;
00107   case bitc::BINOP_SDIV:
00108     return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
00109   case bitc::BINOP_UREM: return Instruction::URem;
00110   case bitc::BINOP_SREM:
00111     return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
00112   case bitc::BINOP_SHL:  return Instruction::Shl;
00113   case bitc::BINOP_LSHR: return Instruction::LShr;
00114   case bitc::BINOP_ASHR: return Instruction::AShr;
00115   case bitc::BINOP_AND:  return Instruction::And;
00116   case bitc::BINOP_OR:   return Instruction::Or;
00117   case bitc::BINOP_XOR:  return Instruction::Xor;
00118   }
00119 }
00120 
00121 namespace llvm {
00122 namespace {
00123   /// @brief A class for maintaining the slot number definition
00124   /// as a placeholder for the actual definition for forward constants defs.
00125   class ConstantPlaceHolder : public ConstantExpr {
00126     ConstantPlaceHolder();                       // DO NOT IMPLEMENT
00127     void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
00128   public:
00129     // allocate space for exactly one operand
00130     void *operator new(size_t s) {
00131       return User::operator new(s, 1);
00132     }
00133     explicit ConstantPlaceHolder(const Type *Ty)
00134       : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
00135       Op<0>() = UndefValue::get(Type::Int32Ty);
00136     }
00137     
00138     /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
00139     static inline bool classof(const ConstantPlaceHolder *) { return true; }
00140     static bool classof(const Value *V) {
00141       return isa<ConstantExpr>(V) && 
00142              cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
00143     }
00144     
00145     
00146     /// Provide fast operand accessors
00147     DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
00148   };
00149 }
00150 
00151 
00152   // FIXME: can we inherit this from ConstantExpr?
00153 template <>
00154 struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
00155 };
00156 
00157 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
00158 }
00159 
00160 void BitcodeReaderValueList::resize(unsigned Desired) {
00161   if (Desired > Capacity) {
00162     // Since we expect many values to come from the bitcode file we better
00163     // allocate the double amount, so that the array size grows exponentially
00164     // at each reallocation.  Also, add a small amount of 100 extra elements
00165     // each time, to reallocate less frequently when the array is still small.
00166     //
00167     Capacity = Desired * 2 + 100;
00168     Use *New = allocHungoffUses(Capacity);
00169     Use *Old = OperandList;
00170     unsigned Ops = getNumOperands();
00171     for (int i(Ops - 1); i >= 0; --i)
00172       New[i] = Old[i].get();
00173     OperandList = New;
00174     if (Old) Use::zap(Old, Old + Ops, true);
00175   }
00176 }
00177 
00178 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
00179                                                     const Type *Ty) {
00180   if (Idx >= size()) {
00181     // Insert a bunch of null values.
00182     resize(Idx + 1);
00183     NumOperands = Idx+1;
00184   }
00185 
00186   if (Value *V = OperandList[Idx]) {
00187     assert(Ty == V->getType() && "Type mismatch in constant table!");
00188     return cast<Constant>(V);
00189   }
00190 
00191   // Create and return a placeholder, which will later be RAUW'd.
00192   Constant *C = new ConstantPlaceHolder(Ty);
00193   OperandList[Idx] = C;
00194   return C;
00195 }
00196 
00197 Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
00198   if (Idx >= size()) {
00199     // Insert a bunch of null values.
00200     resize(Idx + 1);
00201     NumOperands = Idx+1;
00202   }
00203   
00204   if (Value *V = OperandList[Idx]) {
00205     assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
00206     return V;
00207   }
00208   
00209   // No type specified, must be invalid reference.
00210   if (Ty == 0) return 0;
00211   
00212   // Create and return a placeholder, which will later be RAUW'd.
00213   Value *V = new Argument(Ty);
00214   OperandList[Idx] = V;
00215   return V;
00216 }
00217 
00218 /// ResolveConstantForwardRefs - Once all constants are read, this method bulk
00219 /// resolves any forward references.  The idea behind this is that we sometimes
00220 /// get constants (such as large arrays) which reference *many* forward ref
00221 /// constants.  Replacing each of these causes a lot of thrashing when
00222 /// building/reuniquing the constant.  Instead of doing this, we look at all the
00223 /// uses and rewrite all the place holders at once for any constant that uses
00224 /// a placeholder.
00225 void BitcodeReaderValueList::ResolveConstantForwardRefs() {
00226   // Sort the values by-pointer so that they are efficient to look up with a 
00227   // binary search.
00228   std::sort(ResolveConstants.begin(), ResolveConstants.end());
00229   
00230   SmallVector<Constant*, 64> NewOps;
00231   
00232   while (!ResolveConstants.empty()) {
00233     Value *RealVal = getOperand(ResolveConstants.back().second);
00234     Constant *Placeholder = ResolveConstants.back().first;
00235     ResolveConstants.pop_back();
00236     
00237     // Loop over all users of the placeholder, updating them to reference the
00238     // new value.  If they reference more than one placeholder, update them all
00239     // at once.
00240     while (!Placeholder->use_empty()) {
00241       Value::use_iterator UI = Placeholder->use_begin();
00242       
00243       // If the using object isn't uniqued, just update the operands.  This
00244       // handles instructions and initializers for global variables.
00245       if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) {
00246         UI.getUse().set(RealVal);
00247         continue;
00248       }
00249       
00250       // Otherwise, we have a constant that uses the placeholder.  Replace that
00251       // constant with a new constant that has *all* placeholder uses updated.
00252       Constant *UserC = cast<Constant>(*UI);
00253       for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
00254            I != E; ++I) {
00255         Value *NewOp;
00256         if (!isa<ConstantPlaceHolder>(*I)) {
00257           // Not a placeholder reference.
00258           NewOp = *I;
00259         } else if (*I == Placeholder) {
00260           // Common case is that it just references this one placeholder.
00261           NewOp = RealVal;
00262         } else {
00263           // Otherwise, look up the placeholder in ResolveConstants.
00264           ResolveConstantsTy::iterator It = 
00265             std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(), 
00266                              std::pair<Constant*, unsigned>(cast<Constant>(*I),
00267                                                             0));
00268           assert(It != ResolveConstants.end() && It->first == *I);
00269           NewOp = this->getOperand(It->second);
00270         }
00271 
00272         NewOps.push_back(cast<Constant>(NewOp));
00273       }
00274 
00275       // Make the new constant.
00276       Constant *NewC;
00277       if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
00278         NewC = ConstantArray::get(UserCA->getType(), &NewOps[0], NewOps.size());
00279       } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
00280         NewC = ConstantStruct::get(&NewOps[0], NewOps.size(),
00281                                    UserCS->getType()->isPacked());
00282       } else if (isa<ConstantVector>(UserC)) {
00283         NewC = ConstantVector::get(&NewOps[0], NewOps.size());
00284       } else {
00285         // Must be a constant expression.
00286         NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
00287                                                           NewOps.size());
00288       }
00289       
00290       UserC->replaceAllUsesWith(NewC);
00291       UserC->destroyConstant();
00292       NewOps.clear();
00293     }
00294     
00295     delete Placeholder;
00296   }
00297 }
00298 
00299 
00300 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
00301   // If the TypeID is in range, return it.
00302   if (ID < TypeList.size())
00303     return TypeList[ID].get();
00304   if (!isTypeTable) return 0;
00305   
00306   // The type table allows forward references.  Push as many Opaque types as
00307   // needed to get up to ID.
00308   while (TypeList.size() <= ID)
00309     TypeList.push_back(OpaqueType::get());
00310   return TypeList.back().get();
00311 }
00312 
00313 //===----------------------------------------------------------------------===//
00314 //  Functions for parsing blocks from the bitcode file
00315 //===----------------------------------------------------------------------===//
00316 
00317 bool BitcodeReader::ParseAttributeBlock() {
00318   if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
00319     return Error("Malformed block record");
00320   
00321   if (!MAttributes.empty())
00322     return Error("Multiple PARAMATTR blocks found!");
00323   
00324   SmallVector<uint64_t, 64> Record;
00325   
00326   SmallVector<AttributeWithIndex, 8> Attrs;
00327   
00328   // Read all the records.
00329   while (1) {
00330     unsigned Code = Stream.ReadCode();
00331     if (Code == bitc::END_BLOCK) {
00332       if (Stream.ReadBlockEnd())
00333         return Error("Error at end of PARAMATTR block");
00334       return false;
00335     }
00336     
00337     if (Code == bitc::ENTER_SUBBLOCK) {
00338       // No known subblocks, always skip them.
00339       Stream.ReadSubBlockID();
00340       if (Stream.SkipBlock())
00341         return Error("Malformed block record");
00342       continue;
00343     }
00344     
00345     if (Code == bitc::DEFINE_ABBREV) {
00346       Stream.ReadAbbrevRecord();
00347       continue;
00348     }
00349     
00350     // Read a record.
00351     Record.clear();
00352     switch (Stream.ReadRecord(Code, Record)) {
00353     default:  // Default behavior: ignore.
00354       break;
00355     case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
00356       if (Record.size() & 1)
00357         return Error("Invalid ENTRY record");
00358 
00359       // FIXME : Remove this autoupgrade code in LLVM 3.0.
00360       // If Function attributes are using index 0 then transfer them
00361       // to index ~0. Index 0 is used for return value attributes but used to be
00362       // used for function attributes.
00363       Attributes RetAttribute = Attribute::None;
00364       Attributes FnAttribute = Attribute::None;
00365       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
00366         // FIXME: remove in LLVM 3.0
00367         // The alignment is stored as a 16-bit raw value from bits 31--16.
00368         // We shift the bits above 31 down by 11 bits.
00369 
00370         unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
00371         if (Alignment && !isPowerOf2_32(Alignment))
00372           return Error("Alignment is not a power of two.");
00373 
00374         Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
00375         if (Alignment)
00376           ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
00377         ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
00378         Record[i+1] = ReconstitutedAttr;
00379 
00380         if (Record[i] == 0)
00381           RetAttribute = Record[i+1];
00382         else if (Record[i] == ~0U)
00383           FnAttribute = Record[i+1];
00384       }
00385 
00386       unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
00387                               Attribute::ReadOnly|Attribute::ReadNone);
00388       
00389       if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
00390           (RetAttribute & OldRetAttrs) != 0) {
00391         if (FnAttribute == Attribute::None) { // add a slot so they get added.
00392           Record.push_back(~0U);
00393           Record.push_back(0);
00394         }
00395         
00396         FnAttribute  |= RetAttribute & OldRetAttrs;
00397         RetAttribute &= ~OldRetAttrs;
00398       }
00399 
00400       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
00401         if (Record[i] == 0) {
00402           if (RetAttribute != Attribute::None)
00403             Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
00404         } else if (Record[i] == ~0U) {
00405           if (FnAttribute != Attribute::None)
00406             Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
00407         } else if (Record[i+1] != Attribute::None)
00408           Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
00409       }
00410 
00411       MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
00412       Attrs.clear();
00413       break;
00414     }
00415     }
00416   }
00417 }
00418 
00419 
00420 bool BitcodeReader::ParseTypeTable() {
00421   if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
00422     return Error("Malformed block record");
00423   
00424   if (!TypeList.empty())
00425     return Error("Multiple TYPE_BLOCKs found!");
00426 
00427   SmallVector<uint64_t, 64> Record;
00428   unsigned NumRecords = 0;
00429 
00430   // Read all the records for this type table.
00431   while (1) {
00432     unsigned Code = Stream.ReadCode();
00433     if (Code == bitc::END_BLOCK) {
00434       if (NumRecords != TypeList.size())
00435         return Error("Invalid type forward reference in TYPE_BLOCK");
00436       if (Stream.ReadBlockEnd())
00437         return Error("Error at end of type table block");
00438       return false;
00439     }
00440     
00441     if (Code == bitc::ENTER_SUBBLOCK) {
00442       // No known subblocks, always skip them.
00443       Stream.ReadSubBlockID();
00444       if (Stream.SkipBlock())
00445         return Error("Malformed block record");
00446       continue;
00447     }
00448     
00449     if (Code == bitc::DEFINE_ABBREV) {
00450       Stream.ReadAbbrevRecord();
00451       continue;
00452     }
00453     
00454     // Read a record.
00455     Record.clear();
00456     const Type *ResultTy = 0;
00457     switch (Stream.ReadRecord(Code, Record)) {
00458     default:  // Default behavior: unknown type.
00459       ResultTy = 0;
00460       break;
00461     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
00462       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
00463       // type list.  This allows us to reserve space.
00464       if (Record.size() < 1)
00465         return Error("Invalid TYPE_CODE_NUMENTRY record");
00466       TypeList.reserve(Record[0]);
00467       continue;
00468     case bitc::TYPE_CODE_VOID:      // VOID
00469       ResultTy = Type::VoidTy;
00470       break;
00471     case bitc::TYPE_CODE_FLOAT:     // FLOAT
00472       ResultTy = Type::FloatTy;
00473       break;
00474     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
00475       ResultTy = Type::DoubleTy;
00476       break;
00477     case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
00478       ResultTy = Type::X86_FP80Ty;
00479       break;
00480     case bitc::TYPE_CODE_FP128:     // FP128
00481       ResultTy = Type::FP128Ty;
00482       break;
00483     case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
00484       ResultTy = Type::PPC_FP128Ty;
00485       break;
00486     case bitc::TYPE_CODE_LABEL:     // LABEL
00487       ResultTy = Type::LabelTy;
00488       break;
00489     case bitc::TYPE_CODE_OPAQUE:    // OPAQUE
00490       ResultTy = 0;
00491       break;
00492     case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
00493       if (Record.size() < 1)
00494         return Error("Invalid Integer type record");
00495       
00496       ResultTy = IntegerType::get(Record[0]);
00497       break;
00498     case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or 
00499                                     //          [pointee type, address space]
00500       if (Record.size() < 1)
00501         return Error("Invalid POINTER type record");
00502       unsigned AddressSpace = 0;
00503       if (Record.size() == 2)
00504         AddressSpace = Record[1];
00505       ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
00506       break;
00507     }
00508     case bitc::TYPE_CODE_FUNCTION: {
00509       // FIXME: attrid is dead, remove it in LLVM 3.0
00510       // FUNCTION: [vararg, attrid, retty, paramty x N]
00511       if (Record.size() < 3)
00512         return Error("Invalid FUNCTION type record");
00513       std::vector<const Type*> ArgTys;
00514       for (unsigned i = 3, e = Record.size(); i != e; ++i)
00515         ArgTys.push_back(getTypeByID(Record[i], true));
00516       
00517       ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
00518                                    Record[0]);
00519       break;
00520     }
00521     case bitc::TYPE_CODE_STRUCT: {  // STRUCT: [ispacked, eltty x N]
00522       if (Record.size() < 1)
00523         return Error("Invalid STRUCT type record");
00524       std::vector<const Type*> EltTys;
00525       for (unsigned i = 1, e = Record.size(); i != e; ++i)
00526         EltTys.push_back(getTypeByID(Record[i], true));
00527       ResultTy = StructType::get(EltTys, Record[0]);
00528       break;
00529     }
00530     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
00531       if (Record.size() < 2)
00532         return Error("Invalid ARRAY type record");
00533       ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
00534       break;
00535     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
00536       if (Record.size() < 2)
00537         return Error("Invalid VECTOR type record");
00538       ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
00539       break;
00540     }
00541     
00542     if (NumRecords == TypeList.size()) {
00543       // If this is a new type slot, just append it.
00544       TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
00545       ++NumRecords;
00546     } else if (ResultTy == 0) {
00547       // Otherwise, this was forward referenced, so an opaque type was created,
00548       // but the result type is actually just an opaque.  Leave the one we
00549       // created previously.
00550       ++NumRecords;
00551     } else {
00552       // Otherwise, this was forward referenced, so an opaque type was created.
00553       // Resolve the opaque type to the real type now.
00554       assert(NumRecords < TypeList.size() && "Typelist imbalance");
00555       const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
00556      
00557       // Don't directly push the new type on the Tab. Instead we want to replace
00558       // the opaque type we previously inserted with the new concrete value. The
00559       // refinement from the abstract (opaque) type to the new type causes all
00560       // uses of the abstract type to use the concrete type (NewTy). This will
00561       // also cause the opaque type to be deleted.
00562       const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
00563       
00564       // This should have replaced the old opaque type with the new type in the
00565       // value table... or with a preexisting type that was already in the
00566       // system.  Let's just make sure it did.
00567       assert(TypeList[NumRecords-1].get() != OldTy &&
00568              "refineAbstractType didn't work!");
00569     }
00570   }
00571 }
00572 
00573 
00574 bool BitcodeReader::ParseTypeSymbolTable() {
00575   if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
00576     return Error("Malformed block record");
00577   
00578   SmallVector<uint64_t, 64> Record;
00579   
00580   // Read all the records for this type table.
00581   std::string TypeName;
00582   while (1) {
00583     unsigned Code = Stream.ReadCode();
00584     if (Code == bitc::END_BLOCK) {
00585       if (Stream.ReadBlockEnd())
00586         return Error("Error at end of type symbol table block");
00587       return false;
00588     }
00589     
00590     if (Code == bitc::ENTER_SUBBLOCK) {
00591       // No known subblocks, always skip them.
00592       Stream.ReadSubBlockID();
00593       if (Stream.SkipBlock())
00594         return Error("Malformed block record");
00595       continue;
00596     }
00597     
00598     if (Code == bitc::DEFINE_ABBREV) {
00599       Stream.ReadAbbrevRecord();
00600       continue;
00601     }
00602     
00603     // Read a record.
00604     Record.clear();
00605     switch (Stream.ReadRecord(Code, Record)) {
00606     default:  // Default behavior: unknown type.
00607       break;
00608     case bitc::TST_CODE_ENTRY:    // TST_ENTRY: [typeid, namechar x N]
00609       if (ConvertToString(Record, 1, TypeName))
00610         return Error("Invalid TST_ENTRY record");
00611       unsigned TypeID = Record[0];
00612       if (TypeID >= TypeList.size())
00613         return Error("Invalid Type ID in TST_ENTRY record");
00614 
00615       TheModule->addTypeName(TypeName, TypeList[TypeID].get());
00616       TypeName.clear();
00617       break;
00618     }
00619   }
00620 }
00621 
00622 bool BitcodeReader::ParseValueSymbolTable() {
00623   if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
00624     return Error("Malformed block record");
00625 
00626   SmallVector<uint64_t, 64> Record;
00627   
00628   // Read all the records for this value table.
00629   SmallString<128> ValueName;
00630   while (1) {
00631     unsigned Code = Stream.ReadCode();
00632     if (Code == bitc::END_BLOCK) {
00633       if (Stream.ReadBlockEnd())
00634         return Error("Error at end of value symbol table block");
00635       return false;
00636     }    
00637     if (Code == bitc::ENTER_SUBBLOCK) {
00638       // No known subblocks, always skip them.
00639       Stream.ReadSubBlockID();
00640       if (Stream.SkipBlock())
00641         return Error("Malformed block record");
00642       continue;
00643     }
00644     
00645     if (Code == bitc::DEFINE_ABBREV) {
00646       Stream.ReadAbbrevRecord();
00647       continue;
00648     }
00649     
00650     // Read a record.
00651     Record.clear();
00652     switch (Stream.ReadRecord(Code, Record)) {
00653     default:  // Default behavior: unknown type.
00654       break;
00655     case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
00656       if (ConvertToString(Record, 1, ValueName))
00657         return Error("Invalid TST_ENTRY record");
00658       unsigned ValueID = Record[0];
00659       if (ValueID >= ValueList.size())
00660         return Error("Invalid Value ID in VST_ENTRY record");
00661       Value *V = ValueList[ValueID];
00662       
00663       V->setName(&ValueName[0], ValueName.size());
00664       ValueName.clear();
00665       break;
00666     }
00667     case bitc::VST_CODE_BBENTRY: {
00668       if (ConvertToString(Record, 1, ValueName))
00669         return Error("Invalid VST_BBENTRY record");
00670       BasicBlock *BB = getBasicBlock(Record[0]);
00671       if (BB == 0)
00672         return Error("Invalid BB ID in VST_BBENTRY record");
00673       
00674       BB->setName(&ValueName[0], ValueName.size());
00675       ValueName.clear();
00676       break;
00677     }
00678     }
00679   }
00680 }
00681 
00682 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
00683 /// the LSB for dense VBR encoding.
00684 static uint64_t DecodeSignRotatedValue(uint64_t V) {
00685   if ((V & 1) == 0)
00686     return V >> 1;
00687   if (V != 1) 
00688     return -(V >> 1);
00689   // There is no such thing as -0 with integers.  "-0" really means MININT.
00690   return 1ULL << 63;
00691 }
00692 
00693 /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
00694 /// values and aliases that we can.
00695 bool BitcodeReader::ResolveGlobalAndAliasInits() {
00696   std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
00697   std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
00698   
00699   GlobalInitWorklist.swap(GlobalInits);
00700   AliasInitWorklist.swap(AliasInits);
00701 
00702   while (!GlobalInitWorklist.empty()) {
00703     unsigned ValID = GlobalInitWorklist.back().second;
00704     if (ValID >= ValueList.size()) {
00705       // Not ready to resolve this yet, it requires something later in the file.
00706       GlobalInits.push_back(GlobalInitWorklist.back());
00707     } else {
00708       if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
00709         GlobalInitWorklist.back().first->setInitializer(C);
00710       else
00711         return Error("Global variable initializer is not a constant!");
00712     }
00713     GlobalInitWorklist.pop_back(); 
00714   }
00715 
00716   while (!AliasInitWorklist.empty()) {
00717     unsigned ValID = AliasInitWorklist.back().second;
00718     if (ValID >= ValueList.size()) {
00719       AliasInits.push_back(AliasInitWorklist.back());
00720     } else {
00721       if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
00722         AliasInitWorklist.back().first->setAliasee(C);
00723       else
00724         return Error("Alias initializer is not a constant!");
00725     }
00726     AliasInitWorklist.pop_back(); 
00727   }
00728   return false;
00729 }
00730 
00731 
00732 bool BitcodeReader::ParseConstants() {
00733   if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
00734     return Error("Malformed block record");
00735 
00736   SmallVector<uint64_t, 64> Record;
00737   
00738   // Read all the records for this value table.
00739   const Type *CurTy = Type::Int32Ty;
00740   unsigned NextCstNo = ValueList.size();
00741   while (1) {
00742     unsigned Code = Stream.ReadCode();
00743     if (Code == bitc::END_BLOCK)
00744       break;
00745     
00746     if (Code == bitc::ENTER_SUBBLOCK) {
00747       // No known subblocks, always skip them.
00748       Stream.ReadSubBlockID();
00749       if (Stream.SkipBlock())
00750         return Error("Malformed block record");
00751       continue;
00752     }
00753     
00754     if (Code == bitc::DEFINE_ABBREV) {
00755       Stream.ReadAbbrevRecord();
00756       continue;
00757     }
00758     
00759     // Read a record.
00760     Record.clear();
00761     Value *V = 0;
00762     switch (Stream.ReadRecord(Code, Record)) {
00763     default:  // Default behavior: unknown constant
00764     case bitc::CST_CODE_UNDEF:     // UNDEF
00765       V = UndefValue::get(CurTy);
00766       break;
00767     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
00768       if (Record.empty())
00769         return Error("Malformed CST_SETTYPE record");
00770       if (Record[0] >= TypeList.size())
00771         return Error("Invalid Type ID in CST_SETTYPE record");
00772       CurTy = TypeList[Record[0]];
00773       continue;  // Skip the ValueList manipulation.
00774     case bitc::CST_CODE_NULL:      // NULL
00775       V = Constant::getNullValue(CurTy);
00776       break;
00777     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
00778       if (!isa<IntegerType>(CurTy) || Record.empty())
00779         return Error("Invalid CST_INTEGER record");
00780       V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
00781       break;
00782     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
00783       if (!isa<IntegerType>(CurTy) || Record.empty())
00784         return Error("Invalid WIDE_INTEGER record");
00785       
00786       unsigned NumWords = Record.size();
00787       SmallVector<uint64_t, 8> Words;
00788       Words.resize(NumWords);
00789       for (unsigned i = 0; i != NumWords; ++i)
00790         Words[i] = DecodeSignRotatedValue(Record[i]);
00791       V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
00792                                  NumWords, &Words[0]));
00793       break;
00794     }
00795     case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
00796       if (Record.empty())
00797         return Error("Invalid FLOAT record");
00798       if (CurTy == Type::FloatTy)
00799         V = ConstantFP::get(APFloat(APInt(32, (uint32_t)Record[0])));
00800       else if (CurTy == Type::DoubleTy)
00801         V = ConstantFP::get(APFloat(APInt(64, Record[0])));
00802       else if (CurTy == Type::X86_FP80Ty)
00803         V = ConstantFP::get(APFloat(APInt(80, 2, &Record[0])));
00804       else if (CurTy == Type::FP128Ty)
00805         V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0]), true));
00806       else if (CurTy == Type::PPC_FP128Ty)
00807         V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0])));
00808       else
00809         V = UndefValue::get(CurTy);
00810       break;
00811     }
00812       
00813     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
00814       if (Record.empty())
00815         return Error("Invalid CST_AGGREGATE record");
00816       
00817       unsigned Size = Record.size();
00818       std::vector<Constant*> Elts;
00819       
00820       if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
00821         for (unsigned i = 0; i != Size; ++i)
00822           Elts.push_back(ValueList.getConstantFwdRef(Record[i],
00823                                                      STy->getElementType(i)));
00824         V = ConstantStruct::get(STy, Elts);
00825       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
00826         const Type *EltTy = ATy->getElementType();
00827         for (unsigned i = 0; i != Size; ++i)
00828           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
00829         V = ConstantArray::get(ATy, Elts);
00830       } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
00831         const Type *EltTy = VTy->getElementType();
00832         for (unsigned i = 0; i != Size; ++i)
00833           Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
00834         V = ConstantVector::get(Elts);
00835       } else {
00836         V = UndefValue::get(CurTy);
00837       }
00838       break;
00839     }
00840     case bitc::CST_CODE_STRING: { // STRING: [values]
00841       if (Record.empty())
00842         return Error("Invalid CST_AGGREGATE record");
00843 
00844       const ArrayType *ATy = cast<ArrayType>(CurTy);
00845       const Type *EltTy = ATy->getElementType();
00846       
00847       unsigned Size = Record.size();
00848       std::vector<Constant*> Elts;
00849       for (unsigned i = 0; i != Size; ++i)
00850         Elts.push_back(ConstantInt::get(EltTy, Record[i]));
00851       V = ConstantArray::get(ATy, Elts);
00852       break;
00853     }
00854     case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
00855       if (Record.empty())
00856         return Error("Invalid CST_AGGREGATE record");
00857       
00858       const ArrayType *ATy = cast<ArrayType>(CurTy);
00859       const Type *EltTy = ATy->getElementType();
00860       
00861       unsigned Size = Record.size();
00862       std::vector<Constant*> Elts;
00863       for (unsigned i = 0; i != Size; ++i)
00864         Elts.push_back(ConstantInt::get(EltTy, Record[i]));
00865       Elts.push_back(Constant::getNullValue(EltTy));
00866       V = ConstantArray::get(ATy, Elts);
00867       break;
00868     }
00869     case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
00870       if (Record.size() < 3) return Error("Invalid CE_BINOP record");
00871       int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
00872       if (Opc < 0) {
00873         V = UndefValue::get(CurTy);  // Unknown binop.
00874       } else {
00875         Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
00876         Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
00877         V = ConstantExpr::get(Opc, LHS, RHS);
00878       }
00879       break;
00880     }  
00881     case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
00882       if (Record.size() < 3) return Error("Invalid CE_CAST record");
00883       int Opc = GetDecodedCastOpcode(Record[0]);
00884       if (Opc < 0) {
00885         V = UndefValue::get(CurTy);  // Unknown cast.
00886       } else {
00887         const Type *OpTy = getTypeByID(Record[1]);
00888         if (!OpTy) return Error("Invalid CE_CAST record");
00889         Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
00890         V = ConstantExpr::getCast(Opc, Op, CurTy);
00891       }
00892       break;
00893     }  
00894     case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
00895       if (Record.size() & 1) return Error("Invalid CE_GEP record");
00896       SmallVector<Constant*, 16> Elts;
00897       for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
00898         const Type *ElTy = getTypeByID(Record[i]);
00899         if (!ElTy) return Error("Invalid CE_GEP record");
00900         Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
00901       }
00902       V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
00903       break;
00904     }
00905     case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
00906       if (Record.size() < 3) return Error("Invalid CE_SELECT record");
00907       V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
00908                                                               Type::Int1Ty),
00909                                   ValueList.getConstantFwdRef(Record[1],CurTy),
00910                                   ValueList.getConstantFwdRef(Record[2],CurTy));
00911       break;
00912     case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
00913       if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
00914       const VectorType *OpTy = 
00915         dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
00916       if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
00917       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
00918       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
00919       V = ConstantExpr::getExtractElement(Op0, Op1);
00920       break;
00921     }
00922     case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
00923       const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
00924       if (Record.size() < 3 || OpTy == 0)
00925         return Error("Invalid CE_INSERTELT record");
00926       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
00927       Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
00928                                                   OpTy->getElementType());
00929       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
00930       V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
00931       break;
00932     }
00933     case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
00934       const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
00935       if (Record.size() < 3 || OpTy == 0)
00936         return Error("Invalid CE_INSERTELT record");
00937       Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
00938       Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
00939       const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
00940       Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
00941       V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
00942       break;
00943     }
00944     case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
00945       if (Record.size() < 4) return Error("Invalid CE_CMP record");
00946       const Type *OpTy = getTypeByID(Record[0]);
00947       if (OpTy == 0) return Error("Invalid CE_CMP record");
00948       Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
00949       Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
00950 
00951       if (OpTy->isFloatingPoint())
00952         V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
00953       else if (!isa<VectorType>(OpTy))
00954         V = ConstantExpr::getICmp(Record[3], Op0, Op1);
00955       else if (OpTy->isFPOrFPVector())
00956         V = ConstantExpr::getVFCmp(Record[3], Op0, Op1);
00957       else
00958         V = ConstantExpr::getVICmp(Record[3], Op0, Op1);
00959       break;
00960     }
00961     case bitc::CST_CODE_INLINEASM: {
00962       if (Record.size() < 2) return Error("Invalid INLINEASM record");
00963       std::string AsmStr, ConstrStr;
00964       bool HasSideEffects = Record[0];
00965       unsigned AsmStrSize = Record[1];
00966       if (2+AsmStrSize >= Record.size())
00967         return Error("Invalid INLINEASM record");
00968       unsigned ConstStrSize = Record[2+AsmStrSize];
00969       if (3+AsmStrSize+ConstStrSize > Record.size())
00970         return Error("Invalid INLINEASM record");
00971       
00972       for (unsigned i = 0; i != AsmStrSize; ++i)
00973         AsmStr += (char)Record[2+i];
00974       for (unsigned i = 0; i != ConstStrSize; ++i)
00975         ConstrStr += (char)Record[3+AsmStrSize+i];
00976       const PointerType *PTy = cast<PointerType>(CurTy);
00977       V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
00978                          AsmStr, ConstrStr, HasSideEffects);
00979       break;
00980     }
00981     }
00982     
00983     ValueList.AssignValue(V, NextCstNo);
00984     ++NextCstNo;
00985   }
00986   
00987   if (NextCstNo != ValueList.size())
00988     return Error("Invalid constant reference!");
00989   
00990   if (Stream.ReadBlockEnd())
00991     return Error("Error at end of constants block");
00992   
00993   // Once all the constants have been read, go through and resolve forward
00994   // references.
00995   ValueList.ResolveConstantForwardRefs();
00996   return false;
00997 }
00998 
00999 /// RememberAndSkipFunctionBody - When we see the block for a function body,
01000 /// remember where it is and then skip it.  This lets us lazily deserialize the
01001 /// functions.
01002 bool BitcodeReader::RememberAndSkipFunctionBody() {
01003   // Get the function we are talking about.
01004   if (FunctionsWithBodies.empty())
01005     return Error("Insufficient function protos");
01006   
01007   Function *Fn = FunctionsWithBodies.back();
01008   FunctionsWithBodies.pop_back();
01009   
01010   // Save the current stream state.
01011   uint64_t CurBit = Stream.GetCurrentBitNo();
01012   DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
01013   
01014   // Set the functions linkage to GhostLinkage so we know it is lazily
01015   // deserialized.
01016   Fn->setLinkage(GlobalValue::GhostLinkage);
01017   
01018   // Skip over the function block for now.
01019   if (Stream.SkipBlock())
01020     return Error("Malformed block record");
01021   return false;
01022 }
01023 
01024 bool BitcodeReader::ParseModule(const std::string &ModuleID) {
01025   // Reject multiple MODULE_BLOCK's in a single bitstream.
01026   if (TheModule)
01027     return Error("Multiple MODULE_BLOCKs in same stream");
01028   
01029   if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
01030     return Error("Malformed block record");
01031 
01032   // Otherwise, create the module.
01033   TheModule = new Module(ModuleID);
01034   
01035   SmallVector<uint64_t, 64> Record;
01036   std::vector<std::string> SectionTable;
01037   std::vector<std::string> GCTable;
01038 
01039   // Read all the records for this module.
01040   while (!Stream.AtEndOfStream()) {
01041     unsigned Code = Stream.ReadCode();
01042     if (Code == bitc::END_BLOCK) {
01043       if (Stream.ReadBlockEnd())
01044         return Error("Error at end of module block");
01045 
01046       // Patch the initializers for globals and aliases up.
01047       ResolveGlobalAndAliasInits();
01048       if (!GlobalInits.empty() || !AliasInits.empty())
01049         return Error("Malformed global initializer set");
01050       if (!FunctionsWithBodies.empty())
01051         return Error("Too few function bodies found");
01052 
01053       // Look for intrinsic functions which need to be upgraded at some point
01054       for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
01055            FI != FE; ++FI) {
01056         Function* NewFn;
01057         if (UpgradeIntrinsicFunction(FI, NewFn))
01058           UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
01059       }
01060 
01061       // Force deallocation of memory for these vectors to favor the client that
01062       // want lazy deserialization.
01063       std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
01064       std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
01065       std::vector<Function*>().swap(FunctionsWithBodies);
01066       return false;
01067     }
01068     
01069     if (Code == bitc::ENTER_SUBBLOCK) {
01070       switch (Stream.ReadSubBlockID()) {
01071       default:  // Skip unknown content.
01072         if (Stream.SkipBlock())
01073           return Error("Malformed block record");
01074         break;
01075       case bitc::BLOCKINFO_BLOCK_ID:
01076         if (Stream.ReadBlockInfoBlock())
01077           return Error("Malformed BlockInfoBlock");
01078         break;
01079       case bitc::PARAMATTR_BLOCK_ID:
01080         if (ParseAttributeBlock())
01081           return true;
01082         break;
01083       case bitc::TYPE_BLOCK_ID:
01084         if (ParseTypeTable())
01085           return true;
01086         break;
01087       case bitc::TYPE_SYMTAB_BLOCK_ID:
01088         if (ParseTypeSymbolTable())
01089           return true;
01090         break;
01091       case bitc::VALUE_SYMTAB_BLOCK_ID:
01092         if (ParseValueSymbolTable())
01093           return true;
01094         break;
01095       case bitc::CONSTANTS_BLOCK_ID:
01096         if (ParseConstants() || ResolveGlobalAndAliasInits())
01097           return true;
01098         break;
01099       case bitc::FUNCTION_BLOCK_ID:
01100         // If this is the first function body we've seen, reverse the
01101         // FunctionsWithBodies list.
01102         if (!HasReversedFunctionsWithBodies) {
01103           std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
01104           HasReversedFunctionsWithBodies = true;
01105         }
01106         
01107         if (RememberAndSkipFunctionBody())
01108           return true;
01109         break;
01110       }
01111       continue;
01112     }
01113     
01114     if (Code == bitc::DEFINE_ABBREV) {
01115       Stream.ReadAbbrevRecord();
01116       continue;
01117     }
01118     
01119     // Read a record.
01120     switch (Stream.ReadRecord(Code, Record)) {
01121     default: break;  // Default behavior, ignore unknown content.
01122     case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
01123       if (Record.size() < 1)
01124         return Error("Malformed MODULE_CODE_VERSION");
01125       // Only version #0 is supported so far.
01126       if (Record[0] != 0)
01127         return Error("Unknown bitstream version!");
01128       break;
01129     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
01130       std::string S;
01131       if (ConvertToString(Record, 0, S))
01132         return Error("Invalid MODULE_CODE_TRIPLE record");
01133       TheModule->setTargetTriple(S);
01134       break;
01135     }
01136     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
01137       std::string S;
01138       if (ConvertToString(Record, 0, S))
01139         return Error("Invalid MODULE_CODE_DATALAYOUT record");
01140       TheModule->setDataLayout(S);
01141       break;
01142     }
01143     case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
01144       std::string S;
01145       if (ConvertToString(Record, 0, S))
01146         return Error("Invalid MODULE_CODE_ASM record");
01147       TheModule->setModuleInlineAsm(S);
01148       break;
01149     }
01150     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
01151       std::string S;
01152       if (ConvertToString(Record, 0, S))
01153         return Error("Invalid MODULE_CODE_DEPLIB record");
01154       TheModule->addLibrary(S);
01155       break;
01156     }
01157     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
01158       std::string S;
01159       if (ConvertToString(Record, 0, S))
01160         return Error("Invalid MODULE_CODE_SECTIONNAME record");
01161       SectionTable.push_back(S);
01162       break;
01163     }
01164     case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
01165       std::string S;
01166       if (ConvertToString(Record, 0, S))
01167         return Error("Invalid MODULE_CODE_GCNAME record");
01168       GCTable.push_back(S);
01169       break;
01170     }
01171     // GLOBALVAR: [pointer type, isconst, initid,
01172     //             linkage, alignment, section, visibility, threadlocal]
01173     case bitc::MODULE_CODE_GLOBALVAR: {
01174       if (Record.size() < 6)
01175         return Error("Invalid MODULE_CODE_GLOBALVAR record");
01176       const Type *Ty = getTypeByID(Record[0]);
01177       if (!isa<PointerType>(Ty))
01178         return Error("Global not a pointer type!");
01179       unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
01180       Ty = cast<PointerType>(Ty)->getElementType();
01181       
01182       bool isConstant = Record[1];
01183       GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
01184       unsigned Alignment = (1 << Record[4]) >> 1;
01185       std::string Section;
01186       if (Record[5]) {
01187         if (Record[5]-1 >= SectionTable.size())
01188           return Error("Invalid section ID");
01189         Section = SectionTable[Record[5]-1];
01190       }
01191       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
01192       if (Record.size() > 6)
01193         Visibility = GetDecodedVisibility(Record[6]);
01194       bool isThreadLocal = false;
01195       if (Record.size() > 7)
01196         isThreadLocal = Record[7];
01197 
01198       GlobalVariable *NewGV =
01199         new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule, 
01200                            isThreadLocal, AddressSpace);
01201       NewGV->setAlignment(Alignment);
01202       if (!Section.empty())
01203         NewGV->setSection(Section);
01204       NewGV->setVisibility(Visibility);
01205       NewGV->setThreadLocal(isThreadLocal);
01206       
01207       ValueList.push_back(NewGV);
01208       
01209       // Remember which value to use for the global initializer.
01210       if (unsigned InitID = Record[2])
01211         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
01212       break;
01213     }
01214     // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
01215     //             alignment, section, visibility, gc]
01216     case bitc::MODULE_CODE_FUNCTION: {
01217       if (Record.size() < 8)
01218         return Error("Invalid MODULE_CODE_FUNCTION record");
01219       const Type *Ty = getTypeByID(Record[0]);
01220       if (!isa<PointerType>(Ty))
01221         return Error("Function not a pointer type!");
01222       const FunctionType *FTy =
01223         dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
01224       if (!FTy)
01225         return Error("Function not a pointer to function type!");
01226 
01227       Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
01228                                         "", TheModule);
01229 
01230       Func->setCallingConv(Record[1]);
01231       bool isProto = Record[2];
01232       Func->setLinkage(GetDecodedLinkage(Record[3]));
01233       Func->setAttributes(getAttributes(Record[4]));
01234       
01235       Func->setAlignment((1 << Record[5]) >> 1);
01236       if (Record[6]) {
01237         if (Record[6]-1 >= SectionTable.size())
01238           return Error("Invalid section ID");
01239         Func->setSection(SectionTable[Record[6]-1]);
01240       }
01241       Func->setVisibility(GetDecodedVisibility(Record[7]));
01242       if (Record.size() > 8 && Record[8]) {
01243         if (Record[8]-1 > GCTable.size())
01244           return Error("Invalid GC ID");
01245         Func->setGC(GCTable[Record[8]-1].c_str());
01246       }
01247       ValueList.push_back(Func);
01248       
01249       // If this is a function with a body, remember the prototype we are
01250       // creating now, so that we can match up the body with them later.
01251       if (!isProto)
01252         FunctionsWithBodies.push_back(Func);
01253       break;
01254     }
01255     // ALIAS: [alias type, aliasee val#, linkage]
01256     // ALIAS: [alias type, aliasee val#, linkage, visibility]
01257     case bitc::MODULE_CODE_ALIAS: {
01258       if (Record.size() < 3)
01259         return Error("Invalid MODULE_ALIAS record");
01260       const Type *Ty = getTypeByID(Record[0]);
01261       if (!isa<PointerType>(Ty))
01262         return Error("Function not a pointer type!");
01263       
01264       GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
01265                                            "", 0, TheModule);
01266       // Old bitcode files didn't have visibility field.
01267       if (Record.size() > 3)
01268         NewGA->setVisibility(GetDecodedVisibility(Record[3]));
01269       ValueList.push_back(NewGA);
01270       AliasInits.push_back(std::make_pair(NewGA, Record[1]));
01271       break;
01272     }
01273     /// MODULE_CODE_PURGEVALS: [numvals]
01274     case bitc::MODULE_CODE_PURGEVALS:
01275       // Trim down the value list to the specified size.
01276       if (Record.size() < 1 || Record[0] > ValueList.size())
01277         return Error("Invalid MODULE_PURGEVALS record");
01278       ValueList.shrinkTo(Record[0]);
01279       break;
01280     }
01281     Record.clear();
01282   }
01283   
01284   return Error("Premature end of bitstream");
01285 }
01286 
01287 /// SkipWrapperHeader - Some systems wrap bc files with a special header for
01288 /// padding or other reasons.  The format of this header is:
01289 ///
01290 /// struct bc_header {
01291 ///   uint32_t Magic;         // 0x0B17C0DE
01292 ///   uint32_t Version;       // Version, currently always 0.
01293 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
01294 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
01295 ///   ... potentially other gunk ...
01296 /// };
01297 /// 
01298 /// This function is called when we find a file with a matching magic number.
01299 /// In this case, skip down to the subsection of the file that is actually a BC
01300 /// file.
01301 static bool SkipWrapperHeader(unsigned char *&BufPtr, unsigned char *&BufEnd) {
01302   enum {
01303     KnownHeaderSize = 4*4,  // Size of header we read.
01304     OffsetField = 2*4,      // Offset in bytes to Offset field.
01305     SizeField = 3*4         // Offset in bytes to Size field.
01306   };
01307   
01308   
01309   // Must contain the header!
01310   if (BufEnd-BufPtr < KnownHeaderSize) return true;
01311   
01312   unsigned Offset = ( BufPtr[OffsetField  ]        |
01313                      (BufPtr[OffsetField+1] << 8)  |
01314                      (BufPtr[OffsetField+2] << 16) |
01315                      (BufPtr[OffsetField+3] << 24));
01316   unsigned Size   = ( BufPtr[SizeField    ]        |
01317                      (BufPtr[SizeField  +1] << 8)  |
01318                      (BufPtr[SizeField  +2] << 16) |
01319                      (BufPtr[SizeField  +3] << 24));
01320   
01321   // Verify that Offset+Size fits in the file.
01322   if (Offset+Size > unsigned(BufEnd-BufPtr))
01323     return true;
01324   BufPtr += Offset;
01325   BufEnd = BufPtr+Size;
01326   return false;
01327 }
01328 
01329 bool BitcodeReader::ParseBitcode() {
01330   TheModule = 0;
01331   
01332   if (Buffer->getBufferSize() & 3)
01333     return Error("Bitcode stream should be a multiple of 4 bytes in length");
01334   
01335   unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
01336   unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
01337   
01338   // If we have a wrapper header, parse it and ignore the non-bc file contents.
01339   // The magic number is 0x0B17C0DE stored in little endian.
01340   if (BufPtr != BufEnd && BufPtr[0] == 0xDE && BufPtr[1] == 0xC0 && 
01341       BufPtr[2] == 0x17 && BufPtr[3] == 0x0B)
01342     if (SkipWrapperHeader(BufPtr, BufEnd))
01343       return Error("Invalid bitcode wrapper header");
01344   
01345   Stream.init(BufPtr, BufEnd);
01346   
01347   // Sniff for the signature.
01348   if (Stream.Read(8) != 'B' ||
01349       Stream.Read(8) != 'C' ||
01350       Stream.Read(4) != 0x0 ||
01351       Stream.Read(4) != 0xC ||
01352       Stream.Read(4) != 0xE ||
01353       Stream.Read(4) != 0xD)
01354     return Error("Invalid bitcode signature");
01355   
01356   // We expect a number of well-defined blocks, though we don't necessarily
01357   // need to understand them all.
01358   while (!Stream.AtEndOfStream()) {
01359     unsigned Code = Stream.ReadCode();
01360     
01361     if (Code != bitc::ENTER_SUBBLOCK)
01362       return Error("Invalid record at top-level");
01363     
01364     unsigned BlockID = Stream.ReadSubBlockID();
01365     
01366     // We only know the MODULE subblock ID.
01367     switch (BlockID) {
01368     case bitc::BLOCKINFO_BLOCK_ID:
01369       if (Stream.ReadBlockInfoBlock())
01370         return Error("Malformed BlockInfoBlock");
01371       break;
01372     case bitc::MODULE_BLOCK_ID:
01373       if (ParseModule(Buffer->getBufferIdentifier()))
01374         return true;
01375       break;
01376     default:
01377       if (Stream.SkipBlock())
01378         return Error("Malformed block record");
01379       break;
01380     }
01381   }
01382   
01383   return false;
01384 }
01385 
01386 
01387 /// ParseFunctionBody - Lazily parse the specified function body block.
01388 bool BitcodeReader::ParseFunctionBody(Function *F) {
01389   if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
01390     return Error("Malformed block record");
01391   
01392   unsigned ModuleValueListSize = ValueList.size();
01393   
01394   // Add all the function arguments to the value table.
01395   for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
01396     ValueList.push_back(I);
01397   
01398   unsigned NextValueNo = ValueList.size();
01399   BasicBlock *CurBB = 0;
01400   unsigned CurBBNo = 0;
01401 
01402   // Read all the records.
01403   SmallVector<uint64_t, 64> Record;
01404   while (1) {
01405     unsigned Code = Stream.ReadCode();
01406     if (Code == bitc::END_BLOCK) {
01407       if (Stream.ReadBlockEnd())
01408         return Error("Error at end of function block");
01409       break;
01410     }
01411     
01412     if (Code == bitc::ENTER_SUBBLOCK) {
01413       switch (Stream.ReadSubBlockID()) {
01414       default:  // Skip unknown content.
01415         if (Stream.SkipBlock())
01416           return Error("Malformed block record");
01417         break;
01418       case bitc::CONSTANTS_BLOCK_ID:
01419         if (ParseConstants()) return true;
01420         NextValueNo = ValueList.size();
01421         break;
01422       case bitc::VALUE_SYMTAB_BLOCK_ID:
01423         if (ParseValueSymbolTable()) return true;
01424         break;
01425       }
01426       continue;
01427     }
01428     
01429     if (Code == bitc::DEFINE_ABBREV) {
01430       Stream.ReadAbbrevRecord();
01431       continue;
01432     }
01433     
01434     // Read a record.
01435     Record.clear();
01436     Instruction *I = 0;
01437     switch (Stream.ReadRecord(Code, Record)) {
01438     default: // Default behavior: reject
01439       return Error("Unknown instruction");
01440     case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
01441       if (Record.size() < 1 || Record[0] == 0)
01442         return Error("Invalid DECLAREBLOCKS record");
01443       // Create all the basic blocks for the function.
01444       FunctionBBs.resize(Record[0]);
01445       for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
01446         FunctionBBs[i] = BasicBlock::Create("", F);
01447       CurBB = FunctionBBs[0];
01448       continue;
01449       
01450     case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
01451       unsigned OpNum = 0;
01452       Value *LHS, *RHS;
01453       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
01454           getValue(Record, OpNum, LHS->getType(), RHS) ||
01455           OpNum+1 != Record.size())
01456         return Error("Invalid BINOP record");
01457       
01458       int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
01459       if (Opc == -1) return Error("Invalid BINOP record");
01460       I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
01461       break;
01462     }
01463     case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
01464       unsigned OpNum = 0;
01465       Value *Op;
01466       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
01467           OpNum+2 != Record.size())
01468         return Error("Invalid CAST record");
01469       
01470       const Type *ResTy = getTypeByID(Record[OpNum]);
01471       int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
01472       if (Opc == -1 || ResTy == 0)
01473         return Error("Invalid CAST record");
01474       I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
01475       break;
01476     }
01477     case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
01478       unsigned OpNum = 0;
01479       Value *BasePtr;
01480       if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
01481         return Error("Invalid GEP record");
01482 
01483       SmallVector<Value*, 16> GEPIdx;
01484       while (OpNum != Record.size()) {
01485         Value *Op;
01486         if (getValueTypePair(Record, OpNum, NextValueNo, Op))
01487           return Error("Invalid GEP record");
01488         GEPIdx.push_back(Op);
01489       }
01490 
01491       I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
01492       break;
01493     }
01494       
01495     case bitc::FUNC_CODE_INST_EXTRACTVAL: {
01496                                        // EXTRACTVAL: [opty, opval, n x indices]
01497       unsigned OpNum = 0;
01498       Value *Agg;
01499       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
01500         return Error("Invalid EXTRACTVAL record");
01501 
01502       SmallVector<unsigned, 4> EXTRACTVALIdx;
01503       for (unsigned RecSize = Record.size();
01504            OpNum != RecSize; ++OpNum) {
01505         uint64_t Index = Record[OpNum];
01506         if ((unsigned)Index != Index)
01507           return Error("Invalid EXTRACTVAL index");
01508         EXTRACTVALIdx.push_back((unsigned)Index);
01509       }
01510 
01511       I = ExtractValueInst::Create(Agg,
01512                                    EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
01513       break;
01514     }
01515       
01516     case bitc::FUNC_CODE_INST_INSERTVAL: {
01517                            // INSERTVAL: [opty, opval, opty, opval, n x indices]
01518       unsigned OpNum = 0;
01519       Value *Agg;
01520       if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
01521         return Error("Invalid INSERTVAL record");
01522       Value *Val;
01523       if (getValueTypePair(Record, OpNum, NextValueNo, Val))
01524         return Error("Invalid INSERTVAL record");
01525 
01526       SmallVector<unsigned, 4> INSERTVALIdx;
01527       for (unsigned RecSize = Record.size();
01528            OpNum != RecSize; ++OpNum) {
01529         uint64_t Index = Record[OpNum];
01530         if ((unsigned)Index != Index)
01531           return Error("Invalid INSERTVAL index");
01532         INSERTVALIdx.push_back((unsigned)Index);
01533       }
01534 
01535       I = InsertValueInst::Create(Agg, Val,
01536                                   INSERTVALIdx.begin(), INSERTVALIdx.end());
01537       break;
01538     }
01539       
01540     case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
01541       // obsolete form of select
01542       // handles select i1 ... in old bitcode
01543       unsigned OpNum = 0;
01544       Value *TrueVal, *FalseVal, *Cond;
01545       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
01546           getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
01547           getValue(Record, OpNum, Type::Int1Ty, Cond))
01548         return Error("Invalid SELECT record");
01549       
01550       I = SelectInst::Create(Cond, TrueVal, FalseVal);
01551       break;
01552     }
01553       
01554     case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
01555       // new form of select
01556       // handles select i1 or select [N x i1]
01557       unsigned OpNum = 0;
01558       Value *TrueVal, *FalseVal, *Cond;
01559       if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
01560           getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
01561           getValueTypePair(Record, OpNum, NextValueNo, Cond))
01562         return Error("Invalid SELECT record");
01563 
01564       // select condition can be either i1 or [N x i1]
01565       if (const VectorType* vector_type =
01566           dyn_cast<const VectorType>(Cond->getType())) {
01567         // expect <n x i1>
01568         if (vector_type->getElementType() != Type::Int1Ty) 
01569           return Error("Invalid SELECT condition type");
01570       } else {
01571         // expect i1
01572         if (Cond->getType() != Type::Int1Ty) 
01573           return Error("Invalid SELECT condition type");
01574       } 
01575       
01576       I = SelectInst::Create(Cond, TrueVal, FalseVal);
01577       break;
01578     }
01579       
01580     case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
01581       unsigned OpNum = 0;
01582       Value *Vec, *Idx;
01583       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
01584           getValue(Record, OpNum, Type::Int32Ty, Idx))
01585         return Error("Invalid EXTRACTELT record");
01586       I = new ExtractElementInst(Vec, Idx);
01587       break;
01588     }
01589       
01590     case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
01591       unsigned OpNum = 0;
01592       Value *Vec, *Elt, *Idx;
01593       if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
01594           getValue(Record, OpNum, 
01595                    cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
01596           getValue(Record, OpNum, Type::Int32Ty, Idx))
01597         return Error("Invalid INSERTELT record");
01598       I = InsertElementInst::Create(Vec, Elt, Idx);
01599       break;
01600     }
01601       
01602     case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
01603       unsigned OpNum = 0;
01604       Value *Vec1, *Vec2, *Mask;
01605       if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
01606           getValue(Record, OpNum, Vec1->getType(), Vec2))
01607         return Error("Invalid SHUFFLEVEC record");
01608 
01609       if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
01610         return Error("Invalid SHUFFLEVEC record");
01611       I = new ShuffleVectorInst(Vec1, Vec2, Mask);
01612       break;
01613     }
01614 
01615     case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
01616       // VFCmp/VICmp
01617       // or old form of ICmp/FCmp returning bool
01618       unsigned OpNum = 0;
01619       Value *LHS, *RHS;
01620       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
01621           getValue(Record, OpNum, LHS->getType(), RHS) ||
01622           OpNum+1 != Record.size())
01623         return Error("Invalid CMP record");
01624       
01625       if (LHS->getType()->isFloatingPoint())
01626         I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
01627       else if (!isa<VectorType>(LHS->getType()))
01628         I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
01629       else if (LHS->getType()->isFPOrFPVector())
01630         I = new VFCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
01631       else
01632         I = new VICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
01633       break;
01634     }
01635     case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
01636       // Fcmp/ICmp returning bool or vector of bool
01637       unsigned OpNum = 0;
01638       Value *LHS, *RHS;
01639       if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
01640           getValue(Record, OpNum, LHS->getType(), RHS) ||
01641           OpNum+1 != Record.size())
01642         return Error("Invalid CMP2 record");
01643       
01644       if (LHS->getType()->isFPOrFPVector())
01645         I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
01646       else 
01647         I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
01648       break;
01649     }
01650     case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
01651       if (Record.size() != 2)
01652         return Error("Invalid GETRESULT record");
01653       unsigned OpNum = 0;
01654       Value *Op;
01655       getValueTypePair(Record, OpNum, NextValueNo, Op);
01656       unsigned Index = Record[1];
01657       I = ExtractValueInst::Create(Op, Index);
01658       break;
01659     }
01660     
01661     case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
01662       {
01663         unsigned Size = Record.size();
01664         if (Size == 0) {
01665           I = ReturnInst::Create();
01666           break;
01667         }
01668 
01669         unsigned OpNum = 0;
01670         SmallVector<Value *,4> Vs;
01671         do {
01672           Value *Op = NULL;
01673           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
01674             return Error("Invalid RET record");
01675           Vs.push_back(Op);
01676         } while(OpNum != Record.size());
01677 
01678         const Type *ReturnType = F->getReturnType();
01679         if (Vs.size() > 1 ||
01680             (isa<StructType>(ReturnType) &&
01681              (Vs.empty() || Vs[0]->getType() != ReturnType))) {
01682           Value *RV = UndefValue::get(ReturnType);
01683           for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
01684             I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
01685             CurBB->getInstList().push_back(I);
01686             ValueList.AssignValue(I, NextValueNo++);
01687             RV = I;
01688           }
01689           I = ReturnInst::Create(RV);
01690           break;
01691         }
01692 
01693         I = ReturnInst::Create(Vs[0]);
01694         break;
01695       }
01696     case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
01697       if (Record.size() != 1 && Record.size() != 3)
01698         return Error("Invalid BR record");
01699       BasicBlock *TrueDest = getBasicBlock(Record[0]);
01700       if (TrueDest == 0)
01701         return Error("Invalid BR record");
01702 
01703       if (Record.size() == 1)
01704         I = BranchInst::Create(TrueDest);
01705       else {
01706         BasicBlock *FalseDest = getBasicBlock(Record[1]);
01707         Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
01708         if (FalseDest == 0 || Cond == 0)
01709           return Error("Invalid BR record");
01710         I = BranchInst::Create(TrueDest, FalseDest, Cond);
01711       }
01712       break;
01713     }
01714     case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
01715       if (Record.size() < 3 || (Record.size() & 1) == 0)
01716         return Error("Invalid SWITCH record");
01717       const Type *OpTy = getTypeByID(Record[0]);
01718       Value *Cond = getFnValueByID(Record[1], OpTy);
01719       BasicBlock *Default = getBasicBlock(Record[2]);
01720       if (OpTy == 0 || Cond == 0 || Default == 0)
01721         return Error("Invalid SWITCH record");
01722       unsigned NumCases = (Record.size()-3)/2;
01723       SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
01724       for (unsigned i = 0, e = NumCases; i != e; ++i) {
01725         ConstantInt *CaseVal = 
01726           dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
01727         BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
01728         if (CaseVal == 0 || DestBB == 0) {
01729           delete SI;
01730           return Error("Invalid SWITCH record!");
01731         }
01732         SI->addCase(CaseVal, DestBB);
01733       }
01734       I = SI;
01735       break;
01736     }
01737       
01738     case bitc::FUNC_CODE_INST_INVOKE: {
01739       // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
01740       if (Record.size() < 4) return Error("Invalid INVOKE record");
01741       AttrListPtr PAL = getAttributes(Record[0]);
01742       unsigned CCInfo = Record[1];
01743       BasicBlock *NormalBB = getBasicBlock(Record[2]);
01744       BasicBlock *UnwindBB = getBasicBlock(Record[3]);
01745       
01746       unsigned OpNum = 4;
01747       Value *Callee;
01748       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
01749         return Error("Invalid INVOKE record");
01750       
01751       const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
01752       const FunctionType *FTy = !CalleeTy ? 0 :
01753         dyn_cast<FunctionType>(CalleeTy->getElementType());
01754 
01755       // Check that the right number of fixed parameters are here.
01756       if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
01757           Record.size() < OpNum+FTy->getNumParams())
01758         return Error("Invalid INVOKE record");
01759       
01760       SmallVector<Value*, 16> Ops;
01761       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
01762         Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
01763         if (Ops.back() == 0) return Error("Invalid INVOKE record");
01764       }
01765       
01766       if (!FTy->isVarArg()) {
01767         if (Record.size() != OpNum)
01768           return Error("Invalid INVOKE record");
01769       } else {
01770         // Read type/value pairs for varargs params.
01771         while (OpNum != Record.size()) {
01772           Value *Op;
01773           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
01774             return Error("Invalid INVOKE record");
01775           Ops.push_back(Op);
01776         }
01777       }
01778       
01779       I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
01780                              Ops.begin(), Ops.end());
01781       cast<InvokeInst>(I)->setCallingConv(CCInfo);
01782       cast<InvokeInst>(I)->setAttributes(PAL);
01783       break;
01784     }
01785     case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
01786       I = new UnwindInst();
01787       break;
01788     case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
01789       I = new UnreachableInst();
01790       break;
01791     case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
01792       if (Record.size() < 1 || ((Record.size()-1)&1))
01793         return Error("Invalid PHI record");
01794       const Type *Ty = getTypeByID(Record[0]);
01795       if (!Ty) return Error("Invalid PHI record");
01796       
01797       PHINode *PN = PHINode::Create(Ty);
01798       PN->reserveOperandSpace((Record.size()-1)/2);
01799       
01800       for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
01801         Value *V = getFnValueByID(Record[1+i], Ty);
01802         BasicBlock *BB = getBasicBlock(Record[2+i]);
01803         if (!V || !BB) return Error("Invalid PHI record");
01804         PN->addIncoming(V, BB);
01805       }
01806       I = PN;
01807       break;
01808     }
01809       
01810     case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
01811       if (Record.size() < 3)
01812         return Error("Invalid MALLOC record");
01813       const PointerType *Ty =
01814         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
01815       Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
01816       unsigned Align = Record[2];
01817       if (!Ty || !Size) return Error("Invalid MALLOC record");
01818       I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
01819       break;
01820     }
01821     case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
01822       unsigned OpNum = 0;
01823       Value *Op;
01824       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
01825           OpNum != Record.size())
01826         return Error("Invalid FREE record");
01827       I = new FreeInst(Op);
01828       break;
01829     }
01830     case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
01831       if (Record.size() < 3)
01832         return Error("Invalid ALLOCA record");
01833       const PointerType *Ty =
01834         dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
01835       Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
01836       unsigned Align = Record[2];
01837       if (!Ty || !Size) return Error("Invalid ALLOCA record");
01838       I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
01839       break;
01840     }
01841     case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
01842       unsigned OpNum = 0;
01843       Value *Op;
01844       if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
01845           OpNum+2 != Record.size())
01846         return Error("Invalid LOAD record");
01847       
01848       I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
01849       break;
01850     }
01851     case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
01852       unsigned OpNum = 0;
01853       Value *Val, *Ptr;
01854       if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
01855           getValue(Record, OpNum, 
01856                     cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
01857           OpNum+2 != Record.size())
01858         return Error("Invalid STORE record");
01859       
01860       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
01861       break;
01862     }
01863     case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
01864       // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
01865       unsigned OpNum = 0;
01866       Value *Val, *Ptr;
01867       if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
01868           getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
01869           OpNum+2 != Record.size())
01870         return Error("Invalid STORE record");
01871       
01872       I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
01873       break;
01874     }
01875     case bitc::FUNC_CODE_INST_CALL: {
01876       // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
01877       if (Record.size() < 3)
01878         return Error("Invalid CALL record");
01879       
01880       AttrListPtr PAL = getAttributes(Record[0]);
01881       unsigned CCInfo = Record[1];
01882       
01883       unsigned OpNum = 2;
01884       Value *Callee;
01885       if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
01886         return Error("Invalid CALL record");
01887       
01888       const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
01889       const FunctionType *FTy = 0;
01890       if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
01891       if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
01892         return Error("Invalid CALL record");
01893       
01894       SmallVector<Value*, 16> Args;
01895       // Read the fixed params.
01896       for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
01897         if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
01898           Args.push_back(getBasicBlock(Record[OpNum]));
01899         else
01900           Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
01901         if (Args.back() == 0) return Error("Invalid CALL record");
01902       }
01903       
01904       // Read type/value pairs for varargs params.
01905       if (!FTy->isVarArg()) {
01906         if (OpNum != Record.size())
01907           return Error("Invalid CALL record");
01908       } else {
01909         while (OpNum != Record.size()) {
01910           Value *Op;
01911           if (getValueTypePair(Record, OpNum, NextValueNo, Op))
01912             return Error("Invalid CALL record");
01913           Args.push_back(Op);
01914         }
01915       }
01916       
01917       I = CallInst::Create(Callee, Args.begin(), Args.end());
01918       cast<CallInst>(I)->setCallingConv(CCInfo>>1);
01919       cast<CallInst>(I)->setTailCall(CCInfo & 1);
01920       cast<CallInst>(I)->setAttributes(PAL);
01921       break;
01922     }
01923     case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
01924       if (Record.size() < 3)
01925         return Error("Invalid VAARG record");
01926       const Type *OpTy = getTypeByID(Record[0]);
01927       Value *Op = getFnValueByID(Record[1], OpTy);
01928       const Type *ResTy = getTypeByID(Record[2]);
01929       if (!OpTy || !Op || !ResTy)
01930         return Error("Invalid VAARG record");
01931       I = new VAArgInst(Op, ResTy);
01932       break;
01933     }
01934     }
01935 
01936     // Add instruction to end of current BB.  If there is no current BB, reject
01937     // this file.
01938     if (CurBB == 0) {
01939       delete I;
01940       return Error("Invalid instruction with no BB");
01941     }
01942     CurBB->getInstList().push_back(I);
01943     
01944     // If this was a terminator instruction, move to the next block.
01945     if (isa<TerminatorInst>(I)) {
01946       ++CurBBNo;
01947       CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
01948     }
01949     
01950     // Non-void values get registered in the value table for future use.
01951     if (I && I->getType() != Type::VoidTy)
01952       ValueList.AssignValue(I, NextValueNo++);
01953   }
01954   
01955   // Check the function list for unresolved values.
01956   if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
01957     if (A->getParent() == 0) {
01958       // We found at least one unresolved value.  Nuke them all to avoid leaks.
01959       for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
01960         if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
01961           A->replaceAllUsesWith(UndefValue::get(A->getType()));
01962           delete A;
01963         }
01964       }
01965       return Error("Never resolved value found in function!");
01966     }
01967   }
01968   
01969   // Trim the value list down to the size it was before we parsed this function.
01970   ValueList.shrinkTo(ModuleValueListSize);
01971   std::vector<BasicBlock*>().swap(FunctionBBs);
01972   
01973   return false;
01974 }
01975 
01976 //===----------------------------------------------------------------------===//
01977 // ModuleProvider implementation
01978 //===----------------------------------------------------------------------===//
01979 
01980 
01981 bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
01982   // If it already is material, ignore the request.
01983   if (!F->hasNotBeenReadFromBitcode()) return false;
01984   
01985   DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII = 
01986     DeferredFunctionInfo.find(F);
01987   assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
01988   
01989   // Move the bit stream to the saved position of the deferred function body and
01990   // restore the real linkage type for the function.
01991   Stream.JumpToBit(DFII->second.first);
01992   F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
01993   
01994   if (ParseFunctionBody(F)) {
01995     if (ErrInfo) *ErrInfo = ErrorString;
01996     return true;
01997   }
01998 
01999   // Upgrade any old intrinsic calls in the function.
02000   for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
02001        E = UpgradedIntrinsics.end(); I != E; ++I) {
02002     if (I->first != I->second) {
02003       for (Value::use_iterator UI = I->first->use_begin(),
02004            UE = I->first->use_end(); UI != UE; ) {
02005         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
02006           UpgradeIntrinsicCall(CI, I->second);
02007       }
02008     }
02009   }
02010   
02011   return false;
02012 }
02013 
02014 void BitcodeReader::dematerializeFunction(Function *F) {
02015   // If this function isn't materialized, or if it is a proto, this is a noop.
02016   if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
02017     return;
02018   
02019   assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
02020   
02021   // Just forget the function body, we can remat it later.
02022   F->deleteBody();
02023   F->setLinkage(GlobalValue::GhostLinkage);
02024 }
02025 
02026 
02027 Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
02028   for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I = 
02029        DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
02030        ++I) {
02031     Function *F = I->first;
02032     if (F->hasNotBeenReadFromBitcode() &&
02033         materializeFunction(F, ErrInfo))
02034       return 0;
02035   }
02036 
02037   // Upgrade any intrinsic calls that slipped through (should not happen!) and 
02038   // delete the old functions to clean up. We can't do this unless the entire 
02039   // module is materialized because there could always be another function body 
02040   // with calls to the old function.
02041   for (std::vector<std::pair<Function*, Function*> >::iterator I =
02042        UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
02043     if (I->first != I->second) {
02044       for (Value::use_iterator UI = I->first->use_begin(),
02045            UE = I->first->use_end(); UI != UE; ) {
02046         if (CallInst* CI = dyn_cast<CallInst>(*UI++))
02047           UpgradeIntrinsicCall(CI, I->second);
02048       }
02049       ValueList.replaceUsesOfWith(I->first, I->second);
02050       I->first->eraseFromParent();
02051     }
02052   }
02053   std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
02054   
02055   return TheModule;
02056 }
02057 
02058 
02059 /// This method is provided by the parent ModuleProvde class and overriden
02060 /// here. It simply releases the module from its provided and frees up our
02061 /// state.
02062 /// @brief Release our hold on the generated module
02063 Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
02064   // Since we're losing control of this Module, we must hand it back complete
02065   Module *M = ModuleProvider::releaseModule(ErrInfo);
02066   FreeState();
02067   return M;
02068 }
02069 
02070 
02071 //===----------------------------------------------------------------------===//
02072 // External interface
02073 //===----------------------------------------------------------------------===//
02074 
02075 /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
02076 ///
02077 ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
02078                                                std::string *ErrMsg) {
02079   BitcodeReader *R = new BitcodeReader(Buffer);
02080   if (R->ParseBitcode()) {
02081     if (ErrMsg)
02082       *ErrMsg = R->getErrorString();
02083     
02084     // Don't let the BitcodeReader dtor delete 'Buffer'.
02085     R->releaseMemoryBuffer();
02086     delete R;
02087     return 0;
02088   }
02089   return R;
02090 }
02091 
02092 /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
02093 /// If an error occurs, return null and fill in *ErrMsg if non-null.
02094 Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
02095   BitcodeReader *R;
02096   R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
02097   if (!R) return 0;
02098   
02099   // Read in the entire module.
02100   Module *M = R->materializeModule(ErrMsg);
02101 
02102   // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
02103   // there was an error.
02104   R->releaseMemoryBuffer();
02105   
02106   // If there was no error, tell ModuleProvider not to delete it when its dtor
02107   // is run.
02108   if (M)
02109     M = R->releaseModule(ErrMsg);
02110   
02111   delete R;
02112   return M;
02113 }