clang 24.0.0git
SemaStmtAsm.cpp
Go to the documentation of this file.
1//===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===//
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 semantic analysis for inline asm statements.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ExprCXX.h"
15#include "clang/AST/TypeLoc.h"
21#include "clang/Sema/Lookup.h"
23#include "clang/Sema/Scope.h"
25#include "clang/Sema/SemaBPF.h"
26#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/StringExtras.h"
28#include "llvm/ADT/StringSet.h"
29#include "llvm/MC/MCParser/MCAsmParser.h"
30#include "llvm/Support/TextEncoding.h"
31#include <optional>
32using namespace clang;
33using namespace sema;
34
35/// Remove the upper-level LValueToRValue cast from an expression.
37 Expr *Parent = E;
38 Expr *ExprUnderCast = nullptr;
39 SmallVector<Expr *, 8> ParentsToUpdate;
40
41 while (true) {
42 ParentsToUpdate.push_back(Parent);
43 if (auto *ParenE = dyn_cast<ParenExpr>(Parent)) {
44 Parent = ParenE->getSubExpr();
45 continue;
46 }
47
48 Expr *Child = nullptr;
49 CastExpr *ParentCast = dyn_cast<CastExpr>(Parent);
50 if (ParentCast)
51 Child = ParentCast->getSubExpr();
52 else
53 return;
54
55 if (auto *CastE = dyn_cast<CastExpr>(Child))
56 if (CastE->getCastKind() == CK_LValueToRValue) {
57 ExprUnderCast = CastE->getSubExpr();
58 // LValueToRValue cast inside GCCAsmStmt requires an explicit cast.
59 ParentCast->setSubExpr(ExprUnderCast);
60 break;
61 }
62 Parent = Child;
63 }
64
65 // Update parent expressions to have same ValueType as the underlying.
66 assert(ExprUnderCast &&
67 "Should be reachable only if LValueToRValue cast was found!");
68 auto ValueKind = ExprUnderCast->getValueKind();
69 for (Expr *E : ParentsToUpdate)
70 E->setValueKind(ValueKind);
71}
72
73/// Emit a warning about usage of "noop"-like casts for lvalues (GNU extension)
74/// and fix the argument with removing LValueToRValue cast from the expression.
75static void emitAndFixInvalidAsmCastLValue(const Expr *LVal, Expr *BadArgument,
76 Sema &S) {
77 S.Diag(LVal->getBeginLoc(), diag::warn_invalid_asm_cast_lvalue)
78 << BadArgument->getSourceRange();
79 removeLValueToRValueCast(BadArgument);
80}
81
82/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
83/// ignore "noop" casts in places where an lvalue is required by an inline asm.
84/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
85/// provide a strong guidance to not use it.
86///
87/// This method checks to see if the argument is an acceptable l-value and
88/// returns false if it is a case we can handle.
89static bool CheckAsmLValue(Expr *E, Sema &S) {
90 // Type dependent expressions will be checked during instantiation.
91 if (E->isTypeDependent())
92 return false;
93
94 if (E->isLValue())
95 return false; // Cool, this is an lvalue.
96
97 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
98 // are supposed to allow.
99 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
100 if (E != E2 && E2->isLValue()) {
102 // Accept, even if we emitted an error diagnostic.
103 return false;
104 }
105
106 // None of the above, just randomly invalid non-lvalue.
107 return true;
108}
109
110/// isOperandMentioned - Return true if the specified operand # is mentioned
111/// anywhere in the decomposed asm string.
112static bool
113isOperandMentioned(unsigned OpNo,
115 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
116 const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
117 if (!Piece.isOperand())
118 continue;
119
120 // If this is a reference to the input and if the input was the smaller
121 // one, then we have to reject this asm.
122 if (Piece.getOperandNo() == OpNo)
123 return true;
124 }
125 return false;
126}
127
128static bool CheckNakedParmReference(Expr *E, Sema &S) {
129 FunctionDecl *Func = dyn_cast<FunctionDecl>(S.CurContext);
130 if (!Func)
131 return false;
132 if (!Func->hasAttr<NakedAttr>())
133 return false;
134
135 SmallVector<Expr*, 4> WorkList;
136 WorkList.push_back(E);
137 while (WorkList.size()) {
138 Expr *E = WorkList.pop_back_val();
139 if (isa<CXXThisExpr>(E)) {
140 S.Diag(E->getBeginLoc(), diag::err_asm_naked_this_ref);
141 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
142 return true;
143 }
144 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
145 if (isa<ParmVarDecl>(DRE->getDecl())) {
146 S.Diag(DRE->getBeginLoc(), diag::err_asm_naked_parm_ref);
147 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
148 return true;
149 }
150 }
151 for (Stmt *Child : E->children()) {
152 if (Expr *E = dyn_cast_or_null<Expr>(Child))
153 WorkList.push_back(E);
154 }
155 }
156 return false;
157}
158
159/// Returns true if given expression is not compatible with inline
160/// assembly's memory constraint; false otherwise.
163 bool is_input_expr) {
164 enum {
165 ExprBitfield = 0,
166 ExprVectorElt,
167 ExprGlobalRegVar,
168 ExprSafeType
169 } EType = ExprSafeType;
170
171 // Bitfields, vector elements and global register variables are not
172 // compatible.
173 if (E->refersToBitField())
174 EType = ExprBitfield;
175 else if (E->refersToVectorElement())
176 EType = ExprVectorElt;
177 else if (E->refersToGlobalRegisterVar())
178 EType = ExprGlobalRegVar;
179
180 if (EType != ExprSafeType) {
181 S.Diag(E->getBeginLoc(), diag::err_asm_non_addr_value_in_memory_constraint)
182 << EType << is_input_expr << Info.getConstraintStr()
183 << E->getSourceRange();
184 return true;
185 }
186
187 return false;
188}
189
190// Extracting the register name from the Expression value,
191// if there is no register name to extract, returns ""
192static StringRef extractRegisterName(const Expr *Expression,
193 const TargetInfo &Target) {
194 Expression = Expression->IgnoreImpCasts();
195 if (const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(Expression)) {
196 // Handle cases where the expression is a variable
197 const VarDecl *Variable = dyn_cast<VarDecl>(AsmDeclRef->getDecl());
198 if (Variable && Variable->getStorageClass() == SC_Register) {
199 if (AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>())
200 if (Target.isValidGCCRegisterName(Attr->getLabel()))
201 return Target.getNormalizedGCCRegisterName(Attr->getLabel(), true);
202 }
203 }
204 return "";
205}
206
207// Checks if there is a conflict between the input and output lists with the
208// clobbers list. If there's a conflict, returns the location of the
209// conflicted clobber, else returns nullptr
210static SourceLocation
212 Expr **Clobbers, int NumClobbers, unsigned NumLabels,
213 const TargetInfo &Target, ASTContext &Cont) {
214 llvm::StringSet<> InOutVars;
215 // Collect all the input and output registers from the extended asm
216 // statement in order to check for conflicts with the clobber list
217 for (unsigned int i = 0; i < Exprs.size() - NumLabels; ++i) {
218 std::string Constraint =
220 StringRef InOutReg = Target.getConstraintRegister(
221 Constraint, extractRegisterName(Exprs[i], Target));
222 if (InOutReg != "")
223 InOutVars.insert(InOutReg);
224 }
225 // Check for each item in the clobber list if it conflicts with the input
226 // or output
227 for (int i = 0; i < NumClobbers; ++i) {
228 std::string Clobber =
230 // We only check registers, therefore we don't check cc and memory
231 // clobbers
232 if (Clobber == "cc" || Clobber == "memory" || Clobber == "unwind")
233 continue;
234 Clobber = Target.getNormalizedGCCRegisterName(Clobber, true);
235 // Go over the output's registers we collected
236 if (InOutVars.count(Clobber))
237 return Clobbers[i]->getBeginLoc();
238 }
239 return SourceLocation();
240}
241
243 bool IsConstexpr) {
244 if (!Expr)
245 return ExprError();
246
247 if (auto *SL = dyn_cast<StringLiteral>(Expr)) {
248 assert(SL->isOrdinary());
249 if (ForAsmLabel && SL->getString().empty()) {
250 Diag(Expr->getBeginLoc(), diag::err_asm_operand_empty_string)
251 << SL->getSourceRange();
252 }
253
254 if (!IsConstexpr &&
255 PP.getTextEncoding().getzOSFromAsmLiteralEncodingConverter() !=
256 nullptr) {
257 SmallString<16> ConvertedAsm;
258 [[maybe_unused]] std::error_code EC =
259 PP.getTextEncoding().getzOSFromAsmLiteralEncodingConverter()->convert(
260 SL->getString(), ConvertedAsm);
261 assert(!EC && "This conversion should always succeed");
262 QualType StrTy = Context.getStringLiteralArrayType(Context.CharTy,
263 ConvertedAsm.size());
264 return StringLiteral::Create(Context, ConvertedAsm,
266 /*Pascal=*/false, StrTy, SL->getBeginLoc());
267 }
268 return SL;
269 }
271 return ExprError();
272 if (Expr->getDependence() != ExprDependence::None)
273 return Expr;
274 APValue V;
276 /*ErrorOnInvalid=*/true))
277 return ExprError();
278
279 if (ForAsmLabel && V.getArrayInitializedElts() == 0) {
280 Diag(Expr->getBeginLoc(), diag::err_asm_operand_empty_string);
281 }
282
283 // The evaluated string is in the literal encoding (-fexec-charset).
284 // Convert it back to UTF-8.
285 if (llvm::TextEncodingConverter *FromLiteral =
286 PP.getTextEncoding().getFromLiteralEncodingConverter()) {
287 std::string Raw = V.getCharArrayAsString();
288 SmallString<16> Converted;
289 if (std::error_code EC = FromLiteral->convert(Raw, Converted)) {
290 Diag(Expr->getBeginLoc(), diag::err_exec_charset_conversion_failed)
291 << EC.message() << /*from literal encoding to UTF-8*/ 2;
292 return ExprError();
293 }
294 llvm::APSInt Proto(Context.getTypeSize(Context.CharTy),
295 Context.CharTy->isUnsignedIntegerType());
296 V = APValue(APValue::UninitArray{}, Converted.size(), Converted.size());
297 for (unsigned I = 0; I < Converted.size(); ++I) {
298 Proto = static_cast<unsigned char>(Converted[I]);
299 V.getArrayInitializedElt(I) = APValue(Proto);
300 }
301 }
302
304}
305
307 bool IsVolatile, unsigned NumOutputs,
308 unsigned NumInputs, IdentifierInfo **Names,
309 MultiExprArg constraints, MultiExprArg Exprs,
310 Expr *asmString, MultiExprArg clobbers,
311 unsigned NumLabels,
312 SourceLocation RParenLoc) {
313 unsigned NumClobbers = clobbers.size();
314
315 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
316
317 FunctionDecl *FD = dyn_cast<FunctionDecl>(getCurLexicalContext());
318 llvm::StringMap<bool> FeatureMap;
319 Context.getFunctionFeatureMap(FeatureMap, FD);
320
321 auto CreateGCCAsmStmt = [&] {
322 return new (Context)
323 GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs,
324 Names, constraints.data(), Exprs.data(), asmString,
325 NumClobbers, clobbers.data(), NumLabels, RParenLoc);
326 };
327
328 if (asmString->getDependence() != ExprDependence::None ||
329 llvm::any_of(
330 constraints,
331 [](Expr *E) { return E->getDependence() != ExprDependence::None; }) ||
332 llvm::any_of(clobbers, [](Expr *E) {
333 return E->getDependence() != ExprDependence::None;
334 }))
335 return CreateGCCAsmStmt();
336
337 for (unsigned i = 0; i != NumOutputs; i++) {
338 Expr *Constraint = constraints[i];
339 StringRef OutputName;
340 if (Names[i])
341 OutputName = Names[i]->getName();
342
343 std::string ConstraintStr =
345
346 if (ConstraintStr.find('\0') != std::string::npos) {
347 Diag(Constraint->getBeginLoc(), diag::err_asm_constraint_embedded_null)
348 << /*output*/ 0;
349 return CreateGCCAsmStmt();
350 }
351
352 TargetInfo::ConstraintInfo Info(ConstraintStr, OutputName);
353 if (!Context.getTargetInfo().validateOutputConstraint(Info) &&
354 !(LangOpts.HIPStdPar && LangOpts.CUDAIsDevice)) {
355 targetDiag(Constraint->getBeginLoc(),
356 diag::err_asm_invalid_output_constraint)
357 << Info.getConstraintStr();
358 return CreateGCCAsmStmt();
359 }
360
361 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
362 if (ER.isInvalid())
363 return StmtError();
364 Exprs[i] = ER.get();
365
366 // Check that the output exprs are valid lvalues.
367 Expr *OutputExpr = Exprs[i];
368
369 // Referring to parameters is not allowed in naked functions.
370 if (CheckNakedParmReference(OutputExpr, *this))
371 return StmtError();
372
373 // Check that the output expression is compatible with memory constraint.
374 if (Info.allowsMemory() &&
375 checkExprMemoryConstraintCompat(*this, OutputExpr, Info, false))
376 return StmtError();
377
378 // Disallow bit-precise integer types, since the backends tend to have
379 // difficulties with abnormal sizes.
380 if (OutputExpr->getType()->isBitIntType())
381 return StmtError(
382 Diag(OutputExpr->getBeginLoc(), diag::err_asm_invalid_type)
383 << OutputExpr->getType() << 0 /*Input*/
384 << OutputExpr->getSourceRange());
385
386 OutputConstraintInfos.push_back(Info);
387
388 // If this is dependent, just continue.
389 if (OutputExpr->isTypeDependent())
390 continue;
391
393 OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr);
394 switch (IsLV) {
395 case Expr::MLV_Valid:
396 // Cool, this is an lvalue.
397 break;
399 // This is OK too.
400 break;
402 const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context);
403 emitAndFixInvalidAsmCastLValue(LVal, OutputExpr, *this);
404 // Accept, even if we emitted an error diagnostic.
405 break;
406 }
409 if (RequireCompleteType(OutputExpr->getBeginLoc(), Exprs[i]->getType(),
410 diag::err_dereference_incomplete_type))
411 return StmtError();
412 [[fallthrough]];
413 default:
414 return StmtError(Diag(OutputExpr->getBeginLoc(),
415 diag::err_asm_invalid_lvalue_in_output)
416 << OutputExpr->getSourceRange());
417 }
418
419 unsigned Size = Context.getTypeSize(OutputExpr->getType());
420 if (!Context.getTargetInfo().validateOutputSize(
421 FeatureMap,
423 Size)) {
424 targetDiag(OutputExpr->getBeginLoc(), diag::err_asm_invalid_output_size)
425 << Info.getConstraintStr();
426 return CreateGCCAsmStmt();
427 }
428 }
429
431
432 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
433 Expr *Constraint = constraints[i];
434
435 StringRef InputName;
436 if (Names[i])
437 InputName = Names[i]->getName();
438
439 std::string ConstraintStr =
441
442 if (ConstraintStr.find('\0') != std::string::npos) {
443 Diag(Constraint->getBeginLoc(), diag::err_asm_constraint_embedded_null)
444 << /*input*/ 1;
445 return CreateGCCAsmStmt();
446 }
447
448 TargetInfo::ConstraintInfo Info(ConstraintStr, InputName);
449 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos,
450 Info)) {
451 targetDiag(Constraint->getBeginLoc(),
452 diag::err_asm_invalid_input_constraint)
453 << Info.getConstraintStr();
454 return CreateGCCAsmStmt();
455 }
456
457 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
458 if (ER.isInvalid())
459 return StmtError();
460 Exprs[i] = ER.get();
461
462 Expr *InputExpr = Exprs[i];
463
464 if (InputExpr->getType()->isMemberPointerType())
465 return StmtError(Diag(InputExpr->getBeginLoc(),
466 diag::err_asm_pmf_through_constraint_not_permitted)
467 << InputExpr->getSourceRange());
468
469 // Referring to parameters is not allowed in naked functions.
470 if (CheckNakedParmReference(InputExpr, *this))
471 return StmtError();
472
473 // Check that the input expression is compatible with memory constraint.
474 if (Info.allowsMemory() &&
475 checkExprMemoryConstraintCompat(*this, InputExpr, Info, true))
476 return StmtError();
477
478 // Only allow void types for memory constraints.
479 if (Info.allowsMemory() && !Info.allowsRegister()) {
480 if (CheckAsmLValue(InputExpr, *this))
481 return StmtError(Diag(InputExpr->getBeginLoc(),
482 diag::err_asm_invalid_lvalue_in_input)
483 << Info.getConstraintStr()
484 << InputExpr->getSourceRange());
485 } else {
487 if (Result.isInvalid())
488 return StmtError();
489
490 InputExpr = Exprs[i] = Result.get();
491
492 if (!Info.allowsRegister() && !Info.allowsMemory())
493 InputExpr = Exprs[i] = BPF().checkAsmImmediateOperand(InputExpr);
494
495 if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
496 if (!InputExpr->isValueDependent()) {
497 Expr::EvalResult EVResult;
498 if (InputExpr->EvaluateAsRValue(EVResult, Context, true)) {
499 // For compatibility with GCC, we also allow pointers that would be
500 // integral constant expressions if they were cast to int.
501 llvm::APSInt IntResult;
502 if (EVResult.Val.toIntegralConstant(IntResult, InputExpr->getType(),
503 Context))
504 if (!Info.isValidAsmImmediate(IntResult))
505 return StmtError(
506 Diag(InputExpr->getBeginLoc(),
507 diag::err_invalid_asm_value_for_constraint)
508 << toString(IntResult, 10) << Info.getConstraintStr()
509 << InputExpr->getSourceRange());
510 }
511 }
512 }
513 }
514
515 if (Info.allowsRegister()) {
516 if (InputExpr->getType()->isVoidType()) {
517 return StmtError(
518 Diag(InputExpr->getBeginLoc(), diag::err_asm_invalid_type_in_input)
519 << InputExpr->getType() << Info.getConstraintStr()
520 << InputExpr->getSourceRange());
521 }
522 }
523
524 if (InputExpr->getType()->isBitIntType())
525 return StmtError(
526 Diag(InputExpr->getBeginLoc(), diag::err_asm_invalid_type)
527 << InputExpr->getType() << 1 /*Output*/
528 << InputExpr->getSourceRange());
529
530 InputConstraintInfos.push_back(Info);
531
532 const Type *Ty = Exprs[i]->getType().getTypePtr();
533 if (Ty->isDependentType())
534 continue;
535
536 if (!Ty->isVoidType() || !Info.allowsMemory())
537 if (RequireCompleteType(InputExpr->getBeginLoc(), Exprs[i]->getType(),
538 diag::err_dereference_incomplete_type))
539 return StmtError();
540
541 unsigned Size = Context.getTypeSize(Ty);
542 if (!Context.getTargetInfo().validateInputSize(FeatureMap, ConstraintStr,
543 Size))
544 return targetDiag(InputExpr->getBeginLoc(),
545 diag::err_asm_invalid_input_size)
546 << Info.getConstraintStr();
547 }
548
549 std::optional<SourceLocation> UnwindClobberLoc;
550
551 // Check that the clobbers are valid.
552 for (unsigned i = 0; i != NumClobbers; i++) {
553 Expr *ClobberExpr = clobbers[i];
554
555 std::string Clobber =
557
558 if (Clobber.find('\0') != std::string::npos) {
559 Diag(ClobberExpr->getBeginLoc(), diag::err_asm_constraint_embedded_null)
560 << /*clobber*/ 2;
561 return CreateGCCAsmStmt();
562 }
563
564 if (!Context.getTargetInfo().isValidClobber(Clobber)) {
565 targetDiag(ClobberExpr->getBeginLoc(),
566 diag::err_asm_unknown_register_name)
567 << Clobber;
568 return new (Context) GCCAsmStmt(
569 Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs, Names,
570 constraints.data(), Exprs.data(), asmString, NumClobbers,
571 clobbers.data(), NumLabels, RParenLoc);
572 }
573
574 if (Clobber == "unwind") {
575 UnwindClobberLoc = ClobberExpr->getBeginLoc();
576 }
577 }
578
579 // Using unwind clobber and asm-goto together is not supported right now.
580 if (UnwindClobberLoc && NumLabels > 0) {
581 targetDiag(*UnwindClobberLoc, diag::err_asm_unwind_and_goto);
582 return CreateGCCAsmStmt();
583 }
584
585 GCCAsmStmt *NS = CreateGCCAsmStmt();
586 // Validate the asm string, ensuring it makes sense given the operands we
587 // have.
588
589 auto GetLocation = [this](const Expr *Str, unsigned Offset) {
590 if (auto *SL = dyn_cast<StringLiteral>(Str))
591 return getLocationOfStringLiteralByte(SL, Offset);
592 return Str->getBeginLoc();
593 };
594
596 unsigned DiagOffs;
597 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
598 targetDiag(GetLocation(asmString, DiagOffs), DiagID)
599 << asmString->getSourceRange();
600 return NS;
601 }
602
603 // Validate constraints and modifiers.
604 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
605 GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
606 if (!Piece.isOperand()) continue;
607
608 // Look for the correct constraint index.
609 unsigned ConstraintIdx = Piece.getOperandNo();
610 unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs();
611 // Labels are the last in the Exprs list.
612 if (NS->isAsmGoto() && ConstraintIdx >= NumOperands)
613 continue;
614 // Look for the (ConstraintIdx - NumOperands + 1)th constraint with
615 // modifier '+'.
616 if (ConstraintIdx >= NumOperands) {
617 unsigned I = 0, E = NS->getNumOutputs();
618
619 for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I)
620 if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) {
621 ConstraintIdx = I;
622 break;
623 }
624
625 assert(I != E && "Invalid operand number should have been caught in "
626 " AnalyzeAsmString");
627 }
628
629 // Now that we have the right indexes go ahead and check.
630 Expr *Constraint = constraints[ConstraintIdx];
631 const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
632 if (Ty->isDependentType() || Ty->isIncompleteType())
633 continue;
634
635 unsigned Size = Context.getTypeSize(Ty);
636 std::string SuggestedModifier;
637 if (!Context.getTargetInfo().validateConstraintModifier(
639 Piece.getModifier(), Size, SuggestedModifier)) {
640 targetDiag(Exprs[ConstraintIdx]->getBeginLoc(),
641 diag::warn_asm_mismatched_size_modifier);
642
643 if (!SuggestedModifier.empty()) {
644 auto B = targetDiag(Piece.getRange().getBegin(),
645 diag::note_asm_missing_constraint_modifier)
646 << SuggestedModifier;
647 if (isa<StringLiteral>(Constraint)) {
648 SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
650 SuggestedModifier);
651 }
652 }
653 }
654 }
655
656 // Validate tied input operands for type mismatches.
657 unsigned NumAlternatives = ~0U;
658 for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
659 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
660 StringRef ConstraintStr = Info.getConstraintStr();
661 unsigned AltCount = ConstraintStr.count(',') + 1;
662 if (NumAlternatives == ~0U) {
663 NumAlternatives = AltCount;
664 } else if (NumAlternatives != AltCount) {
665 targetDiag(NS->getOutputExpr(i)->getBeginLoc(),
666 diag::err_asm_unexpected_constraint_alternatives)
667 << NumAlternatives << AltCount;
668 return NS;
669 }
670 }
671 SmallVector<size_t, 4> InputMatchedToOutput(OutputConstraintInfos.size(),
672 ~0U);
673 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
674 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
675 StringRef ConstraintStr = Info.getConstraintStr();
676 unsigned AltCount = ConstraintStr.count(',') + 1;
677 if (NumAlternatives == ~0U) {
678 NumAlternatives = AltCount;
679 } else if (NumAlternatives != AltCount) {
680 targetDiag(NS->getInputExpr(i)->getBeginLoc(),
681 diag::err_asm_unexpected_constraint_alternatives)
682 << NumAlternatives << AltCount;
683 return NS;
684 }
685
686 // If this is a tied constraint, verify that the output and input have
687 // either exactly the same type, or that they are int/ptr operands with the
688 // same size (int/long, int*/long, are ok etc).
689 if (!Info.hasTiedOperand()) continue;
690
691 unsigned TiedTo = Info.getTiedOperand();
692 unsigned InputOpNo = i+NumOutputs;
693 Expr *OutputExpr = Exprs[TiedTo];
694 Expr *InputExpr = Exprs[InputOpNo];
695
696 // Make sure no more than one input constraint matches each output.
697 assert(TiedTo < InputMatchedToOutput.size() && "TiedTo value out of range");
698 if (InputMatchedToOutput[TiedTo] != ~0U) {
699 targetDiag(NS->getInputExpr(i)->getBeginLoc(),
700 diag::err_asm_input_duplicate_match)
701 << TiedTo;
702 targetDiag(NS->getInputExpr(InputMatchedToOutput[TiedTo])->getBeginLoc(),
703 diag::note_asm_input_duplicate_first)
704 << TiedTo;
705 return NS;
706 }
707 InputMatchedToOutput[TiedTo] = i;
708
709 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
710 continue;
711
712 QualType InTy = InputExpr->getType();
713 QualType OutTy = OutputExpr->getType();
714 if (Context.hasSameType(InTy, OutTy))
715 continue; // All types can be tied to themselves.
716
717 // Decide if the input and output are in the same domain (integer/ptr or
718 // floating point.
719 enum AsmDomain {
720 AD_Int, AD_FP, AD_Other
721 } InputDomain, OutputDomain;
722
723 if (InTy->isIntegerType() || InTy->isPointerType())
724 InputDomain = AD_Int;
725 else if (InTy->isRealFloatingType())
726 InputDomain = AD_FP;
727 else
728 InputDomain = AD_Other;
729
730 if (OutTy->isIntegerType() || OutTy->isPointerType())
731 OutputDomain = AD_Int;
732 else if (OutTy->isRealFloatingType())
733 OutputDomain = AD_FP;
734 else
735 OutputDomain = AD_Other;
736
737 // They are ok if they are the same size and in the same domain. This
738 // allows tying things like:
739 // void* to int*
740 // void* to int if they are the same size.
741 // double to long double if they are the same size.
742 //
743 uint64_t OutSize = Context.getTypeSize(OutTy);
744 uint64_t InSize = Context.getTypeSize(InTy);
745 if (OutSize == InSize && InputDomain == OutputDomain &&
746 InputDomain != AD_Other)
747 continue;
748
749 // If the smaller input/output operand is not mentioned in the asm string,
750 // then we can promote the smaller one to a larger input and the asm string
751 // won't notice.
752 bool SmallerValueMentioned = false;
753
754 // If this is a reference to the input and if the input was the smaller
755 // one, then we have to reject this asm.
756 if (isOperandMentioned(InputOpNo, Pieces)) {
757 // This is a use in the asm string of the smaller operand. Since we
758 // codegen this by promoting to a wider value, the asm will get printed
759 // "wrong".
760 SmallerValueMentioned |= InSize < OutSize;
761 }
762 if (isOperandMentioned(TiedTo, Pieces)) {
763 // If this is a reference to the output, and if the output is the larger
764 // value, then it's ok because we'll promote the input to the larger type.
765 SmallerValueMentioned |= OutSize < InSize;
766 }
767
768 // If the input is an integer register while the output is floating point,
769 // or vice-versa, there is no way they can work together.
770 bool FPTiedToInt = (InputDomain == AD_FP) ^ (OutputDomain == AD_FP);
771
772 // If the smaller value wasn't mentioned in the asm string, and if the
773 // output was a register, just extend the shorter one to the size of the
774 // larger one.
775 if (!SmallerValueMentioned && !FPTiedToInt && InputDomain != AD_Other &&
776 OutputConstraintInfos[TiedTo].allowsRegister()) {
777
778 // FIXME: GCC supports some non-scalar register outputs. Currently
779 // codegen crashes when the size cannot be represented by an integer type
780 // that fits in a general-purpose register.
781 bool FitsInGeneralPurposeRegister =
782 OutSize <= Context.getTargetInfo().getRegisterWidth() &&
783 !Context.getIntTypeForBitwidth(OutSize, /*Signed*/ false).isNull();
784 if (OutputDomain == AD_Other && !FitsInGeneralPurposeRegister) {
785 targetDiag(OutputExpr->getExprLoc(), diag::err_store_value_to_reg);
786 return NS;
787 }
788
789 continue;
790 }
791
792 // Either both of the operands were mentioned or the smaller one was
793 // mentioned. One more special case that we'll allow: if the tied input is
794 // integer, unmentioned, and is a constant, then we'll allow truncating it
795 // down to the size of the destination.
796 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
797 !isOperandMentioned(InputOpNo, Pieces) &&
798 InputExpr->isEvaluatable(Context)) {
799 CastKind castKind =
800 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
801 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
802 Exprs[InputOpNo] = InputExpr;
803 NS->setInputExpr(i, InputExpr);
804 continue;
805 }
806
807 targetDiag(InputExpr->getBeginLoc(), diag::err_asm_tying_incompatible_types)
808 << InTy << OutTy << OutputExpr->getSourceRange()
809 << InputExpr->getSourceRange();
810 return NS;
811 }
812
813 // Check for conflicts between clobber list and input or output lists
815 Exprs, constraints.data(), clobbers.data(), NumClobbers, NumLabels,
816 Context.getTargetInfo(), Context);
817 if (ConstraintLoc.isValid())
818 targetDiag(ConstraintLoc, diag::error_inoutput_conflict_with_clobber);
819
820 // Check for duplicate asm operand name between input, output and label lists.
821 typedef std::pair<StringRef , Expr *> NamedOperand;
822 SmallVector<NamedOperand, 4> NamedOperandList;
823 for (unsigned i = 0, e = NumOutputs + NumInputs + NumLabels; i != e; ++i)
824 if (Names[i])
825 NamedOperandList.emplace_back(
826 std::make_pair(Names[i]->getName(), Exprs[i]));
827 // Sort NamedOperandList.
828 llvm::stable_sort(NamedOperandList, llvm::less_first());
829 // Find adjacent duplicate operand.
831 std::adjacent_find(begin(NamedOperandList), end(NamedOperandList),
832 [](const NamedOperand &LHS, const NamedOperand &RHS) {
833 return LHS.first == RHS.first;
834 });
835 if (Found != NamedOperandList.end()) {
836 Diag((Found + 1)->second->getBeginLoc(),
837 diag::error_duplicate_asm_operand_name)
838 << (Found + 1)->first;
839 Diag(Found->second->getBeginLoc(), diag::note_duplicate_asm_operand_name)
840 << Found->first;
841 return StmtError();
842 }
843 if (NS->isAsmGoto())
845
848 return NS;
849}
850
852 llvm::InlineAsmIdentifierInfo &Info) {
853 QualType T = Res->getType();
854 Expr::EvalResult Eval;
855 if (T->isFunctionType() || T->isDependentType())
856 return Info.setLabel(Res);
857 if (Res->isPRValue()) {
858 bool IsEnum = isa<clang::EnumType>(T);
859 if (DeclRefExpr *DRE = dyn_cast<clang::DeclRefExpr>(Res))
860 if (DRE->getDecl()->getKind() == Decl::EnumConstant)
861 IsEnum = true;
862 if (IsEnum && Res->EvaluateAsRValue(Eval, Context))
863 return Info.setEnum(Eval.Val.getInt().getSExtValue());
864
865 return Info.setLabel(Res);
866 }
867 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
868 unsigned Type = Size;
869 if (const auto *ATy = Context.getAsArrayType(T))
870 Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
871 bool IsGlobalLV = false;
872 if (Res->EvaluateAsLValue(Eval, Context))
873 IsGlobalLV = Eval.isGlobalLValue();
874 Info.setVar(Res, IsGlobalLV, Size, Type);
875}
876
878 SourceLocation TemplateKWLoc,
879 UnqualifiedId &Id,
880 bool IsUnevaluatedContext) {
881
882 if (IsUnevaluatedContext)
886
887 ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
888 /*trailing lparen*/ false,
889 /*is & operand*/ false,
890 /*CorrectionCandidateCallback=*/nullptr,
891 /*IsInlineAsmIdentifier=*/ true);
892
893 if (IsUnevaluatedContext)
895
896 if (!Result.isUsable()) return Result;
897
899 if (!Result.isUsable()) return Result;
900
901 // Referring to parameters is not allowed in naked functions.
902 if (CheckNakedParmReference(Result.get(), *this))
903 return ExprError();
904
905 QualType T = Result.get()->getType();
906
907 if (T->isDependentType()) {
908 return Result;
909 }
910
911 // Any sort of function type is fine.
912 if (T->isFunctionType()) {
913 return Result;
914 }
915
916 // Otherwise, it needs to be a complete type.
917 if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
918 return ExprError();
919 }
920
921 return Result;
922}
923
924bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
925 unsigned &Offset, SourceLocation AsmLoc) {
926 Offset = 0;
928 Member.split(Members, ".");
929
930 NamedDecl *FoundDecl = nullptr;
931
932 // MS InlineAsm uses 'this' as a base
933 if (getLangOpts().CPlusPlus && Base == "this") {
934 if (const Type *PT = getCurrentThisType().getTypePtrOrNull())
935 FoundDecl = PT->getPointeeType()->getAsTagDecl();
936 } else {
937 LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
939 if (LookupName(BaseResult, getCurScope()) && BaseResult.isSingleResult())
940 FoundDecl = BaseResult.getFoundDecl();
941 }
942
943 if (!FoundDecl)
944 return true;
945
946 for (StringRef NextMember : Members) {
947 const RecordType *RT = nullptr;
948 if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
949 RT = VD->getType()->getAsCanonical<RecordType>();
950 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
951 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
952 // MS InlineAsm often uses struct pointer aliases as a base
953 QualType QT = TD->getUnderlyingType();
954 if (const auto *PT = QT->getAs<PointerType>())
955 QT = PT->getPointeeType();
956 RT = QT->getAsCanonical<RecordType>();
957 } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
958 RT = QualType(Context.getCanonicalTypeDeclType(TD))
959 ->getAsCanonical<RecordType>();
960 else if (FieldDecl *TD = dyn_cast<FieldDecl>(FoundDecl))
961 RT = TD->getType()->getAsCanonical<RecordType>();
962 if (!RT)
963 return true;
964
965 if (RequireCompleteType(AsmLoc, QualType(RT, 0),
966 diag::err_asm_incomplete_type))
967 return true;
968
969 LookupResult FieldResult(*this, &Context.Idents.get(NextMember),
971
972 RecordDecl *RD = RT->getDecl()->getDefinitionOrSelf();
973 if (!LookupQualifiedName(FieldResult, RD))
974 return true;
975
976 if (!FieldResult.isSingleResult())
977 return true;
978 FoundDecl = FieldResult.getFoundDecl();
979
980 // FIXME: Handle IndirectFieldDecl?
981 FieldDecl *FD = dyn_cast<FieldDecl>(FoundDecl);
982 if (!FD)
983 return true;
984
985 const ASTRecordLayout &RL = Context.getASTRecordLayout(RD);
986 unsigned i = FD->getFieldIndex();
987 CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
988 Offset += (unsigned)Result.getQuantity();
989 }
990
991 return false;
992}
993
996 SourceLocation AsmLoc) {
997
998 QualType T = E->getType();
999 if (T->isDependentType()) {
1000 DeclarationNameInfo NameInfo;
1001 NameInfo.setLoc(AsmLoc);
1002 NameInfo.setName(&Context.Idents.get(Member));
1004 Context, E, T, /*IsArrow=*/false, AsmLoc, NestedNameSpecifierLoc(),
1006 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, /*TemplateArgs=*/nullptr);
1007 }
1008
1009 auto *RD = T->getAsRecordDecl();
1010 // FIXME: Diagnose this as field access into a scalar type.
1011 if (!RD)
1012 return ExprResult();
1013
1014 LookupResult FieldResult(*this, &Context.Idents.get(Member), AsmLoc,
1016
1017 if (!LookupQualifiedName(FieldResult, RD))
1018 return ExprResult();
1019
1020 // Only normal and indirect field results will work.
1021 ValueDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
1022 if (!FD)
1023 FD = dyn_cast<IndirectFieldDecl>(FieldResult.getFoundDecl());
1024 if (!FD)
1025 return ExprResult();
1026
1027 // Make an Expr to thread through OpDecl.
1029 E, E->getType(), AsmLoc, /*IsArrow=*/false, CXXScopeSpec(),
1030 SourceLocation(), nullptr, FieldResult, nullptr, nullptr);
1031
1032 return Result;
1033}
1034
1036 ArrayRef<Token> AsmToks,
1037 StringRef AsmString,
1038 unsigned NumOutputs, unsigned NumInputs,
1039 ArrayRef<StringRef> Constraints,
1040 ArrayRef<StringRef> Clobbers,
1041 ArrayRef<Expr*> Exprs,
1042 SourceLocation EndLoc) {
1043 bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
1045
1046 bool InvalidOperand = false;
1047 for (uint64_t I = 0; I < NumOutputs + NumInputs; ++I) {
1048 Expr *E = Exprs[I];
1049 if (E->getType()->isBitIntType()) {
1050 InvalidOperand = true;
1051 Diag(E->getBeginLoc(), diag::err_asm_invalid_type)
1052 << E->getType() << (I < NumOutputs)
1053 << E->getSourceRange();
1054 } else if (E->refersToBitField()) {
1055 InvalidOperand = true;
1056 FieldDecl *BitField = E->getSourceBitField();
1057 Diag(E->getBeginLoc(), diag::err_ms_asm_bitfield_unsupported)
1058 << E->getSourceRange();
1059 Diag(BitField->getLocation(), diag::note_bitfield_decl);
1060 }
1061 }
1062 if (InvalidOperand)
1063 return StmtError();
1064
1065 MSAsmStmt *NS =
1066 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
1067 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
1068 Constraints, Exprs, AsmString,
1069 Clobbers, EndLoc);
1070 return NS;
1071}
1072
1073LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
1074 SourceLocation Location,
1075 bool AlwaysCreate) {
1076 LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
1077 Location);
1078
1079 if (Label->isMSAsmLabel()) {
1080 // If we have previously created this label implicitly, mark it as used.
1081 Label->markUsed(Context);
1082 } else {
1083 // Otherwise, insert it, but only resolve it if we have seen the label itself.
1084 std::string InternalName;
1085 llvm::raw_string_ostream OS(InternalName);
1086 // Create an internal name for the label. The name should not be a valid
1087 // mangled name, and should be unique. We use a dot to make the name an
1088 // invalid mangled name. We use LLVM's inline asm ${:uid} escape so that a
1089 // unique label is generated each time this blob is emitted, even after
1090 // inlining or LTO.
1091 OS << "__MSASMLABEL_.${:uid}__";
1092 for (char C : ExternalLabelName) {
1093 OS << C;
1094 // We escape '$' in asm strings by replacing it with "$$"
1095 if (C == '$')
1096 OS << '$';
1097 }
1098 Label->setMSAsmLabel(OS.str());
1099 }
1100 if (AlwaysCreate) {
1101 // The label might have been created implicitly from a previously encountered
1102 // goto statement. So, for both newly created and looked up labels, we mark
1103 // them as resolved.
1104 Label->setMSAsmLabelResolved();
1105 }
1106 // Adjust their location for being able to generate accurate diagnostics.
1107 Label->setLocation(Location);
1108
1109 return Label;
1110}
#define V(N, I)
Defines the clang::Expr interface and subclasses for C++ expressions.
llvm::MachO::Target Target
Definition MachO.h:51
Defines the clang::Preprocessor interface.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to BPF.
static bool isOperandMentioned(unsigned OpNo, ArrayRef< GCCAsmStmt::AsmStringPiece > AsmStrPieces)
isOperandMentioned - Return true if the specified operand # is mentioned anywhere in the decomposed a...
static SourceLocation getClobberConflictLocation(MultiExprArg Exprs, Expr **Constraints, Expr **Clobbers, int NumClobbers, unsigned NumLabels, const TargetInfo &Target, ASTContext &Cont)
static bool CheckAsmLValue(Expr *E, Sema &S)
CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently ignore "noop" casts in p...
static StringRef extractRegisterName(const Expr *Expression, const TargetInfo &Target)
static bool CheckNakedParmReference(Expr *E, Sema &S)
static bool checkExprMemoryConstraintCompat(Sema &S, Expr *E, TargetInfo::ConstraintInfo &Info, bool is_input_expr)
Returns true if given expression is not compatible with inline assembly's memory constraint; false ot...
static void removeLValueToRValueCast(Expr *E)
Remove the upper-level LValueToRValue cast from an expression.
static void emitAndFixInvalidAsmCastLValue(const Expr *LVal, Expr *BadArgument, Sema &S)
Emit a warning about usage of "noop"-like casts for lvalues (GNU extension) and fix the argument with...
Defines the clang::TypeLoc interface and its subclasses.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
APSInt & getInt()
Definition APValue.h:577
bool toIntegralConstant(APSInt &Result, QualType SrcTy, const ASTContext &Ctx) const
Try to convert this value to an integral constant.
Definition APValue.cpp:1117
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
Attr - This represents one attribute.
Definition Attr.h:47
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:1581
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:77
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3745
void setSubExpr(Expr *E)
Definition Expr.h:3797
Expr * getSubExpr()
Definition Expr.h:3795
SourceLocation getBegin() const
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition DeclBase.cpp:594
SourceLocation getLocation() const
Definition DeclBase.h:448
void setLocation(SourceLocation L)
Definition DeclBase.h:449
This represents one expression.
Definition Expr.h:114
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3156
isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, does not have an incomplet...
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:179
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:449
bool refersToVectorElement() const
Returns whether this expression refers to a vector element.
Definition Expr.cpp:4332
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:196
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
bool isPRValue() const
Definition Expr.h:287
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:286
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4271
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:466
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:481
isModifiableLvalueResult
Definition Expr.h:307
@ MLV_LValueCast
Definition Expr.h:314
@ MLV_IncompleteType
Definition Expr.h:315
@ MLV_Valid
Definition Expr.h:308
@ MLV_ArrayType
Definition Expr.h:319
@ MLV_IncompleteVoidType
Definition Expr.h:310
QualType getType() const
Definition Expr.h:146
bool refersToGlobalRegisterVar() const
Returns whether this expression refers to a global register variable.
Definition Expr.cpp:4357
ExprDependence getDependence() const
Definition Expr.h:166
Represents a member of a struct/union/class.
Definition Decl.h:3341
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3426
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
Represents a function declaration or definition.
Definition Decl.h:2082
AsmStringPiece - this is part of a decomposed asm string specification (for use with the AnalyzeAsmSt...
Definition Stmt.h:3495
const std::string & getString() const
Definition Stmt.h:3520
unsigned getOperandNo() const
Definition Stmt.h:3522
CharSourceRange getRange() const
Definition Stmt.h:3527
char getModifier() const
getModifier - Get the modifier for this operand, if present.
Definition Stmt.cpp:549
This represents a GCC inline-assembly statement extension.
Definition Stmt.h:3459
static std::string ExtractStringFromGCCAsmStmtComponent(const Expr *E)
Definition Stmt.cpp:554
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
Represents the declaration of a label.
Definition Decl.h:526
void setMSAsmLabel(StringRef Name)
Definition Decl.cpp:5709
void setMSAsmLabelResolved()
Definition Decl.h:564
bool isMSAsmLabel() const
Definition Decl.h:560
Represents the results of name lookup.
Definition Lookup.h:147
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
This represents a Microsoft inline-assembly statement extension.
Definition Stmt.h:3678
This represents a decl that may have a name.
Definition Decl.h:276
A C++ nested-name-specifier augmented with source location information.
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
A (possibly-)qualified type.
Definition TypeBase.h:938
Represents a struct/union/class.
Definition Decl.h:4508
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4696
Expr * checkAsmImmediateOperand(Expr *E)
Definition SemaBPF.cpp:391
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1165
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9545
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9553
StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, ArrayRef< Token > AsmToks, StringRef AsmString, unsigned NumOutputs, unsigned NumInputs, ArrayRef< StringRef > Constraints, ArrayRef< StringRef > Clobbers, ArrayRef< Expr * > Exprs, SourceLocation EndLoc)
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
void setFunctionHasBranchIntoScope()
Definition Sema.cpp:2675
ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool IsUnevaluatedContext)
ASTContext & Context
Definition Sema.h:1332
void CleanupVarDeclMarking()
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:771
ASTContext & getASTContext() const
Definition Sema.h:935
void PopExpressionEvaluationContext()
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:774
const LangOptions & getLangOpts() const
Definition Sema.h:928
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
@ ReuseLambdaContextDecl
Definition Sema.h:7208
SemaBPF & BPF()
Definition Sema.h:1501
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false)
Preprocessor & PP
Definition Sema.h:1331
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
const LangOptions & LangOpts
Definition Sema.h:1330
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
DeclContext * getCurLexicalContext() const
Definition Sema.h:1169
bool EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx, StringEvaluationContext EvalContext, bool ErrorOnInvalidMessage)
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1484
void FillInlineAsmIdentifierInfo(Expr *Res, llvm::InlineAsmIdentifierInfo &Info)
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc)
ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, SourceLocation AsmLoc)
LabelDecl * LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc=SourceLocation(), bool IsLabelStmt=false)
LookupOrCreateLabel - Do a name lookup of a label with the specified name.
void setFunctionHasBranchProtectedScope()
Definition Sema.cpp:2680
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
Definition Sema.h:6913
ExprResult ActOnGCCAsmStmtString(Expr *Stm, bool ForAsmLabel, bool IsConstexpr=false)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void DiscardCleanupsInEvaluationContext()
LabelDecl * GetOrCreateMSAsmLabel(StringRef ExternalLabelName, SourceLocation Location, bool AlwaysCreate)
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2281
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, IdentifierInfo **Names, MultiExprArg Constraints, MultiExprArg Exprs, Expr *AsmString, MultiExprArg Clobbers, unsigned NumLabels, SourceLocation RParenLoc)
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
Stmt - This represents one statement.
Definition Stmt.h:85
child_range children()
Definition Stmt.cpp:304
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1198
Exposes information about the current target.
Definition TargetInfo.h:228
Represents a declaration of a type.
Definition Decl.h:3696
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9200
bool isBooleanType() const
Definition TypeBase.h:9341
bool isPointerType() const
Definition TypeBase.h:8815
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isBitIntType() const
Definition TypeBase.h:9090
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
bool isMemberPointerType() const
Definition TypeBase.h:8896
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2655
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2533
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3002
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3745
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1110
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
Represents a variable declaration or definition.
Definition Decl.h:934
Defines the clang::TargetInfo interface.
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
@ SC_Register
Definition Specifiers.h:261
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
StmtResult StmtError()
Definition Ownership.h:266
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
ExprResult ExprError()
Definition Ownership.h:265
CastKind
CastKind - The kind of operation required for a conversion.
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669
bool isGlobalLValue() const
Return true if the evaluated lvalue expression is global.
const std::string & getConstraintStr() const
bool isValidAsmImmediate(const llvm::APInt &Value) const
bool hasTiedOperand() const
Return true if this input operand is a matching constraint that ties it to an output operand.