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 "ValueEnumerator.h" 16 #include "llvm/ADT/Triple.h" 17 #include "llvm/Bitcode/BitstreamWriter.h" 18 #include "llvm/Bitcode/LLVMBitCodes.h" 19 #include "llvm/IR/Constants.h" 20 #include "llvm/IR/DerivedTypes.h" 21 #include "llvm/IR/InlineAsm.h" 22 #include "llvm/IR/Instructions.h" 23 #include "llvm/IR/Module.h" 24 #include "llvm/IR/Operator.h" 25 #include "llvm/IR/ValueSymbolTable.h" 26 #include "llvm/Support/CommandLine.h" 27 #include "llvm/Support/ErrorHandling.h" 28 #include "llvm/Support/MathExtras.h" 29 #include "llvm/Support/Program.h" 30 #include "llvm/Support/raw_ostream.h" 31 #include <cctype> 32 #include <map> 33 using namespace llvm; 34 35 static cl::opt<bool> 36 EnablePreserveUseListOrdering("enable-bc-uselist-preserve", 37 cl::desc("Turn on experimental support for " 38 "use-list order preservation."), 39 cl::init(false), cl::Hidden); 40 41 /// These are manifest constants used by the bitcode writer. They do not need to 42 /// be kept in sync with the reader, but need to be consistent within this file. 43 enum { 44 // VALUE_SYMTAB_BLOCK abbrev id's. 45 VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 46 VST_ENTRY_7_ABBREV, 47 VST_ENTRY_6_ABBREV, 48 VST_BBENTRY_6_ABBREV, 49 50 // CONSTANTS_BLOCK abbrev id's. 51 CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 52 CONSTANTS_INTEGER_ABBREV, 53 CONSTANTS_CE_CAST_Abbrev, 54 CONSTANTS_NULL_Abbrev, 55 56 // FUNCTION_BLOCK abbrev id's. 57 FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV, 58 FUNCTION_INST_BINOP_ABBREV, 59 FUNCTION_INST_BINOP_FLAGS_ABBREV, 60 FUNCTION_INST_CAST_ABBREV, 61 FUNCTION_INST_RET_VOID_ABBREV, 62 FUNCTION_INST_RET_VAL_ABBREV, 63 FUNCTION_INST_UNREACHABLE_ABBREV, 64 65 // SwitchInst Magic 66 SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex 67 }; 68 69 static unsigned GetEncodedCastOpcode(unsigned Opcode) { 70 switch (Opcode) { 71 default: llvm_unreachable("Unknown cast instruction!"); 72 case Instruction::Trunc : return bitc::CAST_TRUNC; 73 case Instruction::ZExt : return bitc::CAST_ZEXT; 74 case Instruction::SExt : return bitc::CAST_SEXT; 75 case Instruction::FPToUI : return bitc::CAST_FPTOUI; 76 case Instruction::FPToSI : return bitc::CAST_FPTOSI; 77 case Instruction::UIToFP : return bitc::CAST_UITOFP; 78 case Instruction::SIToFP : return bitc::CAST_SITOFP; 79 case Instruction::FPTrunc : return bitc::CAST_FPTRUNC; 80 case Instruction::FPExt : return bitc::CAST_FPEXT; 81 case Instruction::PtrToInt: return bitc::CAST_PTRTOINT; 82 case Instruction::IntToPtr: return bitc::CAST_INTTOPTR; 83 case Instruction::BitCast : return bitc::CAST_BITCAST; 84 } 85 } 86 87 static unsigned GetEncodedBinaryOpcode(unsigned Opcode) { 88 switch (Opcode) { 89 default: llvm_unreachable("Unknown binary instruction!"); 90 case Instruction::Add: 91 case Instruction::FAdd: return bitc::BINOP_ADD; 92 case Instruction::Sub: 93 case Instruction::FSub: return bitc::BINOP_SUB; 94 case Instruction::Mul: 95 case Instruction::FMul: return bitc::BINOP_MUL; 96 case Instruction::UDiv: return bitc::BINOP_UDIV; 97 case Instruction::FDiv: 98 case Instruction::SDiv: return bitc::BINOP_SDIV; 99 case Instruction::URem: return bitc::BINOP_UREM; 100 case Instruction::FRem: 101 case Instruction::SRem: return bitc::BINOP_SREM; 102 case Instruction::Shl: return bitc::BINOP_SHL; 103 case Instruction::LShr: return bitc::BINOP_LSHR; 104 case Instruction::AShr: return bitc::BINOP_ASHR; 105 case Instruction::And: return bitc::BINOP_AND; 106 case Instruction::Or: return bitc::BINOP_OR; 107 case Instruction::Xor: return bitc::BINOP_XOR; 108 } 109 } 110 111 static unsigned GetEncodedRMWOperation(AtomicRMWInst::BinOp Op) { 112 switch (Op) { 113 default: llvm_unreachable("Unknown RMW operation!"); 114 case AtomicRMWInst::Xchg: return bitc::RMW_XCHG; 115 case AtomicRMWInst::Add: return bitc::RMW_ADD; 116 case AtomicRMWInst::Sub: return bitc::RMW_SUB; 117 case AtomicRMWInst::And: return bitc::RMW_AND; 118 case AtomicRMWInst::Nand: return bitc::RMW_NAND; 119 case AtomicRMWInst::Or: return bitc::RMW_OR; 120 case AtomicRMWInst::Xor: return bitc::RMW_XOR; 121 case AtomicRMWInst::Max: return bitc::RMW_MAX; 122 case AtomicRMWInst::Min: return bitc::RMW_MIN; 123 case AtomicRMWInst::UMax: return bitc::RMW_UMAX; 124 case AtomicRMWInst::UMin: return bitc::RMW_UMIN; 125 } 126 } 127 128 static unsigned GetEncodedOrdering(AtomicOrdering Ordering) { 129 switch (Ordering) { 130 case NotAtomic: return bitc::ORDERING_NOTATOMIC; 131 case Unordered: return bitc::ORDERING_UNORDERED; 132 case Monotonic: return bitc::ORDERING_MONOTONIC; 133 case Acquire: return bitc::ORDERING_ACQUIRE; 134 case Release: return bitc::ORDERING_RELEASE; 135 case AcquireRelease: return bitc::ORDERING_ACQREL; 136 case SequentiallyConsistent: return bitc::ORDERING_SEQCST; 137 } 138 llvm_unreachable("Invalid ordering"); 139 } 140 141 static unsigned GetEncodedSynchScope(SynchronizationScope SynchScope) { 142 switch (SynchScope) { 143 case SingleThread: return bitc::SYNCHSCOPE_SINGLETHREAD; 144 case CrossThread: return bitc::SYNCHSCOPE_CROSSTHREAD; 145 } 146 llvm_unreachable("Invalid synch scope"); 147 } 148 149 static void WriteStringRecord(unsigned Code, StringRef Str, 150 unsigned AbbrevToUse, BitstreamWriter &Stream) { 151 SmallVector<unsigned, 64> Vals; 152 153 // Code: [strchar x N] 154 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 155 if (AbbrevToUse && !BitCodeAbbrevOp::isChar6(Str[i])) 156 AbbrevToUse = 0; 157 Vals.push_back(Str[i]); 158 } 159 160 // Emit the finished record. 161 Stream.EmitRecord(Code, Vals, AbbrevToUse); 162 } 163 164 // Emit information about parameter attributes. 165 static void WriteAttributeTable(const ValueEnumerator &VE, 166 BitstreamWriter &Stream) { 167 const std::vector<AttributeSet> &Attrs = VE.getAttributes(); 168 if (Attrs.empty()) return; 169 170 Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3); 171 172 SmallVector<uint64_t, 64> Record; 173 for (unsigned i = 0, e = Attrs.size(); i != e; ++i) { 174 const AttributeSet &A = Attrs[i]; 175 for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) { 176 unsigned Index = A.getSlotIndex(i); 177 Record.push_back(Index); 178 Record.push_back(AttributeFuncs:: 179 encodeLLVMAttributesForBitcode(A.getSlotAttributes(i), 180 Index)); 181 } 182 183 Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record); 184 Record.clear(); 185 } 186 187 Stream.ExitBlock(); 188 } 189 190 /// WriteTypeTable - Write out the type table for a module. 191 static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) { 192 const ValueEnumerator::TypeList &TypeList = VE.getTypes(); 193 194 Stream.EnterSubblock(bitc::TYPE_BLOCK_ID_NEW, 4 /*count from # abbrevs */); 195 SmallVector<uint64_t, 64> TypeVals; 196 197 uint64_t NumBits = Log2_32_Ceil(VE.getTypes().size()+1); 198 199 // Abbrev for TYPE_CODE_POINTER. 200 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 201 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER)); 202 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 203 Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0 204 unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv); 205 206 // Abbrev for TYPE_CODE_FUNCTION. 207 Abbv = new BitCodeAbbrev(); 208 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION)); 209 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg 210 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 211 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 212 213 unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv); 214 215 // Abbrev for TYPE_CODE_STRUCT_ANON. 216 Abbv = new BitCodeAbbrev(); 217 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_ANON)); 218 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 219 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 220 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 221 222 unsigned StructAnonAbbrev = Stream.EmitAbbrev(Abbv); 223 224 // Abbrev for TYPE_CODE_STRUCT_NAME. 225 Abbv = new BitCodeAbbrev(); 226 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAME)); 227 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 228 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 229 unsigned StructNameAbbrev = Stream.EmitAbbrev(Abbv); 230 231 // Abbrev for TYPE_CODE_STRUCT_NAMED. 232 Abbv = new BitCodeAbbrev(); 233 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT_NAMED)); 234 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked 235 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 236 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 237 238 unsigned StructNamedAbbrev = Stream.EmitAbbrev(Abbv); 239 240 // Abbrev for TYPE_CODE_ARRAY. 241 Abbv = new BitCodeAbbrev(); 242 Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY)); 243 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size 244 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, NumBits)); 245 246 unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv); 247 248 // Emit an entry count so the reader can reserve space. 249 TypeVals.push_back(TypeList.size()); 250 Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals); 251 TypeVals.clear(); 252 253 // Loop over all of the types, emitting each in turn. 254 for (unsigned i = 0, e = TypeList.size(); i != e; ++i) { 255 Type *T = TypeList[i]; 256 int AbbrevToUse = 0; 257 unsigned Code = 0; 258 259 switch (T->getTypeID()) { 260 default: llvm_unreachable("Unknown type!"); 261 case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break; 262 case Type::HalfTyID: Code = bitc::TYPE_CODE_HALF; break; 263 case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break; 264 case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break; 265 case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break; 266 case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break; 267 case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break; 268 case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break; 269 case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break; 270 case Type::X86_MMXTyID: Code = bitc::TYPE_CODE_X86_MMX; break; 271 case Type::IntegerTyID: 272 // INTEGER: [width] 273 Code = bitc::TYPE_CODE_INTEGER; 274 TypeVals.push_back(cast<IntegerType>(T)->getBitWidth()); 275 break; 276 case Type::PointerTyID: { 277 PointerType *PTy = cast<PointerType>(T); 278 // POINTER: [pointee type, address space] 279 Code = bitc::TYPE_CODE_POINTER; 280 TypeVals.push_back(VE.getTypeID(PTy->getElementType())); 281 unsigned AddressSpace = PTy->getAddressSpace(); 282 TypeVals.push_back(AddressSpace); 283 if (AddressSpace == 0) AbbrevToUse = PtrAbbrev; 284 break; 285 } 286 case Type::FunctionTyID: { 287 FunctionType *FT = cast<FunctionType>(T); 288 // FUNCTION: [isvararg, retty, paramty x N] 289 Code = bitc::TYPE_CODE_FUNCTION; 290 TypeVals.push_back(FT->isVarArg()); 291 TypeVals.push_back(VE.getTypeID(FT->getReturnType())); 292 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) 293 TypeVals.push_back(VE.getTypeID(FT->getParamType(i))); 294 AbbrevToUse = FunctionAbbrev; 295 break; 296 } 297 case Type::StructTyID: { 298 StructType *ST = cast<StructType>(T); 299 // STRUCT: [ispacked, eltty x N] 300 TypeVals.push_back(ST->isPacked()); 301 // Output all of the element types. 302 for (StructType::element_iterator I = ST->element_begin(), 303 E = ST->element_end(); I != E; ++I) 304 TypeVals.push_back(VE.getTypeID(*I)); 305 306 if (ST->isLiteral()) { 307 Code = bitc::TYPE_CODE_STRUCT_ANON; 308 AbbrevToUse = StructAnonAbbrev; 309 } else { 310 if (ST->isOpaque()) { 311 Code = bitc::TYPE_CODE_OPAQUE; 312 } else { 313 Code = bitc::TYPE_CODE_STRUCT_NAMED; 314 AbbrevToUse = StructNamedAbbrev; 315 } 316 317 // Emit the name if it is present. 318 if (!ST->getName().empty()) 319 WriteStringRecord(bitc::TYPE_CODE_STRUCT_NAME, ST->getName(), 320 StructNameAbbrev, Stream); 321 } 322 break; 323 } 324 case Type::ArrayTyID: { 325 ArrayType *AT = cast<ArrayType>(T); 326 // ARRAY: [numelts, eltty] 327 Code = bitc::TYPE_CODE_ARRAY; 328 TypeVals.push_back(AT->getNumElements()); 329 TypeVals.push_back(VE.getTypeID(AT->getElementType())); 330 AbbrevToUse = ArrayAbbrev; 331 break; 332 } 333 case Type::VectorTyID: { 334 VectorType *VT = cast<VectorType>(T); 335 // VECTOR [numelts, eltty] 336 Code = bitc::TYPE_CODE_VECTOR; 337 TypeVals.push_back(VT->getNumElements()); 338 TypeVals.push_back(VE.getTypeID(VT->getElementType())); 339 break; 340 } 341 } 342 343 // Emit the finished record. 344 Stream.EmitRecord(Code, TypeVals, AbbrevToUse); 345 TypeVals.clear(); 346 } 347 348 Stream.ExitBlock(); 349 } 350 351 static unsigned getEncodedLinkage(const GlobalValue *GV) { 352 switch (GV->getLinkage()) { 353 case GlobalValue::ExternalLinkage: return 0; 354 case GlobalValue::WeakAnyLinkage: return 1; 355 case GlobalValue::AppendingLinkage: return 2; 356 case GlobalValue::InternalLinkage: return 3; 357 case GlobalValue::LinkOnceAnyLinkage: return 4; 358 case GlobalValue::DLLImportLinkage: return 5; 359 case GlobalValue::DLLExportLinkage: return 6; 360 case GlobalValue::ExternalWeakLinkage: return 7; 361 case GlobalValue::CommonLinkage: return 8; 362 case GlobalValue::PrivateLinkage: return 9; 363 case GlobalValue::WeakODRLinkage: return 10; 364 case GlobalValue::LinkOnceODRLinkage: return 11; 365 case GlobalValue::AvailableExternallyLinkage: return 12; 366 case GlobalValue::LinkerPrivateLinkage: return 13; 367 case GlobalValue::LinkerPrivateWeakLinkage: return 14; 368 case GlobalValue::LinkOnceODRAutoHideLinkage: return 15; 369 } 370 llvm_unreachable("Invalid linkage"); 371 } 372 373 static unsigned getEncodedVisibility(const GlobalValue *GV) { 374 switch (GV->getVisibility()) { 375 case GlobalValue::DefaultVisibility: return 0; 376 case GlobalValue::HiddenVisibility: return 1; 377 case GlobalValue::ProtectedVisibility: return 2; 378 } 379 llvm_unreachable("Invalid visibility"); 380 } 381 382 static unsigned getEncodedThreadLocalMode(const GlobalVariable *GV) { 383 switch (GV->getThreadLocalMode()) { 384 case GlobalVariable::NotThreadLocal: return 0; 385 case GlobalVariable::GeneralDynamicTLSModel: return 1; 386 case GlobalVariable::LocalDynamicTLSModel: return 2; 387 case GlobalVariable::InitialExecTLSModel: return 3; 388 case GlobalVariable::LocalExecTLSModel: return 4; 389 } 390 llvm_unreachable("Invalid TLS model"); 391 } 392 393 // Emit top-level description of module, including target triple, inline asm, 394 // descriptors for global variables, and function prototype info. 395 static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE, 396 BitstreamWriter &Stream) { 397 // Emit various pieces of data attached to a module. 398 if (!M->getTargetTriple().empty()) 399 WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(), 400 0/*TODO*/, Stream); 401 if (!M->getDataLayout().empty()) 402 WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(), 403 0/*TODO*/, Stream); 404 if (!M->getModuleInlineAsm().empty()) 405 WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(), 406 0/*TODO*/, Stream); 407 408 // Emit information about sections and GC, computing how many there are. Also 409 // compute the maximum alignment value. 410 std::map<std::string, unsigned> SectionMap; 411 std::map<std::string, unsigned> GCMap; 412 unsigned MaxAlignment = 0; 413 unsigned MaxGlobalType = 0; 414 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end(); 415 GV != E; ++GV) { 416 MaxAlignment = std::max(MaxAlignment, GV->getAlignment()); 417 MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType())); 418 if (GV->hasSection()) { 419 // Give section names unique ID's. 420 unsigned &Entry = SectionMap[GV->getSection()]; 421 if (!Entry) { 422 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(), 423 0/*TODO*/, Stream); 424 Entry = SectionMap.size(); 425 } 426 } 427 } 428 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) { 429 MaxAlignment = std::max(MaxAlignment, F->getAlignment()); 430 if (F->hasSection()) { 431 // Give section names unique ID's. 432 unsigned &Entry = SectionMap[F->getSection()]; 433 if (!Entry) { 434 WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(), 435 0/*TODO*/, Stream); 436 Entry = SectionMap.size(); 437 } 438 } 439 if (F->hasGC()) { 440 // Same for GC names. 441 unsigned &Entry = GCMap[F->getGC()]; 442 if (!Entry) { 443 WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(), 444 0/*TODO*/, Stream); 445 Entry = GCMap.size(); 446 } 447 } 448 } 449 450 // Emit abbrev for globals, now that we know # sections and max alignment. 451 unsigned SimpleGVarAbbrev = 0; 452 if (!M->global_empty()) { 453 // Add an abbrev for common globals with no visibility or thread localness. 454 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 455 Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR)); 456 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 457 Log2_32_Ceil(MaxGlobalType+1))); 458 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant. 459 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer. 460 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage. 461 if (MaxAlignment == 0) // Alignment. 462 Abbv->Add(BitCodeAbbrevOp(0)); 463 else { 464 unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1; 465 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 466 Log2_32_Ceil(MaxEncAlignment+1))); 467 } 468 if (SectionMap.empty()) // Section. 469 Abbv->Add(BitCodeAbbrevOp(0)); 470 else 471 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 472 Log2_32_Ceil(SectionMap.size()+1))); 473 // Don't bother emitting vis + thread local. 474 SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv); 475 } 476 477 // Emit the global variable information. 478 SmallVector<unsigned, 64> Vals; 479 for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end(); 480 GV != E; ++GV) { 481 unsigned AbbrevToUse = 0; 482 483 // GLOBALVAR: [type, isconst, initid, 484 // linkage, alignment, section, visibility, threadlocal, 485 // unnamed_addr] 486 Vals.push_back(VE.getTypeID(GV->getType())); 487 Vals.push_back(GV->isConstant()); 488 Vals.push_back(GV->isDeclaration() ? 0 : 489 (VE.getValueID(GV->getInitializer()) + 1)); 490 Vals.push_back(getEncodedLinkage(GV)); 491 Vals.push_back(Log2_32(GV->getAlignment())+1); 492 Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0); 493 if (GV->isThreadLocal() || 494 GV->getVisibility() != GlobalValue::DefaultVisibility || 495 GV->hasUnnamedAddr()) { 496 Vals.push_back(getEncodedVisibility(GV)); 497 Vals.push_back(getEncodedThreadLocalMode(GV)); 498 Vals.push_back(GV->hasUnnamedAddr()); 499 } else { 500 AbbrevToUse = SimpleGVarAbbrev; 501 } 502 503 Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse); 504 Vals.clear(); 505 } 506 507 // Emit the function proto information. 508 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) { 509 // FUNCTION: [type, callingconv, isproto, linkage, paramattrs, alignment, 510 // section, visibility, gc, unnamed_addr] 511 Vals.push_back(VE.getTypeID(F->getType())); 512 Vals.push_back(F->getCallingConv()); 513 Vals.push_back(F->isDeclaration()); 514 Vals.push_back(getEncodedLinkage(F)); 515 Vals.push_back(VE.getAttributeID(F->getAttributes())); 516 Vals.push_back(Log2_32(F->getAlignment())+1); 517 Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0); 518 Vals.push_back(getEncodedVisibility(F)); 519 Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0); 520 Vals.push_back(F->hasUnnamedAddr()); 521 522 unsigned AbbrevToUse = 0; 523 Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse); 524 Vals.clear(); 525 } 526 527 // Emit the alias information. 528 for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end(); 529 AI != E; ++AI) { 530 // ALIAS: [alias type, aliasee val#, linkage, visibility] 531 Vals.push_back(VE.getTypeID(AI->getType())); 532 Vals.push_back(VE.getValueID(AI->getAliasee())); 533 Vals.push_back(getEncodedLinkage(AI)); 534 Vals.push_back(getEncodedVisibility(AI)); 535 unsigned AbbrevToUse = 0; 536 Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse); 537 Vals.clear(); 538 } 539 } 540 541 static uint64_t GetOptimizationFlags(const Value *V) { 542 uint64_t Flags = 0; 543 544 if (const OverflowingBinaryOperator *OBO = 545 dyn_cast<OverflowingBinaryOperator>(V)) { 546 if (OBO->hasNoSignedWrap()) 547 Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP; 548 if (OBO->hasNoUnsignedWrap()) 549 Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP; 550 } else if (const PossiblyExactOperator *PEO = 551 dyn_cast<PossiblyExactOperator>(V)) { 552 if (PEO->isExact()) 553 Flags |= 1 << bitc::PEO_EXACT; 554 } else if (const FPMathOperator *FPMO = 555 dyn_cast<const FPMathOperator>(V)) { 556 if (FPMO->hasUnsafeAlgebra()) 557 Flags |= FastMathFlags::UnsafeAlgebra; 558 if (FPMO->hasNoNaNs()) 559 Flags |= FastMathFlags::NoNaNs; 560 if (FPMO->hasNoInfs()) 561 Flags |= FastMathFlags::NoInfs; 562 if (FPMO->hasNoSignedZeros()) 563 Flags |= FastMathFlags::NoSignedZeros; 564 if (FPMO->hasAllowReciprocal()) 565 Flags |= FastMathFlags::AllowReciprocal; 566 } 567 568 return Flags; 569 } 570 571 static void WriteMDNode(const MDNode *N, 572 const ValueEnumerator &VE, 573 BitstreamWriter &Stream, 574 SmallVector<uint64_t, 64> &Record) { 575 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 576 if (N->getOperand(i)) { 577 Record.push_back(VE.getTypeID(N->getOperand(i)->getType())); 578 Record.push_back(VE.getValueID(N->getOperand(i))); 579 } else { 580 Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext()))); 581 Record.push_back(0); 582 } 583 } 584 unsigned MDCode = N->isFunctionLocal() ? bitc::METADATA_FN_NODE : 585 bitc::METADATA_NODE; 586 Stream.EmitRecord(MDCode, Record, 0); 587 Record.clear(); 588 } 589 590 static void WriteModuleMetadata(const Module *M, 591 const ValueEnumerator &VE, 592 BitstreamWriter &Stream) { 593 const ValueEnumerator::ValueList &Vals = VE.getMDValues(); 594 bool StartedMetadataBlock = false; 595 unsigned MDSAbbrev = 0; 596 SmallVector<uint64_t, 64> Record; 597 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 598 599 if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) { 600 if (!N->isFunctionLocal() || !N->getFunction()) { 601 if (!StartedMetadataBlock) { 602 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 603 StartedMetadataBlock = true; 604 } 605 WriteMDNode(N, VE, Stream, Record); 606 } 607 } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) { 608 if (!StartedMetadataBlock) { 609 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 610 611 // Abbrev for METADATA_STRING. 612 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 613 Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING)); 614 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 615 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 616 MDSAbbrev = Stream.EmitAbbrev(Abbv); 617 StartedMetadataBlock = true; 618 } 619 620 // Code: [strchar x N] 621 Record.append(MDS->begin(), MDS->end()); 622 623 // Emit the finished record. 624 Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev); 625 Record.clear(); 626 } 627 } 628 629 // Write named metadata. 630 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(), 631 E = M->named_metadata_end(); I != E; ++I) { 632 const NamedMDNode *NMD = I; 633 if (!StartedMetadataBlock) { 634 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 635 StartedMetadataBlock = true; 636 } 637 638 // Write name. 639 StringRef Str = NMD->getName(); 640 for (unsigned i = 0, e = Str.size(); i != e; ++i) 641 Record.push_back(Str[i]); 642 Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/); 643 Record.clear(); 644 645 // Write named metadata operands. 646 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) 647 Record.push_back(VE.getValueID(NMD->getOperand(i))); 648 Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0); 649 Record.clear(); 650 } 651 652 if (StartedMetadataBlock) 653 Stream.ExitBlock(); 654 } 655 656 static void WriteFunctionLocalMetadata(const Function &F, 657 const ValueEnumerator &VE, 658 BitstreamWriter &Stream) { 659 bool StartedMetadataBlock = false; 660 SmallVector<uint64_t, 64> Record; 661 const SmallVector<const MDNode *, 8> &Vals = VE.getFunctionLocalMDValues(); 662 for (unsigned i = 0, e = Vals.size(); i != e; ++i) 663 if (const MDNode *N = Vals[i]) 664 if (N->isFunctionLocal() && N->getFunction() == &F) { 665 if (!StartedMetadataBlock) { 666 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 667 StartedMetadataBlock = true; 668 } 669 WriteMDNode(N, VE, Stream, Record); 670 } 671 672 if (StartedMetadataBlock) 673 Stream.ExitBlock(); 674 } 675 676 static void WriteMetadataAttachment(const Function &F, 677 const ValueEnumerator &VE, 678 BitstreamWriter &Stream) { 679 Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3); 680 681 SmallVector<uint64_t, 64> Record; 682 683 // Write metadata attachments 684 // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]] 685 SmallVector<std::pair<unsigned, MDNode*>, 4> MDs; 686 687 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 688 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); 689 I != E; ++I) { 690 MDs.clear(); 691 I->getAllMetadataOtherThanDebugLoc(MDs); 692 693 // If no metadata, ignore instruction. 694 if (MDs.empty()) continue; 695 696 Record.push_back(VE.getInstructionID(I)); 697 698 for (unsigned i = 0, e = MDs.size(); i != e; ++i) { 699 Record.push_back(MDs[i].first); 700 Record.push_back(VE.getValueID(MDs[i].second)); 701 } 702 Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0); 703 Record.clear(); 704 } 705 706 Stream.ExitBlock(); 707 } 708 709 static void WriteModuleMetadataStore(const Module *M, BitstreamWriter &Stream) { 710 SmallVector<uint64_t, 64> Record; 711 712 // Write metadata kinds 713 // METADATA_KIND - [n x [id, name]] 714 SmallVector<StringRef, 8> Names; 715 M->getMDKindNames(Names); 716 717 if (Names.empty()) return; 718 719 Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3); 720 721 for (unsigned MDKindID = 0, e = Names.size(); MDKindID != e; ++MDKindID) { 722 Record.push_back(MDKindID); 723 StringRef KName = Names[MDKindID]; 724 Record.append(KName.begin(), KName.end()); 725 726 Stream.EmitRecord(bitc::METADATA_KIND, Record, 0); 727 Record.clear(); 728 } 729 730 Stream.ExitBlock(); 731 } 732 733 static void emitSignedInt64(SmallVectorImpl<uint64_t> &Vals, uint64_t V) { 734 if ((int64_t)V >= 0) 735 Vals.push_back(V << 1); 736 else 737 Vals.push_back((-V << 1) | 1); 738 } 739 740 static void EmitAPInt(SmallVectorImpl<uint64_t> &Vals, 741 unsigned &Code, unsigned &AbbrevToUse, const APInt &Val, 742 bool EmitSizeForWideNumbers = false 743 ) { 744 if (Val.getBitWidth() <= 64) { 745 uint64_t V = Val.getSExtValue(); 746 emitSignedInt64(Vals, V); 747 Code = bitc::CST_CODE_INTEGER; 748 AbbrevToUse = CONSTANTS_INTEGER_ABBREV; 749 } else { 750 // Wide integers, > 64 bits in size. 751 // We have an arbitrary precision integer value to write whose 752 // bit width is > 64. However, in canonical unsigned integer 753 // format it is likely that the high bits are going to be zero. 754 // So, we only write the number of active words. 755 unsigned NWords = Val.getActiveWords(); 756 757 if (EmitSizeForWideNumbers) 758 Vals.push_back(NWords); 759 760 const uint64_t *RawWords = Val.getRawData(); 761 for (unsigned i = 0; i != NWords; ++i) { 762 emitSignedInt64(Vals, RawWords[i]); 763 } 764 Code = bitc::CST_CODE_WIDE_INTEGER; 765 } 766 } 767 768 static void WriteConstants(unsigned FirstVal, unsigned LastVal, 769 const ValueEnumerator &VE, 770 BitstreamWriter &Stream, bool isGlobal) { 771 if (FirstVal == LastVal) return; 772 773 Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4); 774 775 unsigned AggregateAbbrev = 0; 776 unsigned String8Abbrev = 0; 777 unsigned CString7Abbrev = 0; 778 unsigned CString6Abbrev = 0; 779 // If this is a constant pool for the module, emit module-specific abbrevs. 780 if (isGlobal) { 781 // Abbrev for CST_CODE_AGGREGATE. 782 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 783 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE)); 784 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 785 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1))); 786 AggregateAbbrev = Stream.EmitAbbrev(Abbv); 787 788 // Abbrev for CST_CODE_STRING. 789 Abbv = new BitCodeAbbrev(); 790 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING)); 791 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 792 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 793 String8Abbrev = Stream.EmitAbbrev(Abbv); 794 // Abbrev for CST_CODE_CSTRING. 795 Abbv = new BitCodeAbbrev(); 796 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 797 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 798 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 799 CString7Abbrev = Stream.EmitAbbrev(Abbv); 800 // Abbrev for CST_CODE_CSTRING. 801 Abbv = new BitCodeAbbrev(); 802 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING)); 803 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 804 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 805 CString6Abbrev = Stream.EmitAbbrev(Abbv); 806 } 807 808 SmallVector<uint64_t, 64> Record; 809 810 const ValueEnumerator::ValueList &Vals = VE.getValues(); 811 Type *LastTy = 0; 812 for (unsigned i = FirstVal; i != LastVal; ++i) { 813 const Value *V = Vals[i].first; 814 // If we need to switch types, do so now. 815 if (V->getType() != LastTy) { 816 LastTy = V->getType(); 817 Record.push_back(VE.getTypeID(LastTy)); 818 Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record, 819 CONSTANTS_SETTYPE_ABBREV); 820 Record.clear(); 821 } 822 823 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) { 824 Record.push_back(unsigned(IA->hasSideEffects()) | 825 unsigned(IA->isAlignStack()) << 1 | 826 unsigned(IA->getDialect()&1) << 2); 827 828 // Add the asm string. 829 const std::string &AsmStr = IA->getAsmString(); 830 Record.push_back(AsmStr.size()); 831 for (unsigned i = 0, e = AsmStr.size(); i != e; ++i) 832 Record.push_back(AsmStr[i]); 833 834 // Add the constraint string. 835 const std::string &ConstraintStr = IA->getConstraintString(); 836 Record.push_back(ConstraintStr.size()); 837 for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i) 838 Record.push_back(ConstraintStr[i]); 839 Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record); 840 Record.clear(); 841 continue; 842 } 843 const Constant *C = cast<Constant>(V); 844 unsigned Code = -1U; 845 unsigned AbbrevToUse = 0; 846 if (C->isNullValue()) { 847 Code = bitc::CST_CODE_NULL; 848 } else if (isa<UndefValue>(C)) { 849 Code = bitc::CST_CODE_UNDEF; 850 } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) { 851 EmitAPInt(Record, Code, AbbrevToUse, IV->getValue()); 852 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) { 853 Code = bitc::CST_CODE_FLOAT; 854 Type *Ty = CFP->getType(); 855 if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) { 856 Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue()); 857 } else if (Ty->isX86_FP80Ty()) { 858 // api needed to prevent premature destruction 859 // bits are not in the same order as a normal i80 APInt, compensate. 860 APInt api = CFP->getValueAPF().bitcastToAPInt(); 861 const uint64_t *p = api.getRawData(); 862 Record.push_back((p[1] << 48) | (p[0] >> 16)); 863 Record.push_back(p[0] & 0xffffLL); 864 } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) { 865 APInt api = CFP->getValueAPF().bitcastToAPInt(); 866 const uint64_t *p = api.getRawData(); 867 Record.push_back(p[0]); 868 Record.push_back(p[1]); 869 } else { 870 assert (0 && "Unknown FP type!"); 871 } 872 } else if (isa<ConstantDataSequential>(C) && 873 cast<ConstantDataSequential>(C)->isString()) { 874 const ConstantDataSequential *Str = cast<ConstantDataSequential>(C); 875 // Emit constant strings specially. 876 unsigned NumElts = Str->getNumElements(); 877 // If this is a null-terminated string, use the denser CSTRING encoding. 878 if (Str->isCString()) { 879 Code = bitc::CST_CODE_CSTRING; 880 --NumElts; // Don't encode the null, which isn't allowed by char6. 881 } else { 882 Code = bitc::CST_CODE_STRING; 883 AbbrevToUse = String8Abbrev; 884 } 885 bool isCStr7 = Code == bitc::CST_CODE_CSTRING; 886 bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING; 887 for (unsigned i = 0; i != NumElts; ++i) { 888 unsigned char V = Str->getElementAsInteger(i); 889 Record.push_back(V); 890 isCStr7 &= (V & 128) == 0; 891 if (isCStrChar6) 892 isCStrChar6 = BitCodeAbbrevOp::isChar6(V); 893 } 894 895 if (isCStrChar6) 896 AbbrevToUse = CString6Abbrev; 897 else if (isCStr7) 898 AbbrevToUse = CString7Abbrev; 899 } else if (const ConstantDataSequential *CDS = 900 dyn_cast<ConstantDataSequential>(C)) { 901 Code = bitc::CST_CODE_DATA; 902 Type *EltTy = CDS->getType()->getElementType(); 903 if (isa<IntegerType>(EltTy)) { 904 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) 905 Record.push_back(CDS->getElementAsInteger(i)); 906 } else if (EltTy->isFloatTy()) { 907 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 908 union { float F; uint32_t I; }; 909 F = CDS->getElementAsFloat(i); 910 Record.push_back(I); 911 } 912 } else { 913 assert(EltTy->isDoubleTy() && "Unknown ConstantData element type"); 914 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 915 union { double F; uint64_t I; }; 916 F = CDS->getElementAsDouble(i); 917 Record.push_back(I); 918 } 919 } 920 } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) || 921 isa<ConstantVector>(C)) { 922 Code = bitc::CST_CODE_AGGREGATE; 923 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) 924 Record.push_back(VE.getValueID(C->getOperand(i))); 925 AbbrevToUse = AggregateAbbrev; 926 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 927 switch (CE->getOpcode()) { 928 default: 929 if (Instruction::isCast(CE->getOpcode())) { 930 Code = bitc::CST_CODE_CE_CAST; 931 Record.push_back(GetEncodedCastOpcode(CE->getOpcode())); 932 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 933 Record.push_back(VE.getValueID(C->getOperand(0))); 934 AbbrevToUse = CONSTANTS_CE_CAST_Abbrev; 935 } else { 936 assert(CE->getNumOperands() == 2 && "Unknown constant expr!"); 937 Code = bitc::CST_CODE_CE_BINOP; 938 Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode())); 939 Record.push_back(VE.getValueID(C->getOperand(0))); 940 Record.push_back(VE.getValueID(C->getOperand(1))); 941 uint64_t Flags = GetOptimizationFlags(CE); 942 if (Flags != 0) 943 Record.push_back(Flags); 944 } 945 break; 946 case Instruction::GetElementPtr: 947 Code = bitc::CST_CODE_CE_GEP; 948 if (cast<GEPOperator>(C)->isInBounds()) 949 Code = bitc::CST_CODE_CE_INBOUNDS_GEP; 950 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) { 951 Record.push_back(VE.getTypeID(C->getOperand(i)->getType())); 952 Record.push_back(VE.getValueID(C->getOperand(i))); 953 } 954 break; 955 case Instruction::Select: 956 Code = bitc::CST_CODE_CE_SELECT; 957 Record.push_back(VE.getValueID(C->getOperand(0))); 958 Record.push_back(VE.getValueID(C->getOperand(1))); 959 Record.push_back(VE.getValueID(C->getOperand(2))); 960 break; 961 case Instruction::ExtractElement: 962 Code = bitc::CST_CODE_CE_EXTRACTELT; 963 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 964 Record.push_back(VE.getValueID(C->getOperand(0))); 965 Record.push_back(VE.getValueID(C->getOperand(1))); 966 break; 967 case Instruction::InsertElement: 968 Code = bitc::CST_CODE_CE_INSERTELT; 969 Record.push_back(VE.getValueID(C->getOperand(0))); 970 Record.push_back(VE.getValueID(C->getOperand(1))); 971 Record.push_back(VE.getValueID(C->getOperand(2))); 972 break; 973 case Instruction::ShuffleVector: 974 // If the return type and argument types are the same, this is a 975 // standard shufflevector instruction. If the types are different, 976 // then the shuffle is widening or truncating the input vectors, and 977 // the argument type must also be encoded. 978 if (C->getType() == C->getOperand(0)->getType()) { 979 Code = bitc::CST_CODE_CE_SHUFFLEVEC; 980 } else { 981 Code = bitc::CST_CODE_CE_SHUFVEC_EX; 982 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 983 } 984 Record.push_back(VE.getValueID(C->getOperand(0))); 985 Record.push_back(VE.getValueID(C->getOperand(1))); 986 Record.push_back(VE.getValueID(C->getOperand(2))); 987 break; 988 case Instruction::ICmp: 989 case Instruction::FCmp: 990 Code = bitc::CST_CODE_CE_CMP; 991 Record.push_back(VE.getTypeID(C->getOperand(0)->getType())); 992 Record.push_back(VE.getValueID(C->getOperand(0))); 993 Record.push_back(VE.getValueID(C->getOperand(1))); 994 Record.push_back(CE->getPredicate()); 995 break; 996 } 997 } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(C)) { 998 Code = bitc::CST_CODE_BLOCKADDRESS; 999 Record.push_back(VE.getTypeID(BA->getFunction()->getType())); 1000 Record.push_back(VE.getValueID(BA->getFunction())); 1001 Record.push_back(VE.getGlobalBasicBlockID(BA->getBasicBlock())); 1002 } else { 1003 #ifndef NDEBUG 1004 C->dump(); 1005 #endif 1006 llvm_unreachable("Unknown constant!"); 1007 } 1008 Stream.EmitRecord(Code, Record, AbbrevToUse); 1009 Record.clear(); 1010 } 1011 1012 Stream.ExitBlock(); 1013 } 1014 1015 static void WriteModuleConstants(const ValueEnumerator &VE, 1016 BitstreamWriter &Stream) { 1017 const ValueEnumerator::ValueList &Vals = VE.getValues(); 1018 1019 // Find the first constant to emit, which is the first non-globalvalue value. 1020 // We know globalvalues have been emitted by WriteModuleInfo. 1021 for (unsigned i = 0, e = Vals.size(); i != e; ++i) { 1022 if (!isa<GlobalValue>(Vals[i].first)) { 1023 WriteConstants(i, Vals.size(), VE, Stream, true); 1024 return; 1025 } 1026 } 1027 } 1028 1029 /// PushValueAndType - The file has to encode both the value and type id for 1030 /// many values, because we need to know what type to create for forward 1031 /// references. However, most operands are not forward references, so this type 1032 /// field is not needed. 1033 /// 1034 /// This function adds V's value ID to Vals. If the value ID is higher than the 1035 /// instruction ID, then it is a forward reference, and it also includes the 1036 /// type ID. The value ID that is written is encoded relative to the InstID. 1037 static bool PushValueAndType(const Value *V, unsigned InstID, 1038 SmallVector<unsigned, 64> &Vals, 1039 ValueEnumerator &VE) { 1040 unsigned ValID = VE.getValueID(V); 1041 // Make encoding relative to the InstID. 1042 Vals.push_back(InstID - ValID); 1043 if (ValID >= InstID) { 1044 Vals.push_back(VE.getTypeID(V->getType())); 1045 return true; 1046 } 1047 return false; 1048 } 1049 1050 /// pushValue - Like PushValueAndType, but where the type of the value is 1051 /// omitted (perhaps it was already encoded in an earlier operand). 1052 static void pushValue(const Value *V, unsigned InstID, 1053 SmallVector<unsigned, 64> &Vals, 1054 ValueEnumerator &VE) { 1055 unsigned ValID = VE.getValueID(V); 1056 Vals.push_back(InstID - ValID); 1057 } 1058 1059 static void pushValue64(const Value *V, unsigned InstID, 1060 SmallVector<uint64_t, 128> &Vals, 1061 ValueEnumerator &VE) { 1062 uint64_t ValID = VE.getValueID(V); 1063 Vals.push_back(InstID - ValID); 1064 } 1065 1066 static void pushValueSigned(const Value *V, unsigned InstID, 1067 SmallVector<uint64_t, 128> &Vals, 1068 ValueEnumerator &VE) { 1069 unsigned ValID = VE.getValueID(V); 1070 int64_t diff = ((int32_t)InstID - (int32_t)ValID); 1071 emitSignedInt64(Vals, diff); 1072 } 1073 1074 /// WriteInstruction - Emit an instruction to the specified stream. 1075 static void WriteInstruction(const Instruction &I, unsigned InstID, 1076 ValueEnumerator &VE, BitstreamWriter &Stream, 1077 SmallVector<unsigned, 64> &Vals) { 1078 unsigned Code = 0; 1079 unsigned AbbrevToUse = 0; 1080 VE.setInstructionID(&I); 1081 switch (I.getOpcode()) { 1082 default: 1083 if (Instruction::isCast(I.getOpcode())) { 1084 Code = bitc::FUNC_CODE_INST_CAST; 1085 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) 1086 AbbrevToUse = FUNCTION_INST_CAST_ABBREV; 1087 Vals.push_back(VE.getTypeID(I.getType())); 1088 Vals.push_back(GetEncodedCastOpcode(I.getOpcode())); 1089 } else { 1090 assert(isa<BinaryOperator>(I) && "Unknown instruction!"); 1091 Code = bitc::FUNC_CODE_INST_BINOP; 1092 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) 1093 AbbrevToUse = FUNCTION_INST_BINOP_ABBREV; 1094 pushValue(I.getOperand(1), InstID, Vals, VE); 1095 Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode())); 1096 uint64_t Flags = GetOptimizationFlags(&I); 1097 if (Flags != 0) { 1098 if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV) 1099 AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV; 1100 Vals.push_back(Flags); 1101 } 1102 } 1103 break; 1104 1105 case Instruction::GetElementPtr: 1106 Code = bitc::FUNC_CODE_INST_GEP; 1107 if (cast<GEPOperator>(&I)->isInBounds()) 1108 Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP; 1109 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) 1110 PushValueAndType(I.getOperand(i), InstID, Vals, VE); 1111 break; 1112 case Instruction::ExtractValue: { 1113 Code = bitc::FUNC_CODE_INST_EXTRACTVAL; 1114 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1115 const ExtractValueInst *EVI = cast<ExtractValueInst>(&I); 1116 for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i) 1117 Vals.push_back(*i); 1118 break; 1119 } 1120 case Instruction::InsertValue: { 1121 Code = bitc::FUNC_CODE_INST_INSERTVAL; 1122 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1123 PushValueAndType(I.getOperand(1), InstID, Vals, VE); 1124 const InsertValueInst *IVI = cast<InsertValueInst>(&I); 1125 for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i) 1126 Vals.push_back(*i); 1127 break; 1128 } 1129 case Instruction::Select: 1130 Code = bitc::FUNC_CODE_INST_VSELECT; 1131 PushValueAndType(I.getOperand(1), InstID, Vals, VE); 1132 pushValue(I.getOperand(2), InstID, Vals, VE); 1133 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1134 break; 1135 case Instruction::ExtractElement: 1136 Code = bitc::FUNC_CODE_INST_EXTRACTELT; 1137 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1138 pushValue(I.getOperand(1), InstID, Vals, VE); 1139 break; 1140 case Instruction::InsertElement: 1141 Code = bitc::FUNC_CODE_INST_INSERTELT; 1142 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1143 pushValue(I.getOperand(1), InstID, Vals, VE); 1144 pushValue(I.getOperand(2), InstID, Vals, VE); 1145 break; 1146 case Instruction::ShuffleVector: 1147 Code = bitc::FUNC_CODE_INST_SHUFFLEVEC; 1148 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1149 pushValue(I.getOperand(1), InstID, Vals, VE); 1150 pushValue(I.getOperand(2), InstID, Vals, VE); 1151 break; 1152 case Instruction::ICmp: 1153 case Instruction::FCmp: 1154 // compare returning Int1Ty or vector of Int1Ty 1155 Code = bitc::FUNC_CODE_INST_CMP2; 1156 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1157 pushValue(I.getOperand(1), InstID, Vals, VE); 1158 Vals.push_back(cast<CmpInst>(I).getPredicate()); 1159 break; 1160 1161 case Instruction::Ret: 1162 { 1163 Code = bitc::FUNC_CODE_INST_RET; 1164 unsigned NumOperands = I.getNumOperands(); 1165 if (NumOperands == 0) 1166 AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV; 1167 else if (NumOperands == 1) { 1168 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) 1169 AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV; 1170 } else { 1171 for (unsigned i = 0, e = NumOperands; i != e; ++i) 1172 PushValueAndType(I.getOperand(i), InstID, Vals, VE); 1173 } 1174 } 1175 break; 1176 case Instruction::Br: 1177 { 1178 Code = bitc::FUNC_CODE_INST_BR; 1179 BranchInst &II = cast<BranchInst>(I); 1180 Vals.push_back(VE.getValueID(II.getSuccessor(0))); 1181 if (II.isConditional()) { 1182 Vals.push_back(VE.getValueID(II.getSuccessor(1))); 1183 pushValue(II.getCondition(), InstID, Vals, VE); 1184 } 1185 } 1186 break; 1187 case Instruction::Switch: 1188 { 1189 // Redefine Vals, since here we need to use 64 bit values 1190 // explicitly to store large APInt numbers. 1191 SmallVector<uint64_t, 128> Vals64; 1192 1193 Code = bitc::FUNC_CODE_INST_SWITCH; 1194 SwitchInst &SI = cast<SwitchInst>(I); 1195 1196 uint32_t SwitchRecordHeader = SI.hash() | (SWITCH_INST_MAGIC << 16); 1197 Vals64.push_back(SwitchRecordHeader); 1198 1199 Vals64.push_back(VE.getTypeID(SI.getCondition()->getType())); 1200 pushValue64(SI.getCondition(), InstID, Vals64, VE); 1201 Vals64.push_back(VE.getValueID(SI.getDefaultDest())); 1202 Vals64.push_back(SI.getNumCases()); 1203 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end(); 1204 i != e; ++i) { 1205 IntegersSubset& CaseRanges = i.getCaseValueEx(); 1206 unsigned Code, Abbrev; // will unused. 1207 1208 if (CaseRanges.isSingleNumber()) { 1209 Vals64.push_back(1/*NumItems = 1*/); 1210 Vals64.push_back(true/*IsSingleNumber = true*/); 1211 EmitAPInt(Vals64, Code, Abbrev, CaseRanges.getSingleNumber(0), true); 1212 } else { 1213 1214 Vals64.push_back(CaseRanges.getNumItems()); 1215 1216 if (CaseRanges.isSingleNumbersOnly()) { 1217 for (unsigned ri = 0, rn = CaseRanges.getNumItems(); 1218 ri != rn; ++ri) { 1219 1220 Vals64.push_back(true/*IsSingleNumber = true*/); 1221 1222 EmitAPInt(Vals64, Code, Abbrev, 1223 CaseRanges.getSingleNumber(ri), true); 1224 } 1225 } else 1226 for (unsigned ri = 0, rn = CaseRanges.getNumItems(); 1227 ri != rn; ++ri) { 1228 IntegersSubset::Range r = CaseRanges.getItem(ri); 1229 bool IsSingleNumber = CaseRanges.isSingleNumber(ri); 1230 1231 Vals64.push_back(IsSingleNumber); 1232 1233 EmitAPInt(Vals64, Code, Abbrev, r.getLow(), true); 1234 if (!IsSingleNumber) 1235 EmitAPInt(Vals64, Code, Abbrev, r.getHigh(), true); 1236 } 1237 } 1238 Vals64.push_back(VE.getValueID(i.getCaseSuccessor())); 1239 } 1240 1241 Stream.EmitRecord(Code, Vals64, AbbrevToUse); 1242 1243 // Also do expected action - clear external Vals collection: 1244 Vals.clear(); 1245 return; 1246 } 1247 break; 1248 case Instruction::IndirectBr: 1249 Code = bitc::FUNC_CODE_INST_INDIRECTBR; 1250 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 1251 // Encode the address operand as relative, but not the basic blocks. 1252 pushValue(I.getOperand(0), InstID, Vals, VE); 1253 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) 1254 Vals.push_back(VE.getValueID(I.getOperand(i))); 1255 break; 1256 1257 case Instruction::Invoke: { 1258 const InvokeInst *II = cast<InvokeInst>(&I); 1259 const Value *Callee(II->getCalledValue()); 1260 PointerType *PTy = cast<PointerType>(Callee->getType()); 1261 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 1262 Code = bitc::FUNC_CODE_INST_INVOKE; 1263 1264 Vals.push_back(VE.getAttributeID(II->getAttributes())); 1265 Vals.push_back(II->getCallingConv()); 1266 Vals.push_back(VE.getValueID(II->getNormalDest())); 1267 Vals.push_back(VE.getValueID(II->getUnwindDest())); 1268 PushValueAndType(Callee, InstID, Vals, VE); 1269 1270 // Emit value #'s for the fixed parameters. 1271 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 1272 pushValue(I.getOperand(i), InstID, Vals, VE); // fixed param. 1273 1274 // Emit type/value pairs for varargs params. 1275 if (FTy->isVarArg()) { 1276 for (unsigned i = FTy->getNumParams(), e = I.getNumOperands()-3; 1277 i != e; ++i) 1278 PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg 1279 } 1280 break; 1281 } 1282 case Instruction::Resume: 1283 Code = bitc::FUNC_CODE_INST_RESUME; 1284 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1285 break; 1286 case Instruction::Unreachable: 1287 Code = bitc::FUNC_CODE_INST_UNREACHABLE; 1288 AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV; 1289 break; 1290 1291 case Instruction::PHI: { 1292 const PHINode &PN = cast<PHINode>(I); 1293 Code = bitc::FUNC_CODE_INST_PHI; 1294 // With the newer instruction encoding, forward references could give 1295 // negative valued IDs. This is most common for PHIs, so we use 1296 // signed VBRs. 1297 SmallVector<uint64_t, 128> Vals64; 1298 Vals64.push_back(VE.getTypeID(PN.getType())); 1299 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) { 1300 pushValueSigned(PN.getIncomingValue(i), InstID, Vals64, VE); 1301 Vals64.push_back(VE.getValueID(PN.getIncomingBlock(i))); 1302 } 1303 // Emit a Vals64 vector and exit. 1304 Stream.EmitRecord(Code, Vals64, AbbrevToUse); 1305 Vals64.clear(); 1306 return; 1307 } 1308 1309 case Instruction::LandingPad: { 1310 const LandingPadInst &LP = cast<LandingPadInst>(I); 1311 Code = bitc::FUNC_CODE_INST_LANDINGPAD; 1312 Vals.push_back(VE.getTypeID(LP.getType())); 1313 PushValueAndType(LP.getPersonalityFn(), InstID, Vals, VE); 1314 Vals.push_back(LP.isCleanup()); 1315 Vals.push_back(LP.getNumClauses()); 1316 for (unsigned I = 0, E = LP.getNumClauses(); I != E; ++I) { 1317 if (LP.isCatch(I)) 1318 Vals.push_back(LandingPadInst::Catch); 1319 else 1320 Vals.push_back(LandingPadInst::Filter); 1321 PushValueAndType(LP.getClause(I), InstID, Vals, VE); 1322 } 1323 break; 1324 } 1325 1326 case Instruction::Alloca: 1327 Code = bitc::FUNC_CODE_INST_ALLOCA; 1328 Vals.push_back(VE.getTypeID(I.getType())); 1329 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); 1330 Vals.push_back(VE.getValueID(I.getOperand(0))); // size. 1331 Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1); 1332 break; 1333 1334 case Instruction::Load: 1335 if (cast<LoadInst>(I).isAtomic()) { 1336 Code = bitc::FUNC_CODE_INST_LOADATOMIC; 1337 PushValueAndType(I.getOperand(0), InstID, Vals, VE); 1338 } else { 1339 Code = bitc::FUNC_CODE_INST_LOAD; 1340 if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr 1341 AbbrevToUse = FUNCTION_INST_LOAD_ABBREV; 1342 } 1343 Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1); 1344 Vals.push_back(cast<LoadInst>(I).isVolatile()); 1345 if (cast<LoadInst>(I).isAtomic()) { 1346 Vals.push_back(GetEncodedOrdering(cast<LoadInst>(I).getOrdering())); 1347 Vals.push_back(GetEncodedSynchScope(cast<LoadInst>(I).getSynchScope())); 1348 } 1349 break; 1350 case Instruction::Store: 1351 if (cast<StoreInst>(I).isAtomic()) 1352 Code = bitc::FUNC_CODE_INST_STOREATOMIC; 1353 else 1354 Code = bitc::FUNC_CODE_INST_STORE; 1355 PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr 1356 pushValue(I.getOperand(0), InstID, Vals, VE); // val. 1357 Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1); 1358 Vals.push_back(cast<StoreInst>(I).isVolatile()); 1359 if (cast<StoreInst>(I).isAtomic()) { 1360 Vals.push_back(GetEncodedOrdering(cast<StoreInst>(I).getOrdering())); 1361 Vals.push_back(GetEncodedSynchScope(cast<StoreInst>(I).getSynchScope())); 1362 } 1363 break; 1364 case Instruction::AtomicCmpXchg: 1365 Code = bitc::FUNC_CODE_INST_CMPXCHG; 1366 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr 1367 pushValue(I.getOperand(1), InstID, Vals, VE); // cmp. 1368 pushValue(I.getOperand(2), InstID, Vals, VE); // newval. 1369 Vals.push_back(cast<AtomicCmpXchgInst>(I).isVolatile()); 1370 Vals.push_back(GetEncodedOrdering( 1371 cast<AtomicCmpXchgInst>(I).getOrdering())); 1372 Vals.push_back(GetEncodedSynchScope( 1373 cast<AtomicCmpXchgInst>(I).getSynchScope())); 1374 break; 1375 case Instruction::AtomicRMW: 1376 Code = bitc::FUNC_CODE_INST_ATOMICRMW; 1377 PushValueAndType(I.getOperand(0), InstID, Vals, VE); // ptrty + ptr 1378 pushValue(I.getOperand(1), InstID, Vals, VE); // val. 1379 Vals.push_back(GetEncodedRMWOperation( 1380 cast<AtomicRMWInst>(I).getOperation())); 1381 Vals.push_back(cast<AtomicRMWInst>(I).isVolatile()); 1382 Vals.push_back(GetEncodedOrdering(cast<AtomicRMWInst>(I).getOrdering())); 1383 Vals.push_back(GetEncodedSynchScope( 1384 cast<AtomicRMWInst>(I).getSynchScope())); 1385 break; 1386 case Instruction::Fence: 1387 Code = bitc::FUNC_CODE_INST_FENCE; 1388 Vals.push_back(GetEncodedOrdering(cast<FenceInst>(I).getOrdering())); 1389 Vals.push_back(GetEncodedSynchScope(cast<FenceInst>(I).getSynchScope())); 1390 break; 1391 case Instruction::Call: { 1392 const CallInst &CI = cast<CallInst>(I); 1393 PointerType *PTy = cast<PointerType>(CI.getCalledValue()->getType()); 1394 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 1395 1396 Code = bitc::FUNC_CODE_INST_CALL; 1397 1398 Vals.push_back(VE.getAttributeID(CI.getAttributes())); 1399 Vals.push_back((CI.getCallingConv() << 1) | unsigned(CI.isTailCall())); 1400 PushValueAndType(CI.getCalledValue(), InstID, Vals, VE); // Callee 1401 1402 // Emit value #'s for the fixed parameters. 1403 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) { 1404 // Check for labels (can happen with asm labels). 1405 if (FTy->getParamType(i)->isLabelTy()) 1406 Vals.push_back(VE.getValueID(CI.getArgOperand(i))); 1407 else 1408 pushValue(CI.getArgOperand(i), InstID, Vals, VE); // fixed param. 1409 } 1410 1411 // Emit type/value pairs for varargs params. 1412 if (FTy->isVarArg()) { 1413 for (unsigned i = FTy->getNumParams(), e = CI.getNumArgOperands(); 1414 i != e; ++i) 1415 PushValueAndType(CI.getArgOperand(i), InstID, Vals, VE); // varargs 1416 } 1417 break; 1418 } 1419 case Instruction::VAArg: 1420 Code = bitc::FUNC_CODE_INST_VAARG; 1421 Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty 1422 pushValue(I.getOperand(0), InstID, Vals, VE); // valist. 1423 Vals.push_back(VE.getTypeID(I.getType())); // restype. 1424 break; 1425 } 1426 1427 Stream.EmitRecord(Code, Vals, AbbrevToUse); 1428 Vals.clear(); 1429 } 1430 1431 // Emit names for globals/functions etc. 1432 static void WriteValueSymbolTable(const ValueSymbolTable &VST, 1433 const ValueEnumerator &VE, 1434 BitstreamWriter &Stream) { 1435 if (VST.empty()) return; 1436 Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4); 1437 1438 // FIXME: Set up the abbrev, we know how many values there are! 1439 // FIXME: We know if the type names can use 7-bit ascii. 1440 SmallVector<unsigned, 64> NameVals; 1441 1442 for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end(); 1443 SI != SE; ++SI) { 1444 1445 const ValueName &Name = *SI; 1446 1447 // Figure out the encoding to use for the name. 1448 bool is7Bit = true; 1449 bool isChar6 = true; 1450 for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength(); 1451 C != E; ++C) { 1452 if (isChar6) 1453 isChar6 = BitCodeAbbrevOp::isChar6(*C); 1454 if ((unsigned char)*C & 128) { 1455 is7Bit = false; 1456 break; // don't bother scanning the rest. 1457 } 1458 } 1459 1460 unsigned AbbrevToUse = VST_ENTRY_8_ABBREV; 1461 1462 // VST_ENTRY: [valueid, namechar x N] 1463 // VST_BBENTRY: [bbid, namechar x N] 1464 unsigned Code; 1465 if (isa<BasicBlock>(SI->getValue())) { 1466 Code = bitc::VST_CODE_BBENTRY; 1467 if (isChar6) 1468 AbbrevToUse = VST_BBENTRY_6_ABBREV; 1469 } else { 1470 Code = bitc::VST_CODE_ENTRY; 1471 if (isChar6) 1472 AbbrevToUse = VST_ENTRY_6_ABBREV; 1473 else if (is7Bit) 1474 AbbrevToUse = VST_ENTRY_7_ABBREV; 1475 } 1476 1477 NameVals.push_back(VE.getValueID(SI->getValue())); 1478 for (const char *P = Name.getKeyData(), 1479 *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P) 1480 NameVals.push_back((unsigned char)*P); 1481 1482 // Emit the finished record. 1483 Stream.EmitRecord(Code, NameVals, AbbrevToUse); 1484 NameVals.clear(); 1485 } 1486 Stream.ExitBlock(); 1487 } 1488 1489 /// WriteFunction - Emit a function body to the module stream. 1490 static void WriteFunction(const Function &F, ValueEnumerator &VE, 1491 BitstreamWriter &Stream) { 1492 Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4); 1493 VE.incorporateFunction(F); 1494 1495 SmallVector<unsigned, 64> Vals; 1496 1497 // Emit the number of basic blocks, so the reader can create them ahead of 1498 // time. 1499 Vals.push_back(VE.getBasicBlocks().size()); 1500 Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals); 1501 Vals.clear(); 1502 1503 // If there are function-local constants, emit them now. 1504 unsigned CstStart, CstEnd; 1505 VE.getFunctionConstantRange(CstStart, CstEnd); 1506 WriteConstants(CstStart, CstEnd, VE, Stream, false); 1507 1508 // If there is function-local metadata, emit it now. 1509 WriteFunctionLocalMetadata(F, VE, Stream); 1510 1511 // Keep a running idea of what the instruction ID is. 1512 unsigned InstID = CstEnd; 1513 1514 bool NeedsMetadataAttachment = false; 1515 1516 DebugLoc LastDL; 1517 1518 // Finally, emit all the instructions, in order. 1519 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 1520 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); 1521 I != E; ++I) { 1522 WriteInstruction(*I, InstID, VE, Stream, Vals); 1523 1524 if (!I->getType()->isVoidTy()) 1525 ++InstID; 1526 1527 // If the instruction has metadata, write a metadata attachment later. 1528 NeedsMetadataAttachment |= I->hasMetadataOtherThanDebugLoc(); 1529 1530 // If the instruction has a debug location, emit it. 1531 DebugLoc DL = I->getDebugLoc(); 1532 if (DL.isUnknown()) { 1533 // nothing todo. 1534 } else if (DL == LastDL) { 1535 // Just repeat the same debug loc as last time. 1536 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC_AGAIN, Vals); 1537 } else { 1538 MDNode *Scope, *IA; 1539 DL.getScopeAndInlinedAt(Scope, IA, I->getContext()); 1540 1541 Vals.push_back(DL.getLine()); 1542 Vals.push_back(DL.getCol()); 1543 Vals.push_back(Scope ? VE.getValueID(Scope)+1 : 0); 1544 Vals.push_back(IA ? VE.getValueID(IA)+1 : 0); 1545 Stream.EmitRecord(bitc::FUNC_CODE_DEBUG_LOC, Vals); 1546 Vals.clear(); 1547 1548 LastDL = DL; 1549 } 1550 } 1551 1552 // Emit names for all the instructions etc. 1553 WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream); 1554 1555 if (NeedsMetadataAttachment) 1556 WriteMetadataAttachment(F, VE, Stream); 1557 VE.purgeFunction(); 1558 Stream.ExitBlock(); 1559 } 1560 1561 // Emit blockinfo, which defines the standard abbreviations etc. 1562 static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) { 1563 // We only want to emit block info records for blocks that have multiple 1564 // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. 1565 // Other blocks can define their abbrevs inline. 1566 Stream.EnterBlockInfoBlock(2); 1567 1568 { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings. 1569 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1570 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); 1571 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1572 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1573 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); 1574 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 1575 Abbv) != VST_ENTRY_8_ABBREV) 1576 llvm_unreachable("Unexpected abbrev ordering!"); 1577 } 1578 1579 { // 7-bit fixed width VST_ENTRY strings. 1580 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1581 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 1582 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1583 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1584 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); 1585 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 1586 Abbv) != VST_ENTRY_7_ABBREV) 1587 llvm_unreachable("Unexpected abbrev ordering!"); 1588 } 1589 { // 6-bit char6 VST_ENTRY strings. 1590 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1591 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY)); 1592 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1593 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1594 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 1595 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 1596 Abbv) != VST_ENTRY_6_ABBREV) 1597 llvm_unreachable("Unexpected abbrev ordering!"); 1598 } 1599 { // 6-bit char6 VST_BBENTRY strings. 1600 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1601 Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY)); 1602 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1603 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array)); 1604 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6)); 1605 if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID, 1606 Abbv) != VST_BBENTRY_6_ABBREV) 1607 llvm_unreachable("Unexpected abbrev ordering!"); 1608 } 1609 1610 1611 1612 { // SETTYPE abbrev for CONSTANTS_BLOCK. 1613 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1614 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE)); 1615 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1616 Log2_32_Ceil(VE.getTypes().size()+1))); 1617 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 1618 Abbv) != CONSTANTS_SETTYPE_ABBREV) 1619 llvm_unreachable("Unexpected abbrev ordering!"); 1620 } 1621 1622 { // INTEGER abbrev for CONSTANTS_BLOCK. 1623 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1624 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER)); 1625 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); 1626 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 1627 Abbv) != CONSTANTS_INTEGER_ABBREV) 1628 llvm_unreachable("Unexpected abbrev ordering!"); 1629 } 1630 1631 { // CE_CAST abbrev for CONSTANTS_BLOCK. 1632 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1633 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST)); 1634 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc 1635 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid 1636 Log2_32_Ceil(VE.getTypes().size()+1))); 1637 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id 1638 1639 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 1640 Abbv) != CONSTANTS_CE_CAST_Abbrev) 1641 llvm_unreachable("Unexpected abbrev ordering!"); 1642 } 1643 { // NULL abbrev for CONSTANTS_BLOCK. 1644 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1645 Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL)); 1646 if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID, 1647 Abbv) != CONSTANTS_NULL_Abbrev) 1648 llvm_unreachable("Unexpected abbrev ordering!"); 1649 } 1650 1651 // FIXME: This should only use space for first class types! 1652 1653 { // INST_LOAD abbrev for FUNCTION_BLOCK. 1654 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1655 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD)); 1656 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr 1657 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align 1658 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile 1659 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1660 Abbv) != FUNCTION_INST_LOAD_ABBREV) 1661 llvm_unreachable("Unexpected abbrev ordering!"); 1662 } 1663 { // INST_BINOP abbrev for FUNCTION_BLOCK. 1664 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1665 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 1666 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 1667 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 1668 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 1669 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1670 Abbv) != FUNCTION_INST_BINOP_ABBREV) 1671 llvm_unreachable("Unexpected abbrev ordering!"); 1672 } 1673 { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK. 1674 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1675 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP)); 1676 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS 1677 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS 1678 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 1679 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags 1680 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1681 Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV) 1682 llvm_unreachable("Unexpected abbrev ordering!"); 1683 } 1684 { // INST_CAST abbrev for FUNCTION_BLOCK. 1685 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1686 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST)); 1687 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal 1688 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty 1689 Log2_32_Ceil(VE.getTypes().size()+1))); 1690 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc 1691 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1692 Abbv) != FUNCTION_INST_CAST_ABBREV) 1693 llvm_unreachable("Unexpected abbrev ordering!"); 1694 } 1695 1696 { // INST_RET abbrev for FUNCTION_BLOCK. 1697 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1698 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 1699 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1700 Abbv) != FUNCTION_INST_RET_VOID_ABBREV) 1701 llvm_unreachable("Unexpected abbrev ordering!"); 1702 } 1703 { // INST_RET abbrev for FUNCTION_BLOCK. 1704 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1705 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET)); 1706 Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID 1707 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1708 Abbv) != FUNCTION_INST_RET_VAL_ABBREV) 1709 llvm_unreachable("Unexpected abbrev ordering!"); 1710 } 1711 { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK. 1712 BitCodeAbbrev *Abbv = new BitCodeAbbrev(); 1713 Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE)); 1714 if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID, 1715 Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV) 1716 llvm_unreachable("Unexpected abbrev ordering!"); 1717 } 1718 1719 Stream.ExitBlock(); 1720 } 1721 1722 // Sort the Users based on the order in which the reader parses the bitcode 1723 // file. 1724 static bool bitcodereader_order(const User *lhs, const User *rhs) { 1725 // TODO: Implement. 1726 return true; 1727 } 1728 1729 static void WriteUseList(const Value *V, const ValueEnumerator &VE, 1730 BitstreamWriter &Stream) { 1731 1732 // One or zero uses can't get out of order. 1733 if (V->use_empty() || V->hasNUses(1)) 1734 return; 1735 1736 // Make a copy of the in-memory use-list for sorting. 1737 unsigned UseListSize = std::distance(V->use_begin(), V->use_end()); 1738 SmallVector<const User*, 8> UseList; 1739 UseList.reserve(UseListSize); 1740 for (Value::const_use_iterator I = V->use_begin(), E = V->use_end(); 1741 I != E; ++I) { 1742 const User *U = *I; 1743 UseList.push_back(U); 1744 } 1745 1746 // Sort the copy based on the order read by the BitcodeReader. 1747 std::sort(UseList.begin(), UseList.end(), bitcodereader_order); 1748 1749 // TODO: Generate a diff between the BitcodeWriter in-memory use-list and the 1750 // sorted list (i.e., the expected BitcodeReader in-memory use-list). 1751 1752 // TODO: Emit the USELIST_CODE_ENTRYs. 1753 } 1754 1755 static void WriteFunctionUseList(const Function *F, ValueEnumerator &VE, 1756 BitstreamWriter &Stream) { 1757 VE.incorporateFunction(*F); 1758 1759 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end(); 1760 AI != AE; ++AI) 1761 WriteUseList(AI, VE, Stream); 1762 for (Function::const_iterator BB = F->begin(), FE = F->end(); BB != FE; 1763 ++BB) { 1764 WriteUseList(BB, VE, Stream); 1765 for (BasicBlock::const_iterator II = BB->begin(), IE = BB->end(); II != IE; 1766 ++II) { 1767 WriteUseList(II, VE, Stream); 1768 for (User::const_op_iterator OI = II->op_begin(), E = II->op_end(); 1769 OI != E; ++OI) { 1770 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) || 1771 isa<InlineAsm>(*OI)) 1772 WriteUseList(*OI, VE, Stream); 1773 } 1774 } 1775 } 1776 VE.purgeFunction(); 1777 } 1778 1779 // Emit use-lists. 1780 static void WriteModuleUseLists(const Module *M, ValueEnumerator &VE, 1781 BitstreamWriter &Stream) { 1782 Stream.EnterSubblock(bitc::USELIST_BLOCK_ID, 3); 1783 1784 // XXX: this modifies the module, but in a way that should never change the 1785 // behavior of any pass or codegen in LLVM. The problem is that GVs may 1786 // contain entries in the use_list that do not exist in the Module and are 1787 // not stored in the .bc file. 1788 for (Module::const_global_iterator I = M->global_begin(), E = M->global_end(); 1789 I != E; ++I) 1790 I->removeDeadConstantUsers(); 1791 1792 // Write the global variables. 1793 for (Module::const_global_iterator GI = M->global_begin(), 1794 GE = M->global_end(); GI != GE; ++GI) { 1795 WriteUseList(GI, VE, Stream); 1796 1797 // Write the global variable initializers. 1798 if (GI->hasInitializer()) 1799 WriteUseList(GI->getInitializer(), VE, Stream); 1800 } 1801 1802 // Write the functions. 1803 for (Module::const_iterator FI = M->begin(), FE = M->end(); FI != FE; ++FI) { 1804 WriteUseList(FI, VE, Stream); 1805 if (!FI->isDeclaration()) 1806 WriteFunctionUseList(FI, VE, Stream); 1807 } 1808 1809 // Write the aliases. 1810 for (Module::const_alias_iterator AI = M->alias_begin(), AE = M->alias_end(); 1811 AI != AE; ++AI) { 1812 WriteUseList(AI, VE, Stream); 1813 WriteUseList(AI->getAliasee(), VE, Stream); 1814 } 1815 1816 Stream.ExitBlock(); 1817 } 1818 1819 /// WriteModule - Emit the specified module to the bitstream. 1820 static void WriteModule(const Module *M, BitstreamWriter &Stream) { 1821 Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3); 1822 1823 SmallVector<unsigned, 1> Vals; 1824 unsigned CurVersion = 1; 1825 Vals.push_back(CurVersion); 1826 Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals); 1827 1828 // Analyze the module, enumerating globals, functions, etc. 1829 ValueEnumerator VE(M); 1830 1831 // Emit blockinfo, which defines the standard abbreviations etc. 1832 WriteBlockInfo(VE, Stream); 1833 1834 // Emit information about parameter attributes. 1835 WriteAttributeTable(VE, Stream); 1836 1837 // Emit information describing all of the types in the module. 1838 WriteTypeTable(VE, Stream); 1839 1840 // Emit top-level description of module, including target triple, inline asm, 1841 // descriptors for global variables, and function prototype info. 1842 WriteModuleInfo(M, VE, Stream); 1843 1844 // Emit constants. 1845 WriteModuleConstants(VE, Stream); 1846 1847 // Emit metadata. 1848 WriteModuleMetadata(M, VE, Stream); 1849 1850 // Emit metadata. 1851 WriteModuleMetadataStore(M, Stream); 1852 1853 // Emit names for globals/functions etc. 1854 WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream); 1855 1856 // Emit use-lists. 1857 if (EnablePreserveUseListOrdering) 1858 WriteModuleUseLists(M, VE, Stream); 1859 1860 // Emit function bodies. 1861 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) 1862 if (!F->isDeclaration()) 1863 WriteFunction(*F, VE, Stream); 1864 1865 Stream.ExitBlock(); 1866 } 1867 1868 /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a 1869 /// header and trailer to make it compatible with the system archiver. To do 1870 /// this we emit the following header, and then emit a trailer that pads the 1871 /// file out to be a multiple of 16 bytes. 1872 /// 1873 /// struct bc_header { 1874 /// uint32_t Magic; // 0x0B17C0DE 1875 /// uint32_t Version; // Version, currently always 0. 1876 /// uint32_t BitcodeOffset; // Offset to traditional bitcode file. 1877 /// uint32_t BitcodeSize; // Size of traditional bitcode file. 1878 /// uint32_t CPUType; // CPU specifier. 1879 /// ... potentially more later ... 1880 /// }; 1881 enum { 1882 DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size. 1883 DarwinBCHeaderSize = 5*4 1884 }; 1885 1886 static void WriteInt32ToBuffer(uint32_t Value, SmallVectorImpl<char> &Buffer, 1887 uint32_t &Position) { 1888 Buffer[Position + 0] = (unsigned char) (Value >> 0); 1889 Buffer[Position + 1] = (unsigned char) (Value >> 8); 1890 Buffer[Position + 2] = (unsigned char) (Value >> 16); 1891 Buffer[Position + 3] = (unsigned char) (Value >> 24); 1892 Position += 4; 1893 } 1894 1895 static void EmitDarwinBCHeaderAndTrailer(SmallVectorImpl<char> &Buffer, 1896 const Triple &TT) { 1897 unsigned CPUType = ~0U; 1898 1899 // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*, arm-*, thumb-*, 1900 // armv[0-9]-*, thumbv[0-9]-*, armv5te-*, or armv6t2-*. The CPUType is a magic 1901 // number from /usr/include/mach/machine.h. It is ok to reproduce the 1902 // specific constants here because they are implicitly part of the Darwin ABI. 1903 enum { 1904 DARWIN_CPU_ARCH_ABI64 = 0x01000000, 1905 DARWIN_CPU_TYPE_X86 = 7, 1906 DARWIN_CPU_TYPE_ARM = 12, 1907 DARWIN_CPU_TYPE_POWERPC = 18 1908 }; 1909 1910 Triple::ArchType Arch = TT.getArch(); 1911 if (Arch == Triple::x86_64) 1912 CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64; 1913 else if (Arch == Triple::x86) 1914 CPUType = DARWIN_CPU_TYPE_X86; 1915 else if (Arch == Triple::ppc) 1916 CPUType = DARWIN_CPU_TYPE_POWERPC; 1917 else if (Arch == Triple::ppc64) 1918 CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64; 1919 else if (Arch == Triple::arm || Arch == Triple::thumb) 1920 CPUType = DARWIN_CPU_TYPE_ARM; 1921 1922 // Traditional Bitcode starts after header. 1923 assert(Buffer.size() >= DarwinBCHeaderSize && 1924 "Expected header size to be reserved"); 1925 unsigned BCOffset = DarwinBCHeaderSize; 1926 unsigned BCSize = Buffer.size()-DarwinBCHeaderSize; 1927 1928 // Write the magic and version. 1929 unsigned Position = 0; 1930 WriteInt32ToBuffer(0x0B17C0DE , Buffer, Position); 1931 WriteInt32ToBuffer(0 , Buffer, Position); // Version. 1932 WriteInt32ToBuffer(BCOffset , Buffer, Position); 1933 WriteInt32ToBuffer(BCSize , Buffer, Position); 1934 WriteInt32ToBuffer(CPUType , Buffer, Position); 1935 1936 // If the file is not a multiple of 16 bytes, insert dummy padding. 1937 while (Buffer.size() & 15) 1938 Buffer.push_back(0); 1939 } 1940 1941 /// WriteBitcodeToFile - Write the specified module to the specified output 1942 /// stream. 1943 void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) { 1944 SmallVector<char, 0> Buffer; 1945 Buffer.reserve(256*1024); 1946 1947 // If this is darwin or another generic macho target, reserve space for the 1948 // header. 1949 Triple TT(M->getTargetTriple()); 1950 if (TT.isOSDarwin()) 1951 Buffer.insert(Buffer.begin(), DarwinBCHeaderSize, 0); 1952 1953 // Emit the module into the buffer. 1954 { 1955 BitstreamWriter Stream(Buffer); 1956 1957 // Emit the file header. 1958 Stream.Emit((unsigned)'B', 8); 1959 Stream.Emit((unsigned)'C', 8); 1960 Stream.Emit(0x0, 4); 1961 Stream.Emit(0xC, 4); 1962 Stream.Emit(0xE, 4); 1963 Stream.Emit(0xD, 4); 1964 1965 // Emit the module. 1966 WriteModule(M, Stream); 1967 } 1968 1969 if (TT.isOSDarwin()) 1970 EmitDarwinBCHeaderAndTrailer(Buffer, TT); 1971 1972 // Write the generated bitstream to "Out". 1973 Out.write((char*)&Buffer.front(), Buffer.size()); 1974 } 1975