LLVM API Documentation

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