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