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 "ValueEnumerator.h"
00016 #include "llvm/ADT/Triple.h"
00017 #include "llvm/Bitcode/BitstreamWriter.h"
00018 #include "llvm/Bitcode/LLVMBitCodes.h"
00019 #include "llvm/IR/Constants.h"
00020 #include "llvm/IR/DerivedTypes.h"
00021 #include "llvm/IR/InlineAsm.h"
00022 #include "llvm/IR/Instructions.h"
00023 #include "llvm/IR/Module.h"
00024 #include "llvm/IR/Operator.h"
00025 #include "llvm/IR/ValueSymbolTable.h"
00026 #include "llvm/Support/CommandLine.h"
00027 #include "llvm/Support/ErrorHandling.h"
00028 #include "llvm/Support/MathExtras.h"
00029 #include "llvm/Support/Program.h"
00030 #include "llvm/Support/raw_ostream.h"
00031 #include <cctype>
00032 #include <map>
00033 using namespace llvm;
00034 
00035 static cl::opt<bool>
00036 EnablePreserveUseListOrdering("enable-bc-uselist-preserve",
00037                               cl::desc("Turn on experimental support for "
00038                                        "use-list order preservation."),
00039                               cl::init(false), cl::Hidden);
00040 
00041 /// These are manifest constants used by the bitcode writer. They do not need to
00042 /// be kept in sync with the reader, but need to be consistent within this file.
00043 enum {
00044   // VALUE_SYMTAB_BLOCK abbrev id's.
00045   VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
00046   VST_ENTRY_7_ABBREV,
00047   VST_ENTRY_6_ABBREV,
00048   VST_BBENTRY_6_ABBREV,
00049 
00050   // CONSTANTS_BLOCK abbrev id's.
00051   CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
00052   CONSTANTS_INTEGER_ABBREV,
00053   CONSTANTS_CE_CAST_Abbrev,
00054   CONSTANTS_NULL_Abbrev,
00055 
00056   // FUNCTION_BLOCK abbrev id's.
00057   FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
00058   FUNCTION_INST_BINOP_ABBREV,
00059   FUNCTION_INST_BINOP_FLAGS_ABBREV,
00060   FUNCTION_INST_CAST_ABBREV,
00061   FUNCTION_INST_RET_VOID_ABBREV,
00062   FUNCTION_INST_RET_VAL_ABBREV,
00063   FUNCTION_INST_UNREACHABLE_ABBREV
00064 };
00065 
00066 static unsigned GetEncodedCastOpcode(unsigned Opcode) {
00067   switch (Opcode) {
00068   default: llvm_unreachable("Unknown cast instruction!");
00069   case Instruction::Trunc   : return bitc::CAST_TRUNC;
00070   case Instruction::ZExt    : return bitc::CAST_ZEXT;
00071   case Instruction::SExt    : return bitc::CAST_SEXT;
00072   case Instruction::FPToUI  : return bitc::CAST_FPTOUI;
00073   case Instruction::FPToSI  : return bitc::CAST_FPTOSI;
00074   case Instruction::UIToFP  : return bitc::CAST_UITOFP;
00075   case Instruction::SIToFP  : return bitc::CAST_SITOFP;
00076   case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
00077   case Instruction::FPExt   : return bitc::CAST_FPEXT;
00078   case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
00079   case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
00080   case Instruction::BitCast : return bitc::CAST_BITCAST;
00081   case Instruction::AddrSpaceCast: return bitc::CAST_ADDRSPACECAST;
00082   }
00083 }
00084 
00085 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
00086   switch (Opcode) {
00087   default: llvm_unreachable("Unknown binary instruction!");
00088   case Instruction::Add:
00089   case Instruction::FAdd: return bitc::BINOP_ADD;
00090   case Instruction::Sub:
00091   case Instruction::FSub: return bitc::BINOP_SUB;
00092   case Instruction::Mul:
00093   case Instruction::FMul: return bitc::BINOP_MUL;
00094   case Instruction::UDiv: return bitc::BINOP_UDIV;
00095   case Instruction::FDiv:
00096   case Instruction::SDiv: return bitc::BINOP_SDIV;
00097   case Instruction::URem: return bitc::BINOP_UREM;
00098   case Instruction::FRem:
00099   case Instruction::SRem: return bitc::BINOP_SREM;
00100   case Instruction::Shl:  return bitc::BINOP_SHL;
00101   case Instruction::LShr: return bitc::BINOP_LSHR;
00102   case Instruction::AShr: return bitc::BINOP_ASHR;
00103   case Instruction::And:  return bitc::BINOP_AND;
00104   case Instruction::Or:   return bitc::BINOP_OR;
00105   case Instruction::Xor:  return bitc::BINOP_XOR;
00106   }
00107 }
00108 
00109 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) {
00110   switch (Op) {
00111   default: llvm_unreachable("Unknown RMW operation!");
00112   case AtomicRMWInst::Xchg: return bitc::RMW_XCHG;
00113   case AtomicRMWInst::Add: return bitc::RMW_ADD;
00114   case AtomicRMWInst::Sub: return bitc::RMW_SUB;
00115   case AtomicRMWInst::And: return bitc::RMW_AND;
00116   case AtomicRMWInst::Nand: return bitc::RMW_NAND;
00117   case AtomicRMWInst::Or: return bitc::RMW_OR;
00118   case AtomicRMWInst::Xor: return bitc::RMW_XOR;
00119   case AtomicRMWInst::Max: return bitc::RMW_MAX;
00120   case AtomicRMWInst::Min: return bitc::RMW_MIN;
00121   case AtomicRMWInst::UMax: return bitc::RMW_UMAX;
00122   case AtomicRMWInst::UMin: return bitc::RMW_UMIN;
00123   }
00124 }
00125 
00126 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) {
00127   switch (Ordering) {
00128   case NotAtomic: return bitc::ORDERING_NOTATOMIC;
00129   case Unordered: return bitc::ORDERING_UNORDERED;
00130   case Monotonic: return bitc::ORDERING_MONOTONIC;
00131   case Acquire: return bitc::ORDERING_ACQUIRE;
00132   case Release: return bitc::ORDERING_RELEASE;
00133   case AcquireRelease: return bitc::ORDERING_ACQREL;
00134   case SequentiallyConsistent: return bitc::ORDERING_SEQCST;
00135   }
00136   llvm_unreachable("Invalid ordering");
00137 }
00138 
00139 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) {
00140   switch (SynchScope) {
00141   case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD;
00142   case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD;
00143   }
00144   llvm_unreachable("Invalid synch scope");
00145 }
00146 
00147 static void WriteStringRecord(unsigned Code, StringRef Str,
00148                               unsigned AbbrevToUse, BitstreamWriter &Stream) {
00149   SmallVector<unsigned, 64> Vals;
00150 
00151   // Code: [strchar x N]
00152   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
00153     if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i]))
00154       AbbrevToUse = 0;
00155     Vals.push_back(Str[i]);
00156   }
00157 
00158   // Emit the finished record.
00159   Stream.EmitRecord(Code, Vals, AbbrevToUse);
00160 }
00161 
00162 static uint64_t getAttrKindEncoding(Attribute::AttrKind Kind) {
00163   switch (Kind) {
00164   case Attribute::Alignment:
00165     return bitc::ATTR_KIND_ALIGNMENT;
00166   case Attribute::AlwaysInline:
00167     return bitc::ATTR_KIND_ALWAYS_INLINE;
00168   case Attribute::Builtin:
00169     return bitc::ATTR_KIND_BUILTIN;
00170   case Attribute::ByVal:
00171     return bitc::ATTR_KIND_BY_VAL;
00172   case Attribute::InAlloca:
00173     return bitc::ATTR_KIND_IN_ALLOCA;
00174   case Attribute::Cold:
00175     return bitc::ATTR_KIND_COLD;
00176   case Attribute::InlineHint:
00177     return bitc::ATTR_KIND_INLINE_HINT;
00178   case Attribute::InReg:
00179     return bitc::ATTR_KIND_IN_REG;
00180   case Attribute::JumpTable:
00181     return bitc::ATTR_KIND_JUMP_TABLE;
00182   case Attribute::MinSize:
00183     return bitc::ATTR_KIND_MIN_SIZE;
00184   case Attribute::Naked:
00185     return bitc::ATTR_KIND_NAKED;
00186   case Attribute::Nest:
00187     return bitc::ATTR_KIND_NEST;
00188   case Attribute::NoAlias:
00189     return bitc::ATTR_KIND_NO_ALIAS;
00190   case Attribute::NoBuiltin:
00191     return bitc::ATTR_KIND_NO_BUILTIN;
00192   case Attribute::NoCapture:
00193     return bitc::ATTR_KIND_NO_CAPTURE;
00194   case Attribute::NoDuplicate:
00195     return bitc::ATTR_KIND_NO_DUPLICATE;
00196   case Attribute::NoImplicitFloat:
00197     return bitc::ATTR_KIND_NO_IMPLICIT_FLOAT;
00198   case Attribute::NoInline:
00199     return bitc::ATTR_KIND_NO_INLINE;
00200   case Attribute::NonLazyBind:
00201     return bitc::ATTR_KIND_NON_LAZY_BIND;
00202   case Attribute::NonNull:
00203     return bitc::ATTR_KIND_NON_NULL;
00204   case Attribute::Dereferenceable:
00205     return bitc::ATTR_KIND_DEREFERENCEABLE;
00206   case Attribute::NoRedZone:
00207     return bitc::ATTR_KIND_NO_RED_ZONE;
00208   case Attribute::NoReturn:
00209     return bitc::ATTR_KIND_NO_RETURN;
00210   case Attribute::NoUnwind:
00211     return bitc::ATTR_KIND_NO_UNWIND;
00212   case Attribute::OptimizeForSize:
00213     return bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE;
00214   case Attribute::OptimizeNone:
00215     return bitc::ATTR_KIND_OPTIMIZE_NONE;
00216   case Attribute::ReadNone:
00217     return bitc::ATTR_KIND_READ_NONE;
00218   case Attribute::ReadOnly:
00219     return bitc::ATTR_KIND_READ_ONLY;
00220   case Attribute::Returned:
00221     return bitc::ATTR_KIND_RETURNED;
00222   case Attribute::ReturnsTwice:
00223     return bitc::ATTR_KIND_RETURNS_TWICE;
00224   case Attribute::SExt:
00225     return bitc::ATTR_KIND_S_EXT;
00226   case Attribute::StackAlignment:
00227     return bitc::ATTR_KIND_STACK_ALIGNMENT;
00228   case Attribute::StackProtect:
00229     return bitc::ATTR_KIND_STACK_PROTECT;
00230   case Attribute::StackProtectReq:
00231     return bitc::ATTR_KIND_STACK_PROTECT_REQ;
00232   case Attribute::StackProtectStrong:
00233     return bitc::ATTR_KIND_STACK_PROTECT_STRONG;
00234   case Attribute::StructRet:
00235     return bitc::ATTR_KIND_STRUCT_RET;
00236   case Attribute::SanitizeAddress:
00237     return bitc::ATTR_KIND_SANITIZE_ADDRESS;
00238   case Attribute::SanitizeThread:
00239     return bitc::ATTR_KIND_SANITIZE_THREAD;
00240   case Attribute::SanitizeMemory:
00241     return bitc::ATTR_KIND_SANITIZE_MEMORY;
00242   case Attribute::UWTable:
00243     return bitc::ATTR_KIND_UW_TABLE;
00244   case Attribute::ZExt:
00245     return bitc::ATTR_KIND_Z_EXT;
00246   case Attribute::EndAttrKinds:
00247     llvm_unreachable("Can not encode end-attribute kinds marker.");
00248   case Attribute::None:
00249     llvm_unreachable("Can not encode none-attribute.");
00250   }
00251 
00252   llvm_unreachable("Trying to encode unknown attribute");
00253 }
00254 
00255 static void WriteAttributeGroupTable(const ValueEnumerator &VE,
00256                                      BitstreamWriter &Stream) {
00257   const std::vector<AttributeSet> &AttrGrps = VE.getAttributeGroups();
00258   if (AttrGrps.empty()) return;
00259 
00260   Stream.EnterSubblock(bitc::PARAMATTR_GROUP_BLOCK_ID, 3);
00261 
00262   SmallVector<uint64_t, 64> Record;
00263   for (unsigned i = 0, e = AttrGrps.size(); i != e; ++i) {
00264     AttributeSet AS = AttrGrps[i];
00265     for (unsigned i = 0, e = AS.getNumSlots(); i != e; ++i) {
00266       AttributeSet A = AS.getSlotAttributes(i);
00267 
00268       Record.push_back(VE.getAttributeGroupID(A));
00269       Record.push_back(AS.getSlotIndex(i));
00270 
00271       for (AttributeSet::iterator I = AS.begin(0), E = AS.end(0);
00272            I != E; ++I) {
00273         Attribute Attr = *I;
00274         if (Attr.isEnumAttribute()) {
00275           Record.push_back(0);
00276           Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
00277         } else if (Attr.isIntAttribute()) {
00278           Record.push_back(1);
00279           Record.push_back(getAttrKindEncoding(Attr.getKindAsEnum()));
00280           Record.push_back(Attr.getValueAsInt());
00281         } else {
00282           StringRef Kind = Attr.getKindAsString();
00283           StringRef Val = Attr.getValueAsString();
00284 
00285           Record.push_back(Val.empty() ? 3 : 4);
00286           Record.append(Kind.begin(), Kind.end());
00287           Record.push_back(0);
00288           if (!Val.empty()) {
00289             Record.append(Val.begin(), Val.end());
00290             Record.push_back(0);
00291           }
00292         }
00293       }
00294 
00295       Stream.EmitRecord(bitc::PARAMATTR_GRP_CODE_ENTRY, Record);
00296       Record.clear();
00297     }
00298   }
00299 
00300   Stream.ExitBlock();
00301 }
00302 
00303 static void WriteAttributeTable(const ValueEnumerator &VE,
00304                                 BitstreamWriter &Stream) {
00305   const std::vector<AttributeSet> &Attrs = VE.getAttributes();
00306   if (Attrs.empty()) return;
00307 
00308   Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
00309 
00310   SmallVector<uint64_t, 64> Record;
00311   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
00312     const AttributeSet &A = Attrs[i];
00313     for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i)
00314       Record.push_back(VE.getAttributeGroupID(A.getSlotAttributes(i)));
00315 
00316     Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
00317     Record.clear();
00318   }
00319 
00320   Stream.ExitBlock();
00321 }
00322 
00323 /// WriteTypeTable - Write out the type table for a module.
00324 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
00325   const ValueEnumerator::TypeList &TypeList = VE.getTypes();
00326 
00327   Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */);
00328   SmallVector<uint64_t, 64> TypeVals;
00329 
00330   uint64_t NumBits = Log2_32_Ceil(VE.getTypes().size()+1);
00331 
00332   // Abbrev for TYPE_CODE_POINTER.
00333   BitCodeAbbrev *Abbv = new BitCodeAbbrev();
00334   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
00335   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
00336   Abbv->Add(BitCodeAbbrevOp(0));  // Addrspace = 0
00337   unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
00338 
00339   // Abbrev for TYPE_CODE_FUNCTION.
00340   Abbv = new BitCodeAbbrev();
00341   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
00342   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // isvararg
00343   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00344   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
00345 
00346   unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
00347 
00348   // Abbrev for TYPE_CODE_STRUCT_ANON.
00349   Abbv = new BitCodeAbbrev();
00350   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON));
00351   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
00352   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00353   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
00354 
00355   unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv);
00356 
00357   // Abbrev for TYPE_CODE_STRUCT_NAME.
00358   Abbv = new BitCodeAbbrev();
00359   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME));
00360   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00361   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
00362   unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv);
00363 
00364   // Abbrev for TYPE_CODE_STRUCT_NAMED.
00365   Abbv = new BitCodeAbbrev();
00366   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED));
00367   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));  // ispacked
00368   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00369   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
00370 
00371   unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv);
00372 
00373   // Abbrev for TYPE_CODE_ARRAY.
00374   Abbv = new BitCodeAbbrev();
00375   Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
00376   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));   // size
00377   Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits));
00378 
00379   unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
00380 
00381   // Emit an entry count so the reader can reserve space.
00382   TypeVals.push_back(TypeList.size());
00383   Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
00384   TypeVals.clear();
00385 
00386   // Loop over all of the types, emitting each in turn.
00387   for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
00388     Type *T = TypeList[i];
00389     int AbbrevToUse = 0;
00390     unsigned Code = 0;
00391 
00392     switch (T->getTypeID()) {
00393     case Type::VoidTyID:      Code = bitc::TYPE_CODE_VOID;      break;
00394     case Type::HalfTyID:      Code = bitc::TYPE_CODE_HALF;      break;
00395     case Type::FloatTyID:     Code = bitc::TYPE_CODE_FLOAT;     break;
00396     case Type::DoubleTyID:    Code = bitc::TYPE_CODE_DOUBLE;    break;
00397     case Type::X86_FP80TyID:  Code = bitc::TYPE_CODE_X86_FP80;  break;
00398     case Type::FP128TyID:     Code = bitc::TYPE_CODE_FP128;     break;
00399     case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
00400     case Type::LabelTyID:     Code = bitc::TYPE_CODE_LABEL;     break;
00401     case Type::MetadataTyID:  Code = bitc::TYPE_CODE_METADATA;  break;
00402     case Type::X86_MMXTyID:   Code = bitc::TYPE_CODE_X86_MMX;   break;
00403     case Type::IntegerTyID:
00404       // INTEGER: [width]
00405       Code = bitc::TYPE_CODE_INTEGER;
00406       TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
00407       break;
00408     case Type::PointerTyID: {
00409       PointerType *PTy = cast<PointerType>(T);
00410       // POINTER: [pointee type, address space]
00411       Code = bitc::TYPE_CODE_POINTER;
00412       TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
00413       unsigned AddressSpace = PTy->getAddressSpace();
00414       TypeVals.push_back(AddressSpace);
00415       if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
00416       break;
00417     }
00418     case Type::FunctionTyID: {
00419       FunctionType *FT = cast<FunctionType>(T);
00420       // FUNCTION: [isvararg, retty, paramty x N]
00421       Code = bitc::TYPE_CODE_FUNCTION;
00422       TypeVals.push_back(FT->isVarArg());
00423       TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
00424       for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
00425         TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
00426       AbbrevToUse = FunctionAbbrev;
00427       break;
00428     }
00429     case Type::StructTyID: {
00430       StructType *ST = cast<StructType>(T);
00431       // STRUCT: [ispacked, eltty x N]
00432       TypeVals.push_back(ST->isPacked());
00433       // Output all of the element types.
00434       for (StructType::element_iterator I = ST->element_begin(),
00435            E = ST->element_end(); I != E; ++I)
00436         TypeVals.push_back(VE.getTypeID(*I));
00437 
00438       if (ST->isLiteral()) {
00439         Code = bitc::TYPE_CODE_STRUCT_ANON;
00440         AbbrevToUse = StructAnonAbbrev;
00441       } else {
00442         if (ST->isOpaque()) {
00443           Code = bitc::TYPE_CODE_OPAQUE;
00444         } else {
00445           Code = bitc::TYPE_CODE_STRUCT_NAMED;
00446           AbbrevToUse = StructNamedAbbrev;
00447         }
00448 
00449         // Emit the name if it is present.
00450         if (!ST->getName().empty())
00451           WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(),
00452                             StructNameAbbrev, Stream);
00453       }
00454       break;
00455     }
00456     case Type::ArrayTyID: {
00457       ArrayType *AT = cast<ArrayType>(T);
00458       // ARRAY: [numelts, eltty]
00459       Code = bitc::TYPE_CODE_ARRAY;
00460       TypeVals.push_back(AT->getNumElements());
00461       TypeVals.push_back(VE.getTypeID(AT->getElementType()));
00462       AbbrevToUse = ArrayAbbrev;
00463       break;
00464     }
00465     case Type::VectorTyID: {
00466       VectorType *VT = cast<VectorType>(T);
00467       // VECTOR [numelts, eltty]
00468       Code = bitc::TYPE_CODE_VECTOR;
00469       TypeVals.push_back(VT->getNumElements());
00470       TypeVals.push_back(VE.getTypeID(VT->getElementType()));
00471       break;
00472     }
00473     }
00474 
00475     // Emit the finished record.
00476     Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
00477     TypeVals.clear();
00478   }
00479 
00480   Stream.ExitBlock();
00481 }
00482 
00483 static unsigned getEncodedLinkage(const GlobalValue &GV) {
00484   switch (GV.getLinkage()) {
00485   case GlobalValue::ExternalLinkage:                 return 0;
00486   case GlobalValue::WeakAnyLinkage:                  return 1;
00487   case GlobalValue::AppendingLinkage:                return 2;
00488   case GlobalValue::InternalLinkage:                 return 3;
00489   case GlobalValue::LinkOnceAnyLinkage:              return 4;
00490   case GlobalValue::ExternalWeakLinkage:             return 7;
00491   case GlobalValue::CommonLinkage:                   return 8;
00492   case GlobalValue::PrivateLinkage:                  return 9;
00493   case GlobalValue::WeakODRLinkage:                  return 10;
00494   case GlobalValue::LinkOnceODRLinkage:              return 11;
00495   case GlobalValue::AvailableExternallyLinkage:      return 12;
00496   }
00497   llvm_unreachable("Invalid linkage");
00498 }
00499 
00500 static unsigned getEncodedVisibility(const GlobalValue &GV) {
00501   switch (GV.getVisibility()) {
00502   case GlobalValue::DefaultVisibility:   return 0;
00503   case GlobalValue::HiddenVisibility:    return 1;
00504   case GlobalValue::ProtectedVisibility: return 2;
00505   }
00506   llvm_unreachable("Invalid visibility");
00507 }
00508 
00509 static unsigned getEncodedDLLStorageClass(const GlobalValue &GV) {
00510   switch (GV.getDLLStorageClass()) {
00511   case GlobalValue::DefaultStorageClass:   return 0;
00512   case GlobalValue::DLLImportStorageClass: return 1;
00513   case GlobalValue::DLLExportStorageClass: return 2;
00514   }
00515   llvm_unreachable("Invalid DLL storage class");
00516 }
00517 
00518 static unsigned getEncodedThreadLocalMode(const GlobalValue &GV) {
00519   switch (GV.getThreadLocalMode()) {
00520     case GlobalVariable::NotThreadLocal:         return 0;
00521     case GlobalVariable::GeneralDynamicTLSModel: return 1;
00522     case GlobalVariable::LocalDynamicTLSModel:   return 2;
00523     case GlobalVariable::InitialExecTLSModel:    return 3;
00524     case GlobalVariable::LocalExecTLSModel:      return 4;
00525   }
00526   llvm_unreachable("Invalid TLS model");
00527 }
00528 
00529 static unsigned getEncodedComdatSelectionKind(const Comdat &C) {
00530   switch (C.getSelectionKind()) {
00531   case Comdat::Any:
00532     return bitc::COMDAT_SELECTION_KIND_ANY;
00533   case Comdat::ExactMatch:
00534     return bitc::COMDAT_SELECTION_KIND_EXACT_MATCH;
00535   case Comdat::Largest:
00536     return bitc::COMDAT_SELECTION_KIND_LARGEST;
00537   case Comdat::NoDuplicates:
00538     return bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES;
00539   case Comdat::SameSize:
00540     return bitc::COMDAT_SELECTION_KIND_SAME_SIZE;
00541   }
00542   llvm_unreachable("Invalid selection kind");
00543 }
00544 
00545 static void writeComdats(const ValueEnumerator &VE, BitstreamWriter &Stream) {
00546   SmallVector<uint8_t, 64> Vals;
00547   for (const Comdat *C : VE.getComdats()) {
00548     // COMDAT: [selection_kind, name]
00549     Vals.push_back(getEncodedComdatSelectionKind(*C));
00550     Vals.push_back(C->getName().size());
00551     for (char Chr : C->getName())
00552       Vals.push_back((unsigned char)Chr);
00553     Stream.EmitRecord(bitc::MODULE_CODE_COMDAT, Vals, /*AbbrevToUse=*/0);
00554     Vals.clear();
00555   }
00556 }
00557 
00558 // Emit top-level description of module, including target triple, inline asm,
00559 // descriptors for global variables, and function prototype info.
00560 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
00561                             BitstreamWriter &Stream) {
00562   // Emit various pieces of data attached to a module.
00563   if (!M->getTargetTriple().empty())
00564     WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
00565                       0/*TODO*/, Stream);
00566   const std::string &DL = M->getDataLayoutStr();
00567   if (!DL.empty())
00568     WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, DL, 0 /*TODO*/, Stream);
00569   if (!M->getModuleInlineAsm().empty())
00570     WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
00571                       0/*TODO*/, Stream);
00572 
00573   // Emit information about sections and GC, computing how many there are. Also
00574   // compute the maximum alignment value.
00575   std::map<std::string, unsigned> SectionMap;
00576   std::map<std::string, unsigned> GCMap;
00577   unsigned MaxAlignment = 0;
00578   unsigned MaxGlobalType = 0;
00579   for (const GlobalValue &GV : M->globals()) {
00580     MaxAlignment = std::max(MaxAlignment, GV.getAlignment());
00581     MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV.getType()));
00582     if (GV.hasSection()) {
00583       // Give section names unique ID's.
00584       unsigned &Entry = SectionMap[GV.getSection()];
00585       if (!Entry) {
00586         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV.getSection(),
00587                           0/*TODO*/, Stream);
00588         Entry = SectionMap.size();
00589       }
00590     }
00591   }
00592   for (const Function &F : *M) {
00593     MaxAlignment = std::max(MaxAlignment, F.getAlignment());
00594     if (F.hasSection()) {
00595       // Give section names unique ID's.
00596       unsigned &Entry = SectionMap[F.getSection()];
00597       if (!Entry) {
00598         WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F.getSection(),
00599                           0/*TODO*/, Stream);
00600         Entry = SectionMap.size();
00601       }
00602     }
00603     if (F.hasGC()) {
00604       // Same for GC names.
00605       unsigned &Entry = GCMap[F.getGC()];
00606       if (!Entry) {
00607         WriteStringRecord(bitc::MODULE_CODE_GCNAME, F.getGC(),
00608                           0/*TODO*/, Stream);
00609         Entry = GCMap.size();
00610       }
00611     }
00612   }
00613 
00614   // Emit abbrev for globals, now that we know # sections and max alignment.
00615   unsigned SimpleGVarAbbrev = 0;
00616   if (!M->global_empty()) {
00617     // Add an abbrev for common globals with no visibility or thread localness.
00618     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
00619     Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
00620     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00621                               Log2_32_Ceil(MaxGlobalType+1)));
00622     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1));      // Constant.
00623     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));        // Initializer.
00624     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));      // Linkage.
00625     if (MaxAlignment == 0)                                      // Alignment.
00626       Abbv->Add(BitCodeAbbrevOp(0));
00627     else {
00628       unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
00629       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00630                                Log2_32_Ceil(MaxEncAlignment+1)));
00631     }
00632     if (SectionMap.empty())                                    // Section.
00633       Abbv->Add(BitCodeAbbrevOp(0));
00634     else
00635       Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
00636                                Log2_32_Ceil(SectionMap.size()+1)));
00637     // Don't bother emitting vis + thread local.
00638     SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
00639   }
00640 
00641   // Emit the global variable information.
00642   SmallVector<unsigned, 64> Vals;
00643   for (const GlobalVariable &GV : M->globals()) {
00644     unsigned AbbrevToUse = 0;
00645 
00646     // GLOBALVAR: [type, isconst, initid,
00647     //             linkage, alignment, section, visibility, threadlocal,
00648     //             unnamed_addr, externally_initialized, dllstorageclass]
00649     Vals.push_back(VE.getTypeID(GV.getType()));
00650     Vals.push_back(GV.isConstant());
00651     Vals.push_back(GV.isDeclaration() ? 0 :
00652                    (VE.getValueID(GV.getInitializer()) + 1));
00653     Vals.push_back(getEncodedLinkage(GV));
00654     Vals.push_back(Log2_32(GV.getAlignment())+1);
00655     Vals.push_back(GV.hasSection() ? SectionMap[GV.getSection()] : 0);
00656     if (GV.isThreadLocal() ||
00657         GV.getVisibility() != GlobalValue::DefaultVisibility ||
00658         GV.hasUnnamedAddr() || GV.isExternallyInitialized() ||
00659         GV.getDLLStorageClass() != GlobalValue::DefaultStorageClass ||
00660         GV.hasComdat()) {
00661       Vals.push_back(getEncodedVisibility(GV));
00662       Vals.push_back(getEncodedThreadLocalMode(GV));
00663       Vals.push_back(GV.hasUnnamedAddr());
00664       Vals.push_back(GV.isExternallyInitialized());
00665       Vals.push_back(getEncodedDLLStorageClass(GV));
00666       Vals.push_back(GV.hasComdat() ? VE.getComdatID(GV.getComdat()) : 0);
00667     } else {
00668       AbbrevToUse = SimpleGVarAbbrev;
00669     }
00670 
00671     Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
00672     Vals.clear();
00673   }
00674 
00675   // Emit the function proto information.
00676   for (const Function &F : *M) {
00677     // FUNCTION:  [type, callingconv, isproto, linkage, paramattrs, alignment,
00678     //             section, visibility, gc, unnamed_addr, prefix]
00679     Vals.push_back(VE.getTypeID(F.getType()));
00680     Vals.push_back(F.getCallingConv());
00681     Vals.push_back(F.isDeclaration());
00682     Vals.push_back(getEncodedLinkage(F));
00683     Vals.push_back(VE.getAttributeID(F.getAttributes()));
00684     Vals.push_back(Log2_32(F.getAlignment())+1);
00685     Vals.push_back(F.hasSection() ? SectionMap[F.getSection()] : 0);
00686     Vals.push_back(getEncodedVisibility(F));
00687     Vals.push_back(F.hasGC() ? GCMap[F.getGC()] : 0);
00688     Vals.push_back(F.hasUnnamedAddr());
00689     Vals.push_back(F.hasPrefixData() ? (VE.getValueID(F.getPrefixData()) + 1)
00690                                       : 0);
00691     Vals.push_back(getEncodedDLLStorageClass(F));
00692     Vals.push_back(F.hasComdat() ? VE.getComdatID(F.getComdat()) : 0);
00693 
00694     unsigned AbbrevToUse = 0;
00695     Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
00696     Vals.clear();
00697   }
00698 
00699   // Emit the alias information.
00700   for (const GlobalAlias &A : M->aliases()) {
00701     // ALIAS: [alias type, aliasee val#, linkage, visibility]
00702     Vals.push_back(VE.getTypeID(A.getType()));
00703     Vals.push_back(VE.getValueID(A.getAliasee()));
00704     Vals.push_back(getEncodedLinkage(A));
00705     Vals.push_back(getEncodedVisibility(A));
00706     Vals.push_back(getEncodedDLLStorageClass(A));
00707     Vals.push_back(getEncodedThreadLocalMode(A));
00708     Vals.push_back(A.hasUnnamedAddr());
00709     unsigned AbbrevToUse = 0;
00710     Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
00711     Vals.clear();
00712   }
00713 }
00714 
00715 static uint64_t GetOptimizationFlags(const Value *V) {
00716   uint64_t Flags = 0;
00717 
00718   if (const OverflowingBinaryOperator *OBO =
00719         dyn_cast<OverflowingBinaryOperator>(V)) {
00720     if (OBO->hasNoSignedWrap())
00721       Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
00722     if (OBO->hasNoUnsignedWrap())
00723       Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
00724   } else if (const PossiblyExactOperator *PEO =
00725                dyn_cast<PossiblyExactOperator>(V)) {
00726     if (PEO->isExact())
00727       Flags |= 1 << bitc::PEO_EXACT;
00728   } else if (const FPMathOperator *FPMO =
00729              dyn_cast<const FPMathOperator>(V)) {
00730     if (FPMO->hasUnsafeAlgebra())
00731       Flags |= FastMathFlags::UnsafeAlgebra;
00732     if (FPMO->hasNoNaNs())
00733       Flags |= FastMathFlags::NoNaNs;
00734     if (FPMO->hasNoInfs())
00735       Flags |= FastMathFlags::NoInfs;
00736     if (FPMO->hasNoSignedZeros())
00737       Flags |= FastMathFlags::NoSignedZeros;
00738     if (FPMO->hasAllowReciprocal())
00739       Flags |= FastMathFlags::AllowReciprocal;
00740   }
00741 
00742   return Flags;
00743 }
00744 
00745 static void WriteMDNode(const MDNode *N,
00746                         const ValueEnumerator &VE,
00747                         BitstreamWriter &Stream,
00748                         SmallVectorImpl<uint64_t> &Record) {
00749   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
00750     if (N->getOperand(i)) {
00751       Record.push_back(VE.getTypeID(N->getOperand(i)->getType()));
00752       Record.push_back(VE.getValueID(N->getOperand(i)));
00753     } else {
00754       Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
00755       Record.push_back(0);
00756     }
00757   }
00758   unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE :
00759                                            bitc::METADATA_NODE;
00760   Stream.EmitRecord(MDCode, Record, 0);
00761   Record.clear();
00762 }
00763 
00764 static void WriteModuleMetadata(const Module *M,
00765                                 const ValueEnumerator &VE,
00766                                 BitstreamWriter &Stream) {
00767   const ValueEnumerator::ValueList &Vals = VE.getMDValues();
00768   bool StartedMetadataBlock = false;
00769   unsigned MDSAbbrev = 0;
00770   SmallVector<uint64_t, 64> Record;
00771   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
00772 
00773     if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
00774       if (!N->isFunctionLocal() || !N->getFunction()) {
00775         if (!StartedMetadataBlock) {
00776           Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
00777           StartedMetadataBlock = true;
00778         }
00779         WriteMDNode(N, VE, Stream, Record);
00780       }
00781     } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
00782       if (!StartedMetadataBlock)  {
00783         Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
00784 
00785         // Abbrev for METADATA_STRING.
00786         BitCodeAbbrev *Abbv = new BitCodeAbbrev();
00787         Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
00788         Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00789         Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
00790         MDSAbbrev = Stream.EmitAbbrev(Abbv);
00791         StartedMetadataBlock = true;
00792       }
00793 
00794       // Code: [strchar x N]
00795       Record.append(MDS->begin(), MDS->end());
00796 
00797       // Emit the finished record.
00798       Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
00799       Record.clear();
00800     }
00801   }
00802 
00803   // Write named metadata.
00804   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
00805        E = M->named_metadata_end(); I != E; ++I) {
00806     const NamedMDNode *NMD = I;
00807     if (!StartedMetadataBlock)  {
00808       Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
00809       StartedMetadataBlock = true;
00810     }
00811 
00812     // Write name.
00813     StringRef Str = NMD->getName();
00814     for (unsigned i = 0, e = Str.size(); i != e; ++i)
00815       Record.push_back(Str[i]);
00816     Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
00817     Record.clear();
00818 
00819     // Write named metadata operands.
00820     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
00821       Record.push_back(VE.getValueID(NMD->getOperand(i)));
00822     Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
00823     Record.clear();
00824   }
00825 
00826   if (StartedMetadataBlock)
00827     Stream.ExitBlock();
00828 }
00829 
00830 static void WriteFunctionLocalMetadata(const Function &F,
00831                                        const ValueEnumerator &VE,
00832                                        BitstreamWriter &Stream) {
00833   bool StartedMetadataBlock = false;
00834   SmallVector<uint64_t, 64> Record;
00835   const SmallVectorImpl<const MDNode *> &Vals = VE.getFunctionLocalMDValues();
00836   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
00837     if (const MDNode *N = Vals[i])
00838       if (N->isFunctionLocal() && N->getFunction() == &F) {
00839         if (!StartedMetadataBlock) {
00840           Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
00841           StartedMetadataBlock = true;
00842         }
00843         WriteMDNode(N, VE, Stream, Record);
00844       }
00845 
00846   if (StartedMetadataBlock)
00847     Stream.ExitBlock();
00848 }
00849 
00850 static void WriteMetadataAttachment(const Function &F,
00851                                     const ValueEnumerator &VE,
00852                                     BitstreamWriter &Stream) {
00853   Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
00854 
00855   SmallVector<uint64_t, 64> Record;
00856 
00857   // Write metadata attachments
00858   // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
00859   SmallVector<std::pair<unsigned, MDNode*>, 4> MDs;
00860 
00861   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
00862     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
00863          I != E; ++I) {
00864       MDs.clear();
00865       I->getAllMetadataOtherThanDebugLoc(MDs);
00866 
00867       // If no metadata, ignore instruction.
00868       if (MDs.empty()) continue;
00869 
00870       Record.push_back(VE.getInstructionID(I));
00871 
00872       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
00873         Record.push_back(MDs[i].first);
00874         Record.push_back(VE.getValueID(MDs[i].second));
00875       }
00876       Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
00877       Record.clear();
00878     }
00879 
00880   Stream.ExitBlock();
00881 }
00882 
00883 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) {
00884   SmallVector<uint64_t, 64> Record;
00885 
00886   // Write metadata kinds
00887   // METADATA_KIND - [n x [id, name]]
00888   SmallVector<StringRef, 8> Names;
00889   M->getMDKindNames(Names);
00890 
00891   if (Names.empty()) return;
00892 
00893   Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
00894 
00895   for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) {
00896     Record.push_back(MDKindID);
00897     StringRef KName = Names[MDKindID];
00898     Record.append(KName.begin(), KName.end());
00899 
00900     Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
00901     Record.clear();
00902   }
00903 
00904   Stream.ExitBlock();
00905 }
00906 
00907 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) {
00908   if ((int64_t)V >= 0)
00909     Vals.push_back(V << 1);
00910   else
00911     Vals.push_back((-V << 1) | 1);
00912 }
00913 
00914 static void WriteConstants(unsigned FirstVal, unsigned LastVal,
00915                            const ValueEnumerator &VE,
00916                            BitstreamWriter &Stream, bool isGlobal) {
00917   if (FirstVal == LastVal) return;
00918 
00919   Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
00920 
00921   unsigned AggregateAbbrev = 0;
00922   unsigned String8Abbrev = 0;
00923   unsigned CString7Abbrev = 0;
00924   unsigned CString6Abbrev = 0;
00925   // If this is a constant pool for the module, emit module-specific abbrevs.
00926   if (isGlobal) {
00927     // Abbrev for CST_CODE_AGGREGATE.
00928     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
00929     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
00930     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00931     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
00932     AggregateAbbrev = Stream.EmitAbbrev(Abbv);
00933 
00934     // Abbrev for CST_CODE_STRING.
00935     Abbv = new BitCodeAbbrev();
00936     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
00937     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00938     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
00939     String8Abbrev = Stream.EmitAbbrev(Abbv);
00940     // Abbrev for CST_CODE_CSTRING.
00941     Abbv = new BitCodeAbbrev();
00942     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
00943     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00944     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
00945     CString7Abbrev = Stream.EmitAbbrev(Abbv);
00946     // Abbrev for CST_CODE_CSTRING.
00947     Abbv = new BitCodeAbbrev();
00948     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
00949     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
00950     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
00951     CString6Abbrev = Stream.EmitAbbrev(Abbv);
00952   }
00953 
00954   SmallVector<uint64_t, 64> Record;
00955 
00956   const ValueEnumerator::ValueList &Vals = VE.getValues();
00957   Type *LastTy = nullptr;
00958   for (unsigned i = FirstVal; i != LastVal; ++i) {
00959     const Value *V = Vals[i].first;
00960     // If we need to switch types, do so now.
00961     if (V->getType() != LastTy) {
00962       LastTy = V->getType();
00963       Record.push_back(VE.getTypeID(LastTy));
00964       Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
00965                         CONSTANTS_SETTYPE_ABBREV);
00966       Record.clear();
00967     }
00968 
00969     if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
00970       Record.push_back(unsigned(IA->hasSideEffects()) |
00971                        unsigned(IA->isAlignStack()) << 1 |
00972                        unsigned(IA->getDialect()&1) << 2);
00973 
00974       // Add the asm string.
00975       const std::string &AsmStr = IA->getAsmString();
00976       Record.push_back(AsmStr.size());
00977       for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
00978         Record.push_back(AsmStr[i]);
00979 
00980       // Add the constraint string.
00981       const std::string &ConstraintStr = IA->getConstraintString();
00982       Record.push_back(ConstraintStr.size());
00983       for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
00984         Record.push_back(ConstraintStr[i]);
00985       Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
00986       Record.clear();
00987       continue;
00988     }
00989     const Constant *C = cast<Constant>(V);
00990     unsigned Code = -1U;
00991     unsigned AbbrevToUse = 0;
00992     if (C->isNullValue()) {
00993       Code = bitc::CST_CODE_NULL;
00994     } else if (isa<UndefValue>(C)) {
00995       Code = bitc::CST_CODE_UNDEF;
00996     } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
00997       if (IV->getBitWidth() <= 64) {
00998         uint64_t V = IV->getSExtValue();
00999         emitSignedInt64(Record, V);
01000         Code = bitc::CST_CODE_INTEGER;
01001         AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
01002       } else {                             // Wide integers, > 64 bits in size.
01003         // We have an arbitrary precision integer value to write whose
01004         // bit width is > 64. However, in canonical unsigned integer
01005         // format it is likely that the high bits are going to be zero.
01006         // So, we only write the number of active words.
01007         unsigned NWords = IV->getValue().getActiveWords();
01008         const uint64_t *RawWords = IV->getValue().getRawData();
01009         for (unsigned i = 0; i != NWords; ++i) {
01010           emitSignedInt64(Record, RawWords[i]);
01011         }
01012         Code = bitc::CST_CODE_WIDE_INTEGER;
01013       }
01014     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
01015       Code = bitc::CST_CODE_FLOAT;
01016       Type *Ty = CFP->getType();
01017       if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) {
01018         Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
01019       } else if (Ty->isX86_FP80Ty()) {
01020         // api needed to prevent premature destruction
01021         // bits are not in the same order as a normal i80 APInt, compensate.
01022         APInt api = CFP->getValueAPF().bitcastToAPInt();
01023         const uint64_t *p = api.getRawData();
01024         Record.push_back((p[1] << 48) | (p[0] >> 16));
01025         Record.push_back(p[0] & 0xffffLL);
01026       } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
01027         APInt api = CFP->getValueAPF().bitcastToAPInt();
01028         const uint64_t *p = api.getRawData();
01029         Record.push_back(p[0]);
01030         Record.push_back(p[1]);
01031       } else {
01032         assert (0 && "Unknown FP type!");
01033       }
01034     } else if (isa<ConstantDataSequential>(C) &&
01035                cast<ConstantDataSequential>(C)->isString()) {
01036       const ConstantDataSequential *Str = cast<ConstantDataSequential>(C);
01037       // Emit constant strings specially.
01038       unsigned NumElts = Str->getNumElements();
01039       // If this is a null-terminated string, use the denser CSTRING encoding.
01040       if (Str->isCString()) {
01041         Code = bitc::CST_CODE_CSTRING;
01042         --NumElts;  // Don't encode the null, which isn't allowed by char6.
01043       } else {
01044         Code = bitc::CST_CODE_STRING;
01045         AbbrevToUse = String8Abbrev;
01046       }
01047       bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
01048       bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
01049       for (unsigned i = 0; i != NumElts; ++i) {
01050         unsigned char V = Str->getElementAsInteger(i);
01051         Record.push_back(V);
01052         isCStr7 &= (V & 128) == 0;
01053         if (isCStrChar6)
01054           isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
01055       }
01056 
01057       if (isCStrChar6)
01058         AbbrevToUse = CString6Abbrev;
01059       else if (isCStr7)
01060         AbbrevToUse = CString7Abbrev;
01061     } else if (const ConstantDataSequential *CDS =
01062                   dyn_cast<ConstantDataSequential>(C)) {
01063       Code = bitc::CST_CODE_DATA;
01064       Type *EltTy = CDS->getType()->getElementType();
01065       if (isa<IntegerType>(EltTy)) {
01066         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i)
01067           Record.push_back(CDS->getElementAsInteger(i));
01068       } else if (EltTy->isFloatTy()) {
01069         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
01070           union { float F; uint32_t I; };
01071           F = CDS->getElementAsFloat(i);
01072           Record.push_back(I);
01073         }
01074       } else {
01075         assert(EltTy->isDoubleTy() && "Unknown ConstantData element type");
01076         for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
01077           union { double F; uint64_t I; };
01078           F = CDS->getElementAsDouble(i);
01079           Record.push_back(I);
01080         }
01081       }
01082     } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
01083                isa<ConstantVector>(C)) {
01084       Code = bitc::CST_CODE_AGGREGATE;
01085       for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
01086         Record.push_back(VE.getValueID(C->getOperand(i)));
01087       AbbrevToUse = AggregateAbbrev;
01088     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
01089       switch (CE->getOpcode()) {
01090       default:
01091         if (Instruction::isCast(CE->getOpcode())) {
01092           Code = bitc::CST_CODE_CE_CAST;
01093           Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
01094           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
01095           Record.push_back(VE.getValueID(C->getOperand(0)));
01096           AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
01097         } else {
01098           assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
01099           Code = bitc::CST_CODE_CE_BINOP;
01100           Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
01101           Record.push_back(VE.getValueID(C->getOperand(0)));
01102           Record.push_back(VE.getValueID(C->getOperand(1)));
01103           uint64_t Flags = GetOptimizationFlags(CE);
01104           if (Flags != 0)
01105             Record.push_back(Flags);
01106         }
01107         break;
01108       case Instruction::GetElementPtr:
01109         Code = bitc::CST_CODE_CE_GEP;
01110         if (cast<GEPOperator>(C)->isInBounds())
01111           Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
01112         for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
01113           Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
01114           Record.push_back(VE.getValueID(C->getOperand(i)));
01115         }
01116         break;
01117       case Instruction::Select:
01118         Code = bitc::CST_CODE_CE_SELECT;
01119         Record.push_back(VE.getValueID(C->getOperand(0)));
01120         Record.push_back(VE.getValueID(C->getOperand(1)));
01121         Record.push_back(VE.getValueID(C->getOperand(2)));
01122         break;
01123       case Instruction::ExtractElement:
01124         Code = bitc::CST_CODE_CE_EXTRACTELT;
01125         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
01126         Record.push_back(VE.getValueID(C->getOperand(0)));
01127         Record.push_back(VE.getTypeID(C->getOperand(1)->getType()));
01128         Record.push_back(VE.getValueID(C->getOperand(1)));
01129         break;
01130       case Instruction::InsertElement:
01131         Code = bitc::CST_CODE_CE_INSERTELT;
01132         Record.push_back(VE.getValueID(C->getOperand(0)));
01133         Record.push_back(VE.getValueID(C->getOperand(1)));
01134         Record.push_back(VE.getTypeID(C->getOperand(2)->getType()));
01135         Record.push_back(VE.getValueID(C->getOperand(2)));
01136         break;
01137       case Instruction::ShuffleVector:
01138         // If the return type and argument types are the same, this is a
01139         // standard shufflevector instruction.  If the types are different,
01140         // then the shuffle is widening or truncating the input vectors, and
01141         // the argument type must also be encoded.
01142         if (C->getType() == C->getOperand(0)->getType()) {
01143           Code = bitc::CST_CODE_CE_SHUFFLEVEC;
01144         } else {
01145           Code = bitc::CST_CODE_CE_SHUFVEC_EX;
01146           Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
01147         }
01148         Record.push_back(VE.getValueID(C->getOperand(0)));
01149         Record.push_back(VE.getValueID(C->getOperand(1)));
01150         Record.push_back(VE.getValueID(C->getOperand(2)));
01151         break;
01152       case Instruction::ICmp:
01153       case Instruction::FCmp:
01154         Code = bitc::CST_CODE_CE_CMP;
01155         Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
01156         Record.push_back(VE.getValueID(C->getOperand(0)));
01157         Record.push_back(VE.getValueID(C->getOperand(1)));
01158         Record.push_back(CE->getPredicate());
01159         break;
01160       }
01161     } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
01162       Code = bitc::CST_CODE_BLOCKADDRESS;
01163       Record.push_back(VE.getTypeID(BA->getFunction()->getType()));
01164       Record.push_back(VE.getValueID(BA->getFunction()));
01165       Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock()));
01166     } else {
01167 #ifndef NDEBUG
01168       C->dump();
01169 #endif
01170       llvm_unreachable("Unknown constant!");
01171     }
01172     Stream.EmitRecord(Code, Record, AbbrevToUse);
01173     Record.clear();
01174   }
01175 
01176   Stream.ExitBlock();
01177 }
01178 
01179 static void WriteModuleConstants(const ValueEnumerator &VE,
01180                                  BitstreamWriter &Stream) {
01181   const ValueEnumerator::ValueList &Vals = VE.getValues();
01182 
01183   // Find the first constant to emit, which is the first non-globalvalue value.
01184   // We know globalvalues have been emitted by WriteModuleInfo.
01185   for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
01186     if (!isa<GlobalValue>(Vals[i].first)) {
01187       WriteConstants(i, Vals.size(), VE, Stream, true);
01188       return;
01189     }
01190   }
01191 }
01192 
01193 /// PushValueAndType - The file has to encode both the value and type id for
01194 /// many values, because we need to know what type to create for forward
01195 /// references.  However, most operands are not forward references, so this type
01196 /// field is not needed.
01197 ///
01198 /// This function adds V's value ID to Vals.  If the value ID is higher than the
01199 /// instruction ID, then it is a forward reference, and it also includes the
01200 /// type ID.  The value ID that is written is encoded relative to the InstID.
01201 static bool PushValueAndType(const Value *V, unsigned InstID,
01202                              SmallVectorImpl<unsigned> &Vals,
01203                              ValueEnumerator &VE) {
01204   unsigned ValID = VE.getValueID(V);
01205   // Make encoding relative to the InstID.
01206   Vals.push_back(InstID - ValID);
01207   if (ValID >= InstID) {
01208     Vals.push_back(VE.getTypeID(V->getType()));
01209     return true;
01210   }
01211   return false;
01212 }
01213 
01214 /// pushValue - Like PushValueAndType, but where the type of the value is
01215 /// omitted (perhaps it was already encoded in an earlier operand).
01216 static void pushValue(const Value *V, unsigned InstID,
01217                       SmallVectorImpl<unsigned> &Vals,
01218                       ValueEnumerator &VE) {
01219   unsigned ValID = VE.getValueID(V);
01220   Vals.push_back(InstID - ValID);
01221 }
01222 
01223 static void pushValueSigned(const Value *V, unsigned InstID,
01224                             SmallVectorImpl<uint64_t> &Vals,
01225                             ValueEnumerator &VE) {
01226   unsigned ValID = VE.getValueID(V);
01227   int64_t diff = ((int32_t)InstID - (int32_t)ValID);
01228   emitSignedInt64(Vals, diff);
01229 }
01230 
01231 /// WriteInstruction - Emit an instruction to the specified stream.
01232 static void WriteInstruction(const Instruction &I, unsigned InstID,
01233                              ValueEnumerator &VE, BitstreamWriter &Stream,
01234                              SmallVectorImpl<unsigned> &Vals) {
01235   unsigned Code = 0;
01236   unsigned AbbrevToUse = 0;
01237   VE.setInstructionID(&I);
01238   switch (I.getOpcode()) {
01239   default:
01240     if (Instruction::isCast(I.getOpcode())) {
01241       Code = bitc::FUNC_CODE_INST_CAST;
01242       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
01243         AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
01244       Vals.push_back(VE.getTypeID(I.getType()));
01245       Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
01246     } else {
01247       assert(isa<BinaryOperator>(I) && "Unknown instruction!");
01248       Code = bitc::FUNC_CODE_INST_BINOP;
01249       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
01250         AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
01251       pushValue(I.getOperand(1), InstID, Vals, VE);
01252       Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
01253       uint64_t Flags = GetOptimizationFlags(&I);
01254       if (Flags != 0) {
01255         if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
01256           AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
01257         Vals.push_back(Flags);
01258       }
01259     }
01260     break;
01261 
01262   case Instruction::GetElementPtr:
01263     Code = bitc::FUNC_CODE_INST_GEP;
01264     if (cast<GEPOperator>(&I)->isInBounds())
01265       Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
01266     for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
01267       PushValueAndType(I.getOperand(i), InstID, Vals, VE);
01268     break;
01269   case Instruction::ExtractValue: {
01270     Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
01271     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01272     const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
01273     for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
01274       Vals.push_back(*i);
01275     break;
01276   }
01277   case Instruction::InsertValue: {
01278     Code = bitc::FUNC_CODE_INST_INSERTVAL;
01279     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01280     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
01281     const InsertValueInst *IVI = cast<InsertValueInst>(&I);
01282     for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
01283       Vals.push_back(*i);
01284     break;
01285   }
01286   case Instruction::Select:
01287     Code = bitc::FUNC_CODE_INST_VSELECT;
01288     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
01289     pushValue(I.getOperand(2), InstID, Vals, VE);
01290     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01291     break;
01292   case Instruction::ExtractElement:
01293     Code = bitc::FUNC_CODE_INST_EXTRACTELT;
01294     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01295     PushValueAndType(I.getOperand(1), InstID, Vals, VE);
01296     break;
01297   case Instruction::InsertElement:
01298     Code = bitc::FUNC_CODE_INST_INSERTELT;
01299     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01300     pushValue(I.getOperand(1), InstID, Vals, VE);
01301     PushValueAndType(I.getOperand(2), InstID, Vals, VE);
01302     break;
01303   case Instruction::ShuffleVector:
01304     Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
01305     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01306     pushValue(I.getOperand(1), InstID, Vals, VE);
01307     pushValue(I.getOperand(2), InstID, Vals, VE);
01308     break;
01309   case Instruction::ICmp:
01310   case Instruction::FCmp:
01311     // compare returning Int1Ty or vector of Int1Ty
01312     Code = bitc::FUNC_CODE_INST_CMP2;
01313     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01314     pushValue(I.getOperand(1), InstID, Vals, VE);
01315     Vals.push_back(cast<CmpInst>(I).getPredicate());
01316     break;
01317 
01318   case Instruction::Ret:
01319     {
01320       Code = bitc::FUNC_CODE_INST_RET;
01321       unsigned NumOperands = I.getNumOperands();
01322       if (NumOperands == 0)
01323         AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
01324       else if (NumOperands == 1) {
01325         if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
01326           AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
01327       } else {
01328         for (unsigned i = 0, e = NumOperands; i != e; ++i)
01329           PushValueAndType(I.getOperand(i), InstID, Vals, VE);
01330       }
01331     }
01332     break;
01333   case Instruction::Br:
01334     {
01335       Code = bitc::FUNC_CODE_INST_BR;
01336       const BranchInst &II = cast<BranchInst>(I);
01337       Vals.push_back(VE.getValueID(II.getSuccessor(0)));
01338       if (II.isConditional()) {
01339         Vals.push_back(VE.getValueID(II.getSuccessor(1)));
01340         pushValue(II.getCondition(), InstID, Vals, VE);
01341       }
01342     }
01343     break;
01344   case Instruction::Switch:
01345     {
01346       Code = bitc::FUNC_CODE_INST_SWITCH;
01347       const SwitchInst &SI = cast<SwitchInst>(I);
01348       Vals.push_back(VE.getTypeID(SI.getCondition()->getType()));
01349       pushValue(SI.getCondition(), InstID, Vals, VE);
01350       Vals.push_back(VE.getValueID(SI.getDefaultDest()));
01351       for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
01352            i != e; ++i) {
01353         Vals.push_back(VE.getValueID(i.getCaseValue()));
01354         Vals.push_back(VE.getValueID(i.getCaseSuccessor()));
01355       }
01356     }
01357     break;
01358   case Instruction::IndirectBr:
01359     Code = bitc::FUNC_CODE_INST_INDIRECTBR;
01360     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
01361     // Encode the address operand as relative, but not the basic blocks.
01362     pushValue(I.getOperand(0), InstID, Vals, VE);
01363     for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i)
01364       Vals.push_back(VE.getValueID(I.getOperand(i)));
01365     break;
01366 
01367   case Instruction::Invoke: {
01368     const InvokeInst *II = cast<InvokeInst>(&I);
01369     const Value *Callee(II->getCalledValue());
01370     PointerType *PTy = cast<PointerType>(Callee->getType());
01371     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
01372     Code = bitc::FUNC_CODE_INST_INVOKE;
01373 
01374     Vals.push_back(VE.getAttributeID(II->getAttributes()));
01375     Vals.push_back(II->getCallingConv());
01376     Vals.push_back(VE.getValueID(II->getNormalDest()));
01377     Vals.push_back(VE.getValueID(II->getUnwindDest()));
01378     PushValueAndType(Callee, InstID, Vals, VE);
01379 
01380     // Emit value #'s for the fixed parameters.
01381     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
01382       pushValue(I.getOperand(i), InstID, Vals, VE);  // fixed param.
01383 
01384     // Emit type/value pairs for varargs params.
01385     if (FTy->isVarArg()) {
01386       for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3;
01387            i != e; ++i)
01388         PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
01389     }
01390     break;
01391   }
01392   case Instruction::Resume:
01393     Code = bitc::FUNC_CODE_INST_RESUME;
01394     PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01395     break;
01396   case Instruction::Unreachable:
01397     Code = bitc::FUNC_CODE_INST_UNREACHABLE;
01398     AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
01399     break;
01400 
01401   case Instruction::PHI: {
01402     const PHINode &PN = cast<PHINode>(I);
01403     Code = bitc::FUNC_CODE_INST_PHI;
01404     // With the newer instruction encoding, forward references could give
01405     // negative valued IDs.  This is most common for PHIs, so we use
01406     // signed VBRs.
01407     SmallVector<uint64_t, 128> Vals64;
01408     Vals64.push_back(VE.getTypeID(PN.getType()));
01409     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
01410       pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE);
01411       Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i)));
01412     }
01413     // Emit a Vals64 vector and exit.
01414     Stream.EmitRecord(Code, Vals64, AbbrevToUse);
01415     Vals64.clear();
01416     return;
01417   }
01418 
01419   case Instruction::LandingPad: {
01420     const LandingPadInst &LP = cast<LandingPadInst>(I);
01421     Code = bitc::FUNC_CODE_INST_LANDINGPAD;
01422     Vals.push_back(VE.getTypeID(LP.getType()));
01423     PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE);
01424     Vals.push_back(LP.isCleanup());
01425     Vals.push_back(LP.getNumClauses());
01426     for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) {
01427       if (LP.isCatch(I))
01428         Vals.push_back(LandingPadInst::Catch);
01429       else
01430         Vals.push_back(LandingPadInst::Filter);
01431       PushValueAndType(LP.getClause(I), InstID, Vals, VE);
01432     }
01433     break;
01434   }
01435 
01436   case Instruction::Alloca: {
01437     Code = bitc::FUNC_CODE_INST_ALLOCA;
01438     Vals.push_back(VE.getTypeID(I.getType()));
01439     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
01440     Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
01441     const AllocaInst &AI = cast<AllocaInst>(I);
01442     unsigned AlignRecord = Log2_32(AI.getAlignment()) + 1;
01443     assert(Log2_32(Value::MaximumAlignment) + 1 < 1 << 5 &&
01444            "not enough bits for maximum alignment");
01445     assert(AlignRecord < 1 << 5 && "alignment greater than 1 << 64");
01446     AlignRecord |= AI.isUsedWithInAlloca() << 5;
01447     Vals.push_back(AlignRecord);
01448     break;
01449   }
01450 
01451   case Instruction::Load:
01452     if (cast<LoadInst>(I).isAtomic()) {
01453       Code = bitc::FUNC_CODE_INST_LOADATOMIC;
01454       PushValueAndType(I.getOperand(0), InstID, Vals, VE);
01455     } else {
01456       Code = bitc::FUNC_CODE_INST_LOAD;
01457       if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))  // ptr
01458         AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
01459     }
01460     Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
01461     Vals.push_back(cast<LoadInst>(I).isVolatile());
01462     if (cast<LoadInst>(I).isAtomic()) {
01463       Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering()));
01464       Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope()));
01465     }
01466     break;
01467   case Instruction::Store:
01468     if (cast<StoreInst>(I).isAtomic())
01469       Code = bitc::FUNC_CODE_INST_STOREATOMIC;
01470     else
01471       Code = bitc::FUNC_CODE_INST_STORE;
01472     PushValueAndType(I.getOperand(1), InstID, Vals, VE);  // ptrty + ptr
01473     pushValue(I.getOperand(0), InstID, Vals, VE);         // val.
01474     Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
01475     Vals.push_back(cast<StoreInst>(I).isVolatile());
01476     if (cast<StoreInst>(I).isAtomic()) {
01477       Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering()));
01478       Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope()));
01479     }
01480     break;
01481   case Instruction::AtomicCmpXchg:
01482     Code = bitc::FUNC_CODE_INST_CMPXCHG;
01483     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
01484     pushValue(I.getOperand(1), InstID, Vals, VE);         // cmp.
01485     pushValue(I.getOperand(2), InstID, Vals, VE);         // newval.
01486     Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile());
01487     Vals.push_back(GetEncodedOrdering(
01488                      cast<AtomicCmpXchgInst>(I).getSuccessOrdering()));
01489     Vals.push_back(GetEncodedSynchScope(
01490                      cast<AtomicCmpXchgInst>(I).getSynchScope()));
01491     Vals.push_back(GetEncodedOrdering(
01492                      cast<AtomicCmpXchgInst>(I).getFailureOrdering()));
01493     Vals.push_back(cast<AtomicCmpXchgInst>(I).isWeak());
01494     break;
01495   case Instruction::AtomicRMW:
01496     Code = bitc::FUNC_CODE_INST_ATOMICRMW;
01497     PushValueAndType(I.getOperand(0), InstID, Vals, VE);  // ptrty + ptr
01498     pushValue(I.getOperand(1), InstID, Vals, VE);         // val.
01499     Vals.push_back(GetEncodedRMWOperation(
01500                      cast<AtomicRMWInst>(I).getOperation()));
01501     Vals.push_back(cast<AtomicRMWInst>(I).isVolatile());
01502     Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering()));
01503     Vals.push_back(GetEncodedSynchScope(
01504                      cast<AtomicRMWInst>(I).getSynchScope()));
01505     break;
01506   case Instruction::Fence:
01507     Code = bitc::FUNC_CODE_INST_FENCE;
01508     Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering()));
01509     Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope()));
01510     break;
01511   case Instruction::Call: {
01512     const CallInst &CI = cast<CallInst>(I);
01513     PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType());
01514     FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
01515 
01516     Code = bitc::FUNC_CODE_INST_CALL;
01517 
01518     Vals.push_back(VE.getAttributeID(CI.getAttributes()));
01519     Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall()) |
01520                    unsigned(CI.isMustTailCall()) << 14);
01521     PushValueAndType(CI.getCalledValue(), InstID, Vals, VE);  // Callee
01522 
01523     // Emit value #'s for the fixed parameters.
01524     for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
01525       // Check for labels (can happen with asm labels).
01526       if (FTy->getParamType(i)->isLabelTy())
01527         Vals.push_back(VE.getValueID(CI.getArgOperand(i)));
01528       else
01529         pushValue(CI.getArgOperand(i), InstID, Vals, VE);  // fixed param.
01530     }
01531 
01532     // Emit type/value pairs for varargs params.
01533     if (FTy->isVarArg()) {
01534       for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands();
01535            i != e; ++i)
01536         PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE);  // varargs
01537     }
01538     break;
01539   }
01540   case Instruction::VAArg:
01541     Code = bitc::FUNC_CODE_INST_VAARG;
01542     Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));   // valistty
01543     pushValue(I.getOperand(0), InstID, Vals, VE); // valist.
01544     Vals.push_back(VE.getTypeID(I.getType())); // restype.
01545     break;
01546   }
01547 
01548   Stream.EmitRecord(Code, Vals, AbbrevToUse);
01549   Vals.clear();
01550 }
01551 
01552 // Emit names for globals/functions etc.
01553 static void WriteValueSymbolTable(const ValueSymbolTable &VST,
01554                                   const ValueEnumerator &VE,
01555                                   BitstreamWriter &Stream) {
01556   if (VST.empty()) return;
01557   Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
01558 
01559   // FIXME: Set up the abbrev, we know how many values there are!
01560   // FIXME: We know if the type names can use 7-bit ascii.
01561   SmallVector<unsigned, 64> NameVals;
01562 
01563   for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
01564        SI != SE; ++SI) {
01565 
01566     const ValueName &Name = *SI;
01567 
01568     // Figure out the encoding to use for the name.
01569     bool is7Bit = true;
01570     bool isChar6 = true;
01571     for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
01572          C != E; ++C) {
01573       if (isChar6)
01574         isChar6 = BitCodeAbbrevOp::isChar6(*C);
01575       if ((unsigned char)*C & 128) {
01576         is7Bit = false;
01577         break;  // don't bother scanning the rest.
01578       }
01579     }
01580 
01581     unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
01582 
01583     // VST_ENTRY:   [valueid, namechar x N]
01584     // VST_BBENTRY: [bbid, namechar x N]
01585     unsigned Code;
01586     if (isa<BasicBlock>(SI->getValue())) {
01587       Code = bitc::VST_CODE_BBENTRY;
01588       if (isChar6)
01589         AbbrevToUse = VST_BBENTRY_6_ABBREV;
01590     } else {
01591       Code = bitc::VST_CODE_ENTRY;
01592       if (isChar6)
01593         AbbrevToUse = VST_ENTRY_6_ABBREV;
01594       else if (is7Bit)
01595         AbbrevToUse = VST_ENTRY_7_ABBREV;
01596     }
01597 
01598     NameVals.push_back(VE.getValueID(SI->getValue()));
01599     for (const char *P = Name.getKeyData(),
01600          *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
01601       NameVals.push_back((unsigned char)*P);
01602 
01603     // Emit the finished record.
01604     Stream.EmitRecord(Code, NameVals, AbbrevToUse);
01605     NameVals.clear();
01606   }
01607   Stream.ExitBlock();
01608 }
01609 
01610 /// WriteFunction - Emit a function body to the module stream.
01611 static void WriteFunction(const Function &F, ValueEnumerator &VE,
01612                           BitstreamWriter &Stream) {
01613   Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
01614   VE.incorporateFunction(F);
01615 
01616   SmallVector<unsigned, 64> Vals;
01617 
01618   // Emit the number of basic blocks, so the reader can create them ahead of
01619   // time.
01620   Vals.push_back(VE.getBasicBlocks().size());
01621   Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
01622   Vals.clear();
01623 
01624   // If there are function-local constants, emit them now.
01625   unsigned CstStart, CstEnd;
01626   VE.getFunctionConstantRange(CstStart, CstEnd);
01627   WriteConstants(CstStart, CstEnd, VE, Stream, false);
01628 
01629   // If there is function-local metadata, emit it now.
01630   WriteFunctionLocalMetadata(F, VE, Stream);
01631 
01632   // Keep a running idea of what the instruction ID is.
01633   unsigned InstID = CstEnd;
01634 
01635   bool NeedsMetadataAttachment = false;
01636 
01637   DebugLoc LastDL;
01638 
01639   // Finally, emit all the instructions, in order.
01640   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
01641     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
01642          I != E; ++I) {
01643       WriteInstruction(*I, InstID, VE, Stream, Vals);
01644 
01645       if (!I->getType()->isVoidTy())
01646         ++InstID;
01647 
01648       // If the instruction has metadata, write a metadata attachment later.
01649       NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc();
01650 
01651       // If the instruction has a debug location, emit it.
01652       DebugLoc DL = I->getDebugLoc();
01653       if (DL.isUnknown()) {
01654         // nothing todo.
01655       } else if (DL == LastDL) {
01656         // Just repeat the same debug loc as last time.
01657         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals);
01658       } else {
01659         MDNode *Scope, *IA;
01660         DL.getScopeAndInlinedAt(Scope, IA, I->getContext());
01661 
01662         Vals.push_back(DL.getLine());
01663         Vals.push_back(DL.getCol());
01664         Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0);
01665         Vals.push_back(IA ? VE.getValueID(IA)+1 : 0);
01666         Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals);
01667         Vals.clear();
01668 
01669         LastDL = DL;
01670       }
01671     }
01672 
01673   // Emit names for all the instructions etc.
01674   WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
01675 
01676   if (NeedsMetadataAttachment)
01677     WriteMetadataAttachment(F, VE, Stream);
01678   VE.purgeFunction();
01679   Stream.ExitBlock();
01680 }
01681 
01682 // Emit blockinfo, which defines the standard abbreviations etc.
01683 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
01684   // We only want to emit block info records for blocks that have multiple
01685   // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK.
01686   // Other blocks can define their abbrevs inline.
01687   Stream.EnterBlockInfoBlock(2);
01688 
01689   { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
01690     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01691     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
01692     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01693     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01694     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
01695     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
01696                                    Abbv) != VST_ENTRY_8_ABBREV)
01697       llvm_unreachable("Unexpected abbrev ordering!");
01698   }
01699 
01700   { // 7-bit fixed width VST_ENTRY strings.
01701     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01702     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
01703     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01704     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01705     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
01706     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
01707                                    Abbv) != VST_ENTRY_7_ABBREV)
01708       llvm_unreachable("Unexpected abbrev ordering!");
01709   }
01710   { // 6-bit char6 VST_ENTRY strings.
01711     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01712     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
01713     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01714     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01715     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
01716     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
01717                                    Abbv) != VST_ENTRY_6_ABBREV)
01718       llvm_unreachable("Unexpected abbrev ordering!");
01719   }
01720   { // 6-bit char6 VST_BBENTRY strings.
01721     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01722     Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
01723     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01724     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
01725     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
01726     if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
01727                                    Abbv) != VST_BBENTRY_6_ABBREV)
01728       llvm_unreachable("Unexpected abbrev ordering!");
01729   }
01730 
01731 
01732 
01733   { // SETTYPE abbrev for CONSTANTS_BLOCK.
01734     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01735     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
01736     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
01737                               Log2_32_Ceil(VE.getTypes().size()+1)));
01738     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
01739                                    Abbv) != CONSTANTS_SETTYPE_ABBREV)
01740       llvm_unreachable("Unexpected abbrev ordering!");
01741   }
01742 
01743   { // INTEGER abbrev for CONSTANTS_BLOCK.
01744     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01745     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
01746     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
01747     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
01748                                    Abbv) != CONSTANTS_INTEGER_ABBREV)
01749       llvm_unreachable("Unexpected abbrev ordering!");
01750   }
01751 
01752   { // CE_CAST abbrev for CONSTANTS_BLOCK.
01753     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01754     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
01755     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // cast opc
01756     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // typeid
01757                               Log2_32_Ceil(VE.getTypes().size()+1)));
01758     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));    // value id
01759 
01760     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
01761                                    Abbv) != CONSTANTS_CE_CAST_Abbrev)
01762       llvm_unreachable("Unexpected abbrev ordering!");
01763   }
01764   { // NULL abbrev for CONSTANTS_BLOCK.
01765     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01766     Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
01767     if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
01768                                    Abbv) != CONSTANTS_NULL_Abbrev)
01769       llvm_unreachable("Unexpected abbrev ordering!");
01770   }
01771 
01772   // FIXME: This should only use space for first class types!
01773 
01774   { // INST_LOAD abbrev for FUNCTION_BLOCK.
01775     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01776     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
01777     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
01778     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
01779     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
01780     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01781                                    Abbv) != FUNCTION_INST_LOAD_ABBREV)
01782       llvm_unreachable("Unexpected abbrev ordering!");
01783   }
01784   { // INST_BINOP abbrev for FUNCTION_BLOCK.
01785     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01786     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
01787     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
01788     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
01789     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
01790     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01791                                    Abbv) != FUNCTION_INST_BINOP_ABBREV)
01792       llvm_unreachable("Unexpected abbrev ordering!");
01793   }
01794   { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
01795     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01796     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
01797     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
01798     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
01799     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
01800     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
01801     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01802                                    Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
01803       llvm_unreachable("Unexpected abbrev ordering!");
01804   }
01805   { // INST_CAST abbrev for FUNCTION_BLOCK.
01806     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01807     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
01808     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6));    // OpVal
01809     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,       // dest ty
01810                               Log2_32_Ceil(VE.getTypes().size()+1)));
01811     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4));  // opc
01812     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01813                                    Abbv) != FUNCTION_INST_CAST_ABBREV)
01814       llvm_unreachable("Unexpected abbrev ordering!");
01815   }
01816 
01817   { // INST_RET abbrev for FUNCTION_BLOCK.
01818     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01819     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
01820     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01821                                    Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
01822       llvm_unreachable("Unexpected abbrev ordering!");
01823   }
01824   { // INST_RET abbrev for FUNCTION_BLOCK.
01825     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01826     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
01827     Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
01828     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01829                                    Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
01830       llvm_unreachable("Unexpected abbrev ordering!");
01831   }
01832   { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
01833     BitCodeAbbrev *Abbv = new BitCodeAbbrev();
01834     Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
01835     if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
01836                                    Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
01837       llvm_unreachable("Unexpected abbrev ordering!");
01838   }
01839 
01840   Stream.ExitBlock();
01841 }
01842 
01843 // Sort the Users based on the order in which the reader parses the bitcode
01844 // file.
01845 static bool bitcodereader_order(const User *lhs, const User *rhs) {
01846   // TODO: Implement.
01847   return true;
01848 }
01849 
01850 static void WriteUseList(const Value *V, const ValueEnumerator &VE,
01851                          BitstreamWriter &Stream) {
01852 
01853   // One or zero uses can't get out of order.
01854   if (V->use_empty() || V->hasNUses(1))
01855     return;
01856 
01857   // Make a copy of the in-memory use-list for sorting.
01858   SmallVector<const User*, 8> UserList(V->user_begin(), V->user_end());
01859 
01860   // Sort the copy based on the order read by the BitcodeReader.
01861   std::sort(UserList.begin(), UserList.end(), bitcodereader_order);
01862 
01863   // TODO: Generate a diff between the BitcodeWriter in-memory use-list and the
01864   // sorted list (i.e., the expected BitcodeReader in-memory use-list).
01865 
01866   // TODO: Emit the USELIST_CODE_ENTRYs.
01867 }
01868 
01869 static void WriteFunctionUseList(const Function *F, ValueEnumerator &VE,
01870                                  BitstreamWriter &Stream) {
01871   VE.incorporateFunction(*F);
01872 
01873   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
01874        AI != AE; ++AI)
01875     WriteUseList(AI, VE, Stream);
01876   for (Function::const_iterator BB = F->begin(), FE = F->end(); BB != FE;
01877        ++BB) {
01878     WriteUseList(BB, VE, Stream);
01879     for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE;
01880          ++II) {
01881       WriteUseList(II, VE, Stream);
01882       for (User::const_op_iterator OI = II->op_begin(), E = II->op_end();
01883            OI != E; ++OI) {
01884         if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
01885             isa<InlineAsm>(*OI))
01886           WriteUseList(*OI, VE, Stream);
01887       }
01888     }
01889   }
01890   VE.purgeFunction();
01891 }
01892 
01893 // Emit use-lists.
01894 static void WriteModuleUseLists(const Module *M, ValueEnumerator &VE,
01895                                 BitstreamWriter &Stream) {
01896   Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3);
01897 
01898   // XXX: this modifies the module, but in a way that should never change the
01899   // behavior of any pass or codegen in LLVM. The problem is that GVs may
01900   // contain entries in the use_list that do not exist in the Module and are
01901   // not stored in the .bc file.
01902   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
01903        I != E; ++I)
01904     I->removeDeadConstantUsers();
01905 
01906   // Write the global variables.
01907   for (Module::const_global_iterator GI = M->global_begin(),
01908          GE = M->global_end(); GI != GE; ++GI) {
01909     WriteUseList(GI, VE, Stream);
01910 
01911     // Write the global variable initializers.
01912     if (GI->hasInitializer())
01913       WriteUseList(GI->getInitializer(), VE, Stream);
01914   }
01915 
01916   // Write the functions.
01917   for (Module::const_iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) {
01918     WriteUseList(FI, VE, Stream);
01919     if (!FI->isDeclaration())
01920       WriteFunctionUseList(FI, VE, Stream);
01921     if (FI->hasPrefixData())
01922       WriteUseList(FI->getPrefixData(), VE, Stream);
01923   }
01924 
01925   // Write the aliases.
01926   for (Module::const_alias_iterator AI = M->alias_begin(), AE = M->alias_end();
01927        AI != AE; ++AI) {
01928     WriteUseList(AI, VE, Stream);
01929     WriteUseList(AI->getAliasee(), VE, Stream);
01930   }
01931 
01932   Stream.ExitBlock();
01933 }
01934 
01935 /// WriteModule - Emit the specified module to the bitstream.
01936 static void WriteModule(const Module *M, BitstreamWriter &Stream) {
01937   Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
01938 
01939   SmallVector<unsigned, 1> Vals;
01940   unsigned CurVersion = 1;
01941   Vals.push_back(CurVersion);
01942   Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
01943 
01944   // Analyze the module, enumerating globals, functions, etc.
01945   ValueEnumerator VE(M);
01946 
01947   // Emit blockinfo, which defines the standard abbreviations etc.
01948   WriteBlockInfo(VE, Stream);
01949 
01950   // Emit information about attribute groups.
01951   WriteAttributeGroupTable(VE, Stream);
01952 
01953   // Emit information about parameter attributes.
01954   WriteAttributeTable(VE, Stream);
01955 
01956   // Emit information describing all of the types in the module.
01957   WriteTypeTable(VE, Stream);
01958 
01959   writeComdats(VE, Stream);
01960 
01961   // Emit top-level description of module, including target triple, inline asm,
01962   // descriptors for global variables, and function prototype info.
01963   WriteModuleInfo(M, VE, Stream);
01964 
01965   // Emit constants.
01966   WriteModuleConstants(VE, Stream);
01967 
01968   // Emit metadata.
01969   WriteModuleMetadata(M, VE, Stream);
01970 
01971   // Emit metadata.
01972   WriteModuleMetadataStore(M, Stream);
01973 
01974   // Emit names for globals/functions etc.
01975   WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
01976 
01977   // Emit use-lists.
01978   if (EnablePreserveUseListOrdering)
01979     WriteModuleUseLists(M, VE, Stream);
01980 
01981   // Emit function bodies.
01982   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F)
01983     if (!F->isDeclaration())
01984       WriteFunction(*F, VE, Stream);
01985 
01986   Stream.ExitBlock();
01987 }
01988 
01989 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
01990 /// header and trailer to make it compatible with the system archiver.  To do
01991 /// this we emit the following header, and then emit a trailer that pads the
01992 /// file out to be a multiple of 16 bytes.
01993 ///
01994 /// struct bc_header {
01995 ///   uint32_t Magic;         // 0x0B17C0DE
01996 ///   uint32_t Version;       // Version, currently always 0.
01997 ///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
01998 ///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
01999 ///   uint32_t CPUType;       // CPU specifier.
02000 ///   ... potentially more later ...
02001 /// };
02002 enum {
02003   DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
02004   DarwinBCHeaderSize = 5*4
02005 };
02006 
02007 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer,
02008                                uint32_t &Position) {
02009   Buffer[Position + 0] = (unsigned char) (Value >>  0);
02010   Buffer[Position + 1] = (unsigned char) (Value >>  8);
02011   Buffer[Position + 2] = (unsigned char) (Value >> 16);
02012   Buffer[Position + 3] = (unsigned char) (Value >> 24);
02013   Position += 4;
02014 }
02015 
02016 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer,
02017                                          const Triple &TT) {
02018   unsigned CPUType = ~0U;
02019 
02020   // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*,
02021   // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic
02022   // number from /usr/include/mach/machine.h.  It is ok to reproduce the
02023   // specific constants here because they are implicitly part of the Darwin ABI.
02024   enum {
02025     DARWIN_CPU_ARCH_ABI64      = 0x01000000,
02026     DARWIN_CPU_TYPE_X86        = 7,
02027     DARWIN_CPU_TYPE_ARM        = 12,
02028     DARWIN_CPU_TYPE_POWERPC    = 18
02029   };
02030 
02031   Triple::ArchType Arch = TT.getArch();
02032   if (Arch == Triple::x86_64)
02033     CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
02034   else if (Arch == Triple::x86)
02035     CPUType = DARWIN_CPU_TYPE_X86;
02036   else if (Arch == Triple::ppc)
02037     CPUType = DARWIN_CPU_TYPE_POWERPC;
02038   else if (Arch == Triple::ppc64)
02039     CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
02040   else if (Arch == Triple::arm || Arch == Triple::thumb)
02041     CPUType = DARWIN_CPU_TYPE_ARM;
02042 
02043   // Traditional Bitcode starts after header.
02044   assert(Buffer.size() >= DarwinBCHeaderSize &&
02045          "Expected header size to be reserved");
02046   unsigned BCOffset = DarwinBCHeaderSize;
02047   unsigned BCSize = Buffer.size()-DarwinBCHeaderSize;
02048 
02049   // Write the magic and version.
02050   unsigned Position = 0;
02051   WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position);
02052   WriteInt32ToBuffer(0          , Buffer, Position); // Version.
02053   WriteInt32ToBuffer(BCOffset   , Buffer, Position);
02054   WriteInt32ToBuffer(BCSize     , Buffer, Position);
02055   WriteInt32ToBuffer(CPUType    , Buffer, Position);
02056 
02057   // If the file is not a multiple of 16 bytes, insert dummy padding.
02058   while (Buffer.size() & 15)
02059     Buffer.push_back(0);
02060 }
02061 
02062 /// WriteBitcodeToFile - Write the specified module to the specified output
02063 /// stream.
02064 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
02065   SmallVector<char, 0> Buffer;
02066   Buffer.reserve(256*1024);
02067 
02068   // If this is darwin or another generic macho target, reserve space for the
02069   // header.
02070   Triple TT(M->getTargetTriple());
02071   if (TT.isOSDarwin())
02072     Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0);
02073 
02074   // Emit the module into the buffer.
02075   {
02076     BitstreamWriter Stream(Buffer);
02077 
02078     // Emit the file header.
02079     Stream.Emit((unsigned)'B', 8);
02080     Stream.Emit((unsigned)'C', 8);
02081     Stream.Emit(0x0, 4);
02082     Stream.Emit(0xC, 4);
02083     Stream.Emit(0xE, 4);
02084     Stream.Emit(0xD, 4);
02085 
02086     // Emit the module.
02087     WriteModule(M, Stream);
02088   }
02089 
02090   if (TT.isOSDarwin())
02091     EmitDarwinBCHeaderAndTrailer(Buffer, TT);
02092 
02093   // Write the generated bitstream to "Out".
02094   Out.write((char*)&Buffer.front(), Buffer.size());
02095 }