58baf104c7a0299abc2e950ea0e983aa2b9df783
[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, unsigned BlockID)
20   : Stream(stream), inBlock(BlockID >= 8) {
21     
22   if (inBlock) Stream.EnterSubblock(8,3);
23 }
24
25 Serializer::~Serializer() {
26   if (inRecord())
27     EmitRecord();
28
29   if (inBlock)
30     Stream.ExitBlock();
31   
32   Stream.FlushToWord();
33 }
34
35 void Serializer::EmitRecord() {
36   assert(Record.size() > 0 && "Cannot emit empty record.");
37   Stream.EmitRecord(8,Record);
38   Record.clear();
39 }
40
41 void Serializer::EmitInt(unsigned X) {
42   Record.push_back(X);
43 }
44
45 void Serializer::EmitCStr(const char* s, const char* end) {
46   Record.push_back(end - s);
47   
48   while(s != end) {
49     Record.push_back(*s);
50     ++s;
51   }
52
53   EmitRecord();
54 }
55
56 void Serializer::EmitCStr(const char* s) {
57   EmitCStr(s,s+strlen(s));
58 }
59
60 unsigned Serializer::getPtrId(const void* ptr) {
61   if (!ptr)
62     return 0;
63   
64   MapTy::iterator I = PtrMap.find(ptr);
65   
66   if (I == PtrMap.end()) {
67     unsigned id = PtrMap.size()+1;
68     PtrMap[ptr] = id;
69     return id;
70   }
71   else return I->second;
72 }
73
74 #define INT_EMIT(TYPE)\
75 void SerializeTrait<TYPE>::Emit(Serializer&S, TYPE X) { S.EmitInt(X); }
76
77 INT_EMIT(bool)
78 INT_EMIT(unsigned char)
79 INT_EMIT(unsigned short)
80 INT_EMIT(unsigned int)
81 INT_EMIT(unsigned long)