clang 23.0.0git
PPMacroExpansion.cpp
Go to the documentation of this file.
1//===--- PPMacroExpansion.cpp - Top level Macro Expansion -----------------===//
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 top level handling of macro expansion for the
10// preprocessor.
11//
12//===----------------------------------------------------------------------===//
13
18#include "clang/Basic/LLVM.h"
28#include "clang/Lex/MacroArgs.h"
29#include "clang/Lex/MacroInfo.h"
33#include "clang/Lex/Token.h"
34#include "llvm/ADT/ArrayRef.h"
35#include "llvm/ADT/DenseMap.h"
36#include "llvm/ADT/DenseSet.h"
37#include "llvm/ADT/FoldingSet.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/SmallVector.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ADT/StringSwitch.h"
42#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Support/Format.h"
44#include "llvm/Support/Path.h"
45#include "llvm/Support/raw_ostream.h"
46#include <algorithm>
47#include <cassert>
48#include <cstddef>
49#include <cstring>
50#include <ctime>
51#include <iomanip>
52#include <optional>
53#include <sstream>
54#include <string>
55#include <tuple>
56#include <utility>
57
58using namespace clang;
59
62 if (!II->hadMacroDefinition())
63 return nullptr;
64 auto Pos = CurSubmoduleState->Macros.find(II);
65 return Pos == CurSubmoduleState->Macros.end() ? nullptr
66 : Pos->second.getLatest();
67}
68
70 assert(MD && "MacroDirective should be non-zero!");
71 assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
72
73 MacroState &StoredMD = CurSubmoduleState->Macros[II];
74 auto *OldMD = StoredMD.getLatest();
75 MD->setPrevious(OldMD);
76 StoredMD.setLatest(MD);
77 StoredMD.overrideActiveModuleMacros(*this, II);
78
79 if (needModuleMacros()) {
80 // Track that we created a new macro directive, so we know we should
81 // consider building a ModuleMacro for it when we get to the end of
82 // the module.
83 PendingModuleMacroNames.push_back(II);
84 }
85
86 // Set up the identifier as having associated macro history.
87 II->setHasMacroDefinition(true);
88 if (!MD->isDefined() && !LeafModuleMacros.contains(II))
89 II->setHasMacroDefinition(false);
90 if (II->isFromAST())
92}
93
96 MacroDirective *MD) {
97 // Normally, when a macro is defined, it goes through appendMacroDirective()
98 // above, which chains a macro to previous defines, undefs, etc.
99 // However, in a pch, the whole macro history up to the end of the pch is
100 // stored, so ASTReader goes through this function instead.
101 // However, built-in macros are already registered in the Preprocessor
102 // ctor, and ASTWriter stops writing the macro chain at built-in macros,
103 // so in that case the chain from the pch needs to be spliced to the existing
104 // built-in.
105
106 assert(II && MD);
107 MacroState &StoredMD = CurSubmoduleState->Macros[II];
108
109 if (auto *OldMD = StoredMD.getLatest()) {
110 // shouldIgnoreMacro() in ASTWriter also stops at macros from the
111 // predefines buffer in module builds. However, in module builds, modules
112 // are loaded completely before predefines are processed, so StoredMD
113 // will be nullptr for them when they're loaded. StoredMD should only be
114 // non-nullptr for builtins read from a pch file.
115 assert(OldMD->getMacroInfo()->isBuiltinMacro() &&
116 "only built-ins should have an entry here");
117 assert(!OldMD->getPrevious() && "builtin should only have a single entry");
118 ED->setPrevious(OldMD);
119 StoredMD.setLatest(MD);
120 } else {
121 StoredMD = MD;
122 }
123
124 // Setup the identifier as having associated macro history.
125 II->setHasMacroDefinition(true);
126 if (!MD->isDefined() && !LeafModuleMacros.contains(II))
127 II->setHasMacroDefinition(false);
128}
129
132 ArrayRef<ModuleMacro *> Overrides,
133 bool &New) {
134 llvm::FoldingSetNodeID ID;
135 ModuleMacro::Profile(ID, Mod, II);
136
137 void *InsertPos;
138 if (auto *MM = ModuleMacros.FindNodeOrInsertPos(ID, InsertPos)) {
139 New = false;
140 return MM;
141 }
142
143 auto *MM = ModuleMacro::create(*this, Mod, II, Macro, Overrides);
144 ModuleMacros.InsertNode(MM, InsertPos);
145
146 // Each overridden macro is now overridden by one more macro.
147 bool HidAny = false;
148 for (auto *O : Overrides) {
149 HidAny |= (O->NumOverriddenBy == 0);
150 ++O->NumOverriddenBy;
151 }
152
153 // If we were the first overrider for any macro, it's no longer a leaf.
154 auto &LeafMacros = LeafModuleMacros[II];
155 if (HidAny) {
156 llvm::erase_if(LeafMacros,
157 [](ModuleMacro *MM) { return MM->NumOverriddenBy != 0; });
158 }
159
160 // The new macro is always a leaf macro.
161 LeafMacros.push_back(MM);
162 // The identifier now has defined macros (that may or may not be visible).
163 II->setHasMacroDefinition(true);
164
165 New = true;
166 return MM;
167}
168
170 const IdentifierInfo *II) {
171 llvm::FoldingSetNodeID ID;
172 ModuleMacro::Profile(ID, Mod, II);
173
174 void *InsertPos;
175 return ModuleMacros.FindNodeOrInsertPos(ID, InsertPos);
176}
177
178void Preprocessor::updateModuleMacroInfo(const IdentifierInfo *II,
179 ModuleMacroInfo &Info) {
180 assert(Info.ActiveModuleMacrosGeneration !=
181 CurSubmoduleState->VisibleModules.getGeneration() &&
182 "don't need to update this macro name info");
183 Info.ActiveModuleMacrosGeneration =
184 CurSubmoduleState->VisibleModules.getGeneration();
185
186 auto Leaf = LeafModuleMacros.find(II);
187 if (Leaf == LeafModuleMacros.end()) {
188 // No imported macros at all: nothing to do.
189 return;
190 }
191
192 Info.ActiveModuleMacros.clear();
193
194 // Every macro that's locally overridden is overridden by a visible macro.
195 llvm::DenseMap<ModuleMacro *, int> NumHiddenOverrides;
196 for (auto *O : Info.OverriddenMacros)
197 NumHiddenOverrides[O] = -1;
198
199 // Collect all macros that are not overridden by a visible macro.
201 for (auto *LeafMM : Leaf->second) {
202 assert(LeafMM->getNumOverridingMacros() == 0 && "leaf macro overridden");
203 if (NumHiddenOverrides.lookup(LeafMM) == 0)
204 Worklist.push_back(LeafMM);
205 }
206 while (!Worklist.empty()) {
207 auto *MM = Worklist.pop_back_val();
208 if (CurSubmoduleState->VisibleModules.isVisible(MM->getOwningModule())) {
209 // We only care about collecting definitions; undefinitions only act
210 // to override other definitions.
211 if (MM->getMacroInfo())
212 Info.ActiveModuleMacros.push_back(MM);
213 } else {
214 for (auto *O : MM->overrides())
215 if ((unsigned)++NumHiddenOverrides[O] == O->getNumOverridingMacros())
216 Worklist.push_back(O);
217 }
218 }
219 // Our reverse postorder walk found the macros in reverse order.
220 std::reverse(Info.ActiveModuleMacros.begin(), Info.ActiveModuleMacros.end());
221
222 // Determine whether the macro name is ambiguous.
223 MacroInfo *MI = nullptr;
224 bool IsSystemMacro = true;
225 bool IsAmbiguous = false;
226 if (auto *MD = Info.MD) {
227 while (isa_and_nonnull<VisibilityMacroDirective>(MD))
228 MD = MD->getPrevious();
229 if (auto *DMD = dyn_cast_or_null<DefMacroDirective>(MD)) {
230 MI = DMD->getInfo();
231 IsSystemMacro &= SourceMgr.isInSystemHeader(DMD->getLocation());
232 }
233 }
234 for (auto *Active : Info.ActiveModuleMacros) {
235 auto *NewMI = Active->getMacroInfo();
236
237 // Before marking the macro as ambiguous, check if this is a case where
238 // both macros are in system headers. If so, we trust that the system
239 // did not get it wrong. This also handles cases where Clang's own
240 // headers have a different spelling of certain system macros:
241 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
242 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
243 //
244 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
245 // overrides the system limits.h's macros, so there's no conflict here.
246 if (MI && NewMI != MI &&
247 !MI->isIdenticalTo(*NewMI, *this, /*Syntactically=*/true))
248 IsAmbiguous = true;
249 IsSystemMacro &= Active->getOwningModule()->IsSystem ||
250 SourceMgr.isInSystemHeader(NewMI->getDefinitionLoc());
251 MI = NewMI;
252 }
253 Info.IsAmbiguous = IsAmbiguous && !IsSystemMacro;
254}
255
258 auto LeafIt = LeafModuleMacros.find(II);
259 if (LeafIt != LeafModuleMacros.end())
260 Leaf = LeafIt->second;
261 const MacroState *State = nullptr;
262 auto Pos = CurSubmoduleState->Macros.find(II);
263 if (Pos != CurSubmoduleState->Macros.end())
264 State = &Pos->second;
265
266 llvm::errs() << "MacroState " << State << " " << II->getNameStart();
267 if (State && State->isAmbiguous(*this, II))
268 llvm::errs() << " ambiguous";
269 if (State && !State->getOverriddenMacros().empty()) {
270 llvm::errs() << " overrides";
271 for (auto *O : State->getOverriddenMacros())
272 llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
273 }
274 llvm::errs() << "\n";
275
276 // Dump local macro directives.
277 for (auto *MD = State ? State->getLatest() : nullptr; MD;
278 MD = MD->getPrevious()) {
279 llvm::errs() << " ";
280 MD->dump();
281 }
282
283 // Dump module macros.
284 llvm::DenseSet<ModuleMacro*> Active;
285 for (auto *MM : State ? State->getActiveModuleMacros(*this, II)
287 Active.insert(MM);
288 llvm::DenseSet<ModuleMacro*> Visited;
290 while (!Worklist.empty()) {
291 auto *MM = Worklist.pop_back_val();
292 llvm::errs() << " ModuleMacro " << MM << " "
293 << MM->getOwningModule()->getFullModuleName();
294 if (!MM->getMacroInfo())
295 llvm::errs() << " undef";
296
297 if (Active.count(MM))
298 llvm::errs() << " active";
299 else if (!CurSubmoduleState->VisibleModules.isVisible(
300 MM->getOwningModule()))
301 llvm::errs() << " hidden";
302 else if (MM->getMacroInfo())
303 llvm::errs() << " overridden";
304
305 if (!MM->overrides().empty()) {
306 llvm::errs() << " overrides";
307 for (auto *O : MM->overrides()) {
308 llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
309 if (Visited.insert(O).second)
310 Worklist.push_back(O);
311 }
312 }
313 llvm::errs() << "\n";
314 if (auto *MI = MM->getMacroInfo()) {
315 llvm::errs() << " ";
316 MI->dump();
317 llvm::errs() << "\n";
318 }
319 }
320}
321
322/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
323/// identifier table.
324void Preprocessor::RegisterBuiltinMacros() {
325 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
326 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
327 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
328 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
329 Ident__COUNTER__ = RegisterBuiltinMacro("__COUNTER__");
330 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
331 Ident__FLT_EVAL_METHOD__ = RegisterBuiltinMacro("__FLT_EVAL_METHOD__");
332
333 // C++ Standing Document Extensions.
335 Ident__has_cpp_attribute = RegisterBuiltinMacro("__has_cpp_attribute");
336 else
337 Ident__has_cpp_attribute = nullptr;
338
339 // GCC Extensions.
340 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
341 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
342 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
343
344 // Microsoft Extensions.
345 if (getLangOpts().MicrosoftExt) {
346 Ident__identifier = RegisterBuiltinMacro("__identifier");
347 Ident__pragma = RegisterBuiltinMacro("__pragma");
348 } else {
349 Ident__identifier = nullptr;
350 Ident__pragma = nullptr;
351 }
352
353 // Clang Extensions.
354 Ident__FILE_NAME__ = RegisterBuiltinMacro("__FILE_NAME__");
355 Ident__has_feature = RegisterBuiltinMacro("__has_feature");
356 Ident__has_extension = RegisterBuiltinMacro("__has_extension");
357 Ident__has_builtin = RegisterBuiltinMacro("__has_builtin");
358 Ident__has_constexpr_builtin =
359 RegisterBuiltinMacro("__has_constexpr_builtin");
360 Ident__has_attribute = RegisterBuiltinMacro("__has_attribute");
361 if (!getLangOpts().CPlusPlus)
362 Ident__has_c_attribute = RegisterBuiltinMacro("__has_c_attribute");
363 else
364 Ident__has_c_attribute = nullptr;
365
366 Ident__has_declspec = RegisterBuiltinMacro("__has_declspec_attribute");
367 Ident__has_embed = RegisterBuiltinMacro("__has_embed");
368 Ident__has_include = RegisterBuiltinMacro("__has_include");
369 Ident__has_include_next = RegisterBuiltinMacro("__has_include_next");
370 Ident__has_warning = RegisterBuiltinMacro("__has_warning");
371 Ident__is_identifier = RegisterBuiltinMacro("__is_identifier");
372 Ident__is_target_arch = RegisterBuiltinMacro("__is_target_arch");
373 Ident__is_target_vendor = RegisterBuiltinMacro("__is_target_vendor");
374 Ident__is_target_os = RegisterBuiltinMacro("__is_target_os");
375 Ident__is_target_environment =
376 RegisterBuiltinMacro("__is_target_environment");
377 Ident__is_target_variant_os = RegisterBuiltinMacro("__is_target_variant_os");
378 Ident__is_target_variant_environment =
379 RegisterBuiltinMacro("__is_target_variant_environment");
380
381 // Modules.
382 Ident__building_module = RegisterBuiltinMacro("__building_module");
383 if (!getLangOpts().CurrentModule.empty())
384 Ident__MODULE__ = RegisterBuiltinMacro("__MODULE__");
385 else
386 Ident__MODULE__ = nullptr;
387}
388
389/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
390/// in its expansion, currently expands to that token literally.
392 const IdentifierInfo *MacroIdent,
393 Preprocessor &PP) {
395
396 // If the token isn't an identifier, it's always literally expanded.
397 if (!II) return true;
398
399 // If the information about this identifier is out of date, update it from
400 // the external source.
401 if (II->isOutOfDate())
403
404 // If the identifier is a macro, and if that macro is enabled, it may be
405 // expanded so it's not a trivial expansion.
406 if (auto *ExpansionMI = PP.getMacroInfo(II))
407 if (ExpansionMI->isEnabled() &&
408 // Fast expanding "#define X X" is ok, because X would be disabled.
409 II != MacroIdent)
410 return false;
411
412 // If this is an object-like macro invocation, it is safe to trivially expand
413 // it.
414 if (MI->isObjectLike()) return true;
415
416 // If this is a function-like macro invocation, it's safe to trivially expand
417 // as long as the identifier is not a macro argument.
418 return !llvm::is_contained(MI->params(), II);
419}
420
421/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
422/// expanded as a macro, handle it and return the next token as 'Identifier'.
423bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
424 const MacroDefinition &M) {
425 emitMacroExpansionWarnings(Identifier);
426
427 MacroInfo *MI = M.getMacroInfo();
428
429 // If this is a macro expansion in the "#if !defined(x)" line for the file,
430 // then the macro could expand to different things in other contexts, we need
431 // to disable the optimization in this case.
432 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
433
434 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
435 if (MI->isBuiltinMacro()) {
436 if (Callbacks)
437 Callbacks->MacroExpands(Identifier, M, Identifier.getLocation(),
438 /*Args=*/nullptr);
439 ExpandBuiltinMacro(Identifier);
440 return true;
441 }
442
443 /// Args - If this is a function-like macro expansion, this contains,
444 /// for each macro argument, the list of tokens that were provided to the
445 /// invocation.
446 MacroArgs *Args = nullptr;
447
448 // Remember where the end of the expansion occurred. For an object-like
449 // macro, this is the identifier. For a function-like macro, this is the ')'.
450 SourceLocation ExpansionEnd = Identifier.getLocation();
451
452 // If this is a function-like macro, read the arguments.
453 if (MI->isFunctionLike()) {
454 // Remember that we are now parsing the arguments to a macro invocation.
455 // Preprocessor directives used inside macro arguments are not portable, and
456 // this enables the warning.
457 InMacroArgs = true;
458 ArgMacro = &Identifier;
459
460 Args = ReadMacroCallArgumentList(Identifier, MI, ExpansionEnd);
461
462 // Finished parsing args.
463 InMacroArgs = false;
464 ArgMacro = nullptr;
465
466 // If there was an error parsing the arguments, bail out.
467 if (!Args) return true;
468
469 ++NumFnMacroExpanded;
470 } else {
471 ++NumMacroExpanded;
472 }
473
474 // Notice that this macro has been used.
475 markMacroAsUsed(MI);
476
477 // Remember where the token is expanded.
478 SourceLocation ExpandLoc = Identifier.getLocation();
479 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
480
481 if (Callbacks) {
482 if (InMacroArgs) {
483 // We can have macro expansion inside a conditional directive while
484 // reading the function macro arguments. To ensure, in that case, that
485 // MacroExpands callbacks still happen in source order, queue this
486 // callback to have it happen after the function macro callback.
487 DelayedMacroExpandsCallbacks.push_back(
488 MacroExpandsInfo(Identifier, M, ExpansionRange));
489 } else {
490 Callbacks->MacroExpands(Identifier, M, ExpansionRange, Args);
491 if (!DelayedMacroExpandsCallbacks.empty()) {
492 for (const MacroExpandsInfo &Info : DelayedMacroExpandsCallbacks) {
493 // FIXME: We lose macro args info with delayed callback.
494 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
495 /*Args=*/nullptr);
496 }
497 DelayedMacroExpandsCallbacks.clear();
498 }
499 }
500 }
501
502 // If the macro definition is ambiguous, complain.
503 if (M.isAmbiguous()) {
504 Diag(Identifier, diag::warn_pp_ambiguous_macro)
505 << Identifier.getIdentifierInfo();
506 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
507 << Identifier.getIdentifierInfo();
508 M.forAllDefinitions([&](const MacroInfo *OtherMI) {
509 if (OtherMI != MI)
510 Diag(OtherMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other)
511 << Identifier.getIdentifierInfo();
512 });
513 }
514
515 // If we started lexing a macro, enter the macro expansion body.
516
517 // If this macro expands to no tokens, don't bother to push it onto the
518 // expansion stack, only to take it right back off.
519 if (MI->getNumTokens() == 0) {
520 // No need for arg info.
521 if (Args) Args->destroy(*this);
522
523 // Propagate whitespace info as if we had pushed, then popped,
524 // a macro context.
526 PropagateLineStartLeadingSpaceInfo(Identifier);
527 ++NumFastMacroExpanded;
528 return false;
529 } else if (MI->getNumTokens() == 1 &&
531 *this)) {
532 // Otherwise, if this macro expands into a single trivially-expanded
533 // token: expand it now. This handles common cases like
534 // "#define VAL 42".
535
536 // No need for arg info.
537 if (Args) Args->destroy(*this);
538
539 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
540 // identifier to the expanded token.
541 bool isAtStartOfLine = Identifier.isAtStartOfLine();
542 bool hasLeadingSpace = Identifier.hasLeadingSpace();
543
544 // Replace the result token.
545 Identifier = MI->getReplacementToken(0);
546
547 // Restore the StartOfLine/LeadingSpace markers.
548 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
549 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
550
551 // Update the tokens location to include both its expansion and physical
552 // locations.
553 SourceLocation Loc =
554 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
555 ExpansionEnd,Identifier.getLength());
556 Identifier.setLocation(Loc);
557
558 // If this is a disabled macro or #define X X, we must mark the result as
559 // unexpandable.
560 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
561 if (MacroInfo *NewMI = getMacroInfo(NewII))
562 if (!NewMI->isEnabled() || NewMI == MI) {
563 Identifier.setFlag(Token::DisableExpand);
564 // Don't warn for "#define X X" like "#define bool bool" from
565 // stdbool.h.
566 if (NewMI != MI || MI->isFunctionLike())
567 Diag(Identifier, diag::pp_disabled_macro_expansion);
568 }
569 }
570
571 // Since this is not an identifier token, it can't be macro expanded, so
572 // we're done.
573 ++NumFastMacroExpanded;
574 return true;
575 }
576
577 // Start expanding the macro.
578 EnterMacro(Identifier, ExpansionEnd, MI, Args);
579 return false;
580}
581
586
587/// CheckMatchedBrackets - Returns true if the braces and parentheses in the
588/// token vector are properly nested.
591 for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
592 E = Tokens.end();
593 I != E; ++I) {
594 if (I->is(tok::l_paren)) {
595 Brackets.push_back(Paren);
596 } else if (I->is(tok::r_paren)) {
597 if (Brackets.empty() || Brackets.back() == Brace)
598 return false;
599 Brackets.pop_back();
600 } else if (I->is(tok::l_brace)) {
601 Brackets.push_back(Brace);
602 } else if (I->is(tok::r_brace)) {
603 if (Brackets.empty() || Brackets.back() == Paren)
604 return false;
605 Brackets.pop_back();
606 }
607 }
608 return Brackets.empty();
609}
610
611/// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
612/// vector of tokens in NewTokens. The new number of arguments will be placed
613/// in NumArgs and the ranges which need to surrounded in parentheses will be
614/// in ParenHints.
615/// Returns false if the token stream cannot be changed. If this is because
616/// of an initializer list starting a macro argument, the range of those
617/// initializer lists will be place in InitLists.
619 SmallVectorImpl<Token> &OldTokens,
620 SmallVectorImpl<Token> &NewTokens,
621 unsigned &NumArgs,
623 SmallVectorImpl<SourceRange> &InitLists) {
624 if (!CheckMatchedBrackets(OldTokens))
625 return false;
626
627 // Once it is known that the brackets are matched, only a simple count of the
628 // braces is needed.
629 unsigned Braces = 0;
630
631 // First token of a new macro argument.
632 SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
633
634 // First closing brace in a new macro argument. Used to generate
635 // SourceRanges for InitLists.
636 SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
637 NumArgs = 0;
638 Token TempToken;
639 // Set to true when a macro separator token is found inside a braced list.
640 // If true, the fixed argument spans multiple old arguments and ParenHints
641 // will be updated.
642 bool FoundSeparatorToken = false;
643 for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
644 E = OldTokens.end();
645 I != E; ++I) {
646 if (I->is(tok::l_brace)) {
647 ++Braces;
648 } else if (I->is(tok::r_brace)) {
649 --Braces;
650 if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
651 ClosingBrace = I;
652 } else if (I->is(tok::eof)) {
653 // EOF token is used to separate macro arguments
654 if (Braces != 0) {
655 // Assume comma separator is actually braced list separator and change
656 // it back to a comma.
657 FoundSeparatorToken = true;
658 I->setKind(tok::comma);
659 I->setLength(1);
660 } else { // Braces == 0
661 // Separator token still separates arguments.
662 ++NumArgs;
663
664 // If the argument starts with a brace, it can't be fixed with
665 // parentheses. A different diagnostic will be given.
666 if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
667 InitLists.push_back(
668 SourceRange(ArgStartIterator->getLocation(),
669 PP.getLocForEndOfToken(ClosingBrace->getLocation())));
670 ClosingBrace = E;
671 }
672
673 // Add left paren
674 if (FoundSeparatorToken) {
675 TempToken.startToken();
676 TempToken.setKind(tok::l_paren);
677 TempToken.setLocation(ArgStartIterator->getLocation());
678 TempToken.setLength(0);
679 NewTokens.push_back(TempToken);
680 }
681
682 // Copy over argument tokens
683 NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
684
685 // Add right paren and store the paren locations in ParenHints
686 if (FoundSeparatorToken) {
687 SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
688 TempToken.startToken();
689 TempToken.setKind(tok::r_paren);
690 TempToken.setLocation(Loc);
691 TempToken.setLength(0);
692 NewTokens.push_back(TempToken);
693 ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
694 Loc));
695 }
696
697 // Copy separator token
698 NewTokens.push_back(*I);
699
700 // Reset values
701 ArgStartIterator = I + 1;
702 FoundSeparatorToken = false;
703 }
704 }
705 }
706
707 return !ParenHints.empty() && InitLists.empty();
708}
709
710/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
711/// token is the '(' of the macro, this method is invoked to read all of the
712/// actual arguments specified for the macro invocation. This returns null on
713/// error.
714MacroArgs *Preprocessor::ReadMacroCallArgumentList(Token &MacroName,
715 MacroInfo *MI,
716 SourceLocation &MacroEnd) {
717 // The number of fixed arguments to parse.
718 unsigned NumFixedArgsLeft = MI->getNumParams();
719 bool isVariadic = MI->isVariadic();
720
721 // Outer loop, while there are more arguments, keep reading them.
722 Token Tok;
723
724 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
725 // an argument value in a macro could expand to ',' or '(' or ')'.
727 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
728
729 // ArgTokens - Build up a list of tokens that make up each argument. Each
730 // argument is separated by an EOF token. Use a SmallVector so we can avoid
731 // heap allocations in the common case.
732 SmallVector<Token, 64> ArgTokens;
733 bool ContainsCodeCompletionTok = false;
734 bool FoundElidedComma = false;
735
736 SourceLocation TooManyArgsLoc;
737
738 unsigned NumActuals = 0;
739 while (Tok.isNot(tok::r_paren)) {
740 if (ContainsCodeCompletionTok && Tok.isOneOf(tok::eof, tok::eod))
741 break;
742
743 assert(Tok.isOneOf(tok::l_paren, tok::comma) &&
744 "only expect argument separators here");
745
746 size_t ArgTokenStart = ArgTokens.size();
747 SourceLocation ArgStartLoc = Tok.getLocation();
748
749 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
750 // that we already consumed the first one.
751 unsigned NumParens = 0;
752
753 while (true) {
754 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
755 // an argument value in a macro could expand to ',' or '(' or ')'.
757
758 if (Tok.isOneOf(tok::eof, tok::eod)) { // "#if f(<eof>" & "#if f(\n"
759 if (!ContainsCodeCompletionTok) {
760 Diag(MacroName, diag::err_unterm_macro_invoc);
761 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
762 << MacroName.getIdentifierInfo();
763 // Do not lose the EOF/EOD. Return it to the client.
764 MacroName = Tok;
765 return nullptr;
766 }
767 // Do not lose the EOF/EOD.
768 auto Toks = std::make_unique<Token[]>(1);
769 Toks[0] = Tok;
770 EnterTokenStream(std::move(Toks), 1, true, /*IsReinject*/ false);
771 break;
772 } else if (Tok.is(tok::r_paren)) {
773 // If we found the ) token, the macro arg list is done.
774 if (NumParens-- == 0) {
775 MacroEnd = Tok.getLocation();
776 if (!ArgTokens.empty() &&
777 ArgTokens.back().commaAfterElided()) {
778 FoundElidedComma = true;
779 }
780 break;
781 }
782 } else if (Tok.is(tok::l_paren)) {
783 ++NumParens;
784 } else if (Tok.is(tok::comma)) {
785 // In Microsoft-compatibility mode, single commas from nested macro
786 // expansions should not be considered as argument separators. We test
787 // for this with the IgnoredComma token flag.
789 // However, in MSVC's preprocessor, subsequent expansions do treat
790 // these commas as argument separators. This leads to a common
791 // workaround used in macros that need to work in both MSVC and
792 // compliant preprocessors. Therefore, the IgnoredComma flag can only
793 // apply once to any given token.
795 } else if (NumParens == 0) {
796 // Comma ends this argument if there are more fixed arguments
797 // expected. However, if this is a variadic macro, and this is part of
798 // the variadic part, then the comma is just an argument token.
799 if (!isVariadic)
800 break;
801 if (NumFixedArgsLeft > 1)
802 break;
803 }
804 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
805 // If this is a comment token in the argument list and we're just in
806 // -C mode (not -CC mode), discard the comment.
807 continue;
808 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
809 // Reading macro arguments can cause macros that we are currently
810 // expanding from to be popped off the expansion stack. Doing so causes
811 // them to be reenabled for expansion. Here we record whether any
812 // identifiers we lex as macro arguments correspond to disabled macros.
813 // If so, we mark the token as noexpand. This is a subtle aspect of
814 // C99 6.10.3.4p2.
815 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
816 if (!MI->isEnabled())
818 } else if (Tok.is(tok::code_completion)) {
819 ContainsCodeCompletionTok = true;
820 if (CodeComplete)
821 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
822 MI, NumActuals);
823 // Don't mark that we reached the code-completion point because the
824 // parser is going to handle the token and there will be another
825 // code-completion callback.
826 }
827
828 ArgTokens.push_back(Tok);
829 }
830
831 // If this was an empty argument list foo(), don't add this as an empty
832 // argument.
833 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
834 break;
835
836 // If this is not a variadic macro, and too many args were specified, emit
837 // an error.
838 if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
839 if (ArgTokens.size() != ArgTokenStart)
840 TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
841 else
842 TooManyArgsLoc = ArgStartLoc;
843 }
844
845 // Empty arguments are standard in C99 and C++0x, and are supported as an
846 // extension in other modes.
847 if (ArgTokens.size() == ArgTokenStart && !getLangOpts().C99)
849 ? diag::warn_cxx98_compat_empty_fnmacro_arg
850 : diag::ext_empty_fnmacro_arg);
851
852 // Add a marker EOF token to the end of the token list for this argument.
853 Token EOFTok;
854 EOFTok.startToken();
855 EOFTok.setKind(tok::eof);
856 EOFTok.setLocation(Tok.getLocation());
857 EOFTok.setLength(0);
858 ArgTokens.push_back(EOFTok);
859 ++NumActuals;
860 if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
861 --NumFixedArgsLeft;
862 }
863
864 // Okay, we either found the r_paren. Check to see if we parsed too few
865 // arguments.
866 unsigned MinArgsExpected = MI->getNumParams();
867
868 // If this is not a variadic macro, and too many args were specified, emit
869 // an error.
870 if (!isVariadic && NumActuals > MinArgsExpected &&
871 !ContainsCodeCompletionTok) {
872 // Emit the diagnostic at the macro name in case there is a missing ).
873 // Emitting it at the , could be far away from the macro name.
874 Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
875 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
876 << MacroName.getIdentifierInfo();
877
878 // Commas from braced initializer lists will be treated as argument
879 // separators inside macros. Attempt to correct for this with parentheses.
880 // TODO: See if this can be generalized to angle brackets for templates
881 // inside macro arguments.
882
883 SmallVector<Token, 4> FixedArgTokens;
884 unsigned FixedNumArgs = 0;
885 SmallVector<SourceRange, 4> ParenHints, InitLists;
886 if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
887 ParenHints, InitLists)) {
888 if (!InitLists.empty()) {
889 DiagnosticBuilder DB =
890 Diag(MacroName,
891 diag::note_init_list_at_beginning_of_macro_argument);
892 for (SourceRange Range : InitLists)
893 DB << Range;
894 }
895 return nullptr;
896 }
897 if (FixedNumArgs != MinArgsExpected)
898 return nullptr;
899
900 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
901 for (SourceRange ParenLocation : ParenHints) {
902 DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
903 DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
904 }
905 ArgTokens.swap(FixedArgTokens);
906 NumActuals = FixedNumArgs;
907 }
908
909 // See MacroArgs instance var for description of this.
910 bool isVarargsElided = false;
911
912 if (ContainsCodeCompletionTok) {
913 // Recover from not-fully-formed macro invocation during code-completion.
914 Token EOFTok;
915 EOFTok.startToken();
916 EOFTok.setKind(tok::eof);
917 EOFTok.setLocation(Tok.getLocation());
918 EOFTok.setLength(0);
919 for (; NumActuals < MinArgsExpected; ++NumActuals)
920 ArgTokens.push_back(EOFTok);
921 }
922
923 if (NumActuals < MinArgsExpected) {
924 // There are several cases where too few arguments is ok, handle them now.
925 if (NumActuals == 0 && MinArgsExpected == 1) {
926 // #define A(X) or #define A(...) ---> A()
927
928 // If there is exactly one argument, and that argument is missing,
929 // then we have an empty "()" argument empty list. This is fine, even if
930 // the macro expects one argument (the argument is just empty).
931 isVarargsElided = MI->isVariadic();
932 } else if ((FoundElidedComma || MI->isVariadic()) &&
933 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
934 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
935 // Varargs where the named vararg parameter is missing: OK as extension.
936 // #define A(x, ...)
937 // A("blah")
938 //
939 // If the macro contains the comma pasting extension, the diagnostic
940 // is suppressed; we know we'll get another diagnostic later.
941 if (!MI->hasCommaPasting()) {
942 // C++20 [cpp.replace]p15, C23 6.10.5p12
943 //
944 // C++20 and C23 allow this construct, but standards before that
945 // do not (we allow it as an extension).
946 unsigned ID;
948 ID = diag::warn_cxx17_compat_missing_varargs_arg;
949 else if (getLangOpts().CPlusPlus)
950 ID = diag::ext_cxx_missing_varargs_arg;
951 else if (getLangOpts().C23)
952 ID = diag::warn_c17_compat_missing_varargs_arg;
953 else
954 ID = diag::ext_c_missing_varargs_arg;
955 Diag(Tok, ID);
956 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
957 << MacroName.getIdentifierInfo();
958 }
959
960 // Remember this occurred, allowing us to elide the comma when used for
961 // cases like:
962 // #define A(x, foo...) blah(a, ## foo)
963 // #define B(x, ...) blah(a, ## __VA_ARGS__)
964 // #define C(...) blah(a, ## __VA_ARGS__)
965 // A(x) B(x) C()
966 isVarargsElided = true;
967 } else if (!ContainsCodeCompletionTok) {
968 // Otherwise, emit the error.
969 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
970 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
971 << MacroName.getIdentifierInfo();
972 return nullptr;
973 }
974
975 // Add a marker EOF token to the end of the token list for this argument.
976 SourceLocation EndLoc = Tok.getLocation();
977 Tok.startToken();
978 Tok.setKind(tok::eof);
979 Tok.setLocation(EndLoc);
980 Tok.setLength(0);
981 ArgTokens.push_back(Tok);
982
983 // If we expect two arguments, add both as empty.
984 if (NumActuals == 0 && MinArgsExpected == 2)
985 ArgTokens.push_back(Tok);
986
987 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
988 !ContainsCodeCompletionTok) {
989 // Emit the diagnostic at the macro name in case there is a missing ).
990 // Emitting it at the , could be far away from the macro name.
991 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
992 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
993 << MacroName.getIdentifierInfo();
994 return nullptr;
995 }
996
997 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
998}
999
1000/// Keeps macro expanded tokens for TokenLexers.
1001//
1002/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
1003/// going to lex in the cache and when it finishes the tokens are removed
1004/// from the end of the cache.
1005Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
1006 ArrayRef<Token> tokens) {
1007 assert(tokLexer);
1008 if (tokens.empty())
1009 return nullptr;
1010
1011 size_t newIndex = MacroExpandedTokens.size();
1012 bool cacheNeedsToGrow = tokens.size() >
1013 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
1014 MacroExpandedTokens.append(tokens.begin(), tokens.end());
1015
1016 if (cacheNeedsToGrow) {
1017 // Go through all the TokenLexers whose 'Tokens' pointer points in the
1018 // buffer and update the pointers to the (potential) new buffer array.
1019 for (const auto &Lexer : MacroExpandingLexersStack) {
1020 TokenLexer *prevLexer;
1021 size_t tokIndex;
1022 std::tie(prevLexer, tokIndex) = Lexer;
1023 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
1024 }
1025 }
1026
1027 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
1028 return MacroExpandedTokens.data() + newIndex;
1029}
1030
1031void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
1032 assert(!MacroExpandingLexersStack.empty());
1033 size_t tokIndex = MacroExpandingLexersStack.back().second;
1034 assert(tokIndex < MacroExpandedTokens.size());
1035 // Pop the cached macro expanded tokens from the end.
1036 MacroExpandedTokens.resize(tokIndex);
1037 MacroExpandingLexersStack.pop_back();
1038}
1039
1040/// ComputeDATE_TIME - Compute the current time, enter it into the specified
1041/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1042/// the identifier tokens inserted.
1043static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
1044 Preprocessor &PP) {
1045 time_t TT;
1046 std::tm *TM;
1049 TM = std::gmtime(&TT);
1050 } else {
1051 TT = std::time(nullptr);
1052 TM = std::localtime(&TT);
1053 }
1054
1055 static const char * const Months[] = {
1056 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1057 };
1058
1059 {
1060 SmallString<32> TmpBuffer;
1061 llvm::raw_svector_ostream TmpStream(TmpBuffer);
1062 if (TM)
1063 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
1064 TM->tm_mday, TM->tm_year + 1900);
1065 else
1066 TmpStream << "??? ?? ????";
1067 Token TmpTok;
1068 TmpTok.startToken();
1069 PP.CreateString(TmpStream.str(), TmpTok);
1070 DATELoc = TmpTok.getLocation();
1071 }
1072
1073 {
1074 SmallString<32> TmpBuffer;
1075 llvm::raw_svector_ostream TmpStream(TmpBuffer);
1076 if (TM)
1077 TmpStream << llvm::format("\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min,
1078 TM->tm_sec);
1079 else
1080 TmpStream << "??:??:??";
1081 Token TmpTok;
1082 TmpTok.startToken();
1083 PP.CreateString(TmpStream.str(), TmpTok);
1084 TIMELoc = TmpTok.getLocation();
1085 }
1086}
1087
1088/// HasFeature - Return true if we recognize and implement the feature
1089/// specified by the identifier as a standard language feature.
1090static bool HasFeature(const Preprocessor &PP, StringRef Feature) {
1091 const LangOptions &LangOpts = PP.getLangOpts();
1092
1093 // Normalize the feature name, __foo__ becomes foo.
1094 if (Feature.starts_with("__") && Feature.ends_with("__") &&
1095 Feature.size() >= 4)
1096 Feature = Feature.substr(2, Feature.size() - 4);
1097
1098#define FEATURE(Name, Predicate) .Case(#Name, Predicate)
1099 return llvm::StringSwitch<bool>(Feature)
1100#include "clang/Basic/Features.def"
1101 .Default(false);
1102#undef FEATURE
1103}
1104
1105/// HasExtension - Return true if we recognize and implement the feature
1106/// specified by the identifier, either as an extension or a standard language
1107/// feature.
1108static bool HasExtension(const Preprocessor &PP, StringRef Extension) {
1109 if (HasFeature(PP, Extension))
1110 return true;
1111
1112 // If the use of an extension results in an error diagnostic, extensions are
1113 // effectively unavailable, so just return false here.
1116 return false;
1117
1118 const LangOptions &LangOpts = PP.getLangOpts();
1119
1120 // Normalize the extension name, __foo__ becomes foo.
1121 if (Extension.starts_with("__") && Extension.ends_with("__") &&
1122 Extension.size() >= 4)
1123 Extension = Extension.substr(2, Extension.size() - 4);
1124
1125 // Because we inherit the feature list from HasFeature, this string switch
1126 // must be less restrictive than HasFeature's.
1127#define EXTENSION(Name, Predicate) .Case(#Name, Predicate)
1128 return llvm::StringSwitch<bool>(Extension)
1129#include "clang/Basic/Features.def"
1130 .Default(false);
1131#undef EXTENSION
1132}
1133
1134/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1135/// or '__has_include_next("path")' expression.
1136/// Returns true if successful.
1138 Preprocessor &PP,
1139 ConstSearchDirIterator LookupFrom,
1140 const FileEntry *LookupFromFile) {
1141 // Save the location of the current token. If a '(' is later found, use
1142 // that location. If not, use the end of this location instead.
1143 SourceLocation LParenLoc = Tok.getLocation();
1144
1145 // These expressions are only allowed within a preprocessor directive.
1146 if (!PP.isParsingIfOrElifDirective()) {
1147 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II;
1148 // Return a valid identifier token.
1149 assert(Tok.is(tok::identifier));
1150 Tok.setIdentifierInfo(II);
1151 return false;
1152 }
1153
1154 // Get '('. If we don't have a '(', try to form a header-name token.
1155 do {
1156 if (PP.LexHeaderName(Tok))
1157 return false;
1158 } while (Tok.getKind() == tok::comment);
1159
1160 // Ensure we have a '('.
1161 if (Tok.isNot(tok::l_paren)) {
1162 // No '(', use end of last token.
1163 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
1164 PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
1165 // If the next token looks like a filename or the start of one,
1166 // assume it is and process it as such.
1167 if (Tok.isNot(tok::header_name))
1168 return false;
1169 } else {
1170 // Save '(' location for possible missing ')' message.
1171 LParenLoc = Tok.getLocation();
1172 if (PP.LexHeaderName(Tok))
1173 return false;
1174 }
1175
1176 if (Tok.isNot(tok::header_name)) {
1177 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1178 return false;
1179 }
1180
1181 // Reserve a buffer to get the spelling.
1182 SmallString<128> FilenameBuffer;
1183 bool Invalid = false;
1184 StringRef Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1185 if (Invalid)
1186 return false;
1187
1188 SourceLocation FilenameLoc = Tok.getLocation();
1189
1190 // Get ')'.
1191 PP.LexNonComment(Tok);
1192
1193 // Ensure we have a trailing ).
1194 if (Tok.isNot(tok::r_paren)) {
1195 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1196 << II << tok::r_paren;
1197 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1198 return false;
1199 }
1200
1201 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1202 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1203 // error.
1204 if (Filename.empty())
1205 return false;
1206
1207 // Passing this to LookupFile forces header search to check whether the found
1208 // file belongs to a module. Skipping that check could incorrectly mark
1209 // modular header as textual, causing issues down the line.
1211
1212 // Search include directories.
1214 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
1215 nullptr, nullptr, nullptr, &KH, nullptr, nullptr);
1216
1217 if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
1219 if (File)
1221 Callbacks->HasInclude(FilenameLoc, Filename, isAngled, File, FileType);
1222 }
1223
1224 // Get the result value. A result of true means the file exists.
1225 return File.has_value();
1226}
1227
1228/// EvaluateHasEmbed - Process a '__has_embed("foo" params...)' expression.
1229/// Returns a filled optional with the value if successful; otherwise, empty.
1230EmbedResult Preprocessor::EvaluateHasEmbed(Token &Tok, IdentifierInfo *II) {
1231 // These expressions are only allowed within a preprocessor directive.
1232 if (!this->isParsingIfOrElifDirective()) {
1233 Diag(Tok, diag::err_pp_directive_required) << II;
1234 // Return a valid identifier token.
1235 assert(Tok.is(tok::identifier));
1237 return EmbedResult::Invalid;
1238 }
1239
1240 // Ensure we have a '('.
1242 if (Tok.isNot(tok::l_paren)) {
1243 Diag(Tok, diag::err_pp_expected_after) << II << tok::l_paren;
1244 // If the next token looks like a filename or the start of one,
1245 // assume it is and process it as such.
1246 return EmbedResult::Invalid;
1247 }
1248
1249 // Save '(' location for possible missing ')' message and then lex the header
1250 // name token for the embed resource.
1251 SourceLocation LParenLoc = Tok.getLocation();
1252 if (this->LexHeaderName(Tok))
1253 return EmbedResult::Invalid;
1254
1255 if (Tok.isNot(tok::header_name)) {
1256 Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1257 return EmbedResult::Invalid;
1258 }
1259
1260 SourceLocation FilenameLoc = Tok.getLocation();
1261 Token FilenameTok = Tok;
1262
1263 std::optional<LexEmbedParametersResult> Params =
1264 this->LexEmbedParameters(Tok, /*ForHasEmbed=*/true);
1265
1266 if (!Params)
1267 return EmbedResult::Invalid;
1268
1269 if (Tok.isNot(tok::r_paren)) {
1270 Diag(this->getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1271 << II << tok::r_paren;
1272 Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1273 if (Tok.isNot(tok::eod))
1275 return EmbedResult::Invalid;
1276 }
1277
1278 if (Params->UnrecognizedParams > 0)
1279 return EmbedResult::NotFound;
1280
1281 SmallString<128> FilenameBuffer;
1282 StringRef Filename = this->getSpelling(FilenameTok, FilenameBuffer);
1283 if (Filename.empty())
1284 return EmbedResult::Empty;
1285
1286 bool isAngled =
1287 this->GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
1288 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1289 // error.
1290 OptionalFileEntryRef MaybeFileEntry =
1291 this->LookupEmbedFile(Filename, isAngled, false);
1292 if (Callbacks) {
1293 Callbacks->HasEmbed(LParenLoc, Filename, isAngled, MaybeFileEntry);
1294 }
1295 if (!MaybeFileEntry)
1296 return EmbedResult::NotFound;
1297
1298 size_t FileSize = MaybeFileEntry->getSize();
1299 // First, "offset" into the file (this reduces the amount of data we can read
1300 // from the file).
1301 if (Params->MaybeOffsetParam) {
1302 if (Params->MaybeOffsetParam->Offset > FileSize)
1303 FileSize = 0;
1304 else
1305 FileSize -= Params->MaybeOffsetParam->Offset;
1306 }
1307
1308 // Second, limit the data from the file (this also reduces the amount of data
1309 // we can read from the file).
1310 if (Params->MaybeLimitParam) {
1311 if (Params->MaybeLimitParam->Limit > FileSize)
1312 FileSize = 0;
1313 else
1314 FileSize = Params->MaybeLimitParam->Limit;
1315 }
1316
1317 // If we have no data left to read, the file is empty, otherwise we have the
1318 // expected resource.
1319 if (FileSize == 0)
1320 return EmbedResult::Empty;
1321 return EmbedResult::Found;
1322}
1323
1324bool Preprocessor::EvaluateHasInclude(Token &Tok, IdentifierInfo *II) {
1325 return EvaluateHasIncludeCommon(Tok, II, *this, nullptr, nullptr);
1326}
1327
1328bool Preprocessor::EvaluateHasIncludeNext(Token &Tok, IdentifierInfo *II) {
1329 ConstSearchDirIterator Lookup = nullptr;
1330 const FileEntry *LookupFromFile;
1331 std::tie(Lookup, LookupFromFile) = getIncludeNextStart(Tok);
1332
1333 return EvaluateHasIncludeCommon(Tok, II, *this, Lookup, LookupFromFile);
1334}
1335
1336/// Process single-argument builtin feature-like macros that return
1337/// integer values.
1338static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS,
1339 Token &Tok, IdentifierInfo *II,
1340 Preprocessor &PP, bool ExpandArgs,
1341 llvm::function_ref<
1342 int(Token &Tok,
1343 bool &HasLexedNextTok)> Op) {
1344 // Parse the initial '('.
1346 if (Tok.isNot(tok::l_paren)) {
1347 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1348 << tok::l_paren;
1349
1350 // Provide a dummy '0' value on output stream to elide further errors.
1351 if (!Tok.isOneOf(tok::eof, tok::eod)) {
1352 OS << 0;
1353 Tok.setKind(tok::numeric_constant);
1354 }
1355 return;
1356 }
1357
1358 unsigned ParenDepth = 1;
1359 SourceLocation LParenLoc = Tok.getLocation();
1360 std::optional<int> Result;
1361
1362 Token ResultTok;
1363 bool SuppressDiagnostic = false;
1364 while (Tok.isNoneOf(tok::eod, tok::eof)) {
1365 // Parse next token.
1366 if (ExpandArgs)
1367 PP.Lex(Tok);
1368 else
1370
1371already_lexed:
1372 switch (Tok.getKind()) {
1373 case tok::eof:
1374 case tok::eod:
1375 // Don't provide even a dummy value if the eod or eof marker is
1376 // reached. Simply provide a diagnostic.
1377 PP.Diag(Tok.getLocation(), diag::err_unterm_macro_invoc);
1378 return;
1379
1380 case tok::comma:
1381 if (!SuppressDiagnostic) {
1382 PP.Diag(Tok.getLocation(), diag::err_too_many_args_in_macro_invoc);
1383 SuppressDiagnostic = true;
1384 }
1385 continue;
1386
1387 case tok::l_paren:
1388 ++ParenDepth;
1389 if (Result)
1390 break;
1391 if (!SuppressDiagnostic) {
1392 PP.Diag(Tok.getLocation(), diag::err_pp_nested_paren) << II;
1393 SuppressDiagnostic = true;
1394 }
1395 continue;
1396
1397 case tok::r_paren:
1398 if (--ParenDepth > 0)
1399 continue;
1400
1401 // The last ')' has been reached; return the value if one found or
1402 // a diagnostic and a dummy value.
1403 if (Result) {
1404 OS << *Result;
1405 // For strict conformance to __has_cpp_attribute rules, use 'L'
1406 // suffix for dated literals.
1407 if (*Result > 1)
1408 OS << 'L';
1409 } else {
1410 OS << 0;
1411 if (!SuppressDiagnostic)
1412 PP.Diag(Tok.getLocation(), diag::err_too_few_args_in_macro_invoc);
1413 }
1414 Tok.setKind(tok::numeric_constant);
1415 return;
1416
1417 default: {
1418 // Parse the macro argument, if one not found so far.
1419 if (Result)
1420 break;
1421
1422 bool HasLexedNextToken = false;
1423 Result = Op(Tok, HasLexedNextToken);
1424 ResultTok = Tok;
1425 if (HasLexedNextToken)
1426 goto already_lexed;
1427 continue;
1428 }
1429 }
1430
1431 // Diagnose missing ')'.
1432 if (!SuppressDiagnostic) {
1433 if (auto Diag = PP.Diag(Tok.getLocation(), diag::err_pp_expected_after)) {
1434 if (IdentifierInfo *LastII = ResultTok.getIdentifierInfo())
1435 Diag << LastII;
1436 else
1437 Diag << ResultTok.getKind();
1438 Diag << tok::r_paren << ResultTok.getLocation();
1439 }
1440 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1441 SuppressDiagnostic = true;
1442 }
1443}
1444}
1445
1446/// Helper function to return the IdentifierInfo structure of a Token
1447/// or generate a diagnostic if none available.
1449 Preprocessor &PP,
1450 signed DiagID) {
1451 IdentifierInfo *II;
1452 if (!Tok.isAnnotation() && (II = Tok.getIdentifierInfo()))
1453 return II;
1454
1455 PP.Diag(Tok.getLocation(), DiagID);
1456 return nullptr;
1457}
1458
1459/// Implements the __is_target_arch builtin macro.
1460static bool isTargetArch(const TargetInfo &TI, const IdentifierInfo *II) {
1461 llvm::Triple Arch(II->getName().lower() + "--");
1462 const llvm::Triple &TT = TI.getTriple();
1463 if (TT.isThumb()) {
1464 // arm matches thumb or thumbv7. armv7 matches thumbv7.
1465 if ((Arch.getSubArch() == llvm::Triple::NoSubArch ||
1466 Arch.getSubArch() == TT.getSubArch()) &&
1467 ((TT.getArch() == llvm::Triple::thumb &&
1468 Arch.getArch() == llvm::Triple::arm) ||
1469 (TT.getArch() == llvm::Triple::thumbeb &&
1470 Arch.getArch() == llvm::Triple::armeb)))
1471 return true;
1472 }
1473 // Check the parsed arch when it has no sub arch to allow Clang to
1474 // match thumb to thumbv7 but to prohibit matching thumbv6 to thumbv7.
1475 return (Arch.getSubArch() == llvm::Triple::NoSubArch ||
1476 Arch.getSubArch() == TT.getSubArch()) &&
1477 Arch.getArch() == TT.getArch();
1478}
1479
1480/// Implements the __is_target_vendor builtin macro.
1481static bool isTargetVendor(const TargetInfo &TI, const IdentifierInfo *II) {
1482 StringRef VendorName = TI.getTriple().getVendorName();
1483 if (VendorName.empty())
1484 VendorName = "unknown";
1485 return VendorName.equals_insensitive(II->getName());
1486}
1487
1488/// Implements the __is_target_os builtin macro.
1489static bool isTargetOS(const TargetInfo &TI, const IdentifierInfo *II) {
1490 llvm::Triple OS(llvm::Twine("unknown-unknown-") + II->getName().lower());
1491 if (OS.getOS() == llvm::Triple::Darwin) {
1492 // Darwin matches macos, ios, etc.
1493 return TI.getTriple().isOSDarwin();
1494 }
1495 return TI.getTriple().getOS() == OS.getOS();
1496}
1497
1498/// Implements the __is_target_environment builtin macro.
1499static bool isTargetEnvironment(const TargetInfo &TI,
1500 const IdentifierInfo *II) {
1501 llvm::Triple Env(llvm::Twine("---") + II->getName().lower());
1502 // The unknown environment is matched only if
1503 // '__is_target_environment(unknown)' is used.
1504 if (Env.getEnvironment() == llvm::Triple::UnknownEnvironment &&
1505 Env.getEnvironmentName() != "unknown")
1506 return false;
1507 return TI.getTriple().getEnvironment() == Env.getEnvironment();
1508}
1509
1510/// Implements the __is_target_variant_os builtin macro.
1511static bool isTargetVariantOS(const TargetInfo &TI, const IdentifierInfo *II) {
1512 if (TI.getTriple().isOSDarwin()) {
1513 const llvm::Triple *VariantTriple = TI.getDarwinTargetVariantTriple();
1514 if (!VariantTriple)
1515 return false;
1516
1517 llvm::Triple OS(llvm::Twine("unknown-unknown-") + II->getName().lower());
1518 if (OS.getOS() == llvm::Triple::Darwin) {
1519 // Darwin matches macos, ios, etc.
1520 return VariantTriple->isOSDarwin();
1521 }
1522 return VariantTriple->getOS() == OS.getOS();
1523 }
1524 return false;
1525}
1526
1527/// Implements the __is_target_variant_environment builtin macro.
1529 const IdentifierInfo *II) {
1530 if (TI.getTriple().isOSDarwin()) {
1531 const llvm::Triple *VariantTriple = TI.getDarwinTargetVariantTriple();
1532 if (!VariantTriple)
1533 return false;
1534 llvm::Triple Env(llvm::Twine("---") + II->getName().lower());
1535 return VariantTriple->getEnvironment() == Env.getEnvironment();
1536 }
1537 return false;
1538}
1539
1540#if defined(__sun__) && defined(__svr4__) && defined(__clang__) && \
1541 __clang__ < 20
1542// GCC mangles std::tm as tm for binary compatibility on Solaris (Issue
1543// #33114). We need to match this to allow the std::put_time calls to link
1544// (PR #99075). clang 20 contains a fix, but the workaround is still needed
1545// with older versions.
1546asm("_ZNKSt8time_putIcSt19ostreambuf_iteratorIcSt11char_traitsIcEEE3putES3_"
1547 "RSt8ios_basecPKSt2tmPKcSB_ = "
1548 "_ZNKSt8time_putIcSt19ostreambuf_iteratorIcSt11char_traitsIcEEE3putES3_"
1549 "RSt8ios_basecPK2tmPKcSB_");
1550#endif
1551
1552static bool IsBuiltinTrait(Token &Tok) {
1553
1554#define TYPE_TRAIT_1(Spelling, Name, Key) \
1555 case tok::kw_##Spelling: \
1556 return true;
1557#define TYPE_TRAIT_2(Spelling, Name, Key) \
1558 case tok::kw_##Spelling: \
1559 return true;
1560#define TYPE_TRAIT_N(Spelling, Name, Key) \
1561 case tok::kw_##Spelling: \
1562 return true;
1563#define ARRAY_TYPE_TRAIT(Spelling, Name, Key) \
1564 case tok::kw_##Spelling: \
1565 return true;
1566#define EXPRESSION_TRAIT(Spelling, Name, Key) \
1567 case tok::kw_##Spelling: \
1568 return true;
1569#define TRANSFORM_TYPE_TRAIT_DEF(K, Spelling) \
1570 case tok::kw___##Spelling: \
1571 return true;
1572
1573 switch (Tok.getKind()) {
1574 default:
1575 return false;
1576#include "clang/Basic/TokenKinds.def"
1577 }
1578}
1579
1580/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1581/// as a builtin macro, handle it and return the next token as 'Tok'.
1582void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1583 // Figure out which token this is.
1584 IdentifierInfo *II = Tok.getIdentifierInfo();
1585 assert(II && "Can't be a macro without id info!");
1586
1587 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1588 // invoke the pragma handler, then lex the token after it.
1589 if (II == Ident_Pragma)
1590 return Handle_Pragma(Tok);
1591 else if (II == Ident__pragma) // in non-MS mode this is null
1592 return HandleMicrosoft__pragma(Tok);
1593
1594 ++NumBuiltinMacroExpanded;
1595
1596 SmallString<128> TmpBuffer;
1597 llvm::raw_svector_ostream OS(TmpBuffer);
1598
1599 // Set up the return result.
1600 Tok.setIdentifierInfo(nullptr);
1602 bool IsAtStartOfLine = Tok.isAtStartOfLine();
1603 bool HasLeadingSpace = Tok.hasLeadingSpace();
1604
1605 if (II == Ident__LINE__) {
1606 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1607 // source file) of the current source line (an integer constant)". This can
1608 // be affected by #line.
1609 SourceLocation Loc = Tok.getLocation();
1610
1611 // Advance to the location of the first _, this might not be the first byte
1612 // of the token if it starts with an escaped newline.
1613 Loc = AdvanceToTokenCharacter(Loc, 0);
1614
1615 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1616 // a macro expansion. This doesn't matter for object-like macros, but
1617 // can matter for a function-like macro that expands to contain __LINE__.
1618 // Skip down through expansion points until we find a file loc for the
1619 // end of the expansion history.
1620 Loc = SourceMgr.getExpansionRange(Loc).getEnd();
1621 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1622
1623 // __LINE__ expands to a simple numeric value.
1624 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1625 Tok.setKind(tok::numeric_constant);
1626 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__ ||
1627 II == Ident__FILE_NAME__) {
1628 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1629 // character string literal)". This can be affected by #line.
1630 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1631
1632 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1633 // #include stack instead of the current file.
1634 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1635 SourceLocation NextLoc = PLoc.getIncludeLoc();
1636 while (NextLoc.isValid()) {
1637 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1638 if (PLoc.isInvalid())
1639 break;
1640
1641 NextLoc = PLoc.getIncludeLoc();
1642 }
1643 }
1644
1645 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1646 SmallString<256> FN;
1647 if (PLoc.isValid()) {
1648 // __FILE_NAME__ is a Clang-specific extension that expands to the
1649 // the last part of __FILE__.
1650 if (II == Ident__FILE_NAME__) {
1652 } else {
1653 FN += PLoc.getFilename();
1655 }
1656 Lexer::Stringify(FN);
1657 OS << '"' << FN << '"';
1658 }
1659 Tok.setKind(tok::string_literal);
1660 } else if (II == Ident__DATE__) {
1661 Diag(Tok.getLocation(), diag::warn_pp_date_time);
1662 if (!DATELoc.isValid())
1663 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1664 Tok.setKind(tok::string_literal);
1665 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1666 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1667 Tok.getLocation(),
1668 Tok.getLength()));
1669 return;
1670 } else if (II == Ident__TIME__) {
1671 Diag(Tok.getLocation(), diag::warn_pp_date_time);
1672 if (!TIMELoc.isValid())
1673 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1674 Tok.setKind(tok::string_literal);
1675 Tok.setLength(strlen("\"hh:mm:ss\""));
1676 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1677 Tok.getLocation(),
1678 Tok.getLength()));
1679 return;
1680 } else if (II == Ident__INCLUDE_LEVEL__) {
1681 // Compute the presumed include depth of this token. This can be affected
1682 // by GNU line markers.
1683 unsigned Depth = 0;
1684
1685 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1686 if (PLoc.isValid()) {
1687 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1688 for (; PLoc.isValid(); ++Depth)
1689 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1690 }
1691
1692 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1693 OS << Depth;
1694 Tok.setKind(tok::numeric_constant);
1695 } else if (II == Ident__TIMESTAMP__) {
1696 Diag(Tok.getLocation(), diag::warn_pp_date_time);
1697 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1698 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1699 std::string Result;
1700 std::stringstream TmpStream;
1701 TmpStream.imbue(std::locale("C"));
1702 if (getPreprocessorOpts().SourceDateEpoch) {
1703 time_t TT = *getPreprocessorOpts().SourceDateEpoch;
1704 std::tm *TM = std::gmtime(&TT);
1705 TmpStream << std::put_time(TM, "%a %b %e %T %Y");
1706 } else {
1707 // Get the file that we are lexing out of. If we're currently lexing from
1708 // a macro, dig into the include stack.
1709 const FileEntry *CurFile = nullptr;
1710 if (PreprocessorLexer *TheLexer = getCurrentFileLexer())
1711 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1712 if (CurFile) {
1713 time_t TT = CurFile->getModificationTime();
1714 struct tm *TM = localtime(&TT);
1715 TmpStream << std::put_time(TM, "%a %b %e %T %Y");
1716 }
1717 }
1718 Result = TmpStream.str();
1719 if (Result.empty())
1720 Result = "??? ??? ?? ??:??:?? ????";
1721 OS << '"' << Result << '"';
1722 Tok.setKind(tok::string_literal);
1723 } else if (II == Ident__FLT_EVAL_METHOD__) {
1724 // __FLT_EVAL_METHOD__ is set to the default value.
1725 OS << getTUFPEvalMethod();
1726 // __FLT_EVAL_METHOD__ expands to a simple numeric value.
1727 Tok.setKind(tok::numeric_constant);
1728 if (getLastFPEvalPragmaLocation().isValid()) {
1729 // The program is ill-formed. The value of __FLT_EVAL_METHOD__ is altered
1730 // by the pragma.
1731 Diag(Tok, diag::err_illegal_use_of_flt_eval_macro);
1732 Diag(getLastFPEvalPragmaLocation(), diag::note_pragma_entered_here);
1733 }
1734 } else if (II == Ident__COUNTER__) {
1736 getLangOpts().C2y ? diag::warn_counter : diag::ext_counter);
1737 // __COUNTER__ expands to a simple numeric value that must be less than
1738 // 2147483647.
1739 constexpr uint32_t MaxPosValue = std::numeric_limits<int32_t>::max();
1740 if (CounterValue > MaxPosValue) {
1741 Diag(Tok.getLocation(), diag::err_counter_overflow);
1742 // Retain the maximal value so we don't issue conversion-related
1743 // diagnostics by overflowing into a long long. While this does produce
1744 // a duplicate value, there's no way to ignore this error so there's no
1745 // translation anyway.
1746 CounterValue = MaxPosValue;
1747 }
1748 OS << CounterValue++;
1749 Tok.setKind(tok::numeric_constant);
1750 } else if (II == Ident__has_feature) {
1751 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1752 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1753 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1754 diag::err_feature_check_malformed);
1755 return II && HasFeature(*this, II->getName());
1756 });
1757 } else if (II == Ident__has_extension) {
1758 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1759 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1760 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1761 diag::err_feature_check_malformed);
1762 return II && HasExtension(*this, II->getName());
1763 });
1764 } else if (II == Ident__has_builtin) {
1766 OS, Tok, II, *this, false,
1767 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1768 IdentifierInfo *II = ExpectFeatureIdentifierInfo(
1769 Tok, *this, diag::err_feature_check_malformed);
1770 if (!II)
1771 return false;
1772 unsigned BuiltinID = II->getBuiltinID();
1773 if (BuiltinID != 0) {
1774 switch (II->getBuiltinID()) {
1775 case Builtin::BI__builtin_cpu_is:
1776 return getTargetInfo().supportsCpuIs();
1777 case Builtin::BI__builtin_cpu_init:
1778 return getTargetInfo().supportsCpuInit();
1779 case Builtin::BI__builtin_cpu_supports:
1781 case Builtin::BI__builtin_operator_new:
1782 case Builtin::BI__builtin_operator_delete:
1783 // denotes date of behavior change to support calling arbitrary
1784 // usual allocation and deallocation functions. Required by libc++
1785 return 201802;
1786 default:
1787 // __has_builtin should return false for aux builtins.
1788 if (getBuiltinInfo().isAuxBuiltinID(BuiltinID))
1789 return false;
1791 getBuiltinInfo().getRequiredFeatures(BuiltinID),
1792 getTargetInfo().getTargetOpts().FeatureMap);
1793 }
1794 return true;
1795 } else if (IsBuiltinTrait(Tok)) {
1796 return true;
1797 } else if (II->getTokenID() != tok::identifier &&
1798 II->getName().starts_with("__builtin_")) {
1799 return true;
1800 } else {
1801 return llvm::StringSwitch<bool>(II->getName())
1802 // Report builtin templates as being builtins.
1803#define BuiltinTemplate(BTName) .Case(#BTName, getLangOpts().CPlusPlus)
1804#include "clang/Basic/BuiltinTemplates.inc"
1805 // Likewise for some builtin preprocessor macros.
1806 // FIXME: This is inconsistent; we usually suggest detecting
1807 // builtin macros via #ifdef. Don't add more cases here.
1808 .Case("__is_target_arch", true)
1809 .Case("__is_target_vendor", true)
1810 .Case("__is_target_os", true)
1811 .Case("__is_target_environment", true)
1812 .Case("__is_target_variant_os", true)
1813 .Case("__is_target_variant_environment", true)
1814 .Default(false);
1815 }
1816 });
1817 } else if (II == Ident__has_constexpr_builtin) {
1819 OS, Tok, II, *this, false,
1820 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1821 IdentifierInfo *II = ExpectFeatureIdentifierInfo(
1822 Tok, *this, diag::err_feature_check_malformed);
1823 if (!II)
1824 return false;
1825 unsigned BuiltinOp = II->getBuiltinID();
1826 return BuiltinOp != 0 &&
1827 this->getBuiltinInfo().isConstantEvaluated(BuiltinOp);
1828 });
1829 } else if (II == Ident__is_identifier) {
1830 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1831 [](Token &Tok, bool &HasLexedNextToken) -> int {
1832 return Tok.is(tok::identifier);
1833 });
1834 } else if (II == Ident__has_attribute) {
1835 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,
1836 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1837 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1838 diag::err_feature_check_malformed);
1840 II, getTargetInfo(), getLangOpts())
1841 : 0;
1842 });
1843 } else if (II == Ident__has_declspec) {
1844 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,
1845 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1846 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1847 diag::err_feature_check_malformed);
1848 if (II) {
1849 const LangOptions &LangOpts = getLangOpts();
1850 return LangOpts.DeclSpecKeyword &&
1852 II, getTargetInfo(), LangOpts);
1853 }
1854
1855 return false;
1856 });
1857 } else if (II == Ident__has_cpp_attribute ||
1858 II == Ident__has_c_attribute) {
1859 bool IsCXX = II == Ident__has_cpp_attribute;
1860 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,
1861 [&](Token &Tok, bool &HasLexedNextToken) -> int {
1862 IdentifierInfo *ScopeII = nullptr;
1863 IdentifierInfo *II = ExpectFeatureIdentifierInfo(
1864 Tok, *this, diag::err_feature_check_malformed);
1865 if (!II)
1866 return false;
1867
1868 // It is possible to receive a scope token. Read the "::", if it is
1869 // available, and the subsequent identifier.
1871 if (Tok.isNot(tok::coloncolon))
1872 HasLexedNextToken = true;
1873 else {
1874 ScopeII = II;
1875 // Lex an expanded token for the attribute name.
1876 Lex(Tok);
1877 II = ExpectFeatureIdentifierInfo(Tok, *this,
1878 diag::err_feature_check_malformed);
1879 }
1880
1884 return II ? hasAttribute(Syntax, ScopeII, II, getTargetInfo(),
1885 getLangOpts())
1886 : 0;
1887 });
1888 } else if (II == Ident__has_include ||
1889 II == Ident__has_include_next) {
1890 // The argument to these two builtins should be a parenthesized
1891 // file name string literal using angle brackets (<>) or
1892 // double-quotes ("").
1893 bool Value;
1894 if (II == Ident__has_include)
1895 Value = EvaluateHasInclude(Tok, II);
1896 else
1897 Value = EvaluateHasIncludeNext(Tok, II);
1898
1899 if (Tok.isNot(tok::r_paren))
1900 return;
1901 OS << (int)Value;
1902 Tok.setKind(tok::numeric_constant);
1903 } else if (II == Ident__has_embed) {
1904 // The argument to these two builtins should be a parenthesized
1905 // file name string literal using angle brackets (<>) or
1906 // double-quotes (""), optionally followed by a series of
1907 // arguments similar to form like attributes.
1908 EmbedResult Value = EvaluateHasEmbed(Tok, II);
1910 return;
1911
1912 Tok.setKind(tok::numeric_constant);
1913 OS << static_cast<int>(Value);
1914 } else if (II == Ident__has_warning) {
1915 // The argument should be a parenthesized string literal.
1916 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1917 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1918 std::string WarningName;
1919 SourceLocation StrStartLoc = Tok.getLocation();
1920
1921 HasLexedNextToken = Tok.is(tok::string_literal);
1922 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1923 /*AllowMacroExpansion=*/false))
1924 return false;
1925
1926 // FIXME: Should we accept "-R..." flags here, or should that be
1927 // handled by a separate __has_remark?
1928 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1929 WarningName[1] != 'W') {
1930 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1931 return false;
1932 }
1933
1934 // Finally, check if the warning flags maps to a diagnostic group.
1935 // We construct a SmallVector here to talk to getDiagnosticIDs().
1936 // Although we don't use the result, this isn't a hot path, and not
1937 // worth special casing.
1938 SmallVector<diag::kind, 10> Diags;
1939 return !getDiagnostics().getDiagnosticIDs()->
1941 WarningName.substr(2), Diags);
1942 });
1943 } else if (II == Ident__building_module) {
1944 // The argument to this builtin should be an identifier. The
1945 // builtin evaluates to 1 when that identifier names the module we are
1946 // currently building.
1947 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1948 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1949 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1950 diag::err_expected_id_building_module);
1951 return getLangOpts().isCompilingModule() && II &&
1952 (II->getName() == getLangOpts().CurrentModule);
1953 });
1954 } else if (II == Ident__MODULE__) {
1955 // The current module as an identifier.
1957 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1958 Tok.setIdentifierInfo(ModuleII);
1959 Tok.setKind(ModuleII->getTokenID());
1960 } else if (II == Ident__identifier) {
1961 SourceLocation Loc = Tok.getLocation();
1962
1963 // We're expecting '__identifier' '(' identifier ')'. Try to recover
1964 // if the parens are missing.
1966 if (Tok.isNot(tok::l_paren)) {
1967 // No '(', use end of last token.
1968 Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
1969 << II << tok::l_paren;
1970 // If the next token isn't valid as our argument, we can't recover.
1972 Tok.setKind(tok::identifier);
1973 return;
1974 }
1975
1976 SourceLocation LParenLoc = Tok.getLocation();
1978
1980 Tok.setKind(tok::identifier);
1981 else if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) {
1982 StringLiteralParser Literal(Tok, *this,
1984 if (Literal.hadError)
1985 return;
1986
1988 Tok.setKind(tok::identifier);
1989 } else {
1990 Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
1991 << Tok.getKind();
1992 // Don't walk past anything that's not a real token.
1993 if (Tok.isOneOf(tok::eof, tok::eod) || Tok.isAnnotation())
1994 return;
1995 }
1996
1997 // Discard the ')', preserving 'Tok' as our result.
1998 Token RParen;
1999 LexNonComment(RParen);
2000 if (RParen.isNot(tok::r_paren)) {
2001 Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
2002 << Tok.getKind() << tok::r_paren;
2003 Diag(LParenLoc, diag::note_matching) << tok::l_paren;
2004 }
2005 return;
2006 } else if (II == Ident__is_target_arch) {
2008 OS, Tok, II, *this, false,
2009 [this](Token &Tok, bool &HasLexedNextToken) -> int {
2010 IdentifierInfo *II = ExpectFeatureIdentifierInfo(
2011 Tok, *this, diag::err_feature_check_malformed);
2012 return II && isTargetArch(getTargetInfo(), II);
2013 });
2014 } else if (II == Ident__is_target_vendor) {
2016 OS, Tok, II, *this, false,
2017 [this](Token &Tok, bool &HasLexedNextToken) -> int {
2018 IdentifierInfo *II = ExpectFeatureIdentifierInfo(
2019 Tok, *this, diag::err_feature_check_malformed);
2020 return II && isTargetVendor(getTargetInfo(), II);
2021 });
2022 } else if (II == Ident__is_target_os) {
2024 OS, Tok, II, *this, false,
2025 [this](Token &Tok, bool &HasLexedNextToken) -> int {
2026 IdentifierInfo *II = ExpectFeatureIdentifierInfo(
2027 Tok, *this, diag::err_feature_check_malformed);
2028 return II && isTargetOS(getTargetInfo(), II);
2029 });
2030 } else if (II == Ident__is_target_environment) {
2032 OS, Tok, II, *this, false,
2033 [this](Token &Tok, bool &HasLexedNextToken) -> int {
2034 IdentifierInfo *II = ExpectFeatureIdentifierInfo(
2035 Tok, *this, diag::err_feature_check_malformed);
2036 return II && isTargetEnvironment(getTargetInfo(), II);
2037 });
2038 } else if (II == Ident__is_target_variant_os) {
2040 OS, Tok, II, *this, false,
2041 [this](Token &Tok, bool &HasLexedNextToken) -> int {
2042 IdentifierInfo *II = ExpectFeatureIdentifierInfo(
2043 Tok, *this, diag::err_feature_check_malformed);
2044 return II && isTargetVariantOS(getTargetInfo(), II);
2045 });
2046 } else if (II == Ident__is_target_variant_environment) {
2048 OS, Tok, II, *this, false,
2049 [this](Token &Tok, bool &HasLexedNextToken) -> int {
2050 IdentifierInfo *II = ExpectFeatureIdentifierInfo(
2051 Tok, *this, diag::err_feature_check_malformed);
2052 return II && isTargetVariantEnvironment(getTargetInfo(), II);
2053 });
2054 } else {
2055 llvm_unreachable("Unknown identifier!");
2056 }
2058 Tok.setFlagValue(Token::StartOfLine, IsAtStartOfLine);
2059 Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
2061}
2062
2064 // If the 'used' status changed, and the macro requires 'unused' warning,
2065 // remove its SourceLocation from the warn-for-unused-macro locations.
2066 if (MI->isWarnIfUnused() && !MI->isUsed())
2067 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2068 MI->setIsUsed(true);
2069}
2070
2072 const LangOptions &LangOpts,
2073 const TargetInfo &TI) {
2074 LangOpts.remapPathPrefix(Path);
2075 if (LangOpts.UseTargetPathSeparator) {
2076 if (TI.getTriple().isOSWindows())
2077 llvm::sys::path::remove_dots(Path, false,
2078 llvm::sys::path::Style::windows_backslash);
2079 else
2080 llvm::sys::path::remove_dots(Path, false, llvm::sys::path::Style::posix);
2081 }
2082}
2083
2085 const PresumedLoc &PLoc,
2086 const LangOptions &LangOpts,
2087 const TargetInfo &TI) {
2088 // Try to get the last path component, failing that return the original
2089 // presumed location.
2090 StringRef PLFileName = llvm::sys::path::filename(PLoc.getFilename());
2091 if (PLFileName.empty())
2092 PLFileName = PLoc.getFilename();
2093 FileName.append(PLFileName.begin(), PLFileName.end());
2094 processPathForFileMacro(FileName, LangOpts, TI);
2095}
Defines enum values for all the target-independent builtin functions.
static bool getDiagnosticsInGroup(diag::Flavor Flavor, const WarningOption *Group, SmallVectorImpl< diag::kind > &Diags, diag::CustomDiagInfo *CustomDiagInfo)
Return true if any diagnostics were found in this group, even if they were filtered out due to having...
Token Tok
The Token.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::FileType FileType
Definition MachO.h:46
Defines the clang::MacroInfo and clang::MacroDirective classes.
static bool HasExtension(const Preprocessor &PP, StringRef Extension)
HasExtension - Return true if we recognize and implement the feature specified by the identifier,...
static bool CheckMatchedBrackets(const SmallVectorImpl< Token > &Tokens)
CheckMatchedBrackets - Returns true if the braces and parentheses in the token vector are properly ne...
static bool EvaluateHasIncludeCommon(Token &Tok, IdentifierInfo *II, Preprocessor &PP, ConstSearchDirIterator LookupFrom, const FileEntry *LookupFromFile)
EvaluateHasIncludeCommon - Process a '__has_include("path")' or '__has_include_next("path")' expressi...
static bool GenerateNewArgTokens(Preprocessor &PP, SmallVectorImpl< Token > &OldTokens, SmallVectorImpl< Token > &NewTokens, unsigned &NumArgs, SmallVectorImpl< SourceRange > &ParenHints, SmallVectorImpl< SourceRange > &InitLists)
GenerateNewArgTokens - Returns true if OldTokens can be converted to a new vector of tokens in NewTok...
static bool isTargetVariantOS(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_variant_os builtin macro.
static bool isTrivialSingleTokenExpansion(const MacroInfo *MI, const IdentifierInfo *MacroIdent, Preprocessor &PP)
isTrivialSingleTokenExpansion - Return true if MI, which has a single token in its expansion,...
static bool isTargetArch(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_arch builtin macro.
static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc, Preprocessor &PP)
ComputeDATE_TIME - Compute the current time, enter it into the specified scratch buffer,...
static bool isTargetVariantEnvironment(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_variant_environment builtin macro.
static bool isTargetEnvironment(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_environment builtin macro.
static bool IsBuiltinTrait(Token &Tok)
static bool isTargetOS(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_os builtin macro.
static bool isTargetVendor(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_vendor builtin macro.
static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream &OS, Token &Tok, IdentifierInfo *II, Preprocessor &PP, bool ExpandArgs, llvm::function_ref< int(Token &Tok, bool &HasLexedNextTok)> Op)
Process single-argument builtin feature-like macros that return integer values.
static bool HasFeature(const Preprocessor &PP, StringRef Feature)
HasFeature - Return true if we recognize and implement the feature specified by the identifier as a s...
static IdentifierInfo * ExpectFeatureIdentifierInfo(Token &Tok, Preprocessor &PP, signed DiagID)
Helper function to return the IdentifierInfo structure of a Token or generate a diagnostic if none av...
Defines the PreprocessorLexer interface.
Defines the clang::Preprocessor interface.
Defines the clang::SourceLocation class and associated facilities.
Syntax
The style used to specify an attribute.
bool isConstantEvaluated(unsigned ID) const
Return true if this function can be constant evaluated by Clang frontend.
Definition Builtins.h:459
diag::Severity getExtensionHandlingBehavior() const
Definition Diagnostic.h:818
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:597
virtual void updateOutOfDateIdentifier(const IdentifierInfo &II)=0
Update an out-of-date identifier.
off_t getSize() const
Definition FileEntry.h:346
Cached information about one file (either on disk or in the virtual file system).
Definition FileEntry.h:302
time_t getModificationTime() const
Definition FileEntry.h:333
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
SrcMgr::CharacteristicKind getFileDirFlavor(FileEntryRef File)
Return whether the specified file is a normal header, a system header, or a C++ friendly system heade...
One of these records is kept for each identifier that is lexed.
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
bool hadMacroDefinition() const
Returns true if this identifier was #defined to some value at any moment.
bool isFromAST() const
Return true if the identifier in its current state was loaded from an AST file.
const char * getNameStart() const
Return the beginning of the actual null-terminated string for this identifier.
void setHasMacroDefinition(bool Val)
bool isOutOfDate() const
Determine whether the information for this identifier is out of date with respect to the external sou...
void setChangedSinceDeserialization()
Note that this identifier has changed since it was loaded from an AST file.
StringRef getName() const
Return the actual identifier string.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
bool isCompilingModule() const
Are we compiling a module?
std::string CurrentModule
The name of the current module, of which the main source file is a part.
static std::string Stringify(StringRef Str, bool Charify=false)
Stringify - Convert the specified string into a C string by i) escaping '\' and " characters and ii) ...
Definition Lexer.cpp:319
MacroArgs - An instance of this class captures information about the formal arguments specified to a ...
Definition MacroArgs.h:30
static MacroArgs * create(const MacroInfo *MI, ArrayRef< Token > UnexpArgTokens, bool VarargsElided, Preprocessor &PP)
MacroArgs ctor function - Create a new MacroArgs object with the specified macro and argument info.
Definition MacroArgs.cpp:23
void destroy(Preprocessor &PP)
destroy - Destroy and deallocate the memory for this object.
Definition MacroArgs.cpp:77
A description of the current definition of a macro.
Definition MacroInfo.h:590
MacroInfo * getMacroInfo() const
Get the MacroInfo that should be used for this definition.
Definition MacroInfo.h:606
bool isAmbiguous() const
true if the definition is ambiguous, false otherwise.
Definition MacroInfo.h:615
void forAllDefinitions(Fn F) const
Definition MacroInfo.h:626
Encapsulates changes to the "macros namespace" (the location where the macro name became active,...
Definition MacroInfo.h:313
const MacroDirective * getPrevious() const
Get previous definition of the macro with the same name.
Definition MacroInfo.h:354
void setPrevious(MacroDirective *Prev)
Set previous definition of the macro with the same name.
Definition MacroInfo.h:351
bool isDefined() const
Definition MacroInfo.h:410
Encapsulates the data about a macro definition (e.g.
Definition MacroInfo.h:39
bool isIdenticalTo(const MacroInfo &Other, Preprocessor &PP, bool Syntactically) const
Return true if the specified macro definition is equal to this macro in spelling, arguments,...
Definition MacroInfo.cpp:89
bool isUsed() const
Return false if this macro is defined in the main file and has not yet been used.
Definition MacroInfo.h:224
bool isFunctionLike() const
Definition MacroInfo.h:201
ArrayRef< const IdentifierInfo * > params() const
Definition MacroInfo.h:185
unsigned getNumTokens() const
Return the number of tokens that this macro expands to.
Definition MacroInfo.h:235
void dump() const
unsigned getNumParams() const
Definition MacroInfo.h:184
const Token & getReplacementToken(unsigned Tok) const
Definition MacroInfo.h:237
bool isBuiltinMacro() const
Return true if this macro requires processing before expansion.
Definition MacroInfo.h:217
SourceLocation getDefinitionLoc() const
Return the location that the macro was defined at.
Definition MacroInfo.h:125
bool isVariadic() const
Definition MacroInfo.h:209
bool hasCommaPasting() const
Definition MacroInfo.h:219
bool isObjectLike() const
Definition MacroInfo.h:202
bool isWarnIfUnused() const
Return true if we should emit a warning if the macro is unused.
Definition MacroInfo.h:232
bool isEnabled() const
Return true if this macro is enabled.
Definition MacroInfo.h:281
void setIsUsed(bool Val)
Set the value of the IsUsed flag.
Definition MacroInfo.h:154
Represents a macro directive exported by a module.
Definition MacroInfo.h:514
static ModuleMacro * create(Preprocessor &PP, Module *OwningModule, const IdentifierInfo *II, MacroInfo *Macro, ArrayRef< ModuleMacro * > Overrides)
void Profile(llvm::FoldingSetNodeID &ID) const
Definition MacroInfo.h:545
A header that is known to reside within a given module, whether it was included or excluded.
Definition ModuleMap.h:158
Describes a module or submodule.
Definition Module.h:144
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition PPCallbacks.h:37
std::optional< uint64_t > SourceDateEpoch
If set, the UNIX timestamp specified by SOURCE_DATE_EPOCH.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
SourceLocation getLastFPEvalPragmaLocation() const
bool FinishLexStringLiteral(Token &Result, std::string &String, const char *DiagnosticTag, bool AllowMacroExpansion)
Complete the lexing of a string literal where the first token has already been lexed (see LexStringLi...
void dumpMacroInfo(const IdentifierInfo *II)
ModuleMacro * addModuleMacro(Module *Mod, IdentifierInfo *II, MacroInfo *Macro, ArrayRef< ModuleMacro * > Overrides, bool &IsNew)
Register an exported macro for a module and identifier.
void setLoadedMacroDirective(IdentifierInfo *II, MacroDirective *ED, MacroDirective *MD)
Set a MacroDirective that was loaded from a PCH file.
PPCallbacks * getPPCallbacks() const
SourceRange DiscardUntilEndOfDirective(SmallVectorImpl< Token > *DiscardedToks=nullptr)
Read and discard all tokens remaining on the current line until the tok::eod token is found.
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
void CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart=SourceLocation(), SourceLocation ExpansionLocEnd=SourceLocation())
Plop the specified string into a scratch buffer and set the specified token's location and length to ...
void markMacroAsUsed(MacroInfo *MI)
A macro is used, update information about macros that need unused warnings.
MacroDirective * getLocalMacroDirectiveHistory(const IdentifierInfo *II) const
Given an identifier, return the latest non-imported macro directive for that identifier.
friend class MacroArgs
void Lex(Token &Result)
Lex the next token for this preprocessor.
bool isParsingIfOrElifDirective() const
True if we are currently preprocessing a if or elif directive.
void LexNonComment(Token &Result)
Lex a token.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Char) const
Given a location that specifies the start of a token, return a new location that specifies a characte...
OptionalFileEntryRef LookupEmbedFile(StringRef Filename, bool isAngled, bool OpenFile)
Given a "Filename" or <Filename> reference, look up the indicated embed resource.
static void processPathToFileName(SmallVectorImpl< char > &FileName, const PresumedLoc &PLoc, const LangOptions &LangOpts, const TargetInfo &TI)
const TargetInfo & getTargetInfo() const
bool LexHeaderName(Token &Result, bool AllowMacroExpansion=true)
Lex a token, forming a header-name token if possible.
void LexUnexpandedToken(Token &Result)
Just like Lex, but disables macro expansion of identifier tokens.
ModuleMacro * getModuleMacro(Module *Mod, const IdentifierInfo *II)
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
bool GetIncludeFilenameSpelling(SourceLocation Loc, StringRef &Buffer)
Turn the specified lexer token into a fully checked and spelled filename, e.g.
PreprocessorLexer * getCurrentFileLexer() const
Return the current file lexer being lexed from.
HeaderSearch & getHeaderSearchInfo() const
void emitMacroExpansionWarnings(const Token &Identifier, bool IsIfnDef=false) const
ExternalPreprocessorSource * getExternalSource() const
OptionalFileEntryRef LookupFile(SourceLocation FilenameLoc, StringRef Filename, bool isAngled, ConstSearchDirIterator FromDir, const FileEntry *FromFile, ConstSearchDirIterator *CurDir, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool *IsFrameworkFound, bool SkipCache=false, bool OpenFile=true, bool CacheFailures=true)
Given a "foo" or <foo> reference, look up the indicated file.
Builtin::Context & getBuiltinInfo()
const PreprocessorOptions & getPreprocessorOpts() const
Retrieve the preprocessor options used to initialize this preprocessor.
LangOptions::FPEvalMethodKind getTUFPEvalMethod() const
const LangOptions & getLangOpts() const
static void processPathForFileMacro(SmallVectorImpl< char > &Path, const LangOptions &LangOpts, const TargetInfo &TI)
DiagnosticsEngine & getDiagnostics() const
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
std::optional< LexEmbedParametersResult > LexEmbedParameters(Token &Current, bool ForHasEmbed)
Lex the parameters for an embed directive, returns nullopt on error.
void EnterMacro(Token &Tok, SourceLocation ILEnd, MacroInfo *Macro, MacroArgs *Args)
Add a Macro to the top of the include stack and start lexing tokens from it instead of the current bu...
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
void appendMacroDirective(IdentifierInfo *II, MacroDirective *MD)
Add a directive to the macro directive history for this identifier.
Represents an unpacked "presumed" location which can be presented to the user.
const char * getFilename() const
Return the presumed filename of this location.
unsigned getLine() const
Return the presumed line number of this location.
bool isInvalid() const
Return true if this object is invalid or uninitialized.
SourceLocation getIncludeLoc() const
Return the presumed include location of this location.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
Exposes information about the current target.
Definition TargetInfo.h:226
virtual bool supportsCpuSupports() const
virtual bool supportsCpuInit() const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
const llvm::Triple * getDarwinTargetVariantTriple() const
Returns the darwin target variant triple, the variant of the deployment target for which the code is ...
virtual bool supportsCpuIs() const
TokenLexer - This implements a lexer that returns tokens from a macro body or token stream instead of...
Definition TokenLexer.h:30
Token - This structure provides full information about a lexed token.
Definition Token.h:36
IdentifierInfo * getIdentifierInfo() const
Definition Token.h:197
unsigned getFlags() const
Return the internal represtation of the flags.
Definition Token.h:272
void clearFlag(TokenFlags Flag)
Unset the specified flag.
Definition Token.h:264
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition Token.h:142
unsigned getLength() const
Definition Token.h:145
void setLength(unsigned Len)
Definition Token.h:151
void setKind(tok::TokenKind K)
Definition Token.h:100
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition Token.h:104
tok::TokenKind getKind() const
Definition Token.h:99
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition Token.h:286
bool isOneOf(Ts... Ks) const
Definition Token.h:105
@ DisableExpand
Definition Token.h:79
@ IgnoredComma
Definition Token.h:84
@ LeadingEmptyMacro
Definition Token.h:81
@ LeadingSpace
Definition Token.h:77
@ StartOfLine
Definition Token.h:75
@ NeedsCleaning
Definition Token.h:80
bool hasLeadingSpace() const
Return true if this token has whitespace before it.
Definition Token.h:294
void setLocation(SourceLocation L)
Definition Token.h:150
bool isNot(tok::TokenKind K) const
Definition Token.h:111
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition Token.h:131
bool hasUDSuffix() const
Return true if this token is a string or character literal which has a ud-suffix.
Definition Token.h:321
void startToken()
Reset all flags to cleared.
Definition Token.h:187
void setIdentifierInfo(IdentifierInfo *II)
Definition Token.h:206
void setFlagValue(TokenFlags Flag, bool Val)
Set a flag to either true or false.
Definition Token.h:277
void setFlag(TokenFlags Flag)
Set the specified flag.
Definition Token.h:254
unsigned getGeneration() const
Get the current visibility generation.
Definition Module.h:887
Defines the clang::TargetInfo interface.
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
@ WarningOrError
A diagnostic that indicates a problem or potential problem.
@ Error
Present this diagnostic as an error.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:208
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
int hasAttribute(AttributeCommonInfo::Syntax Syntax, llvm::StringRef ScopeName, llvm::StringRef AttrName, const TargetInfo &Target, const LangOptions &LangOpts, bool CheckPlugins)
Return the version number associated with the attribute if we recognize and implement the attribute s...
detail::SearchDirIteratorImpl< true > ConstSearchDirIterator
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Result
The result type of a method or function.
Definition TypeBase.h:905
@ Braces
New-expression has a C++11 list-initializer.
Definition ExprCXX.h:2249
unsigned int uint32_t