BitcodeWriter.cpp revision d7bb295d223e028aa9ba7fbeafc8928db4a74972
1//===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// Bitcode writer implementation. 11// 12//===----------------------------------------------------------------------===// 13 14#include "llvm/Bitcode/ReaderWriter.h" 15#include "llvm/Bitcode/BitstreamWriter.h" 16#include "llvm/Bitcode/LLVMBitCodes.h" 17#include "ValueEnumerator.h" 18#include "llvm/Constants.h" 19#include "llvm/DerivedTypes.h" 20#include "llvm/InlineAsm.h" 21#include "llvm/Instructions.h" 22#include "llvm/Module.h" 23#include "llvm/Operator.h" 24#include "llvm/TypeSymbolTable.h" 25#include "llvm/ValueSymbolTable.h" 26#include "llvm/Support/ErrorHandling.h" 27#include "llvm/Support/MathExtras.h" 28#include "llvm/Support/raw_ostream.h" 29#include "llvm/Support/Program.h" 30#include <cctype> 31using namespace llvm; 32 33/// These are manifest constants used by the bitcode writer. They do not need to 34/// be kept in sync with the reader, but need to be consistent within this file. 35enum { 36 CurVersion = 0, 37 38 // VALUE_SYMTAB_BLOCK abbrev id's. 39 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 40 VST_ENTRY_7_ABBREV, 41 VST_ENTRY_6_ABBREV, 42 VST_BBENTRY_6_ABBREV, 43 VST_LPADENTRY_6_ABBREV, 44 45 // CONSTANTS_BLOCK abbrev id's. 46 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 47 CONSTANTS_INTEGER_ABBREV, 48 CONSTANTS_CE_CAST_Abbrev, 49 CONSTANTS_NULL_Abbrev, 50 51 // FUNCTION_BLOCK abbrev id's. 52 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 53 FUNCTION_INST_BINOP_ABBREV, 54 FUNCTION_INST_BINOP_FLAGS_ABBREV, 55 FUNCTION_INST_CAST_ABBREV, 56 FUNCTION_INST_RET_VOID_ABBREV, 57 FUNCTION_INST_RET_VAL_ABBREV, 58 FUNCTION_INST_UNREACHABLE_ABBREV 59}; 60 61 62static unsigned GetEncodedCastOpcode(unsigned Opcode) { 63 switch (Opcode) { 64 default: llvm_unreachable("Unknown cast instruction!"); 65 case Instruction::Trunc : return bitc::CAST_TRUNC; 66 case Instruction::ZExt : return bitc::CAST_ZEXT; 67 case Instruction::SExt : return bitc::CAST_SEXT; 68 case Instruction::FPToUI : return bitc::CAST_FPTOUI; 69 case Instruction::FPToSI : return bitc::CAST_FPTOSI; 70 case Instruction::UIToFP : return bitc::CAST_UITOFP; 71 case Instruction::SIToFP : return bitc::CAST_SITOFP; 72 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC; 73 case Instruction::FPExt : return bitc::CAST_FPEXT; 74 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT; 75 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR; 76 case Instruction::BitCast : return bitc::CAST_BITCAST; 77 } 78} 79 80static unsigned GetEncodedBinaryOpcode(unsigned Opcode) { 81 switch (Opcode) { 82 default: llvm_unreachable("Unknown binary instruction!"); 83 case Instruction::Add: 84 case Instruction::FAdd: return bitc::BINOP_ADD; 85 case Instruction::Sub: 86 case Instruction::FSub: return bitc::BINOP_SUB; 87 case Instruction::Mul: 88 case Instruction::FMul: return bitc::BINOP_MUL; 89 case Instruction::UDiv: return bitc::BINOP_UDIV; 90 case Instruction::FDiv: 91 case Instruction::SDiv: return bitc::BINOP_SDIV; 92 case Instruction::URem: return bitc::BINOP_UREM; 93 case Instruction::FRem: 94 case Instruction::SRem: return bitc::BINOP_SREM; 95 case Instruction::Shl: return bitc::BINOP_SHL; 96 case Instruction::LShr: return bitc::BINOP_LSHR; 97 case Instruction::AShr: return bitc::BINOP_ASHR; 98 case Instruction::And: return bitc::BINOP_AND; 99 case Instruction::Or: return bitc::BINOP_OR; 100 case Instruction::Xor: return bitc::BINOP_XOR; 101 } 102} 103 104 105 106static void WriteStringRecord(unsigned Code, const std::string &Str, 107 unsigned AbbrevToUse, BitstreamWriter &Stream) { 108 SmallVector<unsigned, 64> Vals; 109 110 // Code: [strchar x N] 111 for (unsigned i = 0, e = Str.size(); i != e; ++i) 112 Vals.push_back(Str[i]); 113 114 // Emit the finished record. 115 Stream.EmitRecord(Code, Vals, AbbrevToUse); 116} 117 118// Emit information about parameter attributes. 119static void WriteAttributeTable(const ValueEnumerator &VE, 120 BitstreamWriter &Stream) { 121 const std::vector<AttrListPtr> &Attrs = VE.getAttributes(); 122 if (Attrs.empty()) return; 123 124 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3); 125 126 SmallVector<uint64_t, 64> Record; 127 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) { 128 const AttrListPtr &A = Attrs[i]; 129 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) { 130 const AttributeWithIndex &PAWI = A.getSlot(i); 131 Record.push_back(PAWI.Index); 132 133 // FIXME: remove in LLVM 3.0 134 // Store the alignment in the bitcode as a 16-bit raw value instead of a 135 // 5-bit log2 encoded value. Shift the bits above the alignment up by 136 // 11 bits. 137 uint64_t FauxAttr = PAWI.Attrs & 0xffff; 138 if (PAWI.Attrs & Attribute::Alignment) 139 FauxAttr |= (1ull<<16)<<(((PAWI.Attrs & Attribute::Alignment)-1) >> 16); 140 FauxAttr |= (PAWI.Attrs & (0x3FFull << 21)) << 11; 141 142 Record.push_back(FauxAttr); 143 } 144 145 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record); 146 Record.clear(); 147 } 148 149 Stream.ExitBlock(); 150} 151 152/// WriteTypeTable - Write out the type table for a module. 153static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) { 154 const ValueEnumerator::TypeList &TypeList = VE.getTypes(); 155 156 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */); 157 SmallVector<uint64_t, 64> TypeVals; 158 159 // Abbrev for TYPE_CODE_POINTER. 160 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 161 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER)); 162 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 163 Log2_32_Ceil(VE.getTypes().size()+1))); 164 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0 165 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv); 166 167 // Abbrev for TYPE_CODE_FUNCTION. 168 Abbv = new BitCodeAbbrev(); 169 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION)); 170 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg 171 Abbv->Add(BitCodeAbbrevOp(0)); // FIXME: DEAD value, remove in LLVM 3.0 172 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 173 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 174 Log2_32_Ceil(VE.getTypes().size()+1))); 175 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv); 176 177 // Abbrev for TYPE_CODE_STRUCT. 178 Abbv = new BitCodeAbbrev(); 179 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT)); 180 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 181 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 182 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 183 Log2_32_Ceil(VE.getTypes().size()+1))); 184 unsigned StructAbbrev = Stream.EmitAbbrev(Abbv); 185 186 // Abbrev for TYPE_CODE_ARRAY. 187 Abbv = new BitCodeAbbrev(); 188 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY)); 189 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size 190 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 191 Log2_32_Ceil(VE.getTypes().size()+1))); 192 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv); 193 194 // Emit an entry count so the reader can reserve space. 195 TypeVals.push_back(TypeList.size()); 196 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals); 197 TypeVals.clear(); 198 199 // Loop over all of the types, emitting each in turn. 200 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) { 201 const Type *T = TypeList[i]; 202 int AbbrevToUse = 0; 203 unsigned Code = 0; 204 205 switch (T->getTypeID()) { 206 default: llvm_unreachable("Unknown type!"); 207 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break; 208 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break; 209 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break; 210 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break; 211 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break; 212 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break; 213 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break; 214 case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break; 215 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break; 216 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break; 217 case Type::IntegerTyID: 218 // INTEGER: [width] 219 Code = bitc::TYPE_CODE_INTEGER; 220 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth()); 221 break; 222 case Type::PointerTyID: { 223 const PointerType *PTy = cast<PointerType>(T); 224 // POINTER: [pointee type, address space] 225 Code = bitc::TYPE_CODE_POINTER; 226 TypeVals.push_back(VE.getTypeID(PTy->getElementType())); 227 unsigned AddressSpace = PTy->getAddressSpace(); 228 TypeVals.push_back(AddressSpace); 229 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev; 230 break; 231 } 232 case Type::FunctionTyID: { 233 const FunctionType *FT = cast<FunctionType>(T); 234 // FUNCTION: [isvararg, attrid, retty, paramty x N] 235 Code = bitc::TYPE_CODE_FUNCTION; 236 TypeVals.push_back(FT->isVarArg()); 237 TypeVals.push_back(0); // FIXME: DEAD: remove in llvm 3.0 238 TypeVals.push_back(VE.getTypeID(FT->getReturnType())); 239 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) 240 TypeVals.push_back(VE.getTypeID(FT->getParamType(i))); 241 AbbrevToUse = FunctionAbbrev; 242 break; 243 } 244 case Type::StructTyID: { 245 const StructType *ST = cast<StructType>(T); 246 // STRUCT: [ispacked, eltty x N] 247 Code = bitc::TYPE_CODE_STRUCT; 248 TypeVals.push_back(ST->isPacked()); 249 // Output all of the element types. 250 for (StructType::element_iterator I = ST->element_begin(), 251 E = ST->element_end(); I != E; ++I) 252 TypeVals.push_back(VE.getTypeID(*I)); 253 AbbrevToUse = StructAbbrev; 254 break; 255 } 256 case Type::ArrayTyID: { 257 const ArrayType *AT = cast<ArrayType>(T); 258 // ARRAY: [numelts, eltty] 259 Code = bitc::TYPE_CODE_ARRAY; 260 TypeVals.push_back(AT->getNumElements()); 261 TypeVals.push_back(VE.getTypeID(AT->getElementType())); 262 AbbrevToUse = ArrayAbbrev; 263 break; 264 } 265 case Type::VectorTyID: { 266 const VectorType *VT = cast<VectorType>(T); 267 // VECTOR [numelts, eltty] 268 Code = bitc::TYPE_CODE_VECTOR; 269 TypeVals.push_back(VT->getNumElements()); 270 TypeVals.push_back(VE.getTypeID(VT->getElementType())); 271 break; 272 } 273 } 274 275 // Emit the finished record. 276 Stream.EmitRecord(Code, TypeVals, AbbrevToUse); 277 TypeVals.clear(); 278 } 279 280 Stream.ExitBlock(); 281} 282 283static unsigned getEncodedLinkage(const GlobalValue *GV) { 284 switch (GV->getLinkage()) { 285 default: llvm_unreachable("Invalid linkage!"); 286 case GlobalValue::ExternalLinkage: return 0; 287 case GlobalValue::WeakAnyLinkage: return 1; 288 case GlobalValue::AppendingLinkage: return 2; 289 case GlobalValue::InternalLinkage: return 3; 290 case GlobalValue::LinkOnceAnyLinkage: return 4; 291 case GlobalValue::DLLImportLinkage: return 5; 292 case GlobalValue::DLLExportLinkage: return 6; 293 case GlobalValue::ExternalWeakLinkage: return 7; 294 case GlobalValue::CommonLinkage: return 8; 295 case GlobalValue::PrivateLinkage: return 9; 296 case GlobalValue::WeakODRLinkage: return 10; 297 case GlobalValue::LinkOnceODRLinkage: return 11; 298 case GlobalValue::AvailableExternallyLinkage: return 12; 299 case GlobalValue::LinkerPrivateLinkage: return 13; 300 case GlobalValue::LinkerPrivateWeakLinkage: return 14; 301 case GlobalValue::LinkerPrivateWeakDefAutoLinkage: return 15; 302 } 303} 304 305static unsigned getEncodedVisibility(const GlobalValue *GV) { 306 switch (GV->getVisibility()) { 307 default: llvm_unreachable("Invalid visibility!"); 308 case GlobalValue::DefaultVisibility: return 0; 309 case GlobalValue::HiddenVisibility: return 1; 310 case GlobalValue::ProtectedVisibility: return 2; 311 } 312} 313 314// Emit top-level description of module, including target triple, inline asm, 315// descriptors for global variables, and function prototype info. 316static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE, 317 BitstreamWriter &Stream) { 318 // Emit the list of dependent libraries for the Module. 319 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I) 320 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream); 321 322 // Emit various pieces of data attached to a module. 323 if (!M->getTargetTriple().empty()) 324 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(), 325 0/*TODO*/, Stream); 326 if (!M->getDataLayout().empty()) 327 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(), 328 0/*TODO*/, Stream); 329 if (!M->getModuleInlineAsm().empty()) 330 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(), 331 0/*TODO*/, Stream); 332 333 // Emit information about sections and GC, computing how many there are. Also 334 // compute the maximum alignment value. 335 std::map<std::string, unsigned> SectionMap; 336 std::map<std::string, unsigned> GCMap; 337 unsigned MaxAlignment = 0; 338 unsigned MaxGlobalType = 0; 339 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end(); 340 GV != E; ++GV) { 341 MaxAlignment = std::max(MaxAlignment, GV->getAlignment()); 342 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType())); 343 344 if (!GV->hasSection()) continue; 345 // Give section names unique ID's. 346 unsigned &Entry = SectionMap[GV->getSection()]; 347 if (Entry != 0) continue; 348 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(), 349 0/*TODO*/, Stream); 350 Entry = SectionMap.size(); 351 } 352 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) { 353 MaxAlignment = std::max(MaxAlignment, F->getAlignment()); 354 if (F->hasSection()) { 355 // Give section names unique ID's. 356 unsigned &Entry = SectionMap[F->getSection()]; 357 if (!Entry) { 358 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(), 359 0/*TODO*/, Stream); 360 Entry = SectionMap.size(); 361 } 362 } 363 if (F->hasGC()) { 364 // Same for GC names. 365 unsigned &Entry = GCMap[F->getGC()]; 366 if (!Entry) { 367 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(), 368 0/*TODO*/, Stream); 369 Entry = GCMap.size(); 370 } 371 } 372 } 373 374 // Emit abbrev for globals, now that we know # sections and max alignment. 375 unsigned SimpleGVarAbbrev = 0; 376 if (!M->global_empty()) { 377 // Add an abbrev for common globals with no visibility or thread localness. 378 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 379 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR)); 380 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 381 Log2_32_Ceil(MaxGlobalType+1))); 382 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant. 383 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer. 384 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage. 385 if (MaxAlignment == 0) // Alignment. 386 Abbv->Add(BitCodeAbbrevOp(0)); 387 else { 388 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1; 389 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 390 Log2_32_Ceil(MaxEncAlignment+1))); 391 } 392 if (SectionMap.empty()) // Section. 393 Abbv->Add(BitCodeAbbrevOp(0)); 394 else 395 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 396 Log2_32_Ceil(SectionMap.size()+1))); 397 // Don't bother emitting vis + thread local. 398 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv); 399 } 400 401 // Emit the global variable information. 402 SmallVector<unsigned, 64> Vals; 403 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end(); 404 GV != E; ++GV) { 405 unsigned AbbrevToUse = 0; 406 407 // GLOBALVAR: [type, isconst, initid, 408 // linkage, alignment, section, visibility, threadlocal, 409 // unnamed_addr] 410 Vals.push_back(VE.getTypeID(GV->getType())); 411 Vals.push_back(GV->isConstant()); 412 Vals.push_back(GV->isDeclaration() ? 0 : 413 (VE.getValueID(GV->getInitializer()) + 1)); 414 Vals.push_back(getEncodedLinkage(GV)); 415 Vals.push_back(Log2_32(GV->getAlignment())+1); 416 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0); 417 if (GV->isThreadLocal() || 418 GV->getVisibility() != GlobalValue::DefaultVisibility || 419 GV->hasUnnamedAddr()) { 420 Vals.push_back(getEncodedVisibility(GV)); 421 Vals.push_back(GV->isThreadLocal()); 422 Vals.push_back(GV->hasUnnamedAddr()); 423 } else { 424 AbbrevToUse = SimpleGVarAbbrev; 425 } 426 427 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse); 428 Vals.clear(); 429 } 430 431 // Emit the function proto information. 432 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) { 433 // FUNCTION: [type, callingconv, isproto, paramattr, 434 // linkage, alignment, section, visibility, gc, unnamed_addr] 435 Vals.push_back(VE.getTypeID(F->getType())); 436 Vals.push_back(F->getCallingConv()); 437 Vals.push_back(F->isDeclaration()); 438 Vals.push_back(getEncodedLinkage(F)); 439 Vals.push_back(VE.getAttributeID(F->getAttributes())); 440 Vals.push_back(Log2_32(F->getAlignment())+1); 441 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0); 442 Vals.push_back(getEncodedVisibility(F)); 443 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0); 444 Vals.push_back(F->hasUnnamedAddr()); 445 446 unsigned AbbrevToUse = 0; 447 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse); 448 Vals.clear(); 449 } 450 451 452 // Emit the alias information. 453 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end(); 454 AI != E; ++AI) { 455 Vals.push_back(VE.getTypeID(AI->getType())); 456 Vals.push_back(VE.getValueID(AI->getAliasee())); 457 Vals.push_back(getEncodedLinkage(AI)); 458 Vals.push_back(getEncodedVisibility(AI)); 459 unsigned AbbrevToUse = 0; 460 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse); 461 Vals.clear(); 462 } 463} 464 465static uint64_t GetOptimizationFlags(const Value *V) { 466 uint64_t Flags = 0; 467 468 if (const OverflowingBinaryOperator *OBO = 469 dyn_cast<OverflowingBinaryOperator>(V)) { 470 if (OBO->hasNoSignedWrap()) 471 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP; 472 if (OBO->hasNoUnsignedWrap()) 473 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP; 474 } else if (const PossiblyExactOperator *PEO = 475 dyn_cast<PossiblyExactOperator>(V)) { 476 if (PEO->isExact()) 477 Flags |= 1 << bitc::PEO_EXACT; 478 } 479 480 return Flags; 481} 482 483static void WriteMDNode(const MDNode *N, 484 const ValueEnumerator &VE, 485 BitstreamWriter &Stream, 486 SmallVector<uint64_t, 64> &Record) { 487 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 488 if (N->getOperand(i)) { 489 Record.push_back(VE.getTypeID(N->getOperand(i)->getType())); 490 Record.push_back(VE.getValueID(N->getOperand(i))); 491 } else { 492 Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext()))); 493 Record.push_back(0); 494 } 495 } 496 unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE2 : 497 bitc::METADATA_NODE2; 498 Stream.EmitRecord(MDCode, Record, 0); 499 Record.clear(); 500} 501 502static void WriteModuleMetadata(const Module *M, 503 const ValueEnumerator &VE, 504 BitstreamWriter &Stream) { 505 const ValueEnumerator::ValueList &Vals = VE.getMDValues(); 506 bool StartedMetadataBlock = false; 507 unsigned MDSAbbrev = 0; 508 SmallVector<uint64_t, 64> Record; 509 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 510 511 if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) { 512 if (!N->isFunctionLocal() || !N->getFunction()) { 513 if (!StartedMetadataBlock) { 514 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 515 StartedMetadataBlock = true; 516 } 517 WriteMDNode(N, VE, Stream, Record); 518 } 519 } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) { 520 if (!StartedMetadataBlock) { 521 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 522 523 // Abbrev for METADATA_STRING. 524 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 525 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING)); 526 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 527 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 528 MDSAbbrev = Stream.EmitAbbrev(Abbv); 529 StartedMetadataBlock = true; 530 } 531 532 // Code: [strchar x N] 533 Record.append(MDS->begin(), MDS->end()); 534 535 // Emit the finished record. 536 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev); 537 Record.clear(); 538 } 539 } 540 541 // Write named metadata. 542 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(), 543 E = M->named_metadata_end(); I != E; ++I) { 544 const NamedMDNode *NMD = I; 545 if (!StartedMetadataBlock) { 546 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 547 StartedMetadataBlock = true; 548 } 549 550 // Write name. 551 StringRef Str = NMD->getName(); 552 for (unsigned i = 0, e = Str.size(); i != e; ++i) 553 Record.push_back(Str[i]); 554 Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/); 555 Record.clear(); 556 557 // Write named metadata operands. 558 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) 559 Record.push_back(VE.getValueID(NMD->getOperand(i))); 560 Stream.EmitRecord(bitc::METADATA_NAMED_NODE2, Record, 0); 561 Record.clear(); 562 } 563 564 if (StartedMetadataBlock) 565 Stream.ExitBlock(); 566} 567 568static void WriteFunctionLocalMetadata(const Function &F, 569 const ValueEnumerator &VE, 570 BitstreamWriter &Stream) { 571 bool StartedMetadataBlock = false; 572 SmallVector<uint64_t, 64> Record; 573 const SmallVector<const MDNode *, 8> &Vals = VE.getFunctionLocalMDValues(); 574 for (unsigned i = 0, e = Vals.size(); i != e; ++i) 575 if (const MDNode *N = Vals[i]) 576 if (N->isFunctionLocal() && N->getFunction() == &F) { 577 if (!StartedMetadataBlock) { 578 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 579 StartedMetadataBlock = true; 580 } 581 WriteMDNode(N, VE, Stream, Record); 582 } 583 584 if (StartedMetadataBlock) 585 Stream.ExitBlock(); 586} 587 588static void WriteMetadataAttachment(const Function &F, 589 const ValueEnumerator &VE, 590 BitstreamWriter &Stream) { 591 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3); 592 593 SmallVector<uint64_t, 64> Record; 594 595 // Write metadata attachments 596 // METADATA_ATTACHMENT2 - [m x [value, [n x [id, mdnode]]] 597 SmallVector<std::pair<unsigned, MDNode*>, 4> MDs; 598 599 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 600 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); 601 I != E; ++I) { 602 MDs.clear(); 603 I->getAllMetadataOtherThanDebugLoc(MDs); 604 605 // If no metadata, ignore instruction. 606 if (MDs.empty()) continue; 607 608 Record.push_back(VE.getInstructionID(I)); 609 610 for (unsigned i = 0, e = MDs.size(); i != e; ++i) { 611 Record.push_back(MDs[i].first); 612 Record.push_back(VE.getValueID(MDs[i].second)); 613 } 614 Stream.EmitRecord(bitc::METADATA_ATTACHMENT2, Record, 0); 615 Record.clear(); 616 } 617 618 Stream.ExitBlock(); 619} 620 621static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) { 622 SmallVector<uint64_t, 64> Record; 623 624 // Write metadata kinds 625 // METADATA_KIND - [n x [id, name]] 626 SmallVector<StringRef, 4> Names; 627 M->getMDKindNames(Names); 628 629 if (Names.empty()) return; 630 631 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 632 633 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) { 634 Record.push_back(MDKindID); 635 StringRef KName = Names[MDKindID]; 636 Record.append(KName.begin(), KName.end()); 637 638 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0); 639 Record.clear(); 640 } 641 642 Stream.ExitBlock(); 643} 644 645static void WriteConstants(unsigned FirstVal, unsigned LastVal, 646 const ValueEnumerator &VE, 647 BitstreamWriter &Stream, bool isGlobal) { 648 if (FirstVal == LastVal) return; 649 650 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4); 651 652 unsigned AggregateAbbrev = 0; 653 unsigned String8Abbrev = 0; 654 unsigned CString7Abbrev = 0; 655 unsigned CString6Abbrev = 0; 656 // If this is a constant pool for the module, emit module-specific abbrevs. 657 if (isGlobal) { 658 // Abbrev for CST_CODE_AGGREGATE. 659 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 660 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE)); 661 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 662 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1))); 663 AggregateAbbrev = Stream.EmitAbbrev(Abbv); 664 665 // Abbrev for CST_CODE_STRING. 666 Abbv = new BitCodeAbbrev(); 667 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING)); 668 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 669 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 670 String8Abbrev = Stream.EmitAbbrev(Abbv); 671 // Abbrev for CST_CODE_CSTRING. 672 Abbv = new BitCodeAbbrev(); 673 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 674 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 675 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 676 CString7Abbrev = Stream.EmitAbbrev(Abbv); 677 // Abbrev for CST_CODE_CSTRING. 678 Abbv = new BitCodeAbbrev(); 679 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 680 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 681 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 682 CString6Abbrev = Stream.EmitAbbrev(Abbv); 683 } 684 685 SmallVector<uint64_t, 64> Record; 686 687 const ValueEnumerator::ValueList &Vals = VE.getValues(); 688 const Type *LastTy = 0; 689 for (unsigned i = FirstVal; i != LastVal; ++i) { 690 const Value *V = Vals[i].first; 691 // If we need to switch types, do so now. 692 if (V->getType() != LastTy) { 693 LastTy = V->getType(); 694 Record.push_back(VE.getTypeID(LastTy)); 695 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record, 696 CONSTANTS_SETTYPE_ABBREV); 697 Record.clear(); 698 } 699 700 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 701 Record.push_back(unsigned(IA->hasSideEffects()) | 702 unsigned(IA->isAlignStack()) << 1); 703 704 // Add the asm string. 705 const std::string &AsmStr = IA->getAsmString(); 706 Record.push_back(AsmStr.size()); 707 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i) 708 Record.push_back(AsmStr[i]); 709 710 // Add the constraint string. 711 const std::string &ConstraintStr = IA->getConstraintString(); 712 Record.push_back(ConstraintStr.size()); 713 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i) 714 Record.push_back(ConstraintStr[i]); 715 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record); 716 Record.clear(); 717 continue; 718 } 719 const Constant *C = cast<Constant>(V); 720 unsigned Code = -1U; 721 unsigned AbbrevToUse = 0; 722 if (C->isNullValue()) { 723 Code = bitc::CST_CODE_NULL; 724 } else if (isa<UndefValue>(C)) { 725 Code = bitc::CST_CODE_UNDEF; 726 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) { 727 if (IV->getBitWidth() <= 64) { 728 uint64_t V = IV->getSExtValue(); 729 if ((int64_t)V >= 0) 730 Record.push_back(V << 1); 731 else 732 Record.push_back((-V << 1) | 1); 733 Code = bitc::CST_CODE_INTEGER; 734 AbbrevToUse = CONSTANTS_INTEGER_ABBREV; 735 } else { // Wide integers, > 64 bits in size. 736 // We have an arbitrary precision integer value to write whose 737 // bit width is > 64. However, in canonical unsigned integer 738 // format it is likely that the high bits are going to be zero. 739 // So, we only write the number of active words. 740 unsigned NWords = IV->getValue().getActiveWords(); 741 const uint64_t *RawWords = IV->getValue().getRawData(); 742 for (unsigned i = 0; i != NWords; ++i) { 743 int64_t V = RawWords[i]; 744 if (V >= 0) 745 Record.push_back(V << 1); 746 else 747 Record.push_back((-V << 1) | 1); 748 } 749 Code = bitc::CST_CODE_WIDE_INTEGER; 750 } 751 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 752 Code = bitc::CST_CODE_FLOAT; 753 const Type *Ty = CFP->getType(); 754 if (Ty->isFloatTy() || Ty->isDoubleTy()) { 755 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue()); 756 } else if (Ty->isX86_FP80Ty()) { 757 // api needed to prevent premature destruction 758 // bits are not in the same order as a normal i80 APInt, compensate. 759 APInt api = CFP->getValueAPF().bitcastToAPInt(); 760 const uint64_t *p = api.getRawData(); 761 Record.push_back((p[1] << 48) | (p[0] >> 16)); 762 Record.push_back(p[0] & 0xffffLL); 763 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) { 764 APInt api = CFP->getValueAPF().bitcastToAPInt(); 765 const uint64_t *p = api.getRawData(); 766 Record.push_back(p[0]); 767 Record.push_back(p[1]); 768 } else { 769 assert (0 && "Unknown FP type!"); 770 } 771 } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) { 772 const ConstantArray *CA = cast<ConstantArray>(C); 773 // Emit constant strings specially. 774 unsigned NumOps = CA->getNumOperands(); 775 // If this is a null-terminated string, use the denser CSTRING encoding. 776 if (CA->getOperand(NumOps-1)->isNullValue()) { 777 Code = bitc::CST_CODE_CSTRING; 778 --NumOps; // Don't encode the null, which isn't allowed by char6. 779 } else { 780 Code = bitc::CST_CODE_STRING; 781 AbbrevToUse = String8Abbrev; 782 } 783 bool isCStr7 = Code == bitc::CST_CODE_CSTRING; 784 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING; 785 for (unsigned i = 0; i != NumOps; ++i) { 786 unsigned char V = cast<ConstantInt>(CA->getOperand(i))->getZExtValue(); 787 Record.push_back(V); 788 isCStr7 &= (V & 128) == 0; 789 if (isCStrChar6) 790 isCStrChar6 = BitCodeAbbrevOp::isChar6(V); 791 } 792 793 if (isCStrChar6) 794 AbbrevToUse = CString6Abbrev; 795 else if (isCStr7) 796 AbbrevToUse = CString7Abbrev; 797 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) || 798 isa<ConstantVector>(V)) { 799 Code = bitc::CST_CODE_AGGREGATE; 800 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) 801 Record.push_back(VE.getValueID(C->getOperand(i))); 802 AbbrevToUse = AggregateAbbrev; 803 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 804 switch (CE->getOpcode()) { 805 default: 806 if (Instruction::isCast(CE->getOpcode())) { 807 Code = bitc::CST_CODE_CE_CAST; 808 Record.push_back(GetEncodedCastOpcode(CE->getOpcode())); 809 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 810 Record.push_back(VE.getValueID(C->getOperand(0))); 811 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev; 812 } else { 813 assert(CE->getNumOperands() == 2 && "Unknown constant expr!"); 814 Code = bitc::CST_CODE_CE_BINOP; 815 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode())); 816 Record.push_back(VE.getValueID(C->getOperand(0))); 817 Record.push_back(VE.getValueID(C->getOperand(1))); 818 uint64_t Flags = GetOptimizationFlags(CE); 819 if (Flags != 0) 820 Record.push_back(Flags); 821 } 822 break; 823 case Instruction::GetElementPtr: 824 Code = bitc::CST_CODE_CE_GEP; 825 if (cast<GEPOperator>(C)->isInBounds()) 826 Code = bitc::CST_CODE_CE_INBOUNDS_GEP; 827 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) { 828 Record.push_back(VE.getTypeID(C->getOperand(i)->getType())); 829 Record.push_back(VE.getValueID(C->getOperand(i))); 830 } 831 break; 832 case Instruction::Select: 833 Code = bitc::CST_CODE_CE_SELECT; 834 Record.push_back(VE.getValueID(C->getOperand(0))); 835 Record.push_back(VE.getValueID(C->getOperand(1))); 836 Record.push_back(VE.getValueID(C->getOperand(2))); 837 break; 838 case Instruction::ExtractElement: 839 Code = bitc::CST_CODE_CE_EXTRACTELT; 840 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 841 Record.push_back(VE.getValueID(C->getOperand(0))); 842 Record.push_back(VE.getValueID(C->getOperand(1))); 843 break; 844 case Instruction::InsertElement: 845 Code = bitc::CST_CODE_CE_INSERTELT; 846 Record.push_back(VE.getValueID(C->getOperand(0))); 847 Record.push_back(VE.getValueID(C->getOperand(1))); 848 Record.push_back(VE.getValueID(C->getOperand(2))); 849 break; 850 case Instruction::ShuffleVector: 851 // If the return type and argument types are the same, this is a 852 // standard shufflevector instruction. If the types are different, 853 // then the shuffle is widening or truncating the input vectors, and 854 // the argument type must also be encoded. 855 if (C->getType() == C->getOperand(0)->getType()) { 856 Code = bitc::CST_CODE_CE_SHUFFLEVEC; 857 } else { 858 Code = bitc::CST_CODE_CE_SHUFVEC_EX; 859 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 860 } 861 Record.push_back(VE.getValueID(C->getOperand(0))); 862 Record.push_back(VE.getValueID(C->getOperand(1))); 863 Record.push_back(VE.getValueID(C->getOperand(2))); 864 break; 865 case Instruction::ICmp: 866 case Instruction::FCmp: 867 Code = bitc::CST_CODE_CE_CMP; 868 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 869 Record.push_back(VE.getValueID(C->getOperand(0))); 870 Record.push_back(VE.getValueID(C->getOperand(1))); 871 Record.push_back(CE->getPredicate()); 872 break; 873 } 874 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) { 875 assert(BA->getFunction() == BA->getBasicBlock()->getParent() && 876 "Malformed blockaddress"); 877 Code = bitc::CST_CODE_BLOCKADDRESS; 878 Record.push_back(VE.getTypeID(BA->getFunction()->getType())); 879 Record.push_back(VE.getValueID(BA->getFunction())); 880 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock())); 881 } else { 882#ifndef NDEBUG 883 C->dump(); 884#endif 885 llvm_unreachable("Unknown constant!"); 886 } 887 Stream.EmitRecord(Code, Record, AbbrevToUse); 888 Record.clear(); 889 } 890 891 Stream.ExitBlock(); 892} 893 894static void WriteModuleConstants(const ValueEnumerator &VE, 895 BitstreamWriter &Stream) { 896 const ValueEnumerator::ValueList &Vals = VE.getValues(); 897 898 // Find the first constant to emit, which is the first non-globalvalue value. 899 // We know globalvalues have been emitted by WriteModuleInfo. 900 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 901 if (!isa<GlobalValue>(Vals[i].first)) { 902 WriteConstants(i, Vals.size(), VE, Stream, true); 903 return; 904 } 905 } 906} 907 908/// PushValueAndType - The file has to encode both the value and type id for 909/// many values, because we need to know what type to create for forward 910/// references. However, most operands are not forward references, so this type 911/// field is not needed. 912/// 913/// This function adds V's value ID to Vals. If the value ID is higher than the 914/// instruction ID, then it is a forward reference, and it also includes the 915/// type ID. 916static bool PushValueAndType(const Value *V, unsigned InstID, 917 SmallVector<unsigned, 64> &Vals, 918 ValueEnumerator &VE) { 919 unsigned ValID = VE.getValueID(V); 920 Vals.push_back(ValID); 921 if (ValID >= InstID) { 922 Vals.push_back(VE.getTypeID(V->getType())); 923 return true; 924 } 925 return false; 926} 927 928/// WriteInstruction - Emit an instruction to the specified stream. 929static void WriteInstruction(const Instruction &I, unsigned InstID, 930 ValueEnumerator &VE, BitstreamWriter &Stream, 931 SmallVector<unsigned, 64> &Vals) { 932 unsigned Code = 0; 933 unsigned AbbrevToUse = 0; 934 VE.setInstructionID(&I); 935 switch (I.getOpcode()) { 936 default: 937 if (Instruction::isCast(I.getOpcode())) { 938 Code = bitc::FUNC_CODE_INST_CAST; 939 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) 940 AbbrevToUse = FUNCTION_INST_CAST_ABBREV; 941 Vals.push_back(VE.getTypeID(I.getType())); 942 Vals.push_back(GetEncodedCastOpcode(I.getOpcode())); 943 } else { 944 assert(isa<BinaryOperator>(I) && "Unknown instruction!"); 945 Code = bitc::FUNC_CODE_INST_BINOP; 946 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) 947 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV; 948 Vals.push_back(VE.getValueID(I.getOperand(1))); 949 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode())); 950 uint64_t Flags = GetOptimizationFlags(&I); 951 if (Flags != 0) { 952 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV) 953 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV; 954 Vals.push_back(Flags); 955 } 956 } 957 break; 958 959 case Instruction::GetElementPtr: 960 Code = bitc::FUNC_CODE_INST_GEP; 961 if (cast<GEPOperator>(&I)->isInBounds()) 962 Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP; 963 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 964 PushValueAndType(I.getOperand(i), InstID, Vals, VE); 965 break; 966 case Instruction::ExtractValue: { 967 Code = bitc::FUNC_CODE_INST_EXTRACTVAL; 968 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 969 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I); 970 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i) 971 Vals.push_back(*i); 972 break; 973 } 974 case Instruction::InsertValue: { 975 Code = bitc::FUNC_CODE_INST_INSERTVAL; 976 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 977 PushValueAndType(I.getOperand(1), InstID, Vals, VE); 978 const InsertValueInst *IVI = cast<InsertValueInst>(&I); 979 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i) 980 Vals.push_back(*i); 981 break; 982 } 983 case Instruction::Select: 984 Code = bitc::FUNC_CODE_INST_VSELECT; 985 PushValueAndType(I.getOperand(1), InstID, Vals, VE); 986 Vals.push_back(VE.getValueID(I.getOperand(2))); 987 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 988 break; 989 case Instruction::ExtractElement: 990 Code = bitc::FUNC_CODE_INST_EXTRACTELT; 991 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 992 Vals.push_back(VE.getValueID(I.getOperand(1))); 993 break; 994 case Instruction::InsertElement: 995 Code = bitc::FUNC_CODE_INST_INSERTELT; 996 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 997 Vals.push_back(VE.getValueID(I.getOperand(1))); 998 Vals.push_back(VE.getValueID(I.getOperand(2))); 999 break; 1000 case Instruction::ShuffleVector: 1001 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC; 1002 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1003 Vals.push_back(VE.getValueID(I.getOperand(1))); 1004 Vals.push_back(VE.getValueID(I.getOperand(2))); 1005 break; 1006 case Instruction::ICmp: 1007 case Instruction::FCmp: 1008 // compare returning Int1Ty or vector of Int1Ty 1009 Code = bitc::FUNC_CODE_INST_CMP2; 1010 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1011 Vals.push_back(VE.getValueID(I.getOperand(1))); 1012 Vals.push_back(cast<CmpInst>(I).getPredicate()); 1013 break; 1014 1015 case Instruction::Ret: 1016 { 1017 Code = bitc::FUNC_CODE_INST_RET; 1018 unsigned NumOperands = I.getNumOperands(); 1019 if (NumOperands == 0) 1020 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV; 1021 else if (NumOperands == 1) { 1022 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) 1023 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV; 1024 } else { 1025 for (unsigned i = 0, e = NumOperands; i != e; ++i) 1026 PushValueAndType(I.getOperand(i), InstID, Vals, VE); 1027 } 1028 } 1029 break; 1030 case Instruction::Br: 1031 { 1032 Code = bitc::FUNC_CODE_INST_BR; 1033 BranchInst &II = cast<BranchInst>(I); 1034 Vals.push_back(VE.getValueID(II.getSuccessor(0))); 1035 if (II.isConditional()) { 1036 Vals.push_back(VE.getValueID(II.getSuccessor(1))); 1037 Vals.push_back(VE.getValueID(II.getCondition())); 1038 } 1039 } 1040 break; 1041 case Instruction::Switch: 1042 Code = bitc::FUNC_CODE_INST_SWITCH; 1043 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 1044 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 1045 Vals.push_back(VE.getValueID(I.getOperand(i))); 1046 break; 1047 case Instruction::IndirectBr: 1048 Code = bitc::FUNC_CODE_INST_INDIRECTBR; 1049 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 1050 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 1051 Vals.push_back(VE.getValueID(I.getOperand(i))); 1052 break; 1053 1054 case Instruction::Invoke: { 1055 const InvokeInst *II = cast<InvokeInst>(&I); 1056 const Value *Callee(II->getCalledValue()); 1057 const PointerType *PTy = cast<PointerType>(Callee->getType()); 1058 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 1059 Code = bitc::FUNC_CODE_INST_INVOKE; 1060 1061 Vals.push_back(VE.getAttributeID(II->getAttributes())); 1062 Vals.push_back(II->getCallingConv()); 1063 Vals.push_back(VE.getValueID(II->getNormalDest())); 1064 Vals.push_back(VE.getValueID(II->getUnwindDest())); 1065 PushValueAndType(Callee, InstID, Vals, VE); 1066 1067 // Emit value #'s for the fixed parameters. 1068 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 1069 Vals.push_back(VE.getValueID(I.getOperand(i))); // fixed param. 1070 1071 // Emit type/value pairs for varargs params. 1072 if (FTy->isVarArg()) { 1073 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3; 1074 i != e; ++i) 1075 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg 1076 } 1077 break; 1078 } 1079 case Instruction::Unwind: 1080 Code = bitc::FUNC_CODE_INST_UNWIND; 1081 break; 1082 case Instruction::Unreachable: 1083 Code = bitc::FUNC_CODE_INST_UNREACHABLE; 1084 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV; 1085 break; 1086 1087 case Instruction::PHI: 1088 Code = bitc::FUNC_CODE_INST_PHI; 1089 Vals.push_back(VE.getTypeID(I.getType())); 1090 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 1091 Vals.push_back(VE.getValueID(I.getOperand(i))); 1092 break; 1093 1094 case Instruction::Alloca: 1095 Code = bitc::FUNC_CODE_INST_ALLOCA; 1096 Vals.push_back(VE.getTypeID(I.getType())); 1097 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 1098 Vals.push_back(VE.getValueID(I.getOperand(0))); // size. 1099 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1); 1100 break; 1101 1102 case Instruction::Load: 1103 Code = bitc::FUNC_CODE_INST_LOAD; 1104 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr 1105 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV; 1106 1107 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1); 1108 Vals.push_back(cast<LoadInst>(I).isVolatile()); 1109 break; 1110 case Instruction::Store: 1111 Code = bitc::FUNC_CODE_INST_STORE2; 1112 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr 1113 Vals.push_back(VE.getValueID(I.getOperand(0))); // val. 1114 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1); 1115 Vals.push_back(cast<StoreInst>(I).isVolatile()); 1116 break; 1117 case Instruction::Call: { 1118 const CallInst &CI = cast<CallInst>(I); 1119 const PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType()); 1120 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 1121 1122 Code = bitc::FUNC_CODE_INST_CALL2; 1123 1124 Vals.push_back(VE.getAttributeID(CI.getAttributes())); 1125 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall())); 1126 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee 1127 1128 // Emit value #'s for the fixed parameters. 1129 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 1130 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); // fixed param. 1131 1132 // Emit type/value pairs for varargs params. 1133 if (FTy->isVarArg()) { 1134 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands(); 1135 i != e; ++i) 1136 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs 1137 } 1138 break; 1139 } 1140 case Instruction::VAArg: 1141 Code = bitc::FUNC_CODE_INST_VAARG; 1142 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty 1143 Vals.push_back(VE.getValueID(I.getOperand(0))); // valist. 1144 Vals.push_back(VE.getTypeID(I.getType())); // restype. 1145 break; 1146 } 1147 1148 Stream.EmitRecord(Code, Vals, AbbrevToUse); 1149 Vals.clear(); 1150} 1151 1152// Emit names for globals/functions etc. 1153static void WriteValueSymbolTable(const ValueSymbolTable &VST, 1154 const ValueEnumerator &VE, 1155 BitstreamWriter &Stream) { 1156 if (VST.empty()) return; 1157 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 1158 1159 // FIXME: Set up the abbrev, we know how many values there are! 1160 // FIXME: We know if the type names can use 7-bit ascii. 1161 SmallVector<unsigned, 64> NameVals; 1162 1163 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end(); 1164 SI != SE; ++SI) { 1165 1166 const ValueName &Name = *SI; 1167 1168 // Figure out the encoding to use for the name. 1169 bool is7Bit = true; 1170 bool isChar6 = true; 1171 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength(); 1172 C != E; ++C) { 1173 if (isChar6) 1174 isChar6 = BitCodeAbbrevOp::isChar6(*C); 1175 if ((unsigned char)*C & 128) { 1176 is7Bit = false; 1177 break; // don't bother scanning the rest. 1178 } 1179 } 1180 1181 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV; 1182 1183 // VST_ENTRY: [valueid, namechar x N] 1184 // VST_BBENTRY: [bbid, namechar x N] 1185 // VST_LPADENTRY: [lpadid, namechar x N] 1186 unsigned Code; 1187 if (const BasicBlock *BB = dyn_cast<BasicBlock>(SI->getValue())) { 1188 if (BB->isLandingPad()) { 1189 Code = bitc::VST_CODE_LPADENTRY; 1190 if (isChar6) 1191 AbbrevToUse = VST_LPADENTRY_6_ABBREV; 1192 } else { 1193 Code = bitc::VST_CODE_BBENTRY; 1194 if (isChar6) 1195 AbbrevToUse = VST_BBENTRY_6_ABBREV; 1196 } 1197 } else { 1198 Code = bitc::VST_CODE_ENTRY; 1199 if (isChar6) 1200 AbbrevToUse = VST_ENTRY_6_ABBREV; 1201 else if (is7Bit) 1202 AbbrevToUse = VST_ENTRY_7_ABBREV; 1203 } 1204 1205 NameVals.push_back(VE.getValueID(SI->getValue())); 1206 for (const char *P = Name.getKeyData(), 1207 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P) 1208 NameVals.push_back((unsigned char)*P); 1209 1210 // Emit the finished record. 1211 Stream.EmitRecord(Code, NameVals, AbbrevToUse); 1212 NameVals.clear(); 1213 } 1214 Stream.ExitBlock(); 1215} 1216 1217/// WriteFunction - Emit a function body to the module stream. 1218static void WriteFunction(const Function &F, ValueEnumerator &VE, 1219 BitstreamWriter &Stream) { 1220 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4); 1221 VE.incorporateFunction(F); 1222 1223 SmallVector<unsigned, 64> Vals; 1224 1225 // Emit the number of basic blocks, so the reader can create them ahead of 1226 // time. 1227 Vals.push_back(VE.getBasicBlocks().size()); 1228 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals); 1229 Vals.clear(); 1230 1231 // If there are function-local constants, emit them now. 1232 unsigned CstStart, CstEnd; 1233 VE.getFunctionConstantRange(CstStart, CstEnd); 1234 WriteConstants(CstStart, CstEnd, VE, Stream, false); 1235 1236 // If there is function-local metadata, emit it now. 1237 WriteFunctionLocalMetadata(F, VE, Stream); 1238 1239 // Keep a running idea of what the instruction ID is. 1240 unsigned InstID = CstEnd; 1241 1242 bool NeedsMetadataAttachment = false; 1243 1244 DebugLoc LastDL; 1245 1246 // Finally, emit all the instructions, in order. 1247 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 1248 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); 1249 I != E; ++I) { 1250 WriteInstruction(*I, InstID, VE, Stream, Vals); 1251 1252 if (!I->getType()->isVoidTy()) 1253 ++InstID; 1254 1255 // If the instruction has metadata, write a metadata attachment later. 1256 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc(); 1257 1258 // If the instruction has a debug location, emit it. 1259 DebugLoc DL = I->getDebugLoc(); 1260 if (DL.isUnknown()) { 1261 // nothing todo. 1262 } else if (DL == LastDL) { 1263 // Just repeat the same debug loc as last time. 1264 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals); 1265 } else { 1266 MDNode *Scope, *IA; 1267 DL.getScopeAndInlinedAt(Scope, IA, I->getContext()); 1268 1269 Vals.push_back(DL.getLine()); 1270 Vals.push_back(DL.getCol()); 1271 Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0); 1272 Vals.push_back(IA ? VE.getValueID(IA)+1 : 0); 1273 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC2, Vals); 1274 Vals.clear(); 1275 1276 LastDL = DL; 1277 } 1278 } 1279 1280 // Emit names for all the instructions etc. 1281 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream); 1282 1283 if (NeedsMetadataAttachment) 1284 WriteMetadataAttachment(F, VE, Stream); 1285 VE.purgeFunction(); 1286 Stream.ExitBlock(); 1287} 1288 1289/// WriteTypeSymbolTable - Emit a block for the specified type symtab. 1290static void WriteTypeSymbolTable(const TypeSymbolTable &TST, 1291 const ValueEnumerator &VE, 1292 BitstreamWriter &Stream) { 1293 if (TST.empty()) return; 1294 1295 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3); 1296 1297 // 7-bit fixed width VST_CODE_ENTRY strings. 1298 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1299 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 1300 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1301 Log2_32_Ceil(VE.getTypes().size()+1))); 1302 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1303 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 1304 unsigned V7Abbrev = Stream.EmitAbbrev(Abbv); 1305 1306 SmallVector<unsigned, 64> NameVals; 1307 1308 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 1309 TI != TE; ++TI) { 1310 // TST_ENTRY: [typeid, namechar x N] 1311 NameVals.push_back(VE.getTypeID(TI->second)); 1312 1313 const std::string &Str = TI->first; 1314 bool is7Bit = true; 1315 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 1316 NameVals.push_back((unsigned char)Str[i]); 1317 if (Str[i] & 128) 1318 is7Bit = false; 1319 } 1320 1321 // Emit the finished record. 1322 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0); 1323 NameVals.clear(); 1324 } 1325 1326 Stream.ExitBlock(); 1327} 1328 1329// Emit blockinfo, which defines the standard abbreviations etc. 1330static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) { 1331 // We only want to emit block info records for blocks that have multiple 1332 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other 1333 // blocks can defined their abbrevs inline. 1334 Stream.EnterBlockInfoBlock(2); 1335 1336 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings. 1337 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1338 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); 1339 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1340 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1341 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 1342 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 1343 Abbv) != VST_ENTRY_8_ABBREV) 1344 llvm_unreachable("Unexpected abbrev ordering!"); 1345 } 1346 1347 { // 7-bit fixed width VST_ENTRY strings. 1348 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1349 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 1350 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1351 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1352 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 1353 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 1354 Abbv) != VST_ENTRY_7_ABBREV) 1355 llvm_unreachable("Unexpected abbrev ordering!"); 1356 } 1357 { // 6-bit char6 VST_ENTRY strings. 1358 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1359 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 1360 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1361 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1362 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 1363 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 1364 Abbv) != VST_ENTRY_6_ABBREV) 1365 llvm_unreachable("Unexpected abbrev ordering!"); 1366 } 1367 { // 6-bit char6 VST_BBENTRY strings. 1368 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1369 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY)); 1370 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1371 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1372 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 1373 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 1374 Abbv) != VST_BBENTRY_6_ABBREV) 1375 llvm_unreachable("Unexpected abbrev ordering!"); 1376 } 1377 { // 6-bit char6 VST_LPADENTRY strings. 1378 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1379 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_LPADENTRY)); 1380 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1381 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1382 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 1383 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 1384 Abbv) != VST_LPADENTRY_6_ABBREV) 1385 llvm_unreachable("Unexpected abbrev ordering!"); 1386 } 1387 1388 { // SETTYPE abbrev for CONSTANTS_BLOCK. 1389 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1390 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE)); 1391 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1392 Log2_32_Ceil(VE.getTypes().size()+1))); 1393 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 1394 Abbv) != CONSTANTS_SETTYPE_ABBREV) 1395 llvm_unreachable("Unexpected abbrev ordering!"); 1396 } 1397 1398 { // INTEGER abbrev for CONSTANTS_BLOCK. 1399 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1400 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER)); 1401 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1402 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 1403 Abbv) != CONSTANTS_INTEGER_ABBREV) 1404 llvm_unreachable("Unexpected abbrev ordering!"); 1405 } 1406 1407 { // CE_CAST abbrev for CONSTANTS_BLOCK. 1408 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1409 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST)); 1410 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc 1411 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid 1412 Log2_32_Ceil(VE.getTypes().size()+1))); 1413 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 1414 1415 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 1416 Abbv) != CONSTANTS_CE_CAST_Abbrev) 1417 llvm_unreachable("Unexpected abbrev ordering!"); 1418 } 1419 { // NULL abbrev for CONSTANTS_BLOCK. 1420 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1421 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL)); 1422 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 1423 Abbv) != CONSTANTS_NULL_Abbrev) 1424 llvm_unreachable("Unexpected abbrev ordering!"); 1425 } 1426 1427 // FIXME: This should only use space for first class types! 1428 1429 { // INST_LOAD abbrev for FUNCTION_BLOCK. 1430 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1431 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD)); 1432 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr 1433 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align 1434 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile 1435 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1436 Abbv) != FUNCTION_INST_LOAD_ABBREV) 1437 llvm_unreachable("Unexpected abbrev ordering!"); 1438 } 1439 { // INST_BINOP abbrev for FUNCTION_BLOCK. 1440 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1441 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 1442 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 1443 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 1444 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 1445 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1446 Abbv) != FUNCTION_INST_BINOP_ABBREV) 1447 llvm_unreachable("Unexpected abbrev ordering!"); 1448 } 1449 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK. 1450 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1451 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 1452 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 1453 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 1454 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 1455 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags 1456 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1457 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV) 1458 llvm_unreachable("Unexpected abbrev ordering!"); 1459 } 1460 { // INST_CAST abbrev for FUNCTION_BLOCK. 1461 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1462 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST)); 1463 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal 1464 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 1465 Log2_32_Ceil(VE.getTypes().size()+1))); 1466 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 1467 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1468 Abbv) != FUNCTION_INST_CAST_ABBREV) 1469 llvm_unreachable("Unexpected abbrev ordering!"); 1470 } 1471 1472 { // INST_RET abbrev for FUNCTION_BLOCK. 1473 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1474 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 1475 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1476 Abbv) != FUNCTION_INST_RET_VOID_ABBREV) 1477 llvm_unreachable("Unexpected abbrev ordering!"); 1478 } 1479 { // INST_RET abbrev for FUNCTION_BLOCK. 1480 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1481 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 1482 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID 1483 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1484 Abbv) != FUNCTION_INST_RET_VAL_ABBREV) 1485 llvm_unreachable("Unexpected abbrev ordering!"); 1486 } 1487 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK. 1488 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1489 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE)); 1490 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1491 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV) 1492 llvm_unreachable("Unexpected abbrev ordering!"); 1493 } 1494 1495 Stream.ExitBlock(); 1496} 1497 1498 1499/// WriteModule - Emit the specified module to the bitstream. 1500static void WriteModule(const Module *M, BitstreamWriter &Stream) { 1501 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 1502 1503 // Emit the version number if it is non-zero. 1504 if (CurVersion) { 1505 SmallVector<unsigned, 1> Vals; 1506 Vals.push_back(CurVersion); 1507 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals); 1508 } 1509 1510 // Analyze the module, enumerating globals, functions, etc. 1511 ValueEnumerator VE(M); 1512 1513 // Emit blockinfo, which defines the standard abbreviations etc. 1514 WriteBlockInfo(VE, Stream); 1515 1516 // Emit information about parameter attributes. 1517 WriteAttributeTable(VE, Stream); 1518 1519 // Emit information describing all of the types in the module. 1520 WriteTypeTable(VE, Stream); 1521 1522 // Emit top-level description of module, including target triple, inline asm, 1523 // descriptors for global variables, and function prototype info. 1524 WriteModuleInfo(M, VE, Stream); 1525 1526 // Emit constants. 1527 WriteModuleConstants(VE, Stream); 1528 1529 // Emit metadata. 1530 WriteModuleMetadata(M, VE, Stream); 1531 1532 // Emit function bodies. 1533 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) 1534 if (!I->isDeclaration()) 1535 WriteFunction(*I, VE, Stream); 1536 1537 // Emit metadata. 1538 WriteModuleMetadataStore(M, Stream); 1539 1540 // Emit the type symbol table information. 1541 WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream); 1542 1543 // Emit names for globals/functions etc. 1544 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream); 1545 1546 Stream.ExitBlock(); 1547} 1548 1549/// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a 1550/// header and trailer to make it compatible with the system archiver. To do 1551/// this we emit the following header, and then emit a trailer that pads the 1552/// file out to be a multiple of 16 bytes. 1553/// 1554/// struct bc_header { 1555/// uint32_t Magic; // 0x0B17C0DE 1556/// uint32_t Version; // Version, currently always 0. 1557/// uint32_t BitcodeOffset; // Offset to traditional bitcode file. 1558/// uint32_t BitcodeSize; // Size of traditional bitcode file. 1559/// uint32_t CPUType; // CPU specifier. 1560/// ... potentially more later ... 1561/// }; 1562enum { 1563 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size. 1564 DarwinBCHeaderSize = 5*4 1565}; 1566 1567/// isARMTriplet - Return true if the triplet looks like: 1568/// arm-*, thumb-*, armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. 1569static bool isARMTriplet(const std::string &TT) { 1570 size_t Pos = 0; 1571 size_t Size = TT.size(); 1572 if (Size >= 6 && 1573 TT[0] == 't' && TT[1] == 'h' && TT[2] == 'u' && 1574 TT[3] == 'm' && TT[4] == 'b') 1575 Pos = 5; 1576 else if (Size >= 4 && TT[0] == 'a' && TT[1] == 'r' && TT[2] == 'm') 1577 Pos = 3; 1578 else 1579 return false; 1580 1581 if (TT[Pos] == '-') 1582 return true; 1583 else if (TT[Pos] == 'v') { 1584 if (Size >= Pos+4 && 1585 TT[Pos+1] == '6' && TT[Pos+2] == 't' && TT[Pos+3] == '2') 1586 return true; 1587 else if (Size >= Pos+4 && 1588 TT[Pos+1] == '5' && TT[Pos+2] == 't' && TT[Pos+3] == 'e') 1589 return true; 1590 } else 1591 return false; 1592 while (++Pos < Size && TT[Pos] != '-') { 1593 if (!isdigit(TT[Pos])) 1594 return false; 1595 } 1596 return true; 1597} 1598 1599static void EmitDarwinBCHeader(BitstreamWriter &Stream, 1600 const std::string &TT) { 1601 unsigned CPUType = ~0U; 1602 1603 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*, 1604 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic 1605 // number from /usr/include/mach/machine.h. It is ok to reproduce the 1606 // specific constants here because they are implicitly part of the Darwin ABI. 1607 enum { 1608 DARWIN_CPU_ARCH_ABI64 = 0x01000000, 1609 DARWIN_CPU_TYPE_X86 = 7, 1610 DARWIN_CPU_TYPE_ARM = 12, 1611 DARWIN_CPU_TYPE_POWERPC = 18 1612 }; 1613 1614 if (TT.find("x86_64-") == 0) 1615 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64; 1616 else if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' && 1617 TT[4] == '-' && TT[1] - '3' < 6) 1618 CPUType = DARWIN_CPU_TYPE_X86; 1619 else if (TT.find("powerpc-") == 0) 1620 CPUType = DARWIN_CPU_TYPE_POWERPC; 1621 else if (TT.find("powerpc64-") == 0) 1622 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64; 1623 else if (isARMTriplet(TT)) 1624 CPUType = DARWIN_CPU_TYPE_ARM; 1625 1626 // Traditional Bitcode starts after header. 1627 unsigned BCOffset = DarwinBCHeaderSize; 1628 1629 Stream.Emit(0x0B17C0DE, 32); 1630 Stream.Emit(0 , 32); // Version. 1631 Stream.Emit(BCOffset , 32); 1632 Stream.Emit(0 , 32); // Filled in later. 1633 Stream.Emit(CPUType , 32); 1634} 1635 1636/// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and 1637/// finalize the header. 1638static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) { 1639 // Update the size field in the header. 1640 Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize); 1641 1642 // If the file is not a multiple of 16 bytes, insert dummy padding. 1643 while (BufferSize & 15) { 1644 Stream.Emit(0, 8); 1645 ++BufferSize; 1646 } 1647} 1648 1649 1650/// WriteBitcodeToFile - Write the specified module to the specified output 1651/// stream. 1652void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) { 1653 std::vector<unsigned char> Buffer; 1654 BitstreamWriter Stream(Buffer); 1655 1656 Buffer.reserve(256*1024); 1657 1658 WriteBitcodeToStream( M, Stream ); 1659 1660 // Write the generated bitstream to "Out". 1661 Out.write((char*)&Buffer.front(), Buffer.size()); 1662} 1663 1664/// WriteBitcodeToStream - Write the specified module to the specified output 1665/// stream. 1666void llvm::WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream) { 1667 // If this is darwin or another generic macho target, emit a file header and 1668 // trailer if needed. 1669 bool isMacho = 1670 M->getTargetTriple().find("-darwin") != std::string::npos || 1671 M->getTargetTriple().find("-macho") != std::string::npos; 1672 if (isMacho) 1673 EmitDarwinBCHeader(Stream, M->getTargetTriple()); 1674 1675 // Emit the file header. 1676 Stream.Emit((unsigned)'B', 8); 1677 Stream.Emit((unsigned)'C', 8); 1678 Stream.Emit(0x0, 4); 1679 Stream.Emit(0xC, 4); 1680 Stream.Emit(0xE, 4); 1681 Stream.Emit(0xD, 4); 1682 1683 // Emit the module. 1684 WriteModule(M, Stream); 1685 1686 if (isMacho) 1687 EmitDarwinBCTrailer(Stream, Stream.getBuffer().size()); 1688} 1689