LLVM API Documentation

StringTableBuilder.cpp
Go to the documentation of this file.
00001 //===-- StringTableBuilder.cpp - String table building utility ------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "llvm/MC/StringTableBuilder.h"
00011 #include "llvm/ADT/SmallVector.h"
00012 
00013 using namespace llvm;
00014 
00015 static bool compareBySuffix(StringRef a, StringRef b) {
00016   size_t sizeA = a.size();
00017   size_t sizeB = b.size();
00018   size_t len = std::min(sizeA, sizeB);
00019   for (size_t i = 0; i < len; ++i) {
00020     char ca = a[sizeA - i - 1];
00021     char cb = b[sizeB - i - 1];
00022     if (ca != cb)
00023       return ca > cb;
00024   }
00025   return sizeA > sizeB;
00026 }
00027 
00028 void StringTableBuilder::finalize() {
00029   SmallVector<StringRef, 8> Strings;
00030   for (auto i = StringIndexMap.begin(), e = StringIndexMap.end(); i != e; ++i)
00031     Strings.push_back(i->getKey());
00032 
00033   std::sort(Strings.begin(), Strings.end(), compareBySuffix);
00034 
00035   // FIXME: Starting with a null byte is ELF specific. Generalize this so we
00036   // can use the class with other object formats.
00037   StringTable += '\x00';
00038 
00039   StringRef Previous;
00040   for (StringRef s : Strings) {
00041     if (Previous.endswith(s)) {
00042       StringIndexMap[s] = StringTable.size() - 1 - s.size();
00043       continue;
00044     }
00045 
00046     StringIndexMap[s] = StringTable.size();
00047     StringTable += s;
00048     StringTable += '\x00';
00049     Previous = s;
00050   }
00051 }