BitcodeWriter.cpp 54 KB

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