BitcodeWriter.cpp 74 KB

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