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