Serializer no longer automatically emits a root-level block in the bitstream.
[oota-llvm.git] / lib / Bitcode / Writer / Serialize.cpp
1 //==- Serialize.cpp - Generic Object Serialization to Bitcode ----*- C++ -*-==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Ted Kremenek and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the internal methods used for object serialization.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Bitcode/Serialize.h"
15 #include "string.h"
16
17 using namespace llvm;
18
19 Serializer::Serializer(BitstreamWriter& stream)
20   : Stream(stream), BlockLevel(0) {}
21
22 Serializer::~Serializer() {
23   if (inRecord())
24     EmitRecord();
25
26   while (BlockLevel > 0)
27     Stream.ExitBlock();
28    
29   Stream.FlushToWord();
30 }
31
32 void Serializer::EmitRecord() {
33   assert(Record.size() > 0 && "Cannot emit empty record.");
34   Stream.EmitRecord(8,Record);
35   Record.clear();
36 }
37
38 void Serializer::EnterBlock(unsigned BlockID,unsigned CodeLen) {
39   FlushRecord();
40   Stream.EnterSubblock(BlockID,CodeLen);
41   ++BlockLevel;
42 }
43
44 void Serializer::ExitBlock() {
45   assert (BlockLevel > 0);
46   --BlockLevel;
47   FlushRecord();
48   Stream.ExitBlock();
49 }
50
51 void Serializer::EmitInt(unsigned X) {
52   assert (BlockLevel > 0);
53   Record.push_back(X);
54 }
55
56 void Serializer::EmitCStr(const char* s, const char* end) {
57   Record.push_back(end - s);
58   
59   while(s != end) {
60     Record.push_back(*s);
61     ++s;
62   }
63
64   EmitRecord();
65 }
66
67 void Serializer::EmitCStr(const char* s) {
68   EmitCStr(s,s+strlen(s));
69 }
70
71 unsigned Serializer::getPtrId(const void* ptr) {
72   if (!ptr)
73     return 0;
74   
75   MapTy::iterator I = PtrMap.find(ptr);
76   
77   if (I == PtrMap.end()) {
78     unsigned id = PtrMap.size()+1;
79     PtrMap[ptr] = id;
80     return id;
81   }
82   else return I->second;
83 }
84
85
86 #define INT_EMIT(TYPE)\
87 void SerializeTrait<TYPE>::Emit(Serializer&S, TYPE X) { S.EmitInt(X); }
88
89 INT_EMIT(bool)
90 INT_EMIT(unsigned char)
91 INT_EMIT(unsigned short)
92 INT_EMIT(unsigned int)
93 INT_EMIT(unsigned long)