Merge branch 'master' into msp430
[llvm/msp430.git] / lib / Bitcode / Writer / Serialize.cpp
blob79464a61be46ae0dde61331cc794f9e112b1d04a
1 //==- Serialize.cpp - Generic Object Serialization to Bitcode ----*- C++ -*-==//
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 // This file defines the internal methods used for object serialization.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Bitcode/Serialize.h"
15 #include "string.h"
17 #ifdef DEBUG_BACKPATCH
18 #include "llvm/Support/Streams.h"
19 #endif
21 using namespace llvm;
23 Serializer::Serializer(BitstreamWriter& stream)
24 : Stream(stream), BlockLevel(0) {}
26 Serializer::~Serializer() {
27 if (inRecord())
28 EmitRecord();
30 while (BlockLevel > 0)
31 Stream.ExitBlock();
33 Stream.FlushToWord();
36 void Serializer::EmitRecord() {
37 assert(Record.size() > 0 && "Cannot emit empty record.");
38 Stream.EmitRecord(8,Record);
39 Record.clear();
42 void Serializer::EnterBlock(unsigned BlockID,unsigned CodeLen) {
43 FlushRecord();
44 Stream.EnterSubblock(BlockID,CodeLen);
45 ++BlockLevel;
48 void Serializer::ExitBlock() {
49 assert (BlockLevel > 0);
50 --BlockLevel;
51 FlushRecord();
52 Stream.ExitBlock();
55 void Serializer::EmitInt(uint64_t X) {
56 assert (BlockLevel > 0);
57 Record.push_back(X);
60 void Serializer::EmitSInt(int64_t X) {
61 if (X >= 0)
62 EmitInt(X << 1);
63 else
64 EmitInt((-X << 1) | 1);
67 void Serializer::EmitCStr(const char* s, const char* end) {
68 Record.push_back(end - s);
70 while(s != end) {
71 Record.push_back(*s);
72 ++s;
76 void Serializer::EmitCStr(const char* s) {
77 EmitCStr(s,s+strlen(s));
80 SerializedPtrID Serializer::getPtrId(const void* ptr) {
81 if (!ptr)
82 return 0;
84 MapTy::iterator I = PtrMap.find(ptr);
86 if (I == PtrMap.end()) {
87 unsigned id = PtrMap.size()+1;
88 #ifdef DEBUG_BACKPATCH
89 llvm::cerr << "Registered PTR: " << ptr << " => " << id << "\n";
90 #endif
91 PtrMap[ptr] = id;
92 return id;
94 else return I->second;
97 bool Serializer::isRegistered(const void* ptr) const {
98 MapTy::const_iterator I = PtrMap.find(ptr);
99 return I != PtrMap.end();
103 #define INT_EMIT(TYPE)\
104 void SerializeTrait<TYPE>::Emit(Serializer&S, TYPE X) { S.EmitInt(X); }
106 INT_EMIT(bool)
107 INT_EMIT(unsigned char)
108 INT_EMIT(unsigned short)
109 INT_EMIT(unsigned int)
110 INT_EMIT(unsigned long)
112 #define SINT_EMIT(TYPE)\
113 void SerializeTrait<TYPE>::Emit(Serializer&S, TYPE X) { S.EmitSInt(X); }
115 SINT_EMIT(signed char)
116 SINT_EMIT(signed short)
117 SINT_EMIT(signed int)
118 SINT_EMIT(signed long)