1 //===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for inline asm statements.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/RecordLayout.h"
16 #include "clang/AST/TypeLoc.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Lex/Preprocessor.h"
19 #include "clang/Sema/Initialization.h"
20 #include "clang/Sema/Lookup.h"
21 #include "clang/Sema/Scope.h"
22 #include "clang/Sema/ScopeInfo.h"
23 #include "llvm/ADT/ArrayRef.h"
24 #include "llvm/ADT/BitVector.h"
25 #include "llvm/MC/MCParser/MCAsmParser.h"
26 using namespace clang;
29 /// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
30 /// ignore "noop" casts in places where an lvalue is required by an inline asm.
31 /// We emulate this behavior when -fheinous-gnu-extensions is specified, but
32 /// provide a strong guidance to not use it.
34 /// This method checks to see if the argument is an acceptable l-value and
35 /// returns false if it is a case we can handle.
36 static bool CheckAsmLValue(const Expr *E, Sema &S) {
37 // Type dependent expressions will be checked during instantiation.
38 if (E->isTypeDependent())
42 return false; // Cool, this is an lvalue.
44 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
45 // are supposed to allow.
46 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
47 if (E != E2 && E2->isLValue()) {
48 if (!S.getLangOpts().HeinousExtensions)
49 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
50 << E->getSourceRange();
52 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
53 << E->getSourceRange();
54 // Accept, even if we emitted an error diagnostic.
58 // None of the above, just randomly invalid non-lvalue.
62 /// isOperandMentioned - Return true if the specified operand # is mentioned
63 /// anywhere in the decomposed asm string.
64 static bool isOperandMentioned(unsigned OpNo,
65 ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
66 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
67 const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
68 if (!Piece.isOperand()) continue;
70 // If this is a reference to the input and if the input was the smaller
71 // one, then we have to reject this asm.
72 if (Piece.getOperandNo() == OpNo)
78 static bool CheckNakedParmReference(Expr *E, Sema &S) {
79 FunctionDecl *Func = dyn_cast<FunctionDecl>(S.CurContext);
82 if (!Func->hasAttr<NakedAttr>())
85 SmallVector<Expr*, 4> WorkList;
86 WorkList.push_back(E);
87 while (WorkList.size()) {
88 Expr *E = WorkList.pop_back_val();
89 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
90 if (isa<ParmVarDecl>(DRE->getDecl())) {
91 S.Diag(DRE->getLocStart(), diag::err_asm_naked_parm_ref);
92 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
96 for (Stmt *Child : E->children()) {
97 if (Expr *E = dyn_cast_or_null<Expr>(Child))
98 WorkList.push_back(E);
104 StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
105 bool IsVolatile, unsigned NumOutputs,
106 unsigned NumInputs, IdentifierInfo **Names,
107 MultiExprArg constraints, MultiExprArg Exprs,
108 Expr *asmString, MultiExprArg clobbers,
109 SourceLocation RParenLoc) {
110 unsigned NumClobbers = clobbers.size();
111 StringLiteral **Constraints =
112 reinterpret_cast<StringLiteral**>(constraints.data());
113 StringLiteral *AsmString = cast<StringLiteral>(asmString);
114 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
116 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
118 // The parser verifies that there is a string literal here.
119 assert(AsmString->isAscii());
121 for (unsigned i = 0; i != NumOutputs; i++) {
122 StringLiteral *Literal = Constraints[i];
123 assert(Literal->isAscii());
125 StringRef OutputName;
127 OutputName = Names[i]->getName();
129 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
130 if (!Context.getTargetInfo().validateOutputConstraint(Info))
131 return StmtError(Diag(Literal->getLocStart(),
132 diag::err_asm_invalid_output_constraint)
133 << Info.getConstraintStr());
135 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
140 // Check that the output exprs are valid lvalues.
141 Expr *OutputExpr = Exprs[i];
143 // Referring to parameters is not allowed in naked functions.
144 if (CheckNakedParmReference(OutputExpr, *this))
147 OutputConstraintInfos.push_back(Info);
149 // If this is dependent, just continue.
150 if (OutputExpr->isTypeDependent())
153 Expr::isModifiableLvalueResult IsLV =
154 OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr);
156 case Expr::MLV_Valid:
157 // Cool, this is an lvalue.
159 case Expr::MLV_ArrayType:
162 case Expr::MLV_LValueCast: {
163 const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context);
164 if (!getLangOpts().HeinousExtensions) {
165 Diag(LVal->getLocStart(), diag::err_invalid_asm_cast_lvalue)
166 << OutputExpr->getSourceRange();
168 Diag(LVal->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
169 << OutputExpr->getSourceRange();
171 // Accept, even if we emitted an error diagnostic.
174 case Expr::MLV_IncompleteType:
175 case Expr::MLV_IncompleteVoidType:
176 if (RequireCompleteType(OutputExpr->getLocStart(), Exprs[i]->getType(),
177 diag::err_dereference_incomplete_type))
180 return StmtError(Diag(OutputExpr->getLocStart(),
181 diag::err_asm_invalid_lvalue_in_output)
182 << OutputExpr->getSourceRange());
185 unsigned Size = Context.getTypeSize(OutputExpr->getType());
186 if (!Context.getTargetInfo().validateOutputSize(Literal->getString(),
188 return StmtError(Diag(OutputExpr->getLocStart(),
189 diag::err_asm_invalid_output_size)
190 << Info.getConstraintStr());
193 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
195 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
196 StringLiteral *Literal = Constraints[i];
197 assert(Literal->isAscii());
201 InputName = Names[i]->getName();
203 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
204 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
206 return StmtError(Diag(Literal->getLocStart(),
207 diag::err_asm_invalid_input_constraint)
208 << Info.getConstraintStr());
211 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
216 Expr *InputExpr = Exprs[i];
218 // Referring to parameters is not allowed in naked functions.
219 if (CheckNakedParmReference(InputExpr, *this))
222 // Only allow void types for memory constraints.
223 if (Info.allowsMemory() && !Info.allowsRegister()) {
224 if (CheckAsmLValue(InputExpr, *this))
225 return StmtError(Diag(InputExpr->getLocStart(),
226 diag::err_asm_invalid_lvalue_in_input)
227 << Info.getConstraintStr()
228 << InputExpr->getSourceRange());
229 } else if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
231 if (!InputExpr->EvaluateAsInt(Result, Context))
233 Diag(InputExpr->getLocStart(), diag::err_asm_immediate_expected)
234 << Info.getConstraintStr() << InputExpr->getSourceRange());
235 if (Result.slt(Info.getImmConstantMin()) ||
236 Result.sgt(Info.getImmConstantMax()))
237 return StmtError(Diag(InputExpr->getLocStart(),
238 diag::err_invalid_asm_value_for_constraint)
239 << Result.toString(10) << Info.getConstraintStr()
240 << InputExpr->getSourceRange());
243 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
244 if (Result.isInvalid())
247 Exprs[i] = Result.get();
250 if (Info.allowsRegister()) {
251 if (InputExpr->getType()->isVoidType()) {
252 return StmtError(Diag(InputExpr->getLocStart(),
253 diag::err_asm_invalid_type_in_input)
254 << InputExpr->getType() << Info.getConstraintStr()
255 << InputExpr->getSourceRange());
259 InputConstraintInfos.push_back(Info);
261 const Type *Ty = Exprs[i]->getType().getTypePtr();
262 if (Ty->isDependentType())
265 if (!Ty->isVoidType() || !Info.allowsMemory())
266 if (RequireCompleteType(InputExpr->getLocStart(), Exprs[i]->getType(),
267 diag::err_dereference_incomplete_type))
270 unsigned Size = Context.getTypeSize(Ty);
271 if (!Context.getTargetInfo().validateInputSize(Literal->getString(),
273 return StmtError(Diag(InputExpr->getLocStart(),
274 diag::err_asm_invalid_input_size)
275 << Info.getConstraintStr());
278 // Check that the clobbers are valid.
279 for (unsigned i = 0; i != NumClobbers; i++) {
280 StringLiteral *Literal = Clobbers[i];
281 assert(Literal->isAscii());
283 StringRef Clobber = Literal->getString();
285 if (!Context.getTargetInfo().isValidClobber(Clobber))
286 return StmtError(Diag(Literal->getLocStart(),
287 diag::err_asm_unknown_register_name) << Clobber);
291 new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
292 NumInputs, Names, Constraints, Exprs.data(),
293 AsmString, NumClobbers, Clobbers, RParenLoc);
294 // Validate the asm string, ensuring it makes sense given the operands we
296 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
298 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
299 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
300 << AsmString->getSourceRange();
304 // Validate constraints and modifiers.
305 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
306 GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
307 if (!Piece.isOperand()) continue;
309 // Look for the correct constraint index.
311 unsigned ConstraintIdx = 0;
312 for (unsigned i = 0, e = NS->getNumOutputs(); i != e; ++i, ++ConstraintIdx) {
313 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
314 if (Idx == Piece.getOperandNo())
318 if (Info.isReadWrite()) {
319 if (Idx == Piece.getOperandNo())
325 for (unsigned i = 0, e = NS->getNumInputs(); i != e; ++i, ++ConstraintIdx) {
326 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
327 if (Idx == Piece.getOperandNo())
331 if (Info.isReadWrite()) {
332 if (Idx == Piece.getOperandNo())
338 // Now that we have the right indexes go ahead and check.
339 StringLiteral *Literal = Constraints[ConstraintIdx];
340 const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
341 if (Ty->isDependentType() || Ty->isIncompleteType())
344 unsigned Size = Context.getTypeSize(Ty);
345 std::string SuggestedModifier;
346 if (!Context.getTargetInfo().validateConstraintModifier(
347 Literal->getString(), Piece.getModifier(), Size,
348 SuggestedModifier)) {
349 Diag(Exprs[ConstraintIdx]->getLocStart(),
350 diag::warn_asm_mismatched_size_modifier);
352 if (!SuggestedModifier.empty()) {
353 auto B = Diag(Piece.getRange().getBegin(),
354 diag::note_asm_missing_constraint_modifier)
355 << SuggestedModifier;
356 SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
357 B.AddFixItHint(FixItHint::CreateReplacement(Piece.getRange(),
363 // Validate tied input operands for type mismatches.
364 unsigned NumAlternatives = ~0U;
365 for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
366 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
367 StringRef ConstraintStr = Info.getConstraintStr();
368 unsigned AltCount = ConstraintStr.count(',') + 1;
369 if (NumAlternatives == ~0U)
370 NumAlternatives = AltCount;
371 else if (NumAlternatives != AltCount)
372 return StmtError(Diag(NS->getOutputExpr(i)->getLocStart(),
373 diag::err_asm_unexpected_constraint_alternatives)
374 << NumAlternatives << AltCount);
376 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
377 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
378 StringRef ConstraintStr = Info.getConstraintStr();
379 unsigned AltCount = ConstraintStr.count(',') + 1;
380 if (NumAlternatives == ~0U)
381 NumAlternatives = AltCount;
382 else if (NumAlternatives != AltCount)
383 return StmtError(Diag(NS->getInputExpr(i)->getLocStart(),
384 diag::err_asm_unexpected_constraint_alternatives)
385 << NumAlternatives << AltCount);
387 // If this is a tied constraint, verify that the output and input have
388 // either exactly the same type, or that they are int/ptr operands with the
389 // same size (int/long, int*/long, are ok etc).
390 if (!Info.hasTiedOperand()) continue;
392 unsigned TiedTo = Info.getTiedOperand();
393 unsigned InputOpNo = i+NumOutputs;
394 Expr *OutputExpr = Exprs[TiedTo];
395 Expr *InputExpr = Exprs[InputOpNo];
397 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
400 QualType InTy = InputExpr->getType();
401 QualType OutTy = OutputExpr->getType();
402 if (Context.hasSameType(InTy, OutTy))
403 continue; // All types can be tied to themselves.
405 // Decide if the input and output are in the same domain (integer/ptr or
408 AD_Int, AD_FP, AD_Other
409 } InputDomain, OutputDomain;
411 if (InTy->isIntegerType() || InTy->isPointerType())
412 InputDomain = AD_Int;
413 else if (InTy->isRealFloatingType())
416 InputDomain = AD_Other;
418 if (OutTy->isIntegerType() || OutTy->isPointerType())
419 OutputDomain = AD_Int;
420 else if (OutTy->isRealFloatingType())
421 OutputDomain = AD_FP;
423 OutputDomain = AD_Other;
425 // They are ok if they are the same size and in the same domain. This
426 // allows tying things like:
428 // void* to int if they are the same size.
429 // double to long double if they are the same size.
431 uint64_t OutSize = Context.getTypeSize(OutTy);
432 uint64_t InSize = Context.getTypeSize(InTy);
433 if (OutSize == InSize && InputDomain == OutputDomain &&
434 InputDomain != AD_Other)
437 // If the smaller input/output operand is not mentioned in the asm string,
438 // then we can promote the smaller one to a larger input and the asm string
440 bool SmallerValueMentioned = false;
442 // If this is a reference to the input and if the input was the smaller
443 // one, then we have to reject this asm.
444 if (isOperandMentioned(InputOpNo, Pieces)) {
445 // This is a use in the asm string of the smaller operand. Since we
446 // codegen this by promoting to a wider value, the asm will get printed
448 SmallerValueMentioned |= InSize < OutSize;
450 if (isOperandMentioned(TiedTo, Pieces)) {
451 // If this is a reference to the output, and if the output is the larger
452 // value, then it's ok because we'll promote the input to the larger type.
453 SmallerValueMentioned |= OutSize < InSize;
456 // If the smaller value wasn't mentioned in the asm string, and if the
457 // output was a register, just extend the shorter one to the size of the
459 if (!SmallerValueMentioned && InputDomain != AD_Other &&
460 OutputConstraintInfos[TiedTo].allowsRegister())
463 // Either both of the operands were mentioned or the smaller one was
464 // mentioned. One more special case that we'll allow: if the tied input is
465 // integer, unmentioned, and is a constant, then we'll allow truncating it
466 // down to the size of the destination.
467 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
468 !isOperandMentioned(InputOpNo, Pieces) &&
469 InputExpr->isEvaluatable(Context)) {
471 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
472 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
473 Exprs[InputOpNo] = InputExpr;
474 NS->setInputExpr(i, InputExpr);
478 Diag(InputExpr->getLocStart(),
479 diag::err_asm_tying_incompatible_types)
480 << InTy << OutTy << OutputExpr->getSourceRange()
481 << InputExpr->getSourceRange();
488 ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
489 SourceLocation TemplateKWLoc,
491 llvm::InlineAsmIdentifierInfo &Info,
492 bool IsUnevaluatedContext) {
495 if (IsUnevaluatedContext)
496 PushExpressionEvaluationContext(UnevaluatedAbstract,
497 ReuseLambdaContextDecl);
499 ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
500 /*trailing lparen*/ false,
501 /*is & operand*/ false,
502 /*CorrectionCandidateCallback=*/nullptr,
503 /*IsInlineAsmIdentifier=*/ true);
505 if (IsUnevaluatedContext)
506 PopExpressionEvaluationContext();
508 if (!Result.isUsable()) return Result;
510 Result = CheckPlaceholderExpr(Result.get());
511 if (!Result.isUsable()) return Result;
513 // Referring to parameters is not allowed in naked functions.
514 if (CheckNakedParmReference(Result.get(), *this))
517 QualType T = Result.get()->getType();
519 // For now, reject dependent types.
520 if (T->isDependentType()) {
521 Diag(Id.getLocStart(), diag::err_asm_incomplete_type) << T;
525 // Any sort of function type is fine.
526 if (T->isFunctionType()) {
530 // Otherwise, it needs to be a complete type.
531 if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
535 // Compute the type size (and array length if applicable?).
536 Info.Type = Info.Size = Context.getTypeSizeInChars(T).getQuantity();
537 if (T->isArrayType()) {
538 const ArrayType *ATy = Context.getAsArrayType(T);
539 Info.Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
540 Info.Length = Info.Size / Info.Type;
543 // We can work with the expression as long as it's not an r-value.
544 if (!Result.get()->isRValue())
545 Info.IsVarDecl = true;
550 bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
551 unsigned &Offset, SourceLocation AsmLoc) {
553 LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
556 if (!LookupName(BaseResult, getCurScope()))
559 if (!BaseResult.isSingleResult())
562 const RecordType *RT = nullptr;
563 NamedDecl *FoundDecl = BaseResult.getFoundDecl();
564 if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
565 RT = VD->getType()->getAs<RecordType>();
566 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
567 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
568 RT = TD->getUnderlyingType()->getAs<RecordType>();
569 } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
570 RT = TD->getTypeForDecl()->getAs<RecordType>();
574 if (RequireCompleteType(AsmLoc, QualType(RT, 0), 0))
577 LookupResult FieldResult(*this, &Context.Idents.get(Member), SourceLocation(),
580 if (!LookupQualifiedName(FieldResult, RT->getDecl()))
583 // FIXME: Handle IndirectFieldDecl?
584 FieldDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
588 const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
589 unsigned i = FD->getFieldIndex();
590 CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
591 Offset = (unsigned)Result.getQuantity();
596 StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
597 ArrayRef<Token> AsmToks,
599 unsigned NumOutputs, unsigned NumInputs,
600 ArrayRef<StringRef> Constraints,
601 ArrayRef<StringRef> Clobbers,
602 ArrayRef<Expr*> Exprs,
603 SourceLocation EndLoc) {
604 bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
605 getCurFunction()->setHasBranchProtectedScope();
607 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
608 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
609 Constraints, Exprs, AsmString,
614 LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
615 SourceLocation Location,
617 LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
620 if (Label->isMSAsmLabel()) {
621 // If we have previously created this label implicitly, mark it as used.
622 Label->markUsed(Context);
624 // Otherwise, insert it, but only resolve it if we have seen the label itself.
625 std::string InternalName;
626 llvm::raw_string_ostream OS(InternalName);
627 // Create an internal name for the label. The name should not be a valid mangled
628 // name, and should be unique. We use a dot to make the name an invalid mangled
630 OS << "__MSASMLABEL_." << MSAsmLabelNameCounter++ << "__" << ExternalLabelName;
631 Label->setMSAsmLabel(OS.str());
634 // The label might have been created implicitly from a previously encountered
635 // goto statement. So, for both newly created and looked up labels, we mark
637 Label->setMSAsmLabelResolved();
639 // Adjust their location for being able to generate accurate diagnostics.
640 Label->setLocation(Location);