Merged in autoconf branch. This provides configuration via the autoconf
[oota-llvm.git] / lib / Bytecode / Reader / Reader.cpp
index c74d09f0c599e887c966b42320017ca0e0813ec2..42ba5d9584c4fd0a793ab0b646f9aa7a1613975b 100644 (file)
 //===----------------------------------------------------------------------===//
 
 #include "ReaderInternals.h"
+#include "Config/sys/mman.h"
 #include "llvm/Bytecode/Reader.h"
 #include "llvm/Bytecode/Format.h"
 #include "llvm/Module.h"
 #include "llvm/Constants.h"
 #include "llvm/iPHINode.h"
 #include "llvm/iOther.h"
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/mman.h>
-#include <fcntl.h>
-#include <unistd.h>
+#include "Config/sys/types.h"
+#include "Config/sys/stat.h"
+#include "Config/fcntl.h"
+#include "Config/unistd.h"
 #include <algorithm>
 
 bool BytecodeParser::getTypeSlot(const Type *Ty, unsigned &Slot) {
   if (Ty->isPrimitiveType()) {
     Slot = Ty->getPrimitiveID();
   } else {
-    // Check the method level types first...
-    TypeValuesListTy::iterator I = find(MethodTypeValues.begin(),
-                                       MethodTypeValues.end(), Ty);
-    if (I != MethodTypeValues.end()) {
+    // Check the function level types first...
+    TypeValuesListTy::iterator I = find(FunctionTypeValues.begin(),
+                                       FunctionTypeValues.end(), Ty);
+    if (I != FunctionTypeValues.end()) {
       Slot = FirstDerivedTyID+ModuleTypeValues.size()+
-             (&*I - &MethodTypeValues[0]);
+             (&*I - &FunctionTypeValues[0]);
     } else {
       I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), Ty);
       if (I == ModuleTypeValues.end()) return true;   // Didn't find type!
@@ -55,19 +55,44 @@ const Type *BytecodeParser::getType(unsigned ID) {
   return cast_or_null<Type>(V);
 }
 
-int BytecodeParser::insertValue(Value *Val, std::vector<ValueList> &ValueTab) {
+int BytecodeParser::insertValue(Value *Val, ValueTable &ValueTab) {
+  assert((!HasImplicitZeroInitializer || !isa<Constant>(Val) ||
+          Val->getType()->isPrimitiveType() ||
+          !cast<Constant>(Val)->isNullValue()) &&
+         "Cannot read null values from bytecode!");
   unsigned type;
   if (getTypeSlot(Val->getType(), type)) return -1;
   assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
  
-  if (ValueTab.size() <= type)
-    ValueTab.resize(type+1, ValueList());
+  if (ValueTab.size() <= type) {
+    unsigned OldSize = ValueTab.size();
+    ValueTab.resize(type+1);
+    while (OldSize != type+1)
+      ValueTab[OldSize++] = new ValueList();
+  }
 
   //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size() 
   //     << "] = " << Val << "\n";
-  ValueTab[type].push_back(Val);
+  ValueTab[type]->push_back(Val);
+
+  bool HasOffset = HasImplicitZeroInitializer &&
+                       !Val->getType()->isPrimitiveType();
+
+  return ValueTab[type]->size()-1 + HasOffset;
+}
+
 
-  return ValueTab[type].size()-1;
+void BytecodeParser::setValueTo(ValueTable &ValueTab, unsigned Slot,
+                                Value *Val) {
+  assert(&ValueTab == &ModuleValues && "Can only setValueTo on Module values!");
+  unsigned type;
+  if (getTypeSlot(Val->getType(), type))
+    assert(0 && "getTypeSlot failed!");
+  
+  assert((!HasImplicitZeroInitializer || Slot != 0) &&
+         "Cannot change zero init");
+  assert(type < ValueTab.size() && Slot <= ValueTab[type]->size());
+  ValueTab[type]->setOperand(Slot-HasImplicitZeroInitializer, Val);
 }
 
 Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
@@ -90,33 +115,33 @@ Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
     if (Num < ModuleTypeValues.size())
       return (Value*)ModuleTypeValues[Num].get();
 
-    // Nope, is it a method level type?
+    // Nope, is it a function level type?
     Num -= ModuleTypeValues.size();
-    if (Num < MethodTypeValues.size())
-      return (Value*)MethodTypeValues[Num].get();
+    if (Num < FunctionTypeValues.size())
+      return (Value*)FunctionTypeValues[Num].get();
 
     return 0;
   }
 
+  if (HasImplicitZeroInitializer && type >= FirstDerivedTyID) {
+    if (Num == 0)
+      return Constant::getNullValue(Ty);
+    --Num;
+  }
+
   if (type < ModuleValues.size()) {
-    if (Num < ModuleValues[type].size())
-      return ModuleValues[type][Num];
-    Num -= ModuleValues[type].size();
+    if (Num < ModuleValues[type]->size())
+      return ModuleValues[type]->getOperand(Num);
+    Num -= ModuleValues[type]->size();
   }
 
-  if (Values.size() > type && Values[type].size() > Num)
-    return Values[type][Num];
+  if (Values.size() > type && Values[type]->size() > Num)
+    return Values[type]->getOperand(Num);
 
   if (!Create) return 0;  // Do not create a placeholder?
 
   Value *d = 0;
   switch (Ty->getPrimitiveID()) {
-  case Type::FunctionTyID:
-    std::cerr << "Creating method pholder! : " << type << ":" << oNum << " " 
-              << Ty->getName() << "\n";
-    d = new FunctionPHolder(Ty, oNum);
-    if (insertValue(d, LateResolveModuleValues) == -1) return 0;
-    return d;
   case Type::LabelTyID:
     d = new BBPHolder(Ty, oNum);
     break;
@@ -140,8 +165,10 @@ Constant *BytecodeParser::getConstantValue(const Type *Ty, unsigned Slot) {
   if (Value *V = getValue(Ty, Slot, false))
     return dyn_cast<Constant>(V);      // If we already have the value parsed...
 
-  GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(Ty, Slot));
-  if (I != GlobalRefs.end()) {
+  std::pair<const Type*, unsigned> Key(Ty, Slot);
+  GlobalRefsType::iterator I = GlobalRefs.lower_bound(Key);
+
+  if (I != GlobalRefs.end() && I->first == Key) {
     BCR_TRACE(5, "Previous forward ref found!\n");
     return cast<Constant>(I->second);
   } else {
@@ -151,29 +178,28 @@ Constant *BytecodeParser::getConstantValue(const Type *Ty, unsigned Slot) {
     Constant *C = new ConstPHolder(Ty, Slot);
     
     // Keep track of the fact that we have a forward ref to recycle it
-    GlobalRefs.insert(std::make_pair(std::make_pair(Ty, Slot), C));
+    GlobalRefs.insert(I, std::make_pair(Key, C));
     return C;
   }
 }
 
 
-
 bool BytecodeParser::postResolveValues(ValueTable &ValTab) {
   bool Error = false;
-  for (unsigned ty = 0; ty < ValTab.size(); ++ty) {
-    ValueList &DL = ValTab[ty];
-    unsigned Size;
-    while ((Size = DL.size())) {
-      unsigned IDNumber = getValueIDNumberFromPlaceHolder(DL[Size-1]);
+  while (!ValTab.empty()) {
+    ValueList &DL = *ValTab.back();
+    ValTab.pop_back();    
 
-      Value *D = DL[Size-1];
+    while (!DL.empty()) {
+      Value *D = DL.back();
+      unsigned IDNumber = getValueIDNumberFromPlaceHolder(D);
       DL.pop_back();
 
       Value *NewDef = getValue(D->getType(), IDNumber, false);
       if (NewDef == 0) {
        Error = true;  // Unresolved thinger
        std::cerr << "Unresolvable reference found: <"
-                  << D->getType()->getDescription() << ">:" << IDNumber <<"!\n";
+                  << *D->getType() << ">:" << IDNumber <<"!\n";
       } else {
        // Fixup all of the uses of this placeholder def...
         D->replaceAllUsesWith(NewDef);
@@ -183,19 +209,20 @@ bool BytecodeParser::postResolveValues(ValueTable &ValTab) {
        delete D;  // memory, 'cause otherwise we can't remove all uses!
       }
     }
+    delete &DL;
   }
 
   return Error;
 }
 
-bool BytecodeParser::ParseBasicBlock(const uchar *&Buf, const uchar *EndBuf, 
+bool BytecodeParser::ParseBasicBlock(const unsigned char *&Buf,
+                                     const unsigned char *EndBuf, 
                                     BasicBlock *&BB) {
   BB = new BasicBlock();
 
   while (Buf < EndBuf) {
     Instruction *Inst;
-    if (ParseInstruction(Buf, EndBuf, Inst,
-                         /*HACK*/BB)) {
+    if (ParseInstruction(Buf, EndBuf, Inst, /*HACK*/BB)) {
       delete BB;
       return true;
     }
@@ -211,7 +238,8 @@ bool BytecodeParser::ParseBasicBlock(const uchar *&Buf, const uchar *EndBuf,
   return false;
 }
 
-bool BytecodeParser::ParseSymbolTable(const uchar *&Buf, const uchar *EndBuf,
+bool BytecodeParser::ParseSymbolTable(const unsigned char *&Buf,
+                                      const unsigned char *EndBuf,
                                      SymbolTable *ST) {
   while (Buf < EndBuf) {
     // Symtab block header: [num entries][type id number]
@@ -232,15 +260,15 @@ bool BytecodeParser::ParseSymbolTable(const uchar *&Buf, const uchar *EndBuf,
       if (read(Buf, EndBuf, Name, false))  // Not aligned...
        return true;
 
-      Value *D = getValue(Ty, slot, false); // Find mapping...
-      if (D == 0) {
+      Value *V = getValue(Ty, slot, false); // Find mapping...
+      if (V == 0) {
        BCR_TRACE(3, "FAILED LOOKUP: Slot #" << slot << "\n");
        return true;
       }
-      BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << D;
-               if (!isa<Instruction>(D)) std::cerr << "\n");
+      BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << *V;
+               if (!isa<Instruction>(V)) std::cerr << "\n");
 
-      D->setName(Name, ST);
+      V->setName(Name, ST);
     }
   }
 
@@ -256,53 +284,52 @@ void BytecodeParser::ResolveReferencesToValue(Value *NewV, unsigned Slot) {
   BCR_TRACE(3, "Mutating forward refs!\n");
   Value *VPH = I->second;   // Get the placeholder...
 
-  // Loop over all of the uses of the Value.  What they are depends
-  // on what NewV is.  Replacing a use of the old reference takes the
-  // use off the use list, so loop with !use_empty(), not the use_iterator.
-  while (!VPH->use_empty()) {
-    Constant *C = cast<Constant>(VPH->use_back());
-    unsigned numReplaced = C->mutateReferences(VPH, NewV);
-    assert(numReplaced > 0 && "Supposed user wasn't really a user?");
-      
-    if (GlobalValue* GVal = dyn_cast<GlobalValue>(NewV)) {
-      // Remove the placeholder GlobalValue from the module...
-      GVal->getParent()->getGlobalList().remove(cast<GlobalVariable>(VPH));
-    }
-  }
+  VPH->replaceAllUsesWith(NewV);
+
+  // If this is a global variable being resolved, remove the placeholder from
+  // the module...
+  if (GlobalValue* GVal = dyn_cast<GlobalValue>(NewV))
+    GVal->getParent()->getGlobalList().remove(cast<GlobalVariable>(VPH));
 
   delete VPH;                         // Delete the old placeholder
   GlobalRefs.erase(I);                // Remove the map entry for it
 }
 
-bool BytecodeParser::ParseMethod(const uchar *&Buf, const uchar *EndBuf, 
-                                Module *C) {
+
+bool BytecodeParser::ParseFunction(const unsigned char *&Buf,
+                                   const unsigned char *EndBuf) {
   // Clear out the local values table...
-  Values.clear();
   if (FunctionSignatureList.empty()) {
     Error = "Function found, but FunctionSignatureList empty!";
-    return true;  // Unexpected method!
+    return true;  // Unexpected function!
   }
 
-  const PointerType *PMTy = FunctionSignatureList.back().first; // PtrMeth
-  const FunctionType *MTy  = dyn_cast<FunctionType>(PMTy->getElementType());
-  if (MTy == 0) return true;  // Not ptr to method!
+  GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
 
-  unsigned isInternal;
-  if (read_vbr(Buf, EndBuf, isInternal)) return true;
+  if (!hasInternalMarkerOnly) {
+    unsigned LinkageType;
+    if (read_vbr(Buf, EndBuf, LinkageType)) return true;
+    if (LinkageType & ~0x3) return true;
+    Linkage = (GlobalValue::LinkageTypes)LinkageType;
+  } else {
+    // We used to only support two linkage models: internal and external
+    unsigned isInternal;
+    if (read_vbr(Buf, EndBuf, isInternal)) return true;
+    if (isInternal) Linkage = GlobalValue::InternalLinkage;
+  }
 
-  unsigned MethSlot = FunctionSignatureList.back().second;
+  Function *F = FunctionSignatureList.back().first;
+  unsigned FunctionSlot = FunctionSignatureList.back().second;
   FunctionSignatureList.pop_back();
-  Function *M = new Function(MTy, isInternal != 0);
-
-  BCR_TRACE(2, "METHOD TYPE: " << MTy << "\n");
+  F->setLinkage(Linkage);
 
-  const FunctionType::ParamTypes &Params = MTy->getParamTypes();
-  Function::aiterator AI = M->abegin();
+  const FunctionType::ParamTypes &Params =F->getFunctionType()->getParamTypes();
+  Function::aiterator AI = F->abegin();
   for (FunctionType::ParamTypes::const_iterator It = Params.begin();
        It != Params.end(); ++It, ++AI) {
     if (insertValue(AI, Values) == -1) {
-      Error = "Error reading method arguments!\n";
-      delete M; return true; 
+      Error = "Error reading function arguments!\n";
+      return true; 
     }
   }
 
@@ -311,34 +338,31 @@ bool BytecodeParser::ParseMethod(const uchar *&Buf, const uchar *EndBuf,
     const unsigned char *OldBuf = Buf;
     if (readBlock(Buf, EndBuf, Type, Size)) {
       Error = "Error reading Function level block!";
-      delete M; return true; 
+      return true; 
     }
 
     switch (Type) {
     case BytecodeFormat::ConstantPool:
       BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
-      if (ParseConstantPool(Buf, Buf+Size, Values, MethodTypeValues)) {
-       delete M; return true;
-      }
+      if (ParseConstantPool(Buf, Buf+Size, Values, FunctionTypeValues))
+       return true;
       break;
 
     case BytecodeFormat::BasicBlock: {
       BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
       BasicBlock *BB;
       if (ParseBasicBlock(Buf, Buf+Size, BB) ||
-         insertValue(BB, Values) == -1) {
-       delete M; return true;                // Parse error... :(
-      }
+         insertValue(BB, Values) == -1)
+       return true;                // Parse error... :(
 
-      M->getBasicBlockList().push_back(BB);
+      F->getBasicBlockList().push_back(BB);
       break;
     }
 
     case BytecodeFormat::SymbolTable:
       BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
-      if (ParseSymbolTable(Buf, Buf+Size, &M->getSymbolTable())) {
-       delete M; return true;
-      }
+      if (ParseSymbolTable(Buf, Buf+Size, &F->getSymbolTable()))
+       return true;
       break;
 
     default:
@@ -351,46 +375,26 @@ bool BytecodeParser::ParseMethod(const uchar *&Buf, const uchar *EndBuf,
 
     if (align32(Buf, EndBuf)) {
       Error = "Error aligning Function level block!";
-      delete M;    // Malformed bc file, read past end of block.
-      return true;
+      return true;   // Malformed bc file, read past end of block.
     }
   }
 
-  if (postResolveValues(LateResolveValues) ||
-      postResolveValues(LateResolveModuleValues)) {
-    Error = "Error resolving method values!";
-    delete M; return true;     // Unresolvable references!
+  if (postResolveValues(LateResolveValues)) {
+    Error = "Error resolving function values!";
+    return true;     // Unresolvable references!
   }
 
-  Value *FunctionPHolder = getValue(PMTy, MethSlot, false);
-  assert(FunctionPHolder && "Something is broken no placeholder found!");
-  assert(isa<Function>(FunctionPHolder) && "Not a function?");
-
-  unsigned type;  // Type slot
-  assert(!getTypeSlot(MTy, type) && "How can meth type not exist?");
-  getTypeSlot(PMTy, type);
-
-  C->getFunctionList().push_back(M);
-
-  // Replace placeholder with the real method pointer...
-  ModuleValues[type][MethSlot] = M;
+  ResolveReferencesToValue(F, FunctionSlot);
 
-  // Clear out method level types...
-  MethodTypeValues.clear();
-
-  // If anyone is using the placeholder make them use the real method instead
-  FunctionPHolder->replaceAllUsesWith(M);
-
-  // We don't need the placeholder anymore!
-  delete FunctionPHolder;
-
-  ResolveReferencesToValue(M, MethSlot);
+  // Clear out function level types...
+  FunctionTypeValues.clear();
 
+  freeTable(Values);
   return false;
 }
 
-bool BytecodeParser::ParseModuleGlobalInfo(const uchar *&Buf, const uchar *End,
-                                          Module *Mod) {
+bool BytecodeParser::ParseModuleGlobalInfo(const unsigned char *&Buf,
+                                           const unsigned char *End){
   if (!FunctionSignatureList.empty()) {
     Error = "Two ModuleGlobalInfo packets found!";
     return true;  // Two ModuleGlobal blocks?
@@ -400,48 +404,47 @@ bool BytecodeParser::ParseModuleGlobalInfo(const uchar *&Buf, const uchar *End,
   unsigned VarType;
   if (read_vbr(Buf, End, VarType)) return true;
   while (VarType != Type::VoidTyID) { // List is terminated by Void
-    // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
-    // bit2 = isInternal, bit3+ = slot#
-    const Type *Ty = getType(VarType >> 3);
+    unsigned SlotNo;
+    GlobalValue::LinkageTypes Linkage;
+
+    if (!hasInternalMarkerOnly) {
+      // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
+      // bit2,3 = Linkage, bit4+ = slot#
+      SlotNo = VarType >> 4;
+      Linkage = (GlobalValue::LinkageTypes)((VarType >> 2) & 3);
+    } else {
+      // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
+      // bit2 = isInternal, bit3+ = slot#
+      SlotNo = VarType >> 3;
+      Linkage = (VarType & 4) ? GlobalValue::InternalLinkage :
+        GlobalValue::ExternalLinkage;
+    }
+
+    const Type *Ty = getType(SlotNo);
     if (!Ty || !isa<PointerType>(Ty)) { 
       Error = "Global not pointer type!  Ty = " + Ty->getDescription();
       return true; 
     }
 
-    const PointerType *PTy = cast<const PointerType>(Ty);
-    const Type *ElTy = PTy->getElementType();
-
-    Constant *Initializer = 0;
-    if (VarType & 2) { // Does it have an initalizer?
-      // Do not improvise... values must have been stored in the constant pool,
-      // which should have been read before now.
-      //
-      unsigned InitSlot;
-      if (read_vbr(Buf, End, InitSlot)) return true;
-      
-      Value *V = getValue(ElTy, InitSlot, false);
-      if (V == 0) return true;
-      Initializer = cast<Constant>(V);
-    }
+    const Type *ElTy = cast<PointerType>(Ty)->getElementType();
 
     // Create the global variable...
-    GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, VarType & 4,
-                                           Initializer);
+    GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Linkage,
+                                            0, "", TheModule);
     int DestSlot = insertValue(GV, ModuleValues);
     if (DestSlot == -1) return true;
-
-    Mod->getGlobalList().push_back(GV);
-
+    BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
     ResolveReferencesToValue(GV, (unsigned)DestSlot);
 
-    BCR_TRACE(2, "Global Variable of type: " << PTy->getDescription() 
-             << " into slot #" << DestSlot << "\n");
-
+    if (VarType & 2) { // Does it have an initalizer?
+      unsigned InitSlot;
+      if (read_vbr(Buf, End, InitSlot)) return true;
+      GlobalInits.push_back(std::make_pair(GV, InitSlot));
+    }
     if (read_vbr(Buf, End, VarType)) return true;
   }
 
-  // Read the method signatures for all of the methods that are coming, and 
-  // create fillers in the Value tables.
+  // Read the function objects for all of the functions that are coming
   unsigned FnSignature;
   if (read_vbr(Buf, End, FnSignature)) return true;
   while (FnSignature != Type::VoidTyID) { // List is terminated by Void
@@ -452,29 +455,26 @@ bool BytecodeParser::ParseModuleGlobalInfo(const uchar *&Buf, const uchar *End,
       return true; 
     }
 
-    // We create methods by passing the underlying FunctionType to create...
+    // We create functions by passing the underlying FunctionType to create...
     Ty = cast<PointerType>(Ty)->getElementType();
 
-    // When the ModuleGlobalInfo section is read, we load the type of each 
-    // method and the 'ModuleValues' slot that it lands in.  We then load a 
-    // placeholder into its slot to reserve it.  When the method is loaded, this
-    // placeholder is replaced.
+    // When the ModuleGlobalInfo section is read, we load the type of each
+    // function and the 'ModuleValues' slot that it lands in.  We then load a
+    // placeholder into its slot to reserve it.  When the function is loaded,
+    // this placeholder is replaced.
 
     // Insert the placeholder...
-    Value *Val = new FunctionPHolder(Ty, 0);
-    if (insertValue(Val, ModuleValues) == -1) return true;
-
-    // Figure out which entry of its typeslot it went into...
-    unsigned TypeSlot;
-    if (getTypeSlot(Val->getType(), TypeSlot)) return true;
+    Function *Func = new Function(cast<FunctionType>(Ty),
+                                  GlobalValue::InternalLinkage, "", TheModule);
+    int DestSlot = insertValue(Func, ModuleValues);
+    if (DestSlot == -1) return true;
+    ResolveReferencesToValue(Func, (unsigned)DestSlot);
 
-    unsigned SlotNo = ModuleValues[TypeSlot].size()-1;
-    
-    // Keep track of this information in a linked list that is emptied as 
-    // methods are loaded...
+    // Keep track of this information in a list that is emptied as functions are
+    // loaded...
     //
-    FunctionSignatureList.push_back(
-           std::make_pair(cast<const PointerType>(Val->getType()), SlotNo));
+    FunctionSignatureList.push_back(std::make_pair(Func, DestSlot));
+
     if (read_vbr(Buf, End, FnSignature)) return true;
     BCR_TRACE(2, "Function of type: " << Ty << "\n");
   }
@@ -492,9 +492,59 @@ bool BytecodeParser::ParseModuleGlobalInfo(const uchar *&Buf, const uchar *End,
   return false;
 }
 
-bool BytecodeParser::ParseModule(const uchar *Buf, const uchar *EndBuf, 
-                                 Module *&Mod) {
+bool BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
+                                      const unsigned char *EndBuf) {
+  unsigned Version;
+  if (read_vbr(Buf, EndBuf, Version)) return true;
+
+  // Unpack version number: low four bits are for flags, top bits = version
+  isBigEndian     = Version & 1;
+  hasLongPointers = Version & 2;
+  RevisionNum     = Version >> 4;
+
+  // Default values for the current bytecode version
+  HasImplicitZeroInitializer = true;
+  hasInternalMarkerOnly = false;
+  FirstDerivedTyID = 14;
+
+  switch (RevisionNum) {
+  case 0:                  // Initial revision
+    // Version #0 didn't have any of the flags stored correctly, and in fact as
+    // only valid with a 14 in the flags values.  Also, it does not support
+    // encoding zero initializers for arrays compactly.
+    //
+    if (Version != 14) return true;  // Unknown revision 0 flags?
+    HasImplicitZeroInitializer = false;
+    isBigEndian = hasLongPointers = true;
+    hasInternalMarkerOnly = true;
+    break;
+  case 1:
+    // Version #1 has two bit fields: isBigEndian and hasLongPointers
+    hasInternalMarkerOnly = true;
+    break;
+  case 2:
+    // Version #2 added information about all 4 linkage types instead of just
+    // having internal and external.
+    break;
+  default:
+    Error = "Unknown bytecode version number!";
+    return true;
+  }
 
+  TheModule->setEndianness(isBigEndian ? Module::BigEndian :
+                                         Module::LittleEndian);
+  TheModule->setPointerSize(hasLongPointers ? Module::Pointer64 : 
+                                              Module::Pointer32);
+
+  BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
+  BCR_TRACE(1, "BigEndian/LongPointers = " << isBigEndian << ","
+               << hasLongPointers << "\n");
+  BCR_TRACE(1, "HasImplicitZeroInit = " << HasImplicitZeroInitializer << "\n");
+  return false;
+}
+
+bool BytecodeParser::ParseModule(const unsigned char *Buf,
+                                 const unsigned char *EndBuf) {
   unsigned Type, Size;
   if (readBlock(Buf, EndBuf, Type, Size)) return true;
   if (Type != BytecodeFormat::Module || Buf+Size != EndBuf) {
@@ -506,44 +556,40 @@ bool BytecodeParser::ParseModule(const uchar *Buf, const uchar *EndBuf,
   FunctionSignatureList.clear();                 // Just in case...
 
   // Read into instance variables...
-  if (read_vbr(Buf, EndBuf, FirstDerivedTyID)) return true;
+  if (ParseVersionInfo(Buf, EndBuf)) return true;
   if (align32(Buf, EndBuf)) return true;
-  BCR_TRACE(1, "FirstDerivedTyID = " << FirstDerivedTyID << "\n");
-
-  TheModule = Mod = new Module();
 
   while (Buf < EndBuf) {
     const unsigned char *OldBuf = Buf;
-    if (readBlock(Buf, EndBuf, Type, Size)) { delete Mod; return true;}
+    if (readBlock(Buf, EndBuf, Type, Size)) return true;
     switch (Type) {
-    case BytecodeFormat::ConstantPool:
-      BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
-      if (ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues)) {
-       delete Mod; return true;
-      }
+    case BytecodeFormat::GlobalTypePlane:
+      BCR_TRACE(1, "BLOCK BytecodeFormat::GlobalTypePlane: {\n");
+      if (ParseGlobalTypes(Buf, Buf+Size)) return true;
       break;
 
     case BytecodeFormat::ModuleGlobalInfo:
       BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
+      if (ParseModuleGlobalInfo(Buf, Buf+Size)) return true;
+      break;
 
-      if (ParseModuleGlobalInfo(Buf, Buf+Size, Mod)) {
-       delete Mod; return true;
-      }
+    case BytecodeFormat::ConstantPool:
+      BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
+      if (ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues))
+       return true;
       break;
 
     case BytecodeFormat::Function: {
       BCR_TRACE(1, "BLOCK BytecodeFormat::Function: {\n");
-      if (ParseMethod(Buf, Buf+Size, Mod)) {
-       delete Mod; return true;              // Error parsing function
-      }
+      if (ParseFunction(Buf, Buf+Size))
+        return true;  // Error parsing function
       break;
     }
 
     case BytecodeFormat::SymbolTable:
       BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
-      if (ParseSymbolTable(Buf, Buf+Size, &Mod->getSymbolTable())) {
-       delete Mod; return true;
-      }
+      if (ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable()))
+        return true;
       break;
 
     default:
@@ -553,10 +599,25 @@ bool BytecodeParser::ParseModule(const uchar *Buf, const uchar *EndBuf,
       break;
     }
     BCR_TRACE(1, "} end block\n");
-    if (align32(Buf, EndBuf)) { delete Mod; return true; }
+    if (align32(Buf, EndBuf)) return true;
   }
 
-  if (!FunctionSignatureList.empty()) {     // Expected more methods!
+  // After the module constant pool has been read, we can safely initialize
+  // global variables...
+  while (!GlobalInits.empty()) {
+    GlobalVariable *GV = GlobalInits.back().first;
+    unsigned Slot = GlobalInits.back().second;
+    GlobalInits.pop_back();
+
+    // Look up the initializer value...
+    if (Value *V = getValue(GV->getType()->getElementType(), Slot, false)) {
+      if (GV->hasInitializer()) return true;
+      GV->setInitializer(cast<Constant>(V));
+    } else
+      return true;
+  }
+
+  if (!FunctionSignatureList.empty()) {     // Expected more functions!
     Error = "Function expected, but bytecode stream at end!";
     return true;
   }
@@ -565,27 +626,46 @@ bool BytecodeParser::ParseModule(const uchar *Buf, const uchar *EndBuf,
   return false;
 }
 
-Module *BytecodeParser::ParseBytecode(const uchar *Buf, const uchar *EndBuf) {
-  LateResolveValues.clear();
+static inline Module *Error(std::string *ErrorStr, const char *Message) {
+  if (ErrorStr) *ErrorStr = Message;
+  return 0;
+}
+
+Module *BytecodeParser::ParseBytecode(const unsigned char *Buf,
+                                      const unsigned char *EndBuf,
+                                      const std::string &ModuleID) {
   unsigned Sig;
   // Read and check signature...
   if (read(Buf, EndBuf, Sig) ||
-      Sig != ('l' | ('l' << 8) | ('v' << 16) | 'm' << 24)) {
-    Error = "Invalid bytecode signature!";
-    return 0;                          // Invalid signature!
+      Sig != ('l' | ('l' << 8) | ('v' << 16) | 'm' << 24))
+    return ::Error(&Error, "Invalid bytecode signature!");
+
+  TheModule = new Module(ModuleID);
+  if (ParseModule(Buf, EndBuf)) {
+    freeState();       // Must destroy handles before deleting module!
+    delete TheModule;
+    TheModule = 0;
   }
-
-  Module *Result;
-  if (ParseModule(Buf, EndBuf, Result)) return 0;
-  return Result;
+  return TheModule;
 }
 
 
 Module *ParseBytecodeBuffer(const unsigned char *Buffer, unsigned Length,
-                            std::string *ErrorStr) {
+                            const std::string &ModuleID, std::string *ErrorStr){
   BytecodeParser Parser;
-  Module *R = Parser.ParseBytecode(Buffer, Buffer+Length);
+  unsigned char *PtrToDelete = 0;
+  if ((intptr_t)Buffer & 3) {         // If the buffer is not 4 byte aligned...
+    // Allocate a new buffer to hold the bytecode...
+    PtrToDelete = new unsigned char[Length+4];
+    unsigned Offset = 4-((intptr_t)PtrToDelete & 3);  // Make sure it's aligned
+    memcpy(PtrToDelete+Offset, Buffer, Length);       // Copy it over
+    Buffer = PtrToDelete+Offset;
+  }
+
+  Module *R = Parser.ParseBytecode(Buffer, Buffer+Length, ModuleID);
   if (ErrorStr) *ErrorStr = Parser.getError();
+
+  delete [] PtrToDelete;   // Delete alignment buffer if neccesary
   return R;
 }
 
@@ -602,11 +682,6 @@ public:
   }
 };
 
-static inline Module *Error(std::string *ErrorStr, const char *Message) {
-  if (ErrorStr) *ErrorStr = Message;
-  return 0;
-}
-
 // Parse and return a class file...
 //
 Module *ParseBytecodeFile(const std::string &Filename, std::string *ErrorStr) {
@@ -630,13 +705,13 @@ Module *ParseBytecodeFile(const std::string &Filename, std::string *ErrorStr) {
       return Error(ErrorStr, "Error mmapping file!");
 
     // Parse the bytecode we mmapped in
-    Result = ParseBytecodeBuffer(Buffer, Length, ErrorStr);
+    Result = ParseBytecodeBuffer(Buffer, Length, Filename, ErrorStr);
 
     // Unmmap the bytecode...
     munmap((char*)Buffer, Length);
   } else {                              // Read from stdin
     int BlockSize;
-    uchar Buffer[4096*4];
+    unsigned char Buffer[4096*4];
     std::vector<unsigned char> FileData;
 
     // Read in all of the data from stdin, we cannot mmap stdin...
@@ -652,15 +727,16 @@ Module *ParseBytecodeFile(const std::string &Filename, std::string *ErrorStr) {
 
 #define ALIGN_PTRS 0
 #if ALIGN_PTRS
-    uchar *Buf = (uchar*)mmap(0, FileData.size(), PROT_READ|PROT_WRITE, 
-                             MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
-    assert((Buf != (uchar*)-1) && "mmap returned error!");
+    unsigned char *Buf =
+      (unsigned char*)mmap(0, FileData.size(), PROT_READ|PROT_WRITE, 
+                           MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
+    assert((Buf != (unsigned char*)-1) && "mmap returned error!");
     memcpy(Buf, &FileData[0], FileData.size());
 #else
     unsigned char *Buf = &FileData[0];
 #endif
 
-    Result = ParseBytecodeBuffer(Buf, FileData.size(), ErrorStr);
+    Result = ParseBytecodeBuffer(Buf, FileData.size(), "<stdin>", ErrorStr);
 
 #if ALIGN_PTRS
     munmap((char*)Buf, FileData.size());   // Free mmap'd data area