BitcodeWriter.cpp 64 KB

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