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