BitcodeWriter.cpp 59 KB

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