BitcodeWriter.cpp 76 KB

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