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