LLVM API Documentation

BitcodeWriter.cpp

Go to the documentation of this file.
00001 //===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // Bitcode writer implementation.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Bitcode/ReaderWriter.h"
00015 #include "llvm/Bitcode/BitstreamWriter.h"
00016 #include "llvm/Bitcode/LLVMBitCodes.h"
00017 #include "ValueEnumerator.h"
00018 #include "llvm/Constants.h"
00019 #include "llvm/DerivedTypes.h"
00020 #include "llvm/InlineAsm.h"
00021 #include "llvm/Instructions.h"
00022 #include "llvm/Module.h"
00023 #include "llvm/TypeSymbolTable.h"
00024 #include "llvm/ValueSymbolTable.h"
00025 #include "llvm/Support/MathExtras.h"
00026 #include "llvm/Support/Streams.h"
00027 #include "llvm/Support/raw_ostream.h"
00028 #include "llvm/System/Program.h"
00029 using namespace llvm;
00030 
00031 /// These are manifest constants used by the bitcode writer. They do not need to
00032 /// be kept in sync with the reader, but need to be consistent within this file.
00033 enum {
00034   CurVersion = 0,
00035   
00036   // VALUE_SYMTAB_BLOCK abbrev id's.
00037   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
00038   VST_ENTRY_7_ABBREV,
00039   VST_ENTRY_6_ABBREV,
00040   VST_BBENTRY_6_ABBREV,
00041   
00042   // CONSTANTS_BLOCK abbrev id's.
00043   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
00044   CONSTANTS_INTEGER_ABBREV,
00045   CONSTANTS_CE_CAST_Abbrev,
00046   CONSTANTS_NULL_Abbrev,
00047   
00048   // FUNCTION_BLOCK abbrev id's.
00049   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
00050   FUNCTION_INST_BINOP_ABBREV,
00051   FUNCTION_INST_CAST_ABBREV,
00052   FUNCTION_INST_RET_VOID_ABBREV,
00053   FUNCTION_INST_RET_VAL_ABBREV,
00054   FUNCTION_INST_UNREACHABLE_ABBREV
00055 };
00056 
00057 
00058 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
00059   switch (Opcode) {
00060   default: assert(0 && "Unknown cast instruction!");
00061   case Instruction::Trunc   : return bitc::CAST_TRUNC;
00062   case Instruction::ZExt    : return bitc::CAST_ZEXT;
00063   case Instruction::SExt    : return bitc::CAST_SEXT;
00064   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
00065   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
00066   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
00067   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
00068   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
00069   case Instruction::FPExt   : return bitc::CAST_FPEXT;
00070   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
00071   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
00072   case Instruction::BitCast : return bitc::CAST_BITCAST;
00073   }
00074 }
00075 
00076 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
00077   switch (Opcode) {
00078   default: assert(0 && "Unknown binary instruction!");
00079   case Instruction::Add:  return bitc::BINOP_ADD;
00080   case Instruction::Sub:  return bitc::BINOP_SUB;
00081   case Instruction::Mul:  return bitc::BINOP_MUL;
00082   case Instruction::UDiv: return bitc::BINOP_UDIV;
00083   case Instruction::FDiv:
00084   case Instruction::SDiv: return bitc::BINOP_SDIV;
00085   case Instruction::URem: return bitc::BINOP_UREM;
00086   case Instruction::FRem:
00087   case Instruction::SRem: return bitc::BINOP_SREM;
00088   case Instruction::Shl:  return bitc::BINOP_SHL;
00089   case Instruction::LShr: return bitc::BINOP_LSHR;
00090   case Instruction::AShr: return bitc::BINOP_ASHR;
00091   case Instruction::And:  return bitc::BINOP_AND;
00092   case Instruction::Or:   return bitc::BINOP_OR;
00093   case Instruction::Xor:  return bitc::BINOP_XOR;
00094   }
00095 }
00096 
00097 
00098 
00099 static void WriteStringRecord(unsigned Code, const std::string &Str, 
00100                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
00101   SmallVector<unsigned, 64> Vals;
00102   
00103   // Code: [strchar x N]
00104   for (unsigned i = 0, e = Str.size(); i != e; ++i)
00105     Vals.push_back(Str[i]);
00106     
00107   // Emit the finished record.
00108   Stream.EmitRecord(Code, Vals, AbbrevToUse);
00109 }
00110 
00111 // Emit information about parameter attributes.
00112 static void WriteAttributeTable(const ValueEnumerator &VE, 
00113                                 BitstreamWriter &Stream) {
00114   const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
00115   if (Attrs.empty()) return;
00116   
00117   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
00118 
00119   SmallVector<uint64_t, 64> Record;
00120   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
00121     const AttrListPtr &A = Attrs[i];
00122     for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
00123       const AttributeWithIndex &PAWI = A.getSlot(i);
00124       Record.push_back(PAWI.Index);
00125 
00126       // FIXME: remove in LLVM 3.0
00127       // Store the alignment in the bitcode as a 16-bit raw value instead of a
00128       // 5-bit log2 encoded value. Shift the bits above the alignment up by
00129       // 11 bits.
00130       uint64_t FauxAttr = PAWI.Attrs & 0xffff;
00131       if (PAWI.Attrs & Attribute::Alignment)
00132         FauxAttr |= (1ull<<16)<<(((PAWI.Attrs & Attribute::Alignment)-1) >> 16);
00133       FauxAttr |= (PAWI.Attrs & (0x3FFull << 21)) << 11;
00134 
00135       Record.push_back(FauxAttr);
00136     }
00137     
00138     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
00139     Record.clear();
00140   }
00141   
00142   Stream.ExitBlock();
00143 }
00144 
00145 /// WriteTypeTable - Write out the type table for a module.
00146 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
00147   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
00148   
00149   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
00150   SmallVector<uint64_t, 64> TypeVals;
00151   
00152   // Abbrev for TYPE_CODE_POINTER.
00153   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
00154   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
00155   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00156                             Log2_32_Ceil(VE.getTypes().size()+1)));
00157   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
00158   unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
00159   
00160   // Abbrev for TYPE_CODE_FUNCTION.
00161   Abbv = new BitCodeAbbrev();
00162   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
00163   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
00164   Abbv->Add(BitCodeAbbrevOp(0));  // FIXME: DEAD value, remove in LLVM 3.0
00165   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00166   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00167                             Log2_32_Ceil(VE.getTypes().size()+1)));
00168   unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
00169   
00170   // Abbrev for TYPE_CODE_STRUCT.
00171   Abbv = new BitCodeAbbrev();
00172   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT));
00173   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
00174   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00175   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00176                             Log2_32_Ceil(VE.getTypes().size()+1)));
00177   unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
00178  
00179   // Abbrev for TYPE_CODE_ARRAY.
00180   Abbv = new BitCodeAbbrev();
00181   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
00182   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
00183   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00184                             Log2_32_Ceil(VE.getTypes().size()+1)));
00185   unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
00186   
00187   // Emit an entry count so the reader can reserve space.
00188   TypeVals.push_back(TypeList.size());
00189   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
00190   TypeVals.clear();
00191   
00192   // Loop over all of the types, emitting each in turn.
00193   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
00194     const Type *T = TypeList[i].first;
00195     int AbbrevToUse = 0;
00196     unsigned Code = 0;
00197     
00198     switch (T->getTypeID()) {
00199     default: assert(0 && "Unknown type!");
00200     case Type::VoidTyID:   Code = bitc::TYPE_CODE_VOID;   break;
00201     case Type::FloatTyID:  Code = bitc::TYPE_CODE_FLOAT;  break;
00202     case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
00203     case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
00204     case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
00205     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
00206     case Type::LabelTyID:  Code = bitc::TYPE_CODE_LABEL;  break;
00207     case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
00208     case Type::IntegerTyID:
00209       // INTEGER: [width]
00210       Code = bitc::TYPE_CODE_INTEGER;
00211       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
00212       break;
00213     case Type::PointerTyID: {
00214       const PointerType *PTy = cast<PointerType>(T);
00215       // POINTER: [pointee type, address space]
00216       Code = bitc::TYPE_CODE_POINTER;
00217       TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
00218       unsigned AddressSpace = PTy->getAddressSpace();
00219       TypeVals.push_back(AddressSpace);
00220       if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
00221       break;
00222     }
00223     case Type::FunctionTyID: {
00224       const FunctionType *FT = cast<FunctionType>(T);
00225       // FUNCTION: [isvararg, attrid, retty, paramty x N]
00226       Code = bitc::TYPE_CODE_FUNCTION;
00227       TypeVals.push_back(FT->isVarArg());
00228       TypeVals.push_back(0);  // FIXME: DEAD: remove in llvm 3.0
00229       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
00230       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
00231         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
00232       AbbrevToUse = FunctionAbbrev;
00233       break;
00234     }
00235     case Type::StructTyID: {
00236       const StructType *ST = cast<StructType>(T);
00237       // STRUCT: [ispacked, eltty x N]
00238       Code = bitc::TYPE_CODE_STRUCT;
00239       TypeVals.push_back(ST->isPacked());
00240       // Output all of the element types.
00241       for (StructType::element_iterator I = ST->element_begin(),
00242            E = ST->element_end(); I != E; ++I)
00243         TypeVals.push_back(VE.getTypeID(*I));
00244       AbbrevToUse = StructAbbrev;
00245       break;
00246     }
00247     case Type::ArrayTyID: {
00248       const ArrayType *AT = cast<ArrayType>(T);
00249       // ARRAY: [numelts, eltty]
00250       Code = bitc::TYPE_CODE_ARRAY;
00251       TypeVals.push_back(AT->getNumElements());
00252       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
00253       AbbrevToUse = ArrayAbbrev;
00254       break;
00255     }
00256     case Type::VectorTyID: {
00257       const VectorType *VT = cast<VectorType>(T);
00258       // VECTOR [numelts, eltty]
00259       Code = bitc::TYPE_CODE_VECTOR;
00260       TypeVals.push_back(VT->getNumElements());
00261       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
00262       break;
00263     }
00264     }
00265 
00266     // Emit the finished record.
00267     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
00268     TypeVals.clear();
00269   }
00270   
00271   Stream.ExitBlock();
00272 }
00273 
00274 static unsigned getEncodedLinkage(const GlobalValue *GV) {
00275   switch (GV->getLinkage()) {
00276   default: assert(0 && "Invalid linkage!");
00277   case GlobalValue::GhostLinkage:  // Map ghost linkage onto external.
00278   case GlobalValue::ExternalLinkage:     return 0;
00279   case GlobalValue::WeakLinkage:         return 1;
00280   case GlobalValue::AppendingLinkage:    return 2;
00281   case GlobalValue::InternalLinkage:     return 3;
00282   case GlobalValue::LinkOnceLinkage:     return 4;
00283   case GlobalValue::DLLImportLinkage:    return 5;
00284   case GlobalValue::DLLExportLinkage:    return 6;
00285   case GlobalValue::ExternalWeakLinkage: return 7;
00286   case GlobalValue::CommonLinkage:       return 8;
00287   case GlobalValue::PrivateLinkage:      return 9;
00288   }
00289 }
00290 
00291 static unsigned getEncodedVisibility(const GlobalValue *GV) {
00292   switch (GV->getVisibility()) {
00293   default: assert(0 && "Invalid visibility!");
00294   case GlobalValue::DefaultVisibility:   return 0;
00295   case GlobalValue::HiddenVisibility:    return 1;
00296   case GlobalValue::ProtectedVisibility: return 2;
00297   }
00298 }
00299 
00300 // Emit top-level description of module, including target triple, inline asm,
00301 // descriptors for global variables, and function prototype info.
00302 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
00303                             BitstreamWriter &Stream) {
00304   // Emit the list of dependent libraries for the Module.
00305   for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
00306     WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
00307 
00308   // Emit various pieces of data attached to a module.
00309   if (!M->getTargetTriple().empty())
00310     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
00311                       0/*TODO*/, Stream);
00312   if (!M->getDataLayout().empty())
00313     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
00314                       0/*TODO*/, Stream);
00315   if (!M->getModuleInlineAsm().empty())
00316     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
00317                       0/*TODO*/, Stream);
00318 
00319   // Emit information about sections and GC, computing how many there are. Also
00320   // compute the maximum alignment value.
00321   std::map<std::string, unsigned> SectionMap;
00322   std::map<std::string, unsigned> GCMap;
00323   unsigned MaxAlignment = 0;
00324   unsigned MaxGlobalType = 0;
00325   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
00326        GV != E; ++GV) {
00327     MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
00328     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
00329     
00330     if (!GV->hasSection()) continue;
00331     // Give section names unique ID's.
00332     unsigned &Entry = SectionMap[GV->getSection()];
00333     if (Entry != 0) continue;
00334     WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
00335                       0/*TODO*/, Stream);
00336     Entry = SectionMap.size();
00337   }
00338   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
00339     MaxAlignment = std::max(MaxAlignment, F->getAlignment());
00340     if (F->hasSection()) {
00341       // Give section names unique ID's.
00342       unsigned &Entry = SectionMap[F->getSection()];
00343       if (!Entry) {
00344         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
00345                           0/*TODO*/, Stream);
00346         Entry = SectionMap.size();
00347       }
00348     }
00349     if (F->hasGC()) {
00350       // Same for GC names.
00351       unsigned &Entry = GCMap[F->getGC()];
00352       if (!Entry) {
00353         WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
00354                           0/*TODO*/, Stream);
00355         Entry = GCMap.size();
00356       }
00357     }
00358   }
00359   
00360   // Emit abbrev for globals, now that we know # sections and max alignment.
00361   unsigned SimpleGVarAbbrev = 0;
00362   if (!M->global_empty()) { 
00363     // Add an abbrev for common globals with no visibility or thread localness.
00364     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
00365     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
00366     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00367                               Log2_32_Ceil(MaxGlobalType+1)));
00368     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));      // Constant.
00369     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));        // Initializer.
00370     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));      // Linkage.
00371     if (MaxAlignment == 0)                                      // Alignment.
00372       Abbv->Add(BitCodeAbbrevOp(0));
00373     else {
00374       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
00375       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00376                                Log2_32_Ceil(MaxEncAlignment+1)));
00377     }
00378     if (SectionMap.empty())                                    // Section.
00379       Abbv->Add(BitCodeAbbrevOp(0));
00380     else
00381       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00382                                Log2_32_Ceil(SectionMap.size()+1)));
00383     // Don't bother emitting vis + thread local.
00384     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
00385   }
00386   
00387   // Emit the global variable information.
00388   SmallVector<unsigned, 64> Vals;
00389   for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
00390        GV != E; ++GV) {
00391     unsigned AbbrevToUse = 0;
00392 
00393     // GLOBALVAR: [type, isconst, initid, 
00394     //             linkage, alignment, section, visibility, threadlocal]
00395     Vals.push_back(VE.getTypeID(GV->getType()));
00396     Vals.push_back(GV->isConstant());
00397     Vals.push_back(GV->isDeclaration() ? 0 :
00398                    (VE.getValueID(GV->getInitializer()) + 1));
00399     Vals.push_back(getEncodedLinkage(GV));
00400     Vals.push_back(Log2_32(GV->getAlignment())+1);
00401     Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
00402     if (GV->isThreadLocal() || 
00403         GV->getVisibility() != GlobalValue::DefaultVisibility) {
00404       Vals.push_back(getEncodedVisibility(GV));
00405       Vals.push_back(GV->isThreadLocal());
00406     } else {
00407       AbbrevToUse = SimpleGVarAbbrev;
00408     }
00409     
00410     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
00411     Vals.clear();
00412   }
00413 
00414   // Emit the function proto information.
00415   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
00416     // FUNCTION:  [type, callingconv, isproto, paramattr,
00417     //             linkage, alignment, section, visibility, gc]
00418     Vals.push_back(VE.getTypeID(F->getType()));
00419     Vals.push_back(F->getCallingConv());
00420     Vals.push_back(F->isDeclaration());
00421     Vals.push_back(getEncodedLinkage(F));
00422     Vals.push_back(VE.getAttributeID(F->getAttributes()));
00423     Vals.push_back(Log2_32(F->getAlignment())+1);
00424     Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
00425     Vals.push_back(getEncodedVisibility(F));
00426     Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
00427     
00428     unsigned AbbrevToUse = 0;
00429     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
00430     Vals.clear();
00431   }
00432   
00433   
00434   // Emit the alias information.
00435   for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
00436        AI != E; ++AI) {
00437     Vals.push_back(VE.getTypeID(AI->getType()));
00438     Vals.push_back(VE.getValueID(AI->getAliasee()));
00439     Vals.push_back(getEncodedLinkage(AI));
00440     Vals.push_back(getEncodedVisibility(AI));
00441     unsigned AbbrevToUse = 0;
00442     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
00443     Vals.clear();
00444   }
00445 }
00446 
00447 
00448 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
00449                            const ValueEnumerator &VE,
00450                            BitstreamWriter &Stream, bool isGlobal) {
00451   if (FirstVal == LastVal) return;
00452   
00453   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
00454 
00455   unsigned AggregateAbbrev = 0;
00456   unsigned String8Abbrev = 0;
00457   unsigned CString7Abbrev = 0;
00458   unsigned CString6Abbrev = 0;
00459   // If this is a constant pool for the module, emit module-specific abbrevs.
00460   if (isGlobal) {
00461     // Abbrev for CST_CODE_AGGREGATE.
00462     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
00463     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
00464     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00465     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
00466     AggregateAbbrev = Stream.EmitAbbrev(Abbv);
00467 
00468     // Abbrev for CST_CODE_STRING.
00469     Abbv = new BitCodeAbbrev();
00470     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
00471     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00472     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
00473     String8Abbrev = Stream.EmitAbbrev(Abbv);
00474     // Abbrev for CST_CODE_CSTRING.
00475     Abbv = new BitCodeAbbrev();
00476     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
00477     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00478     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
00479     CString7Abbrev = Stream.EmitAbbrev(Abbv);
00480     // Abbrev for CST_CODE_CSTRING.
00481     Abbv = new BitCodeAbbrev();
00482     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
00483     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00484     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
00485     CString6Abbrev = Stream.EmitAbbrev(Abbv);
00486   }  
00487   
00488   SmallVector<uint64_t, 64> Record;
00489 
00490   const ValueEnumerator::ValueList &Vals = VE.getValues();
00491   const Type *LastTy = 0;
00492   for (unsigned i = FirstVal; i != LastVal; ++i) {
00493     const Value *V = Vals[i].first;
00494     // If we need to switch types, do so now.
00495     if (V->getType() != LastTy) {
00496       LastTy = V->getType();
00497       Record.push_back(VE.getTypeID(LastTy));
00498       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
00499                         CONSTANTS_SETTYPE_ABBREV);
00500       Record.clear();
00501     }
00502     
00503     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
00504       Record.push_back(unsigned(IA->hasSideEffects()));
00505       
00506       // Add the asm string.
00507       const std::string &AsmStr = IA->getAsmString();
00508       Record.push_back(AsmStr.size());
00509       for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
00510         Record.push_back(AsmStr[i]);
00511       
00512       // Add the constraint string.
00513       const std::string &ConstraintStr = IA->getConstraintString();
00514       Record.push_back(ConstraintStr.size());
00515       for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
00516         Record.push_back(ConstraintStr[i]);
00517       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
00518       Record.clear();
00519       continue;
00520     }
00521     const Constant *C = cast<Constant>(V);
00522     unsigned Code = -1U;
00523     unsigned AbbrevToUse = 0;
00524     if (C->isNullValue()) {
00525       Code = bitc::CST_CODE_NULL;
00526     } else if (isa<UndefValue>(C)) {
00527       Code = bitc::CST_CODE_UNDEF;
00528     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
00529       if (IV->getBitWidth() <= 64) {
00530         int64_t V = IV->getSExtValue();
00531         if (V >= 0)
00532           Record.push_back(V << 1);
00533         else
00534           Record.push_back((-V << 1) | 1);
00535         Code = bitc::CST_CODE_INTEGER;
00536         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
00537       } else {                             // Wide integers, > 64 bits in size.
00538         // We have an arbitrary precision integer value to write whose 
00539         // bit width is > 64. However, in canonical unsigned integer 
00540         // format it is likely that the high bits are going to be zero.
00541         // So, we only write the number of active words.
00542         unsigned NWords = IV->getValue().getActiveWords(); 
00543         const uint64_t *RawWords = IV->getValue().getRawData();
00544         for (unsigned i = 0; i != NWords; ++i) {
00545           int64_t V = RawWords[i];
00546           if (V >= 0)
00547             Record.push_back(V << 1);
00548           else
00549             Record.push_back((-V << 1) | 1);
00550         }
00551         Code = bitc::CST_CODE_WIDE_INTEGER;
00552       }
00553     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
00554       Code = bitc::CST_CODE_FLOAT;
00555       const Type *Ty = CFP->getType();
00556       if (Ty == Type::FloatTy || Ty == Type::DoubleTy) {
00557         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
00558       } else if (Ty == Type::X86_FP80Ty) {
00559         // api needed to prevent premature destruction
00560         APInt api = CFP->getValueAPF().bitcastToAPInt();
00561         const uint64_t *p = api.getRawData();
00562         Record.push_back(p[0]);
00563         Record.push_back((uint16_t)p[1]);
00564       } else if (Ty == Type::FP128Ty || Ty == Type::PPC_FP128Ty) {
00565         APInt api = CFP->getValueAPF().bitcastToAPInt();
00566         const uint64_t *p = api.getRawData();
00567         Record.push_back(p[0]);
00568         Record.push_back(p[1]);
00569       } else {
00570         assert (0 && "Unknown FP type!");
00571       }
00572     } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
00573       // Emit constant strings specially.
00574       unsigned NumOps = C->getNumOperands();
00575       // If this is a null-terminated string, use the denser CSTRING encoding.
00576       if (C->getOperand(NumOps-1)->isNullValue()) {
00577         Code = bitc::CST_CODE_CSTRING;
00578         --NumOps;  // Don't encode the null, which isn't allowed by char6.
00579       } else {
00580         Code = bitc::CST_CODE_STRING;
00581         AbbrevToUse = String8Abbrev;
00582       }
00583       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
00584       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
00585       for (unsigned i = 0; i != NumOps; ++i) {
00586         unsigned char V = cast<ConstantInt>(C->getOperand(i))->getZExtValue();
00587         Record.push_back(V);
00588         isCStr7 &= (V & 128) == 0;
00589         if (isCStrChar6) 
00590           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
00591       }
00592       
00593       if (isCStrChar6)
00594         AbbrevToUse = CString6Abbrev;
00595       else if (isCStr7)
00596         AbbrevToUse = CString7Abbrev;
00597     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
00598                isa<ConstantVector>(V)) {
00599       Code = bitc::CST_CODE_AGGREGATE;
00600       for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
00601         Record.push_back(VE.getValueID(C->getOperand(i)));
00602       AbbrevToUse = AggregateAbbrev;
00603     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
00604       switch (CE->getOpcode()) {
00605       default:
00606         if (Instruction::isCast(CE->getOpcode())) {
00607           Code = bitc::CST_CODE_CE_CAST;
00608           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
00609           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
00610           Record.push_back(VE.getValueID(C->getOperand(0)));
00611           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
00612         } else {
00613           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
00614           Code = bitc::CST_CODE_CE_BINOP;
00615           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
00616           Record.push_back(VE.getValueID(C->getOperand(0)));
00617           Record.push_back(VE.getValueID(C->getOperand(1)));
00618         }
00619         break;
00620       case Instruction::GetElementPtr:
00621         Code = bitc::CST_CODE_CE_GEP;
00622         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
00623           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
00624           Record.push_back(VE.getValueID(C->getOperand(i)));
00625         }
00626         break;
00627       case Instruction::Select:
00628         Code = bitc::CST_CODE_CE_SELECT;
00629         Record.push_back(VE.getValueID(C->getOperand(0)));
00630         Record.push_back(VE.getValueID(C->getOperand(1)));
00631         Record.push_back(VE.getValueID(C->getOperand(2)));
00632         break;
00633       case Instruction::ExtractElement:
00634         Code = bitc::CST_CODE_CE_EXTRACTELT;
00635         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
00636         Record.push_back(VE.getValueID(C->getOperand(0)));
00637         Record.push_back(VE.getValueID(C->getOperand(1)));
00638         break;
00639       case Instruction::InsertElement:
00640         Code = bitc::CST_CODE_CE_INSERTELT;
00641         Record.push_back(VE.getValueID(C->getOperand(0)));
00642         Record.push_back(VE.getValueID(C->getOperand(1)));
00643         Record.push_back(VE.getValueID(C->getOperand(2)));
00644         break;
00645       case Instruction::ShuffleVector:
00646         Code = bitc::CST_CODE_CE_SHUFFLEVEC;
00647         Record.push_back(VE.getValueID(C->getOperand(0)));
00648         Record.push_back(VE.getValueID(C->getOperand(1)));
00649         Record.push_back(VE.getValueID(C->getOperand(2)));
00650         break;
00651       case Instruction::ICmp:
00652       case Instruction::FCmp:
00653       case Instruction::VICmp:
00654       case Instruction::VFCmp:
00655         if (isa<VectorType>(C->getOperand(0)->getType())
00656             && (CE->getOpcode() == Instruction::ICmp
00657                 || CE->getOpcode() == Instruction::FCmp)) {
00658           // compare returning vector of Int1Ty
00659           assert(0 && "Unsupported constant!");
00660         } else {
00661           Code = bitc::CST_CODE_CE_CMP;
00662         }
00663         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
00664         Record.push_back(VE.getValueID(C->getOperand(0)));
00665         Record.push_back(VE.getValueID(C->getOperand(1)));
00666         Record.push_back(CE->getPredicate());
00667         break;
00668       }
00669     } else {
00670       assert(0 && "Unknown constant!");
00671     }
00672     Stream.EmitRecord(Code, Record, AbbrevToUse);
00673     Record.clear();
00674   }
00675 
00676   Stream.ExitBlock();
00677 }
00678 
00679 static void WriteModuleConstants(const ValueEnumerator &VE,
00680                                  BitstreamWriter &Stream) {
00681   const ValueEnumerator::ValueList &Vals = VE.getValues();
00682   
00683   // Find the first constant to emit, which is the first non-globalvalue value.
00684   // We know globalvalues have been emitted by WriteModuleInfo.
00685   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
00686     if (!isa<GlobalValue>(Vals[i].first)) {
00687       WriteConstants(i, Vals.size(), VE, Stream, true);
00688       return;
00689     }
00690   }
00691 }
00692 
00693 /// PushValueAndType - The file has to encode both the value and type id for
00694 /// many values, because we need to know what type to create for forward
00695 /// references.  However, most operands are not forward references, so this type
00696 /// field is not needed.
00697 ///
00698 /// This function adds V's value ID to Vals.  If the value ID is higher than the
00699 /// instruction ID, then it is a forward reference, and it also includes the
00700 /// type ID.
00701 static bool PushValueAndType(const Value *V, unsigned InstID,
00702                              SmallVector<unsigned, 64> &Vals, 
00703                              ValueEnumerator &VE) {
00704   unsigned ValID = VE.getValueID(V);
00705   Vals.push_back(ValID);
00706   if (ValID >= InstID) {
00707     Vals.push_back(VE.getTypeID(V->getType()));
00708     return true;
00709   }
00710   return false;
00711 }
00712 
00713 /// WriteInstruction - Emit an instruction to the specified stream.
00714 static void WriteInstruction(const Instruction &I, unsigned InstID,
00715                              ValueEnumerator &VE, BitstreamWriter &Stream,
00716                              SmallVector<unsigned, 64> &Vals) {
00717   unsigned Code = 0;
00718   unsigned AbbrevToUse = 0;
00719   switch (I.getOpcode()) {
00720   default:
00721     if (Instruction::isCast(I.getOpcode())) {
00722       Code = bitc::FUNC_CODE_INST_CAST;
00723       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
00724         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
00725       Vals.push_back(VE.getTypeID(I.getType()));
00726       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
00727     } else {
00728       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
00729       Code = bitc::FUNC_CODE_INST_BINOP;
00730       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
00731         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
00732       Vals.push_back(VE.getValueID(I.getOperand(1)));
00733       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
00734     }
00735     break;
00736 
00737   case Instruction::GetElementPtr:
00738     Code = bitc::FUNC_CODE_INST_GEP;
00739     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
00740       PushValueAndType(I.getOperand(i), InstID, Vals, VE);
00741     break;
00742   case Instruction::ExtractValue: {
00743     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
00744     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
00745     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
00746     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
00747       Vals.push_back(*i);
00748     break;
00749   }
00750   case Instruction::InsertValue: {
00751     Code = bitc::FUNC_CODE_INST_INSERTVAL;
00752     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
00753     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
00754     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
00755     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
00756       Vals.push_back(*i);
00757     break;
00758   }
00759   case Instruction::Select:
00760     Code = bitc::FUNC_CODE_INST_VSELECT;
00761     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
00762     Vals.push_back(VE.getValueID(I.getOperand(2)));
00763     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
00764     break;
00765   case Instruction::ExtractElement:
00766     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
00767     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
00768     Vals.push_back(VE.getValueID(I.getOperand(1)));
00769     break;
00770   case Instruction::InsertElement:
00771     Code = bitc::FUNC_CODE_INST_INSERTELT;
00772     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
00773     Vals.push_back(VE.getValueID(I.getOperand(1)));
00774     Vals.push_back(VE.getValueID(I.getOperand(2)));
00775     break;
00776   case Instruction::ShuffleVector:
00777     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
00778     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
00779     Vals.push_back(VE.getValueID(I.getOperand(1)));
00780     Vals.push_back(VE.getValueID(I.getOperand(2)));
00781     break;
00782   case Instruction::ICmp:
00783   case Instruction::FCmp:
00784   case Instruction::VICmp:
00785   case Instruction::VFCmp:
00786     if (I.getOpcode() == Instruction::ICmp
00787         || I.getOpcode() == Instruction::FCmp) {
00788       // compare returning Int1Ty or vector of Int1Ty
00789       Code = bitc::FUNC_CODE_INST_CMP2;
00790     } else {
00791       Code = bitc::FUNC_CODE_INST_CMP;
00792     }
00793     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
00794     Vals.push_back(VE.getValueID(I.getOperand(1)));
00795     Vals.push_back(cast<CmpInst>(I).getPredicate());
00796     break;
00797 
00798   case Instruction::Ret: 
00799     {
00800       Code = bitc::FUNC_CODE_INST_RET;
00801       unsigned NumOperands = I.getNumOperands();
00802       if (NumOperands == 0)
00803         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
00804       else if (NumOperands == 1) {
00805         if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
00806           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
00807       } else {
00808         for (unsigned i = 0, e = NumOperands; i != e; ++i)
00809           PushValueAndType(I.getOperand(i), InstID, Vals, VE);
00810       }
00811     }
00812     break;
00813   case Instruction::Br:
00814     {
00815       Code = bitc::FUNC_CODE_INST_BR;
00816       BranchInst &II(cast<BranchInst>(I));
00817       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
00818       if (II.isConditional()) {
00819         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
00820         Vals.push_back(VE.getValueID(II.getCondition()));
00821       }
00822     }
00823     break;
00824   case Instruction::Switch:
00825     Code = bitc::FUNC_CODE_INST_SWITCH;
00826     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
00827     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
00828       Vals.push_back(VE.getValueID(I.getOperand(i)));
00829     break;
00830   case Instruction::Invoke: {
00831     const InvokeInst *II = cast<InvokeInst>(&I);
00832     const Value *Callee(II->getCalledValue());
00833     const PointerType *PTy = cast<PointerType>(Callee->getType());
00834     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
00835     Code = bitc::FUNC_CODE_INST_INVOKE;
00836     
00837     Vals.push_back(VE.getAttributeID(II->getAttributes()));
00838     Vals.push_back(II->getCallingConv());
00839     Vals.push_back(VE.getValueID(II->getNormalDest()));
00840     Vals.push_back(VE.getValueID(II->getUnwindDest()));
00841     PushValueAndType(Callee, InstID, Vals, VE);
00842     
00843     // Emit value #'s for the fixed parameters.
00844     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
00845       Vals.push_back(VE.getValueID(I.getOperand(i+3)));  // fixed param.
00846 
00847     // Emit type/value pairs for varargs params.
00848     if (FTy->isVarArg()) {
00849       for (unsigned i = 3+FTy->getNumParams(), e = I.getNumOperands();
00850            i != e; ++i)
00851         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
00852     }
00853     break;
00854   }
00855   case Instruction::Unwind:
00856     Code = bitc::FUNC_CODE_INST_UNWIND;
00857     break;
00858   case Instruction::Unreachable:
00859     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
00860     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
00861     break;
00862   
00863   case Instruction::PHI:
00864     Code = bitc::FUNC_CODE_INST_PHI;
00865     Vals.push_back(VE.getTypeID(I.getType()));
00866     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
00867       Vals.push_back(VE.getValueID(I.getOperand(i)));
00868     break;
00869     
00870   case Instruction::Malloc:
00871     Code = bitc::FUNC_CODE_INST_MALLOC;
00872     Vals.push_back(VE.getTypeID(I.getType()));
00873     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
00874     Vals.push_back(Log2_32(cast<MallocInst>(I).getAlignment())+1);
00875     break;
00876     
00877   case Instruction::Free:
00878     Code = bitc::FUNC_CODE_INST_FREE;
00879     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
00880     break;
00881     
00882   case Instruction::Alloca:
00883     Code = bitc::FUNC_CODE_INST_ALLOCA;
00884     Vals.push_back(VE.getTypeID(I.getType()));
00885     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
00886     Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
00887     break;
00888     
00889   case Instruction::Load:
00890     Code = bitc::FUNC_CODE_INST_LOAD;
00891     if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
00892       AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
00893       
00894     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
00895     Vals.push_back(cast<LoadInst>(I).isVolatile());
00896     break;
00897   case Instruction::Store:
00898     Code = bitc::FUNC_CODE_INST_STORE2;
00899     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
00900     Vals.push_back(VE.getValueID(I.getOperand(0)));       // val.
00901     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
00902     Vals.push_back(cast<StoreInst>(I).isVolatile());
00903     break;
00904   case Instruction::Call: {
00905     const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
00906     const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
00907 
00908     Code = bitc::FUNC_CODE_INST_CALL;
00909     
00910     const CallInst *CI = cast<CallInst>(&I);
00911     Vals.push_back(VE.getAttributeID(CI->getAttributes()));
00912     Vals.push_back((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
00913     PushValueAndType(CI->getOperand(0), InstID, Vals, VE);  // Callee
00914     
00915     // Emit value #'s for the fixed parameters.
00916     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
00917       Vals.push_back(VE.getValueID(I.getOperand(i+1)));  // fixed param.
00918       
00919     // Emit type/value pairs for varargs params.
00920     if (FTy->isVarArg()) {
00921       unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
00922       for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
00923            i != e; ++i)
00924         PushValueAndType(I.getOperand(i), InstID, Vals, VE);  // varargs
00925     }
00926     break;
00927   }
00928   case Instruction::VAArg:
00929     Code = bitc::FUNC_CODE_INST_VAARG;
00930     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
00931     Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
00932     Vals.push_back(VE.getTypeID(I.getType())); // restype.
00933     break;
00934   }
00935   
00936   Stream.EmitRecord(Code, Vals, AbbrevToUse);
00937   Vals.clear();
00938 }
00939 
00940 // Emit names for globals/functions etc.
00941 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
00942                                   const ValueEnumerator &VE,
00943                                   BitstreamWriter &Stream) {
00944   if (VST.empty()) return;
00945   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
00946 
00947   // FIXME: Set up the abbrev, we know how many values there are!
00948   // FIXME: We know if the type names can use 7-bit ascii.
00949   SmallVector<unsigned, 64> NameVals;
00950   
00951   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
00952        SI != SE; ++SI) {
00953     
00954     const ValueName &Name = *SI;
00955     
00956     // Figure out the encoding to use for the name.
00957     bool is7Bit = true;
00958     bool isChar6 = true;
00959     for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
00960          C != E; ++C) {
00961       if (isChar6) 
00962         isChar6 = BitCodeAbbrevOp::isChar6(*C);
00963       if ((unsigned char)*C & 128) {
00964         is7Bit = false;
00965         break;  // don't bother scanning the rest.
00966       }
00967     }
00968     
00969     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
00970     
00971     // VST_ENTRY:   [valueid, namechar x N]
00972     // VST_BBENTRY: [bbid, namechar x N]
00973     unsigned Code;
00974     if (isa<BasicBlock>(SI->getValue())) {
00975       Code = bitc::VST_CODE_BBENTRY;
00976       if (isChar6)
00977         AbbrevToUse = VST_BBENTRY_6_ABBREV;
00978     } else {
00979       Code = bitc::VST_CODE_ENTRY;
00980       if (isChar6)
00981         AbbrevToUse = VST_ENTRY_6_ABBREV;
00982       else if (is7Bit)
00983         AbbrevToUse = VST_ENTRY_7_ABBREV;
00984     }
00985     
00986     NameVals.push_back(VE.getValueID(SI->getValue()));
00987     for (const char *P = Name.getKeyData(),
00988          *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
00989       NameVals.push_back((unsigned char)*P);
00990     
00991     // Emit the finished record.
00992     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
00993     NameVals.clear();
00994   }
00995   Stream.ExitBlock();
00996 }
00997 
00998 /// WriteFunction - Emit a function body to the module stream.
00999 static void WriteFunction(const Function &F, ValueEnumerator &VE, 
01000                           BitstreamWriter &Stream) {
01001   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
01002   VE.incorporateFunction(F);
01003 
01004   SmallVector<unsigned, 64> Vals;
01005   
01006   // Emit the number of basic blocks, so the reader can create them ahead of
01007   // time.
01008   Vals.push_back(VE.getBasicBlocks().size());
01009   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
01010   Vals.clear();
01011   
01012   // If there are function-local constants, emit them now.
01013   unsigned CstStart, CstEnd;
01014   VE.getFunctionConstantRange(CstStart, CstEnd);
01015   WriteConstants(CstStart, CstEnd, VE, Stream, false);
01016   
01017   // Keep a running idea of what the instruction ID is. 
01018   unsigned InstID = CstEnd;
01019   
01020   // Finally, emit all the instructions, in order.
01021   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
01022     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
01023          I != E; ++I) {
01024       WriteInstruction(*I, InstID, VE, Stream, Vals);
01025       if (I->getType() != Type::VoidTy)
01026         ++InstID;
01027     }
01028   
01029   // Emit names for all the instructions etc.
01030   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
01031     
01032   VE.purgeFunction();
01033   Stream.ExitBlock();
01034 }
01035 
01036 /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
01037 static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
01038                                  const ValueEnumerator &VE,
01039                                  BitstreamWriter &Stream) {
01040   if (TST.empty()) return;
01041   
01042   Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
01043   
01044   // 7-bit fixed width VST_CODE_ENTRY strings.
01045   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01046   Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
01047   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
01048                             Log2_32_Ceil(VE.getTypes().size()+1)));
01049   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01050   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
01051   unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
01052   
01053   SmallVector<unsigned, 64> NameVals;
01054   
01055   for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 
01056        TI != TE; ++TI) {
01057     // TST_ENTRY: [typeid, namechar x N]
01058     NameVals.push_back(VE.getTypeID(TI->second));
01059     
01060     const std::string &Str = TI->first;
01061     bool is7Bit = true;
01062     for (unsigned i = 0, e = Str.size(); i != e; ++i) {
01063       NameVals.push_back((unsigned char)Str[i]);
01064       if (Str[i] & 128)
01065         is7Bit = false;
01066     }
01067     
01068     // Emit the finished record.
01069     Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
01070     NameVals.clear();
01071   }
01072   
01073   Stream.ExitBlock();
01074 }
01075 
01076 // Emit blockinfo, which defines the standard abbreviations etc.
01077 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
01078   // We only want to emit block info records for blocks that have multiple
01079   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.  Other
01080   // blocks can defined their abbrevs inline.
01081   Stream.EnterBlockInfoBlock(2);
01082   
01083   { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
01084     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01085     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
01086     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01087     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01088     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
01089     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 
01090                                    Abbv) != VST_ENTRY_8_ABBREV)
01091       assert(0 && "Unexpected abbrev ordering!");
01092   }
01093   
01094   { // 7-bit fixed width VST_ENTRY strings.
01095     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01096     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
01097     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01098     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01099     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
01100     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
01101                                    Abbv) != VST_ENTRY_7_ABBREV)
01102       assert(0 && "Unexpected abbrev ordering!");
01103   }
01104   { // 6-bit char6 VST_ENTRY strings.
01105     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01106     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
01107     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01108     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01109     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
01110     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
01111                                    Abbv) != VST_ENTRY_6_ABBREV)
01112       assert(0 && "Unexpected abbrev ordering!");
01113   }
01114   { // 6-bit char6 VST_BBENTRY strings.
01115     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01116     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
01117     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01118     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01119     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
01120     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
01121                                    Abbv) != VST_BBENTRY_6_ABBREV)
01122       assert(0 && "Unexpected abbrev ordering!");
01123   }
01124   
01125   
01126   
01127   { // SETTYPE abbrev for CONSTANTS_BLOCK.
01128     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01129     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
01130     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
01131                               Log2_32_Ceil(VE.getTypes().size()+1)));
01132     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
01133                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
01134       assert(0 && "Unexpected abbrev ordering!");
01135   }
01136   
01137   { // INTEGER abbrev for CONSTANTS_BLOCK.
01138     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01139     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
01140     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01141     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
01142                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
01143       assert(0 && "Unexpected abbrev ordering!");
01144   }
01145   
01146   { // CE_CAST abbrev for CONSTANTS_BLOCK.
01147     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01148     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
01149     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
01150     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
01151                               Log2_32_Ceil(VE.getTypes().size()+1)));
01152     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
01153 
01154     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
01155                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
01156       assert(0 && "Unexpected abbrev ordering!");
01157   }
01158   { // NULL abbrev for CONSTANTS_BLOCK.
01159     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01160     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
01161     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
01162                                    Abbv) != CONSTANTS_NULL_Abbrev)
01163       assert(0 && "Unexpected abbrev ordering!");
01164   }
01165   
01166   // FIXME: This should only use space for first class types!
01167  
01168   { // INST_LOAD abbrev for FUNCTION_BLOCK.
01169     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01170     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
01171     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
01172     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
01173     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
01174     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01175                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
01176       assert(0 && "Unexpected abbrev ordering!");
01177   }
01178   { // INST_BINOP abbrev for FUNCTION_BLOCK.
01179     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01180     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
01181     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
01182     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
01183     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
01184     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01185                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
01186       assert(0 && "Unexpected abbrev ordering!");
01187   }
01188   { // INST_CAST abbrev for FUNCTION_BLOCK.
01189     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01190     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
01191     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
01192     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
01193                               Log2_32_Ceil(VE.getTypes().size()+1)));
01194     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
01195     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01196                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
01197       assert(0 && "Unexpected abbrev ordering!");
01198   }
01199   
01200   { // INST_RET abbrev for FUNCTION_BLOCK.
01201     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01202     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
01203     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01204                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
01205       assert(0 && "Unexpected abbrev ordering!");
01206   }
01207   { // INST_RET abbrev for FUNCTION_BLOCK.
01208     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01209     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
01210     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
01211     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01212                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
01213       assert(0 && "Unexpected abbrev ordering!");
01214   }
01215   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
01216     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01217     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
01218     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01219                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
01220       assert(0 && "Unexpected abbrev ordering!");
01221   }
01222   
01223   Stream.ExitBlock();
01224 }
01225 
01226 
01227 /// WriteModule - Emit the specified module to the bitstream.
01228 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
01229   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
01230   
01231   // Emit the version number if it is non-zero.
01232   if (CurVersion) {
01233     SmallVector<unsigned, 1> Vals;
01234     Vals.push_back(CurVersion);
01235     Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
01236   }
01237   
01238   // Analyze the module, enumerating globals, functions, etc.
01239   ValueEnumerator VE(M);
01240 
01241   // Emit blockinfo, which defines the standard abbreviations etc.
01242   WriteBlockInfo(VE, Stream);
01243   
01244   // Emit information about parameter attributes.
01245   WriteAttributeTable(VE, Stream);
01246   
01247   // Emit information describing all of the types in the module.
01248   WriteTypeTable(VE, Stream);
01249   
01250   // Emit top-level description of module, including target triple, inline asm,
01251   // descriptors for global variables, and function prototype info.
01252   WriteModuleInfo(M, VE, Stream);
01253   
01254   // Emit constants.
01255   WriteModuleConstants(VE, Stream);
01256   
01257   // If we have any aggregate values in the value table, purge them - these can
01258   // only be used to initialize global variables.  Doing so makes the value
01259   // namespace smaller for code in functions.
01260   int NumNonAggregates = VE.PurgeAggregateValues();
01261   if (NumNonAggregates != -1) {
01262     SmallVector<unsigned, 1> Vals;
01263     Vals.push_back(NumNonAggregates);
01264     Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals);
01265   }
01266   
01267   // Emit function bodies.
01268   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
01269     if (!I->isDeclaration())
01270       WriteFunction(*I, VE, Stream);
01271   
01272   // Emit the type symbol table information.
01273   WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
01274   
01275   // Emit names for globals/functions etc.
01276   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
01277   
01278   Stream.ExitBlock();
01279 }
01280 
01281 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
01282 /// header and trailer to make it compatible with the system archiver.  To do
01283 /// this we emit the following header, and then emit a trailer that pads the
01284 /// file out to be a multiple of 16 bytes.
01285 /// 
01286 /// struct bc_header {
01287 ///   uint32_t Magic;         // 0x0B17C0DE
01288 ///   uint32_t Version;       // Version, currently always 0.
01289 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
01290 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
01291 ///   uint32_t CPUType;       // CPU specifier.
01292 ///   ... potentially more later ...
01293 /// };
01294 enum {
01295   DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
01296   DarwinBCHeaderSize = 5*4
01297 };
01298 
01299 static void EmitDarwinBCHeader(BitstreamWriter &Stream,
01300                                const std::string &TT) {
01301   unsigned CPUType = ~0U;
01302   
01303   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*.  The CPUType is a
01304   // magic number from /usr/include/mach/machine.h.  It is ok to reproduce the
01305   // specific constants here because they are implicitly part of the Darwin ABI.
01306   enum {
01307     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
01308     DARWIN_CPU_TYPE_X86        = 7,
01309     DARWIN_CPU_TYPE_POWERPC    = 18
01310   };
01311   
01312   if (TT.find("x86_64-") == 0)
01313     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
01314   else if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&
01315            TT[4] == '-' && TT[1] - '3' < 6)
01316     CPUType = DARWIN_CPU_TYPE_X86;
01317   else if (TT.find("powerpc-") == 0)
01318     CPUType = DARWIN_CPU_TYPE_POWERPC;
01319   else if (TT.find("powerpc64-") == 0)
01320     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
01321   
01322   // Traditional Bitcode starts after header.
01323   unsigned BCOffset = DarwinBCHeaderSize;
01324   
01325   Stream.Emit(0x0B17C0DE, 32);
01326   Stream.Emit(0         , 32);  // Version.
01327   Stream.Emit(BCOffset  , 32);
01328   Stream.Emit(0         , 32);  // Filled in later.
01329   Stream.Emit(CPUType   , 32);
01330 }
01331 
01332 /// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and
01333 /// finalize the header.
01334 static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) {
01335   // Update the size field in the header.
01336   Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize);
01337   
01338   // If the file is not a multiple of 16 bytes, insert dummy padding.
01339   while (BufferSize & 15) {
01340     Stream.Emit(0, 8);
01341     ++BufferSize;
01342   }
01343 }
01344 
01345 
01346 /// WriteBitcodeToFile - Write the specified module to the specified output
01347 /// stream.
01348 void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) {
01349   raw_os_ostream RawOut(Out);
01350   // If writing to stdout, set binary mode.
01351   if (llvm::cout == Out)
01352     sys::Program::ChangeStdoutToBinary();
01353   WriteBitcodeToFile(M, RawOut);
01354 }
01355 
01356 /// WriteBitcodeToFile - Write the specified module to the specified output
01357 /// stream.
01358 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
01359   std::vector<unsigned char> Buffer;
01360   BitstreamWriter Stream(Buffer);
01361   
01362   Buffer.reserve(256*1024);
01363 
01364   WriteBitcodeToStream( M, Stream );
01365   
01366   // If writing to stdout, set binary mode.
01367   if (&llvm::outs() == &Out)
01368     sys::Program::ChangeStdoutToBinary();
01369 
01370   // Write the generated bitstream to "Out".
01371   Out.write((char*)&Buffer.front(), Buffer.size());
01372   
01373   // Make sure it hits disk now.
01374   Out.flush();
01375 }
01376 
01377 /// WriteBitcodeToStream - Write the specified module to the specified output
01378 /// stream.
01379 void llvm::WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream) {
01380   // If this is darwin, emit a file header and trailer if needed.
01381   bool isDarwin = M->getTargetTriple().find("-darwin") != std::string::npos;
01382   if (isDarwin)
01383     EmitDarwinBCHeader(Stream, M->getTargetTriple());
01384   
01385   // Emit the file header.
01386   Stream.Emit((unsigned)'B', 8);
01387   Stream.Emit((unsigned)'C', 8);
01388   Stream.Emit(0x0, 4);
01389   Stream.Emit(0xC, 4);
01390   Stream.Emit(0xE, 4);
01391   Stream.Emit(0xD, 4);
01392 
01393   // Emit the module.
01394   WriteModule(M, Stream);
01395 
01396   if (isDarwin)
01397     EmitDarwinBCTrailer(Stream, Stream.getBuffer().size());
01398 }