blob: 9ba7a09f9962475ac2991d5f9809bdfc1de59a03 [file] [log] [blame]
Daniel Dunbar44981682009-09-16 22:38:48 +00001//===-- StringRef.cpp - Lightweight String References ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/ADT/StringRef.h"
Zachary Turner8bd42a12017-02-14 19:06:37 +000011#include "llvm/ADT/APFloat.h"
John McCall512b6502010-02-28 09:55:58 +000012#include "llvm/ADT/APInt.h"
Chandler Carruthca99ad32012-03-04 10:55:27 +000013#include "llvm/ADT/Hashing.h"
Francis Visoiu Mistrih26d6fc12017-11-28 14:22:27 +000014#include "llvm/ADT/StringExtras.h"
Kaelyn Uhrain7a9ccf42012-02-15 22:13:07 +000015#include "llvm/ADT/edit_distance.h"
Benjamin Kramer08fd2cf2010-08-23 18:16:08 +000016#include <bitset>
Douglas Gregor09470e62010-01-07 00:51:54 +000017
Daniel Dunbar44981682009-09-16 22:38:48 +000018using namespace llvm;
19
Daniel Dunbarc827d9e2009-09-22 03:34:40 +000020// MSVC emits references to this into the translation units which reference it.
21#ifndef _MSC_VER
Daniel Dunbar44981682009-09-16 22:38:48 +000022const size_t StringRef::npos;
Daniel Dunbarc827d9e2009-09-22 03:34:40 +000023#endif
Chris Lattner68ee7002009-09-19 19:47:14 +000024
Rui Ueyama00e24e42013-10-30 18:32:26 +000025// strncasecmp() is not available on non-POSIX systems, so define an
26// alternative function here.
27static int ascii_strncasecmp(const char *LHS, const char *RHS, size_t Length) {
28 for (size_t I = 0; I < Length; ++I) {
Francis Visoiu Mistrih26d6fc12017-11-28 14:22:27 +000029 unsigned char LHC = toLower(LHS[I]);
30 unsigned char RHC = toLower(RHS[I]);
Benjamin Kramer68e49452009-11-12 20:36:59 +000031 if (LHC != RHC)
32 return LHC < RHC ? -1 : 1;
33 }
Rui Ueyama00e24e42013-10-30 18:32:26 +000034 return 0;
35}
Benjamin Kramer68e49452009-11-12 20:36:59 +000036
Rui Ueyama00e24e42013-10-30 18:32:26 +000037/// compare_lower - Compare strings, ignoring case.
38int StringRef::compare_lower(StringRef RHS) const {
Craig Topper3ced27c2014-08-21 04:31:10 +000039 if (int Res = ascii_strncasecmp(Data, RHS.Data, std::min(Length, RHS.Length)))
Rui Ueyama00e24e42013-10-30 18:32:26 +000040 return Res;
Benjamin Kramer68e49452009-11-12 20:36:59 +000041 if (Length == RHS.Length)
Benjamin Kramerb04d4af2010-08-26 14:21:08 +000042 return 0;
Benjamin Kramer68e49452009-11-12 20:36:59 +000043 return Length < RHS.Length ? -1 : 1;
44}
45
Rui Ueyama00e24e42013-10-30 18:32:26 +000046/// Check if this string starts with the given \p Prefix, ignoring case.
47bool StringRef::startswith_lower(StringRef Prefix) const {
48 return Length >= Prefix.Length &&
49 ascii_strncasecmp(Data, Prefix.Data, Prefix.Length) == 0;
50}
51
52/// Check if this string ends with the given \p Suffix, ignoring case.
53bool StringRef::endswith_lower(StringRef Suffix) const {
54 return Length >= Suffix.Length &&
55 ascii_strncasecmp(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
56}
57
Zachary Turner17412b02016-11-12 17:17:12 +000058size_t StringRef::find_lower(char C, size_t From) const {
Francis Visoiu Mistrih26d6fc12017-11-28 14:22:27 +000059 char L = toLower(C);
60 return find_if([L](char D) { return toLower(D) == L; }, From);
Zachary Turner17412b02016-11-12 17:17:12 +000061}
62
Jakob Stoklund Olesend1d7ed62010-05-26 21:47:28 +000063/// compare_numeric - Compare strings, handle embedded numbers.
64int StringRef::compare_numeric(StringRef RHS) const {
Craig Topper3ced27c2014-08-21 04:31:10 +000065 for (size_t I = 0, E = std::min(Length, RHS.Length); I != E; ++I) {
Jakob Stoklund Olesenc874e2d2011-09-30 17:03:55 +000066 // Check for sequences of digits.
Francis Visoiu Mistrih26d6fc12017-11-28 14:22:27 +000067 if (isDigit(Data[I]) && isDigit(RHS.Data[I])) {
Jakob Stoklund Olesenc874e2d2011-09-30 17:03:55 +000068 // The longer sequence of numbers is considered larger.
69 // This doesn't really handle prefixed zeros well.
70 size_t J;
71 for (J = I + 1; J != E + 1; ++J) {
Francis Visoiu Mistrih26d6fc12017-11-28 14:22:27 +000072 bool ld = J < Length && isDigit(Data[J]);
73 bool rd = J < RHS.Length && isDigit(RHS.Data[J]);
Jakob Stoklund Olesend1d7ed62010-05-26 21:47:28 +000074 if (ld != rd)
75 return rd ? -1 : 1;
76 if (!rd)
77 break;
78 }
Jakob Stoklund Olesenc874e2d2011-09-30 17:03:55 +000079 // The two number sequences have the same length (J-I), just memcmp them.
80 if (int Res = compareMemory(Data + I, RHS.Data + I, J - I))
81 return Res < 0 ? -1 : 1;
82 // Identical number sequences, continue search after the numbers.
83 I = J - 1;
84 continue;
Jakob Stoklund Olesend1d7ed62010-05-26 21:47:28 +000085 }
Jakob Stoklund Olesenc874e2d2011-09-30 17:03:55 +000086 if (Data[I] != RHS.Data[I])
87 return (unsigned char)Data[I] < (unsigned char)RHS.Data[I] ? -1 : 1;
Jakob Stoklund Olesend1d7ed62010-05-26 21:47:28 +000088 }
89 if (Length == RHS.Length)
Benjamin Kramerb04d4af2010-08-26 14:21:08 +000090 return 0;
Jakob Stoklund Olesend1d7ed62010-05-26 21:47:28 +000091 return Length < RHS.Length ? -1 : 1;
92}
93
Douglas Gregor5639af42009-12-31 04:24:34 +000094// Compute the edit distance between the two given strings.
Michael J. Spencerf13f4422010-11-26 04:16:08 +000095unsigned StringRef::edit_distance(llvm::StringRef Other,
Douglas Gregor21afc3b2010-10-19 22:13:48 +000096 bool AllowReplacements,
Dmitri Gribenko292c9202013-08-24 01:50:41 +000097 unsigned MaxEditDistance) const {
Kaelyn Uhrain7a9ccf42012-02-15 22:13:07 +000098 return llvm::ComputeEditDistance(
Craig Toppere1d12942014-08-27 05:25:25 +000099 makeArrayRef(data(), size()),
100 makeArrayRef(Other.data(), Other.size()),
Kaelyn Uhrain7a9ccf42012-02-15 22:13:07 +0000101 AllowReplacements, MaxEditDistance);
Douglas Gregor165882c2009-12-30 17:23:44 +0000102}
103
Chris Lattner372a8ae2009-09-20 01:22:16 +0000104//===----------------------------------------------------------------------===//
Daniel Dunbar3fa528d2011-11-06 18:04:43 +0000105// String Operations
106//===----------------------------------------------------------------------===//
107
108std::string StringRef::lower() const {
109 std::string Result(size(), char());
110 for (size_type i = 0, e = size(); i != e; ++i) {
Francis Visoiu Mistrih26d6fc12017-11-28 14:22:27 +0000111 Result[i] = toLower(Data[i]);
Daniel Dunbar3fa528d2011-11-06 18:04:43 +0000112 }
113 return Result;
114}
115
116std::string StringRef::upper() const {
117 std::string Result(size(), char());
118 for (size_type i = 0, e = size(); i != e; ++i) {
Francis Visoiu Mistrih26d6fc12017-11-28 14:22:27 +0000119 Result[i] = toUpper(Data[i]);
Daniel Dunbar3fa528d2011-11-06 18:04:43 +0000120 }
121 return Result;
122}
123
124//===----------------------------------------------------------------------===//
Chris Lattner372a8ae2009-09-20 01:22:16 +0000125// String Searching
126//===----------------------------------------------------------------------===//
127
128
129/// find - Search for the first string \arg Str in the string.
130///
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000131/// \return - The index of the first occurrence of \arg Str, or npos if not
Chris Lattner372a8ae2009-09-20 01:22:16 +0000132/// found.
Daniel Dunbar9806e4a2009-11-11 00:28:53 +0000133size_t StringRef::find(StringRef Str, size_t From) const {
Chandler Carruth233edd22015-09-10 11:17:49 +0000134 if (From > Length)
Chris Lattner372a8ae2009-09-20 01:22:16 +0000135 return npos;
Benjamin Kramer4d681d72011-10-15 10:08:31 +0000136
Chandler Carruthecbe6192016-12-11 07:46:21 +0000137 const char *Start = Data + From;
138 size_t Size = Length - From;
139
Chandler Carruth233edd22015-09-10 11:17:49 +0000140 const char *Needle = Str.data();
141 size_t N = Str.size();
142 if (N == 0)
143 return From;
Chandler Carruth233edd22015-09-10 11:17:49 +0000144 if (Size < N)
145 return npos;
Chandler Carruthecbe6192016-12-11 07:46:21 +0000146 if (N == 1) {
147 const char *Ptr = (const char *)::memchr(Start, Needle[0], Size);
148 return Ptr == nullptr ? npos : Ptr - Data;
149 }
Chandler Carruth233edd22015-09-10 11:17:49 +0000150
Chandler Carruth233edd22015-09-10 11:17:49 +0000151 const char *Stop = Start + (Size - N + 1);
152
Benjamin Kramer4d681d72011-10-15 10:08:31 +0000153 // For short haystacks or unsupported needles fall back to the naive algorithm
Chandler Carruth233edd22015-09-10 11:17:49 +0000154 if (Size < 16 || N > 255) {
155 do {
156 if (std::memcmp(Start, Needle, N) == 0)
157 return Start - Data;
158 ++Start;
159 } while (Start < Stop);
Benjamin Kramer4d681d72011-10-15 10:08:31 +0000160 return npos;
161 }
162
163 // Build the bad char heuristic table, with uint8_t to reduce cache thrashing.
164 uint8_t BadCharSkip[256];
165 std::memset(BadCharSkip, N, 256);
166 for (unsigned i = 0; i != N-1; ++i)
167 BadCharSkip[(uint8_t)Str[i]] = N-1-i;
168
Chandler Carruth233edd22015-09-10 11:17:49 +0000169 do {
Chandler Carruthecbe6192016-12-11 07:46:21 +0000170 uint8_t Last = Start[N - 1];
171 if (LLVM_UNLIKELY(Last == (uint8_t)Needle[N - 1]))
172 if (std::memcmp(Start, Needle, N - 1) == 0)
173 return Start - Data;
Benjamin Kramer4d681d72011-10-15 10:08:31 +0000174
175 // Otherwise skip the appropriate number of bytes.
Chandler Carruthecbe6192016-12-11 07:46:21 +0000176 Start += BadCharSkip[Last];
Chandler Carruth233edd22015-09-10 11:17:49 +0000177 } while (Start < Stop);
Benjamin Kramer4d681d72011-10-15 10:08:31 +0000178
Chris Lattner372a8ae2009-09-20 01:22:16 +0000179 return npos;
180}
181
Zachary Turner17412b02016-11-12 17:17:12 +0000182size_t StringRef::find_lower(StringRef Str, size_t From) const {
183 StringRef This = substr(From);
184 while (This.size() >= Str.size()) {
185 if (This.startswith_lower(Str))
186 return From;
187 This = This.drop_front();
188 ++From;
189 }
190 return npos;
191}
192
193size_t StringRef::rfind_lower(char C, size_t From) const {
194 From = std::min(From, Length);
195 size_t i = From;
196 while (i != 0) {
197 --i;
Francis Visoiu Mistrih26d6fc12017-11-28 14:22:27 +0000198 if (toLower(Data[i]) == toLower(C))
Zachary Turner17412b02016-11-12 17:17:12 +0000199 return i;
200 }
201 return npos;
202}
203
Chris Lattner372a8ae2009-09-20 01:22:16 +0000204/// rfind - Search for the last string \arg Str in the string.
205///
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000206/// \return - The index of the last occurrence of \arg Str, or npos if not
Chris Lattner372a8ae2009-09-20 01:22:16 +0000207/// found.
Daniel Dunbarad36e8a2009-11-06 10:58:06 +0000208size_t StringRef::rfind(StringRef Str) const {
Chris Lattner372a8ae2009-09-20 01:22:16 +0000209 size_t N = Str.size();
210 if (N > Length)
211 return npos;
212 for (size_t i = Length - N + 1, e = 0; i != e;) {
213 --i;
214 if (substr(i, N).equals(Str))
215 return i;
216 }
217 return npos;
218}
219
Zachary Turner17412b02016-11-12 17:17:12 +0000220size_t StringRef::rfind_lower(StringRef Str) const {
221 size_t N = Str.size();
222 if (N > Length)
223 return npos;
224 for (size_t i = Length - N + 1, e = 0; i != e;) {
225 --i;
226 if (substr(i, N).equals_lower(Str))
227 return i;
228 }
229 return npos;
230}
231
Daniel Dunbar9806e4a2009-11-11 00:28:53 +0000232/// find_first_of - Find the first character in the string that is in \arg
233/// Chars, or npos if not found.
234///
Benjamin Kramer08fd2cf2010-08-23 18:16:08 +0000235/// Note: O(size() + Chars.size())
Daniel Dunbar9806e4a2009-11-11 00:28:53 +0000236StringRef::size_type StringRef::find_first_of(StringRef Chars,
237 size_t From) const {
Benjamin Kramer08fd2cf2010-08-23 18:16:08 +0000238 std::bitset<1 << CHAR_BIT> CharBits;
239 for (size_type i = 0; i != Chars.size(); ++i)
240 CharBits.set((unsigned char)Chars[i]);
241
Craig Topper3ced27c2014-08-21 04:31:10 +0000242 for (size_type i = std::min(From, Length), e = Length; i != e; ++i)
Benjamin Kramer08fd2cf2010-08-23 18:16:08 +0000243 if (CharBits.test((unsigned char)Data[i]))
Chris Lattner372a8ae2009-09-20 01:22:16 +0000244 return i;
245 return npos;
246}
247
248/// find_first_not_of - Find the first character in the string that is not
Daniel Dunbar9806e4a2009-11-11 00:28:53 +0000249/// \arg C or npos if not found.
250StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const {
Craig Topper3ced27c2014-08-21 04:31:10 +0000251 for (size_type i = std::min(From, Length), e = Length; i != e; ++i)
Daniel Dunbar9806e4a2009-11-11 00:28:53 +0000252 if (Data[i] != C)
253 return i;
254 return npos;
255}
256
257/// find_first_not_of - Find the first character in the string that is not
258/// in the string \arg Chars, or npos if not found.
259///
Benjamin Kramer08fd2cf2010-08-23 18:16:08 +0000260/// Note: O(size() + Chars.size())
Daniel Dunbar9806e4a2009-11-11 00:28:53 +0000261StringRef::size_type StringRef::find_first_not_of(StringRef Chars,
262 size_t From) const {
Benjamin Kramer08fd2cf2010-08-23 18:16:08 +0000263 std::bitset<1 << CHAR_BIT> CharBits;
264 for (size_type i = 0; i != Chars.size(); ++i)
265 CharBits.set((unsigned char)Chars[i]);
266
Craig Topper3ced27c2014-08-21 04:31:10 +0000267 for (size_type i = std::min(From, Length), e = Length; i != e; ++i)
Benjamin Kramer08fd2cf2010-08-23 18:16:08 +0000268 if (!CharBits.test((unsigned char)Data[i]))
Chris Lattner372a8ae2009-09-20 01:22:16 +0000269 return i;
270 return npos;
271}
272
Michael J. Spencere1d3603d2010-11-30 23:27:35 +0000273/// find_last_of - Find the last character in the string that is in \arg C,
274/// or npos if not found.
275///
276/// Note: O(size() + Chars.size())
277StringRef::size_type StringRef::find_last_of(StringRef Chars,
278 size_t From) const {
279 std::bitset<1 << CHAR_BIT> CharBits;
280 for (size_type i = 0; i != Chars.size(); ++i)
281 CharBits.set((unsigned char)Chars[i]);
282
Craig Topper3ced27c2014-08-21 04:31:10 +0000283 for (size_type i = std::min(From, Length) - 1, e = -1; i != e; --i)
Michael J. Spencere1d3603d2010-11-30 23:27:35 +0000284 if (CharBits.test((unsigned char)Data[i]))
285 return i;
286 return npos;
287}
Chris Lattner372a8ae2009-09-20 01:22:16 +0000288
Michael J. Spencer93303812012-05-11 22:08:50 +0000289/// find_last_not_of - Find the last character in the string that is not
290/// \arg C, or npos if not found.
291StringRef::size_type StringRef::find_last_not_of(char C, size_t From) const {
Craig Topper3ced27c2014-08-21 04:31:10 +0000292 for (size_type i = std::min(From, Length) - 1, e = -1; i != e; --i)
Michael J. Spencer93303812012-05-11 22:08:50 +0000293 if (Data[i] != C)
294 return i;
295 return npos;
296}
297
298/// find_last_not_of - Find the last character in the string that is not in
299/// \arg Chars, or npos if not found.
300///
301/// Note: O(size() + Chars.size())
302StringRef::size_type StringRef::find_last_not_of(StringRef Chars,
303 size_t From) const {
304 std::bitset<1 << CHAR_BIT> CharBits;
305 for (size_type i = 0, e = Chars.size(); i != e; ++i)
306 CharBits.set((unsigned char)Chars[i]);
307
Craig Topper3ced27c2014-08-21 04:31:10 +0000308 for (size_type i = std::min(From, Length) - 1, e = -1; i != e; --i)
Michael J. Spencer93303812012-05-11 22:08:50 +0000309 if (!CharBits.test((unsigned char)Data[i]))
310 return i;
311 return npos;
312}
313
Duncan Sands8570b292012-02-21 12:00:25 +0000314void StringRef::split(SmallVectorImpl<StringRef> &A,
Chandler Carruth4425c912015-09-10 07:51:37 +0000315 StringRef Separator, int MaxSplit,
Duncan Sands8570b292012-02-21 12:00:25 +0000316 bool KeepEmpty) const {
Chandler Carruth4425c912015-09-10 07:51:37 +0000317 StringRef S = *this;
Duncan Sands8570b292012-02-21 12:00:25 +0000318
Chandler Carruth4425c912015-09-10 07:51:37 +0000319 // Count down from MaxSplit. When MaxSplit is -1, this will just split
320 // "forever". This doesn't support splitting more than 2^31 times
321 // intentionally; if we ever want that we can make MaxSplit a 64-bit integer
322 // but that seems unlikely to be useful.
323 while (MaxSplit-- != 0) {
324 size_t Idx = S.find(Separator);
325 if (Idx == npos)
326 break;
Duncan Sands8570b292012-02-21 12:00:25 +0000327
Chandler Carruth4425c912015-09-10 07:51:37 +0000328 // Push this split.
329 if (KeepEmpty || Idx > 0)
330 A.push_back(S.slice(0, Idx));
331
332 // Jump forward.
333 S = S.slice(Idx + Separator.size(), npos);
Duncan Sands8570b292012-02-21 12:00:25 +0000334 }
Chandler Carruth4425c912015-09-10 07:51:37 +0000335
336 // Push the tail.
337 if (KeepEmpty || !S.empty())
338 A.push_back(S);
Duncan Sands8570b292012-02-21 12:00:25 +0000339}
340
Chandler Carruth47712172015-09-10 06:07:03 +0000341void StringRef::split(SmallVectorImpl<StringRef> &A, char Separator,
342 int MaxSplit, bool KeepEmpty) const {
Chandler Carruth4425c912015-09-10 07:51:37 +0000343 StringRef S = *this;
Chandler Carruth47712172015-09-10 06:07:03 +0000344
Chandler Carruth4425c912015-09-10 07:51:37 +0000345 // Count down from MaxSplit. When MaxSplit is -1, this will just split
346 // "forever". This doesn't support splitting more than 2^31 times
347 // intentionally; if we ever want that we can make MaxSplit a 64-bit integer
348 // but that seems unlikely to be useful.
349 while (MaxSplit-- != 0) {
350 size_t Idx = S.find(Separator);
351 if (Idx == npos)
352 break;
Chandler Carruth47712172015-09-10 06:07:03 +0000353
Chandler Carruth4425c912015-09-10 07:51:37 +0000354 // Push this split.
355 if (KeepEmpty || Idx > 0)
356 A.push_back(S.slice(0, Idx));
357
358 // Jump forward.
359 S = S.slice(Idx + 1, npos);
Chandler Carruth47712172015-09-10 06:07:03 +0000360 }
Chandler Carruth4425c912015-09-10 07:51:37 +0000361
362 // Push the tail.
363 if (KeepEmpty || !S.empty())
364 A.push_back(S);
Chandler Carruth47712172015-09-10 06:07:03 +0000365}
366
Chris Lattner372a8ae2009-09-20 01:22:16 +0000367//===----------------------------------------------------------------------===//
368// Helpful Algorithms
369//===----------------------------------------------------------------------===//
370
371/// count - Return the number of non-overlapped occurrences of \arg Str in
372/// the string.
Daniel Dunbarad36e8a2009-11-06 10:58:06 +0000373size_t StringRef::count(StringRef Str) const {
Chris Lattner372a8ae2009-09-20 01:22:16 +0000374 size_t Count = 0;
375 size_t N = Str.size();
376 if (N > Length)
377 return 0;
378 for (size_t i = 0, e = Length - N + 1; i != e; ++i)
379 if (substr(i, N).equals(Str))
380 ++Count;
381 return Count;
382}
383
John McCall512b6502010-02-28 09:55:58 +0000384static unsigned GetAutoSenseRadix(StringRef &Str) {
Zachary Turnerd5d57632016-09-22 15:55:05 +0000385 if (Str.empty())
386 return 10;
387
Colin LeMahieu01431462016-03-18 18:22:07 +0000388 if (Str.startswith("0x") || Str.startswith("0X")) {
John McCall512b6502010-02-28 09:55:58 +0000389 Str = Str.substr(2);
390 return 16;
Chris Lattner0a1bafe2012-04-21 22:03:05 +0000391 }
392
Colin LeMahieu01431462016-03-18 18:22:07 +0000393 if (Str.startswith("0b") || Str.startswith("0B")) {
John McCall512b6502010-02-28 09:55:58 +0000394 Str = Str.substr(2);
395 return 2;
John McCall512b6502010-02-28 09:55:58 +0000396 }
Chris Lattner0a1bafe2012-04-21 22:03:05 +0000397
398 if (Str.startswith("0o")) {
399 Str = Str.substr(2);
400 return 8;
401 }
402
Francis Visoiu Mistrih26d6fc12017-11-28 14:22:27 +0000403 if (Str[0] == '0' && Str.size() > 1 && isDigit(Str[1])) {
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000404 Str = Str.substr(1);
Chris Lattner0a1bafe2012-04-21 22:03:05 +0000405 return 8;
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000406 }
407
Chris Lattner0a1bafe2012-04-21 22:03:05 +0000408 return 10;
John McCall512b6502010-02-28 09:55:58 +0000409}
410
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000411bool llvm::consumeUnsignedInteger(StringRef &Str, unsigned Radix,
412 unsigned long long &Result) {
Chris Lattner68ee7002009-09-19 19:47:14 +0000413 // Autosense radix if not specified.
John McCall512b6502010-02-28 09:55:58 +0000414 if (Radix == 0)
415 Radix = GetAutoSenseRadix(Str);
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000416
Chris Lattner68ee7002009-09-19 19:47:14 +0000417 // Empty strings (after the radix autosense) are invalid.
418 if (Str.empty()) return true;
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000419
Chris Lattner68ee7002009-09-19 19:47:14 +0000420 // Parse all the bytes of the string given this radix. Watch for overflow.
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000421 StringRef Str2 = Str;
Chris Lattner68ee7002009-09-19 19:47:14 +0000422 Result = 0;
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000423 while (!Str2.empty()) {
Chris Lattner68ee7002009-09-19 19:47:14 +0000424 unsigned CharVal;
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000425 if (Str2[0] >= '0' && Str2[0] <= '9')
426 CharVal = Str2[0] - '0';
427 else if (Str2[0] >= 'a' && Str2[0] <= 'z')
428 CharVal = Str2[0] - 'a' + 10;
429 else if (Str2[0] >= 'A' && Str2[0] <= 'Z')
430 CharVal = Str2[0] - 'A' + 10;
Chris Lattner68ee7002009-09-19 19:47:14 +0000431 else
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000432 break;
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000433
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000434 // If the parsed value is larger than the integer radix, we cannot
435 // consume any more characters.
Chris Lattner68ee7002009-09-19 19:47:14 +0000436 if (CharVal >= Radix)
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000437 break;
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000438
Chris Lattner68ee7002009-09-19 19:47:14 +0000439 // Add in this character.
440 unsigned long long PrevResult = Result;
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000441 Result = Result * Radix + CharVal;
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000442
Nick Kledzik35c79da2012-10-02 20:01:48 +0000443 // Check for overflow by shifting back and seeing if bits were lost.
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000444 if (Result / Radix < PrevResult)
Chris Lattner68ee7002009-09-19 19:47:14 +0000445 return true;
446
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000447 Str2 = Str2.substr(1);
Chris Lattner68ee7002009-09-19 19:47:14 +0000448 }
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000449
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000450 // We consider the operation a failure if no characters were consumed
451 // successfully.
452 if (Str.size() == Str2.size())
453 return true;
454
455 Str = Str2;
Chris Lattner68ee7002009-09-19 19:47:14 +0000456 return false;
457}
458
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000459bool llvm::consumeSignedInteger(StringRef &Str, unsigned Radix,
460 long long &Result) {
Chris Lattner84c15272009-09-19 23:58:48 +0000461 unsigned long long ULLVal;
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000462
Chris Lattner84c15272009-09-19 23:58:48 +0000463 // Handle positive strings first.
Michael J. Spencercfa95f62012-03-10 23:02:54 +0000464 if (Str.empty() || Str.front() != '-') {
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000465 if (consumeUnsignedInteger(Str, Radix, ULLVal) ||
Chris Lattner84c15272009-09-19 23:58:48 +0000466 // Check for value so large it overflows a signed value.
467 (long long)ULLVal < 0)
468 return true;
469 Result = ULLVal;
470 return false;
471 }
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000472
Chris Lattner84c15272009-09-19 23:58:48 +0000473 // Get the positive part of the value.
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000474 StringRef Str2 = Str.drop_front(1);
475 if (consumeUnsignedInteger(Str2, Radix, ULLVal) ||
Chris Lattner84c15272009-09-19 23:58:48 +0000476 // Reject values so large they'd overflow as negative signed, but allow
477 // "-0". This negates the unsigned so that the negative isn't undefined
478 // on signed overflow.
479 (long long)-ULLVal > 0)
480 return true;
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000481
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000482 Str = Str2;
Chris Lattner84c15272009-09-19 23:58:48 +0000483 Result = -ULLVal;
484 return false;
485}
486
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000487/// GetAsUnsignedInteger - Workhorse method that converts a integer character
488/// sequence of radix up to 36 to an unsigned long long value.
489bool llvm::getAsUnsignedInteger(StringRef Str, unsigned Radix,
490 unsigned long long &Result) {
491 if (consumeUnsignedInteger(Str, Radix, Result))
492 return true;
493
494 // For getAsUnsignedInteger, we require the whole string to be consumed or
495 // else we consider it a failure.
496 return !Str.empty();
497}
498
499bool llvm::getAsSignedInteger(StringRef Str, unsigned Radix,
500 long long &Result) {
501 if (consumeSignedInteger(Str, Radix, Result))
502 return true;
503
504 // For getAsSignedInteger, we require the whole string to be consumed or else
505 // we consider it a failure.
506 return !Str.empty();
507}
508
John McCall512b6502010-02-28 09:55:58 +0000509bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const {
510 StringRef Str = *this;
511
512 // Autosense radix if not specified.
513 if (Radix == 0)
514 Radix = GetAutoSenseRadix(Str);
515
516 assert(Radix > 1 && Radix <= 36);
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000517
John McCall512b6502010-02-28 09:55:58 +0000518 // Empty strings (after the radix autosense) are invalid.
519 if (Str.empty()) return true;
520
521 // Skip leading zeroes. This can be a significant improvement if
522 // it means we don't need > 64 bits.
523 while (!Str.empty() && Str.front() == '0')
524 Str = Str.substr(1);
525
526 // If it was nothing but zeroes....
527 if (Str.empty()) {
528 Result = APInt(64, 0);
529 return false;
530 }
531
532 // (Over-)estimate the required number of bits.
533 unsigned Log2Radix = 0;
534 while ((1U << Log2Radix) < Radix) Log2Radix++;
535 bool IsPowerOf2Radix = ((1U << Log2Radix) == Radix);
536
537 unsigned BitWidth = Log2Radix * Str.size();
538 if (BitWidth < Result.getBitWidth())
539 BitWidth = Result.getBitWidth(); // don't shrink the result
Chris Lattner5e146662012-04-23 00:27:54 +0000540 else if (BitWidth > Result.getBitWidth())
Jay Foad583abbc2010-12-07 08:25:19 +0000541 Result = Result.zext(BitWidth);
John McCall512b6502010-02-28 09:55:58 +0000542
543 APInt RadixAP, CharAP; // unused unless !IsPowerOf2Radix
544 if (!IsPowerOf2Radix) {
545 // These must have the same bit-width as Result.
546 RadixAP = APInt(BitWidth, Radix);
547 CharAP = APInt(BitWidth, 0);
548 }
549
550 // Parse all the bytes of the string given this radix.
551 Result = 0;
552 while (!Str.empty()) {
553 unsigned CharVal;
554 if (Str[0] >= '0' && Str[0] <= '9')
555 CharVal = Str[0]-'0';
556 else if (Str[0] >= 'a' && Str[0] <= 'z')
557 CharVal = Str[0]-'a'+10;
558 else if (Str[0] >= 'A' && Str[0] <= 'Z')
559 CharVal = Str[0]-'A'+10;
560 else
561 return true;
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000562
John McCall512b6502010-02-28 09:55:58 +0000563 // If the parsed value is larger than the integer radix, the string is
564 // invalid.
565 if (CharVal >= Radix)
566 return true;
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000567
John McCall512b6502010-02-28 09:55:58 +0000568 // Add in this character.
569 if (IsPowerOf2Radix) {
570 Result <<= Log2Radix;
571 Result |= CharVal;
572 } else {
573 Result *= RadixAP;
574 CharAP = CharVal;
575 Result += CharAP;
576 }
577
578 Str = Str.substr(1);
579 }
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000580
John McCall512b6502010-02-28 09:55:58 +0000581 return false;
582}
Chandler Carruthca99ad32012-03-04 10:55:27 +0000583
Zachary Turner8bd42a12017-02-14 19:06:37 +0000584bool StringRef::getAsDouble(double &Result, bool AllowInexact) const {
585 APFloat F(0.0);
586 APFloat::opStatus Status =
587 F.convertFromString(*this, APFloat::rmNearestTiesToEven);
588 if (Status != APFloat::opOK) {
Serguei Katkov768d6dd2017-12-19 04:27:39 +0000589 if (!AllowInexact || !(Status & APFloat::opInexact))
Zachary Turner8bd42a12017-02-14 19:06:37 +0000590 return true;
591 }
592
593 Result = F.convertToDouble();
594 return false;
595}
Chandler Carruthca99ad32012-03-04 10:55:27 +0000596
597// Implementation of StringRef hashing.
598hash_code llvm::hash_value(StringRef S) {
599 return hash_combine_range(S.begin(), S.end());
600}