diff options
Diffstat (limited to 'include/llvm/Support')
34 files changed, 758 insertions, 968 deletions
diff --git a/include/llvm/Support/BlockFrequency.h b/include/llvm/Support/BlockFrequency.h index 839cf93..666b3c8 100644 --- a/include/llvm/Support/BlockFrequency.h +++ b/include/llvm/Support/BlockFrequency.h @@ -25,17 +25,35 @@ class BranchProbability; class BlockFrequency { uint64_t Frequency; - static const int64_t ENTRY_FREQ = 1024; + static const int64_t ENTRY_FREQ = 1 << 14; + + // Scale frequency by N/D, saturating on overflow. + void scale(uint32_t N, uint32_t D); public: BlockFrequency(uint64_t Freq = 0) : Frequency(Freq) { } + /// \brief Returns the frequency of the entry block of the function. static uint64_t getEntryFrequency() { return ENTRY_FREQ; } + + /// \brief Returns the maximum possible frequency, the saturation value. + static uint64_t getMaxFrequency() { return -1ULL; } + + /// \brief Returns the frequency as a fixpoint number scaled by the entry + /// frequency. uint64_t getFrequency() const { return Frequency; } + /// \brief Multiplies with a branch probability. The computation will never + /// overflow. BlockFrequency &operator*=(const BranchProbability &Prob); const BlockFrequency operator*(const BranchProbability &Prob) const; + /// \brief Divide by a non-zero branch probability using saturating + /// arithmetic. + BlockFrequency &operator/=(const BranchProbability &Prob); + BlockFrequency operator/(const BranchProbability &Prob) const; + + /// \brief Adds another block frequency using saturating arithmetic. BlockFrequency &operator+=(const BlockFrequency &Freq); const BlockFrequency operator+(const BlockFrequency &Freq) const; diff --git a/include/llvm/Support/CFG.h b/include/llvm/Support/CFG.h index 71a83e9..74ec726 100644 --- a/include/llvm/Support/CFG.h +++ b/include/llvm/Support/CFG.h @@ -328,7 +328,7 @@ template <> struct GraphTraits<Function*> : public GraphTraits<BasicBlock*> { typedef Function::iterator nodes_iterator; static nodes_iterator nodes_begin(Function *F) { return F->begin(); } static nodes_iterator nodes_end (Function *F) { return F->end(); } - static unsigned size (Function *F) { return F->size(); } + static size_t size (Function *F) { return F->size(); } }; template <> struct GraphTraits<const Function*> : public GraphTraits<const BasicBlock*> { @@ -338,7 +338,7 @@ template <> struct GraphTraits<const Function*> : typedef Function::const_iterator nodes_iterator; static nodes_iterator nodes_begin(const Function *F) { return F->begin(); } static nodes_iterator nodes_end (const Function *F) { return F->end(); } - static unsigned size (const Function *F) { return F->size(); } + static size_t size (const Function *F) { return F->size(); } }; diff --git a/include/llvm/Support/COFF.h b/include/llvm/Support/COFF.h index d348b76..a39a3f9 100644 --- a/include/llvm/Support/COFF.h +++ b/include/llvm/Support/COFF.h @@ -488,6 +488,24 @@ namespace COFF { uint32_t Size; }; + enum DataDirectoryIndex { + EXPORT_TABLE = 0, + IMPORT_TABLE, + RESOURCE_TABLE, + EXCEPTION_TABLE, + CERTIFICATE_TABLE, + BASE_RELOCATION_TABLE, + DEBUG, + ARCHITECTURE, + GLOBAL_PTR, + TLS_TABLE, + LOAD_CONFIG_TABLE, + BOUND_IMPORT, + IAT, + DELAY_IMPORT_DESCRIPTOR, + CLR_RUNTIME_HEADER + }; + enum WindowsSubsystem { IMAGE_SUBSYSTEM_UNKNOWN = 0, ///< An unknown subsystem. IMAGE_SUBSYSTEM_NATIVE = 1, ///< Device drivers and native Windows processes diff --git a/include/llvm/Support/CallSite.h b/include/llvm/Support/CallSite.h index d80d9d8..2a1c5ca 100644 --- a/include/llvm/Support/CallSite.h +++ b/include/llvm/Support/CallSite.h @@ -198,6 +198,12 @@ public: CALLSITE_DELEGATE_GETTER(getParamAlignment(i)); } + /// \brief Return true if the call should not be treated as a call to a + /// builtin. + bool isNoBuiltin() const { + CALLSITE_DELEGATE_GETTER(isNoBuiltin()); + } + /// @brief Return true if the call should not be inlined. bool isNoInline() const { CALLSITE_DELEGATE_GETTER(isNoInline()); @@ -251,6 +257,15 @@ public: return paramHasAttr(ArgNo + 1, Attribute::ByVal); } + bool doesNotAccessMemory(unsigned ArgNo) const { + return paramHasAttr(ArgNo + 1, Attribute::ReadNone); + } + + bool onlyReadsMemory(unsigned ArgNo) const { + return paramHasAttr(ArgNo + 1, Attribute::ReadOnly) || + paramHasAttr(ArgNo + 1, Attribute::ReadNone); + } + /// hasArgument - Returns true if this CallSite passes the given Value* as an /// argument to the called function. bool hasArgument(const Value *Arg) const { diff --git a/include/llvm/Support/Casting.h b/include/llvm/Support/Casting.h index 0d2d6c9..d70acbf 100644 --- a/include/llvm/Support/Casting.h +++ b/include/llvm/Support/Casting.h @@ -206,7 +206,10 @@ template<class To, class FromTy> struct cast_convert_val<To,FromTy,FromTy> { } }; - +template <class X> struct is_simple_type { + static const bool value = + is_same<X, typename simplify_type<X>::SimpleType>::value; +}; // cast<X> - Return the argument parameter cast to the specified type. This // casting operator asserts that the type is correct, so it does not return null @@ -216,10 +219,12 @@ template<class To, class FromTy> struct cast_convert_val<To,FromTy,FromTy> { // cast<Instruction>(myVal)->getParent() // template <class X, class Y> -inline typename cast_retty<X, const Y>::ret_type cast(const Y &Val) { +inline typename enable_if_c<!is_simple_type<Y>::value, + typename cast_retty<X, const Y>::ret_type>::type +cast(const Y &Val) { assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!"); - return cast_convert_val<X, const Y, - typename simplify_type<const Y>::SimpleType>::doit(Val); + return cast_convert_val< + X, const Y, typename simplify_type<const Y>::SimpleType>::doit(Val); } template <class X, class Y> @@ -230,10 +235,7 @@ inline typename cast_retty<X, Y>::ret_type cast(Y &Val) { } template <class X, class Y> -inline typename enable_if< - is_same<Y, typename simplify_type<Y>::SimpleType>, - typename cast_retty<X, Y*>::ret_type ->::type cast(Y *Val) { +inline typename cast_retty<X, Y *>::ret_type cast(Y *Val) { assert(isa<X>(Val) && "cast<Ty>() argument of incompatible type!"); return cast_convert_val<X, Y*, typename simplify_type<Y*>::SimpleType>::doit(Val); @@ -259,7 +261,9 @@ inline typename cast_retty<X, Y*>::ret_type cast_or_null(Y *Val) { // template <class X, class Y> -inline typename cast_retty<X, const Y>::ret_type dyn_cast(const Y &Val) { +inline typename enable_if_c<!is_simple_type<Y>::value, + typename cast_retty<X, const Y>::ret_type>::type +dyn_cast(const Y &Val) { return isa<X>(Val) ? cast<X>(Val) : 0; } @@ -269,10 +273,7 @@ inline typename cast_retty<X, Y>::ret_type dyn_cast(Y &Val) { } template <class X, class Y> -inline typename enable_if< - is_same<Y, typename simplify_type<Y>::SimpleType>, - typename cast_retty<X, Y*>::ret_type ->::type dyn_cast(Y *Val) { +inline typename cast_retty<X, Y *>::ret_type dyn_cast(Y *Val) { return isa<X>(Val) ? cast<X>(Val) : 0; } diff --git a/include/llvm/Support/CommandLine.h b/include/llvm/Support/CommandLine.h index 531760b..c0bfbae 100644 --- a/include/llvm/Support/CommandLine.h +++ b/include/llvm/Support/CommandLine.h @@ -1745,6 +1745,59 @@ void PrintHelpMessage(bool Hidden=false, bool Categorized=false); /// llvm::cl::ParseCommandLineOptions(). void getRegisteredOptions(StringMap<Option*> &Map); +//===----------------------------------------------------------------------===// +// Standalone command line processing utilities. +// + +/// \brief Saves strings in the inheritor's stable storage and returns a stable +/// raw character pointer. +class StringSaver { +public: + virtual const char *SaveString(const char *Str) = 0; + virtual ~StringSaver() {}; // Pacify -Wnon-virtual-dtor. +}; + +/// \brief Tokenizes a command line that can contain escapes and quotes. +// +/// The quoting rules match those used by GCC and other tools that use +/// libiberty's buildargv() or expandargv() utilities, and do not match bash. +/// They differ from buildargv() on treatment of backslashes that do not escape +/// a special character to make it possible to accept most Windows file paths. +/// +/// \param [in] Source The string to be split on whitespace with quotes. +/// \param [in] Saver Delegates back to the caller for saving parsed strings. +/// \param [out] NewArgv All parsed strings are appended to NewArgv. +void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver, + SmallVectorImpl<const char *> &NewArgv); + +/// \brief Tokenizes a Windows command line which may contain quotes and escaped +/// quotes. +/// +/// See MSDN docs for CommandLineToArgvW for information on the quoting rules. +/// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx +/// +/// \param [in] Source The string to be split on whitespace with quotes. +/// \param [in] Saver Delegates back to the caller for saving parsed strings. +/// \param [out] NewArgv All parsed strings are appended to NewArgv. +void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver, + SmallVectorImpl<const char *> &NewArgv); + +/// \brief String tokenization function type. Should be compatible with either +/// Windows or Unix command line tokenizers. +typedef void (*TokenizerCallback)(StringRef Source, StringSaver &Saver, + SmallVectorImpl<const char *> &NewArgv); + +/// \brief Expand response files on a command line recursively using the given +/// StringSaver and tokenization strategy. Argv should contain the command line +/// before expansion and will be modified in place. +/// +/// \param [in] Saver Delegates back to the caller for saving parsed strings. +/// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows. +/// \param [in,out] Argv Command line into which to expand response files. +/// \return true if all @files were expanded successfully or there were none. +bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer, + SmallVectorImpl<const char *> &Argv); + } // End namespace cl } // End namespace llvm diff --git a/include/llvm/Support/Compiler.h b/include/llvm/Support/Compiler.h index 13d057b..feac934 100644 --- a/include/llvm/Support/Compiler.h +++ b/include/llvm/Support/Compiler.h @@ -21,6 +21,25 @@ # define __has_feature(x) 0 #endif +#ifndef __has_attribute +# define __has_attribute(x) 0 +#endif + +#ifndef __has_builtin +# define __has_builtin(x) 0 +#endif + +/// \macro __GNUC_PREREQ +/// \brief Defines __GNUC_PREREQ if glibc's features.h isn't available. +#ifndef __GNUC_PREREQ +# if defined(__GNUC__) && defined(__GNUC_MINOR__) +# define __GNUC_PREREQ(maj, min) \ + ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min)) +# else +# define __GNUC_PREREQ(maj, min) 0 +# endif +#endif + /// \brief Does the compiler support r-value references? /// This implies that <utility> provides the one-argument std::move; it /// does not imply the existence of any other C++ library features. @@ -146,13 +165,15 @@ /// into a shared library, then the class should be private to the library and /// not accessible from outside it. Can also be used to mark variables and /// functions, making them private to any shared library they are linked into. -#if (__GNUC__ >= 4) && !defined(__MINGW32__) && !defined(__CYGWIN__) +/// On PE/COFF targets, library visibility is the default, so this isn't needed. +#if (__has_attribute(visibility) || __GNUC_PREREQ(4, 0)) && \ + !defined(__MINGW32__) && !defined(__CYGWIN__) && !defined(LLVM_ON_WIN32) #define LLVM_LIBRARY_VISIBILITY __attribute__ ((visibility("hidden"))) #else #define LLVM_LIBRARY_VISIBILITY #endif -#if (__GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) +#if __has_attribute(used) || __GNUC_PREREQ(3, 1) #define LLVM_ATTRIBUTE_USED __attribute__((__used__)) #else #define LLVM_ATTRIBUTE_USED @@ -166,31 +187,37 @@ // more portable solution: // (void)unused_var_name; // Prefer cast-to-void wherever it is sufficient. -#if (__GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) +#if __has_attribute(unused) || __GNUC_PREREQ(3, 1) #define LLVM_ATTRIBUTE_UNUSED __attribute__((__unused__)) #else #define LLVM_ATTRIBUTE_UNUSED #endif -#if (__GNUC__ >= 4) && !defined(__MINGW32__) && !defined(__CYGWIN__) +// FIXME: Provide this for PE/COFF targets. +#if (__has_attribute(weak) || __GNUC_PREREQ(4, 0)) && \ + (!defined(__MINGW32__) && !defined(__CYGWIN__) && !defined(LLVM_ON_WIN32)) #define LLVM_ATTRIBUTE_WEAK __attribute__((__weak__)) #else #define LLVM_ATTRIBUTE_WEAK #endif -#ifdef __GNUC__ // aka 'CONST' but following LLVM Conventions. +// Prior to clang 3.2, clang did not accept any spelling of +// __has_attribute(const), so assume it is supported. +#if defined(__clang__) || defined(__GNUC__) +// aka 'CONST' but following LLVM Conventions. #define LLVM_READNONE __attribute__((__const__)) #else #define LLVM_READNONE #endif -#ifdef __GNUC__ // aka 'PURE' but following LLVM Conventions. +#if __has_attribute(pure) || defined(__GNUC__) +// aka 'PURE' but following LLVM Conventions. #define LLVM_READONLY __attribute__((__pure__)) #else #define LLVM_READONLY #endif -#if (__GNUC__ >= 4) +#if __has_builtin(__builtin_expect) || __GNUC_PREREQ(4, 0) #define LLVM_LIKELY(EXPR) __builtin_expect((bool)(EXPR), true) #define LLVM_UNLIKELY(EXPR) __builtin_expect((bool)(EXPR), false) #else @@ -213,7 +240,7 @@ /// LLVM_ATTRIBUTE_NOINLINE - On compilers where we have a directive to do so, /// mark a method "not for inlining". -#if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) +#if __has_attribute(noinline) || __GNUC_PREREQ(3, 4) #define LLVM_ATTRIBUTE_NOINLINE __attribute__((noinline)) #elif defined(_MSC_VER) #define LLVM_ATTRIBUTE_NOINLINE __declspec(noinline) @@ -225,7 +252,7 @@ /// so, mark a method "always inline" because it is performance sensitive. GCC /// 3.4 supported this but is buggy in various cases and produces unimplemented /// errors, just use it in GCC 4.0 and later. -#if __GNUC__ > 3 +#if __has_attribute(always_inline) || __GNUC_PREREQ(4, 0) #define LLVM_ATTRIBUTE_ALWAYS_INLINE inline __attribute__((always_inline)) #elif defined(_MSC_VER) #define LLVM_ATTRIBUTE_ALWAYS_INLINE __forceinline @@ -267,8 +294,7 @@ /// LLVM_BUILTIN_UNREACHABLE - On compilers which support it, expands /// to an expression which states that it is undefined behavior for the /// compiler to reach this point. Otherwise is not defined. -#if defined(__clang__) || (__GNUC__ > 4) \ - || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) +#if __has_builtin(__builtin_unreachable) || __GNUC_PREREQ(4, 5) # define LLVM_BUILTIN_UNREACHABLE __builtin_unreachable() #elif defined(_MSC_VER) # define LLVM_BUILTIN_UNREACHABLE __assume(false) @@ -276,8 +302,7 @@ /// LLVM_BUILTIN_TRAP - On compilers which support it, expands to an expression /// which causes the program to exit abnormally. -#if defined(__clang__) || (__GNUC__ > 4) \ - || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3) +#if __has_builtin(__builtin_trap) || __GNUC_PREREQ(4, 3) # define LLVM_BUILTIN_TRAP __builtin_trap() #else # define LLVM_BUILTIN_TRAP *(volatile int*)0x11 = 0 @@ -285,11 +310,10 @@ /// \macro LLVM_ASSUME_ALIGNED /// \brief Returns a pointer with an assumed alignment. -#if !defined(__clang__) && ((__GNUC__ > 4) \ - || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)) -// FIXME: Enable on clang when it supports it. +#if __has_builtin(__builtin_assume_aligned) && __GNUC_PREREQ(4, 7) # define LLVM_ASSUME_ALIGNED(p, a) __builtin_assume_aligned(p, a) #elif defined(LLVM_BUILTIN_UNREACHABLE) +// As of today, clang does not support __builtin_assume_aligned. # define LLVM_ASSUME_ALIGNED(p, a) \ (((uintptr_t(p) % (a)) == 0) ? (p) : (LLVM_BUILTIN_UNREACHABLE, (p))) #else diff --git a/include/llvm/Support/ConstantRange.h b/include/llvm/Support/ConstantRange.h index 0f29256..f757c6e 100644 --- a/include/llvm/Support/ConstantRange.h +++ b/include/llvm/Support/ConstantRange.h @@ -42,6 +42,14 @@ namespace llvm { class ConstantRange { APInt Lower, Upper; +#if LLVM_HAS_RVALUE_REFERENCES + // If we have move semantics, pass APInts by value and move them into place. + typedef APInt APIntMoveTy; +#else + // Otherwise pass by const ref to save one copy. + typedef const APInt &APIntMoveTy; +#endif + public: /// Initialize a full (the default) or empty set for the specified bit width. /// @@ -49,12 +57,12 @@ public: /// Initialize a range to hold the single specified value. /// - ConstantRange(const APInt &Value); + ConstantRange(APIntMoveTy Value); /// @brief Initialize a range of values explicitly. This will assert out if /// Lower==Upper and Lower != Min or Max value for its type. It will also /// assert out if the two APInt's are not the same bit width. - ConstantRange(const APInt &Lower, const APInt &Upper); + ConstantRange(APIntMoveTy Lower, APIntMoveTy Upper); /// makeICmpRegion - Produce the smallest range that contains all values that /// might satisfy the comparison specified by Pred when compared to any value diff --git a/include/llvm/Support/ConvertUTF.h b/include/llvm/Support/ConvertUTF.h index 1eae6d6..2820366 100644 --- a/include/llvm/Support/ConvertUTF.h +++ b/include/llvm/Support/ConvertUTF.h @@ -87,8 +87,8 @@ ------------------------------------------------------------------------ */ -#ifndef CLANG_BASIC_CONVERTUTF_H -#define CLANG_BASIC_CONVERTUTF_H +#ifndef LLVM_SUPPORT_CONVERTUTF_H +#define LLVM_SUPPORT_CONVERTUTF_H /* --------------------------------------------------------------------- The following 4 definitions are compiler-specific. @@ -112,6 +112,9 @@ typedef unsigned char Boolean; /* 0 or 1 */ #define UNI_MAX_UTF8_BYTES_PER_CODE_POINT 4 +#define UNI_UTF16_BYTE_ORDER_MARK_NATIVE 0xFEFF +#define UNI_UTF16_BYTE_ORDER_MARK_SWAPPED 0xFFFE + typedef enum { conversionOK, /* conversion successful */ sourceExhausted, /* partial character in source, but hit end */ @@ -165,6 +168,7 @@ unsigned getNumBytesForUTF8(UTF8 firstByte); /*************************************************************************/ /* Below are LLVM-specific wrappers of the functions above. */ +#include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/StringRef.h" namespace llvm { @@ -219,6 +223,22 @@ static inline ConversionResult convertUTF8Sequence(const UTF8 **source, return sourceExhausted; return ConvertUTF8toUTF32(source, *source + size, &target, target + 1, flags); } + +/** + * Returns true if a blob of text starts with a UTF-16 big or little endian byte + * order mark. + */ +bool hasUTF16ByteOrderMark(ArrayRef<char> SrcBytes); + +/** + * Converts a stream of raw bytes assumed to be UTF16 into a UTF8 std::string. + * + * \param [in] SrcBytes A buffer of what is assumed to be UTF-16 encoded text. + * \param [out] Out Converted UTF-8 is stored here on success. + * \returns true on success + */ +bool convertUTF16ToUTF8String(ArrayRef<char> SrcBytes, std::string &Out); + } /* end namespace llvm */ #endif diff --git a/include/llvm/Support/DataTypes.h.cmake b/include/llvm/Support/DataTypes.h.cmake index 7484abd..a26070c 100644 --- a/include/llvm/Support/DataTypes.h.cmake +++ b/include/llvm/Support/DataTypes.h.cmake @@ -26,7 +26,6 @@ #ifndef SUPPORT_DATATYPES_H #define SUPPORT_DATATYPES_H -#cmakedefine HAVE_SYS_TYPES_H ${HAVE_SYS_TYPES_H} #cmakedefine HAVE_INTTYPES_H ${HAVE_INTTYPES_H} #cmakedefine HAVE_STDINT_H ${HAVE_STDINT_H} #cmakedefine HAVE_UINT64_T ${HAVE_UINT64_T} @@ -54,9 +53,7 @@ #endif /* Note that <inttypes.h> includes <stdint.h>, if this is a C99 system. */ -#ifdef HAVE_SYS_TYPES_H #include <sys/types.h> -#endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> @@ -101,7 +98,11 @@ typedef short int16_t; typedef unsigned short uint16_t; typedef signed char int8_t; typedef unsigned char uint8_t; -typedef signed int ssize_t; +#if defined(_WIN64) + typedef signed __int64 ssize_t; +#else + typedef signed int ssize_t; +#endif #ifndef INT8_MAX # define INT8_MAX 127 #endif diff --git a/include/llvm/Support/DataTypes.h.in b/include/llvm/Support/DataTypes.h.in index b9fb48a..7fc9b72 100644 --- a/include/llvm/Support/DataTypes.h.in +++ b/include/llvm/Support/DataTypes.h.in @@ -26,7 +26,6 @@ #ifndef SUPPORT_DATATYPES_H #define SUPPORT_DATATYPES_H -#undef HAVE_SYS_TYPES_H #undef HAVE_INTTYPES_H #undef HAVE_STDINT_H #undef HAVE_UINT64_T @@ -54,9 +53,7 @@ #endif /* Note that <inttypes.h> includes <stdint.h>, if this is a C99 system. */ -#ifdef HAVE_SYS_TYPES_H #include <sys/types.h> -#endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> @@ -98,7 +95,12 @@ typedef short int16_t; typedef unsigned short uint16_t; typedef signed char int8_t; typedef unsigned char uint8_t; -typedef signed int ssize_t; +#if defined(_WIN64) + typedef signed __int64 ssize_t; +#else + typedef signed int ssize_t; +#endif + #ifndef INT8_MAX # define INT8_MAX 127 #endif diff --git a/include/llvm/Support/Dwarf.h b/include/llvm/Support/Dwarf.h index b52914f..d0e2322 100644 --- a/include/llvm/Support/Dwarf.h +++ b/include/llvm/Support/Dwarf.h @@ -272,6 +272,8 @@ enum dwarf_constants { DW_AT_GNU_vector = 0x2107, DW_AT_GNU_template_name = 0x2110, + DW_AT_GNU_odr_signature = 0x210f, + // Extensions for Fission proposal. DW_AT_GNU_dwo_name = 0x2130, DW_AT_GNU_dwo_id = 0x2131, diff --git a/include/llvm/Support/ELF.h b/include/llvm/Support/ELF.h index ac11f0a..54da31c 100644 --- a/include/llvm/Support/ELF.h +++ b/include/llvm/Support/ELF.h @@ -276,7 +276,6 @@ enum { EM_STM8 = 186, // STMicroeletronics STM8 8-bit microcontroller EM_TILE64 = 187, // Tilera TILE64 multicore architecture family EM_TILEPRO = 188, // Tilera TILEPro multicore architecture family - EM_MICROBLAZE = 189, // Xilinx MicroBlaze 32-bit RISC soft processor core EM_CUDA = 190, // NVIDIA CUDA architecture EM_TILEGX = 191, // Tilera TILE-Gx multicore architecture family EM_CLOUDSHIELD = 192, // CloudShield architecture family @@ -287,8 +286,7 @@ enum { EM_RL78 = 197, // Renesas RL78 family EM_VIDEOCORE5 = 198, // Broadcom VideoCore V processor EM_78KOR = 199, // Renesas 78KOR family - EM_56800EX = 200, // Freescale 56800EX Digital Signal Controller (DSC) - EM_MBLAZE = 47787 // Xilinx MicroBlaze + EM_56800EX = 200 // Freescale 56800EX Digital Signal Controller (DSC) }; // Object file classes. @@ -418,32 +416,6 @@ enum { R_386_NUM = 43 }; -// MBlaze relocations. -enum { - R_MICROBLAZE_NONE = 0, - R_MICROBLAZE_32 = 1, - R_MICROBLAZE_32_PCREL = 2, - R_MICROBLAZE_64_PCREL = 3, - R_MICROBLAZE_32_PCREL_LO = 4, - R_MICROBLAZE_64 = 5, - R_MICROBLAZE_32_LO = 6, - R_MICROBLAZE_SRO32 = 7, - R_MICROBLAZE_SRW32 = 8, - R_MICROBLAZE_64_NONE = 9, - R_MICROBLAZE_32_SYM_OP_SYM = 10, - R_MICROBLAZE_GNU_VTINHERIT = 11, - R_MICROBLAZE_GNU_VTENTRY = 12, - R_MICROBLAZE_GOTPC_64 = 13, - R_MICROBLAZE_GOT_64 = 14, - R_MICROBLAZE_PLT_64 = 15, - R_MICROBLAZE_REL = 16, - R_MICROBLAZE_JUMP_SLOT = 17, - R_MICROBLAZE_GLOB_DAT = 18, - R_MICROBLAZE_GOTOFF_64 = 19, - R_MICROBLAZE_GOTOFF_32 = 20, - R_MICROBLAZE_COPY = 21 -}; - // ELF Relocation types for PPC32 enum { R_PPC_NONE = 0, /* No relocation. */ @@ -460,9 +432,45 @@ enum { R_PPC_REL14 = 11, R_PPC_REL14_BRTAKEN = 12, R_PPC_REL14_BRNTAKEN = 13, + R_PPC_GOT16 = 14, + R_PPC_GOT16_LO = 15, + R_PPC_GOT16_HI = 16, + R_PPC_GOT16_HA = 17, R_PPC_REL32 = 26, + R_PPC_TLS = 67, + R_PPC_DTPMOD32 = 68, + R_PPC_TPREL16 = 69, R_PPC_TPREL16_LO = 70, - R_PPC_TPREL16_HA = 72 + R_PPC_TPREL16_HI = 71, + R_PPC_TPREL16_HA = 72, + R_PPC_TPREL32 = 73, + R_PPC_DTPREL16 = 74, + R_PPC_DTPREL16_LO = 75, + R_PPC_DTPREL16_HI = 76, + R_PPC_DTPREL16_HA = 77, + R_PPC_DTPREL32 = 78, + R_PPC_GOT_TLSGD16 = 79, + R_PPC_GOT_TLSGD16_LO = 80, + R_PPC_GOT_TLSGD16_HI = 81, + R_PPC_GOT_TLSGD16_HA = 82, + R_PPC_GOT_TLSLD16 = 83, + R_PPC_GOT_TLSLD16_LO = 84, + R_PPC_GOT_TLSLD16_HI = 85, + R_PPC_GOT_TLSLD16_HA = 86, + R_PPC_GOT_TPREL16 = 87, + R_PPC_GOT_TPREL16_LO = 88, + R_PPC_GOT_TPREL16_HI = 89, + R_PPC_GOT_TPREL16_HA = 90, + R_PPC_GOT_DTPREL16 = 91, + R_PPC_GOT_DTPREL16_LO = 92, + R_PPC_GOT_DTPREL16_HI = 93, + R_PPC_GOT_DTPREL16_HA = 94, + R_PPC_TLSGD = 95, + R_PPC_TLSLD = 96, + R_PPC_REL16 = 249, + R_PPC_REL16_LO = 250, + R_PPC_REL16_HI = 251, + R_PPC_REL16_HA = 252 }; // ELF Relocation types for PPC64 @@ -481,32 +489,74 @@ enum { R_PPC64_REL14 = 11, R_PPC64_REL14_BRTAKEN = 12, R_PPC64_REL14_BRNTAKEN = 13, + R_PPC64_GOT16 = 14, + R_PPC64_GOT16_LO = 15, + R_PPC64_GOT16_HI = 16, + R_PPC64_GOT16_HA = 17, R_PPC64_REL32 = 26, R_PPC64_ADDR64 = 38, R_PPC64_ADDR16_HIGHER = 39, + R_PPC64_ADDR16_HIGHERA = 40, R_PPC64_ADDR16_HIGHEST = 41, + R_PPC64_ADDR16_HIGHESTA = 42, R_PPC64_REL64 = 44, R_PPC64_TOC16 = 47, R_PPC64_TOC16_LO = 48, + R_PPC64_TOC16_HI = 49, R_PPC64_TOC16_HA = 50, R_PPC64_TOC = 51, R_PPC64_ADDR16_DS = 56, R_PPC64_ADDR16_LO_DS = 57, + R_PPC64_GOT16_DS = 58, + R_PPC64_GOT16_LO_DS = 59, R_PPC64_TOC16_DS = 63, R_PPC64_TOC16_LO_DS = 64, R_PPC64_TLS = 67, + R_PPC64_DTPMOD64 = 68, + R_PPC64_TPREL16 = 69, R_PPC64_TPREL16_LO = 70, + R_PPC64_TPREL16_HI = 71, R_PPC64_TPREL16_HA = 72, + R_PPC64_TPREL64 = 73, + R_PPC64_DTPREL16 = 74, R_PPC64_DTPREL16_LO = 75, + R_PPC64_DTPREL16_HI = 76, R_PPC64_DTPREL16_HA = 77, + R_PPC64_DTPREL64 = 78, + R_PPC64_GOT_TLSGD16 = 79, R_PPC64_GOT_TLSGD16_LO = 80, + R_PPC64_GOT_TLSGD16_HI = 81, R_PPC64_GOT_TLSGD16_HA = 82, + R_PPC64_GOT_TLSLD16 = 83, R_PPC64_GOT_TLSLD16_LO = 84, + R_PPC64_GOT_TLSLD16_HI = 85, R_PPC64_GOT_TLSLD16_HA = 86, + R_PPC64_GOT_TPREL16_DS = 87, R_PPC64_GOT_TPREL16_LO_DS = 88, + R_PPC64_GOT_TPREL16_HI = 89, R_PPC64_GOT_TPREL16_HA = 90, + R_PPC64_GOT_DTPREL16_DS = 91, + R_PPC64_GOT_DTPREL16_LO_DS = 92, + R_PPC64_GOT_DTPREL16_HI = 93, + R_PPC64_GOT_DTPREL16_HA = 94, + R_PPC64_TPREL16_DS = 95, + R_PPC64_TPREL16_LO_DS = 96, + R_PPC64_TPREL16_HIGHER = 97, + R_PPC64_TPREL16_HIGHERA = 98, + R_PPC64_TPREL16_HIGHEST = 99, + R_PPC64_TPREL16_HIGHESTA = 100, + R_PPC64_DTPREL16_DS = 101, + R_PPC64_DTPREL16_LO_DS = 102, + R_PPC64_DTPREL16_HIGHER = 103, + R_PPC64_DTPREL16_HIGHERA = 104, + R_PPC64_DTPREL16_HIGHEST = 105, + R_PPC64_DTPREL16_HIGHESTA = 106, R_PPC64_TLSGD = 107, - R_PPC64_TLSLD = 108 + R_PPC64_TLSLD = 108, + R_PPC64_REL16 = 249, + R_PPC64_REL16_LO = 250, + R_PPC64_REL16_HI = 251, + R_PPC64_REL16_HA = 252 }; // ELF Relocation types for AArch64 @@ -790,6 +840,8 @@ enum { R_MIPS_PC16 = 10, R_MIPS_CALL16 = 11, R_MIPS_GPREL32 = 12, + R_MIPS_UNUSED1 = 13, + R_MIPS_UNUSED2 = 14, R_MIPS_SHIFT5 = 16, R_MIPS_SHIFT6 = 17, R_MIPS_64 = 18, diff --git a/include/llvm/Support/FileSystem.h b/include/llvm/Support/FileSystem.h index 570b34b..c130b47 100644 --- a/include/llvm/Support/FileSystem.h +++ b/include/llvm/Support/FileSystem.h @@ -33,6 +33,7 @@ #include "llvm/ADT/Twine.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/TimeValue.h" #include "llvm/Support/system_error.h" #include <ctime> #include <iterator> @@ -72,22 +73,6 @@ private: int v_; }; -/// copy_option - An "enum class" enumeration of copy semantics for copy -/// operations. -struct copy_option { - enum _ { - fail_if_exists, - overwrite_if_exists - }; - - copy_option(_ v) : v_(v) {} - explicit copy_option(int v) : v_(_(v)) {} - operator int() const {return v_;} - -private: - int v_; -}; - /// space_info - Self explanatory. struct space_info { uint64_t capacity; @@ -95,30 +80,28 @@ struct space_info { uint64_t available; }; - enum perms { - no_perms = 0, - owner_read = 0400, - owner_write = 0200, - owner_exe = 0100, - owner_all = owner_read | owner_write | owner_exe, - group_read = 040, - group_write = 020, - group_exe = 010, - group_all = group_read | group_write | group_exe, - others_read = 04, - others_write = 02, - others_exe = 01, - others_all = others_read | others_write | others_exe, - all_all = owner_all | group_all | others_all, - set_uid_on_exe = 04000, - set_gid_on_exe = 02000, - sticky_bit = 01000, - perms_mask = all_all | set_uid_on_exe | set_gid_on_exe | sticky_bit, - perms_not_known = 0xFFFF, - add_perms = 0x1000, - remove_perms = 0x2000, - symlink_perms = 0x4000 + no_perms = 0, + owner_read = 0400, + owner_write = 0200, + owner_exe = 0100, + owner_all = owner_read | owner_write | owner_exe, + group_read = 040, + group_write = 020, + group_exe = 010, + group_all = group_read | group_write | group_exe, + others_read = 04, + others_write = 02, + others_exe = 01, + others_all = others_read | others_write | others_exe, + all_read = owner_read | group_read | others_read, + all_write = owner_write | group_write | others_write, + all_exe = owner_exe | group_exe | others_exe, + all_all = owner_all | group_all | others_all, + set_uid_on_exe = 04000, + set_gid_on_exe = 02000, + sticky_bit = 01000, + perms_not_known = 0xFFFF }; // Helper functions so that you can use & and | to manipulate perms bits: @@ -142,8 +125,25 @@ inline perms operator~(perms x) { return static_cast<perms>(~static_cast<unsigned short>(x)); } +class UniqueID { + uint64_t Device; + uint64_t File; + +public: + UniqueID() {} + UniqueID(uint64_t Device, uint64_t File) : Device(Device), File(File) {} + bool operator==(const UniqueID &Other) const { + return Device == Other.Device && File == Other.File; + } + bool operator!=(const UniqueID &Other) const { return !(*this == Other); } + bool operator<(const UniqueID &Other) const { + return Device < Other.Device || + (Device == Other.Device && File < Other.File); + } + uint64_t getDevice() const { return Device; } + uint64_t getFile() const { return File; } +}; - /// file_status - Represents the result of a call to stat and friends. It has /// a platform specific member to store the result. class file_status @@ -151,6 +151,10 @@ class file_status #if defined(LLVM_ON_UNIX) dev_t fs_st_dev; ino_t fs_st_ino; + time_t fs_st_mtime; + uid_t fs_st_uid; + gid_t fs_st_gid; + off_t fs_st_size; #elif defined (LLVM_ON_WIN32) uint32_t LastWriteTimeHigh; uint32_t LastWriteTimeLow; @@ -161,18 +165,51 @@ class file_status uint32_t FileIndexLow; #endif friend bool equivalent(file_status A, file_status B); - friend error_code status(const Twine &path, file_status &result); file_type Type; perms Perms; public: - explicit file_status(file_type v=file_type::status_error, - perms prms=perms_not_known) - : Type(v), Perms(prms) {} + file_status() : Type(file_type::status_error) {} + file_status(file_type Type) : Type(Type) {} + + #if defined(LLVM_ON_UNIX) + file_status(file_type Type, perms Perms, dev_t Dev, ino_t Ino, time_t MTime, + uid_t UID, gid_t GID, off_t Size) + : fs_st_dev(Dev), fs_st_ino(Ino), fs_st_mtime(MTime), fs_st_uid(UID), + fs_st_gid(GID), fs_st_size(Size), Type(Type), Perms(Perms) {} + #elif defined(LLVM_ON_WIN32) + file_status(file_type Type, uint32_t LastWriteTimeHigh, + uint32_t LastWriteTimeLow, uint32_t VolumeSerialNumber, + uint32_t FileSizeHigh, uint32_t FileSizeLow, + uint32_t FileIndexHigh, uint32_t FileIndexLow) + : LastWriteTimeHigh(LastWriteTimeHigh), + LastWriteTimeLow(LastWriteTimeLow), + VolumeSerialNumber(VolumeSerialNumber), FileSizeHigh(FileSizeHigh), + FileSizeLow(FileSizeLow), FileIndexHigh(FileIndexHigh), + FileIndexLow(FileIndexLow), Type(Type), Perms(perms_not_known) {} + #endif // getters file_type type() const { return Type; } perms permissions() const { return Perms; } - + TimeValue getLastModificationTime() const; + UniqueID getUniqueID() const; + + #if defined(LLVM_ON_UNIX) + uint32_t getUser() const { return fs_st_uid; } + uint32_t getGroup() const { return fs_st_gid; } + uint64_t getSize() const { return fs_st_size; } + #elif defined (LLVM_ON_WIN32) + uint32_t getUser() const { + return 9999; // Not applicable to Windows, so... + } + uint32_t getGroup() const { + return 9999; // Not applicable to Windows, so... + } + uint64_t getSize() const { + return (uint64_t(FileSizeHigh) << 32) + FileSizeLow; + } + #endif + // setters void type(file_type v) { Type = v; } void permissions(perms p) { Perms = p; } @@ -199,6 +236,7 @@ struct file_magic { macho_bundle, ///< Mach-O Bundle file macho_dynamically_linked_shared_lib_stub, ///< Mach-O Shared lib stub macho_dsym_companion, ///< Mach-O dSYM companion file + macho_universal_binary, ///< Mach-O universal binary coff_object, ///< COFF object file pecoff_executable ///< PECOFF executable file }; @@ -232,18 +270,6 @@ private: /// platform specific error_code. error_code make_absolute(SmallVectorImpl<char> &path); -/// @brief Copy the file at \a from to the path \a to. -/// -/// @param from The path to copy the file from. -/// @param to The path to copy the file to. -/// @param copt Behavior if \a to already exists. -/// @returns errc::success if the file has been successfully copied. -/// errc::file_exists if \a to already exists and \a copt == -/// copy_option::fail_if_exists. Otherwise a platform specific -/// error_code. -error_code copy_file(const Twine &from, const Twine &to, - copy_option copt = copy_option::fail_if_exists); - /// @brief Create all the non-existent directories in path. /// /// @param path Directories to create. @@ -252,6 +278,13 @@ error_code copy_file(const Twine &from, const Twine &to, /// otherwise a platform specific error_code. error_code create_directories(const Twine &path, bool &existed); +/// @brief Convenience function for clients that don't need to know if the +/// directory existed or not. +inline error_code create_directories(const Twine &Path) { + bool Existed; + return create_directories(Path, Existed); +} + /// @brief Create the directory in path. /// /// @param path Directory to create. @@ -260,6 +293,13 @@ error_code create_directories(const Twine &path, bool &existed); /// otherwise a platform specific error_code. error_code create_directory(const Twine &path, bool &existed); +/// @brief Convenience function for clients that don't need to know if the +/// directory existed or not. +inline error_code create_directory(const Twine &Path) { + bool Existed; + return create_directory(Path, Existed); +} + /// @brief Create a hard link from \a from to \a to. /// /// @param to The path to hard link to. @@ -292,6 +332,13 @@ error_code current_path(SmallVectorImpl<char> &result); /// successfully set, otherwise a platform specific error_code. error_code remove(const Twine &path, bool &existed); +/// @brief Convenience function for clients that don't need to know if the file +/// existed or not. +inline error_code remove(const Twine &Path) { + bool Existed; + return remove(Path, Existed); +} + /// @brief Recursively remove all files below \a path, then \a path. Files are /// removed as if by POSIX remove(). /// @@ -301,6 +348,13 @@ error_code remove(const Twine &path, bool &existed); /// successfully set, otherwise a platform specific error_code. error_code remove_all(const Twine &path, uint32_t &num_removed); +/// @brief Convenience function for clients that don't need to know how many +/// files were removed. +inline error_code remove_all(const Twine &Path) { + uint32_t Removed; + return remove_all(Path, Removed); +} + /// @brief Rename \a from to \a to. Files are renamed as if by POSIX rename(). /// /// @param from The path to rename from. @@ -342,6 +396,18 @@ inline bool exists(const Twine &path) { return !exists(path, result) && result; } +/// @brief Can we execute this file? +/// +/// @param Path Input path. +/// @returns True if we can execute it, false otherwise. +bool can_execute(const Twine &Path); + +/// @brief Can we write this file? +/// +/// @param Path Input path. +/// @returns True if we can write to it, false otherwise. +bool can_write(const Twine &Path); + /// @brief Do file_status's represent the same thing? /// /// @param A Input file_status. @@ -372,14 +438,6 @@ inline bool equivalent(const Twine &A, const Twine &B) { return !equivalent(A, B, result) && result; } -/// @brief Get file size. -/// -/// @param path Input path. -/// @param result Set to the size of the file in \a path. -/// @returns errc::success if result has been successfully set, otherwise a -/// platform specific error_code. -error_code file_size(const Twine &path, uint64_t &result); - /// @brief Does status represent a directory? /// /// @param status A file_status previously returned from status. @@ -395,6 +453,13 @@ bool is_directory(file_status status); /// platform specific error_code. error_code is_directory(const Twine &path, bool &result); +/// @brief Simpler version of is_directory for clients that don't need to +/// differentiate between an error and false. +inline bool is_directory(const Twine &Path) { + bool Result; + return !is_directory(Path, Result) && Result; +} + /// @brief Does status represent a regular file? /// /// @param status A file_status previously returned from status. @@ -410,6 +475,15 @@ bool is_regular_file(file_status status); /// platform specific error_code. error_code is_regular_file(const Twine &path, bool &result); +/// @brief Simpler version of is_regular_file for clients that don't need to +/// differentiate between an error and false. +inline bool is_regular_file(const Twine &Path) { + bool Result; + if (is_regular_file(Path, Result)) + return false; + return Result; +} + /// @brief Does this status represent something that exists but is not a /// directory, regular file, or symlink? /// @@ -451,12 +525,25 @@ error_code is_symlink(const Twine &path, bool &result); /// platform specific error_code. error_code status(const Twine &path, file_status &result); -/// @brief Modifies permission bits on a file +/// @brief A version for when a file descriptor is already available. +error_code status(int FD, file_status &Result); + +/// @brief Get file size. /// -/// @param path Input path. -/// @returns errc::success if permissions have been changed, otherwise a +/// @param Path Input path. +/// @param Result Set to the size of the file in \a Path. +/// @returns errc::success if result has been successfully set, otherwise a /// platform specific error_code. -error_code permissions(const Twine &path, perms prms); +inline error_code file_size(const Twine &Path, uint64_t &Result) { + file_status Status; + error_code EC = status(Path, Status); + if (EC) + return EC; + Result = Status.getSize(); + return error_code::success(); +} + +error_code setLastModificationAndAccessTime(int FD, TimeValue Time); /// @brief Is status available? /// @@ -472,28 +559,84 @@ bool status_known(file_status s); /// platform specific error_code. error_code status_known(const Twine &path, bool &result); -/// @brief Generate a unique path and open it as a file. +/// @brief Create a uniquely named file. /// /// Generates a unique path suitable for a temporary file and then opens it as a /// file. The name is based on \a model with '%' replaced by a random char in /// [0-9a-f]. If \a model is not an absolute path, a suitable temporary /// directory will be prepended. /// +/// Example: clang-%%-%%-%%-%%-%%.s => clang-a0-b1-c2-d3-e4.s +/// /// This is an atomic operation. Either the file is created and opened, or the /// file system is left untouched. /// -/// clang-%%-%%-%%-%%-%%.s => /tmp/clang-a0-b1-c2-d3-e4.s +/// The intendend use is for files that are to be kept, possibly after +/// renaming them. For example, when running 'clang -c foo.o', the file can +/// be first created as foo-abc123.o and then renamed. /// -/// @param model Name to base unique path off of. -/// @param result_fd Set to the opened file's file descriptor. -/// @param result_path Set to the opened file's absolute path. -/// @param makeAbsolute If true and \a model is not an absolute path, a temp -/// directory will be prepended. -/// @returns errc::success if result_{fd,path} have been successfully set, +/// @param Model Name to base unique path off of. +/// @param ResultFD Set to the opened file's file descriptor. +/// @param ResultPath Set to the opened file's absolute path. +/// @returns errc::success if Result{FD,Path} have been successfully set, /// otherwise a platform specific error_code. -error_code unique_file(const Twine &model, int &result_fd, - SmallVectorImpl<char> &result_path, - bool makeAbsolute = true, unsigned mode = 0600); +error_code createUniqueFile(const Twine &Model, int &ResultFD, + SmallVectorImpl<char> &ResultPath, + unsigned Mode = all_read | all_write); + +/// @brief Simpler version for clients that don't want an open file. +error_code createUniqueFile(const Twine &Model, + SmallVectorImpl<char> &ResultPath); + +/// @brief Create a file in the system temporary directory. +/// +/// The filename is of the form prefix-random_chars.suffix. Since the directory +/// is not know to the caller, Prefix and Suffix cannot have path separators. +/// The files are created with mode 0600. +/// +/// This should be used for things like a temporary .s that is removed after +/// running the assembler. +error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, + int &ResultFD, + SmallVectorImpl<char> &ResultPath); + +/// @brief Simpler version for clients that don't want an open file. +error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, + SmallVectorImpl<char> &ResultPath); + +error_code createUniqueDirectory(const Twine &Prefix, + SmallVectorImpl<char> &ResultPath); + +enum OpenFlags { + F_None = 0, + + /// F_Excl - When opening a file, this flag makes raw_fd_ostream + /// report an error if the file already exists. + F_Excl = 1, + + /// F_Append - When opening a file, if it already exists append to the + /// existing file instead of returning an error. This may not be specified + /// with F_Excl. + F_Append = 2, + + /// F_Binary - The file should be opened in binary mode on platforms that + /// make this distinction. + F_Binary = 4 +}; + +inline OpenFlags operator|(OpenFlags A, OpenFlags B) { + return OpenFlags(unsigned(A) | unsigned(B)); +} + +inline OpenFlags &operator|=(OpenFlags &A, OpenFlags B) { + A = A | B; + return A; +} + +error_code openFileForWrite(const Twine &Name, int &ResultFD, OpenFlags Flags, + unsigned Mode = 0666); + +error_code openFileForRead(const Twine &Name, int &ResultFD); /// @brief Canonicalize path. /// @@ -538,43 +681,7 @@ file_magic identify_magic(StringRef magic); /// platform specific error_code. error_code identify_magic(const Twine &path, file_magic &result); -/// @brief Get library paths the system linker uses. -/// -/// @param result Set to the list of system library paths. -/// @returns errc::success if result has been successfully set, otherwise a -/// platform specific error_code. -error_code GetSystemLibraryPaths(SmallVectorImpl<std::string> &result); - -/// @brief Get bitcode library paths the system linker uses -/// + LLVM_LIB_SEARCH_PATH + LLVM_LIBDIR. -/// -/// @param result Set to the list of bitcode library paths. -/// @returns errc::success if result has been successfully set, otherwise a -/// platform specific error_code. -error_code GetBitcodeLibraryPaths(SmallVectorImpl<std::string> &result); - -/// @brief Find a library. -/// -/// Find the path to a library using its short name. Use the system -/// dependent library paths to locate the library. -/// -/// c => /usr/lib/libc.so -/// -/// @param short_name Library name one would give to the system linker. -/// @param result Set to the absolute path \a short_name represents. -/// @returns errc::success if result has been successfully set, otherwise a -/// platform specific error_code. -error_code FindLibrary(const Twine &short_name, SmallVectorImpl<char> &result); - -/// @brief Get absolute path of main executable. -/// -/// @param argv0 The program name as it was spelled on the command line. -/// @param MainAddr Address of some symbol in the executable (not in a library). -/// @param result Set to the absolute path of the current executable. -/// @returns errc::success if result has been successfully set, otherwise a -/// platform specific error_code. -error_code GetMainExecutable(const char *argv0, void *MainAddr, - SmallVectorImpl<char> &result); +error_code getUniqueID(const Twine Path, UniqueID &Result); /// This class represents a memory mapped file. It is based on /// boost::iostreams::mapped_file. @@ -648,7 +755,7 @@ public: char *data() const; /// Get a const view of the data. Modifying this memory has undefined - /// behaivor. + /// behavior. const char *const_data() const; /// \returns The minimum alignment offset must be. @@ -679,7 +786,10 @@ error_code map_file_pages(const Twine &path, off_t file_offset, size_t size, /// platform specific error_code. error_code unmap_file_pages(void *base, size_t size); - +/// Return the path to the main executable, given the value of argv[0] from +/// program startup and the address of main itself. In extremis, this function +/// may fail and return an empty path. +std::string getMainExecutable(const char *argv0, void *MainExecAddr); /// @} /// @name Iterators diff --git a/include/llvm/Support/FileUtilities.h b/include/llvm/Support/FileUtilities.h index c6feb9f..79c59e4 100644 --- a/include/llvm/Support/FileUtilities.h +++ b/include/llvm/Support/FileUtilities.h @@ -17,7 +17,6 @@ #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" -#include "llvm/Support/PathV1.h" namespace llvm { @@ -28,8 +27,8 @@ namespace llvm { /// option, it will set the string to an error message if an error occurs, or /// if the files are different. /// - int DiffFilesWithTolerance(const sys::PathWithStatus &FileA, - const sys::PathWithStatus &FileB, + int DiffFilesWithTolerance(StringRef FileA, + StringRef FileB, double AbsTol, double RelTol, std::string *Error = 0); diff --git a/include/llvm/Support/GraphWriter.h b/include/llvm/Support/GraphWriter.h index e867fae..62547dd 100644 --- a/include/llvm/Support/GraphWriter.h +++ b/include/llvm/Support/GraphWriter.h @@ -26,7 +26,6 @@ #include "llvm/ADT/GraphTraits.h" #include "llvm/Support/DOTGraphTraits.h" #include "llvm/Support/Path.h" -#include "llvm/Support/PathV1.h" #include "llvm/Support/raw_ostream.h" #include <cassert> #include <vector> @@ -51,7 +50,8 @@ namespace GraphProgram { }; } -void DisplayGraph(const sys::Path& Filename, bool wait=true, GraphProgram::Name program = GraphProgram::DOT); +void DisplayGraph(StringRef Filename, bool wait = true, + GraphProgram::Name program = GraphProgram::DOT); template<typename GraphType> class GraphWriter { @@ -319,34 +319,23 @@ raw_ostream &WriteGraph(raw_ostream &O, const GraphType &G, return O; } -template<typename GraphType> -sys::Path WriteGraph(const GraphType &G, const Twine &Name, - bool ShortNames = false, const Twine &Title = "") { - std::string ErrMsg; - sys::Path Filename = sys::Path::GetTemporaryDirectory(&ErrMsg); - if (Filename.isEmpty()) { - errs() << "Error: " << ErrMsg << "\n"; - return Filename; - } - Filename.appendComponent((Name + ".dot").str()); - if (Filename.makeUnique(true,&ErrMsg)) { - errs() << "Error: " << ErrMsg << "\n"; - return sys::Path(); - } +std::string createGraphFilename(const Twine &Name, int &FD); - errs() << "Writing '" << Filename.str() << "'... "; +template <typename GraphType> +std::string WriteGraph(const GraphType &G, const Twine &Name, + bool ShortNames = false, const Twine &Title = "") { + int FD; + std::string Filename = createGraphFilename(Name, FD); + raw_fd_ostream O(FD, /*shouldClose=*/ true); - std::string ErrorInfo; - raw_fd_ostream O(Filename.c_str(), ErrorInfo); - - if (ErrorInfo.empty()) { - llvm::WriteGraph(O, G, ShortNames, Title); - errs() << " done. \n"; - } else { - errs() << "error opening file '" << Filename.str() << "' for writing!\n"; - Filename.clear(); + if (FD == -1) { + errs() << "error opening file '" << Filename << "' for writing!\n"; + return ""; } + llvm::WriteGraph(O, G, ShortNames, Title); + errs() << " done. \n"; + return Filename; } @@ -357,9 +346,9 @@ template<typename GraphType> void ViewGraph(const GraphType &G, const Twine &Name, bool ShortNames = false, const Twine &Title = "", GraphProgram::Name Program = GraphProgram::DOT) { - sys::Path Filename = llvm::WriteGraph(G, Name, ShortNames, Title); + std::string Filename = llvm::WriteGraph(G, Name, ShortNames, Title); - if (Filename.isEmpty()) + if (Filename.empty()) return; DisplayGraph(Filename, true, Program); diff --git a/include/llvm/Support/IntegersSubset.h b/include/llvm/Support/IntegersSubset.h index ce34d78..64b79ee 100644 --- a/include/llvm/Support/IntegersSubset.h +++ b/include/llvm/Support/IntegersSubset.h @@ -361,7 +361,7 @@ public: FlatCollection.end(), CheckingVal) != FlatCollection.end(); - for (unsigned i = 0, e = getNumItems(); i < e; ++i) { + for (size_t i = 0, e = getNumItems(); i < e; ++i) { if (RangeLinks[i].first == RangeLinks[i].second) { if (*RangeLinks[i].first == CheckingVal) return true; @@ -382,7 +382,7 @@ public: } /// Return number of items (ranges) stored in set. - unsigned getNumItems() const { + size_t getNumItems() const { return RangeLinks.size(); } @@ -409,7 +409,7 @@ public: /// for range [<0>, <1>, <5>] the size will 3 unsigned getSize() const { APInt sz(((const APInt&)getItem(0).getLow()).getBitWidth(), 0); - for (unsigned i = 0, e = getNumItems(); i != e; ++i) { + for (size_t i = 0, e = getNumItems(); i != e; ++i) { const APInt Low = getItem(i).getLow(); const APInt High = getItem(i).getHigh(); APInt S = High - Low + 1; diff --git a/include/llvm/Support/LEB128.h b/include/llvm/Support/LEB128.h index 802b4f3..3d73792 100644 --- a/include/llvm/Support/LEB128.h +++ b/include/llvm/Support/LEB128.h @@ -20,7 +20,7 @@ namespace llvm { /// Utility function to encode a SLEB128 value to an output stream. -static inline void encodeSLEB128(int64_t Value, raw_ostream &OS) { +inline void encodeSLEB128(int64_t Value, raw_ostream &OS) { bool More; do { uint8_t Byte = Value & 0x7f; @@ -29,19 +29,19 @@ static inline void encodeSLEB128(int64_t Value, raw_ostream &OS) { More = !((((Value == 0 ) && ((Byte & 0x40) == 0)) || ((Value == -1) && ((Byte & 0x40) != 0)))); if (More) - Byte |= 0x80; // Mark this byte that that more bytes will follow. + Byte |= 0x80; // Mark this byte to show that more bytes will follow. OS << char(Byte); } while (More); } /// Utility function to encode a ULEB128 value to an output stream. -static inline void encodeULEB128(uint64_t Value, raw_ostream &OS, - unsigned Padding = 0) { +inline void encodeULEB128(uint64_t Value, raw_ostream &OS, + unsigned Padding = 0) { do { uint8_t Byte = Value & 0x7f; Value >>= 7; if (Value != 0 || Padding != 0) - Byte |= 0x80; // Mark this byte that that more bytes will follow. + Byte |= 0x80; // Mark this byte to show that more bytes will follow. OS << char(Byte); } while (Value != 0); @@ -55,14 +55,14 @@ static inline void encodeULEB128(uint64_t Value, raw_ostream &OS, /// Utility function to encode a ULEB128 value to a buffer. Returns /// the length in bytes of the encoded value. -static inline unsigned encodeULEB128(uint64_t Value, uint8_t *p, - unsigned Padding = 0) { +inline unsigned encodeULEB128(uint64_t Value, uint8_t *p, + unsigned Padding = 0) { uint8_t *orig_p = p; do { uint8_t Byte = Value & 0x7f; Value >>= 7; if (Value != 0 || Padding != 0) - Byte |= 0x80; // Mark this byte that that more bytes will follow. + Byte |= 0x80; // Mark this byte to show that more bytes will follow. *p++ = Byte; } while (Value != 0); @@ -77,7 +77,7 @@ static inline unsigned encodeULEB128(uint64_t Value, uint8_t *p, /// Utility function to decode a ULEB128 value. -static inline uint64_t decodeULEB128(const uint8_t *p, unsigned *n = 0) { +inline uint64_t decodeULEB128(const uint8_t *p, unsigned *n = 0) { const uint8_t *orig_p = p; uint64_t Value = 0; unsigned Shift = 0; diff --git a/include/llvm/Support/MathExtras.h b/include/llvm/Support/MathExtras.h index a65bfbc..00c6ad7 100644 --- a/include/llvm/Support/MathExtras.h +++ b/include/llvm/Support/MathExtras.h @@ -45,7 +45,9 @@ enum ZeroBehavior { template <typename T> typename enable_if_c<std::numeric_limits<T>::is_integer && !std::numeric_limits<T>::is_signed, std::size_t>::type -countTrailingZeros(T Val, ZeroBehavior /*ZB*/ = ZB_Width) { +countTrailingZeros(T Val, ZeroBehavior ZB = ZB_Width) { + (void)ZB; + if (!Val) return std::numeric_limits<T>::digits; if (Val & 0x1) @@ -78,7 +80,7 @@ inline std::size_t countTrailingZeros<uint32_t>(uint32_t Val, ZeroBehavior ZB) { if (ZB != ZB_Undefined && Val == 0) return 32; -#if __GNUC__ >= 4 +#if __has_builtin(__builtin_ctz) || __GNUC_PREREQ(4, 0) return __builtin_ctz(Val); #elif _MSC_VER unsigned long Index; @@ -93,7 +95,7 @@ inline std::size_t countTrailingZeros<uint64_t>(uint64_t Val, ZeroBehavior ZB) { if (ZB != ZB_Undefined && Val == 0) return 64; -#if __GNUC__ >= 4 +#if __has_builtin(__builtin_ctzll) || __GNUC_PREREQ(4, 0) return __builtin_ctzll(Val); #elif _MSC_VER unsigned long Index; @@ -114,7 +116,9 @@ inline std::size_t countTrailingZeros<uint64_t>(uint64_t Val, ZeroBehavior ZB) { template <typename T> typename enable_if_c<std::numeric_limits<T>::is_integer && !std::numeric_limits<T>::is_signed, std::size_t>::type -countLeadingZeros(T Val, ZeroBehavior /*ZB*/ = ZB_Width) { +countLeadingZeros(T Val, ZeroBehavior ZB = ZB_Width) { + (void)ZB; + if (!Val) return std::numeric_limits<T>::digits; @@ -142,7 +146,7 @@ inline std::size_t countLeadingZeros<uint32_t>(uint32_t Val, ZeroBehavior ZB) { if (ZB != ZB_Undefined && Val == 0) return 32; -#if __GNUC__ >= 4 +#if __has_builtin(__builtin_clz) || __GNUC_PREREQ(4, 0) return __builtin_clz(Val); #elif _MSC_VER unsigned long Index; @@ -157,7 +161,7 @@ inline std::size_t countLeadingZeros<uint64_t>(uint64_t Val, ZeroBehavior ZB) { if (ZB != ZB_Undefined && Val == 0) return 64; -#if __GNUC__ >= 4 +#if __has_builtin(__builtin_clzll) || __GNUC_PREREQ(4, 0) return __builtin_clzll(Val); #elif _MSC_VER unsigned long Index; diff --git a/include/llvm/Support/MemoryBuffer.h b/include/llvm/Support/MemoryBuffer.h index 0cce726..4f28da4 100644 --- a/include/llvm/Support/MemoryBuffer.h +++ b/include/llvm/Support/MemoryBuffer.h @@ -74,13 +74,18 @@ public: int64_t FileSize = -1, bool RequiresNullTerminator = true); - /// getOpenFile - Given an already-open file descriptor, read the file and - /// return a MemoryBuffer. + /// Given an already-open file descriptor, map some slice of it into a + /// MemoryBuffer. The slice is specified by an \p Offset and \p MapSize. + /// Since this is in the middle of a file, the buffer is not null terminated. + static error_code getOpenFileSlice(int FD, const char *Filename, + OwningPtr<MemoryBuffer> &Result, + uint64_t MapSize, int64_t Offset); + + /// Given an already-open file descriptor, read the file and return a + /// MemoryBuffer. static error_code getOpenFile(int FD, const char *Filename, - OwningPtr<MemoryBuffer> &result, - uint64_t FileSize = -1, - uint64_t MapSize = -1, - int64_t Offset = 0, + OwningPtr<MemoryBuffer> &Result, + uint64_t FileSize, bool RequiresNullTerminator = true); /// getMemBuffer - Open the specified memory range as a MemoryBuffer. Note @@ -119,11 +124,7 @@ public: static error_code getFileOrSTDIN(StringRef Filename, OwningPtr<MemoryBuffer> &result, int64_t FileSize = -1); - static error_code getFileOrSTDIN(const char *Filename, - OwningPtr<MemoryBuffer> &result, - int64_t FileSize = -1); - - + //===--------------------------------------------------------------------===// // Provided for performance analysis. //===--------------------------------------------------------------------===// diff --git a/include/llvm/Support/Path.h b/include/llvm/Support/Path.h index a70498a..f9a65e5 100644 --- a/include/llvm/Support/Path.h +++ b/include/llvm/Support/Path.h @@ -111,6 +111,7 @@ inline reverse_iterator rend(StringRef path) { /// @code /// directory/filename.cpp => directory/ /// directory/ => directory +/// filename.cpp => <empty> /// / => / /// @endcode /// diff --git a/include/llvm/Support/PathV1.h b/include/llvm/Support/PathV1.h deleted file mode 100644 index eaf2550..0000000 --- a/include/llvm/Support/PathV1.h +++ /dev/null @@ -1,557 +0,0 @@ -//===- llvm/Support/PathV1.h - Path Operating System Concept ----*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file declares the llvm::sys::Path class. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_SUPPORT_PATHV1_H -#define LLVM_SUPPORT_PATHV1_H - -#include "llvm/ADT/StringRef.h" -#include "llvm/Support/Compiler.h" -#include "llvm/Support/TimeValue.h" -#include <set> -#include <string> -#include <vector> - -#define LLVM_PATH_DEPRECATED_MSG(replacement) \ - "PathV1 has been deprecated and will be removed as soon as all LLVM and" \ - " Clang clients have been moved over to PathV2. Please use `" #replacement \ - "` from PathV2 instead." - -namespace llvm { -namespace sys { - - /// This structure provides basic file system information about a file. It - /// is patterned after the stat(2) Unix operating system call but made - /// platform independent and eliminates many of the unix-specific fields. - /// However, to support llvm-ar, the mode, user, and group fields are - /// retained. These pertain to unix security and may not have a meaningful - /// value on non-Unix platforms. However, the other fields should - /// always be applicable on all platforms. The structure is filled in by - /// the PathWithStatus class. - /// @brief File status structure - class FileStatus { - public: - uint64_t fileSize; ///< Size of the file in bytes - TimeValue modTime; ///< Time of file's modification - uint32_t mode; ///< Mode of the file, if applicable - uint32_t user; ///< User ID of owner, if applicable - uint32_t group; ///< Group ID of owner, if applicable - uint64_t uniqueID; ///< A number to uniquely ID this file - bool isDir : 1; ///< True if this is a directory. - bool isFile : 1; ///< True if this is a file. - - FileStatus() : fileSize(0), modTime(0,0), mode(0777), user(999), - group(999), uniqueID(0), isDir(false), isFile(false) { } - - TimeValue getTimestamp() const { return modTime; } - uint64_t getSize() const { return fileSize; } - uint32_t getMode() const { return mode; } - uint32_t getUser() const { return user; } - uint32_t getGroup() const { return group; } - uint64_t getUniqueID() const { return uniqueID; } - }; - - /// This class provides an abstraction for the path to a file or directory - /// in the operating system's filesystem and provides various basic operations - /// on it. Note that this class only represents the name of a path to a file - /// or directory which may or may not be valid for a given machine's file - /// system. The class is patterned after the java.io.File class with various - /// extensions and several omissions (not relevant to LLVM). A Path object - /// ensures that the path it encapsulates is syntactically valid for the - /// operating system it is running on but does not ensure correctness for - /// any particular file system. That is, a syntactically valid path might - /// specify path components that do not exist in the file system and using - /// such a Path to act on the file system could produce errors. There is one - /// invalid Path value which is permitted: the empty path. The class should - /// never allow a syntactically invalid non-empty path name to be assigned. - /// Empty paths are required in order to indicate an error result in some - /// situations. If the path is empty, the isValid operation will return - /// false. All operations will fail if isValid is false. Operations that - /// change the path will either return false if it would cause a syntactically - /// invalid path name (in which case the Path object is left unchanged) or - /// throw an std::string exception indicating the error. The methods are - /// grouped into four basic categories: Path Accessors (provide information - /// about the path without accessing disk), Disk Accessors (provide - /// information about the underlying file or directory), Path Mutators - /// (change the path information, not the disk), and Disk Mutators (change - /// the disk file/directory referenced by the path). The Disk Mutator methods - /// all have the word "disk" embedded in their method name to reinforce the - /// notion that the operation modifies the file system. - /// @since 1.4 - /// @brief An abstraction for operating system paths. - class Path { - /// @name Constructors - /// @{ - public: - /// Construct a path to a unique temporary directory that is created in - /// a "standard" place for the operating system. The directory is - /// guaranteed to be created on exit from this function. If the directory - /// cannot be created, the function will throw an exception. - /// @returns an invalid path (empty) on error - /// @param ErrMsg Optional place for an error message if an error occurs - /// @brief Construct a path to an new, unique, existing temporary - /// directory. - static Path GetTemporaryDirectory(std::string* ErrMsg = 0); - - /// Construct a path to the current directory for the current process. - /// @returns The current working directory. - /// @brief Returns the current working directory. - static Path GetCurrentDirectory(); - - /// Return the suffix commonly used on file names that contain an - /// executable. - /// @returns The executable file suffix for the current platform. - /// @brief Return the executable file suffix. - static StringRef GetEXESuffix(); - - /// GetMainExecutable - Return the path to the main executable, given the - /// value of argv[0] from program startup and the address of main itself. - /// In extremis, this function may fail and return an empty path. - static Path GetMainExecutable(const char *argv0, void *MainAddr); - - /// This is one of the very few ways in which a path can be constructed - /// with a syntactically invalid name. The only *legal* invalid name is an - /// empty one. Other invalid names are not permitted. Empty paths are - /// provided so that they can be used to indicate null or error results in - /// other lib/System functionality. - /// @brief Construct an empty (and invalid) path. - Path() : path() {} - Path(const Path &that) : path(that.path) {} - - /// This constructor will accept a char* or std::string as a path. No - /// checking is done on this path to determine if it is valid. To - /// determine validity of the path, use the isValid method. - /// @param p The path to assign. - /// @brief Construct a Path from a string. - explicit Path(StringRef p); - - /// This constructor will accept a character range as a path. No checking - /// is done on this path to determine if it is valid. To determine - /// validity of the path, use the isValid method. - /// @param StrStart A pointer to the first character of the path name - /// @param StrLen The length of the path name at StrStart - /// @brief Construct a Path from a string. - Path(const char *StrStart, unsigned StrLen); - - /// @} - /// @name Operators - /// @{ - public: - /// Makes a copy of \p that to \p this. - /// @returns \p this - /// @brief Assignment Operator - Path &operator=(const Path &that) { - path = that.path; - return *this; - } - - /// Makes a copy of \p that to \p this. - /// @param that A StringRef denoting the path - /// @returns \p this - /// @brief Assignment Operator - Path &operator=(StringRef that); - - /// Compares \p this Path with \p that Path for equality. - /// @returns true if \p this and \p that refer to the same thing. - /// @brief Equality Operator - bool operator==(const Path &that) const; - - /// Compares \p this Path with \p that Path for inequality. - /// @returns true if \p this and \p that refer to different things. - /// @brief Inequality Operator - bool operator!=(const Path &that) const { return !(*this == that); } - - /// Determines if \p this Path is less than \p that Path. This is required - /// so that Path objects can be placed into ordered collections (e.g. - /// std::map). The comparison is done lexicographically as defined by - /// the std::string::compare method. - /// @returns true if \p this path is lexicographically less than \p that. - /// @brief Less Than Operator - bool operator<(const Path& that) const; - - /// @} - /// @name Path Accessors - /// @{ - public: - /// This function will use an operating system specific algorithm to - /// determine if the current value of \p this is a syntactically valid - /// path name for the operating system. The path name does not need to - /// exist, validity is simply syntactical. Empty paths are always invalid. - /// @returns true iff the path name is syntactically legal for the - /// host operating system. - /// @brief Determine if a path is syntactically valid or not. - bool isValid() const; - - /// This function determines if the contents of the path name are empty. - /// That is, the path name has a zero length. This does NOT determine if - /// if the file is empty. To get the length of the file itself, Use the - /// PathWithStatus::getFileStatus() method and then the getSize() method - /// on the returned FileStatus object. - /// @returns true iff the path is empty. - /// @brief Determines if the path name is empty (invalid). - bool isEmpty() const { return path.empty(); } - - - - /// Obtain a 'C' string for the path name. - /// @returns a 'C' string containing the path name. - /// @brief Returns the path as a C string. - const char *c_str() const { return path.c_str(); } - const std::string &str() const { return path; } - - - /// size - Return the length in bytes of this path name. - size_t size() const { return path.size(); } - - /// empty - Returns true if the path is empty. - unsigned empty() const { return path.empty(); } - - /// @} - /// @name Disk Accessors - /// @{ - public: - /// This function determines if the path name in the object references an - /// archive file by looking at its magic number. - /// @returns true if the file starts with the magic number for an archive - /// file. - /// @brief Determine if the path references an archive file. - bool isArchive() const; - - /// This function determines if the path name in the object references a - /// native Dynamic Library (shared library, shared object) by looking at - /// the file's magic number. The Path object must reference a file, not a - /// directory. - /// @returns true if the file starts with the magic number for a native - /// shared library. - /// @brief Determine if the path references a dynamic library. - bool isDynamicLibrary() const; - - /// This function determines if the path name in the object references a - /// native object file by looking at it's magic number. The term object - /// file is defined as "an organized collection of separate, named - /// sequences of binary data." This covers the obvious file formats such - /// as COFF and ELF, but it also includes llvm ir bitcode, archives, - /// libraries, etc... - /// @returns true if the file starts with the magic number for an object - /// file. - /// @brief Determine if the path references an object file. - bool isObjectFile() const; - - /// This function determines if the path name references an existing file - /// or directory in the file system. - /// @returns true if the pathname references an existing file or - /// directory. - /// @brief Determines if the path is a file or directory in - /// the file system. - LLVM_ATTRIBUTE_DEPRECATED(bool exists() const, - LLVM_PATH_DEPRECATED_MSG(fs::exists)); - - /// This function determines if the path name references an - /// existing directory. - /// @returns true if the pathname references an existing directory. - /// @brief Determines if the path is a directory in the file system. - LLVM_ATTRIBUTE_DEPRECATED(bool isDirectory() const, - LLVM_PATH_DEPRECATED_MSG(fs::is_directory)); - - /// This function determines if the path name references an - /// existing symbolic link. - /// @returns true if the pathname references an existing symlink. - /// @brief Determines if the path is a symlink in the file system. - LLVM_ATTRIBUTE_DEPRECATED(bool isSymLink() const, - LLVM_PATH_DEPRECATED_MSG(fs::is_symlink)); - - /// This function determines if the path name references a readable file - /// or directory in the file system. This function checks for - /// the existence and readability (by the current program) of the file - /// or directory. - /// @returns true if the pathname references a readable file. - /// @brief Determines if the path is a readable file or directory - /// in the file system. - bool canRead() const; - - /// This function determines if the path name references a writable file - /// or directory in the file system. This function checks for the - /// existence and writability (by the current program) of the file or - /// directory. - /// @returns true if the pathname references a writable file. - /// @brief Determines if the path is a writable file or directory - /// in the file system. - bool canWrite() const; - - /// This function checks that what we're trying to work only on a regular - /// file. Check for things like /dev/null, any block special file, or - /// other things that aren't "regular" regular files. - /// @returns true if the file is S_ISREG. - /// @brief Determines if the file is a regular file - bool isRegularFile() const; - - /// This function determines if the path name references an executable - /// file in the file system. This function checks for the existence and - /// executability (by the current program) of the file. - /// @returns true if the pathname references an executable file. - /// @brief Determines if the path is an executable file in the file - /// system. - bool canExecute() const; - - /// This function builds a list of paths that are the names of the - /// files and directories in a directory. - /// @returns true if an error occurs, true otherwise - /// @brief Build a list of directory's contents. - bool getDirectoryContents( - std::set<Path> &paths, ///< The resulting list of file & directory names - std::string* ErrMsg ///< Optional place to return an error message. - ) const; - - /// @} - /// @name Path Mutators - /// @{ - public: - /// The path name is cleared and becomes empty. This is an invalid - /// path name but is the *only* invalid path name. This is provided - /// so that path objects can be used to indicate the lack of a - /// valid path being found. - /// @brief Make the path empty. - void clear() { path.clear(); } - - /// This method sets the Path object to \p unverified_path. This can fail - /// if the \p unverified_path does not pass the syntactic checks of the - /// isValid() method. If verification fails, the Path object remains - /// unchanged and false is returned. Otherwise true is returned and the - /// Path object takes on the path value of \p unverified_path - /// @returns true if the path was set, false otherwise. - /// @param unverified_path The path to be set in Path object. - /// @brief Set a full path from a StringRef - bool set(StringRef unverified_path); - - /// One path component is removed from the Path. If only one component is - /// present in the path, the Path object becomes empty. If the Path object - /// is empty, no change is made. - /// @returns false if the path component could not be removed. - /// @brief Removes the last directory component of the Path. - bool eraseComponent(); - - /// The \p component is added to the end of the Path if it is a legal - /// name for the operating system. A directory separator will be added if - /// needed. - /// @returns false if the path component could not be added. - /// @brief Appends one path component to the Path. - bool appendComponent(StringRef component); - - /// A period and the \p suffix are appended to the end of the pathname. - /// When the \p suffix is empty, no action is performed. - /// @brief Adds a period and the \p suffix to the end of the pathname. - void appendSuffix(StringRef suffix); - - /// The suffix of the filename is erased. The suffix begins with and - /// includes the last . character in the filename after the last directory - /// separator and extends until the end of the name. If no . character is - /// after the last directory separator, then the file name is left - /// unchanged (i.e. it was already without a suffix) but the function - /// returns false. - /// @returns false if there was no suffix to remove, true otherwise. - /// @brief Remove the suffix from a path name. - bool eraseSuffix(); - - /// The current Path name is made unique in the file system. Upon return, - /// the Path will have been changed to make a unique file in the file - /// system or it will not have been changed if the current path name is - /// already unique. - /// @throws std::string if an unrecoverable error occurs. - /// @brief Make the current path name unique in the file system. - bool makeUnique( bool reuse_current /*= true*/, std::string* ErrMsg ); - - /// The current Path name is made absolute by prepending the - /// current working directory if necessary. - LLVM_ATTRIBUTE_DEPRECATED( - void makeAbsolute(), - LLVM_PATH_DEPRECATED_MSG(fs::make_absolute)); - - /// @} - /// @name Disk Mutators - /// @{ - public: - /// This method attempts to make the file referenced by the Path object - /// available for reading so that the canRead() method will return true. - /// @brief Make the file readable; - bool makeReadableOnDisk(std::string* ErrMsg = 0); - - /// This method attempts to make the file referenced by the Path object - /// available for writing so that the canWrite() method will return true. - /// @brief Make the file writable; - bool makeWriteableOnDisk(std::string* ErrMsg = 0); - - /// This method allows the last modified time stamp and permission bits - /// to be set on the disk object referenced by the Path. - /// @throws std::string if an error occurs. - /// @returns true on error. - /// @brief Set the status information. - bool setStatusInfoOnDisk(const FileStatus &SI, - std::string *ErrStr = 0) const; - - /// This method attempts to create a directory in the file system with the - /// same name as the Path object. The \p create_parents parameter controls - /// whether intermediate directories are created or not. if \p - /// create_parents is true, then an attempt will be made to create all - /// intermediate directories, as needed. If \p create_parents is false, - /// then only the final directory component of the Path name will be - /// created. The created directory will have no entries. - /// @returns true if the directory could not be created, false otherwise - /// @brief Create the directory this Path refers to. - bool createDirectoryOnDisk( - bool create_parents = false, ///< Determines whether non-existent - ///< directory components other than the last one (the "parents") - ///< are created or not. - std::string* ErrMsg = 0 ///< Optional place to put error messages. - ); - - /// This is like createFile except that it creates a temporary file. A - /// unique temporary file name is generated based on the contents of - /// \p this before the call. The new name is assigned to \p this and the - /// file is created. Note that this will both change the Path object - /// *and* create the corresponding file. This function will ensure that - /// the newly generated temporary file name is unique in the file system. - /// @returns true if the file couldn't be created, false otherwise. - /// @brief Create a unique temporary file - bool createTemporaryFileOnDisk( - bool reuse_current = false, ///< When set to true, this parameter - ///< indicates that if the current file name does not exist then - ///< it will be used without modification. - std::string* ErrMsg = 0 ///< Optional place to put error messages - ); - - /// This method renames the file referenced by \p this as \p newName. The - /// file referenced by \p this must exist. The file referenced by - /// \p newName does not need to exist. - /// @returns true on error, false otherwise - /// @brief Rename one file as another. - bool renamePathOnDisk(const Path& newName, std::string* ErrMsg); - - /// This method attempts to destroy the file or directory named by the - /// last component of the Path. If the Path refers to a directory and the - /// \p destroy_contents is false, an attempt will be made to remove just - /// the directory (the final Path component). If \p destroy_contents is - /// true, an attempt will be made to remove the entire contents of the - /// directory, recursively. If the Path refers to a file, the - /// \p destroy_contents parameter is ignored. - /// @param destroy_contents Indicates whether the contents of a destroyed - /// @param Err An optional string to receive an error message. - /// directory should also be destroyed (recursively). - /// @returns false if the file/directory was destroyed, true on error. - /// @brief Removes the file or directory from the filesystem. - bool eraseFromDisk(bool destroy_contents = false, - std::string *Err = 0) const; - - /// @} - /// @name Data - /// @{ - protected: - // Our win32 implementation relies on this string being mutable. - mutable std::string path; ///< Storage for the path name. - - - /// @} - }; - - /// This class is identical to Path class except it allows you to obtain the - /// file status of the Path as well. The reason for the distinction is one of - /// efficiency. First, the file status requires additional space and the space - /// is incorporated directly into PathWithStatus without an additional malloc. - /// Second, obtaining status information is an expensive operation on most - /// operating systems so we want to be careful and explicit about where we - /// allow this operation in LLVM. - /// @brief Path with file status class. - class PathWithStatus : public Path { - /// @name Constructors - /// @{ - public: - /// @brief Default constructor - PathWithStatus() : Path(), status(), fsIsValid(false) {} - - /// @brief Copy constructor - PathWithStatus(const PathWithStatus &that) - : Path(static_cast<const Path&>(that)), status(that.status), - fsIsValid(that.fsIsValid) {} - - /// This constructor allows construction from a Path object - /// @brief Path constructor - PathWithStatus(const Path &other) - : Path(other), status(), fsIsValid(false) {} - - /// This constructor will accept a char* or std::string as a path. No - /// checking is done on this path to determine if it is valid. To - /// determine validity of the path, use the isValid method. - /// @brief Construct a Path from a string. - explicit PathWithStatus( - StringRef p ///< The path to assign. - ) : Path(p), status(), fsIsValid(false) {} - - /// This constructor will accept a character range as a path. No checking - /// is done on this path to determine if it is valid. To determine - /// validity of the path, use the isValid method. - /// @brief Construct a Path from a string. - explicit PathWithStatus( - const char *StrStart, ///< Pointer to the first character of the path - unsigned StrLen ///< Length of the path. - ) : Path(StrStart, StrLen), status(), fsIsValid(false) {} - - /// Makes a copy of \p that to \p this. - /// @returns \p this - /// @brief Assignment Operator - PathWithStatus &operator=(const PathWithStatus &that) { - static_cast<Path&>(*this) = static_cast<const Path&>(that); - status = that.status; - fsIsValid = that.fsIsValid; - return *this; - } - - /// Makes a copy of \p that to \p this. - /// @returns \p this - /// @brief Assignment Operator - PathWithStatus &operator=(const Path &that) { - static_cast<Path&>(*this) = static_cast<const Path&>(that); - fsIsValid = false; - return *this; - } - - /// @} - /// @name Methods - /// @{ - public: - /// This function returns status information about the file. The type of - /// path (file or directory) is updated to reflect the actual contents - /// of the file system. - /// @returns 0 on failure, with Error explaining why (if non-zero), - /// otherwise returns a pointer to a FileStatus structure on success. - /// @brief Get file status. - const FileStatus *getFileStatus( - bool forceUpdate = false, ///< Force an update from the file system - std::string *Error = 0 ///< Optional place to return an error msg. - ) const; - - /// @} - /// @name Data - /// @{ - private: - mutable FileStatus status; ///< Status information. - mutable bool fsIsValid; ///< Whether we've obtained it or not - - /// @} - }; - - /// This is the OS-specific path separator: a colon on Unix or a semicolon - /// on Windows. - extern const char PathSeparator; -} - -} - -#endif diff --git a/include/llvm/Support/PatternMatch.h b/include/llvm/Support/PatternMatch.h index 95d9d78..b1732b2 100644 --- a/include/llvm/Support/PatternMatch.h +++ b/include/llvm/Support/PatternMatch.h @@ -696,10 +696,17 @@ m_ZExt(const OpTy &Op) { /// m_UIToFP template<typename OpTy> inline CastClass_match<OpTy, Instruction::UIToFP> -m_UIToFp(const OpTy &Op) { +m_UIToFP(const OpTy &Op) { return CastClass_match<OpTy, Instruction::UIToFP>(Op); } +/// m_SIToFP +template<typename OpTy> +inline CastClass_match<OpTy, Instruction::SIToFP> +m_SIToFP(const OpTy &Op) { + return CastClass_match<OpTy, Instruction::SIToFP>(Op); +} + //===----------------------------------------------------------------------===// // Matchers for unary operators // diff --git a/include/llvm/Support/Program.h b/include/llvm/Support/Program.h index 08a64de..5134351 100644 --- a/include/llvm/Support/Program.h +++ b/include/llvm/Support/Program.h @@ -16,132 +16,81 @@ #include "llvm/ADT/ArrayRef.h" #include "llvm/Support/Path.h" -#include "llvm/Support/PathV1.h" +#include "llvm/Support/system_error.h" namespace llvm { class error_code; namespace sys { - // TODO: Add operations to communicate with the process, redirect its I/O, - // etc. - - /// This class provides an abstraction for programs that are executable by the - /// operating system. It provides a platform generic way to find executable - /// programs from the path and to execute them in various ways. The sys::Path - /// class is used to specify the location of the Program. - /// @since 1.4 - /// @brief An abstraction for finding and executing programs. - class Program { - /// Opaque handle for target specific data. - void *Data_; - - // Noncopyable. - Program(const Program& other) LLVM_DELETED_FUNCTION; - Program& operator=(const Program& other) LLVM_DELETED_FUNCTION; - - /// @name Methods - /// @{ - - Program(); - ~Program(); + /// This is the OS-specific separator for PATH like environment variables: + // a colon on Unix or a semicolon on Windows. +#if defined(LLVM_ON_UNIX) + const char EnvPathSeparator = ':'; +#elif defined (LLVM_ON_WIN32) + const char EnvPathSeparator = ';'; +#endif - /// This function executes the program using the \p arguments provided. The - /// invoked program will inherit the stdin, stdout, and stderr file - /// descriptors, the environment and other configuration settings of the - /// invoking program. If Path::executable() does not return true when this - /// function is called then a std::string is thrown. - /// @returns false in case of error, true otherwise. - /// @see FindProgramByName - /// @brief Executes the program with the given set of \p args. - bool Execute - ( const Path& path, ///< sys::Path object providing the path of the - ///< program to be executed. It is presumed this is the result of - ///< the FindProgramByName method. - const char** args, ///< A vector of strings that are passed to the + /// This static constructor (factory) will attempt to locate a program in + /// the operating system's file system using some pre-determined set of + /// locations to search (e.g. the PATH on Unix). Paths with slashes are + /// returned unmodified. + /// @returns A Path object initialized to the path of the program or a + /// Path object that is empty (invalid) if the program could not be found. + /// @brief Construct a Program by finding it by name. + std::string FindProgramByName(const std::string& name); + + // These functions change the specified standard stream (stdin, stdout, or + // stderr) to binary mode. They return errc::success if the specified stream + // was changed. Otherwise a platform dependent error is returned. + error_code ChangeStdinToBinary(); + error_code ChangeStdoutToBinary(); + error_code ChangeStderrToBinary(); + + /// This function executes the program using the arguments provided. The + /// invoked program will inherit the stdin, stdout, and stderr file + /// descriptors, the environment and other configuration settings of the + /// invoking program. + /// This function waits the program to finish. + /// @returns an integer result code indicating the status of the program. + /// A zero or positive value indicates the result code of the program. + /// -1 indicates failure to execute + /// -2 indicates a crash during execution or timeout + int ExecuteAndWait( + StringRef Program, ///< Path of the program to be executed. It is + /// presumed this is the result of the FindProgramByName method. + const char **args, ///< A vector of strings that are passed to the ///< program. The first element should be the name of the program. ///< The list *must* be terminated by a null char* entry. - const char ** env = 0, ///< An optional vector of strings to use for + const char **env = 0, ///< An optional vector of strings to use for ///< the program's environment. If not provided, the current program's ///< environment will be used. - const sys::Path** redirects = 0, ///< An optional array of pointers to - ///< Paths. If the array is null, no redirection is done. The array - ///< should have a size of at least three. If the pointer in the array - ///< are not null, then the inferior process's stdin(0), stdout(1), - ///< and stderr(2) will be redirected to the corresponding Paths. - ///< When an empty Path is passed in, the corresponding file + const StringRef **redirects = 0, ///< An optional array of pointers to + ///< paths. If the array is null, no redirection is done. The array + ///< should have a size of at least three. The inferior process's + ///< stdin(0), stdout(1), and stderr(2) will be redirected to the + ///< corresponding paths. + ///< When an empty path is passed in, the corresponding file ///< descriptor will be disconnected (ie, /dev/null'd) in a portable ///< way. + unsigned secondsToWait = 0, ///< If non-zero, this specifies the amount + ///< of time to wait for the child process to exit. If the time + ///< expires, the child is killed and this call returns. If zero, + ///< this function will wait until the child finishes or forever if + ///< it doesn't. unsigned memoryLimit = 0, ///< If non-zero, this specifies max. amount ///< of memory can be allocated by process. If memory usage will be ///< higher limit, the child is killed and this call returns. If zero ///< - no memory limit. - std::string* ErrMsg = 0 ///< If non-zero, provides a pointer to a string + std::string *ErrMsg = 0, ///< If non-zero, provides a pointer to a string ///< instance in which error messages will be returned. If the string ///< is non-empty upon return an error occurred while invoking the ///< program. - ); - - /// This function waits for the program to exit. This function will block - /// the current program until the invoked program exits. - /// @returns an integer result code indicating the status of the program. - /// A zero or positive value indicates the result code of the program. - /// -1 indicates failure to execute - /// -2 indicates a crash during execution or timeout - /// @see Execute - /// @brief Waits for the program to exit. - int Wait - ( const Path& path, ///< The path to the child process executable. - unsigned secondsToWait, ///< If non-zero, this specifies the amount - ///< of time to wait for the child process to exit. If the time - ///< expires, the child is killed and this call returns. If zero, - ///< this function will wait until the child finishes or forever if - ///< it doesn't. - std::string* ErrMsg ///< If non-zero, provides a pointer to a string - ///< instance in which error messages will be returned. If the string - ///< is non-empty upon return an error occurred while waiting. - ); - - public: - /// This static constructor (factory) will attempt to locate a program in - /// the operating system's file system using some pre-determined set of - /// locations to search (e.g. the PATH on Unix). Paths with slashes are - /// returned unmodified. - /// @returns A Path object initialized to the path of the program or a - /// Path object that is empty (invalid) if the program could not be found. - /// @brief Construct a Program by finding it by name. - static Path FindProgramByName(const std::string& name); - - // These methods change the specified standard stream (stdin, stdout, or - // stderr) to binary mode. They return errc::success if the specified stream - // was changed. Otherwise a platform dependent error is returned. - static error_code ChangeStdinToBinary(); - static error_code ChangeStdoutToBinary(); - static error_code ChangeStderrToBinary(); - - /// A convenience function equivalent to Program prg; prg.Execute(..); - /// prg.Wait(..); - /// @see Execute, Wait - static int ExecuteAndWait(const Path& path, - const char** args, - const char ** env = 0, - const sys::Path** redirects = 0, - unsigned secondsToWait = 0, - unsigned memoryLimit = 0, - std::string* ErrMsg = 0, - bool *ExecutionFailed = 0); - - /// A convenience function equivalent to Program prg; prg.Execute(..); - /// @see Execute - static void ExecuteNoWait(const Path& path, - const char** args, - const char ** env = 0, - const sys::Path** redirects = 0, - unsigned memoryLimit = 0, - std::string* ErrMsg = 0); - - /// @} + bool *ExecutionFailed = 0); - }; + /// Similar to ExecuteAndWait, but return immediately. + void ExecuteNoWait(StringRef Program, const char **args, const char **env = 0, + const StringRef **redirects = 0, unsigned memoryLimit = 0, + std::string *ErrMsg = 0); // Return true if the given arguments fit within system-specific // argument length limits. diff --git a/include/llvm/Support/Regex.h b/include/llvm/Support/Regex.h index 82df2c6..3d071be 100644 --- a/include/llvm/Support/Regex.h +++ b/include/llvm/Support/Regex.h @@ -77,6 +77,10 @@ namespace llvm { /// string. std::string sub(StringRef Repl, StringRef String, std::string *Error = 0); + /// \brief If this function returns true, ^Str$ is an extended regular + /// expression that matches Str and only Str. + static bool isLiteralERE(StringRef Str); + private: struct llvm_regex *preg; int error; diff --git a/include/llvm/Support/Registry.h b/include/llvm/Support/Registry.h index 29eafb6..073becd 100644 --- a/include/llvm/Support/Registry.h +++ b/include/llvm/Support/Registry.h @@ -14,6 +14,8 @@ #ifndef LLVM_SUPPORT_REGISTRY_H #define LLVM_SUPPORT_REGISTRY_H +#include "llvm/Support/Compiler.h" + namespace llvm { /// A simple registry entry which provides only a name, description, and /// no-argument constructor. diff --git a/include/llvm/Support/Signals.h b/include/llvm/Support/Signals.h index c0a489a..58ed175 100644 --- a/include/llvm/Support/Signals.h +++ b/include/llvm/Support/Signals.h @@ -16,7 +16,6 @@ #define LLVM_SUPPORT_SIGNALS_H #include "llvm/Support/Path.h" -#include "llvm/Support/PathV1.h" #include <cstdio> namespace llvm { @@ -29,11 +28,11 @@ namespace sys { /// This function registers signal handlers to ensure that if a signal gets /// delivered that the named file is removed. /// @brief Remove a file if a fatal signal occurs. - bool RemoveFileOnSignal(const Path &Filename, std::string* ErrMsg = 0); + bool RemoveFileOnSignal(StringRef Filename, std::string* ErrMsg = 0); /// This function removes a file from the list of files to be removed on /// signal delivery. - void DontRemoveFileOnSignal(const Path &Filename); + void DontRemoveFileOnSignal(StringRef Filename); /// When an error signal (such as SIBABRT or SIGSEGV) is delivered to the /// process, print a stack trace and then exit. diff --git a/include/llvm/Support/SourceMgr.h b/include/llvm/Support/SourceMgr.h index d67914a..5b33d42 100644 --- a/include/llvm/Support/SourceMgr.h +++ b/include/llvm/Support/SourceMgr.h @@ -39,7 +39,7 @@ public: DK_Warning, DK_Note }; - + /// DiagHandlerTy - Clients that want to handle their own diagnostics in a /// custom way can register a function pointer+context as a diagnostic /// handler. It gets called each time PrintMessage is invoked. @@ -98,7 +98,7 @@ public: return Buffers[i].Buffer; } - unsigned getNumBuffers() const { + size_t getNumBuffers() const { return Buffers.size(); } @@ -109,20 +109,20 @@ public: /// AddNewSourceBuffer - Add a new source buffer to this source manager. This /// takes ownership of the memory buffer. - unsigned AddNewSourceBuffer(MemoryBuffer *F, SMLoc IncludeLoc) { + size_t AddNewSourceBuffer(MemoryBuffer *F, SMLoc IncludeLoc) { SrcBuffer NB; NB.Buffer = F; NB.IncludeLoc = IncludeLoc; Buffers.push_back(NB); - return Buffers.size()-1; + return Buffers.size() - 1; } /// AddIncludeFile - Search for a file with the specified name in the current /// directory or in one of the IncludeDirs. If no file is found, this returns /// ~0, otherwise it returns the buffer ID of the stacked file. /// The full path to the included file can be found in IncludedFile. - unsigned AddIncludeFile(const std::string &Filename, SMLoc IncludeLoc, - std::string &IncludedFile); + size_t AddIncludeFile(const std::string &Filename, SMLoc IncludeLoc, + std::string &IncludedFile); /// FindBufferContainingLoc - Return the ID of the buffer containing the /// specified location, returning -1 if not found. @@ -221,7 +221,7 @@ public: SMDiagnostic(StringRef filename, SourceMgr::DiagKind Knd, StringRef Msg) : SM(0), Filename(filename), LineNo(-1), ColumnNo(-1), Kind(Knd), Message(Msg) {} - + // Diagnostic with a location. SMDiagnostic(const SourceMgr &sm, SMLoc L, StringRef FN, int Line, int Col, SourceMgr::DiagKind Kind, diff --git a/include/llvm/Support/SystemUtils.h b/include/llvm/Support/SystemUtils.h index 399aee5..d2d08b2 100644 --- a/include/llvm/Support/SystemUtils.h +++ b/include/llvm/Support/SystemUtils.h @@ -19,7 +19,6 @@ namespace llvm { class raw_ostream; - namespace sys { class Path; } /// Determine if the raw_ostream provided is connected to a terminal. If so, /// generate a warning message to errs() advising against display of bitcode @@ -30,15 +29,6 @@ bool CheckBitcodeOutputToConsole( bool print_warning = true ///< Control whether warnings are printed ); -/// PrependMainExecutablePath - Prepend the path to the program being executed -/// to \p ExeName, given the value of argv[0] and the address of main() -/// itself. This allows us to find another LLVM tool if it is built in the same -/// directory. An empty string is returned on error; note that this function -/// just mainpulates the path and doesn't check for executability. -/// @brief Find a named executable. -sys::Path PrependMainExecutablePath(const std::string &ExeName, - const char *Argv0, void *MainAddr); - } // End llvm namespace #endif diff --git a/include/llvm/Support/TimeValue.h b/include/llvm/Support/TimeValue.h index 4b48b84..2785408 100644 --- a/include/llvm/Support/TimeValue.h +++ b/include/llvm/Support/TimeValue.h @@ -253,9 +253,10 @@ namespace sys { /// Converts the TimeValue into the corresponding number of "ticks" for /// Win32 platforms, correcting for the difference in Win32 zero time. - /// @brief Convert to windows time (seconds since 12:00:00a Jan 1, 1601) + /// @brief Convert to Win32's FILETIME + /// (100ns intervals since 00:00:00 Jan 1, 1601 UTC) uint64_t toWin32Time() const { - uint64_t result = seconds_ - Win32ZeroTimeSeconds; + uint64_t result = (uint64_t)10000000 * (seconds_ - Win32ZeroTimeSeconds); result += nanos_ / NANOSECONDS_PER_WIN32_TICK; return result; } diff --git a/include/llvm/Support/ToolOutputFile.h b/include/llvm/Support/ToolOutputFile.h index b3b7c57..a2191ad 100644 --- a/include/llvm/Support/ToolOutputFile.h +++ b/include/llvm/Support/ToolOutputFile.h @@ -47,7 +47,9 @@ public: /// tool_output_file - This constructor's arguments are passed to /// to raw_fd_ostream's constructor. tool_output_file(const char *filename, std::string &ErrorInfo, - unsigned Flags = 0); + sys::fs::OpenFlags Flags = sys::fs::F_None); + + tool_output_file(const char *Filename, int FD); /// os - Return the contained raw_fd_ostream. raw_fd_ostream &os() { return OS; } diff --git a/include/llvm/Support/UnicodeCharRanges.h b/include/llvm/Support/UnicodeCharRanges.h new file mode 100644 index 0000000..4a4d988 --- /dev/null +++ b/include/llvm/Support/UnicodeCharRanges.h @@ -0,0 +1,98 @@ +//===--- UnicodeCharRanges.h - Types and functions for character ranges ---===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +#ifndef LLVM_SUPPORT_UNICODECHARRANGES_H +#define LLVM_SUPPORT_UNICODECHARRANGES_H + +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/SmallPtrSet.h" +#include "llvm/Support/Compiler.h" +#include "llvm/Support/Debug.h" +#include "llvm/Support/Mutex.h" +#include "llvm/Support/MutexGuard.h" +#include "llvm/Support/raw_ostream.h" + +namespace { + +struct UnicodeCharRange { + uint32_t Lower; + uint32_t Upper; +}; +typedef llvm::ArrayRef<UnicodeCharRange> UnicodeCharSet; + +/// Returns true if each of the ranges in \p CharSet is a proper closed range +/// [min, max], and if the ranges themselves are ordered and non-overlapping. +static inline bool isValidCharSet(UnicodeCharSet CharSet) { +#ifndef NDEBUG + static llvm::SmallPtrSet<const UnicodeCharRange *, 16> Validated; + static llvm::sys::Mutex ValidationMutex; + + // Check the validation cache. + { + llvm::MutexGuard Guard(ValidationMutex); + if (Validated.count(CharSet.data())) + return true; + } + + // Walk through the ranges. + uint32_t Prev = 0; + for (UnicodeCharSet::iterator I = CharSet.begin(), E = CharSet.end(); + I != E; ++I) { + if (I != CharSet.begin() && Prev >= I->Lower) { + DEBUG(llvm::dbgs() << "Upper bound 0x"); + DEBUG(llvm::dbgs().write_hex(Prev)); + DEBUG(llvm::dbgs() << " should be less than succeeding lower bound 0x"); + DEBUG(llvm::dbgs().write_hex(I->Lower) << "\n"); + return false; + } + if (I->Upper < I->Lower) { + DEBUG(llvm::dbgs() << "Upper bound 0x"); + DEBUG(llvm::dbgs().write_hex(I->Lower)); + DEBUG(llvm::dbgs() << " should not be less than lower bound 0x"); + DEBUG(llvm::dbgs().write_hex(I->Upper) << "\n"); + return false; + } + Prev = I->Upper; + } + + // Update the validation cache. + { + llvm::MutexGuard Guard(ValidationMutex); + Validated.insert(CharSet.data()); + } +#endif + return true; +} + +} // namespace + + +/// Returns true if the Unicode code point \p C is within the set of +/// characters specified by \p CharSet. +LLVM_READONLY static inline bool isCharInSet(uint32_t C, + UnicodeCharSet CharSet) { + assert(isValidCharSet(CharSet)); + + size_t LowPoint = 0; + size_t HighPoint = CharSet.size(); + + // Binary search the set of char ranges. + while (HighPoint != LowPoint) { + size_t MidPoint = (HighPoint + LowPoint) / 2; + if (C < CharSet[MidPoint].Lower) + HighPoint = MidPoint; + else if (C > CharSet[MidPoint].Upper) + LowPoint = MidPoint + 1; + else + return true; + } + + return false; +} + +#endif // LLVM_SUPPORT_UNICODECHARRANGES_H diff --git a/include/llvm/Support/YAMLTraits.h b/include/llvm/Support/YAMLTraits.h index 801868f..0f57f44 100644 --- a/include/llvm/Support/YAMLTraits.h +++ b/include/llvm/Support/YAMLTraits.h @@ -14,7 +14,7 @@ #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseMapInfo.h" #include "llvm/ADT/SmallVector.h" -#include "llvm/ADT/StringExtras.h" +#include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/Twine.h" @@ -760,15 +760,7 @@ private: } static inline bool classof(const MapHNode *) { return true; } - struct StrMappingInfo { - static StringRef getEmptyKey() { return StringRef(); } - static StringRef getTombstoneKey() { return StringRef(" ", 0); } - static unsigned getHashValue(StringRef const val) { - return llvm::HashString(val); } - static bool isEqual(StringRef const lhs, - StringRef const rhs) { return lhs.equals(rhs); } - }; - typedef llvm::DenseMap<StringRef, HNode*, StrMappingInfo> NameToNode; + typedef llvm::StringMap<HNode*> NameToNode; bool isValidKey(StringRef key); diff --git a/include/llvm/Support/raw_ostream.h b/include/llvm/Support/raw_ostream.h index d2b4a2a..ec7e06b 100644 --- a/include/llvm/Support/raw_ostream.h +++ b/include/llvm/Support/raw_ostream.h @@ -17,6 +17,7 @@ #include "llvm/ADT/StringRef.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/DataTypes.h" +#include "llvm/Support/FileSystem.h" namespace llvm { class format_object_base; @@ -335,22 +336,6 @@ class raw_fd_ostream : public raw_ostream { void error_detected() { Error = true; } public: - - enum { - /// F_Excl - When opening a file, this flag makes raw_fd_ostream - /// report an error if the file already exists. - F_Excl = 1, - - /// F_Append - When opening a file, if it already exists append to the - /// existing file instead of returning an error. This may not be specified - /// with F_Excl. - F_Append = 2, - - /// F_Binary - The file should be opened in binary mode on platforms that - /// make this distinction. - F_Binary = 4 - }; - /// raw_fd_ostream - Open the specified file for writing. If an error occurs, /// information about the error is put into ErrorInfo, and the stream should /// be immediately destroyed; the string will be empty if no error occurred. @@ -362,7 +347,7 @@ public: /// file descriptor when it is done (this is necessary to detect /// output errors). raw_fd_ostream(const char *Filename, std::string &ErrorInfo, - unsigned Flags = 0); + sys::fs::OpenFlags Flags = sys::fs::F_None); /// raw_fd_ostream ctor - FD is the file descriptor that this writes to. If /// ShouldClose is true, this closes the file when the stream is destroyed. |