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