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