1 //===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements semantic analysis for inline asm statements.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ExprCXX.h"
14 #include "clang/AST/RecordLayout.h"
15 #include "clang/AST/TypeLoc.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/Lex/Preprocessor.h"
18 #include "clang/Sema/Initialization.h"
19 #include "clang/Sema/Lookup.h"
20 #include "clang/Sema/Scope.h"
21 #include "clang/Sema/ScopeInfo.h"
22 #include "clang/Sema/SemaInternal.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/StringSet.h"
25 #include "llvm/MC/MCParser/MCAsmParser.h"
26 using namespace clang;
29 /// Remove the upper-level LValueToRValue cast from an expression.
30 static void removeLValueToRValueCast(Expr *E) {
32 Expr *ExprUnderCast = nullptr;
33 SmallVector<Expr *, 8> ParentsToUpdate;
36 ParentsToUpdate.push_back(Parent);
37 if (auto *ParenE = dyn_cast<ParenExpr>(Parent)) {
38 Parent = ParenE->getSubExpr();
42 Expr *Child = nullptr;
43 CastExpr *ParentCast = dyn_cast<CastExpr>(Parent);
45 Child = ParentCast->getSubExpr();
49 if (auto *CastE = dyn_cast<CastExpr>(Child))
50 if (CastE->getCastKind() == CK_LValueToRValue) {
51 ExprUnderCast = CastE->getSubExpr();
52 // LValueToRValue cast inside GCCAsmStmt requires an explicit cast.
53 ParentCast->setSubExpr(ExprUnderCast);
59 // Update parent expressions to have same ValueType as the underlying.
60 assert(ExprUnderCast &&
61 "Should be reachable only if LValueToRValue cast was found!");
62 auto ValueKind = ExprUnderCast->getValueKind();
63 for (Expr *E : ParentsToUpdate)
64 E->setValueKind(ValueKind);
67 /// Emit a warning about usage of "noop"-like casts for lvalues (GNU extension)
68 /// and fix the argument with removing LValueToRValue cast from the expression.
69 static void emitAndFixInvalidAsmCastLValue(const Expr *LVal, Expr *BadArgument,
71 if (!S.getLangOpts().HeinousExtensions) {
72 S.Diag(LVal->getBeginLoc(), diag::err_invalid_asm_cast_lvalue)
73 << BadArgument->getSourceRange();
75 S.Diag(LVal->getBeginLoc(), diag::warn_invalid_asm_cast_lvalue)
76 << BadArgument->getSourceRange();
78 removeLValueToRValueCast(BadArgument);
81 /// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
82 /// ignore "noop" casts in places where an lvalue is required by an inline asm.
83 /// We emulate this behavior when -fheinous-gnu-extensions is specified, but
84 /// provide a strong guidance to not use it.
86 /// This method checks to see if the argument is an acceptable l-value and
87 /// returns false if it is a case we can handle.
88 static bool CheckAsmLValue(Expr *E, Sema &S) {
89 // Type dependent expressions will be checked during instantiation.
90 if (E->isTypeDependent())
94 return false; // Cool, this is an lvalue.
96 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
97 // are supposed to allow.
98 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
99 if (E != E2 && E2->isLValue()) {
100 emitAndFixInvalidAsmCastLValue(E2, E, S);
101 // Accept, even if we emitted an error diagnostic.
105 // None of the above, just randomly invalid non-lvalue.
109 /// isOperandMentioned - Return true if the specified operand # is mentioned
110 /// anywhere in the decomposed asm string.
112 isOperandMentioned(unsigned OpNo,
113 ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
114 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
115 const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
116 if (!Piece.isOperand())
119 // If this is a reference to the input and if the input was the smaller
120 // one, then we have to reject this asm.
121 if (Piece.getOperandNo() == OpNo)
127 static bool CheckNakedParmReference(Expr *E, Sema &S) {
128 FunctionDecl *Func = dyn_cast<FunctionDecl>(S.CurContext);
131 if (!Func->hasAttr<NakedAttr>())
134 SmallVector<Expr*, 4> WorkList;
135 WorkList.push_back(E);
136 while (WorkList.size()) {
137 Expr *E = WorkList.pop_back_val();
138 if (isa<CXXThisExpr>(E)) {
139 S.Diag(E->getBeginLoc(), diag::err_asm_naked_this_ref);
140 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
143 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
144 if (isa<ParmVarDecl>(DRE->getDecl())) {
145 S.Diag(DRE->getBeginLoc(), diag::err_asm_naked_parm_ref);
146 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
150 for (Stmt *Child : E->children()) {
151 if (Expr *E = dyn_cast_or_null<Expr>(Child))
152 WorkList.push_back(E);
158 /// Returns true if given expression is not compatible with inline
159 /// assembly's memory constraint; false otherwise.
160 static bool checkExprMemoryConstraintCompat(Sema &S, Expr *E,
161 TargetInfo::ConstraintInfo &Info,
162 bool is_input_expr) {
168 } EType = ExprSafeType;
170 // Bitfields, vector elements and global register variables are not
172 if (E->refersToBitField())
173 EType = ExprBitfield;
174 else if (E->refersToVectorElement())
175 EType = ExprVectorElt;
176 else if (E->refersToGlobalRegisterVar())
177 EType = ExprGlobalRegVar;
179 if (EType != ExprSafeType) {
180 S.Diag(E->getBeginLoc(), diag::err_asm_non_addr_value_in_memory_constraint)
181 << EType << is_input_expr << Info.getConstraintStr()
182 << E->getSourceRange();
189 // Extracting the register name from the Expression value,
190 // if there is no register name to extract, returns ""
191 static StringRef extractRegisterName(const Expr *Expression,
192 const TargetInfo &Target) {
193 Expression = Expression->IgnoreImpCasts();
194 if (const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(Expression)) {
195 // Handle cases where the expression is a variable
196 const VarDecl *Variable = dyn_cast<VarDecl>(AsmDeclRef->getDecl());
197 if (Variable && Variable->getStorageClass() == SC_Register) {
198 if (AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>())
199 if (Target.isValidGCCRegisterName(Attr->getLabel()))
200 return Target.getNormalizedGCCRegisterName(Attr->getLabel(), true);
206 // Checks if there is a conflict between the input and output lists with the
207 // clobbers list. If there's a conflict, returns the location of the
208 // conflicted clobber, else returns nullptr
209 static SourceLocation
210 getClobberConflictLocation(MultiExprArg Exprs, StringLiteral **Constraints,
211 StringLiteral **Clobbers, int NumClobbers,
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 StringRef Constraint = Constraints[i]->getString();
219 StringRef InOutReg = Target.getConstraintRegister(
220 Constraint, extractRegisterName(Exprs[i], Target));
222 InOutVars.insert(InOutReg);
224 // Check for each item in the clobber list if it conflicts with the input
226 for (int i = 0; i < NumClobbers; ++i) {
227 StringRef Clobber = Clobbers[i]->getString();
228 // We only check registers, therefore we don't check cc and memory
230 if (Clobber == "cc" || Clobber == "memory")
232 Clobber = Target.getNormalizedGCCRegisterName(Clobber, true);
233 // Go over the output's registers we collected
234 if (InOutVars.count(Clobber))
235 return Clobbers[i]->getBeginLoc();
237 return SourceLocation();
240 StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
241 bool IsVolatile, unsigned NumOutputs,
242 unsigned NumInputs, IdentifierInfo **Names,
243 MultiExprArg constraints, MultiExprArg Exprs,
244 Expr *asmString, MultiExprArg clobbers,
246 SourceLocation RParenLoc) {
247 unsigned NumClobbers = clobbers.size();
248 StringLiteral **Constraints =
249 reinterpret_cast<StringLiteral**>(constraints.data());
250 StringLiteral *AsmString = cast<StringLiteral>(asmString);
251 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
253 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
255 // The parser verifies that there is a string literal here.
256 assert(AsmString->isAscii());
258 for (unsigned i = 0; i != NumOutputs; i++) {
259 StringLiteral *Literal = Constraints[i];
260 assert(Literal->isAscii());
262 StringRef OutputName;
264 OutputName = Names[i]->getName();
266 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
267 if (!Context.getTargetInfo().validateOutputConstraint(Info)) {
268 targetDiag(Literal->getBeginLoc(),
269 diag::err_asm_invalid_output_constraint)
270 << Info.getConstraintStr();
272 GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
273 NumInputs, Names, Constraints, Exprs.data(), AsmString,
274 NumClobbers, Clobbers, NumLabels, RParenLoc);
277 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
282 // Check that the output exprs are valid lvalues.
283 Expr *OutputExpr = Exprs[i];
285 // Referring to parameters is not allowed in naked functions.
286 if (CheckNakedParmReference(OutputExpr, *this))
289 // Check that the output expression is compatible with memory constraint.
290 if (Info.allowsMemory() &&
291 checkExprMemoryConstraintCompat(*this, OutputExpr, Info, false))
294 OutputConstraintInfos.push_back(Info);
296 // If this is dependent, just continue.
297 if (OutputExpr->isTypeDependent())
300 Expr::isModifiableLvalueResult IsLV =
301 OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr);
303 case Expr::MLV_Valid:
304 // Cool, this is an lvalue.
306 case Expr::MLV_ArrayType:
309 case Expr::MLV_LValueCast: {
310 const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context);
311 emitAndFixInvalidAsmCastLValue(LVal, OutputExpr, *this);
312 // Accept, even if we emitted an error diagnostic.
315 case Expr::MLV_IncompleteType:
316 case Expr::MLV_IncompleteVoidType:
317 if (RequireCompleteType(OutputExpr->getBeginLoc(), Exprs[i]->getType(),
318 diag::err_dereference_incomplete_type))
322 return StmtError(Diag(OutputExpr->getBeginLoc(),
323 diag::err_asm_invalid_lvalue_in_output)
324 << OutputExpr->getSourceRange());
327 unsigned Size = Context.getTypeSize(OutputExpr->getType());
328 if (!Context.getTargetInfo().validateOutputSize(Literal->getString(),
330 targetDiag(OutputExpr->getBeginLoc(), diag::err_asm_invalid_output_size)
331 << Info.getConstraintStr();
333 GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
334 NumInputs, Names, Constraints, Exprs.data(), AsmString,
335 NumClobbers, Clobbers, NumLabels, RParenLoc);
339 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
341 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
342 StringLiteral *Literal = Constraints[i];
343 assert(Literal->isAscii());
347 InputName = Names[i]->getName();
349 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
350 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos,
352 targetDiag(Literal->getBeginLoc(), diag::err_asm_invalid_input_constraint)
353 << Info.getConstraintStr();
355 GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
356 NumInputs, Names, Constraints, Exprs.data(), AsmString,
357 NumClobbers, Clobbers, NumLabels, RParenLoc);
360 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
365 Expr *InputExpr = Exprs[i];
367 // Referring to parameters is not allowed in naked functions.
368 if (CheckNakedParmReference(InputExpr, *this))
371 // Check that the input expression is compatible with memory constraint.
372 if (Info.allowsMemory() &&
373 checkExprMemoryConstraintCompat(*this, InputExpr, Info, true))
376 // Only allow void types for memory constraints.
377 if (Info.allowsMemory() && !Info.allowsRegister()) {
378 if (CheckAsmLValue(InputExpr, *this))
379 return StmtError(Diag(InputExpr->getBeginLoc(),
380 diag::err_asm_invalid_lvalue_in_input)
381 << Info.getConstraintStr()
382 << InputExpr->getSourceRange());
383 } else if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
384 if (!InputExpr->isValueDependent()) {
385 Expr::EvalResult EVResult;
386 if (InputExpr->EvaluateAsRValue(EVResult, Context, true)) {
387 // For compatibility with GCC, we also allow pointers that would be
388 // integral constant expressions if they were cast to int.
389 llvm::APSInt IntResult;
390 if (EVResult.Val.toIntegralConstant(IntResult, InputExpr->getType(),
392 if (!Info.isValidAsmImmediate(IntResult))
393 return StmtError(Diag(InputExpr->getBeginLoc(),
394 diag::err_invalid_asm_value_for_constraint)
395 << IntResult.toString(10)
396 << Info.getConstraintStr()
397 << InputExpr->getSourceRange());
402 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
403 if (Result.isInvalid())
406 Exprs[i] = Result.get();
409 if (Info.allowsRegister()) {
410 if (InputExpr->getType()->isVoidType()) {
412 Diag(InputExpr->getBeginLoc(), diag::err_asm_invalid_type_in_input)
413 << InputExpr->getType() << Info.getConstraintStr()
414 << InputExpr->getSourceRange());
418 InputConstraintInfos.push_back(Info);
420 const Type *Ty = Exprs[i]->getType().getTypePtr();
421 if (Ty->isDependentType())
424 if (!Ty->isVoidType() || !Info.allowsMemory())
425 if (RequireCompleteType(InputExpr->getBeginLoc(), Exprs[i]->getType(),
426 diag::err_dereference_incomplete_type))
429 unsigned Size = Context.getTypeSize(Ty);
430 if (!Context.getTargetInfo().validateInputSize(Literal->getString(),
433 targetDiag(InputExpr->getBeginLoc(), diag::err_asm_invalid_input_size)
434 << Info.getConstraintStr());
437 // Check that the clobbers are valid.
438 for (unsigned i = 0; i != NumClobbers; i++) {
439 StringLiteral *Literal = Clobbers[i];
440 assert(Literal->isAscii());
442 StringRef Clobber = Literal->getString();
444 if (!Context.getTargetInfo().isValidClobber(Clobber)) {
445 targetDiag(Literal->getBeginLoc(), diag::err_asm_unknown_register_name)
448 GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
449 NumInputs, Names, Constraints, Exprs.data(), AsmString,
450 NumClobbers, Clobbers, NumLabels, RParenLoc);
455 new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
456 NumInputs, Names, Constraints, Exprs.data(),
457 AsmString, NumClobbers, Clobbers, NumLabels,
459 // Validate the asm string, ensuring it makes sense given the operands we
461 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
463 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
464 targetDiag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
465 << AsmString->getSourceRange();
469 // Validate constraints and modifiers.
470 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
471 GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
472 if (!Piece.isOperand()) continue;
474 // Look for the correct constraint index.
475 unsigned ConstraintIdx = Piece.getOperandNo();
476 // Labels are the last in the Exprs list.
477 if (NS->isAsmGoto() && ConstraintIdx >= NS->getNumInputs())
479 unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs();
480 // Look for the (ConstraintIdx - NumOperands + 1)th constraint with
482 if (ConstraintIdx >= NumOperands) {
483 unsigned I = 0, E = NS->getNumOutputs();
485 for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I)
486 if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) {
491 assert(I != E && "Invalid operand number should have been caught in "
492 " AnalyzeAsmString");
495 // Now that we have the right indexes go ahead and check.
496 StringLiteral *Literal = Constraints[ConstraintIdx];
497 const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
498 if (Ty->isDependentType() || Ty->isIncompleteType())
501 unsigned Size = Context.getTypeSize(Ty);
502 std::string SuggestedModifier;
503 if (!Context.getTargetInfo().validateConstraintModifier(
504 Literal->getString(), Piece.getModifier(), Size,
505 SuggestedModifier)) {
506 targetDiag(Exprs[ConstraintIdx]->getBeginLoc(),
507 diag::warn_asm_mismatched_size_modifier);
509 if (!SuggestedModifier.empty()) {
510 auto B = targetDiag(Piece.getRange().getBegin(),
511 diag::note_asm_missing_constraint_modifier)
512 << SuggestedModifier;
513 SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
514 B << FixItHint::CreateReplacement(Piece.getRange(), SuggestedModifier);
519 // Validate tied input operands for type mismatches.
520 unsigned NumAlternatives = ~0U;
521 for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
522 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
523 StringRef ConstraintStr = Info.getConstraintStr();
524 unsigned AltCount = ConstraintStr.count(',') + 1;
525 if (NumAlternatives == ~0U) {
526 NumAlternatives = AltCount;
527 } else if (NumAlternatives != AltCount) {
528 targetDiag(NS->getOutputExpr(i)->getBeginLoc(),
529 diag::err_asm_unexpected_constraint_alternatives)
530 << NumAlternatives << AltCount;
534 SmallVector<size_t, 4> InputMatchedToOutput(OutputConstraintInfos.size(),
536 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
537 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
538 StringRef ConstraintStr = Info.getConstraintStr();
539 unsigned AltCount = ConstraintStr.count(',') + 1;
540 if (NumAlternatives == ~0U) {
541 NumAlternatives = AltCount;
542 } else if (NumAlternatives != AltCount) {
543 targetDiag(NS->getInputExpr(i)->getBeginLoc(),
544 diag::err_asm_unexpected_constraint_alternatives)
545 << NumAlternatives << AltCount;
549 // If this is a tied constraint, verify that the output and input have
550 // either exactly the same type, or that they are int/ptr operands with the
551 // same size (int/long, int*/long, are ok etc).
552 if (!Info.hasTiedOperand()) continue;
554 unsigned TiedTo = Info.getTiedOperand();
555 unsigned InputOpNo = i+NumOutputs;
556 Expr *OutputExpr = Exprs[TiedTo];
557 Expr *InputExpr = Exprs[InputOpNo];
559 // Make sure no more than one input constraint matches each output.
560 assert(TiedTo < InputMatchedToOutput.size() && "TiedTo value out of range");
561 if (InputMatchedToOutput[TiedTo] != ~0U) {
562 targetDiag(NS->getInputExpr(i)->getBeginLoc(),
563 diag::err_asm_input_duplicate_match)
565 targetDiag(NS->getInputExpr(InputMatchedToOutput[TiedTo])->getBeginLoc(),
566 diag::note_asm_input_duplicate_first)
570 InputMatchedToOutput[TiedTo] = i;
572 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
575 QualType InTy = InputExpr->getType();
576 QualType OutTy = OutputExpr->getType();
577 if (Context.hasSameType(InTy, OutTy))
578 continue; // All types can be tied to themselves.
580 // Decide if the input and output are in the same domain (integer/ptr or
583 AD_Int, AD_FP, AD_Other
584 } InputDomain, OutputDomain;
586 if (InTy->isIntegerType() || InTy->isPointerType())
587 InputDomain = AD_Int;
588 else if (InTy->isRealFloatingType())
591 InputDomain = AD_Other;
593 if (OutTy->isIntegerType() || OutTy->isPointerType())
594 OutputDomain = AD_Int;
595 else if (OutTy->isRealFloatingType())
596 OutputDomain = AD_FP;
598 OutputDomain = AD_Other;
600 // They are ok if they are the same size and in the same domain. This
601 // allows tying things like:
603 // void* to int if they are the same size.
604 // double to long double if they are the same size.
606 uint64_t OutSize = Context.getTypeSize(OutTy);
607 uint64_t InSize = Context.getTypeSize(InTy);
608 if (OutSize == InSize && InputDomain == OutputDomain &&
609 InputDomain != AD_Other)
612 // If the smaller input/output operand is not mentioned in the asm string,
613 // then we can promote the smaller one to a larger input and the asm string
615 bool SmallerValueMentioned = false;
617 // If this is a reference to the input and if the input was the smaller
618 // one, then we have to reject this asm.
619 if (isOperandMentioned(InputOpNo, Pieces)) {
620 // This is a use in the asm string of the smaller operand. Since we
621 // codegen this by promoting to a wider value, the asm will get printed
623 SmallerValueMentioned |= InSize < OutSize;
625 if (isOperandMentioned(TiedTo, Pieces)) {
626 // If this is a reference to the output, and if the output is the larger
627 // value, then it's ok because we'll promote the input to the larger type.
628 SmallerValueMentioned |= OutSize < InSize;
631 // If the smaller value wasn't mentioned in the asm string, and if the
632 // output was a register, just extend the shorter one to the size of the
634 if (!SmallerValueMentioned && InputDomain != AD_Other &&
635 OutputConstraintInfos[TiedTo].allowsRegister())
638 // Either both of the operands were mentioned or the smaller one was
639 // mentioned. One more special case that we'll allow: if the tied input is
640 // integer, unmentioned, and is a constant, then we'll allow truncating it
641 // down to the size of the destination.
642 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
643 !isOperandMentioned(InputOpNo, Pieces) &&
644 InputExpr->isEvaluatable(Context)) {
646 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
647 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
648 Exprs[InputOpNo] = InputExpr;
649 NS->setInputExpr(i, InputExpr);
653 targetDiag(InputExpr->getBeginLoc(), diag::err_asm_tying_incompatible_types)
654 << InTy << OutTy << OutputExpr->getSourceRange()
655 << InputExpr->getSourceRange();
659 // Check for conflicts between clobber list and input or output lists
660 SourceLocation ConstraintLoc =
661 getClobberConflictLocation(Exprs, Constraints, Clobbers, NumClobbers,
663 Context.getTargetInfo(), Context);
664 if (ConstraintLoc.isValid())
665 targetDiag(ConstraintLoc, diag::error_inoutput_conflict_with_clobber);
667 // Check for duplicate asm operand name between input, output and label lists.
668 typedef std::pair<StringRef , Expr *> NamedOperand;
669 SmallVector<NamedOperand, 4> NamedOperandList;
670 for (unsigned i = 0, e = NumOutputs + NumInputs + NumLabels; i != e; ++i)
672 NamedOperandList.emplace_back(
673 std::make_pair(Names[i]->getName(), Exprs[i]));
674 // Sort NamedOperandList.
675 std::stable_sort(NamedOperandList.begin(), NamedOperandList.end(),
676 [](const NamedOperand &LHS, const NamedOperand &RHS) {
677 return LHS.first < RHS.first;
679 // Find adjacent duplicate operand.
680 SmallVector<NamedOperand, 4>::iterator Found =
681 std::adjacent_find(begin(NamedOperandList), end(NamedOperandList),
682 [](const NamedOperand &LHS, const NamedOperand &RHS) {
683 return LHS.first == RHS.first;
685 if (Found != NamedOperandList.end()) {
686 Diag((Found + 1)->second->getBeginLoc(),
687 diag::error_duplicate_asm_operand_name)
688 << (Found + 1)->first;
689 Diag(Found->second->getBeginLoc(), diag::note_duplicate_asm_operand_name)
694 setFunctionHasBranchIntoScope();
698 void Sema::FillInlineAsmIdentifierInfo(Expr *Res,
699 llvm::InlineAsmIdentifierInfo &Info) {
700 QualType T = Res->getType();
701 Expr::EvalResult Eval;
702 if (T->isFunctionType() || T->isDependentType())
703 return Info.setLabel(Res);
704 if (Res->isRValue()) {
705 if (isa<clang::EnumType>(T) && Res->EvaluateAsRValue(Eval, Context))
706 return Info.setEnum(Eval.Val.getInt().getSExtValue());
707 return Info.setLabel(Res);
709 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
710 unsigned Type = Size;
711 if (const auto *ATy = Context.getAsArrayType(T))
712 Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
713 bool IsGlobalLV = false;
714 if (Res->EvaluateAsLValue(Eval, Context))
715 IsGlobalLV = Eval.isGlobalLValue();
716 Info.setVar(Res, IsGlobalLV, Size, Type);
719 ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
720 SourceLocation TemplateKWLoc,
722 bool IsUnevaluatedContext) {
724 if (IsUnevaluatedContext)
725 PushExpressionEvaluationContext(
726 ExpressionEvaluationContext::UnevaluatedAbstract,
727 ReuseLambdaContextDecl);
729 ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
730 /*trailing lparen*/ false,
731 /*is & operand*/ false,
732 /*CorrectionCandidateCallback=*/nullptr,
733 /*IsInlineAsmIdentifier=*/ true);
735 if (IsUnevaluatedContext)
736 PopExpressionEvaluationContext();
738 if (!Result.isUsable()) return Result;
740 Result = CheckPlaceholderExpr(Result.get());
741 if (!Result.isUsable()) return Result;
743 // Referring to parameters is not allowed in naked functions.
744 if (CheckNakedParmReference(Result.get(), *this))
747 QualType T = Result.get()->getType();
749 if (T->isDependentType()) {
753 // Any sort of function type is fine.
754 if (T->isFunctionType()) {
758 // Otherwise, it needs to be a complete type.
759 if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
766 bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
767 unsigned &Offset, SourceLocation AsmLoc) {
769 SmallVector<StringRef, 2> Members;
770 Member.split(Members, ".");
772 NamedDecl *FoundDecl = nullptr;
774 // MS InlineAsm uses 'this' as a base
775 if (getLangOpts().CPlusPlus && Base.equals("this")) {
776 if (const Type *PT = getCurrentThisType().getTypePtrOrNull())
777 FoundDecl = PT->getPointeeType()->getAsTagDecl();
779 LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
781 if (LookupName(BaseResult, getCurScope()) && BaseResult.isSingleResult())
782 FoundDecl = BaseResult.getFoundDecl();
788 for (StringRef NextMember : Members) {
789 const RecordType *RT = nullptr;
790 if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
791 RT = VD->getType()->getAs<RecordType>();
792 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
793 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
794 // MS InlineAsm often uses struct pointer aliases as a base
795 QualType QT = TD->getUnderlyingType();
796 if (const auto *PT = QT->getAs<PointerType>())
797 QT = PT->getPointeeType();
798 RT = QT->getAs<RecordType>();
799 } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
800 RT = TD->getTypeForDecl()->getAs<RecordType>();
801 else if (FieldDecl *TD = dyn_cast<FieldDecl>(FoundDecl))
802 RT = TD->getType()->getAs<RecordType>();
806 if (RequireCompleteType(AsmLoc, QualType(RT, 0),
807 diag::err_asm_incomplete_type))
810 LookupResult FieldResult(*this, &Context.Idents.get(NextMember),
811 SourceLocation(), LookupMemberName);
813 if (!LookupQualifiedName(FieldResult, RT->getDecl()))
816 if (!FieldResult.isSingleResult())
818 FoundDecl = FieldResult.getFoundDecl();
820 // FIXME: Handle IndirectFieldDecl?
821 FieldDecl *FD = dyn_cast<FieldDecl>(FoundDecl);
825 const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
826 unsigned i = FD->getFieldIndex();
827 CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
828 Offset += (unsigned)Result.getQuantity();
835 Sema::LookupInlineAsmVarDeclField(Expr *E, StringRef Member,
836 SourceLocation AsmLoc) {
838 QualType T = E->getType();
839 if (T->isDependentType()) {
840 DeclarationNameInfo NameInfo;
841 NameInfo.setLoc(AsmLoc);
842 NameInfo.setName(&Context.Idents.get(Member));
843 return CXXDependentScopeMemberExpr::Create(
844 Context, E, T, /*IsArrow=*/false, AsmLoc, NestedNameSpecifierLoc(),
846 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, /*TemplateArgs=*/nullptr);
849 const RecordType *RT = T->getAs<RecordType>();
850 // FIXME: Diagnose this as field access into a scalar type.
854 LookupResult FieldResult(*this, &Context.Idents.get(Member), AsmLoc,
857 if (!LookupQualifiedName(FieldResult, RT->getDecl()))
860 // Only normal and indirect field results will work.
861 ValueDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
863 FD = dyn_cast<IndirectFieldDecl>(FieldResult.getFoundDecl());
867 // Make an Expr to thread through OpDecl.
868 ExprResult Result = BuildMemberReferenceExpr(
869 E, E->getType(), AsmLoc, /*IsArrow=*/false, CXXScopeSpec(),
870 SourceLocation(), nullptr, FieldResult, nullptr, nullptr);
875 StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
876 ArrayRef<Token> AsmToks,
878 unsigned NumOutputs, unsigned NumInputs,
879 ArrayRef<StringRef> Constraints,
880 ArrayRef<StringRef> Clobbers,
881 ArrayRef<Expr*> Exprs,
882 SourceLocation EndLoc) {
883 bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
884 setFunctionHasBranchProtectedScope();
886 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
887 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
888 Constraints, Exprs, AsmString,
893 LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
894 SourceLocation Location,
896 LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
899 if (Label->isMSAsmLabel()) {
900 // If we have previously created this label implicitly, mark it as used.
901 Label->markUsed(Context);
903 // Otherwise, insert it, but only resolve it if we have seen the label itself.
904 std::string InternalName;
905 llvm::raw_string_ostream OS(InternalName);
906 // Create an internal name for the label. The name should not be a valid
907 // mangled name, and should be unique. We use a dot to make the name an
908 // invalid mangled name. We use LLVM's inline asm ${:uid} escape so that a
909 // unique label is generated each time this blob is emitted, even after
911 OS << "__MSASMLABEL_.${:uid}__";
912 for (char C : ExternalLabelName) {
914 // We escape '$' in asm strings by replacing it with "$$"
918 Label->setMSAsmLabel(OS.str());
921 // The label might have been created implicitly from a previously encountered
922 // goto statement. So, for both newly created and looked up labels, we mark
924 Label->setMSAsmLabelResolved();
926 // Adjust their location for being able to generate accurate diagnostics.
927 Label->setLocation(Location);