BitcodeWriter.cpp 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579
  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. #include "llvm/Bitcode/ReaderWriter.h"
  14. #include "llvm/Bitcode/BitstreamWriter.h"
  15. #include "llvm/Bitcode/LLVMBitCodes.h"
  16. #include "ValueEnumerator.h"
  17. #include "llvm/Constants.h"
  18. #include "llvm/DerivedTypes.h"
  19. #include "llvm/InlineAsm.h"
  20. #include "llvm/Instructions.h"
  21. #include "llvm/LLVMContext.h"
  22. #include "llvm/Metadata.h"
  23. #include "llvm/Module.h"
  24. #include "llvm/Operator.h"
  25. #include "llvm/TypeSymbolTable.h"
  26. #include "llvm/ValueSymbolTable.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Support/MathExtras.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include "llvm/System/Program.h"
  31. using namespace llvm;
  32. /// These are manifest constants used by the bitcode writer. They do not need to
  33. /// be kept in sync with the reader, but need to be consistent within this file.
  34. enum {
  35. CurVersion = 0,
  36. // VALUE_SYMTAB_BLOCK abbrev id's.
  37. VST_ENTRY_8_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  38. VST_ENTRY_7_ABBREV,
  39. VST_ENTRY_6_ABBREV,
  40. VST_BBENTRY_6_ABBREV,
  41. // CONSTANTS_BLOCK abbrev id's.
  42. CONSTANTS_SETTYPE_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  43. CONSTANTS_INTEGER_ABBREV,
  44. CONSTANTS_CE_CAST_Abbrev,
  45. CONSTANTS_NULL_Abbrev,
  46. // FUNCTION_BLOCK abbrev id's.
  47. FUNCTION_INST_LOAD_ABBREV = bitc::FIRST_APPLICATION_ABBREV,
  48. FUNCTION_INST_BINOP_ABBREV,
  49. FUNCTION_INST_BINOP_FLAGS_ABBREV,
  50. FUNCTION_INST_CAST_ABBREV,
  51. FUNCTION_INST_RET_VOID_ABBREV,
  52. FUNCTION_INST_RET_VAL_ABBREV,
  53. FUNCTION_INST_UNREACHABLE_ABBREV
  54. };
  55. static unsigned GetEncodedCastOpcode(unsigned Opcode) {
  56. switch (Opcode) {
  57. default: llvm_unreachable("Unknown cast instruction!");
  58. case Instruction::Trunc : return bitc::CAST_TRUNC;
  59. case Instruction::ZExt : return bitc::CAST_ZEXT;
  60. case Instruction::SExt : return bitc::CAST_SEXT;
  61. case Instruction::FPToUI : return bitc::CAST_FPTOUI;
  62. case Instruction::FPToSI : return bitc::CAST_FPTOSI;
  63. case Instruction::UIToFP : return bitc::CAST_UITOFP;
  64. case Instruction::SIToFP : return bitc::CAST_SITOFP;
  65. case Instruction::FPTrunc : return bitc::CAST_FPTRUNC;
  66. case Instruction::FPExt : return bitc::CAST_FPEXT;
  67. case Instruction::PtrToInt: return bitc::CAST_PTRTOINT;
  68. case Instruction::IntToPtr: return bitc::CAST_INTTOPTR;
  69. case Instruction::BitCast : return bitc::CAST_BITCAST;
  70. }
  71. }
  72. static unsigned GetEncodedBinaryOpcode(unsigned Opcode) {
  73. switch (Opcode) {
  74. default: llvm_unreachable("Unknown binary instruction!");
  75. case Instruction::Add:
  76. case Instruction::FAdd: return bitc::BINOP_ADD;
  77. case Instruction::Sub:
  78. case Instruction::FSub: return bitc::BINOP_SUB;
  79. case Instruction::Mul:
  80. case Instruction::FMul: return bitc::BINOP_MUL;
  81. case Instruction::UDiv: return bitc::BINOP_UDIV;
  82. case Instruction::FDiv:
  83. case Instruction::SDiv: return bitc::BINOP_SDIV;
  84. case Instruction::URem: return bitc::BINOP_UREM;
  85. case Instruction::FRem:
  86. case Instruction::SRem: return bitc::BINOP_SREM;
  87. case Instruction::Shl: return bitc::BINOP_SHL;
  88. case Instruction::LShr: return bitc::BINOP_LSHR;
  89. case Instruction::AShr: return bitc::BINOP_ASHR;
  90. case Instruction::And: return bitc::BINOP_AND;
  91. case Instruction::Or: return bitc::BINOP_OR;
  92. case Instruction::Xor: return bitc::BINOP_XOR;
  93. }
  94. }
  95. static void WriteStringRecord(unsigned Code, const std::string &Str,
  96. unsigned AbbrevToUse, BitstreamWriter &Stream) {
  97. SmallVector<unsigned, 64> Vals;
  98. // Code: [strchar x N]
  99. for (unsigned i = 0, e = Str.size(); i != e; ++i)
  100. Vals.push_back(Str[i]);
  101. // Emit the finished record.
  102. Stream.EmitRecord(Code, Vals, AbbrevToUse);
  103. }
  104. // Emit information about parameter attributes.
  105. static void WriteAttributeTable(const ValueEnumerator &VE,
  106. BitstreamWriter &Stream) {
  107. const std::vector<AttrListPtr> &Attrs = VE.getAttributes();
  108. if (Attrs.empty()) return;
  109. Stream.EnterSubblock(bitc::PARAMATTR_BLOCK_ID, 3);
  110. SmallVector<uint64_t, 64> Record;
  111. for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
  112. const AttrListPtr &A = Attrs[i];
  113. for (unsigned i = 0, e = A.getNumSlots(); i != e; ++i) {
  114. const AttributeWithIndex &PAWI = A.getSlot(i);
  115. Record.push_back(PAWI.Index);
  116. // FIXME: remove in LLVM 3.0
  117. // Store the alignment in the bitcode as a 16-bit raw value instead of a
  118. // 5-bit log2 encoded value. Shift the bits above the alignment up by
  119. // 11 bits.
  120. uint64_t FauxAttr = PAWI.Attrs & 0xffff;
  121. if (PAWI.Attrs & Attribute::Alignment)
  122. FauxAttr |= (1ull<<16)<<(((PAWI.Attrs & Attribute::Alignment)-1) >> 16);
  123. FauxAttr |= (PAWI.Attrs & (0x3FFull << 21)) << 11;
  124. Record.push_back(FauxAttr);
  125. }
  126. Stream.EmitRecord(bitc::PARAMATTR_CODE_ENTRY, Record);
  127. Record.clear();
  128. }
  129. Stream.ExitBlock();
  130. }
  131. /// WriteTypeTable - Write out the type table for a module.
  132. static void WriteTypeTable(const ValueEnumerator &VE, BitstreamWriter &Stream) {
  133. const ValueEnumerator::TypeList &TypeList = VE.getTypes();
  134. Stream.EnterSubblock(bitc::TYPE_BLOCK_ID, 4 /*count from # abbrevs */);
  135. SmallVector<uint64_t, 64> TypeVals;
  136. // Abbrev for TYPE_CODE_POINTER.
  137. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  138. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_POINTER));
  139. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  140. Log2_32_Ceil(VE.getTypes().size()+1)));
  141. Abbv->Add(BitCodeAbbrevOp(0)); // Addrspace = 0
  142. unsigned PtrAbbrev = Stream.EmitAbbrev(Abbv);
  143. // Abbrev for TYPE_CODE_FUNCTION.
  144. Abbv = new BitCodeAbbrev();
  145. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_FUNCTION));
  146. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // isvararg
  147. Abbv->Add(BitCodeAbbrevOp(0)); // FIXME: DEAD value, remove in LLVM 3.0
  148. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  149. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  150. Log2_32_Ceil(VE.getTypes().size()+1)));
  151. unsigned FunctionAbbrev = Stream.EmitAbbrev(Abbv);
  152. // Abbrev for TYPE_CODE_STRUCT.
  153. Abbv = new BitCodeAbbrev();
  154. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_STRUCT));
  155. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ispacked
  156. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  157. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  158. Log2_32_Ceil(VE.getTypes().size()+1)));
  159. unsigned StructAbbrev = Stream.EmitAbbrev(Abbv);
  160. // Abbrev for TYPE_CODE_ARRAY.
  161. Abbv = new BitCodeAbbrev();
  162. Abbv->Add(BitCodeAbbrevOp(bitc::TYPE_CODE_ARRAY));
  163. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // size
  164. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  165. Log2_32_Ceil(VE.getTypes().size()+1)));
  166. unsigned ArrayAbbrev = Stream.EmitAbbrev(Abbv);
  167. // Emit an entry count so the reader can reserve space.
  168. TypeVals.push_back(TypeList.size());
  169. Stream.EmitRecord(bitc::TYPE_CODE_NUMENTRY, TypeVals);
  170. TypeVals.clear();
  171. // Loop over all of the types, emitting each in turn.
  172. for (unsigned i = 0, e = TypeList.size(); i != e; ++i) {
  173. const Type *T = TypeList[i].first;
  174. int AbbrevToUse = 0;
  175. unsigned Code = 0;
  176. switch (T->getTypeID()) {
  177. default: llvm_unreachable("Unknown type!");
  178. case Type::VoidTyID: Code = bitc::TYPE_CODE_VOID; break;
  179. case Type::FloatTyID: Code = bitc::TYPE_CODE_FLOAT; break;
  180. case Type::DoubleTyID: Code = bitc::TYPE_CODE_DOUBLE; break;
  181. case Type::X86_FP80TyID: Code = bitc::TYPE_CODE_X86_FP80; break;
  182. case Type::FP128TyID: Code = bitc::TYPE_CODE_FP128; break;
  183. case Type::PPC_FP128TyID: Code = bitc::TYPE_CODE_PPC_FP128; break;
  184. case Type::LabelTyID: Code = bitc::TYPE_CODE_LABEL; break;
  185. case Type::OpaqueTyID: Code = bitc::TYPE_CODE_OPAQUE; break;
  186. case Type::MetadataTyID: Code = bitc::TYPE_CODE_METADATA; break;
  187. case Type::IntegerTyID:
  188. // INTEGER: [width]
  189. Code = bitc::TYPE_CODE_INTEGER;
  190. TypeVals.push_back(cast<IntegerType>(T)->getBitWidth());
  191. break;
  192. case Type::PointerTyID: {
  193. const PointerType *PTy = cast<PointerType>(T);
  194. // POINTER: [pointee type, address space]
  195. Code = bitc::TYPE_CODE_POINTER;
  196. TypeVals.push_back(VE.getTypeID(PTy->getElementType()));
  197. unsigned AddressSpace = PTy->getAddressSpace();
  198. TypeVals.push_back(AddressSpace);
  199. if (AddressSpace == 0) AbbrevToUse = PtrAbbrev;
  200. break;
  201. }
  202. case Type::FunctionTyID: {
  203. const FunctionType *FT = cast<FunctionType>(T);
  204. // FUNCTION: [isvararg, attrid, retty, paramty x N]
  205. Code = bitc::TYPE_CODE_FUNCTION;
  206. TypeVals.push_back(FT->isVarArg());
  207. TypeVals.push_back(0); // FIXME: DEAD: remove in llvm 3.0
  208. TypeVals.push_back(VE.getTypeID(FT->getReturnType()));
  209. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i)
  210. TypeVals.push_back(VE.getTypeID(FT->getParamType(i)));
  211. AbbrevToUse = FunctionAbbrev;
  212. break;
  213. }
  214. case Type::StructTyID: {
  215. const StructType *ST = cast<StructType>(T);
  216. // STRUCT: [ispacked, eltty x N]
  217. Code = bitc::TYPE_CODE_STRUCT;
  218. TypeVals.push_back(ST->isPacked());
  219. // Output all of the element types.
  220. for (StructType::element_iterator I = ST->element_begin(),
  221. E = ST->element_end(); I != E; ++I)
  222. TypeVals.push_back(VE.getTypeID(*I));
  223. AbbrevToUse = StructAbbrev;
  224. break;
  225. }
  226. case Type::ArrayTyID: {
  227. const ArrayType *AT = cast<ArrayType>(T);
  228. // ARRAY: [numelts, eltty]
  229. Code = bitc::TYPE_CODE_ARRAY;
  230. TypeVals.push_back(AT->getNumElements());
  231. TypeVals.push_back(VE.getTypeID(AT->getElementType()));
  232. AbbrevToUse = ArrayAbbrev;
  233. break;
  234. }
  235. case Type::VectorTyID: {
  236. const VectorType *VT = cast<VectorType>(T);
  237. // VECTOR [numelts, eltty]
  238. Code = bitc::TYPE_CODE_VECTOR;
  239. TypeVals.push_back(VT->getNumElements());
  240. TypeVals.push_back(VE.getTypeID(VT->getElementType()));
  241. break;
  242. }
  243. }
  244. // Emit the finished record.
  245. Stream.EmitRecord(Code, TypeVals, AbbrevToUse);
  246. TypeVals.clear();
  247. }
  248. Stream.ExitBlock();
  249. }
  250. static unsigned getEncodedLinkage(const GlobalValue *GV) {
  251. switch (GV->getLinkage()) {
  252. default: llvm_unreachable("Invalid linkage!");
  253. case GlobalValue::GhostLinkage: // Map ghost linkage onto external.
  254. case GlobalValue::ExternalLinkage: return 0;
  255. case GlobalValue::WeakAnyLinkage: return 1;
  256. case GlobalValue::AppendingLinkage: return 2;
  257. case GlobalValue::InternalLinkage: return 3;
  258. case GlobalValue::LinkOnceAnyLinkage: return 4;
  259. case GlobalValue::DLLImportLinkage: return 5;
  260. case GlobalValue::DLLExportLinkage: return 6;
  261. case GlobalValue::ExternalWeakLinkage: return 7;
  262. case GlobalValue::CommonLinkage: return 8;
  263. case GlobalValue::PrivateLinkage: return 9;
  264. case GlobalValue::WeakODRLinkage: return 10;
  265. case GlobalValue::LinkOnceODRLinkage: return 11;
  266. case GlobalValue::AvailableExternallyLinkage: return 12;
  267. case GlobalValue::LinkerPrivateLinkage: return 13;
  268. }
  269. }
  270. static unsigned getEncodedVisibility(const GlobalValue *GV) {
  271. switch (GV->getVisibility()) {
  272. default: llvm_unreachable("Invalid visibility!");
  273. case GlobalValue::DefaultVisibility: return 0;
  274. case GlobalValue::HiddenVisibility: return 1;
  275. case GlobalValue::ProtectedVisibility: return 2;
  276. }
  277. }
  278. // Emit top-level description of module, including target triple, inline asm,
  279. // descriptors for global variables, and function prototype info.
  280. static void WriteModuleInfo(const Module *M, const ValueEnumerator &VE,
  281. BitstreamWriter &Stream) {
  282. // Emit the list of dependent libraries for the Module.
  283. for (Module::lib_iterator I = M->lib_begin(), E = M->lib_end(); I != E; ++I)
  284. WriteStringRecord(bitc::MODULE_CODE_DEPLIB, *I, 0/*TODO*/, Stream);
  285. // Emit various pieces of data attached to a module.
  286. if (!M->getTargetTriple().empty())
  287. WriteStringRecord(bitc::MODULE_CODE_TRIPLE, M->getTargetTriple(),
  288. 0/*TODO*/, Stream);
  289. if (!M->getDataLayout().empty())
  290. WriteStringRecord(bitc::MODULE_CODE_DATALAYOUT, M->getDataLayout(),
  291. 0/*TODO*/, Stream);
  292. if (!M->getModuleInlineAsm().empty())
  293. WriteStringRecord(bitc::MODULE_CODE_ASM, M->getModuleInlineAsm(),
  294. 0/*TODO*/, Stream);
  295. // Emit information about sections and GC, computing how many there are. Also
  296. // compute the maximum alignment value.
  297. std::map<std::string, unsigned> SectionMap;
  298. std::map<std::string, unsigned> GCMap;
  299. unsigned MaxAlignment = 0;
  300. unsigned MaxGlobalType = 0;
  301. for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
  302. GV != E; ++GV) {
  303. MaxAlignment = std::max(MaxAlignment, GV->getAlignment());
  304. MaxGlobalType = std::max(MaxGlobalType, VE.getTypeID(GV->getType()));
  305. if (!GV->hasSection()) continue;
  306. // Give section names unique ID's.
  307. unsigned &Entry = SectionMap[GV->getSection()];
  308. if (Entry != 0) continue;
  309. WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, GV->getSection(),
  310. 0/*TODO*/, Stream);
  311. Entry = SectionMap.size();
  312. }
  313. for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
  314. MaxAlignment = std::max(MaxAlignment, F->getAlignment());
  315. if (F->hasSection()) {
  316. // Give section names unique ID's.
  317. unsigned &Entry = SectionMap[F->getSection()];
  318. if (!Entry) {
  319. WriteStringRecord(bitc::MODULE_CODE_SECTIONNAME, F->getSection(),
  320. 0/*TODO*/, Stream);
  321. Entry = SectionMap.size();
  322. }
  323. }
  324. if (F->hasGC()) {
  325. // Same for GC names.
  326. unsigned &Entry = GCMap[F->getGC()];
  327. if (!Entry) {
  328. WriteStringRecord(bitc::MODULE_CODE_GCNAME, F->getGC(),
  329. 0/*TODO*/, Stream);
  330. Entry = GCMap.size();
  331. }
  332. }
  333. }
  334. // Emit abbrev for globals, now that we know # sections and max alignment.
  335. unsigned SimpleGVarAbbrev = 0;
  336. if (!M->global_empty()) {
  337. // Add an abbrev for common globals with no visibility or thread localness.
  338. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  339. Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GLOBALVAR));
  340. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  341. Log2_32_Ceil(MaxGlobalType+1)));
  342. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Constant.
  343. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Initializer.
  344. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // Linkage.
  345. if (MaxAlignment == 0) // Alignment.
  346. Abbv->Add(BitCodeAbbrevOp(0));
  347. else {
  348. unsigned MaxEncAlignment = Log2_32(MaxAlignment)+1;
  349. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  350. Log2_32_Ceil(MaxEncAlignment+1)));
  351. }
  352. if (SectionMap.empty()) // Section.
  353. Abbv->Add(BitCodeAbbrevOp(0));
  354. else
  355. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  356. Log2_32_Ceil(SectionMap.size()+1)));
  357. // Don't bother emitting vis + thread local.
  358. SimpleGVarAbbrev = Stream.EmitAbbrev(Abbv);
  359. }
  360. // Emit the global variable information.
  361. SmallVector<unsigned, 64> Vals;
  362. for (Module::const_global_iterator GV = M->global_begin(),E = M->global_end();
  363. GV != E; ++GV) {
  364. unsigned AbbrevToUse = 0;
  365. // GLOBALVAR: [type, isconst, initid,
  366. // linkage, alignment, section, visibility, threadlocal]
  367. Vals.push_back(VE.getTypeID(GV->getType()));
  368. Vals.push_back(GV->isConstant());
  369. Vals.push_back(GV->isDeclaration() ? 0 :
  370. (VE.getValueID(GV->getInitializer()) + 1));
  371. Vals.push_back(getEncodedLinkage(GV));
  372. Vals.push_back(Log2_32(GV->getAlignment())+1);
  373. Vals.push_back(GV->hasSection() ? SectionMap[GV->getSection()] : 0);
  374. if (GV->isThreadLocal() ||
  375. GV->getVisibility() != GlobalValue::DefaultVisibility) {
  376. Vals.push_back(getEncodedVisibility(GV));
  377. Vals.push_back(GV->isThreadLocal());
  378. } else {
  379. AbbrevToUse = SimpleGVarAbbrev;
  380. }
  381. Stream.EmitRecord(bitc::MODULE_CODE_GLOBALVAR, Vals, AbbrevToUse);
  382. Vals.clear();
  383. }
  384. // Emit the function proto information.
  385. for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
  386. // FUNCTION: [type, callingconv, isproto, paramattr,
  387. // linkage, alignment, section, visibility, gc]
  388. Vals.push_back(VE.getTypeID(F->getType()));
  389. Vals.push_back(F->getCallingConv());
  390. Vals.push_back(F->isDeclaration());
  391. Vals.push_back(getEncodedLinkage(F));
  392. Vals.push_back(VE.getAttributeID(F->getAttributes()));
  393. Vals.push_back(Log2_32(F->getAlignment())+1);
  394. Vals.push_back(F->hasSection() ? SectionMap[F->getSection()] : 0);
  395. Vals.push_back(getEncodedVisibility(F));
  396. Vals.push_back(F->hasGC() ? GCMap[F->getGC()] : 0);
  397. unsigned AbbrevToUse = 0;
  398. Stream.EmitRecord(bitc::MODULE_CODE_FUNCTION, Vals, AbbrevToUse);
  399. Vals.clear();
  400. }
  401. // Emit the alias information.
  402. for (Module::const_alias_iterator AI = M->alias_begin(), E = M->alias_end();
  403. AI != E; ++AI) {
  404. Vals.push_back(VE.getTypeID(AI->getType()));
  405. Vals.push_back(VE.getValueID(AI->getAliasee()));
  406. Vals.push_back(getEncodedLinkage(AI));
  407. Vals.push_back(getEncodedVisibility(AI));
  408. unsigned AbbrevToUse = 0;
  409. Stream.EmitRecord(bitc::MODULE_CODE_ALIAS, Vals, AbbrevToUse);
  410. Vals.clear();
  411. }
  412. }
  413. static uint64_t GetOptimizationFlags(const Value *V) {
  414. uint64_t Flags = 0;
  415. if (const OverflowingBinaryOperator *OBO =
  416. dyn_cast<OverflowingBinaryOperator>(V)) {
  417. if (OBO->hasNoSignedWrap())
  418. Flags |= 1 << bitc::OBO_NO_SIGNED_WRAP;
  419. if (OBO->hasNoUnsignedWrap())
  420. Flags |= 1 << bitc::OBO_NO_UNSIGNED_WRAP;
  421. } else if (const SDivOperator *Div = dyn_cast<SDivOperator>(V)) {
  422. if (Div->isExact())
  423. Flags |= 1 << bitc::SDIV_EXACT;
  424. }
  425. return Flags;
  426. }
  427. static void WriteMDNode(const MDNode *N,
  428. const ValueEnumerator &VE,
  429. BitstreamWriter &Stream,
  430. SmallVector<uint64_t, 64> &Record) {
  431. for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) {
  432. if (N->getElement(i)) {
  433. Record.push_back(VE.getTypeID(N->getElement(i)->getType()));
  434. Record.push_back(VE.getValueID(N->getElement(i)));
  435. } else {
  436. Record.push_back(VE.getTypeID(Type::getVoidTy(N->getContext())));
  437. Record.push_back(0);
  438. }
  439. }
  440. Stream.EmitRecord(bitc::METADATA_NODE, Record, 0);
  441. Record.clear();
  442. }
  443. static void WriteModuleMetadata(const ValueEnumerator &VE,
  444. BitstreamWriter &Stream) {
  445. const ValueEnumerator::ValueList &Vals = VE.getMDValues();
  446. bool StartedMetadataBlock = false;
  447. unsigned MDSAbbrev = 0;
  448. SmallVector<uint64_t, 64> Record;
  449. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  450. if (const MDNode *N = dyn_cast<MDNode>(Vals[i].first)) {
  451. if (!StartedMetadataBlock) {
  452. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  453. StartedMetadataBlock = true;
  454. }
  455. WriteMDNode(N, VE, Stream, Record);
  456. } else if (const MDString *MDS = dyn_cast<MDString>(Vals[i].first)) {
  457. if (!StartedMetadataBlock) {
  458. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  459. // Abbrev for METADATA_STRING.
  460. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  461. Abbv->Add(BitCodeAbbrevOp(bitc::METADATA_STRING));
  462. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  463. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  464. MDSAbbrev = Stream.EmitAbbrev(Abbv);
  465. StartedMetadataBlock = true;
  466. }
  467. // Code: [strchar x N]
  468. Record.append(MDS->begin(), MDS->end());
  469. // Emit the finished record.
  470. Stream.EmitRecord(bitc::METADATA_STRING, Record, MDSAbbrev);
  471. Record.clear();
  472. } else if (const NamedMDNode *NMD = dyn_cast<NamedMDNode>(Vals[i].first)) {
  473. if (!StartedMetadataBlock) {
  474. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  475. StartedMetadataBlock = true;
  476. }
  477. // Write name.
  478. std::string Str = NMD->getNameStr();
  479. const char *StrBegin = Str.c_str();
  480. for (unsigned i = 0, e = Str.length(); i != e; ++i)
  481. Record.push_back(StrBegin[i]);
  482. Stream.EmitRecord(bitc::METADATA_NAME, Record, 0/*TODO*/);
  483. Record.clear();
  484. // Write named metadata elements.
  485. for (unsigned i = 0, e = NMD->getNumElements(); i != e; ++i) {
  486. if (NMD->getElement(i))
  487. Record.push_back(VE.getValueID(NMD->getElement(i)));
  488. else
  489. Record.push_back(0);
  490. }
  491. Stream.EmitRecord(bitc::METADATA_NAMED_NODE, Record, 0);
  492. Record.clear();
  493. }
  494. }
  495. if (StartedMetadataBlock)
  496. Stream.ExitBlock();
  497. }
  498. static void WriteMetadataAttachment(const Function &F,
  499. const ValueEnumerator &VE,
  500. BitstreamWriter &Stream) {
  501. bool StartedMetadataBlock = false;
  502. SmallVector<uint64_t, 64> Record;
  503. // Write metadata attachments
  504. // METADATA_ATTACHMENT - [m x [value, [n x [id, mdnode]]]
  505. MetadataContext &TheMetadata = F.getContext().getMetadata();
  506. typedef SmallVector<std::pair<unsigned, TrackingVH<MDNode> >, 2> MDMapTy;
  507. MDMapTy MDs;
  508. for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
  509. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
  510. I != E; ++I) {
  511. MDs.clear();
  512. TheMetadata.getMDs(I, MDs);
  513. bool RecordedInstruction = false;
  514. for (MDMapTy::const_iterator PI = MDs.begin(), PE = MDs.end();
  515. PI != PE; ++PI) {
  516. if (RecordedInstruction == false) {
  517. Record.push_back(VE.getInstructionID(I));
  518. RecordedInstruction = true;
  519. }
  520. Record.push_back(PI->first);
  521. Record.push_back(VE.getValueID(PI->second));
  522. }
  523. if (!Record.empty()) {
  524. if (!StartedMetadataBlock) {
  525. Stream.EnterSubblock(bitc::METADATA_ATTACHMENT_ID, 3);
  526. StartedMetadataBlock = true;
  527. }
  528. Stream.EmitRecord(bitc::METADATA_ATTACHMENT, Record, 0);
  529. Record.clear();
  530. }
  531. }
  532. if (StartedMetadataBlock)
  533. Stream.ExitBlock();
  534. }
  535. static void WriteModuleMetadataStore(const Module *M,
  536. const ValueEnumerator &VE,
  537. BitstreamWriter &Stream) {
  538. bool StartedMetadataBlock = false;
  539. SmallVector<uint64_t, 64> Record;
  540. // Write metadata kinds
  541. // METADATA_KIND - [n x [id, name]]
  542. MetadataContext &TheMetadata = M->getContext().getMetadata();
  543. SmallVector<std::pair<unsigned, StringRef>, 4> Names;
  544. TheMetadata.getHandlerNames(Names);
  545. for (SmallVector<std::pair<unsigned, StringRef>, 4>::iterator
  546. I = Names.begin(),
  547. E = Names.end(); I != E; ++I) {
  548. Record.push_back(I->first);
  549. StringRef KName = I->second;
  550. for (unsigned i = 0, e = KName.size(); i != e; ++i)
  551. Record.push_back(KName[i]);
  552. if (!StartedMetadataBlock) {
  553. Stream.EnterSubblock(bitc::METADATA_BLOCK_ID, 3);
  554. StartedMetadataBlock = true;
  555. }
  556. Stream.EmitRecord(bitc::METADATA_KIND, Record, 0);
  557. Record.clear();
  558. }
  559. if (StartedMetadataBlock)
  560. Stream.ExitBlock();
  561. }
  562. static void WriteConstants(unsigned FirstVal, unsigned LastVal,
  563. const ValueEnumerator &VE,
  564. BitstreamWriter &Stream, bool isGlobal) {
  565. if (FirstVal == LastVal) return;
  566. Stream.EnterSubblock(bitc::CONSTANTS_BLOCK_ID, 4);
  567. unsigned AggregateAbbrev = 0;
  568. unsigned String8Abbrev = 0;
  569. unsigned CString7Abbrev = 0;
  570. unsigned CString6Abbrev = 0;
  571. // If this is a constant pool for the module, emit module-specific abbrevs.
  572. if (isGlobal) {
  573. // Abbrev for CST_CODE_AGGREGATE.
  574. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  575. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_AGGREGATE));
  576. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  577. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, Log2_32_Ceil(LastVal+1)));
  578. AggregateAbbrev = Stream.EmitAbbrev(Abbv);
  579. // Abbrev for CST_CODE_STRING.
  580. Abbv = new BitCodeAbbrev();
  581. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_STRING));
  582. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  583. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  584. String8Abbrev = Stream.EmitAbbrev(Abbv);
  585. // Abbrev for CST_CODE_CSTRING.
  586. Abbv = new BitCodeAbbrev();
  587. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
  588. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  589. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  590. CString7Abbrev = Stream.EmitAbbrev(Abbv);
  591. // Abbrev for CST_CODE_CSTRING.
  592. Abbv = new BitCodeAbbrev();
  593. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CSTRING));
  594. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  595. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  596. CString6Abbrev = Stream.EmitAbbrev(Abbv);
  597. }
  598. SmallVector<uint64_t, 64> Record;
  599. const ValueEnumerator::ValueList &Vals = VE.getValues();
  600. const Type *LastTy = 0;
  601. for (unsigned i = FirstVal; i != LastVal; ++i) {
  602. const Value *V = Vals[i].first;
  603. // If we need to switch types, do so now.
  604. if (V->getType() != LastTy) {
  605. LastTy = V->getType();
  606. Record.push_back(VE.getTypeID(LastTy));
  607. Stream.EmitRecord(bitc::CST_CODE_SETTYPE, Record,
  608. CONSTANTS_SETTYPE_ABBREV);
  609. Record.clear();
  610. }
  611. if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
  612. Record.push_back(unsigned(IA->hasSideEffects()) |
  613. unsigned(IA->isAlignStack()) << 1);
  614. // Add the asm string.
  615. const std::string &AsmStr = IA->getAsmString();
  616. Record.push_back(AsmStr.size());
  617. for (unsigned i = 0, e = AsmStr.size(); i != e; ++i)
  618. Record.push_back(AsmStr[i]);
  619. // Add the constraint string.
  620. const std::string &ConstraintStr = IA->getConstraintString();
  621. Record.push_back(ConstraintStr.size());
  622. for (unsigned i = 0, e = ConstraintStr.size(); i != e; ++i)
  623. Record.push_back(ConstraintStr[i]);
  624. Stream.EmitRecord(bitc::CST_CODE_INLINEASM, Record);
  625. Record.clear();
  626. continue;
  627. }
  628. const Constant *C = cast<Constant>(V);
  629. unsigned Code = -1U;
  630. unsigned AbbrevToUse = 0;
  631. if (C->isNullValue()) {
  632. Code = bitc::CST_CODE_NULL;
  633. } else if (isa<UndefValue>(C)) {
  634. Code = bitc::CST_CODE_UNDEF;
  635. } else if (const ConstantInt *IV = dyn_cast<ConstantInt>(C)) {
  636. if (IV->getBitWidth() <= 64) {
  637. int64_t V = IV->getSExtValue();
  638. if (V >= 0)
  639. Record.push_back(V << 1);
  640. else
  641. Record.push_back((-V << 1) | 1);
  642. Code = bitc::CST_CODE_INTEGER;
  643. AbbrevToUse = CONSTANTS_INTEGER_ABBREV;
  644. } else { // Wide integers, > 64 bits in size.
  645. // We have an arbitrary precision integer value to write whose
  646. // bit width is > 64. However, in canonical unsigned integer
  647. // format it is likely that the high bits are going to be zero.
  648. // So, we only write the number of active words.
  649. unsigned NWords = IV->getValue().getActiveWords();
  650. const uint64_t *RawWords = IV->getValue().getRawData();
  651. for (unsigned i = 0; i != NWords; ++i) {
  652. int64_t V = RawWords[i];
  653. if (V >= 0)
  654. Record.push_back(V << 1);
  655. else
  656. Record.push_back((-V << 1) | 1);
  657. }
  658. Code = bitc::CST_CODE_WIDE_INTEGER;
  659. }
  660. } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
  661. Code = bitc::CST_CODE_FLOAT;
  662. const Type *Ty = CFP->getType();
  663. if (Ty->isFloatTy() || Ty->isDoubleTy()) {
  664. Record.push_back(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
  665. } else if (Ty->isX86_FP80Ty()) {
  666. // api needed to prevent premature destruction
  667. // bits are not in the same order as a normal i80 APInt, compensate.
  668. APInt api = CFP->getValueAPF().bitcastToAPInt();
  669. const uint64_t *p = api.getRawData();
  670. Record.push_back((p[1] << 48) | (p[0] >> 16));
  671. Record.push_back(p[0] & 0xffffLL);
  672. } else if (Ty->isFP128Ty() || Ty->isPPC_FP128Ty()) {
  673. APInt api = CFP->getValueAPF().bitcastToAPInt();
  674. const uint64_t *p = api.getRawData();
  675. Record.push_back(p[0]);
  676. Record.push_back(p[1]);
  677. } else {
  678. assert (0 && "Unknown FP type!");
  679. }
  680. } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
  681. // Emit constant strings specially.
  682. unsigned NumOps = C->getNumOperands();
  683. // If this is a null-terminated string, use the denser CSTRING encoding.
  684. if (C->getOperand(NumOps-1)->isNullValue()) {
  685. Code = bitc::CST_CODE_CSTRING;
  686. --NumOps; // Don't encode the null, which isn't allowed by char6.
  687. } else {
  688. Code = bitc::CST_CODE_STRING;
  689. AbbrevToUse = String8Abbrev;
  690. }
  691. bool isCStr7 = Code == bitc::CST_CODE_CSTRING;
  692. bool isCStrChar6 = Code == bitc::CST_CODE_CSTRING;
  693. for (unsigned i = 0; i != NumOps; ++i) {
  694. unsigned char V = cast<ConstantInt>(C->getOperand(i))->getZExtValue();
  695. Record.push_back(V);
  696. isCStr7 &= (V & 128) == 0;
  697. if (isCStrChar6)
  698. isCStrChar6 = BitCodeAbbrevOp::isChar6(V);
  699. }
  700. if (isCStrChar6)
  701. AbbrevToUse = CString6Abbrev;
  702. else if (isCStr7)
  703. AbbrevToUse = CString7Abbrev;
  704. } else if (isa<ConstantArray>(C) || isa<ConstantStruct>(V) ||
  705. isa<ConstantVector>(V)) {
  706. Code = bitc::CST_CODE_AGGREGATE;
  707. for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
  708. Record.push_back(VE.getValueID(C->getOperand(i)));
  709. AbbrevToUse = AggregateAbbrev;
  710. } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  711. switch (CE->getOpcode()) {
  712. default:
  713. if (Instruction::isCast(CE->getOpcode())) {
  714. Code = bitc::CST_CODE_CE_CAST;
  715. Record.push_back(GetEncodedCastOpcode(CE->getOpcode()));
  716. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  717. Record.push_back(VE.getValueID(C->getOperand(0)));
  718. AbbrevToUse = CONSTANTS_CE_CAST_Abbrev;
  719. } else {
  720. assert(CE->getNumOperands() == 2 && "Unknown constant expr!");
  721. Code = bitc::CST_CODE_CE_BINOP;
  722. Record.push_back(GetEncodedBinaryOpcode(CE->getOpcode()));
  723. Record.push_back(VE.getValueID(C->getOperand(0)));
  724. Record.push_back(VE.getValueID(C->getOperand(1)));
  725. uint64_t Flags = GetOptimizationFlags(CE);
  726. if (Flags != 0)
  727. Record.push_back(Flags);
  728. }
  729. break;
  730. case Instruction::GetElementPtr:
  731. Code = bitc::CST_CODE_CE_GEP;
  732. if (cast<GEPOperator>(C)->isInBounds())
  733. Code = bitc::CST_CODE_CE_INBOUNDS_GEP;
  734. for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
  735. Record.push_back(VE.getTypeID(C->getOperand(i)->getType()));
  736. Record.push_back(VE.getValueID(C->getOperand(i)));
  737. }
  738. break;
  739. case Instruction::Select:
  740. Code = bitc::CST_CODE_CE_SELECT;
  741. Record.push_back(VE.getValueID(C->getOperand(0)));
  742. Record.push_back(VE.getValueID(C->getOperand(1)));
  743. Record.push_back(VE.getValueID(C->getOperand(2)));
  744. break;
  745. case Instruction::ExtractElement:
  746. Code = bitc::CST_CODE_CE_EXTRACTELT;
  747. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  748. Record.push_back(VE.getValueID(C->getOperand(0)));
  749. Record.push_back(VE.getValueID(C->getOperand(1)));
  750. break;
  751. case Instruction::InsertElement:
  752. Code = bitc::CST_CODE_CE_INSERTELT;
  753. Record.push_back(VE.getValueID(C->getOperand(0)));
  754. Record.push_back(VE.getValueID(C->getOperand(1)));
  755. Record.push_back(VE.getValueID(C->getOperand(2)));
  756. break;
  757. case Instruction::ShuffleVector:
  758. // If the return type and argument types are the same, this is a
  759. // standard shufflevector instruction. If the types are different,
  760. // then the shuffle is widening or truncating the input vectors, and
  761. // the argument type must also be encoded.
  762. if (C->getType() == C->getOperand(0)->getType()) {
  763. Code = bitc::CST_CODE_CE_SHUFFLEVEC;
  764. } else {
  765. Code = bitc::CST_CODE_CE_SHUFVEC_EX;
  766. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  767. }
  768. Record.push_back(VE.getValueID(C->getOperand(0)));
  769. Record.push_back(VE.getValueID(C->getOperand(1)));
  770. Record.push_back(VE.getValueID(C->getOperand(2)));
  771. break;
  772. case Instruction::ICmp:
  773. case Instruction::FCmp:
  774. Code = bitc::CST_CODE_CE_CMP;
  775. Record.push_back(VE.getTypeID(C->getOperand(0)->getType()));
  776. Record.push_back(VE.getValueID(C->getOperand(0)));
  777. Record.push_back(VE.getValueID(C->getOperand(1)));
  778. Record.push_back(CE->getPredicate());
  779. break;
  780. }
  781. } else {
  782. llvm_unreachable("Unknown constant!");
  783. }
  784. Stream.EmitRecord(Code, Record, AbbrevToUse);
  785. Record.clear();
  786. }
  787. Stream.ExitBlock();
  788. }
  789. static void WriteModuleConstants(const ValueEnumerator &VE,
  790. BitstreamWriter &Stream) {
  791. const ValueEnumerator::ValueList &Vals = VE.getValues();
  792. // Find the first constant to emit, which is the first non-globalvalue value.
  793. // We know globalvalues have been emitted by WriteModuleInfo.
  794. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  795. if (!isa<GlobalValue>(Vals[i].first)) {
  796. WriteConstants(i, Vals.size(), VE, Stream, true);
  797. return;
  798. }
  799. }
  800. }
  801. /// PushValueAndType - The file has to encode both the value and type id for
  802. /// many values, because we need to know what type to create for forward
  803. /// references. However, most operands are not forward references, so this type
  804. /// field is not needed.
  805. ///
  806. /// This function adds V's value ID to Vals. If the value ID is higher than the
  807. /// instruction ID, then it is a forward reference, and it also includes the
  808. /// type ID.
  809. static bool PushValueAndType(const Value *V, unsigned InstID,
  810. SmallVector<unsigned, 64> &Vals,
  811. ValueEnumerator &VE) {
  812. unsigned ValID = VE.getValueID(V);
  813. Vals.push_back(ValID);
  814. if (ValID >= InstID) {
  815. Vals.push_back(VE.getTypeID(V->getType()));
  816. return true;
  817. }
  818. return false;
  819. }
  820. /// WriteInstruction - Emit an instruction to the specified stream.
  821. static void WriteInstruction(const Instruction &I, unsigned InstID,
  822. ValueEnumerator &VE, BitstreamWriter &Stream,
  823. SmallVector<unsigned, 64> &Vals) {
  824. unsigned Code = 0;
  825. unsigned AbbrevToUse = 0;
  826. VE.setInstructionID(&I);
  827. switch (I.getOpcode()) {
  828. default:
  829. if (Instruction::isCast(I.getOpcode())) {
  830. Code = bitc::FUNC_CODE_INST_CAST;
  831. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
  832. AbbrevToUse = FUNCTION_INST_CAST_ABBREV;
  833. Vals.push_back(VE.getTypeID(I.getType()));
  834. Vals.push_back(GetEncodedCastOpcode(I.getOpcode()));
  835. } else {
  836. assert(isa<BinaryOperator>(I) && "Unknown instruction!");
  837. Code = bitc::FUNC_CODE_INST_BINOP;
  838. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
  839. AbbrevToUse = FUNCTION_INST_BINOP_ABBREV;
  840. Vals.push_back(VE.getValueID(I.getOperand(1)));
  841. Vals.push_back(GetEncodedBinaryOpcode(I.getOpcode()));
  842. uint64_t Flags = GetOptimizationFlags(&I);
  843. if (Flags != 0) {
  844. if (AbbrevToUse == FUNCTION_INST_BINOP_ABBREV)
  845. AbbrevToUse = FUNCTION_INST_BINOP_FLAGS_ABBREV;
  846. Vals.push_back(Flags);
  847. }
  848. }
  849. break;
  850. case Instruction::GetElementPtr:
  851. Code = bitc::FUNC_CODE_INST_GEP;
  852. if (cast<GEPOperator>(&I)->isInBounds())
  853. Code = bitc::FUNC_CODE_INST_INBOUNDS_GEP;
  854. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  855. PushValueAndType(I.getOperand(i), InstID, Vals, VE);
  856. break;
  857. case Instruction::ExtractValue: {
  858. Code = bitc::FUNC_CODE_INST_EXTRACTVAL;
  859. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  860. const ExtractValueInst *EVI = cast<ExtractValueInst>(&I);
  861. for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
  862. Vals.push_back(*i);
  863. break;
  864. }
  865. case Instruction::InsertValue: {
  866. Code = bitc::FUNC_CODE_INST_INSERTVAL;
  867. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  868. PushValueAndType(I.getOperand(1), InstID, Vals, VE);
  869. const InsertValueInst *IVI = cast<InsertValueInst>(&I);
  870. for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
  871. Vals.push_back(*i);
  872. break;
  873. }
  874. case Instruction::Select:
  875. Code = bitc::FUNC_CODE_INST_VSELECT;
  876. PushValueAndType(I.getOperand(1), InstID, Vals, VE);
  877. Vals.push_back(VE.getValueID(I.getOperand(2)));
  878. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  879. break;
  880. case Instruction::ExtractElement:
  881. Code = bitc::FUNC_CODE_INST_EXTRACTELT;
  882. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  883. Vals.push_back(VE.getValueID(I.getOperand(1)));
  884. break;
  885. case Instruction::InsertElement:
  886. Code = bitc::FUNC_CODE_INST_INSERTELT;
  887. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  888. Vals.push_back(VE.getValueID(I.getOperand(1)));
  889. Vals.push_back(VE.getValueID(I.getOperand(2)));
  890. break;
  891. case Instruction::ShuffleVector:
  892. Code = bitc::FUNC_CODE_INST_SHUFFLEVEC;
  893. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  894. Vals.push_back(VE.getValueID(I.getOperand(1)));
  895. Vals.push_back(VE.getValueID(I.getOperand(2)));
  896. break;
  897. case Instruction::ICmp:
  898. case Instruction::FCmp:
  899. // compare returning Int1Ty or vector of Int1Ty
  900. Code = bitc::FUNC_CODE_INST_CMP2;
  901. PushValueAndType(I.getOperand(0), InstID, Vals, VE);
  902. Vals.push_back(VE.getValueID(I.getOperand(1)));
  903. Vals.push_back(cast<CmpInst>(I).getPredicate());
  904. break;
  905. case Instruction::Ret:
  906. {
  907. Code = bitc::FUNC_CODE_INST_RET;
  908. unsigned NumOperands = I.getNumOperands();
  909. if (NumOperands == 0)
  910. AbbrevToUse = FUNCTION_INST_RET_VOID_ABBREV;
  911. else if (NumOperands == 1) {
  912. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE))
  913. AbbrevToUse = FUNCTION_INST_RET_VAL_ABBREV;
  914. } else {
  915. for (unsigned i = 0, e = NumOperands; i != e; ++i)
  916. PushValueAndType(I.getOperand(i), InstID, Vals, VE);
  917. }
  918. }
  919. break;
  920. case Instruction::Br:
  921. {
  922. Code = bitc::FUNC_CODE_INST_BR;
  923. BranchInst &II = cast<BranchInst>(I);
  924. Vals.push_back(VE.getValueID(II.getSuccessor(0)));
  925. if (II.isConditional()) {
  926. Vals.push_back(VE.getValueID(II.getSuccessor(1)));
  927. Vals.push_back(VE.getValueID(II.getCondition()));
  928. }
  929. }
  930. break;
  931. case Instruction::Switch:
  932. Code = bitc::FUNC_CODE_INST_SWITCH;
  933. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
  934. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  935. Vals.push_back(VE.getValueID(I.getOperand(i)));
  936. break;
  937. case Instruction::IndirectBr:
  938. Code = bitc::FUNC_CODE_INST_INDIRECTBR;
  939. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType()));
  940. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  941. Vals.push_back(VE.getValueID(I.getOperand(i)));
  942. break;
  943. case Instruction::Invoke: {
  944. const InvokeInst *II = cast<InvokeInst>(&I);
  945. const Value *Callee(II->getCalledValue());
  946. const PointerType *PTy = cast<PointerType>(Callee->getType());
  947. const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
  948. Code = bitc::FUNC_CODE_INST_INVOKE;
  949. Vals.push_back(VE.getAttributeID(II->getAttributes()));
  950. Vals.push_back(II->getCallingConv());
  951. Vals.push_back(VE.getValueID(II->getNormalDest()));
  952. Vals.push_back(VE.getValueID(II->getUnwindDest()));
  953. PushValueAndType(Callee, InstID, Vals, VE);
  954. // Emit value #'s for the fixed parameters.
  955. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
  956. Vals.push_back(VE.getValueID(I.getOperand(i+3))); // fixed param.
  957. // Emit type/value pairs for varargs params.
  958. if (FTy->isVarArg()) {
  959. for (unsigned i = 3+FTy->getNumParams(), e = I.getNumOperands();
  960. i != e; ++i)
  961. PushValueAndType(I.getOperand(i), InstID, Vals, VE); // vararg
  962. }
  963. break;
  964. }
  965. case Instruction::Unwind:
  966. Code = bitc::FUNC_CODE_INST_UNWIND;
  967. break;
  968. case Instruction::Unreachable:
  969. Code = bitc::FUNC_CODE_INST_UNREACHABLE;
  970. AbbrevToUse = FUNCTION_INST_UNREACHABLE_ABBREV;
  971. break;
  972. case Instruction::PHI:
  973. Code = bitc::FUNC_CODE_INST_PHI;
  974. Vals.push_back(VE.getTypeID(I.getType()));
  975. for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
  976. Vals.push_back(VE.getValueID(I.getOperand(i)));
  977. break;
  978. case Instruction::Alloca:
  979. Code = bitc::FUNC_CODE_INST_ALLOCA;
  980. Vals.push_back(VE.getTypeID(I.getType()));
  981. Vals.push_back(VE.getValueID(I.getOperand(0))); // size.
  982. Vals.push_back(Log2_32(cast<AllocaInst>(I).getAlignment())+1);
  983. break;
  984. case Instruction::Load:
  985. Code = bitc::FUNC_CODE_INST_LOAD;
  986. if (!PushValueAndType(I.getOperand(0), InstID, Vals, VE)) // ptr
  987. AbbrevToUse = FUNCTION_INST_LOAD_ABBREV;
  988. Vals.push_back(Log2_32(cast<LoadInst>(I).getAlignment())+1);
  989. Vals.push_back(cast<LoadInst>(I).isVolatile());
  990. break;
  991. case Instruction::Store:
  992. Code = bitc::FUNC_CODE_INST_STORE2;
  993. PushValueAndType(I.getOperand(1), InstID, Vals, VE); // ptrty + ptr
  994. Vals.push_back(VE.getValueID(I.getOperand(0))); // val.
  995. Vals.push_back(Log2_32(cast<StoreInst>(I).getAlignment())+1);
  996. Vals.push_back(cast<StoreInst>(I).isVolatile());
  997. break;
  998. case Instruction::Call: {
  999. const PointerType *PTy = cast<PointerType>(I.getOperand(0)->getType());
  1000. const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
  1001. Code = bitc::FUNC_CODE_INST_CALL;
  1002. const CallInst *CI = cast<CallInst>(&I);
  1003. Vals.push_back(VE.getAttributeID(CI->getAttributes()));
  1004. Vals.push_back((CI->getCallingConv() << 1) | unsigned(CI->isTailCall()));
  1005. PushValueAndType(CI->getOperand(0), InstID, Vals, VE); // Callee
  1006. // Emit value #'s for the fixed parameters.
  1007. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
  1008. Vals.push_back(VE.getValueID(I.getOperand(i+1))); // fixed param.
  1009. // Emit type/value pairs for varargs params.
  1010. if (FTy->isVarArg()) {
  1011. unsigned NumVarargs = I.getNumOperands()-1-FTy->getNumParams();
  1012. for (unsigned i = I.getNumOperands()-NumVarargs, e = I.getNumOperands();
  1013. i != e; ++i)
  1014. PushValueAndType(I.getOperand(i), InstID, Vals, VE); // varargs
  1015. }
  1016. break;
  1017. }
  1018. case Instruction::VAArg:
  1019. Code = bitc::FUNC_CODE_INST_VAARG;
  1020. Vals.push_back(VE.getTypeID(I.getOperand(0)->getType())); // valistty
  1021. Vals.push_back(VE.getValueID(I.getOperand(0))); // valist.
  1022. Vals.push_back(VE.getTypeID(I.getType())); // restype.
  1023. break;
  1024. }
  1025. Stream.EmitRecord(Code, Vals, AbbrevToUse);
  1026. Vals.clear();
  1027. }
  1028. // Emit names for globals/functions etc.
  1029. static void WriteValueSymbolTable(const ValueSymbolTable &VST,
  1030. const ValueEnumerator &VE,
  1031. BitstreamWriter &Stream) {
  1032. if (VST.empty()) return;
  1033. Stream.EnterSubblock(bitc::VALUE_SYMTAB_BLOCK_ID, 4);
  1034. // FIXME: Set up the abbrev, we know how many values there are!
  1035. // FIXME: We know if the type names can use 7-bit ascii.
  1036. SmallVector<unsigned, 64> NameVals;
  1037. for (ValueSymbolTable::const_iterator SI = VST.begin(), SE = VST.end();
  1038. SI != SE; ++SI) {
  1039. const ValueName &Name = *SI;
  1040. // Figure out the encoding to use for the name.
  1041. bool is7Bit = true;
  1042. bool isChar6 = true;
  1043. for (const char *C = Name.getKeyData(), *E = C+Name.getKeyLength();
  1044. C != E; ++C) {
  1045. if (isChar6)
  1046. isChar6 = BitCodeAbbrevOp::isChar6(*C);
  1047. if ((unsigned char)*C & 128) {
  1048. is7Bit = false;
  1049. break; // don't bother scanning the rest.
  1050. }
  1051. }
  1052. unsigned AbbrevToUse = VST_ENTRY_8_ABBREV;
  1053. // VST_ENTRY: [valueid, namechar x N]
  1054. // VST_BBENTRY: [bbid, namechar x N]
  1055. unsigned Code;
  1056. if (isa<BasicBlock>(SI->getValue())) {
  1057. Code = bitc::VST_CODE_BBENTRY;
  1058. if (isChar6)
  1059. AbbrevToUse = VST_BBENTRY_6_ABBREV;
  1060. } else {
  1061. Code = bitc::VST_CODE_ENTRY;
  1062. if (isChar6)
  1063. AbbrevToUse = VST_ENTRY_6_ABBREV;
  1064. else if (is7Bit)
  1065. AbbrevToUse = VST_ENTRY_7_ABBREV;
  1066. }
  1067. NameVals.push_back(VE.getValueID(SI->getValue()));
  1068. for (const char *P = Name.getKeyData(),
  1069. *E = Name.getKeyData()+Name.getKeyLength(); P != E; ++P)
  1070. NameVals.push_back((unsigned char)*P);
  1071. // Emit the finished record.
  1072. Stream.EmitRecord(Code, NameVals, AbbrevToUse);
  1073. NameVals.clear();
  1074. }
  1075. Stream.ExitBlock();
  1076. }
  1077. /// WriteFunction - Emit a function body to the module stream.
  1078. static void WriteFunction(const Function &F, ValueEnumerator &VE,
  1079. BitstreamWriter &Stream) {
  1080. Stream.EnterSubblock(bitc::FUNCTION_BLOCK_ID, 4);
  1081. VE.incorporateFunction(F);
  1082. SmallVector<unsigned, 64> Vals;
  1083. // Emit the number of basic blocks, so the reader can create them ahead of
  1084. // time.
  1085. Vals.push_back(VE.getBasicBlocks().size());
  1086. Stream.EmitRecord(bitc::FUNC_CODE_DECLAREBLOCKS, Vals);
  1087. Vals.clear();
  1088. // If there are function-local constants, emit them now.
  1089. unsigned CstStart, CstEnd;
  1090. VE.getFunctionConstantRange(CstStart, CstEnd);
  1091. WriteConstants(CstStart, CstEnd, VE, Stream, false);
  1092. // Keep a running idea of what the instruction ID is.
  1093. unsigned InstID = CstEnd;
  1094. // Finally, emit all the instructions, in order.
  1095. for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
  1096. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end();
  1097. I != E; ++I) {
  1098. WriteInstruction(*I, InstID, VE, Stream, Vals);
  1099. if (I->getType() != Type::getVoidTy(F.getContext()))
  1100. ++InstID;
  1101. }
  1102. // Emit names for all the instructions etc.
  1103. WriteValueSymbolTable(F.getValueSymbolTable(), VE, Stream);
  1104. WriteMetadataAttachment(F, VE, Stream);
  1105. VE.purgeFunction();
  1106. Stream.ExitBlock();
  1107. }
  1108. /// WriteTypeSymbolTable - Emit a block for the specified type symtab.
  1109. static void WriteTypeSymbolTable(const TypeSymbolTable &TST,
  1110. const ValueEnumerator &VE,
  1111. BitstreamWriter &Stream) {
  1112. if (TST.empty()) return;
  1113. Stream.EnterSubblock(bitc::TYPE_SYMTAB_BLOCK_ID, 3);
  1114. // 7-bit fixed width VST_CODE_ENTRY strings.
  1115. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1116. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
  1117. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  1118. Log2_32_Ceil(VE.getTypes().size()+1)));
  1119. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1120. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  1121. unsigned V7Abbrev = Stream.EmitAbbrev(Abbv);
  1122. SmallVector<unsigned, 64> NameVals;
  1123. for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
  1124. TI != TE; ++TI) {
  1125. // TST_ENTRY: [typeid, namechar x N]
  1126. NameVals.push_back(VE.getTypeID(TI->second));
  1127. const std::string &Str = TI->first;
  1128. bool is7Bit = true;
  1129. for (unsigned i = 0, e = Str.size(); i != e; ++i) {
  1130. NameVals.push_back((unsigned char)Str[i]);
  1131. if (Str[i] & 128)
  1132. is7Bit = false;
  1133. }
  1134. // Emit the finished record.
  1135. Stream.EmitRecord(bitc::VST_CODE_ENTRY, NameVals, is7Bit ? V7Abbrev : 0);
  1136. NameVals.clear();
  1137. }
  1138. Stream.ExitBlock();
  1139. }
  1140. // Emit blockinfo, which defines the standard abbreviations etc.
  1141. static void WriteBlockInfo(const ValueEnumerator &VE, BitstreamWriter &Stream) {
  1142. // We only want to emit block info records for blocks that have multiple
  1143. // instances: CONSTANTS_BLOCK, FUNCTION_BLOCK and VALUE_SYMTAB_BLOCK. Other
  1144. // blocks can defined their abbrevs inline.
  1145. Stream.EnterBlockInfoBlock(2);
  1146. { // 8-bit fixed-width VST_ENTRY/VST_BBENTRY strings.
  1147. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1148. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3));
  1149. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1150. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1151. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8));
  1152. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
  1153. Abbv) != VST_ENTRY_8_ABBREV)
  1154. llvm_unreachable("Unexpected abbrev ordering!");
  1155. }
  1156. { // 7-bit fixed width VST_ENTRY strings.
  1157. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1158. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
  1159. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1160. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1161. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7));
  1162. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
  1163. Abbv) != VST_ENTRY_7_ABBREV)
  1164. llvm_unreachable("Unexpected abbrev ordering!");
  1165. }
  1166. { // 6-bit char6 VST_ENTRY strings.
  1167. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1168. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_ENTRY));
  1169. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1170. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1171. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  1172. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
  1173. Abbv) != VST_ENTRY_6_ABBREV)
  1174. llvm_unreachable("Unexpected abbrev ordering!");
  1175. }
  1176. { // 6-bit char6 VST_BBENTRY strings.
  1177. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1178. Abbv->Add(BitCodeAbbrevOp(bitc::VST_CODE_BBENTRY));
  1179. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1180. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  1181. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Char6));
  1182. if (Stream.EmitBlockInfoAbbrev(bitc::VALUE_SYMTAB_BLOCK_ID,
  1183. Abbv) != VST_BBENTRY_6_ABBREV)
  1184. llvm_unreachable("Unexpected abbrev ordering!");
  1185. }
  1186. { // SETTYPE abbrev for CONSTANTS_BLOCK.
  1187. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1188. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_SETTYPE));
  1189. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed,
  1190. Log2_32_Ceil(VE.getTypes().size()+1)));
  1191. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
  1192. Abbv) != CONSTANTS_SETTYPE_ABBREV)
  1193. llvm_unreachable("Unexpected abbrev ordering!");
  1194. }
  1195. { // INTEGER abbrev for CONSTANTS_BLOCK.
  1196. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1197. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_INTEGER));
  1198. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8));
  1199. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
  1200. Abbv) != CONSTANTS_INTEGER_ABBREV)
  1201. llvm_unreachable("Unexpected abbrev ordering!");
  1202. }
  1203. { // CE_CAST abbrev for CONSTANTS_BLOCK.
  1204. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1205. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_CE_CAST));
  1206. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // cast opc
  1207. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // typeid
  1208. Log2_32_Ceil(VE.getTypes().size()+1)));
  1209. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // value id
  1210. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
  1211. Abbv) != CONSTANTS_CE_CAST_Abbrev)
  1212. llvm_unreachable("Unexpected abbrev ordering!");
  1213. }
  1214. { // NULL abbrev for CONSTANTS_BLOCK.
  1215. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1216. Abbv->Add(BitCodeAbbrevOp(bitc::CST_CODE_NULL));
  1217. if (Stream.EmitBlockInfoAbbrev(bitc::CONSTANTS_BLOCK_ID,
  1218. Abbv) != CONSTANTS_NULL_Abbrev)
  1219. llvm_unreachable("Unexpected abbrev ordering!");
  1220. }
  1221. // FIXME: This should only use space for first class types!
  1222. { // INST_LOAD abbrev for FUNCTION_BLOCK.
  1223. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1224. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_LOAD));
  1225. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Ptr
  1226. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 4)); // Align
  1227. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // volatile
  1228. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1229. Abbv) != FUNCTION_INST_LOAD_ABBREV)
  1230. llvm_unreachable("Unexpected abbrev ordering!");
  1231. }
  1232. { // INST_BINOP abbrev for FUNCTION_BLOCK.
  1233. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1234. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
  1235. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
  1236. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
  1237. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  1238. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1239. Abbv) != FUNCTION_INST_BINOP_ABBREV)
  1240. llvm_unreachable("Unexpected abbrev ordering!");
  1241. }
  1242. { // INST_BINOP_FLAGS abbrev for FUNCTION_BLOCK.
  1243. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1244. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_BINOP));
  1245. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // LHS
  1246. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // RHS
  1247. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  1248. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 7)); // flags
  1249. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1250. Abbv) != FUNCTION_INST_BINOP_FLAGS_ABBREV)
  1251. llvm_unreachable("Unexpected abbrev ordering!");
  1252. }
  1253. { // INST_CAST abbrev for FUNCTION_BLOCK.
  1254. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1255. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_CAST));
  1256. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // OpVal
  1257. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, // dest ty
  1258. Log2_32_Ceil(VE.getTypes().size()+1)));
  1259. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // opc
  1260. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1261. Abbv) != FUNCTION_INST_CAST_ABBREV)
  1262. llvm_unreachable("Unexpected abbrev ordering!");
  1263. }
  1264. { // INST_RET abbrev for FUNCTION_BLOCK.
  1265. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1266. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
  1267. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1268. Abbv) != FUNCTION_INST_RET_VOID_ABBREV)
  1269. llvm_unreachable("Unexpected abbrev ordering!");
  1270. }
  1271. { // INST_RET abbrev for FUNCTION_BLOCK.
  1272. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1273. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_RET));
  1274. Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ValID
  1275. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1276. Abbv) != FUNCTION_INST_RET_VAL_ABBREV)
  1277. llvm_unreachable("Unexpected abbrev ordering!");
  1278. }
  1279. { // INST_UNREACHABLE abbrev for FUNCTION_BLOCK.
  1280. BitCodeAbbrev *Abbv = new BitCodeAbbrev();
  1281. Abbv->Add(BitCodeAbbrevOp(bitc::FUNC_CODE_INST_UNREACHABLE));
  1282. if (Stream.EmitBlockInfoAbbrev(bitc::FUNCTION_BLOCK_ID,
  1283. Abbv) != FUNCTION_INST_UNREACHABLE_ABBREV)
  1284. llvm_unreachable("Unexpected abbrev ordering!");
  1285. }
  1286. Stream.ExitBlock();
  1287. }
  1288. /// WriteModule - Emit the specified module to the bitstream.
  1289. static void WriteModule(const Module *M, BitstreamWriter &Stream) {
  1290. Stream.EnterSubblock(bitc::MODULE_BLOCK_ID, 3);
  1291. // Emit the version number if it is non-zero.
  1292. if (CurVersion) {
  1293. SmallVector<unsigned, 1> Vals;
  1294. Vals.push_back(CurVersion);
  1295. Stream.EmitRecord(bitc::MODULE_CODE_VERSION, Vals);
  1296. }
  1297. // Analyze the module, enumerating globals, functions, etc.
  1298. ValueEnumerator VE(M);
  1299. // Emit blockinfo, which defines the standard abbreviations etc.
  1300. WriteBlockInfo(VE, Stream);
  1301. // Emit information about parameter attributes.
  1302. WriteAttributeTable(VE, Stream);
  1303. // Emit information describing all of the types in the module.
  1304. WriteTypeTable(VE, Stream);
  1305. // Emit top-level description of module, including target triple, inline asm,
  1306. // descriptors for global variables, and function prototype info.
  1307. WriteModuleInfo(M, VE, Stream);
  1308. // Emit constants.
  1309. WriteModuleConstants(VE, Stream);
  1310. // Emit metadata.
  1311. WriteModuleMetadata(VE, Stream);
  1312. // Emit function bodies.
  1313. for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
  1314. if (!I->isDeclaration())
  1315. WriteFunction(*I, VE, Stream);
  1316. // Emit metadata.
  1317. WriteModuleMetadataStore(M, VE, Stream);
  1318. // Emit the type symbol table information.
  1319. WriteTypeSymbolTable(M->getTypeSymbolTable(), VE, Stream);
  1320. // Emit names for globals/functions etc.
  1321. WriteValueSymbolTable(M->getValueSymbolTable(), VE, Stream);
  1322. Stream.ExitBlock();
  1323. }
  1324. /// EmitDarwinBCHeader - If generating a bc file on darwin, we have to emit a
  1325. /// header and trailer to make it compatible with the system archiver. To do
  1326. /// this we emit the following header, and then emit a trailer that pads the
  1327. /// file out to be a multiple of 16 bytes.
  1328. ///
  1329. /// struct bc_header {
  1330. /// uint32_t Magic; // 0x0B17C0DE
  1331. /// uint32_t Version; // Version, currently always 0.
  1332. /// uint32_t BitcodeOffset; // Offset to traditional bitcode file.
  1333. /// uint32_t BitcodeSize; // Size of traditional bitcode file.
  1334. /// uint32_t CPUType; // CPU specifier.
  1335. /// ... potentially more later ...
  1336. /// };
  1337. enum {
  1338. DarwinBCSizeFieldOffset = 3*4, // Offset to bitcode_size.
  1339. DarwinBCHeaderSize = 5*4
  1340. };
  1341. static void EmitDarwinBCHeader(BitstreamWriter &Stream,
  1342. const std::string &TT) {
  1343. unsigned CPUType = ~0U;
  1344. // Match x86_64-*, i[3-9]86-*, powerpc-*, powerpc64-*. The CPUType is a
  1345. // magic number from /usr/include/mach/machine.h. It is ok to reproduce the
  1346. // specific constants here because they are implicitly part of the Darwin ABI.
  1347. enum {
  1348. DARWIN_CPU_ARCH_ABI64 = 0x01000000,
  1349. DARWIN_CPU_TYPE_X86 = 7,
  1350. DARWIN_CPU_TYPE_POWERPC = 18
  1351. };
  1352. if (TT.find("x86_64-") == 0)
  1353. CPUType = DARWIN_CPU_TYPE_X86 | DARWIN_CPU_ARCH_ABI64;
  1354. else if (TT.size() >= 5 && TT[0] == 'i' && TT[2] == '8' && TT[3] == '6' &&
  1355. TT[4] == '-' && TT[1] - '3' < 6)
  1356. CPUType = DARWIN_CPU_TYPE_X86;
  1357. else if (TT.find("powerpc-") == 0)
  1358. CPUType = DARWIN_CPU_TYPE_POWERPC;
  1359. else if (TT.find("powerpc64-") == 0)
  1360. CPUType = DARWIN_CPU_TYPE_POWERPC | DARWIN_CPU_ARCH_ABI64;
  1361. // Traditional Bitcode starts after header.
  1362. unsigned BCOffset = DarwinBCHeaderSize;
  1363. Stream.Emit(0x0B17C0DE, 32);
  1364. Stream.Emit(0 , 32); // Version.
  1365. Stream.Emit(BCOffset , 32);
  1366. Stream.Emit(0 , 32); // Filled in later.
  1367. Stream.Emit(CPUType , 32);
  1368. }
  1369. /// EmitDarwinBCTrailer - Emit the darwin epilog after the bitcode file and
  1370. /// finalize the header.
  1371. static void EmitDarwinBCTrailer(BitstreamWriter &Stream, unsigned BufferSize) {
  1372. // Update the size field in the header.
  1373. Stream.BackpatchWord(DarwinBCSizeFieldOffset, BufferSize-DarwinBCHeaderSize);
  1374. // If the file is not a multiple of 16 bytes, insert dummy padding.
  1375. while (BufferSize & 15) {
  1376. Stream.Emit(0, 8);
  1377. ++BufferSize;
  1378. }
  1379. }
  1380. /// WriteBitcodeToFile - Write the specified module to the specified output
  1381. /// stream.
  1382. void llvm::WriteBitcodeToFile(const Module *M, raw_ostream &Out) {
  1383. std::vector<unsigned char> Buffer;
  1384. BitstreamWriter Stream(Buffer);
  1385. Buffer.reserve(256*1024);
  1386. WriteBitcodeToStream( M, Stream );
  1387. // If writing to stdout, set binary mode.
  1388. if (&llvm::outs() == &Out)
  1389. sys::Program::ChangeStdoutToBinary();
  1390. // Write the generated bitstream to "Out".
  1391. Out.write((char*)&Buffer.front(), Buffer.size());
  1392. // Make sure it hits disk now.
  1393. Out.flush();
  1394. }
  1395. /// WriteBitcodeToStream - Write the specified module to the specified output
  1396. /// stream.
  1397. void llvm::WriteBitcodeToStream(const Module *M, BitstreamWriter &Stream) {
  1398. // If this is darwin, emit a file header and trailer if needed.
  1399. bool isDarwin = M->getTargetTriple().find("-darwin") != std::string::npos;
  1400. if (isDarwin)
  1401. EmitDarwinBCHeader(Stream, M->getTargetTriple());
  1402. // Emit the file header.
  1403. Stream.Emit((unsigned)'B', 8);
  1404. Stream.Emit((unsigned)'C', 8);
  1405. Stream.Emit(0x0, 4);
  1406. Stream.Emit(0xC, 4);
  1407. Stream.Emit(0xE, 4);
  1408. Stream.Emit(0xD, 4);
  1409. // Emit the module.
  1410. WriteModule(M, Stream);
  1411. if (isDarwin)
  1412. EmitDarwinBCTrailer(Stream, Stream.getBuffer().size());
  1413. }