xref: /llvm-project/clang/lib/AST/FormatString.cpp (revision 0e24686af49d2f9e50438d3a27db6f1ade594855)
1 // FormatString.cpp - Common stuff for handling printf/scanf formats -*- C++ -*-
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 // Shared details for processing format strings of printf and scanf
10 // (and friends).
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "FormatStringParsing.h"
15 #include "clang/Basic/LangOptions.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "llvm/Support/ConvertUTF.h"
18 #include <optional>
19 
20 using clang::analyze_format_string::ArgType;
21 using clang::analyze_format_string::FormatStringHandler;
22 using clang::analyze_format_string::FormatSpecifier;
23 using clang::analyze_format_string::LengthModifier;
24 using clang::analyze_format_string::OptionalAmount;
25 using clang::analyze_format_string::ConversionSpecifier;
26 using namespace clang;
27 
28 // Key function to FormatStringHandler.
29 FormatStringHandler::~FormatStringHandler() {}
30 
31 //===----------------------------------------------------------------------===//
32 // Functions for parsing format strings components in both printf and
33 // scanf format strings.
34 //===----------------------------------------------------------------------===//
35 
36 OptionalAmount
37 clang::analyze_format_string::ParseAmount(const char *&Beg, const char *E) {
38   const char *I = Beg;
39   UpdateOnReturn <const char*> UpdateBeg(Beg, I);
40 
41   unsigned accumulator = 0;
42   bool hasDigits = false;
43 
44   for ( ; I != E; ++I) {
45     char c = *I;
46     if (c >= '0' && c <= '9') {
47       hasDigits = true;
48       accumulator = (accumulator * 10) + (c - '0');
49       continue;
50     }
51 
52     if (hasDigits)
53       return OptionalAmount(OptionalAmount::Constant, accumulator, Beg, I - Beg,
54           false);
55 
56     break;
57   }
58 
59   return OptionalAmount();
60 }
61 
62 OptionalAmount
63 clang::analyze_format_string::ParseNonPositionAmount(const char *&Beg,
64                                                      const char *E,
65                                                      unsigned &argIndex) {
66   if (*Beg == '*') {
67     ++Beg;
68     return OptionalAmount(OptionalAmount::Arg, argIndex++, Beg, 0, false);
69   }
70 
71   return ParseAmount(Beg, E);
72 }
73 
74 OptionalAmount
75 clang::analyze_format_string::ParsePositionAmount(FormatStringHandler &H,
76                                                   const char *Start,
77                                                   const char *&Beg,
78                                                   const char *E,
79                                                   PositionContext p) {
80   if (*Beg == '*') {
81     const char *I = Beg + 1;
82     const OptionalAmount &Amt = ParseAmount(I, E);
83 
84     if (Amt.getHowSpecified() == OptionalAmount::NotSpecified) {
85       H.HandleInvalidPosition(Beg, I - Beg, p);
86       return OptionalAmount(false);
87     }
88 
89     if (I == E) {
90       // No more characters left?
91       H.HandleIncompleteSpecifier(Start, E - Start);
92       return OptionalAmount(false);
93     }
94 
95     assert(Amt.getHowSpecified() == OptionalAmount::Constant);
96 
97     if (*I == '$') {
98       // Handle positional arguments
99 
100       // Special case: '*0$', since this is an easy mistake.
101       if (Amt.getConstantAmount() == 0) {
102         H.HandleZeroPosition(Beg, I - Beg + 1);
103         return OptionalAmount(false);
104       }
105 
106       const char *Tmp = Beg;
107       Beg = ++I;
108 
109       return OptionalAmount(OptionalAmount::Arg, Amt.getConstantAmount() - 1,
110                             Tmp, 0, true);
111     }
112 
113     H.HandleInvalidPosition(Beg, I - Beg, p);
114     return OptionalAmount(false);
115   }
116 
117   return ParseAmount(Beg, E);
118 }
119 
120 
121 bool
122 clang::analyze_format_string::ParseFieldWidth(FormatStringHandler &H,
123                                               FormatSpecifier &CS,
124                                               const char *Start,
125                                               const char *&Beg, const char *E,
126                                               unsigned *argIndex) {
127   // FIXME: Support negative field widths.
128   if (argIndex) {
129     CS.setFieldWidth(ParseNonPositionAmount(Beg, E, *argIndex));
130   }
131   else {
132     const OptionalAmount Amt =
133       ParsePositionAmount(H, Start, Beg, E,
134                           analyze_format_string::FieldWidthPos);
135 
136     if (Amt.isInvalid())
137       return true;
138     CS.setFieldWidth(Amt);
139   }
140   return false;
141 }
142 
143 bool
144 clang::analyze_format_string::ParseArgPosition(FormatStringHandler &H,
145                                                FormatSpecifier &FS,
146                                                const char *Start,
147                                                const char *&Beg,
148                                                const char *E) {
149   const char *I = Beg;
150 
151   const OptionalAmount &Amt = ParseAmount(I, E);
152 
153   if (I == E) {
154     // No more characters left?
155     H.HandleIncompleteSpecifier(Start, E - Start);
156     return true;
157   }
158 
159   if (Amt.getHowSpecified() == OptionalAmount::Constant && *(I++) == '$') {
160     // Warn that positional arguments are non-standard.
161     H.HandlePosition(Start, I - Start);
162 
163     // Special case: '%0$', since this is an easy mistake.
164     if (Amt.getConstantAmount() == 0) {
165       H.HandleZeroPosition(Start, I - Start);
166       return true;
167     }
168 
169     FS.setArgIndex(Amt.getConstantAmount() - 1);
170     FS.setUsesPositionalArg();
171     // Update the caller's pointer if we decided to consume
172     // these characters.
173     Beg = I;
174     return false;
175   }
176 
177   return false;
178 }
179 
180 bool
181 clang::analyze_format_string::ParseVectorModifier(FormatStringHandler &H,
182                                                   FormatSpecifier &FS,
183                                                   const char *&I,
184                                                   const char *E,
185                                                   const LangOptions &LO) {
186   if (!LO.OpenCL)
187     return false;
188 
189   const char *Start = I;
190   if (*I == 'v') {
191     ++I;
192 
193     if (I == E) {
194       H.HandleIncompleteSpecifier(Start, E - Start);
195       return true;
196     }
197 
198     OptionalAmount NumElts = ParseAmount(I, E);
199     if (NumElts.getHowSpecified() != OptionalAmount::Constant) {
200       H.HandleIncompleteSpecifier(Start, E - Start);
201       return true;
202     }
203 
204     FS.setVectorNumElts(NumElts);
205   }
206 
207   return false;
208 }
209 
210 bool
211 clang::analyze_format_string::ParseLengthModifier(FormatSpecifier &FS,
212                                                   const char *&I,
213                                                   const char *E,
214                                                   const LangOptions &LO,
215                                                   bool IsScanf) {
216   LengthModifier::Kind lmKind = LengthModifier::None;
217   const char *lmPosition = I;
218   switch (*I) {
219     default:
220       return false;
221     case 'h':
222       ++I;
223       if (I != E && *I == 'h') {
224         ++I;
225         lmKind = LengthModifier::AsChar;
226       } else if (I != E && *I == 'l' && LO.OpenCL) {
227         ++I;
228         lmKind = LengthModifier::AsShortLong;
229       } else {
230         lmKind = LengthModifier::AsShort;
231       }
232       break;
233     case 'l':
234       ++I;
235       if (I != E && *I == 'l') {
236         ++I;
237         lmKind = LengthModifier::AsLongLong;
238       } else {
239         lmKind = LengthModifier::AsLong;
240       }
241       break;
242     case 'j': lmKind = LengthModifier::AsIntMax;     ++I; break;
243     case 'z': lmKind = LengthModifier::AsSizeT;      ++I; break;
244     case 't': lmKind = LengthModifier::AsPtrDiff;    ++I; break;
245     case 'L': lmKind = LengthModifier::AsLongDouble; ++I; break;
246     case 'q': lmKind = LengthModifier::AsQuad;       ++I; break;
247     case 'a':
248       if (IsScanf && !LO.C99 && !LO.CPlusPlus11) {
249         // For scanf in C90, look at the next character to see if this should
250         // be parsed as the GNU extension 'a' length modifier. If not, this
251         // will be parsed as a conversion specifier.
252         ++I;
253         if (I != E && (*I == 's' || *I == 'S' || *I == '[')) {
254           lmKind = LengthModifier::AsAllocate;
255           break;
256         }
257         --I;
258       }
259       return false;
260     case 'm':
261       if (IsScanf) {
262         lmKind = LengthModifier::AsMAllocate;
263         ++I;
264         break;
265       }
266       return false;
267     // printf: AsInt64, AsInt32, AsInt3264
268     // scanf:  AsInt64
269     case 'I':
270       if (I + 1 != E && I + 2 != E) {
271         if (I[1] == '6' && I[2] == '4') {
272           I += 3;
273           lmKind = LengthModifier::AsInt64;
274           break;
275         }
276         if (IsScanf)
277           return false;
278 
279         if (I[1] == '3' && I[2] == '2') {
280           I += 3;
281           lmKind = LengthModifier::AsInt32;
282           break;
283         }
284       }
285       ++I;
286       lmKind = LengthModifier::AsInt3264;
287       break;
288     case 'w':
289       lmKind = LengthModifier::AsWide; ++I; break;
290   }
291   LengthModifier lm(lmPosition, lmKind);
292   FS.setLengthModifier(lm);
293   return true;
294 }
295 
296 bool clang::analyze_format_string::ParseUTF8InvalidSpecifier(
297     const char *SpecifierBegin, const char *FmtStrEnd, unsigned &Len) {
298   if (SpecifierBegin + 1 >= FmtStrEnd)
299     return false;
300 
301   const llvm::UTF8 *SB =
302       reinterpret_cast<const llvm::UTF8 *>(SpecifierBegin + 1);
303   const llvm::UTF8 *SE = reinterpret_cast<const llvm::UTF8 *>(FmtStrEnd);
304   const char FirstByte = *SB;
305 
306   // If the invalid specifier is a multibyte UTF-8 string, return the
307   // total length accordingly so that the conversion specifier can be
308   // properly updated to reflect a complete UTF-8 specifier.
309   unsigned NumBytes = llvm::getNumBytesForUTF8(FirstByte);
310   if (NumBytes == 1)
311     return false;
312   if (SB + NumBytes > SE)
313     return false;
314 
315   Len = NumBytes + 1;
316   return true;
317 }
318 
319 //===----------------------------------------------------------------------===//
320 // Methods on ArgType.
321 //===----------------------------------------------------------------------===//
322 
323 clang::analyze_format_string::ArgType::MatchKind
324 ArgType::matchesType(ASTContext &C, QualType argTy) const {
325   // When using the format attribute in C++, you can receive a function or an
326   // array that will necessarily decay to a pointer when passed to the final
327   // format consumer. Apply decay before type comparison.
328   if (argTy->canDecayToPointerType())
329     argTy = C.getDecayedType(argTy);
330 
331   if (Ptr) {
332     // It has to be a pointer.
333     const PointerType *PT = argTy->getAs<PointerType>();
334     if (!PT)
335       return NoMatch;
336 
337     // We cannot write through a const qualified pointer.
338     if (PT->getPointeeType().isConstQualified())
339       return NoMatch;
340 
341     argTy = PT->getPointeeType();
342   }
343 
344   switch (K) {
345     case InvalidTy:
346       llvm_unreachable("ArgType must be valid");
347 
348     case UnknownTy:
349       return Match;
350 
351     case AnyCharTy: {
352       if (const auto *ETy = argTy->getAs<EnumType>()) {
353         // If the enum is incomplete we know nothing about the underlying type.
354         // Assume that it's 'int'. Do not use the underlying type for a scoped
355         // enumeration.
356         if (!ETy->getDecl()->isComplete())
357           return NoMatch;
358         if (ETy->isUnscopedEnumerationType())
359           argTy = ETy->getDecl()->getIntegerType();
360       }
361 
362       if (const auto *BT = argTy->getAs<BuiltinType>()) {
363         // The types are perfectly matched?
364         switch (BT->getKind()) {
365         default:
366           break;
367         case BuiltinType::Char_S:
368         case BuiltinType::SChar:
369         case BuiltinType::UChar:
370         case BuiltinType::Char_U:
371             return Match;
372         case BuiltinType::Bool:
373           if (!Ptr)
374             return Match;
375           break;
376         }
377         // "Partially matched" because of promotions?
378         if (!Ptr) {
379           switch (BT->getKind()) {
380           default:
381             break;
382           case BuiltinType::Int:
383           case BuiltinType::UInt:
384             return MatchPromotion;
385           case BuiltinType::Short:
386           case BuiltinType::UShort:
387           case BuiltinType::WChar_S:
388           case BuiltinType::WChar_U:
389             return NoMatchPromotionTypeConfusion;
390           }
391         }
392       }
393       return NoMatch;
394     }
395 
396     case SpecificTy: {
397       if (const EnumType *ETy = argTy->getAs<EnumType>()) {
398         // If the enum is incomplete we know nothing about the underlying type.
399         // Assume that it's 'int'. Do not use the underlying type for a scoped
400         // enumeration as that needs an exact match.
401         if (!ETy->getDecl()->isComplete())
402           argTy = C.IntTy;
403         else if (ETy->isUnscopedEnumerationType())
404           argTy = ETy->getDecl()->getIntegerType();
405       }
406 
407       if (argTy->isSaturatedFixedPointType())
408         argTy = C.getCorrespondingUnsaturatedType(argTy);
409 
410       argTy = C.getCanonicalType(argTy).getUnqualifiedType();
411 
412       if (T == argTy)
413         return Match;
414       if (const auto *BT = argTy->getAs<BuiltinType>()) {
415         // Check if the only difference between them is signed vs unsigned
416         // if true, return match signedness.
417         switch (BT->getKind()) {
418           default:
419             break;
420           case BuiltinType::Bool:
421             if (Ptr && (T == C.UnsignedCharTy || T == C.SignedCharTy))
422               return NoMatch;
423             [[fallthrough]];
424           case BuiltinType::Char_S:
425           case BuiltinType::SChar:
426             if (T == C.UnsignedShortTy || T == C.ShortTy)
427               return NoMatchTypeConfusion;
428             if (T == C.UnsignedCharTy)
429               return NoMatchSignedness;
430             if (T == C.SignedCharTy)
431               return Match;
432             break;
433           case BuiltinType::Char_U:
434           case BuiltinType::UChar:
435             if (T == C.UnsignedShortTy || T == C.ShortTy)
436               return NoMatchTypeConfusion;
437             if (T == C.UnsignedCharTy)
438               return Match;
439             if (T == C.SignedCharTy)
440               return NoMatchSignedness;
441             break;
442           case BuiltinType::Short:
443             if (T == C.UnsignedShortTy)
444               return NoMatchSignedness;
445             break;
446           case BuiltinType::UShort:
447             if (T == C.ShortTy)
448               return NoMatchSignedness;
449             break;
450           case BuiltinType::Int:
451             if (T == C.UnsignedIntTy)
452               return NoMatchSignedness;
453             break;
454           case BuiltinType::UInt:
455             if (T == C.IntTy)
456               return NoMatchSignedness;
457             break;
458           case BuiltinType::Long:
459             if (T == C.UnsignedLongTy)
460               return NoMatchSignedness;
461             break;
462           case BuiltinType::ULong:
463             if (T == C.LongTy)
464               return NoMatchSignedness;
465             break;
466           case BuiltinType::LongLong:
467             if (T == C.UnsignedLongLongTy)
468               return NoMatchSignedness;
469             break;
470           case BuiltinType::ULongLong:
471             if (T == C.LongLongTy)
472               return NoMatchSignedness;
473             break;
474           }
475           // "Partially matched" because of promotions?
476           if (!Ptr) {
477             switch (BT->getKind()) {
478             default:
479               break;
480             case BuiltinType::Bool:
481               if (T == C.IntTy || T == C.UnsignedIntTy)
482                 return MatchPromotion;
483               break;
484             case BuiltinType::Int:
485             case BuiltinType::UInt:
486               if (T == C.SignedCharTy || T == C.UnsignedCharTy ||
487                   T == C.ShortTy || T == C.UnsignedShortTy || T == C.WCharTy ||
488                   T == C.WideCharTy)
489                 return MatchPromotion;
490               break;
491             case BuiltinType::Char_U:
492               if (T == C.UnsignedIntTy)
493                 return MatchPromotion;
494               if (T == C.UnsignedShortTy)
495                 return NoMatchPromotionTypeConfusion;
496               break;
497             case BuiltinType::Char_S:
498               if (T == C.IntTy)
499                 return MatchPromotion;
500               if (T == C.ShortTy)
501                 return NoMatchPromotionTypeConfusion;
502               break;
503             case BuiltinType::Half:
504             case BuiltinType::Float:
505               if (T == C.DoubleTy)
506                 return MatchPromotion;
507               break;
508             case BuiltinType::Short:
509             case BuiltinType::UShort:
510               if (T == C.SignedCharTy || T == C.UnsignedCharTy)
511                 return NoMatchPromotionTypeConfusion;
512               break;
513             case BuiltinType::WChar_U:
514             case BuiltinType::WChar_S:
515               if (T != C.WCharTy && T != C.WideCharTy)
516                 return NoMatchPromotionTypeConfusion;
517             }
518           }
519       }
520       return NoMatch;
521     }
522 
523     case CStrTy:
524       if (const auto *PT = argTy->getAs<PointerType>();
525           PT && PT->getPointeeType()->isCharType())
526         return Match;
527       return NoMatch;
528 
529     case WCStrTy:
530       if (const auto *PT = argTy->getAs<PointerType>();
531           PT &&
532           C.hasSameUnqualifiedType(PT->getPointeeType(), C.getWideCharType()))
533         return Match;
534       return NoMatch;
535 
536     case WIntTy: {
537       QualType WInt = C.getCanonicalType(C.getWIntType()).getUnqualifiedType();
538 
539       if (C.getCanonicalType(argTy).getUnqualifiedType() == WInt)
540         return Match;
541 
542       QualType PromoArg = C.isPromotableIntegerType(argTy)
543                               ? C.getPromotedIntegerType(argTy)
544                               : argTy;
545       PromoArg = C.getCanonicalType(PromoArg).getUnqualifiedType();
546 
547       // If the promoted argument is the corresponding signed type of the
548       // wint_t type, then it should match.
549       if (PromoArg->hasSignedIntegerRepresentation() &&
550           C.getCorrespondingUnsignedType(PromoArg) == WInt)
551         return Match;
552 
553       return WInt == PromoArg ? Match : NoMatch;
554     }
555 
556     case CPointerTy:
557       if (const auto *PT = argTy->getAs<PointerType>()) {
558         QualType PointeeTy = PT->getPointeeType();
559         if (PointeeTy->isVoidType() || (!Ptr && PointeeTy->isCharType()))
560           return Match;
561         return NoMatchPedantic;
562       }
563 
564       // nullptr_t* is not a double pointer, so reject when something like
565       // void** is expected.
566       // In C++, nullptr is promoted to void*. In C23, va_arg(ap, void*) is not
567       // undefined when the next argument is of type nullptr_t.
568       if (!Ptr && argTy->isNullPtrType())
569         return C.getLangOpts().CPlusPlus ? MatchPromotion : Match;
570 
571       if (argTy->isObjCObjectPointerType() || argTy->isBlockPointerType())
572         return NoMatchPedantic;
573 
574       return NoMatch;
575 
576     case ObjCPointerTy: {
577       if (argTy->getAs<ObjCObjectPointerType>() ||
578           argTy->getAs<BlockPointerType>())
579         return Match;
580 
581       // Handle implicit toll-free bridging.
582       if (const PointerType *PT = argTy->getAs<PointerType>()) {
583         // Things such as CFTypeRef are really just opaque pointers
584         // to C structs representing CF types that can often be bridged
585         // to Objective-C objects.  Since the compiler doesn't know which
586         // structs can be toll-free bridged, we just accept them all.
587         QualType pointee = PT->getPointeeType();
588         if (pointee->getAsStructureType() || pointee->isVoidType())
589           return Match;
590       }
591       return NoMatch;
592     }
593   }
594 
595   llvm_unreachable("Invalid ArgType Kind!");
596 }
597 
598 ArgType ArgType::makeVectorType(ASTContext &C, unsigned NumElts) const {
599   // Check for valid vector element types.
600   if (T.isNull())
601     return ArgType::Invalid();
602 
603   QualType Vec = C.getExtVectorType(T, NumElts);
604   return ArgType(Vec, Name);
605 }
606 
607 QualType ArgType::getRepresentativeType(ASTContext &C) const {
608   QualType Res;
609   switch (K) {
610     case InvalidTy:
611       llvm_unreachable("No representative type for Invalid ArgType");
612     case UnknownTy:
613       llvm_unreachable("No representative type for Unknown ArgType");
614     case AnyCharTy:
615       Res = C.CharTy;
616       break;
617     case SpecificTy:
618       Res = T;
619       break;
620     case CStrTy:
621       Res = C.getPointerType(C.CharTy);
622       break;
623     case WCStrTy:
624       Res = C.getPointerType(C.getWideCharType());
625       break;
626     case ObjCPointerTy:
627       Res = C.ObjCBuiltinIdTy;
628       break;
629     case CPointerTy:
630       Res = C.VoidPtrTy;
631       break;
632     case WIntTy: {
633       Res = C.getWIntType();
634       break;
635     }
636   }
637 
638   if (Ptr)
639     Res = C.getPointerType(Res);
640   return Res;
641 }
642 
643 std::string ArgType::getRepresentativeTypeName(ASTContext &C) const {
644   std::string S = getRepresentativeType(C).getAsString(C.getPrintingPolicy());
645 
646   std::string Alias;
647   if (Name) {
648     // Use a specific name for this type, e.g. "size_t".
649     Alias = Name;
650     if (Ptr) {
651       // If ArgType is actually a pointer to T, append an asterisk.
652       Alias += (Alias[Alias.size()-1] == '*') ? "*" : " *";
653     }
654     // If Alias is the same as the underlying type, e.g. wchar_t, then drop it.
655     if (S == Alias)
656       Alias.clear();
657   }
658 
659   if (!Alias.empty())
660     return std::string("'") + Alias + "' (aka '" + S + "')";
661   return std::string("'") + S + "'";
662 }
663 
664 
665 //===----------------------------------------------------------------------===//
666 // Methods on OptionalAmount.
667 //===----------------------------------------------------------------------===//
668 
669 ArgType
670 analyze_format_string::OptionalAmount::getArgType(ASTContext &Ctx) const {
671   return Ctx.IntTy;
672 }
673 
674 //===----------------------------------------------------------------------===//
675 // Methods on LengthModifier.
676 //===----------------------------------------------------------------------===//
677 
678 const char *
679 analyze_format_string::LengthModifier::toString() const {
680   switch (kind) {
681   case AsChar:
682     return "hh";
683   case AsShort:
684     return "h";
685   case AsShortLong:
686     return "hl";
687   case AsLong: // or AsWideChar
688     return "l";
689   case AsLongLong:
690     return "ll";
691   case AsQuad:
692     return "q";
693   case AsIntMax:
694     return "j";
695   case AsSizeT:
696     return "z";
697   case AsPtrDiff:
698     return "t";
699   case AsInt32:
700     return "I32";
701   case AsInt3264:
702     return "I";
703   case AsInt64:
704     return "I64";
705   case AsLongDouble:
706     return "L";
707   case AsAllocate:
708     return "a";
709   case AsMAllocate:
710     return "m";
711   case AsWide:
712     return "w";
713   case None:
714     return "";
715   }
716   return nullptr;
717 }
718 
719 //===----------------------------------------------------------------------===//
720 // Methods on ConversionSpecifier.
721 //===----------------------------------------------------------------------===//
722 
723 const char *ConversionSpecifier::toString() const {
724   switch (kind) {
725   case bArg: return "b";
726   case BArg: return "B";
727   case dArg: return "d";
728   case DArg: return "D";
729   case iArg: return "i";
730   case oArg: return "o";
731   case OArg: return "O";
732   case uArg: return "u";
733   case UArg: return "U";
734   case xArg: return "x";
735   case XArg: return "X";
736   case fArg: return "f";
737   case FArg: return "F";
738   case eArg: return "e";
739   case EArg: return "E";
740   case gArg: return "g";
741   case GArg: return "G";
742   case aArg: return "a";
743   case AArg: return "A";
744   case cArg: return "c";
745   case sArg: return "s";
746   case pArg: return "p";
747   case PArg:
748     return "P";
749   case nArg: return "n";
750   case PercentArg:  return "%";
751   case ScanListArg: return "[";
752   case InvalidSpecifier: return nullptr;
753 
754   // POSIX unicode extensions.
755   case CArg: return "C";
756   case SArg: return "S";
757 
758   // Objective-C specific specifiers.
759   case ObjCObjArg: return "@";
760 
761   // FreeBSD kernel specific specifiers.
762   case FreeBSDbArg: return "b";
763   case FreeBSDDArg: return "D";
764   case FreeBSDrArg: return "r";
765   case FreeBSDyArg: return "y";
766 
767   // GlibC specific specifiers.
768   case PrintErrno: return "m";
769 
770   // MS specific specifiers.
771   case ZArg: return "Z";
772 
773   // ISO/IEC TR 18037 (fixed-point) specific specifiers.
774   case rArg:
775     return "r";
776   case RArg:
777     return "R";
778   case kArg:
779     return "k";
780   case KArg:
781     return "K";
782   }
783   return nullptr;
784 }
785 
786 std::optional<ConversionSpecifier>
787 ConversionSpecifier::getStandardSpecifier() const {
788   ConversionSpecifier::Kind NewKind;
789 
790   switch (getKind()) {
791   default:
792     return std::nullopt;
793   case DArg:
794     NewKind = dArg;
795     break;
796   case UArg:
797     NewKind = uArg;
798     break;
799   case OArg:
800     NewKind = oArg;
801     break;
802   }
803 
804   ConversionSpecifier FixedCS(*this);
805   FixedCS.setKind(NewKind);
806   return FixedCS;
807 }
808 
809 //===----------------------------------------------------------------------===//
810 // Methods on OptionalAmount.
811 //===----------------------------------------------------------------------===//
812 
813 void OptionalAmount::toString(raw_ostream &os) const {
814   switch (hs) {
815   case Invalid:
816   case NotSpecified:
817     return;
818   case Arg:
819     if (UsesDotPrefix)
820         os << ".";
821     if (usesPositionalArg())
822       os << "*" << getPositionalArgIndex() << "$";
823     else
824       os << "*";
825     break;
826   case Constant:
827     if (UsesDotPrefix)
828         os << ".";
829     os << amt;
830     break;
831   }
832 }
833 
834 bool FormatSpecifier::hasValidLengthModifier(const TargetInfo &Target,
835                                              const LangOptions &LO) const {
836   switch (LM.getKind()) {
837     case LengthModifier::None:
838       return true;
839 
840     // Handle most integer flags
841     case LengthModifier::AsShort:
842       // Length modifier only applies to FP vectors.
843       if (LO.OpenCL && CS.isDoubleArg())
844         return !VectorNumElts.isInvalid();
845 
846       if (CS.isFixedPointArg())
847         return true;
848 
849       if (Target.getTriple().isOSMSVCRT()) {
850         switch (CS.getKind()) {
851           case ConversionSpecifier::cArg:
852           case ConversionSpecifier::CArg:
853           case ConversionSpecifier::sArg:
854           case ConversionSpecifier::SArg:
855           case ConversionSpecifier::ZArg:
856             return true;
857           default:
858             break;
859         }
860       }
861       [[fallthrough]];
862     case LengthModifier::AsChar:
863     case LengthModifier::AsLongLong:
864     case LengthModifier::AsQuad:
865     case LengthModifier::AsIntMax:
866     case LengthModifier::AsSizeT:
867     case LengthModifier::AsPtrDiff:
868       switch (CS.getKind()) {
869         case ConversionSpecifier::bArg:
870         case ConversionSpecifier::BArg:
871         case ConversionSpecifier::dArg:
872         case ConversionSpecifier::DArg:
873         case ConversionSpecifier::iArg:
874         case ConversionSpecifier::oArg:
875         case ConversionSpecifier::OArg:
876         case ConversionSpecifier::uArg:
877         case ConversionSpecifier::UArg:
878         case ConversionSpecifier::xArg:
879         case ConversionSpecifier::XArg:
880         case ConversionSpecifier::nArg:
881           return true;
882         case ConversionSpecifier::FreeBSDrArg:
883         case ConversionSpecifier::FreeBSDyArg:
884           return Target.getTriple().isOSFreeBSD() || Target.getTriple().isPS();
885         default:
886           return false;
887       }
888 
889     case LengthModifier::AsShortLong:
890       return LO.OpenCL && !VectorNumElts.isInvalid();
891 
892     // Handle 'l' flag
893     case LengthModifier::AsLong: // or AsWideChar
894       if (CS.isDoubleArg()) {
895         // Invalid for OpenCL FP scalars.
896         if (LO.OpenCL && VectorNumElts.isInvalid())
897           return false;
898         return true;
899       }
900 
901       if (CS.isFixedPointArg())
902         return true;
903 
904       switch (CS.getKind()) {
905         case ConversionSpecifier::bArg:
906         case ConversionSpecifier::BArg:
907         case ConversionSpecifier::dArg:
908         case ConversionSpecifier::DArg:
909         case ConversionSpecifier::iArg:
910         case ConversionSpecifier::oArg:
911         case ConversionSpecifier::OArg:
912         case ConversionSpecifier::uArg:
913         case ConversionSpecifier::UArg:
914         case ConversionSpecifier::xArg:
915         case ConversionSpecifier::XArg:
916         case ConversionSpecifier::nArg:
917         case ConversionSpecifier::cArg:
918         case ConversionSpecifier::sArg:
919         case ConversionSpecifier::ScanListArg:
920         case ConversionSpecifier::ZArg:
921           return true;
922         case ConversionSpecifier::FreeBSDrArg:
923         case ConversionSpecifier::FreeBSDyArg:
924           return Target.getTriple().isOSFreeBSD() || Target.getTriple().isPS();
925         default:
926           return false;
927       }
928 
929     case LengthModifier::AsLongDouble:
930       switch (CS.getKind()) {
931         case ConversionSpecifier::aArg:
932         case ConversionSpecifier::AArg:
933         case ConversionSpecifier::fArg:
934         case ConversionSpecifier::FArg:
935         case ConversionSpecifier::eArg:
936         case ConversionSpecifier::EArg:
937         case ConversionSpecifier::gArg:
938         case ConversionSpecifier::GArg:
939           return true;
940         // GNU libc extension.
941         case ConversionSpecifier::dArg:
942         case ConversionSpecifier::iArg:
943         case ConversionSpecifier::oArg:
944         case ConversionSpecifier::uArg:
945         case ConversionSpecifier::xArg:
946         case ConversionSpecifier::XArg:
947           return !Target.getTriple().isOSDarwin() &&
948                  !Target.getTriple().isOSWindows();
949         default:
950           return false;
951       }
952 
953     case LengthModifier::AsAllocate:
954       switch (CS.getKind()) {
955         case ConversionSpecifier::sArg:
956         case ConversionSpecifier::SArg:
957         case ConversionSpecifier::ScanListArg:
958           return true;
959         default:
960           return false;
961       }
962 
963     case LengthModifier::AsMAllocate:
964       switch (CS.getKind()) {
965         case ConversionSpecifier::cArg:
966         case ConversionSpecifier::CArg:
967         case ConversionSpecifier::sArg:
968         case ConversionSpecifier::SArg:
969         case ConversionSpecifier::ScanListArg:
970           return true;
971         default:
972           return false;
973       }
974     case LengthModifier::AsInt32:
975     case LengthModifier::AsInt3264:
976     case LengthModifier::AsInt64:
977       switch (CS.getKind()) {
978         case ConversionSpecifier::dArg:
979         case ConversionSpecifier::iArg:
980         case ConversionSpecifier::oArg:
981         case ConversionSpecifier::uArg:
982         case ConversionSpecifier::xArg:
983         case ConversionSpecifier::XArg:
984           return Target.getTriple().isOSMSVCRT();
985         default:
986           return false;
987       }
988     case LengthModifier::AsWide:
989       switch (CS.getKind()) {
990         case ConversionSpecifier::cArg:
991         case ConversionSpecifier::CArg:
992         case ConversionSpecifier::sArg:
993         case ConversionSpecifier::SArg:
994         case ConversionSpecifier::ZArg:
995           return Target.getTriple().isOSMSVCRT();
996         default:
997           return false;
998       }
999   }
1000   llvm_unreachable("Invalid LengthModifier Kind!");
1001 }
1002 
1003 bool FormatSpecifier::hasStandardLengthModifier() const {
1004   switch (LM.getKind()) {
1005     case LengthModifier::None:
1006     case LengthModifier::AsChar:
1007     case LengthModifier::AsShort:
1008     case LengthModifier::AsLong:
1009     case LengthModifier::AsLongLong:
1010     case LengthModifier::AsIntMax:
1011     case LengthModifier::AsSizeT:
1012     case LengthModifier::AsPtrDiff:
1013     case LengthModifier::AsLongDouble:
1014       return true;
1015     case LengthModifier::AsAllocate:
1016     case LengthModifier::AsMAllocate:
1017     case LengthModifier::AsQuad:
1018     case LengthModifier::AsInt32:
1019     case LengthModifier::AsInt3264:
1020     case LengthModifier::AsInt64:
1021     case LengthModifier::AsWide:
1022     case LengthModifier::AsShortLong: // ???
1023       return false;
1024   }
1025   llvm_unreachable("Invalid LengthModifier Kind!");
1026 }
1027 
1028 bool FormatSpecifier::hasStandardConversionSpecifier(
1029     const LangOptions &LangOpt) const {
1030   switch (CS.getKind()) {
1031     case ConversionSpecifier::bArg:
1032     case ConversionSpecifier::BArg:
1033     case ConversionSpecifier::cArg:
1034     case ConversionSpecifier::dArg:
1035     case ConversionSpecifier::iArg:
1036     case ConversionSpecifier::oArg:
1037     case ConversionSpecifier::uArg:
1038     case ConversionSpecifier::xArg:
1039     case ConversionSpecifier::XArg:
1040     case ConversionSpecifier::fArg:
1041     case ConversionSpecifier::FArg:
1042     case ConversionSpecifier::eArg:
1043     case ConversionSpecifier::EArg:
1044     case ConversionSpecifier::gArg:
1045     case ConversionSpecifier::GArg:
1046     case ConversionSpecifier::aArg:
1047     case ConversionSpecifier::AArg:
1048     case ConversionSpecifier::sArg:
1049     case ConversionSpecifier::pArg:
1050     case ConversionSpecifier::nArg:
1051     case ConversionSpecifier::ObjCObjArg:
1052     case ConversionSpecifier::ScanListArg:
1053     case ConversionSpecifier::PercentArg:
1054     case ConversionSpecifier::PArg:
1055       return true;
1056     case ConversionSpecifier::CArg:
1057     case ConversionSpecifier::SArg:
1058       return LangOpt.ObjC;
1059     case ConversionSpecifier::InvalidSpecifier:
1060     case ConversionSpecifier::FreeBSDbArg:
1061     case ConversionSpecifier::FreeBSDDArg:
1062     case ConversionSpecifier::FreeBSDrArg:
1063     case ConversionSpecifier::FreeBSDyArg:
1064     case ConversionSpecifier::PrintErrno:
1065     case ConversionSpecifier::DArg:
1066     case ConversionSpecifier::OArg:
1067     case ConversionSpecifier::UArg:
1068     case ConversionSpecifier::ZArg:
1069       return false;
1070     case ConversionSpecifier::rArg:
1071     case ConversionSpecifier::RArg:
1072     case ConversionSpecifier::kArg:
1073     case ConversionSpecifier::KArg:
1074       return LangOpt.FixedPoint;
1075   }
1076   llvm_unreachable("Invalid ConversionSpecifier Kind!");
1077 }
1078 
1079 bool FormatSpecifier::hasStandardLengthConversionCombination() const {
1080   if (LM.getKind() == LengthModifier::AsLongDouble) {
1081     switch(CS.getKind()) {
1082         case ConversionSpecifier::dArg:
1083         case ConversionSpecifier::iArg:
1084         case ConversionSpecifier::oArg:
1085         case ConversionSpecifier::uArg:
1086         case ConversionSpecifier::xArg:
1087         case ConversionSpecifier::XArg:
1088           return false;
1089         default:
1090           return true;
1091     }
1092   }
1093   return true;
1094 }
1095 
1096 std::optional<LengthModifier>
1097 FormatSpecifier::getCorrectedLengthModifier() const {
1098   if (CS.isAnyIntArg() || CS.getKind() == ConversionSpecifier::nArg) {
1099     if (LM.getKind() == LengthModifier::AsLongDouble ||
1100         LM.getKind() == LengthModifier::AsQuad) {
1101       LengthModifier FixedLM(LM);
1102       FixedLM.setKind(LengthModifier::AsLongLong);
1103       return FixedLM;
1104     }
1105   }
1106 
1107   return std::nullopt;
1108 }
1109 
1110 bool FormatSpecifier::namedTypeToLengthModifier(QualType QT,
1111                                                 LengthModifier &LM) {
1112   for (/**/; const auto *TT = QT->getAs<TypedefType>();
1113        QT = TT->getDecl()->getUnderlyingType()) {
1114     const TypedefNameDecl *Typedef = TT->getDecl();
1115     const IdentifierInfo *Identifier = Typedef->getIdentifier();
1116     if (Identifier->getName() == "size_t") {
1117       LM.setKind(LengthModifier::AsSizeT);
1118       return true;
1119     } else if (Identifier->getName() == "ssize_t") {
1120       // Not C99, but common in Unix.
1121       LM.setKind(LengthModifier::AsSizeT);
1122       return true;
1123     } else if (Identifier->getName() == "intmax_t") {
1124       LM.setKind(LengthModifier::AsIntMax);
1125       return true;
1126     } else if (Identifier->getName() == "uintmax_t") {
1127       LM.setKind(LengthModifier::AsIntMax);
1128       return true;
1129     } else if (Identifier->getName() == "ptrdiff_t") {
1130       LM.setKind(LengthModifier::AsPtrDiff);
1131       return true;
1132     }
1133   }
1134   return false;
1135 }
1136