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