1 //===--- LiteralSupport.cpp - Code to parse and process literals ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the NumericLiteralParser, CharLiteralParser, and
10 // StringLiteralParser interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Lex/LiteralSupport.h"
15 #include "clang/Basic/CharInfo.h"
16 #include "clang/Basic/LangOptions.h"
17 #include "clang/Basic/SourceLocation.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/Lex/LexDiagnostic.h"
20 #include "clang/Lex/Lexer.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include "clang/Lex/Token.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/Support/ConvertUTF.h"
28 #include "llvm/Support/Error.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include <algorithm>
31 #include <cassert>
32 #include <cstddef>
33 #include <cstdint>
34 #include <cstring>
35 #include <string>
36 
37 using namespace clang;
38 
39 static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) {
40   switch (kind) {
41   default: llvm_unreachable("Unknown token type!");
42   case tok::char_constant:
43   case tok::string_literal:
44   case tok::utf8_char_constant:
45   case tok::utf8_string_literal:
46     return Target.getCharWidth();
47   case tok::wide_char_constant:
48   case tok::wide_string_literal:
49     return Target.getWCharWidth();
50   case tok::utf16_char_constant:
51   case tok::utf16_string_literal:
52     return Target.getChar16Width();
53   case tok::utf32_char_constant:
54   case tok::utf32_string_literal:
55     return Target.getChar32Width();
56   }
57 }
58 
59 static CharSourceRange MakeCharSourceRange(const LangOptions &Features,
60                                            FullSourceLoc TokLoc,
61                                            const char *TokBegin,
62                                            const char *TokRangeBegin,
63                                            const char *TokRangeEnd) {
64   SourceLocation Begin =
65     Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
66                                    TokLoc.getManager(), Features);
67   SourceLocation End =
68     Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin,
69                                    TokLoc.getManager(), Features);
70   return CharSourceRange::getCharRange(Begin, End);
71 }
72 
73 /// Produce a diagnostic highlighting some portion of a literal.
74 ///
75 /// Emits the diagnostic \p DiagID, highlighting the range of characters from
76 /// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be
77 /// a substring of a spelling buffer for the token beginning at \p TokBegin.
78 static DiagnosticBuilder Diag(DiagnosticsEngine *Diags,
79                               const LangOptions &Features, FullSourceLoc TokLoc,
80                               const char *TokBegin, const char *TokRangeBegin,
81                               const char *TokRangeEnd, unsigned DiagID) {
82   SourceLocation Begin =
83     Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
84                                    TokLoc.getManager(), Features);
85   return Diags->Report(Begin, DiagID) <<
86     MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd);
87 }
88 
89 /// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
90 /// either a character or a string literal.
91 static unsigned ProcessCharEscape(const char *ThisTokBegin,
92                                   const char *&ThisTokBuf,
93                                   const char *ThisTokEnd, bool &HadError,
94                                   FullSourceLoc Loc, unsigned CharWidth,
95                                   DiagnosticsEngine *Diags,
96                                   const LangOptions &Features) {
97   const char *EscapeBegin = ThisTokBuf;
98   bool Delimited = false;
99   bool EndDelimiterFound = false;
100 
101   // Skip the '\' char.
102   ++ThisTokBuf;
103 
104   // We know that this character can't be off the end of the buffer, because
105   // that would have been \", which would not have been the end of string.
106   unsigned ResultChar = *ThisTokBuf++;
107   switch (ResultChar) {
108   // These map to themselves.
109   case '\\': case '\'': case '"': case '?': break;
110 
111     // These have fixed mappings.
112   case 'a':
113     // TODO: K&R: the meaning of '\\a' is different in traditional C
114     ResultChar = 7;
115     break;
116   case 'b':
117     ResultChar = 8;
118     break;
119   case 'e':
120     if (Diags)
121       Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
122            diag::ext_nonstandard_escape) << "e";
123     ResultChar = 27;
124     break;
125   case 'E':
126     if (Diags)
127       Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
128            diag::ext_nonstandard_escape) << "E";
129     ResultChar = 27;
130     break;
131   case 'f':
132     ResultChar = 12;
133     break;
134   case 'n':
135     ResultChar = 10;
136     break;
137   case 'r':
138     ResultChar = 13;
139     break;
140   case 't':
141     ResultChar = 9;
142     break;
143   case 'v':
144     ResultChar = 11;
145     break;
146   case 'x': { // Hex escape.
147     ResultChar = 0;
148     if (ThisTokBuf != ThisTokEnd && *ThisTokBuf == '{') {
149       Delimited = true;
150       ThisTokBuf++;
151       if (*ThisTokBuf == '}') {
152         Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
153              diag::err_delimited_escape_empty);
154         return ResultChar;
155       }
156     } else if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
157       if (Diags)
158         Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
159              diag::err_hex_escape_no_digits) << "x";
160       return ResultChar;
161     }
162 
163     // Hex escapes are a maximal series of hex digits.
164     bool Overflow = false;
165     for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
166       if (Delimited && *ThisTokBuf == '}') {
167         ThisTokBuf++;
168         EndDelimiterFound = true;
169         break;
170       }
171       int CharVal = llvm::hexDigitValue(*ThisTokBuf);
172       if (CharVal == -1) {
173         // Non delimited hex escape sequences stop at the first non-hex digit.
174         if (!Delimited)
175           break;
176         HadError = true;
177         if (Diags)
178           Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
179                diag::err_delimited_escape_invalid)
180               << StringRef(ThisTokBuf, 1);
181         continue;
182       }
183       // About to shift out a digit?
184       if (ResultChar & 0xF0000000)
185         Overflow = true;
186       ResultChar <<= 4;
187       ResultChar |= CharVal;
188     }
189     // See if any bits will be truncated when evaluated as a character.
190     if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
191       Overflow = true;
192       ResultChar &= ~0U >> (32-CharWidth);
193     }
194 
195     // Check for overflow.
196     if (!HadError && Overflow) { // Too many digits to fit in
197       HadError = true;
198       if (Diags)
199         Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
200              diag::err_escape_too_large)
201             << 0;
202     }
203     break;
204   }
205   case '0': case '1': case '2': case '3':
206   case '4': case '5': case '6': case '7': {
207     // Octal escapes.
208     --ThisTokBuf;
209     ResultChar = 0;
210 
211     // Octal escapes are a series of octal digits with maximum length 3.
212     // "\0123" is a two digit sequence equal to "\012" "3".
213     unsigned NumDigits = 0;
214     do {
215       ResultChar <<= 3;
216       ResultChar |= *ThisTokBuf++ - '0';
217       ++NumDigits;
218     } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
219              ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
220 
221     // Check for overflow.  Reject '\777', but not L'\777'.
222     if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
223       if (Diags)
224         Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
225              diag::err_escape_too_large) << 1;
226       ResultChar &= ~0U >> (32-CharWidth);
227     }
228     break;
229   }
230   case 'o': {
231     bool Overflow = false;
232     if (ThisTokBuf == ThisTokEnd || *ThisTokBuf != '{') {
233       HadError = true;
234       if (Diags)
235         Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
236              diag::err_delimited_escape_missing_brace);
237 
238       break;
239     }
240     ResultChar = 0;
241     Delimited = true;
242     ++ThisTokBuf;
243     if (*ThisTokBuf == '}') {
244       Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
245            diag::err_delimited_escape_empty);
246       return ResultChar;
247     }
248 
249     while (ThisTokBuf != ThisTokEnd) {
250       if (*ThisTokBuf == '}') {
251         EndDelimiterFound = true;
252         ThisTokBuf++;
253         break;
254       }
255       if (*ThisTokBuf < '0' || *ThisTokBuf > '7') {
256         HadError = true;
257         if (Diags)
258           Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
259                diag::err_delimited_escape_invalid)
260               << StringRef(ThisTokBuf, 1);
261         ThisTokBuf++;
262         continue;
263       }
264       if (ResultChar & 0x020000000)
265         Overflow = true;
266 
267       ResultChar <<= 3;
268       ResultChar |= *ThisTokBuf++ - '0';
269     }
270     // Check for overflow.  Reject '\777', but not L'\777'.
271     if (!HadError &&
272         (Overflow || (CharWidth != 32 && (ResultChar >> CharWidth) != 0))) {
273       HadError = true;
274       if (Diags)
275         Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
276              diag::err_escape_too_large)
277             << 1;
278       ResultChar &= ~0U >> (32 - CharWidth);
279     }
280     break;
281   }
282     // Otherwise, these are not valid escapes.
283   case '(': case '{': case '[': case '%':
284     // GCC accepts these as extensions.  We warn about them as such though.
285     if (Diags)
286       Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
287            diag::ext_nonstandard_escape)
288         << std::string(1, ResultChar);
289     break;
290   default:
291     if (!Diags)
292       break;
293 
294     if (isPrintable(ResultChar))
295       Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
296            diag::ext_unknown_escape)
297         << std::string(1, ResultChar);
298     else
299       Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
300            diag::ext_unknown_escape)
301         << "x" + llvm::utohexstr(ResultChar);
302     break;
303   }
304 
305   if (Delimited && Diags) {
306     if (!EndDelimiterFound)
307       Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
308            diag::err_expected)
309           << tok::r_brace;
310     else if (!HadError) {
311       Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
312            diag::ext_delimited_escape_sequence);
313     }
314   }
315 
316   return ResultChar;
317 }
318 
319 static void appendCodePoint(unsigned Codepoint,
320                             llvm::SmallVectorImpl<char> &Str) {
321   char ResultBuf[4];
322   char *ResultPtr = ResultBuf;
323   bool Res = llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr);
324   (void)Res;
325   assert(Res && "Unexpected conversion failure");
326   Str.append(ResultBuf, ResultPtr);
327 }
328 
329 void clang::expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input) {
330   for (StringRef::iterator I = Input.begin(), E = Input.end(); I != E; ++I) {
331     if (*I != '\\') {
332       Buf.push_back(*I);
333       continue;
334     }
335 
336     ++I;
337     char Kind = *I;
338     ++I;
339 
340     assert(Kind == 'u' || Kind == 'U');
341     uint32_t CodePoint = 0;
342 
343     if (Kind == 'u' && *I == '{') {
344       for (++I; *I != '}'; ++I) {
345         unsigned Value = llvm::hexDigitValue(*I);
346         assert(Value != -1U);
347         CodePoint <<= 4;
348         CodePoint += Value;
349       }
350       appendCodePoint(CodePoint, Buf);
351       continue;
352     }
353 
354     unsigned NumHexDigits;
355     if (Kind == 'u')
356       NumHexDigits = 4;
357     else
358       NumHexDigits = 8;
359 
360     assert(I + NumHexDigits <= E);
361 
362     for (; NumHexDigits != 0; ++I, --NumHexDigits) {
363       unsigned Value = llvm::hexDigitValue(*I);
364       assert(Value != -1U);
365 
366       CodePoint <<= 4;
367       CodePoint += Value;
368     }
369 
370     appendCodePoint(CodePoint, Buf);
371     --I;
372   }
373 }
374 
375 /// ProcessUCNEscape - Read the Universal Character Name, check constraints and
376 /// return the UTF32.
377 static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
378                              const char *ThisTokEnd,
379                              uint32_t &UcnVal, unsigned short &UcnLen,
380                              FullSourceLoc Loc, DiagnosticsEngine *Diags,
381                              const LangOptions &Features,
382                              bool in_char_string_literal = false) {
383   const char *UcnBegin = ThisTokBuf;
384 
385   // Skip the '\u' char's.
386   ThisTokBuf += 2;
387 
388   bool Delimited = false;
389   bool EndDelimiterFound = false;
390   bool HasError = false;
391 
392   if (UcnBegin[1] == 'u' && in_char_string_literal &&
393       ThisTokBuf != ThisTokEnd && *ThisTokBuf == '{') {
394     Delimited = true;
395     ThisTokBuf++;
396   } else if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
397     if (Diags)
398       Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
399            diag::err_hex_escape_no_digits) << StringRef(&ThisTokBuf[-1], 1);
400     return false;
401   }
402   UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
403 
404   bool Overflow = false;
405   unsigned short Count = 0;
406   for (; ThisTokBuf != ThisTokEnd && (Delimited || Count != UcnLen);
407        ++ThisTokBuf) {
408     if (Delimited && *ThisTokBuf == '}') {
409       ++ThisTokBuf;
410       EndDelimiterFound = true;
411       break;
412     }
413     int CharVal = llvm::hexDigitValue(*ThisTokBuf);
414     if (CharVal == -1) {
415       HasError = true;
416       if (!Delimited)
417         break;
418       if (Diags) {
419         Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
420              diag::err_delimited_escape_invalid)
421             << StringRef(ThisTokBuf, 1);
422       }
423       Count++;
424       continue;
425     }
426     if (UcnVal & 0xF0000000) {
427       Overflow = true;
428       continue;
429     }
430     UcnVal <<= 4;
431     UcnVal |= CharVal;
432     Count++;
433   }
434 
435   if (Overflow) {
436     if (Diags)
437       Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
438            diag::err_escape_too_large)
439           << 0;
440     return false;
441   }
442 
443   if (Delimited && !EndDelimiterFound) {
444     if (Diags) {
445       Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
446            diag::err_expected)
447           << tok::r_brace;
448     }
449     return false;
450   }
451 
452   // If we didn't consume the proper number of digits, there is a problem.
453   if (Count == 0 || (!Delimited && Count != UcnLen)) {
454     if (Diags)
455       Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
456            Delimited ? diag::err_delimited_escape_empty
457                      : diag::err_ucn_escape_incomplete);
458     return false;
459   }
460 
461   if (HasError)
462     return false;
463 
464   // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
465   if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
466       UcnVal > 0x10FFFF) {                      // maximum legal UTF32 value
467     if (Diags)
468       Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
469            diag::err_ucn_escape_invalid);
470     return false;
471   }
472 
473   // C++11 allows UCNs that refer to control characters and basic source
474   // characters inside character and string literals
475   if (UcnVal < 0xa0 &&
476       (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) {  // $, @, `
477     bool IsError = (!Features.CPlusPlus11 || !in_char_string_literal);
478     if (Diags) {
479       char BasicSCSChar = UcnVal;
480       if (UcnVal >= 0x20 && UcnVal < 0x7f)
481         Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
482              IsError ? diag::err_ucn_escape_basic_scs :
483                        diag::warn_cxx98_compat_literal_ucn_escape_basic_scs)
484             << StringRef(&BasicSCSChar, 1);
485       else
486         Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
487              IsError ? diag::err_ucn_control_character :
488                        diag::warn_cxx98_compat_literal_ucn_control_character);
489     }
490     if (IsError)
491       return false;
492   }
493 
494   if (!Features.CPlusPlus && !Features.C99 && Diags)
495     Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
496          diag::warn_ucn_not_valid_in_c89_literal);
497 
498   if (Delimited && Diags)
499     Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
500          diag::ext_delimited_escape_sequence);
501 
502   return true;
503 }
504 
505 /// MeasureUCNEscape - Determine the number of bytes within the resulting string
506 /// which this UCN will occupy.
507 static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
508                             const char *ThisTokEnd, unsigned CharByteWidth,
509                             const LangOptions &Features, bool &HadError) {
510   // UTF-32: 4 bytes per escape.
511   if (CharByteWidth == 4)
512     return 4;
513 
514   uint32_t UcnVal = 0;
515   unsigned short UcnLen = 0;
516   FullSourceLoc Loc;
517 
518   if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
519                         UcnLen, Loc, nullptr, Features, true)) {
520     HadError = true;
521     return 0;
522   }
523 
524   // UTF-16: 2 bytes for BMP, 4 bytes otherwise.
525   if (CharByteWidth == 2)
526     return UcnVal <= 0xFFFF ? 2 : 4;
527 
528   // UTF-8.
529   if (UcnVal < 0x80)
530     return 1;
531   if (UcnVal < 0x800)
532     return 2;
533   if (UcnVal < 0x10000)
534     return 3;
535   return 4;
536 }
537 
538 /// EncodeUCNEscape - Read the Universal Character Name, check constraints and
539 /// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
540 /// StringLiteralParser. When we decide to implement UCN's for identifiers,
541 /// we will likely rework our support for UCN's.
542 static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
543                             const char *ThisTokEnd,
544                             char *&ResultBuf, bool &HadError,
545                             FullSourceLoc Loc, unsigned CharByteWidth,
546                             DiagnosticsEngine *Diags,
547                             const LangOptions &Features) {
548   typedef uint32_t UTF32;
549   UTF32 UcnVal = 0;
550   unsigned short UcnLen = 0;
551   if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
552                         Loc, Diags, Features, true)) {
553     HadError = true;
554     return;
555   }
556 
557   assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
558          "only character widths of 1, 2, or 4 bytes supported");
559 
560   (void)UcnLen;
561   assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
562 
563   if (CharByteWidth == 4) {
564     // FIXME: Make the type of the result buffer correct instead of
565     // using reinterpret_cast.
566     llvm::UTF32 *ResultPtr = reinterpret_cast<llvm::UTF32*>(ResultBuf);
567     *ResultPtr = UcnVal;
568     ResultBuf += 4;
569     return;
570   }
571 
572   if (CharByteWidth == 2) {
573     // FIXME: Make the type of the result buffer correct instead of
574     // using reinterpret_cast.
575     llvm::UTF16 *ResultPtr = reinterpret_cast<llvm::UTF16*>(ResultBuf);
576 
577     if (UcnVal <= (UTF32)0xFFFF) {
578       *ResultPtr = UcnVal;
579       ResultBuf += 2;
580       return;
581     }
582 
583     // Convert to UTF16.
584     UcnVal -= 0x10000;
585     *ResultPtr     = 0xD800 + (UcnVal >> 10);
586     *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
587     ResultBuf += 4;
588     return;
589   }
590 
591   assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
592 
593   // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
594   // The conversion below was inspired by:
595   //   http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
596   // First, we determine how many bytes the result will require.
597   typedef uint8_t UTF8;
598 
599   unsigned short bytesToWrite = 0;
600   if (UcnVal < (UTF32)0x80)
601     bytesToWrite = 1;
602   else if (UcnVal < (UTF32)0x800)
603     bytesToWrite = 2;
604   else if (UcnVal < (UTF32)0x10000)
605     bytesToWrite = 3;
606   else
607     bytesToWrite = 4;
608 
609   const unsigned byteMask = 0xBF;
610   const unsigned byteMark = 0x80;
611 
612   // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
613   // into the first byte, depending on how many bytes follow.
614   static const UTF8 firstByteMark[5] = {
615     0x00, 0x00, 0xC0, 0xE0, 0xF0
616   };
617   // Finally, we write the bytes into ResultBuf.
618   ResultBuf += bytesToWrite;
619   switch (bytesToWrite) { // note: everything falls through.
620   case 4:
621     *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
622     LLVM_FALLTHROUGH;
623   case 3:
624     *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
625     LLVM_FALLTHROUGH;
626   case 2:
627     *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
628     LLVM_FALLTHROUGH;
629   case 1:
630     *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
631   }
632   // Update the buffer.
633   ResultBuf += bytesToWrite;
634 }
635 
636 ///       integer-constant: [C99 6.4.4.1]
637 ///         decimal-constant integer-suffix
638 ///         octal-constant integer-suffix
639 ///         hexadecimal-constant integer-suffix
640 ///         binary-literal integer-suffix [GNU, C++1y]
641 ///       user-defined-integer-literal: [C++11 lex.ext]
642 ///         decimal-literal ud-suffix
643 ///         octal-literal ud-suffix
644 ///         hexadecimal-literal ud-suffix
645 ///         binary-literal ud-suffix [GNU, C++1y]
646 ///       decimal-constant:
647 ///         nonzero-digit
648 ///         decimal-constant digit
649 ///       octal-constant:
650 ///         0
651 ///         octal-constant octal-digit
652 ///       hexadecimal-constant:
653 ///         hexadecimal-prefix hexadecimal-digit
654 ///         hexadecimal-constant hexadecimal-digit
655 ///       hexadecimal-prefix: one of
656 ///         0x 0X
657 ///       binary-literal:
658 ///         0b binary-digit
659 ///         0B binary-digit
660 ///         binary-literal binary-digit
661 ///       integer-suffix:
662 ///         unsigned-suffix [long-suffix]
663 ///         unsigned-suffix [long-long-suffix]
664 ///         long-suffix [unsigned-suffix]
665 ///         long-long-suffix [unsigned-sufix]
666 ///       nonzero-digit:
667 ///         1 2 3 4 5 6 7 8 9
668 ///       octal-digit:
669 ///         0 1 2 3 4 5 6 7
670 ///       hexadecimal-digit:
671 ///         0 1 2 3 4 5 6 7 8 9
672 ///         a b c d e f
673 ///         A B C D E F
674 ///       binary-digit:
675 ///         0
676 ///         1
677 ///       unsigned-suffix: one of
678 ///         u U
679 ///       long-suffix: one of
680 ///         l L
681 ///       long-long-suffix: one of
682 ///         ll LL
683 ///
684 ///       floating-constant: [C99 6.4.4.2]
685 ///         TODO: add rules...
686 ///
687 NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
688                                            SourceLocation TokLoc,
689                                            const SourceManager &SM,
690                                            const LangOptions &LangOpts,
691                                            const TargetInfo &Target,
692                                            DiagnosticsEngine &Diags)
693     : SM(SM), LangOpts(LangOpts), Diags(Diags),
694       ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
695 
696   s = DigitsBegin = ThisTokBegin;
697   saw_exponent = false;
698   saw_period = false;
699   saw_ud_suffix = false;
700   saw_fixed_point_suffix = false;
701   isLong = false;
702   isUnsigned = false;
703   isLongLong = false;
704   isSizeT = false;
705   isHalf = false;
706   isFloat = false;
707   isImaginary = false;
708   isFloat16 = false;
709   isFloat128 = false;
710   MicrosoftInteger = 0;
711   isFract = false;
712   isAccum = false;
713   hadError = false;
714   isBitInt = false;
715 
716   // This routine assumes that the range begin/end matches the regex for integer
717   // and FP constants (specifically, the 'pp-number' regex), and assumes that
718   // the byte at "*end" is both valid and not part of the regex.  Because of
719   // this, it doesn't have to check for 'overscan' in various places.
720   if (isPreprocessingNumberBody(*ThisTokEnd)) {
721     Diags.Report(TokLoc, diag::err_lexing_numeric);
722     hadError = true;
723     return;
724   }
725 
726   if (*s == '0') { // parse radix
727     ParseNumberStartingWithZero(TokLoc);
728     if (hadError)
729       return;
730   } else { // the first digit is non-zero
731     radix = 10;
732     s = SkipDigits(s);
733     if (s == ThisTokEnd) {
734       // Done.
735     } else {
736       ParseDecimalOrOctalCommon(TokLoc);
737       if (hadError)
738         return;
739     }
740   }
741 
742   SuffixBegin = s;
743   checkSeparator(TokLoc, s, CSK_AfterDigits);
744 
745   // Initial scan to lookahead for fixed point suffix.
746   if (LangOpts.FixedPoint) {
747     for (const char *c = s; c != ThisTokEnd; ++c) {
748       if (*c == 'r' || *c == 'k' || *c == 'R' || *c == 'K') {
749         saw_fixed_point_suffix = true;
750         break;
751       }
752     }
753   }
754 
755   // Parse the suffix.  At this point we can classify whether we have an FP or
756   // integer constant.
757   bool isFixedPointConstant = isFixedPointLiteral();
758   bool isFPConstant = isFloatingLiteral();
759   bool HasSize = false;
760 
761   // Loop over all of the characters of the suffix.  If we see something bad,
762   // we break out of the loop.
763   for (; s != ThisTokEnd; ++s) {
764     switch (*s) {
765     case 'R':
766     case 'r':
767       if (!LangOpts.FixedPoint)
768         break;
769       if (isFract || isAccum) break;
770       if (!(saw_period || saw_exponent)) break;
771       isFract = true;
772       continue;
773     case 'K':
774     case 'k':
775       if (!LangOpts.FixedPoint)
776         break;
777       if (isFract || isAccum) break;
778       if (!(saw_period || saw_exponent)) break;
779       isAccum = true;
780       continue;
781     case 'h':      // FP Suffix for "half".
782     case 'H':
783       // OpenCL Extension v1.2 s9.5 - h or H suffix for half type.
784       if (!(LangOpts.Half || LangOpts.FixedPoint))
785         break;
786       if (isIntegerLiteral()) break;  // Error for integer constant.
787       if (HasSize)
788         break;
789       HasSize = true;
790       isHalf = true;
791       continue;  // Success.
792     case 'f':      // FP Suffix for "float"
793     case 'F':
794       if (!isFPConstant) break;  // Error for integer constant.
795       if (HasSize)
796         break;
797       HasSize = true;
798 
799       // CUDA host and device may have different _Float16 support, therefore
800       // allows f16 literals to avoid false alarm.
801       // ToDo: more precise check for CUDA.
802       if ((Target.hasFloat16Type() || LangOpts.CUDA) && s + 2 < ThisTokEnd &&
803           s[1] == '1' && s[2] == '6') {
804         s += 2; // success, eat up 2 characters.
805         isFloat16 = true;
806         continue;
807       }
808 
809       isFloat = true;
810       continue;  // Success.
811     case 'q':    // FP Suffix for "__float128"
812     case 'Q':
813       if (!isFPConstant) break;  // Error for integer constant.
814       if (HasSize)
815         break;
816       HasSize = true;
817       isFloat128 = true;
818       continue;  // Success.
819     case 'u':
820     case 'U':
821       if (isFPConstant) break;  // Error for floating constant.
822       if (isUnsigned) break;    // Cannot be repeated.
823       isUnsigned = true;
824       continue;  // Success.
825     case 'l':
826     case 'L':
827       if (HasSize)
828         break;
829       HasSize = true;
830 
831       // Check for long long.  The L's need to be adjacent and the same case.
832       if (s[1] == s[0]) {
833         assert(s + 1 < ThisTokEnd && "didn't maximally munch?");
834         if (isFPConstant) break;        // long long invalid for floats.
835         isLongLong = true;
836         ++s;  // Eat both of them.
837       } else {
838         isLong = true;
839       }
840       continue; // Success.
841     case 'z':
842     case 'Z':
843       if (isFPConstant)
844         break; // Invalid for floats.
845       if (HasSize)
846         break;
847       HasSize = true;
848       isSizeT = true;
849       continue;
850     case 'i':
851     case 'I':
852       if (LangOpts.MicrosoftExt && !isFPConstant) {
853         // Allow i8, i16, i32, and i64. First, look ahead and check if
854         // suffixes are Microsoft integers and not the imaginary unit.
855         uint8_t Bits = 0;
856         size_t ToSkip = 0;
857         switch (s[1]) {
858         case '8': // i8 suffix
859           Bits = 8;
860           ToSkip = 2;
861           break;
862         case '1':
863           if (s[2] == '6') { // i16 suffix
864             Bits = 16;
865             ToSkip = 3;
866           }
867           break;
868         case '3':
869           if (s[2] == '2') { // i32 suffix
870             Bits = 32;
871             ToSkip = 3;
872           }
873           break;
874         case '6':
875           if (s[2] == '4') { // i64 suffix
876             Bits = 64;
877             ToSkip = 3;
878           }
879           break;
880         default:
881           break;
882         }
883         if (Bits) {
884           if (HasSize)
885             break;
886           HasSize = true;
887           MicrosoftInteger = Bits;
888           s += ToSkip;
889           assert(s <= ThisTokEnd && "didn't maximally munch?");
890           break;
891         }
892       }
893       LLVM_FALLTHROUGH;
894     case 'j':
895     case 'J':
896       if (isImaginary) break;   // Cannot be repeated.
897       isImaginary = true;
898       continue;  // Success.
899     case 'w':
900     case 'W':
901       if (isFPConstant)
902         break; // Invalid for floats.
903       if (HasSize)
904         break; // Invalid if we already have a size for the literal.
905 
906       // wb and WB are allowed, but a mixture of cases like Wb or wB is not. We
907       // explicitly do not support the suffix in C++ as an extension because a
908       // library-based UDL that resolves to a library type may be more
909       // appropriate there.
910       if (!LangOpts.CPlusPlus && ((s[0] == 'w' && s[1] == 'b') ||
911           (s[0] == 'W' && s[1] == 'B'))) {
912         isBitInt = true;
913         HasSize = true;
914         ++s; // Skip both characters (2nd char skipped on continue).
915         continue; // Success.
916       }
917     }
918     // If we reached here, there was an error or a ud-suffix.
919     break;
920   }
921 
922   // "i", "if", and "il" are user-defined suffixes in C++1y.
923   if (s != ThisTokEnd || isImaginary) {
924     // FIXME: Don't bother expanding UCNs if !tok.hasUCN().
925     expandUCNs(UDSuffixBuf, StringRef(SuffixBegin, ThisTokEnd - SuffixBegin));
926     if (isValidUDSuffix(LangOpts, UDSuffixBuf)) {
927       if (!isImaginary) {
928         // Any suffix pieces we might have parsed are actually part of the
929         // ud-suffix.
930         isLong = false;
931         isUnsigned = false;
932         isLongLong = false;
933         isSizeT = false;
934         isFloat = false;
935         isFloat16 = false;
936         isHalf = false;
937         isImaginary = false;
938         isBitInt = false;
939         MicrosoftInteger = 0;
940         saw_fixed_point_suffix = false;
941         isFract = false;
942         isAccum = false;
943       }
944 
945       saw_ud_suffix = true;
946       return;
947     }
948 
949     if (s != ThisTokEnd) {
950       // Report an error if there are any.
951       Diags.Report(Lexer::AdvanceToTokenCharacter(
952                        TokLoc, SuffixBegin - ThisTokBegin, SM, LangOpts),
953                    diag::err_invalid_suffix_constant)
954           << StringRef(SuffixBegin, ThisTokEnd - SuffixBegin)
955           << (isFixedPointConstant ? 2 : isFPConstant);
956       hadError = true;
957     }
958   }
959 
960   if (!hadError && saw_fixed_point_suffix) {
961     assert(isFract || isAccum);
962   }
963 }
964 
965 /// ParseDecimalOrOctalCommon - This method is called for decimal or octal
966 /// numbers. It issues an error for illegal digits, and handles floating point
967 /// parsing. If it detects a floating point number, the radix is set to 10.
968 void NumericLiteralParser::ParseDecimalOrOctalCommon(SourceLocation TokLoc){
969   assert((radix == 8 || radix == 10) && "Unexpected radix");
970 
971   // If we have a hex digit other than 'e' (which denotes a FP exponent) then
972   // the code is using an incorrect base.
973   if (isHexDigit(*s) && *s != 'e' && *s != 'E' &&
974       !isValidUDSuffix(LangOpts, StringRef(s, ThisTokEnd - s))) {
975     Diags.Report(
976         Lexer::AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin, SM, LangOpts),
977         diag::err_invalid_digit)
978         << StringRef(s, 1) << (radix == 8 ? 1 : 0);
979     hadError = true;
980     return;
981   }
982 
983   if (*s == '.') {
984     checkSeparator(TokLoc, s, CSK_AfterDigits);
985     s++;
986     radix = 10;
987     saw_period = true;
988     checkSeparator(TokLoc, s, CSK_BeforeDigits);
989     s = SkipDigits(s); // Skip suffix.
990   }
991   if (*s == 'e' || *s == 'E') { // exponent
992     checkSeparator(TokLoc, s, CSK_AfterDigits);
993     const char *Exponent = s;
994     s++;
995     radix = 10;
996     saw_exponent = true;
997     if (s != ThisTokEnd && (*s == '+' || *s == '-'))  s++; // sign
998     const char *first_non_digit = SkipDigits(s);
999     if (containsDigits(s, first_non_digit)) {
1000       checkSeparator(TokLoc, s, CSK_BeforeDigits);
1001       s = first_non_digit;
1002     } else {
1003       if (!hadError) {
1004         Diags.Report(Lexer::AdvanceToTokenCharacter(
1005                          TokLoc, Exponent - ThisTokBegin, SM, LangOpts),
1006                      diag::err_exponent_has_no_digits);
1007         hadError = true;
1008       }
1009       return;
1010     }
1011   }
1012 }
1013 
1014 /// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
1015 /// suffixes as ud-suffixes, because the diagnostic experience is better if we
1016 /// treat it as an invalid suffix.
1017 bool NumericLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
1018                                            StringRef Suffix) {
1019   if (!LangOpts.CPlusPlus11 || Suffix.empty())
1020     return false;
1021 
1022   // By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid.
1023   if (Suffix[0] == '_')
1024     return true;
1025 
1026   // In C++11, there are no library suffixes.
1027   if (!LangOpts.CPlusPlus14)
1028     return false;
1029 
1030   // In C++14, "s", "h", "min", "ms", "us", and "ns" are used in the library.
1031   // Per tweaked N3660, "il", "i", and "if" are also used in the library.
1032   // In C++2a "d" and "y" are used in the library.
1033   return llvm::StringSwitch<bool>(Suffix)
1034       .Cases("h", "min", "s", true)
1035       .Cases("ms", "us", "ns", true)
1036       .Cases("il", "i", "if", true)
1037       .Cases("d", "y", LangOpts.CPlusPlus20)
1038       .Default(false);
1039 }
1040 
1041 void NumericLiteralParser::checkSeparator(SourceLocation TokLoc,
1042                                           const char *Pos,
1043                                           CheckSeparatorKind IsAfterDigits) {
1044   if (IsAfterDigits == CSK_AfterDigits) {
1045     if (Pos == ThisTokBegin)
1046       return;
1047     --Pos;
1048   } else if (Pos == ThisTokEnd)
1049     return;
1050 
1051   if (isDigitSeparator(*Pos)) {
1052     Diags.Report(Lexer::AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin, SM,
1053                                                 LangOpts),
1054                  diag::err_digit_separator_not_between_digits)
1055         << IsAfterDigits;
1056     hadError = true;
1057   }
1058 }
1059 
1060 /// ParseNumberStartingWithZero - This method is called when the first character
1061 /// of the number is found to be a zero.  This means it is either an octal
1062 /// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
1063 /// a floating point number (01239.123e4).  Eat the prefix, determining the
1064 /// radix etc.
1065 void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
1066   assert(s[0] == '0' && "Invalid method call");
1067   s++;
1068 
1069   int c1 = s[0];
1070 
1071   // Handle a hex number like 0x1234.
1072   if ((c1 == 'x' || c1 == 'X') && (isHexDigit(s[1]) || s[1] == '.')) {
1073     s++;
1074     assert(s < ThisTokEnd && "didn't maximally munch?");
1075     radix = 16;
1076     DigitsBegin = s;
1077     s = SkipHexDigits(s);
1078     bool HasSignificandDigits = containsDigits(DigitsBegin, s);
1079     if (s == ThisTokEnd) {
1080       // Done.
1081     } else if (*s == '.') {
1082       s++;
1083       saw_period = true;
1084       const char *floatDigitsBegin = s;
1085       s = SkipHexDigits(s);
1086       if (containsDigits(floatDigitsBegin, s))
1087         HasSignificandDigits = true;
1088       if (HasSignificandDigits)
1089         checkSeparator(TokLoc, floatDigitsBegin, CSK_BeforeDigits);
1090     }
1091 
1092     if (!HasSignificandDigits) {
1093       Diags.Report(Lexer::AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin, SM,
1094                                                   LangOpts),
1095                    diag::err_hex_constant_requires)
1096           << LangOpts.CPlusPlus << 1;
1097       hadError = true;
1098       return;
1099     }
1100 
1101     // A binary exponent can appear with or with a '.'. If dotted, the
1102     // binary exponent is required.
1103     if (*s == 'p' || *s == 'P') {
1104       checkSeparator(TokLoc, s, CSK_AfterDigits);
1105       const char *Exponent = s;
1106       s++;
1107       saw_exponent = true;
1108       if (s != ThisTokEnd && (*s == '+' || *s == '-'))  s++; // sign
1109       const char *first_non_digit = SkipDigits(s);
1110       if (!containsDigits(s, first_non_digit)) {
1111         if (!hadError) {
1112           Diags.Report(Lexer::AdvanceToTokenCharacter(
1113                            TokLoc, Exponent - ThisTokBegin, SM, LangOpts),
1114                        diag::err_exponent_has_no_digits);
1115           hadError = true;
1116         }
1117         return;
1118       }
1119       checkSeparator(TokLoc, s, CSK_BeforeDigits);
1120       s = first_non_digit;
1121 
1122       if (!LangOpts.HexFloats)
1123         Diags.Report(TokLoc, LangOpts.CPlusPlus
1124                                  ? diag::ext_hex_literal_invalid
1125                                  : diag::ext_hex_constant_invalid);
1126       else if (LangOpts.CPlusPlus17)
1127         Diags.Report(TokLoc, diag::warn_cxx17_hex_literal);
1128     } else if (saw_period) {
1129       Diags.Report(Lexer::AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin, SM,
1130                                                   LangOpts),
1131                    diag::err_hex_constant_requires)
1132           << LangOpts.CPlusPlus << 0;
1133       hadError = true;
1134     }
1135     return;
1136   }
1137 
1138   // Handle simple binary numbers 0b01010
1139   if ((c1 == 'b' || c1 == 'B') && (s[1] == '0' || s[1] == '1')) {
1140     // 0b101010 is a C++1y / GCC extension.
1141     Diags.Report(TokLoc, LangOpts.CPlusPlus14
1142                              ? diag::warn_cxx11_compat_binary_literal
1143                          : LangOpts.CPlusPlus ? diag::ext_binary_literal_cxx14
1144                                               : diag::ext_binary_literal);
1145     ++s;
1146     assert(s < ThisTokEnd && "didn't maximally munch?");
1147     radix = 2;
1148     DigitsBegin = s;
1149     s = SkipBinaryDigits(s);
1150     if (s == ThisTokEnd) {
1151       // Done.
1152     } else if (isHexDigit(*s) &&
1153                !isValidUDSuffix(LangOpts, StringRef(s, ThisTokEnd - s))) {
1154       Diags.Report(Lexer::AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin, SM,
1155                                                   LangOpts),
1156                    diag::err_invalid_digit)
1157           << StringRef(s, 1) << 2;
1158       hadError = true;
1159     }
1160     // Other suffixes will be diagnosed by the caller.
1161     return;
1162   }
1163 
1164   // For now, the radix is set to 8. If we discover that we have a
1165   // floating point constant, the radix will change to 10. Octal floating
1166   // point constants are not permitted (only decimal and hexadecimal).
1167   radix = 8;
1168   const char *PossibleNewDigitStart = s;
1169   s = SkipOctalDigits(s);
1170   // When the value is 0 followed by a suffix (like 0wb), we want to leave 0
1171   // as the start of the digits. So if skipping octal digits does not skip
1172   // anything, we leave the digit start where it was.
1173   if (s != PossibleNewDigitStart)
1174     DigitsBegin = PossibleNewDigitStart;
1175 
1176   if (s == ThisTokEnd)
1177     return; // Done, simple octal number like 01234
1178 
1179   // If we have some other non-octal digit that *is* a decimal digit, see if
1180   // this is part of a floating point number like 094.123 or 09e1.
1181   if (isDigit(*s)) {
1182     const char *EndDecimal = SkipDigits(s);
1183     if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
1184       s = EndDecimal;
1185       radix = 10;
1186     }
1187   }
1188 
1189   ParseDecimalOrOctalCommon(TokLoc);
1190 }
1191 
1192 static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
1193   switch (Radix) {
1194   case 2:
1195     return NumDigits <= 64;
1196   case 8:
1197     return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
1198   case 10:
1199     return NumDigits <= 19; // floor(log10(2^64))
1200   case 16:
1201     return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
1202   default:
1203     llvm_unreachable("impossible Radix");
1204   }
1205 }
1206 
1207 /// GetIntegerValue - Convert this numeric literal value to an APInt that
1208 /// matches Val's input width.  If there is an overflow, set Val to the low bits
1209 /// of the result and return true.  Otherwise, return false.
1210 bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
1211   // Fast path: Compute a conservative bound on the maximum number of
1212   // bits per digit in this radix. If we can't possibly overflow a
1213   // uint64 based on that bound then do the simple conversion to
1214   // integer. This avoids the expensive overflow checking below, and
1215   // handles the common cases that matter (small decimal integers and
1216   // hex/octal values which don't overflow).
1217   const unsigned NumDigits = SuffixBegin - DigitsBegin;
1218   if (alwaysFitsInto64Bits(radix, NumDigits)) {
1219     uint64_t N = 0;
1220     for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr)
1221       if (!isDigitSeparator(*Ptr))
1222         N = N * radix + llvm::hexDigitValue(*Ptr);
1223 
1224     // This will truncate the value to Val's input width. Simply check
1225     // for overflow by comparing.
1226     Val = N;
1227     return Val.getZExtValue() != N;
1228   }
1229 
1230   Val = 0;
1231   const char *Ptr = DigitsBegin;
1232 
1233   llvm::APInt RadixVal(Val.getBitWidth(), radix);
1234   llvm::APInt CharVal(Val.getBitWidth(), 0);
1235   llvm::APInt OldVal = Val;
1236 
1237   bool OverflowOccurred = false;
1238   while (Ptr < SuffixBegin) {
1239     if (isDigitSeparator(*Ptr)) {
1240       ++Ptr;
1241       continue;
1242     }
1243 
1244     unsigned C = llvm::hexDigitValue(*Ptr++);
1245 
1246     // If this letter is out of bound for this radix, reject it.
1247     assert(C < radix && "NumericLiteralParser ctor should have rejected this");
1248 
1249     CharVal = C;
1250 
1251     // Add the digit to the value in the appropriate radix.  If adding in digits
1252     // made the value smaller, then this overflowed.
1253     OldVal = Val;
1254 
1255     // Multiply by radix, did overflow occur on the multiply?
1256     Val *= RadixVal;
1257     OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
1258 
1259     // Add value, did overflow occur on the value?
1260     //   (a + b) ult b  <=> overflow
1261     Val += CharVal;
1262     OverflowOccurred |= Val.ult(CharVal);
1263   }
1264   return OverflowOccurred;
1265 }
1266 
1267 llvm::APFloat::opStatus
1268 NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
1269   using llvm::APFloat;
1270 
1271   unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
1272 
1273   llvm::SmallString<16> Buffer;
1274   StringRef Str(ThisTokBegin, n);
1275   if (Str.contains('\'')) {
1276     Buffer.reserve(n);
1277     std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer),
1278                         &isDigitSeparator);
1279     Str = Buffer;
1280   }
1281 
1282   auto StatusOrErr =
1283       Result.convertFromString(Str, APFloat::rmNearestTiesToEven);
1284   assert(StatusOrErr && "Invalid floating point representation");
1285   return !errorToBool(StatusOrErr.takeError()) ? *StatusOrErr
1286                                                : APFloat::opInvalidOp;
1287 }
1288 
1289 static inline bool IsExponentPart(char c) {
1290   return c == 'p' || c == 'P' || c == 'e' || c == 'E';
1291 }
1292 
1293 bool NumericLiteralParser::GetFixedPointValue(llvm::APInt &StoreVal, unsigned Scale) {
1294   assert(radix == 16 || radix == 10);
1295 
1296   // Find how many digits are needed to store the whole literal.
1297   unsigned NumDigits = SuffixBegin - DigitsBegin;
1298   if (saw_period) --NumDigits;
1299 
1300   // Initial scan of the exponent if it exists
1301   bool ExpOverflowOccurred = false;
1302   bool NegativeExponent = false;
1303   const char *ExponentBegin;
1304   uint64_t Exponent = 0;
1305   int64_t BaseShift = 0;
1306   if (saw_exponent) {
1307     const char *Ptr = DigitsBegin;
1308 
1309     while (!IsExponentPart(*Ptr)) ++Ptr;
1310     ExponentBegin = Ptr;
1311     ++Ptr;
1312     NegativeExponent = *Ptr == '-';
1313     if (NegativeExponent) ++Ptr;
1314 
1315     unsigned NumExpDigits = SuffixBegin - Ptr;
1316     if (alwaysFitsInto64Bits(radix, NumExpDigits)) {
1317       llvm::StringRef ExpStr(Ptr, NumExpDigits);
1318       llvm::APInt ExpInt(/*numBits=*/64, ExpStr, /*radix=*/10);
1319       Exponent = ExpInt.getZExtValue();
1320     } else {
1321       ExpOverflowOccurred = true;
1322     }
1323 
1324     if (NegativeExponent) BaseShift -= Exponent;
1325     else BaseShift += Exponent;
1326   }
1327 
1328   // Number of bits needed for decimal literal is
1329   //   ceil(NumDigits * log2(10))       Integral part
1330   // + Scale                            Fractional part
1331   // + ceil(Exponent * log2(10))        Exponent
1332   // --------------------------------------------------
1333   //   ceil((NumDigits + Exponent) * log2(10)) + Scale
1334   //
1335   // But for simplicity in handling integers, we can round up log2(10) to 4,
1336   // making:
1337   // 4 * (NumDigits + Exponent) + Scale
1338   //
1339   // Number of digits needed for hexadecimal literal is
1340   //   4 * NumDigits                    Integral part
1341   // + Scale                            Fractional part
1342   // + Exponent                         Exponent
1343   // --------------------------------------------------
1344   //   (4 * NumDigits) + Scale + Exponent
1345   uint64_t NumBitsNeeded;
1346   if (radix == 10)
1347     NumBitsNeeded = 4 * (NumDigits + Exponent) + Scale;
1348   else
1349     NumBitsNeeded = 4 * NumDigits + Exponent + Scale;
1350 
1351   if (NumBitsNeeded > std::numeric_limits<unsigned>::max())
1352     ExpOverflowOccurred = true;
1353   llvm::APInt Val(static_cast<unsigned>(NumBitsNeeded), 0, /*isSigned=*/false);
1354 
1355   bool FoundDecimal = false;
1356 
1357   int64_t FractBaseShift = 0;
1358   const char *End = saw_exponent ? ExponentBegin : SuffixBegin;
1359   for (const char *Ptr = DigitsBegin; Ptr < End; ++Ptr) {
1360     if (*Ptr == '.') {
1361       FoundDecimal = true;
1362       continue;
1363     }
1364 
1365     // Normal reading of an integer
1366     unsigned C = llvm::hexDigitValue(*Ptr);
1367     assert(C < radix && "NumericLiteralParser ctor should have rejected this");
1368 
1369     Val *= radix;
1370     Val += C;
1371 
1372     if (FoundDecimal)
1373       // Keep track of how much we will need to adjust this value by from the
1374       // number of digits past the radix point.
1375       --FractBaseShift;
1376   }
1377 
1378   // For a radix of 16, we will be multiplying by 2 instead of 16.
1379   if (radix == 16) FractBaseShift *= 4;
1380   BaseShift += FractBaseShift;
1381 
1382   Val <<= Scale;
1383 
1384   uint64_t Base = (radix == 16) ? 2 : 10;
1385   if (BaseShift > 0) {
1386     for (int64_t i = 0; i < BaseShift; ++i) {
1387       Val *= Base;
1388     }
1389   } else if (BaseShift < 0) {
1390     for (int64_t i = BaseShift; i < 0 && !Val.isZero(); ++i)
1391       Val = Val.udiv(Base);
1392   }
1393 
1394   bool IntOverflowOccurred = false;
1395   auto MaxVal = llvm::APInt::getMaxValue(StoreVal.getBitWidth());
1396   if (Val.getBitWidth() > StoreVal.getBitWidth()) {
1397     IntOverflowOccurred |= Val.ugt(MaxVal.zext(Val.getBitWidth()));
1398     StoreVal = Val.trunc(StoreVal.getBitWidth());
1399   } else if (Val.getBitWidth() < StoreVal.getBitWidth()) {
1400     IntOverflowOccurred |= Val.zext(MaxVal.getBitWidth()).ugt(MaxVal);
1401     StoreVal = Val.zext(StoreVal.getBitWidth());
1402   } else {
1403     StoreVal = Val;
1404   }
1405 
1406   return IntOverflowOccurred || ExpOverflowOccurred;
1407 }
1408 
1409 /// \verbatim
1410 ///       user-defined-character-literal: [C++11 lex.ext]
1411 ///         character-literal ud-suffix
1412 ///       ud-suffix:
1413 ///         identifier
1414 ///       character-literal: [C++11 lex.ccon]
1415 ///         ' c-char-sequence '
1416 ///         u' c-char-sequence '
1417 ///         U' c-char-sequence '
1418 ///         L' c-char-sequence '
1419 ///         u8' c-char-sequence ' [C++1z lex.ccon]
1420 ///       c-char-sequence:
1421 ///         c-char
1422 ///         c-char-sequence c-char
1423 ///       c-char:
1424 ///         any member of the source character set except the single-quote ',
1425 ///           backslash \, or new-line character
1426 ///         escape-sequence
1427 ///         universal-character-name
1428 ///       escape-sequence:
1429 ///         simple-escape-sequence
1430 ///         octal-escape-sequence
1431 ///         hexadecimal-escape-sequence
1432 ///       simple-escape-sequence:
1433 ///         one of \' \" \? \\ \a \b \f \n \r \t \v
1434 ///       octal-escape-sequence:
1435 ///         \ octal-digit
1436 ///         \ octal-digit octal-digit
1437 ///         \ octal-digit octal-digit octal-digit
1438 ///       hexadecimal-escape-sequence:
1439 ///         \x hexadecimal-digit
1440 ///         hexadecimal-escape-sequence hexadecimal-digit
1441 ///       universal-character-name: [C++11 lex.charset]
1442 ///         \u hex-quad
1443 ///         \U hex-quad hex-quad
1444 ///       hex-quad:
1445 ///         hex-digit hex-digit hex-digit hex-digit
1446 /// \endverbatim
1447 ///
1448 CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
1449                                      SourceLocation Loc, Preprocessor &PP,
1450                                      tok::TokenKind kind) {
1451   // At this point we know that the character matches the regex "(L|u|U)?'.*'".
1452   HadError = false;
1453 
1454   Kind = kind;
1455 
1456   const char *TokBegin = begin;
1457 
1458   // Skip over wide character determinant.
1459   if (Kind != tok::char_constant)
1460     ++begin;
1461   if (Kind == tok::utf8_char_constant)
1462     ++begin;
1463 
1464   // Skip over the entry quote.
1465   if (begin[0] != '\'') {
1466     PP.Diag(Loc, diag::err_lexing_char);
1467     HadError = true;
1468     return;
1469   }
1470 
1471   ++begin;
1472 
1473   // Remove an optional ud-suffix.
1474   if (end[-1] != '\'') {
1475     const char *UDSuffixEnd = end;
1476     do {
1477       --end;
1478     } while (end[-1] != '\'');
1479     // FIXME: Don't bother with this if !tok.hasUCN().
1480     expandUCNs(UDSuffixBuf, StringRef(end, UDSuffixEnd - end));
1481     UDSuffixOffset = end - TokBegin;
1482   }
1483 
1484   // Trim the ending quote.
1485   assert(end != begin && "Invalid token lexed");
1486   --end;
1487 
1488   // FIXME: The "Value" is an uint64_t so we can handle char literals of
1489   // up to 64-bits.
1490   // FIXME: This extensively assumes that 'char' is 8-bits.
1491   assert(PP.getTargetInfo().getCharWidth() == 8 &&
1492          "Assumes char is 8 bits");
1493   assert(PP.getTargetInfo().getIntWidth() <= 64 &&
1494          (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
1495          "Assumes sizeof(int) on target is <= 64 and a multiple of char");
1496   assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
1497          "Assumes sizeof(wchar) on target is <= 64");
1498 
1499   SmallVector<uint32_t, 4> codepoint_buffer;
1500   codepoint_buffer.resize(end - begin);
1501   uint32_t *buffer_begin = &codepoint_buffer.front();
1502   uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
1503 
1504   // Unicode escapes representing characters that cannot be correctly
1505   // represented in a single code unit are disallowed in character literals
1506   // by this implementation.
1507   uint32_t largest_character_for_kind;
1508   if (tok::wide_char_constant == Kind) {
1509     largest_character_for_kind =
1510         0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
1511   } else if (tok::utf8_char_constant == Kind) {
1512     largest_character_for_kind = 0x7F;
1513   } else if (tok::utf16_char_constant == Kind) {
1514     largest_character_for_kind = 0xFFFF;
1515   } else if (tok::utf32_char_constant == Kind) {
1516     largest_character_for_kind = 0x10FFFF;
1517   } else {
1518     largest_character_for_kind = 0x7Fu;
1519   }
1520 
1521   while (begin != end) {
1522     // Is this a span of non-escape characters?
1523     if (begin[0] != '\\') {
1524       char const *start = begin;
1525       do {
1526         ++begin;
1527       } while (begin != end && *begin != '\\');
1528 
1529       char const *tmp_in_start = start;
1530       uint32_t *tmp_out_start = buffer_begin;
1531       llvm::ConversionResult res =
1532           llvm::ConvertUTF8toUTF32(reinterpret_cast<llvm::UTF8 const **>(&start),
1533                              reinterpret_cast<llvm::UTF8 const *>(begin),
1534                              &buffer_begin, buffer_end, llvm::strictConversion);
1535       if (res != llvm::conversionOK) {
1536         // If we see bad encoding for unprefixed character literals, warn and
1537         // simply copy the byte values, for compatibility with gcc and
1538         // older versions of clang.
1539         bool NoErrorOnBadEncoding = isAscii();
1540         unsigned Msg = diag::err_bad_character_encoding;
1541         if (NoErrorOnBadEncoding)
1542           Msg = diag::warn_bad_character_encoding;
1543         PP.Diag(Loc, Msg);
1544         if (NoErrorOnBadEncoding) {
1545           start = tmp_in_start;
1546           buffer_begin = tmp_out_start;
1547           for (; start != begin; ++start, ++buffer_begin)
1548             *buffer_begin = static_cast<uint8_t>(*start);
1549         } else {
1550           HadError = true;
1551         }
1552       } else {
1553         for (; tmp_out_start < buffer_begin; ++tmp_out_start) {
1554           if (*tmp_out_start > largest_character_for_kind) {
1555             HadError = true;
1556             PP.Diag(Loc, diag::err_character_too_large);
1557           }
1558         }
1559       }
1560 
1561       continue;
1562     }
1563     // Is this a Universal Character Name escape?
1564     if (begin[1] == 'u' || begin[1] == 'U') {
1565       unsigned short UcnLen = 0;
1566       if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
1567                             FullSourceLoc(Loc, PP.getSourceManager()),
1568                             &PP.getDiagnostics(), PP.getLangOpts(), true)) {
1569         HadError = true;
1570       } else if (*buffer_begin > largest_character_for_kind) {
1571         HadError = true;
1572         PP.Diag(Loc, diag::err_character_too_large);
1573       }
1574 
1575       ++buffer_begin;
1576       continue;
1577     }
1578     unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
1579     uint64_t result =
1580       ProcessCharEscape(TokBegin, begin, end, HadError,
1581                         FullSourceLoc(Loc,PP.getSourceManager()),
1582                         CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
1583     *buffer_begin++ = result;
1584   }
1585 
1586   unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front();
1587 
1588   if (NumCharsSoFar > 1) {
1589     if (isAscii() && NumCharsSoFar == 4)
1590       PP.Diag(Loc, diag::warn_four_char_character_literal);
1591     else if (isAscii())
1592       PP.Diag(Loc, diag::warn_multichar_character_literal);
1593     else {
1594       PP.Diag(Loc, diag::err_multichar_character_literal) << (isWide() ? 0 : 1);
1595       HadError = true;
1596     }
1597     IsMultiChar = true;
1598   } else {
1599     IsMultiChar = false;
1600   }
1601 
1602   llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
1603 
1604   // Narrow character literals act as though their value is concatenated
1605   // in this implementation, but warn on overflow.
1606   bool multi_char_too_long = false;
1607   if (isAscii() && isMultiChar()) {
1608     LitVal = 0;
1609     for (size_t i = 0; i < NumCharsSoFar; ++i) {
1610       // check for enough leading zeros to shift into
1611       multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
1612       LitVal <<= 8;
1613       LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
1614     }
1615   } else if (NumCharsSoFar > 0) {
1616     // otherwise just take the last character
1617     LitVal = buffer_begin[-1];
1618   }
1619 
1620   if (!HadError && multi_char_too_long) {
1621     PP.Diag(Loc, diag::warn_char_constant_too_large);
1622   }
1623 
1624   // Transfer the value from APInt to uint64_t
1625   Value = LitVal.getZExtValue();
1626 
1627   // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1628   // if 'char' is signed for this target (C99 6.4.4.4p10).  Note that multiple
1629   // character constants are not sign extended in the this implementation:
1630   // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
1631   if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
1632       PP.getLangOpts().CharIsSigned)
1633     Value = (signed char)Value;
1634 }
1635 
1636 /// \verbatim
1637 ///       string-literal: [C++0x lex.string]
1638 ///         encoding-prefix " [s-char-sequence] "
1639 ///         encoding-prefix R raw-string
1640 ///       encoding-prefix:
1641 ///         u8
1642 ///         u
1643 ///         U
1644 ///         L
1645 ///       s-char-sequence:
1646 ///         s-char
1647 ///         s-char-sequence s-char
1648 ///       s-char:
1649 ///         any member of the source character set except the double-quote ",
1650 ///           backslash \, or new-line character
1651 ///         escape-sequence
1652 ///         universal-character-name
1653 ///       raw-string:
1654 ///         " d-char-sequence ( r-char-sequence ) d-char-sequence "
1655 ///       r-char-sequence:
1656 ///         r-char
1657 ///         r-char-sequence r-char
1658 ///       r-char:
1659 ///         any member of the source character set, except a right parenthesis )
1660 ///           followed by the initial d-char-sequence (which may be empty)
1661 ///           followed by a double quote ".
1662 ///       d-char-sequence:
1663 ///         d-char
1664 ///         d-char-sequence d-char
1665 ///       d-char:
1666 ///         any member of the basic source character set except:
1667 ///           space, the left parenthesis (, the right parenthesis ),
1668 ///           the backslash \, and the control characters representing horizontal
1669 ///           tab, vertical tab, form feed, and newline.
1670 ///       escape-sequence: [C++0x lex.ccon]
1671 ///         simple-escape-sequence
1672 ///         octal-escape-sequence
1673 ///         hexadecimal-escape-sequence
1674 ///       simple-escape-sequence:
1675 ///         one of \' \" \? \\ \a \b \f \n \r \t \v
1676 ///       octal-escape-sequence:
1677 ///         \ octal-digit
1678 ///         \ octal-digit octal-digit
1679 ///         \ octal-digit octal-digit octal-digit
1680 ///       hexadecimal-escape-sequence:
1681 ///         \x hexadecimal-digit
1682 ///         hexadecimal-escape-sequence hexadecimal-digit
1683 ///       universal-character-name:
1684 ///         \u hex-quad
1685 ///         \U hex-quad hex-quad
1686 ///       hex-quad:
1687 ///         hex-digit hex-digit hex-digit hex-digit
1688 /// \endverbatim
1689 ///
1690 StringLiteralParser::
1691 StringLiteralParser(ArrayRef<Token> StringToks,
1692                     Preprocessor &PP)
1693   : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
1694     Target(PP.getTargetInfo()), Diags(&PP.getDiagnostics()),
1695     MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1696     ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
1697   init(StringToks);
1698 }
1699 
1700 void StringLiteralParser::init(ArrayRef<Token> StringToks){
1701   // The literal token may have come from an invalid source location (e.g. due
1702   // to a PCH error), in which case the token length will be 0.
1703   if (StringToks.empty() || StringToks[0].getLength() < 2)
1704     return DiagnoseLexingError(SourceLocation());
1705 
1706   // Scan all of the string portions, remember the max individual token length,
1707   // computing a bound on the concatenated string length, and see whether any
1708   // piece is a wide-string.  If any of the string portions is a wide-string
1709   // literal, the result is a wide-string literal [C99 6.4.5p4].
1710   assert(!StringToks.empty() && "expected at least one token");
1711   MaxTokenLength = StringToks[0].getLength();
1712   assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
1713   SizeBound = StringToks[0].getLength()-2;  // -2 for "".
1714   Kind = StringToks[0].getKind();
1715 
1716   hadError = false;
1717 
1718   // Implement Translation Phase #6: concatenation of string literals
1719   /// (C99 5.1.1.2p1).  The common case is only one string fragment.
1720   for (unsigned i = 1; i != StringToks.size(); ++i) {
1721     if (StringToks[i].getLength() < 2)
1722       return DiagnoseLexingError(StringToks[i].getLocation());
1723 
1724     // The string could be shorter than this if it needs cleaning, but this is a
1725     // reasonable bound, which is all we need.
1726     assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
1727     SizeBound += StringToks[i].getLength()-2;  // -2 for "".
1728 
1729     // Remember maximum string piece length.
1730     if (StringToks[i].getLength() > MaxTokenLength)
1731       MaxTokenLength = StringToks[i].getLength();
1732 
1733     // Remember if we see any wide or utf-8/16/32 strings.
1734     // Also check for illegal concatenations.
1735     if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
1736       if (isAscii()) {
1737         Kind = StringToks[i].getKind();
1738       } else {
1739         if (Diags)
1740           Diags->Report(StringToks[i].getLocation(),
1741                         diag::err_unsupported_string_concat);
1742         hadError = true;
1743       }
1744     }
1745   }
1746 
1747   // Include space for the null terminator.
1748   ++SizeBound;
1749 
1750   // TODO: K&R warning: "traditional C rejects string constant concatenation"
1751 
1752   // Get the width in bytes of char/wchar_t/char16_t/char32_t
1753   CharByteWidth = getCharWidth(Kind, Target);
1754   assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1755   CharByteWidth /= 8;
1756 
1757   // The output buffer size needs to be large enough to hold wide characters.
1758   // This is a worst-case assumption which basically corresponds to L"" "long".
1759   SizeBound *= CharByteWidth;
1760 
1761   // Size the temporary buffer to hold the result string data.
1762   ResultBuf.resize(SizeBound);
1763 
1764   // Likewise, but for each string piece.
1765   SmallString<512> TokenBuf;
1766   TokenBuf.resize(MaxTokenLength);
1767 
1768   // Loop over all the strings, getting their spelling, and expanding them to
1769   // wide strings as appropriate.
1770   ResultPtr = &ResultBuf[0];   // Next byte to fill in.
1771 
1772   Pascal = false;
1773 
1774   SourceLocation UDSuffixTokLoc;
1775 
1776   for (unsigned i = 0, e = StringToks.size(); i != e; ++i) {
1777     const char *ThisTokBuf = &TokenBuf[0];
1778     // Get the spelling of the token, which eliminates trigraphs, etc.  We know
1779     // that ThisTokBuf points to a buffer that is big enough for the whole token
1780     // and 'spelled' tokens can only shrink.
1781     bool StringInvalid = false;
1782     unsigned ThisTokLen =
1783       Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1784                          &StringInvalid);
1785     if (StringInvalid)
1786       return DiagnoseLexingError(StringToks[i].getLocation());
1787 
1788     const char *ThisTokBegin = ThisTokBuf;
1789     const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1790 
1791     // Remove an optional ud-suffix.
1792     if (ThisTokEnd[-1] != '"') {
1793       const char *UDSuffixEnd = ThisTokEnd;
1794       do {
1795         --ThisTokEnd;
1796       } while (ThisTokEnd[-1] != '"');
1797 
1798       StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1799 
1800       if (UDSuffixBuf.empty()) {
1801         if (StringToks[i].hasUCN())
1802           expandUCNs(UDSuffixBuf, UDSuffix);
1803         else
1804           UDSuffixBuf.assign(UDSuffix);
1805         UDSuffixToken = i;
1806         UDSuffixOffset = ThisTokEnd - ThisTokBuf;
1807         UDSuffixTokLoc = StringToks[i].getLocation();
1808       } else {
1809         SmallString<32> ExpandedUDSuffix;
1810         if (StringToks[i].hasUCN()) {
1811           expandUCNs(ExpandedUDSuffix, UDSuffix);
1812           UDSuffix = ExpandedUDSuffix;
1813         }
1814 
1815         // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1816         // result of a concatenation involving at least one user-defined-string-
1817         // literal, all the participating user-defined-string-literals shall
1818         // have the same ud-suffix.
1819         if (UDSuffixBuf != UDSuffix) {
1820           if (Diags) {
1821             SourceLocation TokLoc = StringToks[i].getLocation();
1822             Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1823               << UDSuffixBuf << UDSuffix
1824               << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1825               << SourceRange(TokLoc, TokLoc);
1826           }
1827           hadError = true;
1828         }
1829       }
1830     }
1831 
1832     // Strip the end quote.
1833     --ThisTokEnd;
1834 
1835     // TODO: Input character set mapping support.
1836 
1837     // Skip marker for wide or unicode strings.
1838     if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
1839       ++ThisTokBuf;
1840       // Skip 8 of u8 marker for utf8 strings.
1841       if (ThisTokBuf[0] == '8')
1842         ++ThisTokBuf;
1843     }
1844 
1845     // Check for raw string
1846     if (ThisTokBuf[0] == 'R') {
1847       if (ThisTokBuf[1] != '"') {
1848         // The file may have come from PCH and then changed after loading the
1849         // PCH; Fail gracefully.
1850         return DiagnoseLexingError(StringToks[i].getLocation());
1851       }
1852       ThisTokBuf += 2; // skip R"
1853 
1854       // C++11 [lex.string]p2: A `d-char-sequence` shall consist of at most 16
1855       // characters.
1856       constexpr unsigned MaxRawStrDelimLen = 16;
1857 
1858       const char *Prefix = ThisTokBuf;
1859       while (static_cast<unsigned>(ThisTokBuf - Prefix) < MaxRawStrDelimLen &&
1860              ThisTokBuf[0] != '(')
1861         ++ThisTokBuf;
1862       if (ThisTokBuf[0] != '(')
1863         return DiagnoseLexingError(StringToks[i].getLocation());
1864       ++ThisTokBuf; // skip '('
1865 
1866       // Remove same number of characters from the end
1867       ThisTokEnd -= ThisTokBuf - Prefix;
1868       if (ThisTokEnd < ThisTokBuf)
1869         return DiagnoseLexingError(StringToks[i].getLocation());
1870 
1871       // C++14 [lex.string]p4: A source-file new-line in a raw string literal
1872       // results in a new-line in the resulting execution string-literal.
1873       StringRef RemainingTokenSpan(ThisTokBuf, ThisTokEnd - ThisTokBuf);
1874       while (!RemainingTokenSpan.empty()) {
1875         // Split the string literal on \r\n boundaries.
1876         size_t CRLFPos = RemainingTokenSpan.find("\r\n");
1877         StringRef BeforeCRLF = RemainingTokenSpan.substr(0, CRLFPos);
1878         StringRef AfterCRLF = RemainingTokenSpan.substr(CRLFPos);
1879 
1880         // Copy everything before the \r\n sequence into the string literal.
1881         if (CopyStringFragment(StringToks[i], ThisTokBegin, BeforeCRLF))
1882           hadError = true;
1883 
1884         // Point into the \n inside the \r\n sequence and operate on the
1885         // remaining portion of the literal.
1886         RemainingTokenSpan = AfterCRLF.substr(1);
1887       }
1888     } else {
1889       if (ThisTokBuf[0] != '"') {
1890         // The file may have come from PCH and then changed after loading the
1891         // PCH; Fail gracefully.
1892         return DiagnoseLexingError(StringToks[i].getLocation());
1893       }
1894       ++ThisTokBuf; // skip "
1895 
1896       // Check if this is a pascal string
1897       if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
1898           ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
1899 
1900         // If the \p sequence is found in the first token, we have a pascal string
1901         // Otherwise, if we already have a pascal string, ignore the first \p
1902         if (i == 0) {
1903           ++ThisTokBuf;
1904           Pascal = true;
1905         } else if (Pascal)
1906           ThisTokBuf += 2;
1907       }
1908 
1909       while (ThisTokBuf != ThisTokEnd) {
1910         // Is this a span of non-escape characters?
1911         if (ThisTokBuf[0] != '\\') {
1912           const char *InStart = ThisTokBuf;
1913           do {
1914             ++ThisTokBuf;
1915           } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
1916 
1917           // Copy the character span over.
1918           if (CopyStringFragment(StringToks[i], ThisTokBegin,
1919                                  StringRef(InStart, ThisTokBuf - InStart)))
1920             hadError = true;
1921           continue;
1922         }
1923         // Is this a Universal Character Name escape?
1924         if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
1925           EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1926                           ResultPtr, hadError,
1927                           FullSourceLoc(StringToks[i].getLocation(), SM),
1928                           CharByteWidth, Diags, Features);
1929           continue;
1930         }
1931         // Otherwise, this is a non-UCN escape character.  Process it.
1932         unsigned ResultChar =
1933           ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
1934                             FullSourceLoc(StringToks[i].getLocation(), SM),
1935                             CharByteWidth*8, Diags, Features);
1936 
1937         if (CharByteWidth == 4) {
1938           // FIXME: Make the type of the result buffer correct instead of
1939           // using reinterpret_cast.
1940           llvm::UTF32 *ResultWidePtr = reinterpret_cast<llvm::UTF32*>(ResultPtr);
1941           *ResultWidePtr = ResultChar;
1942           ResultPtr += 4;
1943         } else if (CharByteWidth == 2) {
1944           // FIXME: Make the type of the result buffer correct instead of
1945           // using reinterpret_cast.
1946           llvm::UTF16 *ResultWidePtr = reinterpret_cast<llvm::UTF16*>(ResultPtr);
1947           *ResultWidePtr = ResultChar & 0xFFFF;
1948           ResultPtr += 2;
1949         } else {
1950           assert(CharByteWidth == 1 && "Unexpected char width");
1951           *ResultPtr++ = ResultChar & 0xFF;
1952         }
1953       }
1954     }
1955   }
1956 
1957   if (Pascal) {
1958     if (CharByteWidth == 4) {
1959       // FIXME: Make the type of the result buffer correct instead of
1960       // using reinterpret_cast.
1961       llvm::UTF32 *ResultWidePtr = reinterpret_cast<llvm::UTF32*>(ResultBuf.data());
1962       ResultWidePtr[0] = GetNumStringChars() - 1;
1963     } else if (CharByteWidth == 2) {
1964       // FIXME: Make the type of the result buffer correct instead of
1965       // using reinterpret_cast.
1966       llvm::UTF16 *ResultWidePtr = reinterpret_cast<llvm::UTF16*>(ResultBuf.data());
1967       ResultWidePtr[0] = GetNumStringChars() - 1;
1968     } else {
1969       assert(CharByteWidth == 1 && "Unexpected char width");
1970       ResultBuf[0] = GetNumStringChars() - 1;
1971     }
1972 
1973     // Verify that pascal strings aren't too large.
1974     if (GetStringLength() > 256) {
1975       if (Diags)
1976         Diags->Report(StringToks.front().getLocation(),
1977                       diag::err_pascal_string_too_long)
1978           << SourceRange(StringToks.front().getLocation(),
1979                          StringToks.back().getLocation());
1980       hadError = true;
1981       return;
1982     }
1983   } else if (Diags) {
1984     // Complain if this string literal has too many characters.
1985     unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
1986 
1987     if (GetNumStringChars() > MaxChars)
1988       Diags->Report(StringToks.front().getLocation(),
1989                     diag::ext_string_too_long)
1990         << GetNumStringChars() << MaxChars
1991         << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
1992         << SourceRange(StringToks.front().getLocation(),
1993                        StringToks.back().getLocation());
1994   }
1995 }
1996 
1997 static const char *resyncUTF8(const char *Err, const char *End) {
1998   if (Err == End)
1999     return End;
2000   End = Err + std::min<unsigned>(llvm::getNumBytesForUTF8(*Err), End-Err);
2001   while (++Err != End && (*Err & 0xC0) == 0x80)
2002     ;
2003   return Err;
2004 }
2005 
2006 /// This function copies from Fragment, which is a sequence of bytes
2007 /// within Tok's contents (which begin at TokBegin) into ResultPtr.
2008 /// Performs widening for multi-byte characters.
2009 bool StringLiteralParser::CopyStringFragment(const Token &Tok,
2010                                              const char *TokBegin,
2011                                              StringRef Fragment) {
2012   const llvm::UTF8 *ErrorPtrTmp;
2013   if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
2014     return false;
2015 
2016   // If we see bad encoding for unprefixed string literals, warn and
2017   // simply copy the byte values, for compatibility with gcc and older
2018   // versions of clang.
2019   bool NoErrorOnBadEncoding = isAscii();
2020   if (NoErrorOnBadEncoding) {
2021     memcpy(ResultPtr, Fragment.data(), Fragment.size());
2022     ResultPtr += Fragment.size();
2023   }
2024 
2025   if (Diags) {
2026     const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
2027 
2028     FullSourceLoc SourceLoc(Tok.getLocation(), SM);
2029     const DiagnosticBuilder &Builder =
2030       Diag(Diags, Features, SourceLoc, TokBegin,
2031            ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
2032            NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
2033                                 : diag::err_bad_string_encoding);
2034 
2035     const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
2036     StringRef NextFragment(NextStart, Fragment.end()-NextStart);
2037 
2038     // Decode into a dummy buffer.
2039     SmallString<512> Dummy;
2040     Dummy.reserve(Fragment.size() * CharByteWidth);
2041     char *Ptr = Dummy.data();
2042 
2043     while (!ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
2044       const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
2045       NextStart = resyncUTF8(ErrorPtr, Fragment.end());
2046       Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
2047                                      ErrorPtr, NextStart);
2048       NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
2049     }
2050   }
2051   return !NoErrorOnBadEncoding;
2052 }
2053 
2054 void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
2055   hadError = true;
2056   if (Diags)
2057     Diags->Report(Loc, diag::err_lexing_string);
2058 }
2059 
2060 /// getOffsetOfStringByte - This function returns the offset of the
2061 /// specified byte of the string data represented by Token.  This handles
2062 /// advancing over escape sequences in the string.
2063 unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
2064                                                     unsigned ByteNo) const {
2065   // Get the spelling of the token.
2066   SmallString<32> SpellingBuffer;
2067   SpellingBuffer.resize(Tok.getLength());
2068 
2069   bool StringInvalid = false;
2070   const char *SpellingPtr = &SpellingBuffer[0];
2071   unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
2072                                        &StringInvalid);
2073   if (StringInvalid)
2074     return 0;
2075 
2076   const char *SpellingStart = SpellingPtr;
2077   const char *SpellingEnd = SpellingPtr+TokLen;
2078 
2079   // Handle UTF-8 strings just like narrow strings.
2080   if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
2081     SpellingPtr += 2;
2082 
2083   assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
2084          SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
2085 
2086   // For raw string literals, this is easy.
2087   if (SpellingPtr[0] == 'R') {
2088     assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
2089     // Skip 'R"'.
2090     SpellingPtr += 2;
2091     while (*SpellingPtr != '(') {
2092       ++SpellingPtr;
2093       assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
2094     }
2095     // Skip '('.
2096     ++SpellingPtr;
2097     return SpellingPtr - SpellingStart + ByteNo;
2098   }
2099 
2100   // Skip over the leading quote
2101   assert(SpellingPtr[0] == '"' && "Should be a string literal!");
2102   ++SpellingPtr;
2103 
2104   // Skip over bytes until we find the offset we're looking for.
2105   while (ByteNo) {
2106     assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
2107 
2108     // Step over non-escapes simply.
2109     if (*SpellingPtr != '\\') {
2110       ++SpellingPtr;
2111       --ByteNo;
2112       continue;
2113     }
2114 
2115     // Otherwise, this is an escape character.  Advance over it.
2116     bool HadError = false;
2117     if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
2118       const char *EscapePtr = SpellingPtr;
2119       unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
2120                                       1, Features, HadError);
2121       if (Len > ByteNo) {
2122         // ByteNo is somewhere within the escape sequence.
2123         SpellingPtr = EscapePtr;
2124         break;
2125       }
2126       ByteNo -= Len;
2127     } else {
2128       ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
2129                         FullSourceLoc(Tok.getLocation(), SM),
2130                         CharByteWidth*8, Diags, Features);
2131       --ByteNo;
2132     }
2133     assert(!HadError && "This method isn't valid on erroneous strings");
2134   }
2135 
2136   return SpellingPtr-SpellingStart;
2137 }
2138 
2139 /// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
2140 /// suffixes as ud-suffixes, because the diagnostic experience is better if we
2141 /// treat it as an invalid suffix.
2142 bool StringLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
2143                                           StringRef Suffix) {
2144   return NumericLiteralParser::isValidUDSuffix(LangOpts, Suffix) ||
2145          Suffix == "sv";
2146 }
2147