LLVM API Documentation

Twine.h
Go to the documentation of this file.
00001 //===-- Twine.h - Fast Temporary String Concatenation -----------*- C++ -*-===//
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 #ifndef LLVM_ADT_TWINE_H
00011 #define LLVM_ADT_TWINE_H
00012 
00013 #include "llvm/ADT/StringRef.h"
00014 #include "llvm/Support/DataTypes.h"
00015 #include "llvm/Support/ErrorHandling.h"
00016 #include <cassert>
00017 #include <string>
00018 
00019 namespace llvm {
00020   template <typename T>
00021   class SmallVectorImpl;
00022   class StringRef;
00023   class raw_ostream;
00024 
00025   /// Twine - A lightweight data structure for efficiently representing the
00026   /// concatenation of temporary values as strings.
00027   ///
00028   /// A Twine is a kind of rope, it represents a concatenated string using a
00029   /// binary-tree, where the string is the preorder of the nodes. Since the
00030   /// Twine can be efficiently rendered into a buffer when its result is used,
00031   /// it avoids the cost of generating temporary values for intermediate string
00032   /// results -- particularly in cases when the Twine result is never
00033   /// required. By explicitly tracking the type of leaf nodes, we can also avoid
00034   /// the creation of temporary strings for conversions operations (such as
00035   /// appending an integer to a string).
00036   ///
00037   /// A Twine is not intended for use directly and should not be stored, its
00038   /// implementation relies on the ability to store pointers to temporary stack
00039   /// objects which may be deallocated at the end of a statement. Twines should
00040   /// only be used accepted as const references in arguments, when an API wishes
00041   /// to accept possibly-concatenated strings.
00042   ///
00043   /// Twines support a special 'null' value, which always concatenates to form
00044   /// itself, and renders as an empty string. This can be returned from APIs to
00045   /// effectively nullify any concatenations performed on the result.
00046   ///
00047   /// \b Implementation
00048   ///
00049   /// Given the nature of a Twine, it is not possible for the Twine's
00050   /// concatenation method to construct interior nodes; the result must be
00051   /// represented inside the returned value. For this reason a Twine object
00052   /// actually holds two values, the left- and right-hand sides of a
00053   /// concatenation. We also have nullary Twine objects, which are effectively
00054   /// sentinel values that represent empty strings.
00055   ///
00056   /// Thus, a Twine can effectively have zero, one, or two children. The \see
00057   /// isNullary(), \see isUnary(), and \see isBinary() predicates exist for
00058   /// testing the number of children.
00059   ///
00060   /// We maintain a number of invariants on Twine objects (FIXME: Why):
00061   ///  - Nullary twines are always represented with their Kind on the left-hand
00062   ///    side, and the Empty kind on the right-hand side.
00063   ///  - Unary twines are always represented with the value on the left-hand
00064   ///    side, and the Empty kind on the right-hand side.
00065   ///  - If a Twine has another Twine as a child, that child should always be
00066   ///    binary (otherwise it could have been folded into the parent).
00067   ///
00068   /// These invariants are check by \see isValid().
00069   ///
00070   /// \b Efficiency Considerations
00071   ///
00072   /// The Twine is designed to yield efficient and small code for common
00073   /// situations. For this reason, the concat() method is inlined so that
00074   /// concatenations of leaf nodes can be optimized into stores directly into a
00075   /// single stack allocated object.
00076   ///
00077   /// In practice, not all compilers can be trusted to optimize concat() fully,
00078   /// so we provide two additional methods (and accompanying operator+
00079   /// overloads) to guarantee that particularly important cases (cstring plus
00080   /// StringRef) codegen as desired.
00081   class Twine {
00082     /// NodeKind - Represent the type of an argument.
00083     enum NodeKind : unsigned char {
00084       /// An empty string; the result of concatenating anything with it is also
00085       /// empty.
00086       NullKind,
00087 
00088       /// The empty string.
00089       EmptyKind,
00090 
00091       /// A pointer to a Twine instance.
00092       TwineKind,
00093 
00094       /// A pointer to a C string instance.
00095       CStringKind,
00096 
00097       /// A pointer to an std::string instance.
00098       StdStringKind,
00099 
00100       /// A pointer to a StringRef instance.
00101       StringRefKind,
00102 
00103       /// A char value reinterpreted as a pointer, to render as a character.
00104       CharKind,
00105 
00106       /// An unsigned int value reinterpreted as a pointer, to render as an
00107       /// unsigned decimal integer.
00108       DecUIKind,
00109 
00110       /// An int value reinterpreted as a pointer, to render as a signed
00111       /// decimal integer.
00112       DecIKind,
00113 
00114       /// A pointer to an unsigned long value, to render as an unsigned decimal
00115       /// integer.
00116       DecULKind,
00117 
00118       /// A pointer to a long value, to render as a signed decimal integer.
00119       DecLKind,
00120 
00121       /// A pointer to an unsigned long long value, to render as an unsigned
00122       /// decimal integer.
00123       DecULLKind,
00124 
00125       /// A pointer to a long long value, to render as a signed decimal integer.
00126       DecLLKind,
00127 
00128       /// A pointer to a uint64_t value, to render as an unsigned hexadecimal
00129       /// integer.
00130       UHexKind
00131     };
00132 
00133     union Child
00134     {
00135       const Twine *twine;
00136       const char *cString;
00137       const std::string *stdString;
00138       const StringRef *stringRef;
00139       char character;
00140       unsigned int decUI;
00141       int decI;
00142       const unsigned long *decUL;
00143       const long *decL;
00144       const unsigned long long *decULL;
00145       const long long *decLL;
00146       const uint64_t *uHex;
00147     };
00148 
00149   private:
00150     /// LHS - The prefix in the concatenation, which may be uninitialized for
00151     /// Null or Empty kinds.
00152     Child LHS;
00153     /// RHS - The suffix in the concatenation, which may be uninitialized for
00154     /// Null or Empty kinds.
00155     Child RHS;
00156     /// LHSKind - The NodeKind of the left hand side, \see getLHSKind().
00157     NodeKind LHSKind;
00158     /// RHSKind - The NodeKind of the right hand side, \see getRHSKind().
00159     NodeKind RHSKind;
00160 
00161   private:
00162     /// Construct a nullary twine; the kind must be NullKind or EmptyKind.
00163     explicit Twine(NodeKind Kind)
00164       : LHSKind(Kind), RHSKind(EmptyKind) {
00165       assert(isNullary() && "Invalid kind!");
00166     }
00167 
00168     /// Construct a binary twine.
00169     explicit Twine(const Twine &_LHS, const Twine &_RHS)
00170       : LHSKind(TwineKind), RHSKind(TwineKind) {
00171       LHS.twine = &_LHS;
00172       RHS.twine = &_RHS;
00173       assert(isValid() && "Invalid twine!");
00174     }
00175 
00176     /// Construct a twine from explicit values.
00177     explicit Twine(Child _LHS, NodeKind _LHSKind,
00178                    Child _RHS, NodeKind _RHSKind)
00179       : LHS(_LHS), RHS(_RHS), LHSKind(_LHSKind), RHSKind(_RHSKind) {
00180       assert(isValid() && "Invalid twine!");
00181     }
00182 
00183     /// Since the intended use of twines is as temporary objects, assignments
00184     /// when concatenating might cause undefined behavior or stack corruptions
00185     Twine &operator=(const Twine &Other) LLVM_DELETED_FUNCTION;
00186 
00187     /// isNull - Check for the null twine.
00188     bool isNull() const {
00189       return getLHSKind() == NullKind;
00190     }
00191 
00192     /// isEmpty - Check for the empty twine.
00193     bool isEmpty() const {
00194       return getLHSKind() == EmptyKind;
00195     }
00196 
00197     /// isNullary - Check if this is a nullary twine (null or empty).
00198     bool isNullary() const {
00199       return isNull() || isEmpty();
00200     }
00201 
00202     /// isUnary - Check if this is a unary twine.
00203     bool isUnary() const {
00204       return getRHSKind() == EmptyKind && !isNullary();
00205     }
00206 
00207     /// isBinary - Check if this is a binary twine.
00208     bool isBinary() const {
00209       return getLHSKind() != NullKind && getRHSKind() != EmptyKind;
00210     }
00211 
00212     /// isValid - Check if this is a valid twine (satisfying the invariants on
00213     /// order and number of arguments).
00214     bool isValid() const {
00215       // Nullary twines always have Empty on the RHS.
00216       if (isNullary() && getRHSKind() != EmptyKind)
00217         return false;
00218 
00219       // Null should never appear on the RHS.
00220       if (getRHSKind() == NullKind)
00221         return false;
00222 
00223       // The RHS cannot be non-empty if the LHS is empty.
00224       if (getRHSKind() != EmptyKind && getLHSKind() == EmptyKind)
00225         return false;
00226 
00227       // A twine child should always be binary.
00228       if (getLHSKind() == TwineKind &&
00229           !LHS.twine->isBinary())
00230         return false;
00231       if (getRHSKind() == TwineKind &&
00232           !RHS.twine->isBinary())
00233         return false;
00234 
00235       return true;
00236     }
00237 
00238     /// getLHSKind - Get the NodeKind of the left-hand side.
00239     NodeKind getLHSKind() const { return LHSKind; }
00240 
00241     /// getRHSKind - Get the NodeKind of the right-hand side.
00242     NodeKind getRHSKind() const { return RHSKind; }
00243 
00244     /// printOneChild - Print one child from a twine.
00245     void printOneChild(raw_ostream &OS, Child Ptr, NodeKind Kind) const;
00246 
00247     /// printOneChildRepr - Print the representation of one child from a twine.
00248     void printOneChildRepr(raw_ostream &OS, Child Ptr,
00249                            NodeKind Kind) const;
00250 
00251   public:
00252     /// @name Constructors
00253     /// @{
00254 
00255     /// Construct from an empty string.
00256     /*implicit*/ Twine() : LHSKind(EmptyKind), RHSKind(EmptyKind) {
00257       assert(isValid() && "Invalid twine!");
00258     }
00259 
00260     /// Construct from a C string.
00261     ///
00262     /// We take care here to optimize "" into the empty twine -- this will be
00263     /// optimized out for string constants. This allows Twine arguments have
00264     /// default "" values, without introducing unnecessary string constants.
00265     /*implicit*/ Twine(const char *Str)
00266       : RHSKind(EmptyKind) {
00267       if (Str[0] != '\0') {
00268         LHS.cString = Str;
00269         LHSKind = CStringKind;
00270       } else
00271         LHSKind = EmptyKind;
00272 
00273       assert(isValid() && "Invalid twine!");
00274     }
00275 
00276     /// Construct from an std::string.
00277     /*implicit*/ Twine(const std::string &Str)
00278       : LHSKind(StdStringKind), RHSKind(EmptyKind) {
00279       LHS.stdString = &Str;
00280       assert(isValid() && "Invalid twine!");
00281     }
00282 
00283     /// Construct from a StringRef.
00284     /*implicit*/ Twine(const StringRef &Str)
00285       : LHSKind(StringRefKind), RHSKind(EmptyKind) {
00286       LHS.stringRef = &Str;
00287       assert(isValid() && "Invalid twine!");
00288     }
00289 
00290     /// Construct from a char.
00291     explicit Twine(char Val)
00292       : LHSKind(CharKind), RHSKind(EmptyKind) {
00293       LHS.character = Val;
00294     }
00295 
00296     /// Construct from a signed char.
00297     explicit Twine(signed char Val)
00298       : LHSKind(CharKind), RHSKind(EmptyKind) {
00299       LHS.character = static_cast<char>(Val);
00300     }
00301 
00302     /// Construct from an unsigned char.
00303     explicit Twine(unsigned char Val)
00304       : LHSKind(CharKind), RHSKind(EmptyKind) {
00305       LHS.character = static_cast<char>(Val);
00306     }
00307 
00308     /// Construct a twine to print \p Val as an unsigned decimal integer.
00309     explicit Twine(unsigned Val)
00310       : LHSKind(DecUIKind), RHSKind(EmptyKind) {
00311       LHS.decUI = Val;
00312     }
00313 
00314     /// Construct a twine to print \p Val as a signed decimal integer.
00315     explicit Twine(int Val)
00316       : LHSKind(DecIKind), RHSKind(EmptyKind) {
00317       LHS.decI = Val;
00318     }
00319 
00320     /// Construct a twine to print \p Val as an unsigned decimal integer.
00321     explicit Twine(const unsigned long &Val)
00322       : LHSKind(DecULKind), RHSKind(EmptyKind) {
00323       LHS.decUL = &Val;
00324     }
00325 
00326     /// Construct a twine to print \p Val as a signed decimal integer.
00327     explicit Twine(const long &Val)
00328       : LHSKind(DecLKind), RHSKind(EmptyKind) {
00329       LHS.decL = &Val;
00330     }
00331 
00332     /// Construct a twine to print \p Val as an unsigned decimal integer.
00333     explicit Twine(const unsigned long long &Val)
00334       : LHSKind(DecULLKind), RHSKind(EmptyKind) {
00335       LHS.decULL = &Val;
00336     }
00337 
00338     /// Construct a twine to print \p Val as a signed decimal integer.
00339     explicit Twine(const long long &Val)
00340       : LHSKind(DecLLKind), RHSKind(EmptyKind) {
00341       LHS.decLL = &Val;
00342     }
00343 
00344     // FIXME: Unfortunately, to make sure this is as efficient as possible we
00345     // need extra binary constructors from particular types. We can't rely on
00346     // the compiler to be smart enough to fold operator+()/concat() down to the
00347     // right thing. Yet.
00348 
00349     /// Construct as the concatenation of a C string and a StringRef.
00350     /*implicit*/ Twine(const char *_LHS, const StringRef &_RHS)
00351       : LHSKind(CStringKind), RHSKind(StringRefKind) {
00352       LHS.cString = _LHS;
00353       RHS.stringRef = &_RHS;
00354       assert(isValid() && "Invalid twine!");
00355     }
00356 
00357     /// Construct as the concatenation of a StringRef and a C string.
00358     /*implicit*/ Twine(const StringRef &_LHS, const char *_RHS)
00359       : LHSKind(StringRefKind), RHSKind(CStringKind) {
00360       LHS.stringRef = &_LHS;
00361       RHS.cString = _RHS;
00362       assert(isValid() && "Invalid twine!");
00363     }
00364 
00365     /// Create a 'null' string, which is an empty string that always
00366     /// concatenates to form another empty string.
00367     static Twine createNull() {
00368       return Twine(NullKind);
00369     }
00370 
00371     /// @}
00372     /// @name Numeric Conversions
00373     /// @{
00374 
00375     // Construct a twine to print \p Val as an unsigned hexadecimal integer.
00376     static Twine utohexstr(const uint64_t &Val) {
00377       Child LHS, RHS;
00378       LHS.uHex = &Val;
00379       RHS.twine = nullptr;
00380       return Twine(LHS, UHexKind, RHS, EmptyKind);
00381     }
00382 
00383     /// @}
00384     /// @name Predicate Operations
00385     /// @{
00386 
00387     /// isTriviallyEmpty - Check if this twine is trivially empty; a false
00388     /// return value does not necessarily mean the twine is empty.
00389     bool isTriviallyEmpty() const {
00390       return isNullary();
00391     }
00392 
00393     /// isSingleStringRef - Return true if this twine can be dynamically
00394     /// accessed as a single StringRef value with getSingleStringRef().
00395     bool isSingleStringRef() const {
00396       if (getRHSKind() != EmptyKind) return false;
00397 
00398       switch (getLHSKind()) {
00399       case EmptyKind:
00400       case CStringKind:
00401       case StdStringKind:
00402       case StringRefKind:
00403         return true;
00404       default:
00405         return false;
00406       }
00407     }
00408 
00409     /// @}
00410     /// @name String Operations
00411     /// @{
00412 
00413     Twine concat(const Twine &Suffix) const;
00414 
00415     /// @}
00416     /// @name Output & Conversion.
00417     /// @{
00418 
00419     /// str - Return the twine contents as a std::string.
00420     std::string str() const;
00421 
00422     /// toVector - Write the concatenated string into the given SmallString or
00423     /// SmallVector.
00424     void toVector(SmallVectorImpl<char> &Out) const;
00425 
00426     /// getSingleStringRef - This returns the twine as a single StringRef.  This
00427     /// method is only valid if isSingleStringRef() is true.
00428     StringRef getSingleStringRef() const {
00429       assert(isSingleStringRef() &&"This cannot be had as a single stringref!");
00430       switch (getLHSKind()) {
00431       default: llvm_unreachable("Out of sync with isSingleStringRef");
00432       case EmptyKind:      return StringRef();
00433       case CStringKind:    return StringRef(LHS.cString);
00434       case StdStringKind:  return StringRef(*LHS.stdString);
00435       case StringRefKind:  return *LHS.stringRef;
00436       }
00437     }
00438 
00439     /// toStringRef - This returns the twine as a single StringRef if it can be
00440     /// represented as such. Otherwise the twine is written into the given
00441     /// SmallVector and a StringRef to the SmallVector's data is returned.
00442     StringRef toStringRef(SmallVectorImpl<char> &Out) const;
00443 
00444     /// toNullTerminatedStringRef - This returns the twine as a single null
00445     /// terminated StringRef if it can be represented as such. Otherwise the
00446     /// twine is written into the given SmallVector and a StringRef to the
00447     /// SmallVector's data is returned.
00448     ///
00449     /// The returned StringRef's size does not include the null terminator.
00450     StringRef toNullTerminatedStringRef(SmallVectorImpl<char> &Out) const;
00451 
00452     /// Write the concatenated string represented by this twine to the
00453     /// stream \p OS.
00454     void print(raw_ostream &OS) const;
00455 
00456     /// Dump the concatenated string represented by this twine to stderr.
00457     void dump() const;
00458 
00459     /// Write the representation of this twine to the stream \p OS.
00460     void printRepr(raw_ostream &OS) const;
00461 
00462     /// Dump the representation of this twine to stderr.
00463     void dumpRepr() const;
00464 
00465     /// @}
00466   };
00467 
00468   /// @name Twine Inline Implementations
00469   /// @{
00470 
00471   inline Twine Twine::concat(const Twine &Suffix) const {
00472     // Concatenation with null is null.
00473     if (isNull() || Suffix.isNull())
00474       return Twine(NullKind);
00475 
00476     // Concatenation with empty yields the other side.
00477     if (isEmpty())
00478       return Suffix;
00479     if (Suffix.isEmpty())
00480       return *this;
00481 
00482     // Otherwise we need to create a new node, taking care to fold in unary
00483     // twines.
00484     Child NewLHS, NewRHS;
00485     NewLHS.twine = this;
00486     NewRHS.twine = &Suffix;
00487     NodeKind NewLHSKind = TwineKind, NewRHSKind = TwineKind;
00488     if (isUnary()) {
00489       NewLHS = LHS;
00490       NewLHSKind = getLHSKind();
00491     }
00492     if (Suffix.isUnary()) {
00493       NewRHS = Suffix.LHS;
00494       NewRHSKind = Suffix.getLHSKind();
00495     }
00496 
00497     return Twine(NewLHS, NewLHSKind, NewRHS, NewRHSKind);
00498   }
00499 
00500   inline Twine operator+(const Twine &LHS, const Twine &RHS) {
00501     return LHS.concat(RHS);
00502   }
00503 
00504   /// Additional overload to guarantee simplified codegen; this is equivalent to
00505   /// concat().
00506 
00507   inline Twine operator+(const char *LHS, const StringRef &RHS) {
00508     return Twine(LHS, RHS);
00509   }
00510 
00511   /// Additional overload to guarantee simplified codegen; this is equivalent to
00512   /// concat().
00513 
00514   inline Twine operator+(const StringRef &LHS, const char *RHS) {
00515     return Twine(LHS, RHS);
00516   }
00517 
00518   inline raw_ostream &operator<<(raw_ostream &OS, const Twine &RHS) {
00519     RHS.print(OS);
00520     return OS;
00521   }
00522 
00523   /// @}
00524 }
00525 
00526 #endif