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"
14 #include "clang/AST/GlobalDecl.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 "clang/Sema/SemaInternal.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/StringSet.h"
26 #include "llvm/MC/MCParser/MCAsmParser.h"
27 using namespace clang;
28 using namespace sema;
29
30 /// Remove the upper-level LValueToRValue cast from an expression.
removeLValueToRValueCast(Expr * E)31 static void removeLValueToRValueCast(Expr *E) {
32 Expr *Parent = E;
33 Expr *ExprUnderCast = nullptr;
34 SmallVector<Expr *, 8> ParentsToUpdate;
35
36 while (true) {
37 ParentsToUpdate.push_back(Parent);
38 if (auto *ParenE = dyn_cast<ParenExpr>(Parent)) {
39 Parent = ParenE->getSubExpr();
40 continue;
41 }
42
43 Expr *Child = nullptr;
44 CastExpr *ParentCast = dyn_cast<CastExpr>(Parent);
45 if (ParentCast)
46 Child = ParentCast->getSubExpr();
47 else
48 return;
49
50 if (auto *CastE = dyn_cast<CastExpr>(Child))
51 if (CastE->getCastKind() == CK_LValueToRValue) {
52 ExprUnderCast = CastE->getSubExpr();
53 // LValueToRValue cast inside GCCAsmStmt requires an explicit cast.
54 ParentCast->setSubExpr(ExprUnderCast);
55 break;
56 }
57 Parent = Child;
58 }
59
60 // Update parent expressions to have same ValueType as the underlying.
61 assert(ExprUnderCast &&
62 "Should be reachable only if LValueToRValue cast was found!");
63 auto ValueKind = ExprUnderCast->getValueKind();
64 for (Expr *E : ParentsToUpdate)
65 E->setValueKind(ValueKind);
66 }
67
68 /// Emit a warning about usage of "noop"-like casts for lvalues (GNU extension)
69 /// and fix the argument with removing LValueToRValue cast from the expression.
emitAndFixInvalidAsmCastLValue(const Expr * LVal,Expr * BadArgument,Sema & S)70 static void emitAndFixInvalidAsmCastLValue(const Expr *LVal, Expr *BadArgument,
71 Sema &S) {
72 if (!S.getLangOpts().HeinousExtensions) {
73 S.Diag(LVal->getBeginLoc(), diag::err_invalid_asm_cast_lvalue)
74 << BadArgument->getSourceRange();
75 } else {
76 S.Diag(LVal->getBeginLoc(), diag::warn_invalid_asm_cast_lvalue)
77 << BadArgument->getSourceRange();
78 }
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.
CheckAsmLValue(Expr * E,Sema & S)89 static 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()) {
101 emitAndFixInvalidAsmCastLValue(E2, E, S);
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.
112 static bool
isOperandMentioned(unsigned OpNo,ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces)113 isOperandMentioned(unsigned OpNo,
114 ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
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
CheckNakedParmReference(Expr * E,Sema & S)128 static 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.
checkExprMemoryConstraintCompat(Sema & S,Expr * E,TargetInfo::ConstraintInfo & Info,bool is_input_expr)161 static bool checkExprMemoryConstraintCompat(Sema &S, Expr *E,
162 TargetInfo::ConstraintInfo &Info,
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 ""
extractRegisterName(const Expr * Expression,const TargetInfo & Target)192 static 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
210 static SourceLocation
getClobberConflictLocation(MultiExprArg Exprs,StringLiteral ** Constraints,StringLiteral ** Clobbers,int NumClobbers,unsigned NumLabels,const TargetInfo & Target,ASTContext & Cont)211 getClobberConflictLocation(MultiExprArg Exprs, StringLiteral **Constraints,
212 StringLiteral **Clobbers, int NumClobbers,
213 unsigned NumLabels,
214 const TargetInfo &Target, ASTContext &Cont) {
215 llvm::StringSet<> InOutVars;
216 // Collect all the input and output registers from the extended asm
217 // statement in order to check for conflicts with the clobber list
218 for (unsigned int i = 0; i < Exprs.size() - NumLabels; ++i) {
219 StringRef Constraint = Constraints[i]->getString();
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 StringRef Clobber = Clobbers[i]->getString();
229 // We only check registers, therefore we don't check cc and memory
230 // clobbers
231 if (Clobber == "cc" || Clobber == "memory" || Clobber == "unwind")
232 continue;
233 Clobber = Target.getNormalizedGCCRegisterName(Clobber, true);
234 // Go over the output's registers we collected
235 if (InOutVars.count(Clobber))
236 return Clobbers[i]->getBeginLoc();
237 }
238 return SourceLocation();
239 }
240
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)241 StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
242 bool IsVolatile, unsigned NumOutputs,
243 unsigned NumInputs, IdentifierInfo **Names,
244 MultiExprArg constraints, MultiExprArg Exprs,
245 Expr *asmString, MultiExprArg clobbers,
246 unsigned NumLabels,
247 SourceLocation RParenLoc) {
248 unsigned NumClobbers = clobbers.size();
249 StringLiteral **Constraints =
250 reinterpret_cast<StringLiteral**>(constraints.data());
251 StringLiteral *AsmString = cast<StringLiteral>(asmString);
252 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
253
254 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
255
256 // The parser verifies that there is a string literal here.
257 assert(AsmString->isOrdinary());
258
259 FunctionDecl *FD = dyn_cast<FunctionDecl>(getCurLexicalContext());
260 llvm::StringMap<bool> FeatureMap;
261 Context.getFunctionFeatureMap(FeatureMap, FD);
262
263 for (unsigned i = 0; i != NumOutputs; i++) {
264 StringLiteral *Literal = Constraints[i];
265 assert(Literal->isOrdinary());
266
267 StringRef OutputName;
268 if (Names[i])
269 OutputName = Names[i]->getName();
270
271 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
272 if (!Context.getTargetInfo().validateOutputConstraint(Info)) {
273 targetDiag(Literal->getBeginLoc(),
274 diag::err_asm_invalid_output_constraint)
275 << Info.getConstraintStr();
276 return new (Context)
277 GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
278 NumInputs, Names, Constraints, Exprs.data(), AsmString,
279 NumClobbers, Clobbers, NumLabels, RParenLoc);
280 }
281
282 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
283 if (ER.isInvalid())
284 return StmtError();
285 Exprs[i] = ER.get();
286
287 // Check that the output exprs are valid lvalues.
288 Expr *OutputExpr = Exprs[i];
289
290 // Referring to parameters is not allowed in naked functions.
291 if (CheckNakedParmReference(OutputExpr, *this))
292 return StmtError();
293
294 // Check that the output expression is compatible with memory constraint.
295 if (Info.allowsMemory() &&
296 checkExprMemoryConstraintCompat(*this, OutputExpr, Info, false))
297 return StmtError();
298
299 // Disallow bit-precise integer types, since the backends tend to have
300 // difficulties with abnormal sizes.
301 if (OutputExpr->getType()->isBitIntType())
302 return StmtError(
303 Diag(OutputExpr->getBeginLoc(), diag::err_asm_invalid_type)
304 << OutputExpr->getType() << 0 /*Input*/
305 << OutputExpr->getSourceRange());
306
307 OutputConstraintInfos.push_back(Info);
308
309 // If this is dependent, just continue.
310 if (OutputExpr->isTypeDependent())
311 continue;
312
313 Expr::isModifiableLvalueResult IsLV =
314 OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr);
315 switch (IsLV) {
316 case Expr::MLV_Valid:
317 // Cool, this is an lvalue.
318 break;
319 case Expr::MLV_ArrayType:
320 // This is OK too.
321 break;
322 case Expr::MLV_LValueCast: {
323 const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context);
324 emitAndFixInvalidAsmCastLValue(LVal, OutputExpr, *this);
325 // Accept, even if we emitted an error diagnostic.
326 break;
327 }
328 case Expr::MLV_IncompleteType:
329 case Expr::MLV_IncompleteVoidType:
330 if (RequireCompleteType(OutputExpr->getBeginLoc(), Exprs[i]->getType(),
331 diag::err_dereference_incomplete_type))
332 return StmtError();
333 LLVM_FALLTHROUGH;
334 default:
335 return StmtError(Diag(OutputExpr->getBeginLoc(),
336 diag::err_asm_invalid_lvalue_in_output)
337 << OutputExpr->getSourceRange());
338 }
339
340 unsigned Size = Context.getTypeSize(OutputExpr->getType());
341 if (!Context.getTargetInfo().validateOutputSize(
342 FeatureMap, Literal->getString(), Size)) {
343 targetDiag(OutputExpr->getBeginLoc(), diag::err_asm_invalid_output_size)
344 << Info.getConstraintStr();
345 return new (Context)
346 GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
347 NumInputs, Names, Constraints, Exprs.data(), AsmString,
348 NumClobbers, Clobbers, NumLabels, RParenLoc);
349 }
350 }
351
352 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
353
354 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
355 StringLiteral *Literal = Constraints[i];
356 assert(Literal->isOrdinary());
357
358 StringRef InputName;
359 if (Names[i])
360 InputName = Names[i]->getName();
361
362 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
363 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos,
364 Info)) {
365 targetDiag(Literal->getBeginLoc(), diag::err_asm_invalid_input_constraint)
366 << Info.getConstraintStr();
367 return new (Context)
368 GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
369 NumInputs, Names, Constraints, Exprs.data(), AsmString,
370 NumClobbers, Clobbers, NumLabels, RParenLoc);
371 }
372
373 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
374 if (ER.isInvalid())
375 return StmtError();
376 Exprs[i] = ER.get();
377
378 Expr *InputExpr = Exprs[i];
379
380 // Referring to parameters is not allowed in naked functions.
381 if (CheckNakedParmReference(InputExpr, *this))
382 return StmtError();
383
384 // Check that the input expression is compatible with memory constraint.
385 if (Info.allowsMemory() &&
386 checkExprMemoryConstraintCompat(*this, InputExpr, Info, true))
387 return StmtError();
388
389 // Only allow void types for memory constraints.
390 if (Info.allowsMemory() && !Info.allowsRegister()) {
391 if (CheckAsmLValue(InputExpr, *this))
392 return StmtError(Diag(InputExpr->getBeginLoc(),
393 diag::err_asm_invalid_lvalue_in_input)
394 << Info.getConstraintStr()
395 << InputExpr->getSourceRange());
396 } else {
397 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
398 if (Result.isInvalid())
399 return StmtError();
400
401 InputExpr = Exprs[i] = Result.get();
402
403 if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
404 if (!InputExpr->isValueDependent()) {
405 Expr::EvalResult EVResult;
406 if (InputExpr->EvaluateAsRValue(EVResult, Context, true)) {
407 // For compatibility with GCC, we also allow pointers that would be
408 // integral constant expressions if they were cast to int.
409 llvm::APSInt IntResult;
410 if (EVResult.Val.toIntegralConstant(IntResult, InputExpr->getType(),
411 Context))
412 if (!Info.isValidAsmImmediate(IntResult))
413 return StmtError(
414 Diag(InputExpr->getBeginLoc(),
415 diag::err_invalid_asm_value_for_constraint)
416 << toString(IntResult, 10) << Info.getConstraintStr()
417 << InputExpr->getSourceRange());
418 }
419 }
420 }
421 }
422
423 if (Info.allowsRegister()) {
424 if (InputExpr->getType()->isVoidType()) {
425 return StmtError(
426 Diag(InputExpr->getBeginLoc(), diag::err_asm_invalid_type_in_input)
427 << InputExpr->getType() << Info.getConstraintStr()
428 << InputExpr->getSourceRange());
429 }
430 }
431
432 if (InputExpr->getType()->isBitIntType())
433 return StmtError(
434 Diag(InputExpr->getBeginLoc(), diag::err_asm_invalid_type)
435 << InputExpr->getType() << 1 /*Output*/
436 << InputExpr->getSourceRange());
437
438 InputConstraintInfos.push_back(Info);
439
440 const Type *Ty = Exprs[i]->getType().getTypePtr();
441 if (Ty->isDependentType())
442 continue;
443
444 if (!Ty->isVoidType() || !Info.allowsMemory())
445 if (RequireCompleteType(InputExpr->getBeginLoc(), Exprs[i]->getType(),
446 diag::err_dereference_incomplete_type))
447 return StmtError();
448
449 unsigned Size = Context.getTypeSize(Ty);
450 if (!Context.getTargetInfo().validateInputSize(FeatureMap,
451 Literal->getString(), Size))
452 return targetDiag(InputExpr->getBeginLoc(),
453 diag::err_asm_invalid_input_size)
454 << Info.getConstraintStr();
455 }
456
457 Optional<SourceLocation> UnwindClobberLoc;
458
459 // Check that the clobbers are valid.
460 for (unsigned i = 0; i != NumClobbers; i++) {
461 StringLiteral *Literal = Clobbers[i];
462 assert(Literal->isOrdinary());
463
464 StringRef Clobber = Literal->getString();
465
466 if (!Context.getTargetInfo().isValidClobber(Clobber)) {
467 targetDiag(Literal->getBeginLoc(), diag::err_asm_unknown_register_name)
468 << Clobber;
469 return new (Context)
470 GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
471 NumInputs, Names, Constraints, Exprs.data(), AsmString,
472 NumClobbers, Clobbers, NumLabels, RParenLoc);
473 }
474
475 if (Clobber == "unwind") {
476 UnwindClobberLoc = Literal->getBeginLoc();
477 }
478 }
479
480 // Using unwind clobber and asm-goto together is not supported right now.
481 if (UnwindClobberLoc && NumLabels > 0) {
482 targetDiag(*UnwindClobberLoc, diag::err_asm_unwind_and_goto);
483 return new (Context)
484 GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs,
485 Names, Constraints, Exprs.data(), AsmString, NumClobbers,
486 Clobbers, NumLabels, RParenLoc);
487 }
488
489 GCCAsmStmt *NS =
490 new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
491 NumInputs, Names, Constraints, Exprs.data(),
492 AsmString, NumClobbers, Clobbers, NumLabels,
493 RParenLoc);
494 // Validate the asm string, ensuring it makes sense given the operands we
495 // have.
496 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
497 unsigned DiagOffs;
498 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
499 targetDiag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
500 << AsmString->getSourceRange();
501 return NS;
502 }
503
504 // Validate constraints and modifiers.
505 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
506 GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
507 if (!Piece.isOperand()) continue;
508
509 // Look for the correct constraint index.
510 unsigned ConstraintIdx = Piece.getOperandNo();
511 unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs();
512 // Labels are the last in the Exprs list.
513 if (NS->isAsmGoto() && ConstraintIdx >= NumOperands)
514 continue;
515 // Look for the (ConstraintIdx - NumOperands + 1)th constraint with
516 // modifier '+'.
517 if (ConstraintIdx >= NumOperands) {
518 unsigned I = 0, E = NS->getNumOutputs();
519
520 for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I)
521 if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) {
522 ConstraintIdx = I;
523 break;
524 }
525
526 assert(I != E && "Invalid operand number should have been caught in "
527 " AnalyzeAsmString");
528 }
529
530 // Now that we have the right indexes go ahead and check.
531 StringLiteral *Literal = Constraints[ConstraintIdx];
532 const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
533 if (Ty->isDependentType() || Ty->isIncompleteType())
534 continue;
535
536 unsigned Size = Context.getTypeSize(Ty);
537 std::string SuggestedModifier;
538 if (!Context.getTargetInfo().validateConstraintModifier(
539 Literal->getString(), Piece.getModifier(), Size,
540 SuggestedModifier)) {
541 targetDiag(Exprs[ConstraintIdx]->getBeginLoc(),
542 diag::warn_asm_mismatched_size_modifier);
543
544 if (!SuggestedModifier.empty()) {
545 auto B = targetDiag(Piece.getRange().getBegin(),
546 diag::note_asm_missing_constraint_modifier)
547 << SuggestedModifier;
548 SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
549 B << FixItHint::CreateReplacement(Piece.getRange(), SuggestedModifier);
550 }
551 }
552 }
553
554 // Validate tied input operands for type mismatches.
555 unsigned NumAlternatives = ~0U;
556 for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
557 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
558 StringRef ConstraintStr = Info.getConstraintStr();
559 unsigned AltCount = ConstraintStr.count(',') + 1;
560 if (NumAlternatives == ~0U) {
561 NumAlternatives = AltCount;
562 } else if (NumAlternatives != AltCount) {
563 targetDiag(NS->getOutputExpr(i)->getBeginLoc(),
564 diag::err_asm_unexpected_constraint_alternatives)
565 << NumAlternatives << AltCount;
566 return NS;
567 }
568 }
569 SmallVector<size_t, 4> InputMatchedToOutput(OutputConstraintInfos.size(),
570 ~0U);
571 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
572 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
573 StringRef ConstraintStr = Info.getConstraintStr();
574 unsigned AltCount = ConstraintStr.count(',') + 1;
575 if (NumAlternatives == ~0U) {
576 NumAlternatives = AltCount;
577 } else if (NumAlternatives != AltCount) {
578 targetDiag(NS->getInputExpr(i)->getBeginLoc(),
579 diag::err_asm_unexpected_constraint_alternatives)
580 << NumAlternatives << AltCount;
581 return NS;
582 }
583
584 // If this is a tied constraint, verify that the output and input have
585 // either exactly the same type, or that they are int/ptr operands with the
586 // same size (int/long, int*/long, are ok etc).
587 if (!Info.hasTiedOperand()) continue;
588
589 unsigned TiedTo = Info.getTiedOperand();
590 unsigned InputOpNo = i+NumOutputs;
591 Expr *OutputExpr = Exprs[TiedTo];
592 Expr *InputExpr = Exprs[InputOpNo];
593
594 // Make sure no more than one input constraint matches each output.
595 assert(TiedTo < InputMatchedToOutput.size() && "TiedTo value out of range");
596 if (InputMatchedToOutput[TiedTo] != ~0U) {
597 targetDiag(NS->getInputExpr(i)->getBeginLoc(),
598 diag::err_asm_input_duplicate_match)
599 << TiedTo;
600 targetDiag(NS->getInputExpr(InputMatchedToOutput[TiedTo])->getBeginLoc(),
601 diag::note_asm_input_duplicate_first)
602 << TiedTo;
603 return NS;
604 }
605 InputMatchedToOutput[TiedTo] = i;
606
607 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
608 continue;
609
610 QualType InTy = InputExpr->getType();
611 QualType OutTy = OutputExpr->getType();
612 if (Context.hasSameType(InTy, OutTy))
613 continue; // All types can be tied to themselves.
614
615 // Decide if the input and output are in the same domain (integer/ptr or
616 // floating point.
617 enum AsmDomain {
618 AD_Int, AD_FP, AD_Other
619 } InputDomain, OutputDomain;
620
621 if (InTy->isIntegerType() || InTy->isPointerType())
622 InputDomain = AD_Int;
623 else if (InTy->isRealFloatingType())
624 InputDomain = AD_FP;
625 else
626 InputDomain = AD_Other;
627
628 if (OutTy->isIntegerType() || OutTy->isPointerType())
629 OutputDomain = AD_Int;
630 else if (OutTy->isRealFloatingType())
631 OutputDomain = AD_FP;
632 else
633 OutputDomain = AD_Other;
634
635 // They are ok if they are the same size and in the same domain. This
636 // allows tying things like:
637 // void* to int*
638 // void* to int if they are the same size.
639 // double to long double if they are the same size.
640 //
641 uint64_t OutSize = Context.getTypeSize(OutTy);
642 uint64_t InSize = Context.getTypeSize(InTy);
643 if (OutSize == InSize && InputDomain == OutputDomain &&
644 InputDomain != AD_Other)
645 continue;
646
647 // If the smaller input/output operand is not mentioned in the asm string,
648 // then we can promote the smaller one to a larger input and the asm string
649 // won't notice.
650 bool SmallerValueMentioned = false;
651
652 // If this is a reference to the input and if the input was the smaller
653 // one, then we have to reject this asm.
654 if (isOperandMentioned(InputOpNo, Pieces)) {
655 // This is a use in the asm string of the smaller operand. Since we
656 // codegen this by promoting to a wider value, the asm will get printed
657 // "wrong".
658 SmallerValueMentioned |= InSize < OutSize;
659 }
660 if (isOperandMentioned(TiedTo, Pieces)) {
661 // If this is a reference to the output, and if the output is the larger
662 // value, then it's ok because we'll promote the input to the larger type.
663 SmallerValueMentioned |= OutSize < InSize;
664 }
665
666 // If the smaller value wasn't mentioned in the asm string, and if the
667 // output was a register, just extend the shorter one to the size of the
668 // larger one.
669 if (!SmallerValueMentioned && InputDomain != AD_Other &&
670 OutputConstraintInfos[TiedTo].allowsRegister()) {
671 // FIXME: GCC supports the OutSize to be 128 at maximum. Currently codegen
672 // crash when the size larger than the register size. So we limit it here.
673 if (OutTy->isStructureType() &&
674 Context.getIntTypeForBitwidth(OutSize, /*Signed*/ false).isNull()) {
675 targetDiag(OutputExpr->getExprLoc(), diag::err_store_value_to_reg);
676 return NS;
677 }
678
679 continue;
680 }
681
682 // Either both of the operands were mentioned or the smaller one was
683 // mentioned. One more special case that we'll allow: if the tied input is
684 // integer, unmentioned, and is a constant, then we'll allow truncating it
685 // down to the size of the destination.
686 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
687 !isOperandMentioned(InputOpNo, Pieces) &&
688 InputExpr->isEvaluatable(Context)) {
689 CastKind castKind =
690 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
691 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
692 Exprs[InputOpNo] = InputExpr;
693 NS->setInputExpr(i, InputExpr);
694 continue;
695 }
696
697 targetDiag(InputExpr->getBeginLoc(), diag::err_asm_tying_incompatible_types)
698 << InTy << OutTy << OutputExpr->getSourceRange()
699 << InputExpr->getSourceRange();
700 return NS;
701 }
702
703 // Check for conflicts between clobber list and input or output lists
704 SourceLocation ConstraintLoc =
705 getClobberConflictLocation(Exprs, Constraints, Clobbers, NumClobbers,
706 NumLabels,
707 Context.getTargetInfo(), Context);
708 if (ConstraintLoc.isValid())
709 targetDiag(ConstraintLoc, diag::error_inoutput_conflict_with_clobber);
710
711 // Check for duplicate asm operand name between input, output and label lists.
712 typedef std::pair<StringRef , Expr *> NamedOperand;
713 SmallVector<NamedOperand, 4> NamedOperandList;
714 for (unsigned i = 0, e = NumOutputs + NumInputs + NumLabels; i != e; ++i)
715 if (Names[i])
716 NamedOperandList.emplace_back(
717 std::make_pair(Names[i]->getName(), Exprs[i]));
718 // Sort NamedOperandList.
719 llvm::stable_sort(NamedOperandList, llvm::less_first());
720 // Find adjacent duplicate operand.
721 SmallVector<NamedOperand, 4>::iterator Found =
722 std::adjacent_find(begin(NamedOperandList), end(NamedOperandList),
723 [](const NamedOperand &LHS, const NamedOperand &RHS) {
724 return LHS.first == RHS.first;
725 });
726 if (Found != NamedOperandList.end()) {
727 Diag((Found + 1)->second->getBeginLoc(),
728 diag::error_duplicate_asm_operand_name)
729 << (Found + 1)->first;
730 Diag(Found->second->getBeginLoc(), diag::note_duplicate_asm_operand_name)
731 << Found->first;
732 return StmtError();
733 }
734 if (NS->isAsmGoto())
735 setFunctionHasBranchIntoScope();
736
737 CleanupVarDeclMarking();
738 DiscardCleanupsInEvaluationContext();
739 return NS;
740 }
741
FillInlineAsmIdentifierInfo(Expr * Res,llvm::InlineAsmIdentifierInfo & Info)742 void Sema::FillInlineAsmIdentifierInfo(Expr *Res,
743 llvm::InlineAsmIdentifierInfo &Info) {
744 QualType T = Res->getType();
745 Expr::EvalResult Eval;
746 if (T->isFunctionType() || T->isDependentType())
747 return Info.setLabel(Res);
748 if (Res->isPRValue()) {
749 bool IsEnum = isa<clang::EnumType>(T);
750 if (DeclRefExpr *DRE = dyn_cast<clang::DeclRefExpr>(Res))
751 if (DRE->getDecl()->getKind() == Decl::EnumConstant)
752 IsEnum = true;
753 if (IsEnum && Res->EvaluateAsRValue(Eval, Context))
754 return Info.setEnum(Eval.Val.getInt().getSExtValue());
755
756 return Info.setLabel(Res);
757 }
758 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
759 unsigned Type = Size;
760 if (const auto *ATy = Context.getAsArrayType(T))
761 Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
762 bool IsGlobalLV = false;
763 if (Res->EvaluateAsLValue(Eval, Context))
764 IsGlobalLV = Eval.isGlobalLValue();
765 Info.setVar(Res, IsGlobalLV, Size, Type);
766 }
767
LookupInlineAsmIdentifier(CXXScopeSpec & SS,SourceLocation TemplateKWLoc,UnqualifiedId & Id,bool IsUnevaluatedContext)768 ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
769 SourceLocation TemplateKWLoc,
770 UnqualifiedId &Id,
771 bool IsUnevaluatedContext) {
772
773 if (IsUnevaluatedContext)
774 PushExpressionEvaluationContext(
775 ExpressionEvaluationContext::UnevaluatedAbstract,
776 ReuseLambdaContextDecl);
777
778 ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
779 /*trailing lparen*/ false,
780 /*is & operand*/ false,
781 /*CorrectionCandidateCallback=*/nullptr,
782 /*IsInlineAsmIdentifier=*/ true);
783
784 if (IsUnevaluatedContext)
785 PopExpressionEvaluationContext();
786
787 if (!Result.isUsable()) return Result;
788
789 Result = CheckPlaceholderExpr(Result.get());
790 if (!Result.isUsable()) return Result;
791
792 // Referring to parameters is not allowed in naked functions.
793 if (CheckNakedParmReference(Result.get(), *this))
794 return ExprError();
795
796 QualType T = Result.get()->getType();
797
798 if (T->isDependentType()) {
799 return Result;
800 }
801
802 // Any sort of function type is fine.
803 if (T->isFunctionType()) {
804 return Result;
805 }
806
807 // Otherwise, it needs to be a complete type.
808 if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
809 return ExprError();
810 }
811
812 return Result;
813 }
814
LookupInlineAsmField(StringRef Base,StringRef Member,unsigned & Offset,SourceLocation AsmLoc)815 bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
816 unsigned &Offset, SourceLocation AsmLoc) {
817 Offset = 0;
818 SmallVector<StringRef, 2> Members;
819 Member.split(Members, ".");
820
821 NamedDecl *FoundDecl = nullptr;
822
823 // MS InlineAsm uses 'this' as a base
824 if (getLangOpts().CPlusPlus && Base.equals("this")) {
825 if (const Type *PT = getCurrentThisType().getTypePtrOrNull())
826 FoundDecl = PT->getPointeeType()->getAsTagDecl();
827 } else {
828 LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
829 LookupOrdinaryName);
830 if (LookupName(BaseResult, getCurScope()) && BaseResult.isSingleResult())
831 FoundDecl = BaseResult.getFoundDecl();
832 }
833
834 if (!FoundDecl)
835 return true;
836
837 for (StringRef NextMember : Members) {
838 const RecordType *RT = nullptr;
839 if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
840 RT = VD->getType()->getAs<RecordType>();
841 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
842 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
843 // MS InlineAsm often uses struct pointer aliases as a base
844 QualType QT = TD->getUnderlyingType();
845 if (const auto *PT = QT->getAs<PointerType>())
846 QT = PT->getPointeeType();
847 RT = QT->getAs<RecordType>();
848 } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
849 RT = TD->getTypeForDecl()->getAs<RecordType>();
850 else if (FieldDecl *TD = dyn_cast<FieldDecl>(FoundDecl))
851 RT = TD->getType()->getAs<RecordType>();
852 if (!RT)
853 return true;
854
855 if (RequireCompleteType(AsmLoc, QualType(RT, 0),
856 diag::err_asm_incomplete_type))
857 return true;
858
859 LookupResult FieldResult(*this, &Context.Idents.get(NextMember),
860 SourceLocation(), LookupMemberName);
861
862 if (!LookupQualifiedName(FieldResult, RT->getDecl()))
863 return true;
864
865 if (!FieldResult.isSingleResult())
866 return true;
867 FoundDecl = FieldResult.getFoundDecl();
868
869 // FIXME: Handle IndirectFieldDecl?
870 FieldDecl *FD = dyn_cast<FieldDecl>(FoundDecl);
871 if (!FD)
872 return true;
873
874 const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
875 unsigned i = FD->getFieldIndex();
876 CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
877 Offset += (unsigned)Result.getQuantity();
878 }
879
880 return false;
881 }
882
883 ExprResult
LookupInlineAsmVarDeclField(Expr * E,StringRef Member,SourceLocation AsmLoc)884 Sema::LookupInlineAsmVarDeclField(Expr *E, StringRef Member,
885 SourceLocation AsmLoc) {
886
887 QualType T = E->getType();
888 if (T->isDependentType()) {
889 DeclarationNameInfo NameInfo;
890 NameInfo.setLoc(AsmLoc);
891 NameInfo.setName(&Context.Idents.get(Member));
892 return CXXDependentScopeMemberExpr::Create(
893 Context, E, T, /*IsArrow=*/false, AsmLoc, NestedNameSpecifierLoc(),
894 SourceLocation(),
895 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, /*TemplateArgs=*/nullptr);
896 }
897
898 const RecordType *RT = T->getAs<RecordType>();
899 // FIXME: Diagnose this as field access into a scalar type.
900 if (!RT)
901 return ExprResult();
902
903 LookupResult FieldResult(*this, &Context.Idents.get(Member), AsmLoc,
904 LookupMemberName);
905
906 if (!LookupQualifiedName(FieldResult, RT->getDecl()))
907 return ExprResult();
908
909 // Only normal and indirect field results will work.
910 ValueDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
911 if (!FD)
912 FD = dyn_cast<IndirectFieldDecl>(FieldResult.getFoundDecl());
913 if (!FD)
914 return ExprResult();
915
916 // Make an Expr to thread through OpDecl.
917 ExprResult Result = BuildMemberReferenceExpr(
918 E, E->getType(), AsmLoc, /*IsArrow=*/false, CXXScopeSpec(),
919 SourceLocation(), nullptr, FieldResult, nullptr, nullptr);
920
921 return Result;
922 }
923
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)924 StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
925 ArrayRef<Token> AsmToks,
926 StringRef AsmString,
927 unsigned NumOutputs, unsigned NumInputs,
928 ArrayRef<StringRef> Constraints,
929 ArrayRef<StringRef> Clobbers,
930 ArrayRef<Expr*> Exprs,
931 SourceLocation EndLoc) {
932 bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
933 setFunctionHasBranchProtectedScope();
934
935 for (uint64_t I = 0; I < NumOutputs + NumInputs; ++I) {
936 if (Exprs[I]->getType()->isBitIntType())
937 return StmtError(
938 Diag(Exprs[I]->getBeginLoc(), diag::err_asm_invalid_type)
939 << Exprs[I]->getType() << (I < NumOutputs)
940 << Exprs[I]->getSourceRange());
941 }
942
943 MSAsmStmt *NS =
944 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
945 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
946 Constraints, Exprs, AsmString,
947 Clobbers, EndLoc);
948 return NS;
949 }
950
GetOrCreateMSAsmLabel(StringRef ExternalLabelName,SourceLocation Location,bool AlwaysCreate)951 LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
952 SourceLocation Location,
953 bool AlwaysCreate) {
954 LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
955 Location);
956
957 if (Label->isMSAsmLabel()) {
958 // If we have previously created this label implicitly, mark it as used.
959 Label->markUsed(Context);
960 } else {
961 // Otherwise, insert it, but only resolve it if we have seen the label itself.
962 std::string InternalName;
963 llvm::raw_string_ostream OS(InternalName);
964 // Create an internal name for the label. The name should not be a valid
965 // mangled name, and should be unique. We use a dot to make the name an
966 // invalid mangled name. We use LLVM's inline asm ${:uid} escape so that a
967 // unique label is generated each time this blob is emitted, even after
968 // inlining or LTO.
969 OS << "__MSASMLABEL_.${:uid}__";
970 for (char C : ExternalLabelName) {
971 OS << C;
972 // We escape '$' in asm strings by replacing it with "$$"
973 if (C == '$')
974 OS << '$';
975 }
976 Label->setMSAsmLabel(OS.str());
977 }
978 if (AlwaysCreate) {
979 // The label might have been created implicitly from a previously encountered
980 // goto statement. So, for both newly created and looked up labels, we mark
981 // them as resolved.
982 Label->setMSAsmLabelResolved();
983 }
984 // Adjust their location for being able to generate accurate diagnostics.
985 Label->setLocation(Location);
986
987 return Label;
988 }
989