Home | History | Annotate | Download | only in BitWriter_3_2
      1 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // Bitcode writer implementation.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "ReaderWriter_3_2.h"
     15 #include "legacy_bitcode.h"
     16 #include "ValueEnumerator.h"
     17 #include "llvm/ADT/Triple.h"
     18 #include "llvm/Bitcode/BitstreamWriter.h"
     19 #include "llvm/Bitcode/LLVMBitCodes.h"
     20 #include "llvm/IR/Constants.h"
     21 #include "llvm/IR/DerivedTypes.h"
     22 #include "llvm/IR/InlineAsm.h"
     23 #include "llvm/IR/Instructions.h"
     24 #include "llvm/IR/Module.h"
     25 #include "llvm/IR/Operator.h"
     26 #include "llvm/IR/ValueSymbolTable.h"
     27 #include "llvm/Support/CommandLine.h"
     28 #include "llvm/Support/ErrorHandling.h"
     29 #include "llvm/Support/MathExtras.h"
     30 #include "llvm/Support/Program.h"
     31 #include "llvm/Support/raw_ostream.h"
     32 #include <cctype>
     33 #include <map>
     34 using namespace llvm;
     35 
     36 static bool EnablePreserveUseListOrdering = false;
     37 
     38 /// These are manifest constants used by the bitcode writer. They do not need to
     39 /// be kept in sync with the reader, but need to be consistent within this file.
     40 enum {
     41   CurVersion = 0,
     42 
     43   // VALUE_SYMTAB_BLOCK abbrev id's.
     44   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
     45   VST_ENTRY_7_ABBREV,
     46   VST_ENTRY_6_ABBREV,
     47   VST_BBENTRY_6_ABBREV,
     48 
     49   // CONSTANTS_BLOCK abbrev id's.
     50   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
     51   CONSTANTS_INTEGER_ABBREV,
     52   CONSTANTS_CE_CAST_Abbrev,
     53   CONSTANTS_NULL_Abbrev,
     54 
     55   // FUNCTION_BLOCK abbrev id's.
     56   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
     57   FUNCTION_INST_BINOP_ABBREV,
     58   FUNCTION_INST_BINOP_FLAGS_ABBREV,
     59   FUNCTION_INST_CAST_ABBREV,
     60   FUNCTION_INST_RET_VOID_ABBREV,
     61   FUNCTION_INST_RET_VAL_ABBREV,
     62   FUNCTION_INST_UNREACHABLE_ABBREV,
     63 
     64   // SwitchInst Magic
     65   SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
     66 };
     67 
     68 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
     69   switch (Opcode) {
     70   default: llvm_unreachable("Unknown cast instruction!");
     71   case Instruction::Trunc   : return bitc::CAST_TRUNC;
     72   case Instruction::ZExt    : return bitc::CAST_ZEXT;
     73   case Instruction::SExt    : return bitc::CAST_SEXT;
     74   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
     75   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
     76   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
     77   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
     78   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
     79   case Instruction::FPExt   : return bitc::CAST_FPEXT;
     80   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
     81   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
     82   case Instruction::BitCast : return bitc::CAST_BITCAST;
     83   }
     84 }
     85 
     86 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
     87   switch (Opcode) {
     88   default: llvm_unreachable("Unknown binary instruction!");
     89   case Instruction::Add:
     90   case Instruction::FAdd: return bitc::BINOP_ADD;
     91   case Instruction::Sub:
     92   case Instruction::FSub: return bitc::BINOP_SUB;
     93   case Instruction::Mul:
     94   case Instruction::FMul: return bitc::BINOP_MUL;
     95   case Instruction::UDiv: return bitc::BINOP_UDIV;
     96   case Instruction::FDiv:
     97   case Instruction::SDiv: return bitc::BINOP_SDIV;
     98   case Instruction::URem: return bitc::BINOP_UREM;
     99   case Instruction::FRem:
    100   case Instruction::SRem: return bitc::BINOP_SREM;
    101   case Instruction::Shl:  return bitc::BINOP_SHL;
    102   case Instruction::LShr: return bitc::BINOP_LSHR;
    103   case Instruction::AShr: return bitc::BINOP_ASHR;
    104   case Instruction::And:  return bitc::BINOP_AND;
    105   case Instruction::Or:   return bitc::BINOP_OR;
    106   case Instruction::Xor:  return bitc::BINOP_XOR;
    107   }
    108 }
    109 
    110 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
    111   switch (Op) {
    112   default: llvm_unreachable("Unknown RMW operation!");
    113   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
    114   case AtomicRMWInst::Add: return bitc::RMW_ADD;
    115   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
    116   case AtomicRMWInst::And: return bitc::RMW_AND;
    117   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
    118   case AtomicRMWInst::Or: return bitc::RMW_OR;
    119   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
    120   case AtomicRMWInst::Max: return bitc::RMW_MAX;
    121   case AtomicRMWInst::Min: return bitc::RMW_MIN;
    122   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
    123   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
    124   }
    125 }
    126 
    127 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
    128   switch (Ordering) {
    129   case NotAtomic: return bitc::ORDERING_NOTATOMIC;
    130   case Unordered: return bitc::ORDERING_UNORDERED;
    131   case Monotonic: return bitc::ORDERING_MONOTONIC;
    132   case Acquire: return bitc::ORDERING_ACQUIRE;
    133   case Release: return bitc::ORDERING_RELEASE;
    134   case AcquireRelease: return bitc::ORDERING_ACQREL;
    135   case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
    136   }
    137   llvm_unreachable("Invalid ordering");
    138 }
    139 
    140 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
    141   switch (SynchScope) {
    142   case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
    143   case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
    144   }
    145   llvm_unreachable("Invalid synch scope");
    146 }
    147 
    148 static void WriteStringRecord(unsigned Code, StringRef Str,
    149                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
    150   SmallVector<unsigned, 64> Vals;
    151 
    152   // Code: [strchar x N]
    153   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
    154     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
    155       AbbrevToUse = 0;
    156     Vals.push_back(Str[i]);
    157   }
    158 
    159   // Emit the finished record.
    160   Stream.EmitRecord(Code, Vals, AbbrevToUse);
    161 }
    162 
    163 // Emit information about parameter attributes.
    164 static void WriteAttributeTable(const llvm_3_2::ValueEnumerator &VE,
    165                                 BitstreamWriter &Stream) {
    166   const std::vector<AttributeSet> &Attrs = VE.getAttributes();
    167   if (Attrs.empty()) return;
    168 
    169   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
    170 
    171   SmallVector<uint64_t, 64> Record;
    172   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
    173     const AttributeSet &A = Attrs[i];
    174     for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
    175       Record.push_back(A.getSlotIndex(i));
    176       Record.push_back(encodeLLVMAttributesForBitcode(A, A.getSlotIndex(i)));
    177     }
    178 
    179     // This needs to use the 3.2 entry type
    180     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY_OLD, Record);
    181     Record.clear();
    182   }
    183 
    184   Stream.ExitBlock();
    185 }
    186 
    187 /// WriteTypeTable - Write out the type table for a module.
    188 static void WriteTypeTable(const llvm_3_2::ValueEnumerator &VE,
    189                            BitstreamWriter &Stream) {
    190   const llvm_3_2::ValueEnumerator::TypeList &TypeList = VE.getTypes();
    191 
    192   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
    193   SmallVector<uint64_t, 64> TypeVals;
    194 
    195   uint64_t NumBits = Log2_32_Ceil(VE.getTypes().size()+1);
    196 
    197   // Abbrev for TYPE_CODE_POINTER.
    198   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
    199   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
    200   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
    201   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
    202   unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
    203 
    204   // Abbrev for TYPE_CODE_FUNCTION.
    205   Abbv = new BitCodeAbbrev();
    206   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
    207   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
    208   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    209   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
    210 
    211   unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
    212 
    213   // Abbrev for TYPE_CODE_STRUCT_ANON.
    214   Abbv = new BitCodeAbbrev();
    215   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
    216   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
    217   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    218   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
    219 
    220   unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
    221 
    222   // Abbrev for TYPE_CODE_STRUCT_NAME.
    223   Abbv = new BitCodeAbbrev();
    224   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
    225   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    226   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
    227   unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
    228 
    229   // Abbrev for TYPE_CODE_STRUCT_NAMED.
    230   Abbv = new BitCodeAbbrev();
    231   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
    232   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
    233   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    234   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
    235 
    236   unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
    237 
    238   // Abbrev for TYPE_CODE_ARRAY.
    239   Abbv = new BitCodeAbbrev();
    240   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
    241   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
    242   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
    243 
    244   unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
    245 
    246   // Emit an entry count so the reader can reserve space.
    247   TypeVals.push_back(TypeList.size());
    248   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
    249   TypeVals.clear();
    250 
    251   // Loop over all of the types, emitting each in turn.
    252   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
    253     Type *T = TypeList[i];
    254     int AbbrevToUse = 0;
    255     unsigned Code = 0;
    256 
    257     switch (T->getTypeID()) {
    258     default: llvm_unreachable("Unknown type!");
    259     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;      break;
    260     case Type::HalfTyID:      Code = bitc::TYPE_CODE_HALF;      break;
    261     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;     break;
    262     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE;    break;
    263     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80;  break;
    264     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128;     break;
    265     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
    266     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;     break;
    267     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA;  break;
    268     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX;   break;
    269     case Type::IntegerTyID:
    270       // INTEGER: [width]
    271       Code = bitc::TYPE_CODE_INTEGER;
    272       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
    273       break;
    274     case Type::PointerTyID: {
    275       PointerType *PTy = cast<PointerType>(T);
    276       // POINTER: [pointee type, address space]
    277       Code = bitc::TYPE_CODE_POINTER;
    278       TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
    279       unsigned AddressSpace = PTy->getAddressSpace();
    280       TypeVals.push_back(AddressSpace);
    281       if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
    282       break;
    283     }
    284     case Type::FunctionTyID: {
    285       FunctionType *FT = cast<FunctionType>(T);
    286       // FUNCTION: [isvararg, retty, paramty x N]
    287       Code = bitc::TYPE_CODE_FUNCTION;
    288       TypeVals.push_back(FT->isVarArg());
    289       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
    290       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
    291         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
    292       AbbrevToUse = FunctionAbbrev;
    293       break;
    294     }
    295     case Type::StructTyID: {
    296       StructType *ST = cast<StructType>(T);
    297       // STRUCT: [ispacked, eltty x N]
    298       TypeVals.push_back(ST->isPacked());
    299       // Output all of the element types.
    300       for (StructType::element_iterator I = ST->element_begin(),
    301            E = ST->element_end(); I != E; ++I)
    302         TypeVals.push_back(VE.getTypeID(*I));
    303 
    304       if (ST->isLiteral()) {
    305         Code = bitc::TYPE_CODE_STRUCT_ANON;
    306         AbbrevToUse = StructAnonAbbrev;
    307       } else {
    308         if (ST->isOpaque()) {
    309           Code = bitc::TYPE_CODE_OPAQUE;
    310         } else {
    311           Code = bitc::TYPE_CODE_STRUCT_NAMED;
    312           AbbrevToUse = StructNamedAbbrev;
    313         }
    314 
    315         // Emit the name if it is present.
    316         if (!ST->getName().empty())
    317           WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
    318                             StructNameAbbrev, Stream);
    319       }
    320       break;
    321     }
    322     case Type::ArrayTyID: {
    323       ArrayType *AT = cast<ArrayType>(T);
    324       // ARRAY: [numelts, eltty]
    325       Code = bitc::TYPE_CODE_ARRAY;
    326       TypeVals.push_back(AT->getNumElements());
    327       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
    328       AbbrevToUse = ArrayAbbrev;
    329       break;
    330     }
    331     case Type::VectorTyID: {
    332       VectorType *VT = cast<VectorType>(T);
    333       // VECTOR [numelts, eltty]
    334       Code = bitc::TYPE_CODE_VECTOR;
    335       TypeVals.push_back(VT->getNumElements());
    336       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
    337       break;
    338     }
    339     }
    340 
    341     // Emit the finished record.
    342     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
    343     TypeVals.clear();
    344   }
    345 
    346   Stream.ExitBlock();
    347 }
    348 
    349 static unsigned getEncodedLinkage(const GlobalValue *GV) {
    350   switch (GV->getLinkage()) {
    351   case GlobalValue::ExternalLinkage:                 return 0;
    352   case GlobalValue::WeakAnyLinkage:                  return 1;
    353   case GlobalValue::AppendingLinkage:                return 2;
    354   case GlobalValue::InternalLinkage:                 return 3;
    355   case GlobalValue::LinkOnceAnyLinkage:              return 4;
    356   case GlobalValue::DLLImportLinkage:                return 5;
    357   case GlobalValue::DLLExportLinkage:                return 6;
    358   case GlobalValue::ExternalWeakLinkage:             return 7;
    359   case GlobalValue::CommonLinkage:                   return 8;
    360   case GlobalValue::PrivateLinkage:                  return 9;
    361   case GlobalValue::WeakODRLinkage:                  return 10;
    362   case GlobalValue::LinkOnceODRLinkage:              return 11;
    363   case GlobalValue::AvailableExternallyLinkage:      return 12;
    364   case GlobalValue::LinkerPrivateLinkage:            return 13;
    365   case GlobalValue::LinkerPrivateWeakLinkage:        return 14;
    366   case GlobalValue::LinkOnceODRAutoHideLinkage:      return 15;
    367   }
    368   llvm_unreachable("Invalid linkage");
    369 }
    370 
    371 static unsigned getEncodedVisibility(const GlobalValue *GV) {
    372   switch (GV->getVisibility()) {
    373   case GlobalValue::DefaultVisibility:   return 0;
    374   case GlobalValue::HiddenVisibility:    return 1;
    375   case GlobalValue::ProtectedVisibility: return 2;
    376   }
    377   llvm_unreachable("Invalid visibility");
    378 }
    379 
    380 static unsigned getEncodedThreadLocalMode(const GlobalVariable *GV) {
    381   switch (GV->getThreadLocalMode()) {
    382     case GlobalVariable::NotThreadLocal:         return 0;
    383     case GlobalVariable::GeneralDynamicTLSModel: return 1;
    384     case GlobalVariable::LocalDynamicTLSModel:   return 2;
    385     case GlobalVariable::InitialExecTLSModel:    return 3;
    386     case GlobalVariable::LocalExecTLSModel:      return 4;
    387   }
    388   llvm_unreachable("Invalid TLS model");
    389 }
    390 
    391 // Emit top-level description of module, including target triple, inline asm,
    392 // descriptors for global variables, and function prototype info.
    393 static void WriteModuleInfo(const Module *M,
    394                             const llvm_3_2::ValueEnumerator &VE,
    395                             BitstreamWriter &Stream) {
    396   // Emit various pieces of data attached to a module.
    397   if (!M->getTargetTriple().empty())
    398     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
    399                       0/*TODO*/, Stream);
    400   if (!M->getDataLayout().empty())
    401     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
    402                       0/*TODO*/, Stream);
    403   if (!M->getModuleInlineAsm().empty())
    404     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
    405                       0/*TODO*/, Stream);
    406 
    407   // Emit information about sections and GC, computing how many there are. Also
    408   // compute the maximum alignment value.
    409   std::map<std::string, unsigned> SectionMap;
    410   std::map<std::string, unsigned> GCMap;
    411   unsigned MaxAlignment = 0;
    412   unsigned MaxGlobalType = 0;
    413   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
    414        GV != E; ++GV) {
    415     MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
    416     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
    417     if (GV->hasSection()) {
    418       // Give section names unique ID's.
    419       unsigned &Entry = SectionMap[GV->getSection()];
    420       if (!Entry) {
    421         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
    422                           0/*TODO*/, Stream);
    423         Entry = SectionMap.size();
    424       }
    425     }
    426   }
    427   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
    428     MaxAlignment = std::max(MaxAlignment, F->getAlignment());
    429     if (F->hasSection()) {
    430       // Give section names unique ID's.
    431       unsigned &Entry = SectionMap[F->getSection()];
    432       if (!Entry) {
    433         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
    434                           0/*TODO*/, Stream);
    435         Entry = SectionMap.size();
    436       }
    437     }
    438     if (F->hasGC()) {
    439       // Same for GC names.
    440       unsigned &Entry = GCMap[F->getGC()];
    441       if (!Entry) {
    442         WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
    443                           0/*TODO*/, Stream);
    444         Entry = GCMap.size();
    445       }
    446     }
    447   }
    448 
    449   // Emit abbrev for globals, now that we know # sections and max alignment.
    450   unsigned SimpleGVarAbbrev = 0;
    451   if (!M->global_empty()) {
    452     // Add an abbrev for common globals with no visibility or thread localness.
    453     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
    454     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
    455     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
    456                               Log2_32_Ceil(MaxGlobalType+1)));
    457     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));      // Constant.
    458     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));        // Initializer.
    459     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));      // Linkage.
    460     if (MaxAlignment == 0)                                      // Alignment.
    461       Abbv->Add(BitCodeAbbrevOp(0));
    462     else {
    463       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
    464       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
    465                                Log2_32_Ceil(MaxEncAlignment+1)));
    466     }
    467     if (SectionMap.empty())                                    // Section.
    468       Abbv->Add(BitCodeAbbrevOp(0));
    469     else
    470       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
    471                                Log2_32_Ceil(SectionMap.size()+1)));
    472     // Don't bother emitting vis + thread local.
    473     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
    474   }
    475 
    476   // Emit the global variable information.
    477   SmallVector<unsigned, 64> Vals;
    478   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
    479        GV != E; ++GV) {
    480     unsigned AbbrevToUse = 0;
    481 
    482     // GLOBALVAR: [type, isconst, initid,
    483     //             linkage, alignment, section, visibility, threadlocal,
    484     //             unnamed_addr]
    485     Vals.push_back(VE.getTypeID(GV->getType()));
    486     Vals.push_back(GV->isConstant());
    487     Vals.push_back(GV->isDeclaration() ? 0 :
    488                    (VE.getValueID(GV->getInitializer()) + 1));
    489     Vals.push_back(getEncodedLinkage(GV));
    490     Vals.push_back(Log2_32(GV->getAlignment())+1);
    491     Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
    492     if (GV->isThreadLocal() ||
    493         GV->getVisibility() != GlobalValue::DefaultVisibility ||
    494         GV->hasUnnamedAddr() || GV->isExternallyInitialized()) {
    495       Vals.push_back(getEncodedVisibility(GV));
    496       Vals.push_back(getEncodedThreadLocalMode(GV));
    497       Vals.push_back(GV->hasUnnamedAddr());
    498       Vals.push_back(GV->isExternallyInitialized());
    499     } else {
    500       AbbrevToUse = SimpleGVarAbbrev;
    501     }
    502 
    503     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
    504     Vals.clear();
    505   }
    506 
    507   // Emit the function proto information.
    508   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
    509     // FUNCTION:  [type, callingconv, isproto, linkage, paramattrs, alignment,
    510     //             section, visibility, gc, unnamed_addr]
    511     Vals.push_back(VE.getTypeID(F->getType()));
    512     Vals.push_back(F->getCallingConv());
    513     Vals.push_back(F->isDeclaration());
    514     Vals.push_back(getEncodedLinkage(F));
    515     Vals.push_back(VE.getAttributeID(F->getAttributes()));
    516     Vals.push_back(Log2_32(F->getAlignment())+1);
    517     Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
    518     Vals.push_back(getEncodedVisibility(F));
    519     Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
    520     Vals.push_back(F->hasUnnamedAddr());
    521 
    522     unsigned AbbrevToUse = 0;
    523     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
    524     Vals.clear();
    525   }
    526 
    527   // Emit the alias information.
    528   for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
    529        AI != E; ++AI) {
    530     // ALIAS: [alias type, aliasee val#, linkage, visibility]
    531     Vals.push_back(VE.getTypeID(AI->getType()));
    532     Vals.push_back(VE.getValueID(AI->getAliasee()));
    533     Vals.push_back(getEncodedLinkage(AI));
    534     Vals.push_back(getEncodedVisibility(AI));
    535     unsigned AbbrevToUse = 0;
    536     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
    537     Vals.clear();
    538   }
    539 }
    540 
    541 static uint64_t GetOptimizationFlags(const Value *V) {
    542   uint64_t Flags = 0;
    543 
    544   if (const OverflowingBinaryOperator *OBO =
    545         dyn_cast<OverflowingBinaryOperator>(V)) {
    546     if (OBO->hasNoSignedWrap())
    547       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
    548     if (OBO->hasNoUnsignedWrap())
    549       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
    550   } else if (const PossiblyExactOperator *PEO =
    551                dyn_cast<PossiblyExactOperator>(V)) {
    552     if (PEO->isExact())
    553       Flags |= 1 << bitc::PEO_EXACT;
    554   } else if (const FPMathOperator *FPMO =
    555              dyn_cast<const FPMathOperator>(V)) {
    556     // FIXME(srhines): We don't handle fast math in llvm-rs-cc today.
    557     if (false) {
    558       if (FPMO->hasUnsafeAlgebra())
    559         Flags |= FastMathFlags::UnsafeAlgebra;
    560       if (FPMO->hasNoNaNs())
    561         Flags |= FastMathFlags::NoNaNs;
    562       if (FPMO->hasNoInfs())
    563         Flags |= FastMathFlags::NoInfs;
    564       if (FPMO->hasNoSignedZeros())
    565         Flags |= FastMathFlags::NoSignedZeros;
    566       if (FPMO->hasAllowReciprocal())
    567         Flags |= FastMathFlags::AllowReciprocal;
    568     }
    569   }
    570 
    571   return Flags;
    572 }
    573 
    574 static void WriteMDNode(const MDNode *N,
    575                         const llvm_3_2::ValueEnumerator &VE,
    576                         BitstreamWriter &Stream,
    577                         SmallVector<uint64_t, 64> &Record) {
    578   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
    579     if (N->getOperand(i)) {
    580       Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
    581       Record.push_back(VE.getValueID(N->getOperand(i)));
    582     } else {
    583       Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
    584       Record.push_back(0);
    585     }
    586   }
    587   unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE :
    588                                            bitc::METADATA_NODE;
    589   Stream.EmitRecord(MDCode, Record, 0);
    590   Record.clear();
    591 }
    592 
    593 static void WriteModuleMetadata(const Module *M,
    594                                 const llvm_3_2::ValueEnumerator &VE,
    595                                 BitstreamWriter &Stream) {
    596   const llvm_3_2::ValueEnumerator::ValueList &Vals = VE.getMDValues();
    597   bool StartedMetadataBlock = false;
    598   unsigned MDSAbbrev = 0;
    599   SmallVector<uint64_t, 64> Record;
    600   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
    601 
    602     if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
    603       if (!N->isFunctionLocal() || !N->getFunction()) {
    604         if (!StartedMetadataBlock) {
    605           Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
    606           StartedMetadataBlock = true;
    607         }
    608         WriteMDNode(N, VE, Stream, Record);
    609       }
    610     } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
    611       if (!StartedMetadataBlock)  {
    612         Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
    613 
    614         // Abbrev for METADATA_STRING.
    615         BitCodeAbbrev *Abbv = new BitCodeAbbrev();
    616         Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
    617         Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    618         Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
    619         MDSAbbrev = Stream.EmitAbbrev(Abbv);
    620         StartedMetadataBlock = true;
    621       }
    622 
    623       // Code: [strchar x N]
    624       Record.append(MDS->begin(), MDS->end());
    625 
    626       // Emit the finished record.
    627       Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
    628       Record.clear();
    629     }
    630   }
    631 
    632   // Write named metadata.
    633   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
    634        E = M->named_metadata_end(); I != E; ++I) {
    635     const NamedMDNode *NMD = I;
    636     if (!StartedMetadataBlock)  {
    637       Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
    638       StartedMetadataBlock = true;
    639     }
    640 
    641     // Write name.
    642     StringRef Str = NMD->getName();
    643     for (unsigned i = 0, e = Str.size(); i != e; ++i)
    644       Record.push_back(Str[i]);
    645     Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
    646     Record.clear();
    647 
    648     // Write named metadata operands.
    649     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
    650       Record.push_back(VE.getValueID(NMD->getOperand(i)));
    651     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
    652     Record.clear();
    653   }
    654 
    655   if (StartedMetadataBlock)
    656     Stream.ExitBlock();
    657 }
    658 
    659 static void WriteFunctionLocalMetadata(const Function &F,
    660                                        const llvm_3_2::ValueEnumerator &VE,
    661                                        BitstreamWriter &Stream) {
    662   bool StartedMetadataBlock = false;
    663   SmallVector<uint64_t, 64> Record;
    664   const SmallVector<const MDNode *, 8> &Vals = VE.getFunctionLocalMDValues();
    665   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
    666     if (const MDNode *N = Vals[i])
    667       if (N->isFunctionLocal() && N->getFunction() == &F) {
    668         if (!StartedMetadataBlock) {
    669           Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
    670           StartedMetadataBlock = true;
    671         }
    672         WriteMDNode(N, VE, Stream, Record);
    673       }
    674 
    675   if (StartedMetadataBlock)
    676     Stream.ExitBlock();
    677 }
    678 
    679 static void WriteMetadataAttachment(const Function &F,
    680                                     const llvm_3_2::ValueEnumerator &VE,
    681                                     BitstreamWriter &Stream) {
    682   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
    683 
    684   SmallVector<uint64_t, 64> Record;
    685 
    686   // Write metadata attachments
    687   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
    688   SmallVector<std::pair<unsigned, MDNode*>, 4> MDs;
    689 
    690   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
    691     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
    692          I != E; ++I) {
    693       MDs.clear();
    694       I->getAllMetadataOtherThanDebugLoc(MDs);
    695 
    696       // If no metadata, ignore instruction.
    697       if (MDs.empty()) continue;
    698 
    699       Record.push_back(VE.getInstructionID(I));
    700 
    701       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
    702         Record.push_back(MDs[i].first);
    703         Record.push_back(VE.getValueID(MDs[i].second));
    704       }
    705       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
    706       Record.clear();
    707     }
    708 
    709   Stream.ExitBlock();
    710 }
    711 
    712 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
    713   SmallVector<uint64_t, 64> Record;
    714 
    715   // Write metadata kinds
    716   // METADATA_KIND - [n x [id, name]]
    717   SmallVector<StringRef, 4> Names;
    718   M->getMDKindNames(Names);
    719 
    720   if (Names.empty()) return;
    721 
    722   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
    723 
    724   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
    725     Record.push_back(MDKindID);
    726     StringRef KName = Names[MDKindID];
    727     Record.append(KName.begin(), KName.end());
    728 
    729     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
    730     Record.clear();
    731   }
    732 
    733   Stream.ExitBlock();
    734 }
    735 
    736 static void EmitAPInt(SmallVectorImpl<uint64_t> &Vals,
    737                       unsigned &Code, unsigned &AbbrevToUse, const APInt &Val,
    738                       bool EmitSizeForWideNumbers = false
    739                       ) {
    740   if (Val.getBitWidth() <= 64) {
    741     uint64_t V = Val.getSExtValue();
    742     if ((int64_t)V >= 0)
    743       Vals.push_back(V << 1);
    744     else
    745       Vals.push_back((-V << 1) | 1);
    746     Code = bitc::CST_CODE_INTEGER;
    747     AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
    748   } else {
    749     // Wide integers, > 64 bits in size.
    750     // We have an arbitrary precision integer value to write whose
    751     // bit width is > 64. However, in canonical unsigned integer
    752     // format it is likely that the high bits are going to be zero.
    753     // So, we only write the number of active words.
    754     unsigned NWords = Val.getActiveWords();
    755 
    756     if (EmitSizeForWideNumbers)
    757       Vals.push_back(NWords);
    758 
    759     const uint64_t *RawWords = Val.getRawData();
    760     for (unsigned i = 0; i != NWords; ++i) {
    761       int64_t V = RawWords[i];
    762       if (V >= 0)
    763         Vals.push_back(V << 1);
    764       else
    765         Vals.push_back((-V << 1) | 1);
    766     }
    767     Code = bitc::CST_CODE_WIDE_INTEGER;
    768   }
    769 }
    770 
    771 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
    772                            const llvm_3_2::ValueEnumerator &VE,
    773                            BitstreamWriter &Stream, bool isGlobal) {
    774   if (FirstVal == LastVal) return;
    775 
    776   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
    777 
    778   unsigned AggregateAbbrev = 0;
    779   unsigned String8Abbrev = 0;
    780   unsigned CString7Abbrev = 0;
    781   unsigned CString6Abbrev = 0;
    782   // If this is a constant pool for the module, emit module-specific abbrevs.
    783   if (isGlobal) {
    784     // Abbrev for CST_CODE_AGGREGATE.
    785     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
    786     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
    787     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    788     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
    789     AggregateAbbrev = Stream.EmitAbbrev(Abbv);
    790 
    791     // Abbrev for CST_CODE_STRING.
    792     Abbv = new BitCodeAbbrev();
    793     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
    794     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    795     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
    796     String8Abbrev = Stream.EmitAbbrev(Abbv);
    797     // Abbrev for CST_CODE_CSTRING.
    798     Abbv = new BitCodeAbbrev();
    799     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
    800     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    801     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
    802     CString7Abbrev = Stream.EmitAbbrev(Abbv);
    803     // Abbrev for CST_CODE_CSTRING.
    804     Abbv = new BitCodeAbbrev();
    805     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
    806     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
    807     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
    808     CString6Abbrev = Stream.EmitAbbrev(Abbv);
    809   }
    810 
    811   SmallVector<uint64_t, 64> Record;
    812 
    813   const llvm_3_2::ValueEnumerator::ValueList &Vals = VE.getValues();
    814   Type *LastTy = 0;
    815   for (unsigned i = FirstVal; i != LastVal; ++i) {
    816     const Value *V = Vals[i].first;
    817     // If we need to switch types, do so now.
    818     if (V->getType() != LastTy) {
    819       LastTy = V->getType();
    820       Record.push_back(VE.getTypeID(LastTy));
    821       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
    822                         CONSTANTS_SETTYPE_ABBREV);
    823       Record.clear();
    824     }
    825 
    826     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
    827       Record.push_back(unsigned(IA->hasSideEffects()) |
    828                        unsigned(IA->isAlignStack()) << 1 |
    829                        unsigned(IA->getDialect()&1) << 2);
    830 
    831       // Add the asm string.
    832       const std::string &AsmStr = IA->getAsmString();
    833       Record.push_back(AsmStr.size());
    834       for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
    835         Record.push_back(AsmStr[i]);
    836 
    837       // Add the constraint string.
    838       const std::string &ConstraintStr = IA->getConstraintString();
    839       Record.push_back(ConstraintStr.size());
    840       for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
    841         Record.push_back(ConstraintStr[i]);
    842       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
    843       Record.clear();
    844       continue;
    845     }
    846     const Constant *C = cast<Constant>(V);
    847     unsigned Code = -1U;
    848     unsigned AbbrevToUse = 0;
    849     if (C->isNullValue()) {
    850       Code = bitc::CST_CODE_NULL;
    851     } else if (isa<UndefValue>(C)) {
    852       Code = bitc::CST_CODE_UNDEF;
    853     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
    854       EmitAPInt(Record, Code, AbbrevToUse, IV->getValue());
    855     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
    856       Code = bitc::CST_CODE_FLOAT;
    857       Type *Ty = CFP->getType();
    858       if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
    859         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
    860       } else if (Ty->isX86_FP80Ty()) {
    861         // api needed to prevent premature destruction
    862         // bits are not in the same order as a normal i80 APInt, compensate.
    863         APInt api = CFP->getValueAPF().bitcastToAPInt();
    864         const uint64_t *p = api.getRawData();
    865         Record.push_back((p[1] << 48) | (p[0] >> 16));
    866         Record.push_back(p[0] & 0xffffLL);
    867       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
    868         APInt api = CFP->getValueAPF().bitcastToAPInt();
    869         const uint64_t *p = api.getRawData();
    870         Record.push_back(p[0]);
    871         Record.push_back(p[1]);
    872       } else {
    873         assert (0 && "Unknown FP type!");
    874       }
    875     } else if (isa<ConstantDataSequential>(C) &&
    876                cast<ConstantDataSequential>(C)->isString()) {
    877       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
    878       // Emit constant strings specially.
    879       unsigned NumElts = Str->getNumElements();
    880       // If this is a null-terminated string, use the denser CSTRING encoding.
    881       if (Str->isCString()) {
    882         Code = bitc::CST_CODE_CSTRING;
    883         --NumElts;  // Don't encode the null, which isn't allowed by char6.
    884       } else {
    885         Code = bitc::CST_CODE_STRING;
    886         AbbrevToUse = String8Abbrev;
    887       }
    888       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
    889       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
    890       for (unsigned i = 0; i != NumElts; ++i) {
    891         unsigned char V = Str->getElementAsInteger(i);
    892         Record.push_back(V);
    893         isCStr7 &= (V & 128) == 0;
    894         if (isCStrChar6)
    895           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
    896       }
    897 
    898       if (isCStrChar6)
    899         AbbrevToUse = CString6Abbrev;
    900       else if (isCStr7)
    901         AbbrevToUse = CString7Abbrev;
    902     } else if (const ConstantDataSequential *CDS =
    903                   dyn_cast<ConstantDataSequential>(C)) {
    904       Code = bitc::CST_CODE_DATA;
    905       Type *EltTy = CDS->getType()->getElementType();
    906       if (isa<IntegerType>(EltTy)) {
    907         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
    908           Record.push_back(CDS->getElementAsInteger(i));
    909       } else if (EltTy->isFloatTy()) {
    910         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
    911           union { float F; uint32_t I; };
    912           F = CDS->getElementAsFloat(i);
    913           Record.push_back(I);
    914         }
    915       } else {
    916         assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
    917         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
    918           union { double F; uint64_t I; };
    919           F = CDS->getElementAsDouble(i);
    920           Record.push_back(I);
    921         }
    922       }
    923     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
    924                isa<ConstantVector>(C)) {
    925       Code = bitc::CST_CODE_AGGREGATE;
    926       for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
    927         Record.push_back(VE.getValueID(C->getOperand(i)));
    928       AbbrevToUse = AggregateAbbrev;
    929     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
    930       switch (CE->getOpcode()) {
    931       default:
    932         if (Instruction::isCast(CE->getOpcode())) {
    933           Code = bitc::CST_CODE_CE_CAST;
    934           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
    935           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
    936           Record.push_back(VE.getValueID(C->getOperand(0)));
    937           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
    938         } else {
    939           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
    940           Code = bitc::CST_CODE_CE_BINOP;
    941           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
    942           Record.push_back(VE.getValueID(C->getOperand(0)));
    943           Record.push_back(VE.getValueID(C->getOperand(1)));
    944           uint64_t Flags = GetOptimizationFlags(CE);
    945           if (Flags != 0)
    946             Record.push_back(Flags);
    947         }
    948         break;
    949       case Instruction::GetElementPtr:
    950         Code = bitc::CST_CODE_CE_GEP;
    951         if (cast<GEPOperator>(C)->isInBounds())
    952           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
    953         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
    954           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
    955           Record.push_back(VE.getValueID(C->getOperand(i)));
    956         }
    957         break;
    958       case Instruction::Select:
    959         Code = bitc::CST_CODE_CE_SELECT;
    960         Record.push_back(VE.getValueID(C->getOperand(0)));
    961         Record.push_back(VE.getValueID(C->getOperand(1)));
    962         Record.push_back(VE.getValueID(C->getOperand(2)));
    963         break;
    964       case Instruction::ExtractElement:
    965         Code = bitc::CST_CODE_CE_EXTRACTELT;
    966         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
    967         Record.push_back(VE.getValueID(C->getOperand(0)));
    968         Record.push_back(VE.getValueID(C->getOperand(1)));
    969         break;
    970       case Instruction::InsertElement:
    971         Code = bitc::CST_CODE_CE_INSERTELT;
    972         Record.push_back(VE.getValueID(C->getOperand(0)));
    973         Record.push_back(VE.getValueID(C->getOperand(1)));
    974         Record.push_back(VE.getValueID(C->getOperand(2)));
    975         break;
    976       case Instruction::ShuffleVector:
    977         // If the return type and argument types are the same, this is a
    978         // standard shufflevector instruction.  If the types are different,
    979         // then the shuffle is widening or truncating the input vectors, and
    980         // the argument type must also be encoded.
    981         if (C->getType() == C->getOperand(0)->getType()) {
    982           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
    983         } else {
    984           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
    985           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
    986         }
    987         Record.push_back(VE.getValueID(C->getOperand(0)));
    988         Record.push_back(VE.getValueID(C->getOperand(1)));
    989         Record.push_back(VE.getValueID(C->getOperand(2)));
    990         break;
    991       case Instruction::ICmp:
    992       case Instruction::FCmp:
    993         Code = bitc::CST_CODE_CE_CMP;
    994         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
    995         Record.push_back(VE.getValueID(C->getOperand(0)));
    996         Record.push_back(VE.getValueID(C->getOperand(1)));
    997         Record.push_back(CE->getPredicate());
    998         break;
    999       }
   1000     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
   1001       Code = bitc::CST_CODE_BLOCKADDRESS;
   1002       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
   1003       Record.push_back(VE.getValueID(BA->getFunction()));
   1004       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
   1005     } else {
   1006 #ifndef NDEBUG
   1007       C->dump();
   1008 #endif
   1009       llvm_unreachable("Unknown constant!");
   1010     }
   1011     Stream.EmitRecord(Code, Record, AbbrevToUse);
   1012     Record.clear();
   1013   }
   1014 
   1015   Stream.ExitBlock();
   1016 }
   1017 
   1018 static void WriteModuleConstants(const llvm_3_2::ValueEnumerator &VE,
   1019                                  BitstreamWriter &Stream) {
   1020   const llvm_3_2::ValueEnumerator::ValueList &Vals = VE.getValues();
   1021 
   1022   // Find the first constant to emit, which is the first non-globalvalue value.
   1023   // We know globalvalues have been emitted by WriteModuleInfo.
   1024   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
   1025     if (!isa<GlobalValue>(Vals[i].first)) {
   1026       WriteConstants(i, Vals.size(), VE, Stream, true);
   1027       return;
   1028     }
   1029   }
   1030 }
   1031 
   1032 /// PushValueAndType - The file has to encode both the value and type id for
   1033 /// many values, because we need to know what type to create for forward
   1034 /// references.  However, most operands are not forward references, so this type
   1035 /// field is not needed.
   1036 ///
   1037 /// This function adds V's value ID to Vals.  If the value ID is higher than the
   1038 /// instruction ID, then it is a forward reference, and it also includes the
   1039 /// type ID.
   1040 static bool PushValueAndType(const Value *V, unsigned InstID,
   1041                              SmallVector<unsigned, 64> &Vals,
   1042                              llvm_3_2::ValueEnumerator &VE) {
   1043   unsigned ValID = VE.getValueID(V);
   1044   Vals.push_back(ValID);
   1045   if (ValID >= InstID) {
   1046     Vals.push_back(VE.getTypeID(V->getType()));
   1047     return true;
   1048   }
   1049   return false;
   1050 }
   1051 
   1052 /// WriteInstruction - Emit an instruction to the specified stream.
   1053 static void WriteInstruction(const Instruction &I, unsigned InstID,
   1054                              llvm_3_2::ValueEnumerator &VE,
   1055                              BitstreamWriter &Stream,
   1056                              SmallVector<unsigned, 64> &Vals) {
   1057   unsigned Code = 0;
   1058   unsigned AbbrevToUse = 0;
   1059   VE.setInstructionID(&I);
   1060   switch (I.getOpcode()) {
   1061   default:
   1062     if (Instruction::isCast(I.getOpcode())) {
   1063       Code = bitc::FUNC_CODE_INST_CAST;
   1064       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
   1065         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
   1066       Vals.push_back(VE.getTypeID(I.getType()));
   1067       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
   1068     } else {
   1069       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
   1070       Code = bitc::FUNC_CODE_INST_BINOP;
   1071       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
   1072         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
   1073       Vals.push_back(VE.getValueID(I.getOperand(1)));
   1074       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
   1075       uint64_t Flags = GetOptimizationFlags(&I);
   1076       if (Flags != 0) {
   1077         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
   1078           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
   1079         Vals.push_back(Flags);
   1080       }
   1081     }
   1082     break;
   1083 
   1084   case Instruction::GetElementPtr:
   1085     Code = bitc::FUNC_CODE_INST_GEP;
   1086     if (cast<GEPOperator>(&I)->isInBounds())
   1087       Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
   1088     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
   1089       PushValueAndType(I.getOperand(i), InstID, Vals, VE);
   1090     break;
   1091   case Instruction::ExtractValue: {
   1092     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
   1093     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
   1094     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
   1095     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
   1096       Vals.push_back(*i);
   1097     break;
   1098   }
   1099   case Instruction::InsertValue: {
   1100     Code = bitc::FUNC_CODE_INST_INSERTVAL;
   1101     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
   1102     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
   1103     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
   1104     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
   1105       Vals.push_back(*i);
   1106     break;
   1107   }
   1108   case Instruction::Select:
   1109     Code = bitc::FUNC_CODE_INST_VSELECT;
   1110     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
   1111     Vals.push_back(VE.getValueID(I.getOperand(2)));
   1112     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
   1113     break;
   1114   case Instruction::ExtractElement:
   1115     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
   1116     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
   1117     Vals.push_back(VE.getValueID(I.getOperand(1)));
   1118     break;
   1119   case Instruction::InsertElement:
   1120     Code = bitc::FUNC_CODE_INST_INSERTELT;
   1121     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
   1122     Vals.push_back(VE.getValueID(I.getOperand(1)));
   1123     Vals.push_back(VE.getValueID(I.getOperand(2)));
   1124     break;
   1125   case Instruction::ShuffleVector:
   1126     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
   1127     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
   1128     Vals.push_back(VE.getValueID(I.getOperand(1)));
   1129     Vals.push_back(VE.getValueID(I.getOperand(2)));
   1130     break;
   1131   case Instruction::ICmp:
   1132   case Instruction::FCmp:
   1133     // compare returning Int1Ty or vector of Int1Ty
   1134     Code = bitc::FUNC_CODE_INST_CMP2;
   1135     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
   1136     Vals.push_back(VE.getValueID(I.getOperand(1)));
   1137     Vals.push_back(cast<CmpInst>(I).getPredicate());
   1138     break;
   1139 
   1140   case Instruction::Ret:
   1141     {
   1142       Code = bitc::FUNC_CODE_INST_RET;
   1143       unsigned NumOperands = I.getNumOperands();
   1144       if (NumOperands == 0)
   1145         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
   1146       else if (NumOperands == 1) {
   1147         if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
   1148           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
   1149       } else {
   1150         for (unsigned i = 0, e = NumOperands; i != e; ++i)
   1151           PushValueAndType(I.getOperand(i), InstID, Vals, VE);
   1152       }
   1153     }
   1154     break;
   1155   case Instruction::Br:
   1156     {
   1157       Code = bitc::FUNC_CODE_INST_BR;
   1158       const BranchInst &II = cast<BranchInst>(I);
   1159       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
   1160       if (II.isConditional()) {
   1161         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
   1162         Vals.push_back(VE.getValueID(II.getCondition()));
   1163       }
   1164     }
   1165     break;
   1166   case Instruction::Switch:
   1167     {
   1168       // Redefine Vals, since here we need to use 64 bit values
   1169       // explicitly to store large APInt numbers.
   1170       SmallVector<uint64_t, 128> Vals64;
   1171 
   1172       Code = bitc::FUNC_CODE_INST_SWITCH;
   1173       const SwitchInst &SI = cast<SwitchInst>(I);
   1174 
   1175       uint32_t SwitchRecordHeader = SI.hash() | (SWITCH_INST_MAGIC << 16);
   1176       Vals64.push_back(SwitchRecordHeader);
   1177 
   1178       Vals64.push_back(VE.getTypeID(SI.getCondition()->getType()));
   1179       Vals64.push_back(VE.getValueID(SI.getCondition()));
   1180       Vals64.push_back(VE.getValueID(SI.getDefaultDest()));
   1181       Vals64.push_back(SI.getNumCases());
   1182       for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
   1183            i != e; ++i) {
   1184         const IntegersSubset& CaseRanges = i.getCaseValueEx();
   1185         unsigned Code, Abbrev; // will unused.
   1186 
   1187         if (CaseRanges.isSingleNumber()) {
   1188           Vals64.push_back(1/*NumItems = 1*/);
   1189           Vals64.push_back(true/*IsSingleNumber = true*/);
   1190           EmitAPInt(Vals64, Code, Abbrev, CaseRanges.getSingleNumber(0), true);
   1191         } else {
   1192 
   1193           Vals64.push_back(CaseRanges.getNumItems());
   1194 
   1195           if (CaseRanges.isSingleNumbersOnly()) {
   1196             for (unsigned ri = 0, rn = CaseRanges.getNumItems();
   1197                  ri != rn; ++ri) {
   1198 
   1199               Vals64.push_back(true/*IsSingleNumber = true*/);
   1200 
   1201               EmitAPInt(Vals64, Code, Abbrev,
   1202                         CaseRanges.getSingleNumber(ri), true);
   1203             }
   1204           } else
   1205             for (unsigned ri = 0, rn = CaseRanges.getNumItems();
   1206                  ri != rn; ++ri) {
   1207               IntegersSubset::Range r = CaseRanges.getItem(ri);
   1208               bool IsSingleNumber = CaseRanges.isSingleNumber(ri);
   1209 
   1210               Vals64.push_back(IsSingleNumber);
   1211 
   1212               EmitAPInt(Vals64, Code, Abbrev, r.getLow(), true);
   1213               if (!IsSingleNumber)
   1214                 EmitAPInt(Vals64, Code, Abbrev, r.getHigh(), true);
   1215             }
   1216         }
   1217         Vals64.push_back(VE.getValueID(i.getCaseSuccessor()));
   1218       }
   1219 
   1220       Stream.EmitRecord(Code, Vals64, AbbrevToUse);
   1221 
   1222       // Also do expected action - clear external Vals collection:
   1223       Vals.clear();
   1224       return;
   1225     }
   1226     break;
   1227   case Instruction::IndirectBr:
   1228     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
   1229     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
   1230     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
   1231       Vals.push_back(VE.getValueID(I.getOperand(i)));
   1232     break;
   1233 
   1234   case Instruction::Invoke: {
   1235     const InvokeInst *II = cast<InvokeInst>(&I);
   1236     const Value *Callee(II->getCalledValue());
   1237     PointerType *PTy = cast<PointerType>(Callee->getType());
   1238     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
   1239     Code = bitc::FUNC_CODE_INST_INVOKE;
   1240 
   1241     Vals.push_back(VE.getAttributeID(II->getAttributes()));
   1242     Vals.push_back(II->getCallingConv());
   1243     Vals.push_back(VE.getValueID(II->getNormalDest()));
   1244     Vals.push_back(VE.getValueID(II->getUnwindDest()));
   1245     PushValueAndType(Callee, InstID, Vals, VE);
   1246 
   1247     // Emit value #'s for the fixed parameters.
   1248     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
   1249       Vals.push_back(VE.getValueID(I.getOperand(i)));  // fixed param.
   1250 
   1251     // Emit type/value pairs for varargs params.
   1252     if (FTy->isVarArg()) {
   1253       for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
   1254            i != e; ++i)
   1255         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
   1256     }
   1257     break;
   1258   }
   1259   case Instruction::Resume:
   1260     Code = bitc::FUNC_CODE_INST_RESUME;
   1261     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
   1262     break;
   1263   case Instruction::Unreachable:
   1264     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
   1265     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
   1266     break;
   1267 
   1268   case Instruction::PHI: {
   1269     const PHINode &PN = cast<PHINode>(I);
   1270     Code = bitc::FUNC_CODE_INST_PHI;
   1271     Vals.push_back(VE.getTypeID(PN.getType()));
   1272     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
   1273       Vals.push_back(VE.getValueID(PN.getIncomingValue(i)));
   1274       Vals.push_back(VE.getValueID(PN.getIncomingBlock(i)));
   1275     }
   1276     break;
   1277   }
   1278 
   1279   case Instruction::LandingPad: {
   1280     const LandingPadInst &LP = cast<LandingPadInst>(I);
   1281     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
   1282     Vals.push_back(VE.getTypeID(LP.getType()));
   1283     PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
   1284     Vals.push_back(LP.isCleanup());
   1285     Vals.push_back(LP.getNumClauses());
   1286     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
   1287       if (LP.isCatch(I))
   1288         Vals.push_back(LandingPadInst::Catch);
   1289       else
   1290         Vals.push_back(LandingPadInst::Filter);
   1291       PushValueAndType(LP.getClause(I), InstID, Vals, VE);
   1292     }
   1293     break;
   1294   }
   1295 
   1296   case Instruction::Alloca:
   1297     Code = bitc::FUNC_CODE_INST_ALLOCA;
   1298     Vals.push_back(VE.getTypeID(I.getType()));
   1299     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
   1300     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
   1301     Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
   1302     break;
   1303 
   1304   case Instruction::Load:
   1305     if (cast<LoadInst>(I).isAtomic()) {
   1306       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
   1307       PushValueAndType(I.getOperand(0), InstID, Vals, VE);
   1308     } else {
   1309       Code = bitc::FUNC_CODE_INST_LOAD;
   1310       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
   1311         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
   1312     }
   1313     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
   1314     Vals.push_back(cast<LoadInst>(I).isVolatile());
   1315     if (cast<LoadInst>(I).isAtomic()) {
   1316       Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
   1317       Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
   1318     }
   1319     break;
   1320   case Instruction::Store:
   1321     if (cast<StoreInst>(I).isAtomic())
   1322       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
   1323     else
   1324       Code = bitc::FUNC_CODE_INST_STORE;
   1325     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
   1326     Vals.push_back(VE.getValueID(I.getOperand(0)));       // val.
   1327     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
   1328     Vals.push_back(cast<StoreInst>(I).isVolatile());
   1329     if (cast<StoreInst>(I).isAtomic()) {
   1330       Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
   1331       Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
   1332     }
   1333     break;
   1334   case Instruction::AtomicCmpXchg:
   1335     Code = bitc::FUNC_CODE_INST_CMPXCHG;
   1336     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
   1337     Vals.push_back(VE.getValueID(I.getOperand(1)));       // cmp.
   1338     Vals.push_back(VE.getValueID(I.getOperand(2)));       // newval.
   1339     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
   1340     Vals.push_back(GetEncodedOrdering(
   1341                      cast<AtomicCmpXchgInst>(I).getOrdering()));
   1342     Vals.push_back(GetEncodedSynchScope(
   1343                      cast<AtomicCmpXchgInst>(I).getSynchScope()));
   1344     break;
   1345   case Instruction::AtomicRMW:
   1346     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
   1347     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
   1348     Vals.push_back(VE.getValueID(I.getOperand(1)));       // val.
   1349     Vals.push_back(GetEncodedRMWOperation(
   1350                      cast<AtomicRMWInst>(I).getOperation()));
   1351     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
   1352     Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
   1353     Vals.push_back(GetEncodedSynchScope(
   1354                      cast<AtomicRMWInst>(I).getSynchScope()));
   1355     break;
   1356   case Instruction::Fence:
   1357     Code = bitc::FUNC_CODE_INST_FENCE;
   1358     Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
   1359     Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
   1360     break;
   1361   case Instruction::Call: {
   1362     const CallInst &CI = cast<CallInst>(I);
   1363     PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
   1364     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
   1365 
   1366     Code = bitc::FUNC_CODE_INST_CALL;
   1367 
   1368     Vals.push_back(VE.getAttributeID(CI.getAttributes()));
   1369     Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()));
   1370     PushValueAndType(CI.getCalledValue(), InstID, Vals, VE);  // Callee
   1371 
   1372     // Emit value #'s for the fixed parameters.
   1373     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
   1374       Vals.push_back(VE.getValueID(CI.getArgOperand(i)));  // fixed param.
   1375 
   1376     // Emit type/value pairs for varargs params.
   1377     if (FTy->isVarArg()) {
   1378       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
   1379            i != e; ++i)
   1380         PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE);  // varargs
   1381     }
   1382     break;
   1383   }
   1384   case Instruction::VAArg:
   1385     Code = bitc::FUNC_CODE_INST_VAARG;
   1386     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
   1387     Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
   1388     Vals.push_back(VE.getTypeID(I.getType())); // restype.
   1389     break;
   1390   }
   1391 
   1392   Stream.EmitRecord(Code, Vals, AbbrevToUse);
   1393   Vals.clear();
   1394 }
   1395 
   1396 // Emit names for globals/functions etc.
   1397 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
   1398                                   const llvm_3_2::ValueEnumerator &VE,
   1399                                   BitstreamWriter &Stream) {
   1400   if (VST.empty()) return;
   1401   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
   1402 
   1403   // FIXME: Set up the abbrev, we know how many values there are!
   1404   // FIXME: We know if the type names can use 7-bit ascii.
   1405   SmallVector<unsigned, 64> NameVals;
   1406 
   1407   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
   1408        SI != SE; ++SI) {
   1409 
   1410     const ValueName &Name = *SI;
   1411 
   1412     // Figure out the encoding to use for the name.
   1413     bool is7Bit = true;
   1414     bool isChar6 = true;
   1415     for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
   1416          C != E; ++C) {
   1417       if (isChar6)
   1418         isChar6 = BitCodeAbbrevOp::isChar6(*C);
   1419       if ((unsigned char)*C & 128) {
   1420         is7Bit = false;
   1421         break;  // don't bother scanning the rest.
   1422       }
   1423     }
   1424 
   1425     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
   1426 
   1427     // VST_ENTRY:   [valueid, namechar x N]
   1428     // VST_BBENTRY: [bbid, namechar x N]
   1429     unsigned Code;
   1430     if (isa<BasicBlock>(SI->getValue())) {
   1431       Code = bitc::VST_CODE_BBENTRY;
   1432       if (isChar6)
   1433         AbbrevToUse = VST_BBENTRY_6_ABBREV;
   1434     } else {
   1435       Code = bitc::VST_CODE_ENTRY;
   1436       if (isChar6)
   1437         AbbrevToUse = VST_ENTRY_6_ABBREV;
   1438       else if (is7Bit)
   1439         AbbrevToUse = VST_ENTRY_7_ABBREV;
   1440     }
   1441 
   1442     NameVals.push_back(VE.getValueID(SI->getValue()));
   1443     for (const char *P = Name.getKeyData(),
   1444          *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
   1445       NameVals.push_back((unsigned char)*P);
   1446 
   1447     // Emit the finished record.
   1448     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
   1449     NameVals.clear();
   1450   }
   1451   Stream.ExitBlock();
   1452 }
   1453 
   1454 /// WriteFunction - Emit a function body to the module stream.
   1455 static void WriteFunction(const Function &F, llvm_3_2::ValueEnumerator &VE,
   1456                           BitstreamWriter &Stream) {
   1457   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
   1458   VE.incorporateFunction(F);
   1459 
   1460   SmallVector<unsigned, 64> Vals;
   1461 
   1462   // Emit the number of basic blocks, so the reader can create them ahead of
   1463   // time.
   1464   Vals.push_back(VE.getBasicBlocks().size());
   1465   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
   1466   Vals.clear();
   1467 
   1468   // If there are function-local constants, emit them now.
   1469   unsigned CstStart, CstEnd;
   1470   VE.getFunctionConstantRange(CstStart, CstEnd);
   1471   WriteConstants(CstStart, CstEnd, VE, Stream, false);
   1472 
   1473   // If there is function-local metadata, emit it now.
   1474   WriteFunctionLocalMetadata(F, VE, Stream);
   1475 
   1476   // Keep a running idea of what the instruction ID is.
   1477   unsigned InstID = CstEnd;
   1478 
   1479   bool NeedsMetadataAttachment = false;
   1480 
   1481   DebugLoc LastDL;
   1482 
   1483   // Finally, emit all the instructions, in order.
   1484   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
   1485     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
   1486          I != E; ++I) {
   1487       WriteInstruction(*I, InstID, VE, Stream, Vals);
   1488 
   1489       if (!I->getType()->isVoidTy())
   1490         ++InstID;
   1491 
   1492       // If the instruction has metadata, write a metadata attachment later.
   1493       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
   1494 
   1495       // If the instruction has a debug location, emit it.
   1496       DebugLoc DL = I->getDebugLoc();
   1497       if (DL.isUnknown()) {
   1498         // nothing todo.
   1499       } else if (DL == LastDL) {
   1500         // Just repeat the same debug loc as last time.
   1501         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
   1502       } else {
   1503         MDNode *Scope, *IA;
   1504         DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
   1505 
   1506         Vals.push_back(DL.getLine());
   1507         Vals.push_back(DL.getCol());
   1508         Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
   1509         Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
   1510         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
   1511         Vals.clear();
   1512 
   1513         LastDL = DL;
   1514       }
   1515     }
   1516 
   1517   // Emit names for all the instructions etc.
   1518   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
   1519 
   1520   if (NeedsMetadataAttachment)
   1521     WriteMetadataAttachment(F, VE, Stream);
   1522   VE.purgeFunction();
   1523   Stream.ExitBlock();
   1524 }
   1525 
   1526 // Emit blockinfo, which defines the standard abbreviations etc.
   1527 static void WriteBlockInfo(const llvm_3_2::ValueEnumerator &VE,
   1528                            BitstreamWriter &Stream) {
   1529   // We only want to emit block info records for blocks that have multiple
   1530   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.  Other
   1531   // blocks can defined their abbrevs inline.
   1532   Stream.EnterBlockInfoBlock(2);
   1533 
   1534   { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
   1535     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1536     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
   1537     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
   1538     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
   1539     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
   1540     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
   1541                                    Abbv) != VST_ENTRY_8_ABBREV)
   1542       llvm_unreachable("Unexpected abbrev ordering!");
   1543   }
   1544 
   1545   { // 7-bit fixed width VST_ENTRY strings.
   1546     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1547     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
   1548     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
   1549     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
   1550     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
   1551     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
   1552                                    Abbv) != VST_ENTRY_7_ABBREV)
   1553       llvm_unreachable("Unexpected abbrev ordering!");
   1554   }
   1555   { // 6-bit char6 VST_ENTRY strings.
   1556     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1557     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
   1558     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
   1559     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
   1560     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
   1561     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
   1562                                    Abbv) != VST_ENTRY_6_ABBREV)
   1563       llvm_unreachable("Unexpected abbrev ordering!");
   1564   }
   1565   { // 6-bit char6 VST_BBENTRY strings.
   1566     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1567     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
   1568     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
   1569     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
   1570     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
   1571     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
   1572                                    Abbv) != VST_BBENTRY_6_ABBREV)
   1573       llvm_unreachable("Unexpected abbrev ordering!");
   1574   }
   1575 
   1576 
   1577 
   1578   { // SETTYPE abbrev for CONSTANTS_BLOCK.
   1579     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1580     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
   1581     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
   1582                               Log2_32_Ceil(VE.getTypes().size()+1)));
   1583     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
   1584                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
   1585       llvm_unreachable("Unexpected abbrev ordering!");
   1586   }
   1587 
   1588   { // INTEGER abbrev for CONSTANTS_BLOCK.
   1589     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1590     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
   1591     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
   1592     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
   1593                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
   1594       llvm_unreachable("Unexpected abbrev ordering!");
   1595   }
   1596 
   1597   { // CE_CAST abbrev for CONSTANTS_BLOCK.
   1598     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1599     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
   1600     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
   1601     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
   1602                               Log2_32_Ceil(VE.getTypes().size()+1)));
   1603     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
   1604 
   1605     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
   1606                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
   1607       llvm_unreachable("Unexpected abbrev ordering!");
   1608   }
   1609   { // NULL abbrev for CONSTANTS_BLOCK.
   1610     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1611     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
   1612     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
   1613                                    Abbv) != CONSTANTS_NULL_Abbrev)
   1614       llvm_unreachable("Unexpected abbrev ordering!");
   1615   }
   1616 
   1617   // FIXME: This should only use space for first class types!
   1618 
   1619   { // INST_LOAD abbrev for FUNCTION_BLOCK.
   1620     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1621     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
   1622     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
   1623     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
   1624     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
   1625     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
   1626                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
   1627       llvm_unreachable("Unexpected abbrev ordering!");
   1628   }
   1629   { // INST_BINOP abbrev for FUNCTION_BLOCK.
   1630     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1631     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
   1632     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
   1633     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
   1634     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
   1635     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
   1636                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
   1637       llvm_unreachable("Unexpected abbrev ordering!");
   1638   }
   1639   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
   1640     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1641     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
   1642     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
   1643     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
   1644     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
   1645     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
   1646     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
   1647                                    Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
   1648       llvm_unreachable("Unexpected abbrev ordering!");
   1649   }
   1650   { // INST_CAST abbrev for FUNCTION_BLOCK.
   1651     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1652     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
   1653     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
   1654     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
   1655                               Log2_32_Ceil(VE.getTypes().size()+1)));
   1656     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
   1657     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
   1658                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
   1659       llvm_unreachable("Unexpected abbrev ordering!");
   1660   }
   1661 
   1662   { // INST_RET abbrev for FUNCTION_BLOCK.
   1663     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1664     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
   1665     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
   1666                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
   1667       llvm_unreachable("Unexpected abbrev ordering!");
   1668   }
   1669   { // INST_RET abbrev for FUNCTION_BLOCK.
   1670     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1671     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
   1672     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
   1673     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
   1674                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
   1675       llvm_unreachable("Unexpected abbrev ordering!");
   1676   }
   1677   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
   1678     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
   1679     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
   1680     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
   1681                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
   1682       llvm_unreachable("Unexpected abbrev ordering!");
   1683   }
   1684 
   1685   Stream.ExitBlock();
   1686 }
   1687 
   1688 // Sort the Users based on the order in which the reader parses the bitcode
   1689 // file.
   1690 static bool bitcodereader_order(const User *lhs, const User *rhs) {
   1691   // TODO: Implement.
   1692   return true;
   1693 }
   1694 
   1695 static void WriteUseList(const Value *V, const llvm_3_2::ValueEnumerator &VE,
   1696                          BitstreamWriter &Stream) {
   1697 
   1698   // One or zero uses can't get out of order.
   1699   if (V->use_empty() || V->hasNUses(1))
   1700     return;
   1701 
   1702   // Make a copy of the in-memory use-list for sorting.
   1703   unsigned UseListSize = std::distance(V->use_begin(), V->use_end());
   1704   SmallVector<const User*, 8> UseList;
   1705   UseList.reserve(UseListSize);
   1706   for (Value::const_use_iterator I = V->use_begin(), E = V->use_end();
   1707        I != E; ++I) {
   1708     const User *U = *I;
   1709     UseList.push_back(U);
   1710   }
   1711 
   1712   // Sort the copy based on the order read by the BitcodeReader.
   1713   std::sort(UseList.begin(), UseList.end(), bitcodereader_order);
   1714 
   1715   // TODO: Generate a diff between the BitcodeWriter in-memory use-list and the
   1716   // sorted list (i.e., the expected BitcodeReader in-memory use-list).
   1717 
   1718   // TODO: Emit the USELIST_CODE_ENTRYs.
   1719 }
   1720 
   1721 static void WriteFunctionUseList(const Function *F,
   1722                                  llvm_3_2::ValueEnumerator &VE,
   1723                                  BitstreamWriter &Stream) {
   1724   VE.incorporateFunction(*F);
   1725 
   1726   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
   1727        AI != AE; ++AI)
   1728     WriteUseList(AI, VE, Stream);
   1729   for (Function::const_iterator BB = F->begin(), FE = F->end(); BB != FE;
   1730        ++BB) {
   1731     WriteUseList(BB, VE, Stream);
   1732     for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE;
   1733          ++II) {
   1734       WriteUseList(II, VE, Stream);
   1735       for (User::const_op_iterator OI = II->op_begin(), E = II->op_end();
   1736            OI != E; ++OI) {
   1737         if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
   1738             isa<InlineAsm>(*OI))
   1739           WriteUseList(*OI, VE, Stream);
   1740       }
   1741     }
   1742   }
   1743   VE.purgeFunction();
   1744 }
   1745 
   1746 // Emit use-lists.
   1747 static void WriteModuleUseLists(const Module *M, llvm_3_2::ValueEnumerator &VE,
   1748                                 BitstreamWriter &Stream) {
   1749   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
   1750 
   1751   // XXX: this modifies the module, but in a way that should never change the
   1752   // behavior of any pass or codegen in LLVM. The problem is that GVs may
   1753   // contain entries in the use_list that do not exist in the Module and are
   1754   // not stored in the .bc file.
   1755   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
   1756        I != E; ++I)
   1757     I->removeDeadConstantUsers();
   1758 
   1759   // Write the global variables.
   1760   for (Module::const_global_iterator GI = M->global_begin(),
   1761          GE = M->global_end(); GI != GE; ++GI) {
   1762     WriteUseList(GI, VE, Stream);
   1763 
   1764     // Write the global variable initializers.
   1765     if (GI->hasInitializer())
   1766       WriteUseList(GI->getInitializer(), VE, Stream);
   1767   }
   1768 
   1769   // Write the functions.
   1770   for (Module::const_iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
   1771     WriteUseList(FI, VE, Stream);
   1772     if (!FI->isDeclaration())
   1773       WriteFunctionUseList(FI, VE, Stream);
   1774   }
   1775 
   1776   // Write the aliases.
   1777   for (Module::const_alias_iterator AI = M->alias_begin(), AE = M->alias_end();
   1778        AI != AE; ++AI) {
   1779     WriteUseList(AI, VE, Stream);
   1780     WriteUseList(AI->getAliasee(), VE, Stream);
   1781   }
   1782 
   1783   Stream.ExitBlock();
   1784 }
   1785 
   1786 /// WriteModule - Emit the specified module to the bitstream.
   1787 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
   1788   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
   1789 
   1790   // Emit the version number if it is non-zero.
   1791   if (CurVersion) {
   1792     SmallVector<unsigned, 1> Vals;
   1793     Vals.push_back(CurVersion);
   1794     Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
   1795   }
   1796 
   1797   // Analyze the module, enumerating globals, functions, etc.
   1798   llvm_3_2::ValueEnumerator VE(M);
   1799 
   1800   // Emit blockinfo, which defines the standard abbreviations etc.
   1801   WriteBlockInfo(VE, Stream);
   1802 
   1803   // Emit information about parameter attributes.
   1804   WriteAttributeTable(VE, Stream);
   1805 
   1806   // Emit information describing all of the types in the module.
   1807   WriteTypeTable(VE, Stream);
   1808 
   1809   // Emit top-level description of module, including target triple, inline asm,
   1810   // descriptors for global variables, and function prototype info.
   1811   WriteModuleInfo(M, VE, Stream);
   1812 
   1813   // Emit constants.
   1814   WriteModuleConstants(VE, Stream);
   1815 
   1816   // Emit metadata.
   1817   WriteModuleMetadata(M, VE, Stream);
   1818 
   1819   // Emit metadata.
   1820   WriteModuleMetadataStore(M, Stream);
   1821 
   1822   // Emit names for globals/functions etc.
   1823   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
   1824 
   1825   // Emit use-lists.
   1826   if (EnablePreserveUseListOrdering)
   1827     WriteModuleUseLists(M, VE, Stream);
   1828 
   1829   // Emit function bodies.
   1830   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
   1831     if (!F->isDeclaration())
   1832       WriteFunction(*F, VE, Stream);
   1833 
   1834   Stream.ExitBlock();
   1835 }
   1836 
   1837 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
   1838 /// header and trailer to make it compatible with the system archiver.  To do
   1839 /// this we emit the following header, and then emit a trailer that pads the
   1840 /// file out to be a multiple of 16 bytes.
   1841 ///
   1842 /// struct bc_header {
   1843 ///   uint32_t Magic;         // 0x0B17C0DE
   1844 ///   uint32_t Version;       // Version, currently always 0.
   1845 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
   1846 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
   1847 ///   uint32_t CPUType;       // CPU specifier.
   1848 ///   ... potentially more later ...
   1849 /// };
   1850 enum {
   1851   DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
   1852   DarwinBCHeaderSize = 5*4
   1853 };
   1854 
   1855 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
   1856                                uint32_t &Position) {
   1857   Buffer[Position + 0] = (unsigned char) (Value >>  0);
   1858   Buffer[Position + 1] = (unsigned char) (Value >>  8);
   1859   Buffer[Position + 2] = (unsigned char) (Value >> 16);
   1860   Buffer[Position + 3] = (unsigned char) (Value >> 24);
   1861   Position += 4;
   1862 }
   1863 
   1864 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
   1865                                          const Triple &TT) {
   1866   unsigned CPUType = ~0U;
   1867 
   1868   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
   1869   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
   1870   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
   1871   // specific constants here because they are implicitly part of the Darwin ABI.
   1872   enum {
   1873     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
   1874     DARWIN_CPU_TYPE_X86        = 7,
   1875     DARWIN_CPU_TYPE_ARM        = 12,
   1876     DARWIN_CPU_TYPE_POWERPC    = 18
   1877   };
   1878 
   1879   Triple::ArchType Arch = TT.getArch();
   1880   if (Arch == Triple::x86_64)
   1881     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
   1882   else if (Arch == Triple::x86)
   1883     CPUType = DARWIN_CPU_TYPE_X86;
   1884   else if (Arch == Triple::ppc)
   1885     CPUType = DARWIN_CPU_TYPE_POWERPC;
   1886   else if (Arch == Triple::ppc64)
   1887     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
   1888   else if (Arch == Triple::arm || Arch == Triple::thumb)
   1889     CPUType = DARWIN_CPU_TYPE_ARM;
   1890 
   1891   // Traditional Bitcode starts after header.
   1892   assert(Buffer.size() >= DarwinBCHeaderSize &&
   1893          "Expected header size to be reserved");
   1894   unsigned BCOffset = DarwinBCHeaderSize;
   1895   unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
   1896 
   1897   // Write the magic and version.
   1898   unsigned Position = 0;
   1899   WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
   1900   WriteInt32ToBuffer(0          , Buffer, Position); // Version.
   1901   WriteInt32ToBuffer(BCOffset   , Buffer, Position);
   1902   WriteInt32ToBuffer(BCSize     , Buffer, Position);
   1903   WriteInt32ToBuffer(CPUType    , Buffer, Position);
   1904 
   1905   // If the file is not a multiple of 16 bytes, insert dummy padding.
   1906   while (Buffer.size() & 15)
   1907     Buffer.push_back(0);
   1908 }
   1909 
   1910 /// WriteBitcodeToFile - Write the specified module to the specified output
   1911 /// stream.
   1912 void llvm_3_2::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
   1913   SmallVector<char, 1024> Buffer;
   1914   Buffer.reserve(256*1024);
   1915 
   1916   // If this is darwin or another generic macho target, reserve space for the
   1917   // header.
   1918   Triple TT(M->getTargetTriple());
   1919   if (TT.isOSDarwin())
   1920     Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
   1921 
   1922   // Emit the module into the buffer.
   1923   {
   1924     BitstreamWriter Stream(Buffer);
   1925 
   1926     // Emit the file header.
   1927     Stream.Emit((unsigned)'B', 8);
   1928     Stream.Emit((unsigned)'C', 8);
   1929     Stream.Emit(0x0, 4);
   1930     Stream.Emit(0xC, 4);
   1931     Stream.Emit(0xE, 4);
   1932     Stream.Emit(0xD, 4);
   1933 
   1934     // Emit the module.
   1935     WriteModule(M, Stream);
   1936   }
   1937 
   1938   if (TT.isOSDarwin())
   1939     EmitDarwinBCHeaderAndTrailer(Buffer, TT);
   1940 
   1941   // Write the generated bitstream to "Out".
   1942   Out.write((char*)&Buffer.front(), Buffer.size());
   1943 }
   1944