BitcodeWriter.cpp revision 01b27458a170fdad6ab2a8f214e160f64477c978
1//===--- Bitcode/Writer/BitcodeWriter.cpp - Bitcode Writer ----------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by Chris Lattner and is distributed under 6// the University of Illinois Open Source 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/Instructions.h" 21#include "llvm/Module.h" 22#include "llvm/TypeSymbolTable.h" 23#include "llvm/ValueSymbolTable.h" 24#include "llvm/Support/MathExtras.h" 25using namespace llvm; 26 27static const unsigned CurVersion = 0; 28 29static unsigned GetEncodedCastOpcode(unsigned Opcode) { 30 switch (Opcode) { 31 default: assert(0 && "Unknown cast instruction!"); 32 case Instruction::Trunc : return bitc::CAST_TRUNC; 33 case Instruction::ZExt : return bitc::CAST_ZEXT; 34 case Instruction::SExt : return bitc::CAST_SEXT; 35 case Instruction::FPToUI : return bitc::CAST_FPTOUI; 36 case Instruction::FPToSI : return bitc::CAST_FPTOSI; 37 case Instruction::UIToFP : return bitc::CAST_UITOFP; 38 case Instruction::SIToFP : return bitc::CAST_SITOFP; 39 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC; 40 case Instruction::FPExt : return bitc::CAST_FPEXT; 41 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT; 42 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR; 43 case Instruction::BitCast : return bitc::CAST_BITCAST; 44 } 45} 46 47static unsigned GetEncodedBinaryOpcode(unsigned Opcode) { 48 switch (Opcode) { 49 default: assert(0 && "Unknown binary instruction!"); 50 case Instruction::Add: return bitc::BINOP_ADD; 51 case Instruction::Sub: return bitc::BINOP_SUB; 52 case Instruction::Mul: return bitc::BINOP_MUL; 53 case Instruction::UDiv: return bitc::BINOP_UDIV; 54 case Instruction::FDiv: 55 case Instruction::SDiv: return bitc::BINOP_SDIV; 56 case Instruction::URem: return bitc::BINOP_UREM; 57 case Instruction::FRem: 58 case Instruction::SRem: return bitc::BINOP_SREM; 59 case Instruction::Shl: return bitc::BINOP_SHL; 60 case Instruction::LShr: return bitc::BINOP_LSHR; 61 case Instruction::AShr: return bitc::BINOP_ASHR; 62 case Instruction::And: return bitc::BINOP_AND; 63 case Instruction::Or: return bitc::BINOP_OR; 64 case Instruction::Xor: return bitc::BINOP_XOR; 65 } 66} 67 68 69 70static void WriteStringRecord(unsigned Code, const std::string &Str, 71 unsigned AbbrevToUse, BitstreamWriter &Stream) { 72 SmallVector<unsigned, 64> Vals; 73 74 // Code: [strlen, strchar x N] 75 Vals.push_back(Str.size()); 76 for (unsigned i = 0, e = Str.size(); i != e; ++i) 77 Vals.push_back(Str[i]); 78 79 // Emit the finished record. 80 Stream.EmitRecord(Code, Vals, AbbrevToUse); 81} 82 83 84/// WriteTypeTable - Write out the type table for a module. 85static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) { 86 const ValueEnumerator::TypeList &TypeList = VE.getTypes(); 87 88 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */); 89 SmallVector<uint64_t, 64> TypeVals; 90 91 // FIXME: Set up abbrevs now that we know the width of the type fields, etc. 92 93 // Emit an entry count so the reader can reserve space. 94 TypeVals.push_back(TypeList.size()); 95 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals); 96 TypeVals.clear(); 97 98 // Loop over all of the types, emitting each in turn. 99 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) { 100 const Type *T = TypeList[i].first; 101 int AbbrevToUse = 0; 102 unsigned Code = 0; 103 104 switch (T->getTypeID()) { 105 case Type::PackedStructTyID: // FIXME: Delete Type::PackedStructTyID. 106 default: assert(0 && "Unknown type!"); 107 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break; 108 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break; 109 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break; 110 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break; 111 case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break; 112 case Type::IntegerTyID: 113 // INTEGER: [width] 114 Code = bitc::TYPE_CODE_INTEGER; 115 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth()); 116 break; 117 case Type::PointerTyID: 118 // POINTER: [pointee type] 119 Code = bitc::TYPE_CODE_POINTER; 120 TypeVals.push_back(VE.getTypeID(cast<PointerType>(T)->getElementType())); 121 break; 122 123 case Type::FunctionTyID: { 124 const FunctionType *FT = cast<FunctionType>(T); 125 // FUNCTION: [isvararg, #pararms, paramty x N] 126 Code = bitc::TYPE_CODE_FUNCTION; 127 TypeVals.push_back(FT->isVarArg()); 128 TypeVals.push_back(VE.getTypeID(FT->getReturnType())); 129 // FIXME: PARAM ATTR ID! 130 TypeVals.push_back(FT->getNumParams()); 131 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) 132 TypeVals.push_back(VE.getTypeID(FT->getParamType(i))); 133 break; 134 } 135 case Type::StructTyID: { 136 const StructType *ST = cast<StructType>(T); 137 // STRUCT: [ispacked, #elts, eltty x N] 138 Code = bitc::TYPE_CODE_STRUCT; 139 TypeVals.push_back(ST->isPacked()); 140 TypeVals.push_back(ST->getNumElements()); 141 // Output all of the element types... 142 for (StructType::element_iterator I = ST->element_begin(), 143 E = ST->element_end(); I != E; ++I) 144 TypeVals.push_back(VE.getTypeID(*I)); 145 break; 146 } 147 case Type::ArrayTyID: { 148 const ArrayType *AT = cast<ArrayType>(T); 149 // ARRAY: [numelts, eltty] 150 Code = bitc::TYPE_CODE_ARRAY; 151 TypeVals.push_back(AT->getNumElements()); 152 TypeVals.push_back(VE.getTypeID(AT->getElementType())); 153 break; 154 } 155 case Type::VectorTyID: { 156 const VectorType *VT = cast<VectorType>(T); 157 // VECTOR [numelts, eltty] 158 Code = bitc::TYPE_CODE_VECTOR; 159 TypeVals.push_back(VT->getNumElements()); 160 TypeVals.push_back(VE.getTypeID(VT->getElementType())); 161 break; 162 } 163 } 164 165 // Emit the finished record. 166 Stream.EmitRecord(Code, TypeVals, AbbrevToUse); 167 TypeVals.clear(); 168 } 169 170 Stream.ExitBlock(); 171} 172 173static unsigned getEncodedLinkage(const GlobalValue *GV) { 174 switch (GV->getLinkage()) { 175 default: assert(0 && "Invalid linkage!"); 176 case GlobalValue::ExternalLinkage: return 0; 177 case GlobalValue::WeakLinkage: return 1; 178 case GlobalValue::AppendingLinkage: return 2; 179 case GlobalValue::InternalLinkage: return 3; 180 case GlobalValue::LinkOnceLinkage: return 4; 181 case GlobalValue::DLLImportLinkage: return 5; 182 case GlobalValue::DLLExportLinkage: return 6; 183 case GlobalValue::ExternalWeakLinkage: return 7; 184 } 185} 186 187static unsigned getEncodedVisibility(const GlobalValue *GV) { 188 switch (GV->getVisibility()) { 189 default: assert(0 && "Invalid visibility!"); 190 case GlobalValue::DefaultVisibility: return 0; 191 case GlobalValue::HiddenVisibility: return 1; 192 } 193} 194 195// Emit top-level description of module, including target triple, inline asm, 196// descriptors for global variables, and function prototype info. 197static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE, 198 BitstreamWriter &Stream) { 199 // Emit the list of dependent libraries for the Module. 200 for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I) 201 WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream); 202 203 // Emit various pieces of data attached to a module. 204 if (!M->getTargetTriple().empty()) 205 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(), 206 0/*TODO*/, Stream); 207 if (!M->getDataLayout().empty()) 208 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(), 209 0/*TODO*/, Stream); 210 if (!M->getModuleInlineAsm().empty()) 211 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(), 212 0/*TODO*/, Stream); 213 214 // Emit information about sections, computing how many there are. Also 215 // compute the maximum alignment value. 216 std::map<std::string, unsigned> SectionMap; 217 unsigned MaxAlignment = 0; 218 unsigned MaxGlobalType = 0; 219 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end(); 220 GV != E; ++GV) { 221 MaxAlignment = std::max(MaxAlignment, GV->getAlignment()); 222 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType())); 223 224 if (!GV->hasSection()) continue; 225 // Give section names unique ID's. 226 unsigned &Entry = SectionMap[GV->getSection()]; 227 if (Entry != 0) continue; 228 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(), 229 0/*TODO*/, Stream); 230 Entry = SectionMap.size(); 231 } 232 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) { 233 MaxAlignment = std::max(MaxAlignment, F->getAlignment()); 234 if (!F->hasSection()) continue; 235 // Give section names unique ID's. 236 unsigned &Entry = SectionMap[F->getSection()]; 237 if (Entry != 0) continue; 238 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(), 239 0/*TODO*/, Stream); 240 Entry = SectionMap.size(); 241 } 242 243 // Emit abbrev for globals, now that we know # sections and max alignment. 244 unsigned SimpleGVarAbbrev = 0; 245 if (!M->global_empty()) { 246 // Add an abbrev for common globals with no visibility or thread localness. 247 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 248 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR)); 249 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 250 Log2_32_Ceil(MaxGlobalType+1))); 251 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 1)); // Constant. 252 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer. 253 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 3)); // Linkage. 254 if (MaxAlignment == 0) // Alignment. 255 Abbv->Add(BitCodeAbbrevOp(0)); 256 else { 257 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1; 258 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 259 Log2_32_Ceil(MaxEncAlignment+1))); 260 } 261 if (SectionMap.empty()) // Section. 262 Abbv->Add(BitCodeAbbrevOp(0)); 263 else 264 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::FixedWidth, 265 Log2_32_Ceil(SectionMap.size()+1))); 266 // Don't bother emitting vis + thread local. 267 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv); 268 } 269 270 // Emit the global variable information. 271 SmallVector<unsigned, 64> Vals; 272 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end(); 273 GV != E; ++GV) { 274 unsigned AbbrevToUse = 0; 275 276 // GLOBALVAR: [type, isconst, initid, 277 // linkage, alignment, section, visibility, threadlocal] 278 Vals.push_back(VE.getTypeID(GV->getType())); 279 Vals.push_back(GV->isConstant()); 280 Vals.push_back(GV->isDeclaration() ? 0 : 281 (VE.getValueID(GV->getInitializer()) + 1)); 282 Vals.push_back(getEncodedLinkage(GV)); 283 Vals.push_back(Log2_32(GV->getAlignment())+1); 284 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0); 285 if (GV->isThreadLocal() || 286 GV->getVisibility() != GlobalValue::DefaultVisibility) { 287 Vals.push_back(getEncodedVisibility(GV)); 288 Vals.push_back(GV->isThreadLocal()); 289 } else { 290 AbbrevToUse = SimpleGVarAbbrev; 291 } 292 293 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse); 294 Vals.clear(); 295 } 296 297 // Emit the function proto information. 298 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) { 299 // FUNCTION: [type, callingconv, isproto, linkage, alignment, section, 300 // visibility] 301 Vals.push_back(VE.getTypeID(F->getType())); 302 Vals.push_back(F->getCallingConv()); 303 Vals.push_back(F->isDeclaration()); 304 Vals.push_back(getEncodedLinkage(F)); 305 Vals.push_back(Log2_32(F->getAlignment())+1); 306 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0); 307 Vals.push_back(getEncodedVisibility(F)); 308 309 unsigned AbbrevToUse = 0; 310 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse); 311 Vals.clear(); 312 } 313 314 315 // Emit the alias information. 316 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end(); 317 AI != E; ++AI) { 318 Vals.push_back(VE.getTypeID(AI->getType())); 319 Vals.push_back(VE.getValueID(AI->getAliasee())); 320 Vals.push_back(getEncodedLinkage(AI)); 321 unsigned AbbrevToUse = 0; 322 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse); 323 Vals.clear(); 324 } 325} 326 327 328static void WriteConstants(unsigned FirstVal, unsigned LastVal, 329 const ValueEnumerator &VE, 330 BitstreamWriter &Stream) { 331 if (FirstVal == LastVal) return; 332 333 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 2); 334 335 // FIXME: Install and use abbrevs to reduce size. Install them globally so 336 // they don't need to be reemitted for each function body. 337 338 SmallVector<uint64_t, 64> Record; 339 340 const ValueEnumerator::ValueList &Vals = VE.getValues(); 341 const Type *LastTy = 0; 342 for (unsigned i = FirstVal; i != LastVal; ++i) { 343 const Value *V = Vals[i].first; 344 // If we need to switch types, do so now. 345 if (V->getType() != LastTy) { 346 LastTy = V->getType(); 347 Record.push_back(VE.getTypeID(LastTy)); 348 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record); 349 Record.clear(); 350 } 351 352 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 353 assert(0 && IA && "FIXME: Inline asm writing unimp!"); 354 continue; 355 } 356 const Constant *C = cast<Constant>(V); 357 unsigned Code = -1U; 358 unsigned AbbrevToUse = 0; 359 if (C->isNullValue()) { 360 Code = bitc::CST_CODE_NULL; 361 } else if (isa<UndefValue>(C)) { 362 Code = bitc::CST_CODE_UNDEF; 363 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) { 364 if (IV->getBitWidth() <= 64) { 365 int64_t V = IV->getSExtValue(); 366 if (V >= 0) 367 Record.push_back(V << 1); 368 else 369 Record.push_back((-V << 1) | 1); 370 Code = bitc::CST_CODE_INTEGER; 371 } else { // Wide integers, > 64 bits in size. 372 // We have an arbitrary precision integer value to write whose 373 // bit width is > 64. However, in canonical unsigned integer 374 // format it is likely that the high bits are going to be zero. 375 // So, we only write the number of active words. 376 unsigned NWords = IV->getValue().getActiveWords(); 377 const uint64_t *RawWords = IV->getValue().getRawData(); 378 Record.push_back(NWords); 379 for (unsigned i = 0; i != NWords; ++i) { 380 int64_t V = RawWords[i]; 381 if (V >= 0) 382 Record.push_back(V << 1); 383 else 384 Record.push_back((-V << 1) | 1); 385 } 386 Code = bitc::CST_CODE_WIDE_INTEGER; 387 } 388 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 389 Code = bitc::CST_CODE_FLOAT; 390 if (CFP->getType() == Type::FloatTy) { 391 Record.push_back(FloatToBits((float)CFP->getValue())); 392 } else { 393 assert (CFP->getType() == Type::DoubleTy && "Unknown FP type!"); 394 Record.push_back(DoubleToBits((double)CFP->getValue())); 395 } 396 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) || 397 isa<ConstantVector>(V)) { 398 Code = bitc::CST_CODE_AGGREGATE; 399 Record.push_back(C->getNumOperands()); 400 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) 401 Record.push_back(VE.getValueID(C->getOperand(i))); 402 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 403 switch (CE->getOpcode()) { 404 default: 405 if (Instruction::isCast(CE->getOpcode())) { 406 Code = bitc::CST_CODE_CE_CAST; 407 Record.push_back(GetEncodedCastOpcode(CE->getOpcode())); 408 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 409 Record.push_back(VE.getValueID(C->getOperand(0))); 410 } else { 411 assert(CE->getNumOperands() == 2 && "Unknown constant expr!"); 412 Code = bitc::CST_CODE_CE_BINOP; 413 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode())); 414 Record.push_back(VE.getValueID(C->getOperand(0))); 415 Record.push_back(VE.getValueID(C->getOperand(1))); 416 } 417 break; 418 case Instruction::GetElementPtr: 419 Code = bitc::CST_CODE_CE_GEP; 420 Record.push_back(CE->getNumOperands()); 421 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) { 422 Record.push_back(VE.getTypeID(C->getOperand(i)->getType())); 423 Record.push_back(VE.getValueID(C->getOperand(i))); 424 } 425 break; 426 case Instruction::Select: 427 Code = bitc::CST_CODE_CE_SELECT; 428 Record.push_back(VE.getValueID(C->getOperand(0))); 429 Record.push_back(VE.getValueID(C->getOperand(1))); 430 Record.push_back(VE.getValueID(C->getOperand(2))); 431 break; 432 case Instruction::ExtractElement: 433 Code = bitc::CST_CODE_CE_EXTRACTELT; 434 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 435 Record.push_back(VE.getValueID(C->getOperand(0))); 436 Record.push_back(VE.getValueID(C->getOperand(1))); 437 break; 438 case Instruction::InsertElement: 439 Code = bitc::CST_CODE_CE_INSERTELT; 440 Record.push_back(VE.getValueID(C->getOperand(0))); 441 Record.push_back(VE.getValueID(C->getOperand(1))); 442 Record.push_back(VE.getValueID(C->getOperand(2))); 443 break; 444 case Instruction::ShuffleVector: 445 Code = bitc::CST_CODE_CE_SHUFFLEVEC; 446 Record.push_back(VE.getValueID(C->getOperand(0))); 447 Record.push_back(VE.getValueID(C->getOperand(1))); 448 Record.push_back(VE.getValueID(C->getOperand(2))); 449 break; 450 case Instruction::ICmp: 451 case Instruction::FCmp: 452 Code = bitc::CST_CODE_CE_CMP; 453 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 454 Record.push_back(VE.getValueID(C->getOperand(0))); 455 Record.push_back(VE.getValueID(C->getOperand(1))); 456 Record.push_back(CE->getPredicate()); 457 break; 458 } 459 } else { 460 assert(0 && "Unknown constant!"); 461 } 462 Stream.EmitRecord(Code, Record, AbbrevToUse); 463 Record.clear(); 464 } 465 466 Stream.ExitBlock(); 467} 468 469static void WriteModuleConstants(const ValueEnumerator &VE, 470 BitstreamWriter &Stream) { 471 const ValueEnumerator::ValueList &Vals = VE.getValues(); 472 473 // Find the first constant to emit, which is the first non-globalvalue value. 474 // We know globalvalues have been emitted by WriteModuleInfo. 475 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 476 if (!isa<GlobalValue>(Vals[i].first)) { 477 WriteConstants(i, Vals.size(), VE, Stream); 478 return; 479 } 480 } 481} 482 483/// WriteInstruction - Emit an instruction to the specified stream. 484static void WriteInstruction(const Instruction &I, ValueEnumerator &VE, 485 BitstreamWriter &Stream, 486 SmallVector<unsigned, 64> &Vals) { 487 return; // FIXME: REMOVE 488 unsigned Code = 0; 489 unsigned AbbrevToUse = 0; 490 switch (I.getOpcode()) { 491 default: 492 if (Instruction::isCast(I.getOpcode())) { 493 Code = bitc::FUNC_CODE_INST_BINOP; 494 Vals.push_back(GetEncodedCastOpcode(I.getOpcode())); 495 Vals.push_back(VE.getTypeID(I.getType())); 496 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 497 Vals.push_back(VE.getValueID(I.getOperand(0))); 498 } else { 499 assert(isa<BinaryOperator>(I) && "Unknown instruction!"); 500 Code = bitc::CST_CODE_CE_BINOP; 501 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode())); 502 Vals.push_back(VE.getTypeID(I.getType())); 503 Vals.push_back(VE.getValueID(I.getOperand(0))); 504 Vals.push_back(VE.getValueID(I.getOperand(1))); 505 } 506 break; 507 508 509 case Instruction::Unwind: 510 Code = bitc::FUNC_CODE_INST_UNWIND; 511 break; 512 case Instruction::Unreachable: 513 Code = bitc::FUNC_CODE_INST_UNREACHABLE; 514 break; 515 516 } 517 518 Stream.EmitRecord(Code, Vals, AbbrevToUse); 519 Vals.clear(); 520} 521 522/// WriteFunction - Emit a function body to the module stream. 523static void WriteFunction(const Function &F, ValueEnumerator &VE, 524 BitstreamWriter &Stream) { 525 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 3); 526 VE.incorporateFunction(F); 527 528 SmallVector<unsigned, 64> Vals; 529 530 // Emit the number of basic blocks, so the reader can create them ahead of 531 // time. 532 Vals.push_back(VE.getBasicBlocks().size()); 533 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals); 534 Vals.clear(); 535 536 // FIXME: Function attributes? 537 538 // If there are function-local constants, emit them now. 539 unsigned CstStart, CstEnd; 540 VE.getFunctionConstantRange(CstStart, CstEnd); 541 WriteConstants(CstStart, CstEnd, VE, Stream); 542 543 // Finally, emit all the instructions, in order. 544 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 545 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) 546 WriteInstruction(*I, VE, Stream, Vals); 547 548 VE.purgeFunction(); 549 Stream.ExitBlock(); 550} 551 552/// WriteTypeSymbolTable - Emit a block for the specified type symtab. 553static void WriteTypeSymbolTable(const TypeSymbolTable &TST, 554 const ValueEnumerator &VE, 555 BitstreamWriter &Stream) { 556 if (TST.empty()) return; 557 558 Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3); 559 560 // FIXME: Set up the abbrev, we know how many types there are! 561 // FIXME: We know if the type names can use 7-bit ascii. 562 563 SmallVector<unsigned, 64> NameVals; 564 565 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 566 TI != TE; ++TI) { 567 unsigned AbbrevToUse = 0; 568 569 // TST_ENTRY: [typeid, namelen, namechar x N] 570 NameVals.push_back(VE.getTypeID(TI->second)); 571 572 const std::string &Str = TI->first; 573 NameVals.push_back(Str.size()); 574 for (unsigned i = 0, e = Str.size(); i != e; ++i) 575 NameVals.push_back(Str[i]); 576 577 // Emit the finished record. 578 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, AbbrevToUse); 579 NameVals.clear(); 580 } 581 582 Stream.ExitBlock(); 583} 584 585// Emit names for globals/functions etc. 586static void WriteValueSymbolTable(const ValueSymbolTable &VST, 587 const ValueEnumerator &VE, 588 BitstreamWriter &Stream) { 589 if (VST.empty()) return; 590 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 3); 591 592 // FIXME: Set up the abbrev, we know how many values there are! 593 // FIXME: We know if the type names can use 7-bit ascii. 594 SmallVector<unsigned, 64> NameVals; 595 596 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end(); 597 SI != SE; ++SI) { 598 unsigned AbbrevToUse = 0; 599 600 // VST_ENTRY: [valueid, namelen, namechar x N] 601 NameVals.push_back(VE.getValueID(SI->getValue())); 602 603 NameVals.push_back(SI->getKeyLength()); 604 for (const char *P = SI->getKeyData(), 605 *E = SI->getKeyData()+SI->getKeyLength(); P != E; ++P) 606 NameVals.push_back((unsigned char)*P); 607 608 // Emit the finished record. 609 Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, AbbrevToUse); 610 NameVals.clear(); 611 } 612 Stream.ExitBlock(); 613} 614 615 616/// WriteModule - Emit the specified module to the bitstream. 617static void WriteModule(const Module *M, BitstreamWriter &Stream) { 618 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 619 620 // Emit the version number if it is non-zero. 621 if (CurVersion) { 622 SmallVector<unsigned, 1> Vals; 623 Vals.push_back(CurVersion); 624 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals); 625 } 626 627 // Analyze the module, enumerating globals, functions, etc. 628 ValueEnumerator VE(M); 629 630 // Emit information describing all of the types in the module. 631 WriteTypeTable(VE, Stream); 632 633 // Emit top-level description of module, including target triple, inline asm, 634 // descriptors for global variables, and function prototype info. 635 WriteModuleInfo(M, VE, Stream); 636 637 // Emit constants. 638 WriteModuleConstants(VE, Stream); 639 640 // If we have any aggregate values in the value table, purge them - these can 641 // only be used to initialize global variables. Doing so makes the value 642 // namespace smaller for code in functions. 643 int NumNonAggregates = VE.PurgeAggregateValues(); 644 if (NumNonAggregates != -1) { 645 SmallVector<unsigned, 1> Vals; 646 Vals.push_back(NumNonAggregates); 647 Stream.EmitRecord(bitc::MODULE_CODE_PURGEVALS, Vals); 648 } 649 650 // Emit function bodies. 651 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) 652 if (!I->isDeclaration()) 653 WriteFunction(*I, VE, Stream); 654 655 // Emit the type symbol table information. 656 WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream); 657 658 // Emit names for globals/functions etc. 659 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream); 660 661 Stream.ExitBlock(); 662} 663 664/// WriteBitcodeToFile - Write the specified module to the specified output 665/// stream. 666void llvm::WriteBitcodeToFile(const Module *M, std::ostream &Out) { 667 std::vector<unsigned char> Buffer; 668 BitstreamWriter Stream(Buffer); 669 670 Buffer.reserve(256*1024); 671 672 // Emit the file header. 673 Stream.Emit((unsigned)'B', 8); 674 Stream.Emit((unsigned)'C', 8); 675 Stream.Emit(0x0, 4); 676 Stream.Emit(0xC, 4); 677 Stream.Emit(0xE, 4); 678 Stream.Emit(0xD, 4); 679 680 // Emit the module. 681 WriteModule(M, Stream); 682 683 // Write the generated bitstream to "Out". 684 Out.write((char*)&Buffer.front(), Buffer.size()); 685} 686