LLVM API Documentation

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