1 //===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for inline asm statements.
11 //
12 //===----------------------------------------------------------------------===//
13 
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;
27 using namespace sema;
28 
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.
33 ///
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())
39     return false;
40 
41   if (E->isLValue())
42     return false;  // Cool, this is an lvalue.
43 
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();
51     else
52       S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
53         << E->getSourceRange();
54     // Accept, even if we emitted an error diagnostic.
55     return false;
56   }
57 
58   // None of the above, just randomly invalid non-lvalue.
59   return true;
60 }
61 
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;
69 
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)
73       return true;
74   }
75   return false;
76 }
77 
78 static bool CheckNakedParmReference(Expr *E, Sema &S) {
79   FunctionDecl *Func = dyn_cast<FunctionDecl>(S.CurContext);
80   if (!Func)
81     return false;
82   if (!Func->hasAttr<NakedAttr>())
83     return false;
84 
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);
93         return true;
94       }
95     }
96     for (Stmt *Child : E->children()) {
97       if (Expr *E = dyn_cast_or_null<Expr>(Child))
98         WorkList.push_back(E);
99     }
100   }
101   return false;
102 }
103 
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());
115 
116   SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
117 
118   // The parser verifies that there is a string literal here.
119   assert(AsmString->isAscii());
120 
121   for (unsigned i = 0; i != NumOutputs; i++) {
122     StringLiteral *Literal = Constraints[i];
123     assert(Literal->isAscii());
124 
125     StringRef OutputName;
126     if (Names[i])
127       OutputName = Names[i]->getName();
128 
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());
134 
135     // Check that the output exprs are valid lvalues.
136     Expr *OutputExpr = Exprs[i];
137     if (CheckAsmLValue(OutputExpr, *this))
138       return StmtError(Diag(OutputExpr->getLocStart(),
139                             diag::err_asm_invalid_lvalue_in_output)
140                        << OutputExpr->getSourceRange());
141 
142     // Referring to parameters is not allowed in naked functions.
143     if (CheckNakedParmReference(OutputExpr, *this))
144       return StmtError();
145 
146     if (RequireCompleteType(OutputExpr->getLocStart(), Exprs[i]->getType(),
147                             diag::err_dereference_incomplete_type))
148       return StmtError();
149 
150     OutputConstraintInfos.push_back(Info);
151 
152     const Type *Ty = OutputExpr->getType().getTypePtr();
153 
154     // If this is a dependent type, just continue. We don't know the size of a
155     // dependent type.
156     if (Ty->isDependentType())
157       continue;
158 
159     unsigned Size = Context.getTypeSize(Ty);
160     if (!Context.getTargetInfo().validateOutputSize(Literal->getString(),
161                                                     Size))
162       return StmtError(Diag(OutputExpr->getLocStart(),
163                             diag::err_asm_invalid_output_size)
164                        << Info.getConstraintStr());
165   }
166 
167   SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
168 
169   for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
170     StringLiteral *Literal = Constraints[i];
171     assert(Literal->isAscii());
172 
173     StringRef InputName;
174     if (Names[i])
175       InputName = Names[i]->getName();
176 
177     TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
178     if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
179                                                 NumOutputs, Info)) {
180       return StmtError(Diag(Literal->getLocStart(),
181                             diag::err_asm_invalid_input_constraint)
182                        << Info.getConstraintStr());
183     }
184 
185     Expr *InputExpr = Exprs[i];
186 
187     // Referring to parameters is not allowed in naked functions.
188     if (CheckNakedParmReference(InputExpr, *this))
189       return StmtError();
190 
191     // Only allow void types for memory constraints.
192     if (Info.allowsMemory() && !Info.allowsRegister()) {
193       if (CheckAsmLValue(InputExpr, *this))
194         return StmtError(Diag(InputExpr->getLocStart(),
195                               diag::err_asm_invalid_lvalue_in_input)
196                          << Info.getConstraintStr()
197                          << InputExpr->getSourceRange());
198     } else {
199       ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
200       if (Result.isInvalid())
201         return StmtError();
202 
203       Exprs[i] = Result.get();
204     }
205 
206     if (Info.allowsRegister()) {
207       if (InputExpr->getType()->isVoidType()) {
208         return StmtError(Diag(InputExpr->getLocStart(),
209                               diag::err_asm_invalid_type_in_input)
210           << InputExpr->getType() << Info.getConstraintStr()
211           << InputExpr->getSourceRange());
212       }
213     }
214 
215     InputConstraintInfos.push_back(Info);
216 
217     const Type *Ty = Exprs[i]->getType().getTypePtr();
218     if (Ty->isDependentType())
219       continue;
220 
221     if (!Ty->isVoidType() || !Info.allowsMemory())
222       if (RequireCompleteType(InputExpr->getLocStart(), Exprs[i]->getType(),
223                               diag::err_dereference_incomplete_type))
224         return StmtError();
225 
226     unsigned Size = Context.getTypeSize(Ty);
227     if (!Context.getTargetInfo().validateInputSize(Literal->getString(),
228                                                    Size))
229       return StmtError(Diag(InputExpr->getLocStart(),
230                             diag::err_asm_invalid_input_size)
231                        << Info.getConstraintStr());
232   }
233 
234   // Check that the clobbers are valid.
235   for (unsigned i = 0; i != NumClobbers; i++) {
236     StringLiteral *Literal = Clobbers[i];
237     assert(Literal->isAscii());
238 
239     StringRef Clobber = Literal->getString();
240 
241     if (!Context.getTargetInfo().isValidClobber(Clobber))
242       return StmtError(Diag(Literal->getLocStart(),
243                   diag::err_asm_unknown_register_name) << Clobber);
244   }
245 
246   GCCAsmStmt *NS =
247     new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
248                              NumInputs, Names, Constraints, Exprs.data(),
249                              AsmString, NumClobbers, Clobbers, RParenLoc);
250   // Validate the asm string, ensuring it makes sense given the operands we
251   // have.
252   SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
253   unsigned DiagOffs;
254   if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
255     Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
256            << AsmString->getSourceRange();
257     return StmtError();
258   }
259 
260   // Validate constraints and modifiers.
261   for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
262     GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
263     if (!Piece.isOperand()) continue;
264 
265     // Look for the correct constraint index.
266     unsigned Idx = 0;
267     unsigned ConstraintIdx = 0;
268     for (unsigned i = 0, e = NS->getNumOutputs(); i != e; ++i, ++ConstraintIdx) {
269       TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
270       if (Idx == Piece.getOperandNo())
271         break;
272       ++Idx;
273 
274       if (Info.isReadWrite()) {
275         if (Idx == Piece.getOperandNo())
276           break;
277         ++Idx;
278       }
279     }
280 
281     for (unsigned i = 0, e = NS->getNumInputs(); i != e; ++i, ++ConstraintIdx) {
282       TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
283       if (Idx == Piece.getOperandNo())
284         break;
285       ++Idx;
286 
287       if (Info.isReadWrite()) {
288         if (Idx == Piece.getOperandNo())
289           break;
290         ++Idx;
291       }
292     }
293 
294     // Now that we have the right indexes go ahead and check.
295     StringLiteral *Literal = Constraints[ConstraintIdx];
296     const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
297     if (Ty->isDependentType() || Ty->isIncompleteType())
298       continue;
299 
300     unsigned Size = Context.getTypeSize(Ty);
301     std::string SuggestedModifier;
302     if (!Context.getTargetInfo().validateConstraintModifier(
303             Literal->getString(), Piece.getModifier(), Size,
304             SuggestedModifier)) {
305       Diag(Exprs[ConstraintIdx]->getLocStart(),
306            diag::warn_asm_mismatched_size_modifier);
307 
308       if (!SuggestedModifier.empty()) {
309         auto B = Diag(Piece.getRange().getBegin(),
310                       diag::note_asm_missing_constraint_modifier)
311                  << SuggestedModifier;
312         SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
313         B.AddFixItHint(FixItHint::CreateReplacement(Piece.getRange(),
314                                                     SuggestedModifier));
315       }
316     }
317   }
318 
319   // Validate tied input operands for type mismatches.
320   for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
321     TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
322 
323     // If this is a tied constraint, verify that the output and input have
324     // either exactly the same type, or that they are int/ptr operands with the
325     // same size (int/long, int*/long, are ok etc).
326     if (!Info.hasTiedOperand()) continue;
327 
328     unsigned TiedTo = Info.getTiedOperand();
329     unsigned InputOpNo = i+NumOutputs;
330     Expr *OutputExpr = Exprs[TiedTo];
331     Expr *InputExpr = Exprs[InputOpNo];
332 
333     if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
334       continue;
335 
336     QualType InTy = InputExpr->getType();
337     QualType OutTy = OutputExpr->getType();
338     if (Context.hasSameType(InTy, OutTy))
339       continue;  // All types can be tied to themselves.
340 
341     // Decide if the input and output are in the same domain (integer/ptr or
342     // floating point.
343     enum AsmDomain {
344       AD_Int, AD_FP, AD_Other
345     } InputDomain, OutputDomain;
346 
347     if (InTy->isIntegerType() || InTy->isPointerType())
348       InputDomain = AD_Int;
349     else if (InTy->isRealFloatingType())
350       InputDomain = AD_FP;
351     else
352       InputDomain = AD_Other;
353 
354     if (OutTy->isIntegerType() || OutTy->isPointerType())
355       OutputDomain = AD_Int;
356     else if (OutTy->isRealFloatingType())
357       OutputDomain = AD_FP;
358     else
359       OutputDomain = AD_Other;
360 
361     // They are ok if they are the same size and in the same domain.  This
362     // allows tying things like:
363     //   void* to int*
364     //   void* to int            if they are the same size.
365     //   double to long double   if they are the same size.
366     //
367     uint64_t OutSize = Context.getTypeSize(OutTy);
368     uint64_t InSize = Context.getTypeSize(InTy);
369     if (OutSize == InSize && InputDomain == OutputDomain &&
370         InputDomain != AD_Other)
371       continue;
372 
373     // If the smaller input/output operand is not mentioned in the asm string,
374     // then we can promote the smaller one to a larger input and the asm string
375     // won't notice.
376     bool SmallerValueMentioned = false;
377 
378     // If this is a reference to the input and if the input was the smaller
379     // one, then we have to reject this asm.
380     if (isOperandMentioned(InputOpNo, Pieces)) {
381       // This is a use in the asm string of the smaller operand.  Since we
382       // codegen this by promoting to a wider value, the asm will get printed
383       // "wrong".
384       SmallerValueMentioned |= InSize < OutSize;
385     }
386     if (isOperandMentioned(TiedTo, Pieces)) {
387       // If this is a reference to the output, and if the output is the larger
388       // value, then it's ok because we'll promote the input to the larger type.
389       SmallerValueMentioned |= OutSize < InSize;
390     }
391 
392     // If the smaller value wasn't mentioned in the asm string, and if the
393     // output was a register, just extend the shorter one to the size of the
394     // larger one.
395     if (!SmallerValueMentioned && InputDomain != AD_Other &&
396         OutputConstraintInfos[TiedTo].allowsRegister())
397       continue;
398 
399     // Either both of the operands were mentioned or the smaller one was
400     // mentioned.  One more special case that we'll allow: if the tied input is
401     // integer, unmentioned, and is a constant, then we'll allow truncating it
402     // down to the size of the destination.
403     if (InputDomain == AD_Int && OutputDomain == AD_Int &&
404         !isOperandMentioned(InputOpNo, Pieces) &&
405         InputExpr->isEvaluatable(Context)) {
406       CastKind castKind =
407         (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
408       InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
409       Exprs[InputOpNo] = InputExpr;
410       NS->setInputExpr(i, InputExpr);
411       continue;
412     }
413 
414     Diag(InputExpr->getLocStart(),
415          diag::err_asm_tying_incompatible_types)
416       << InTy << OutTy << OutputExpr->getSourceRange()
417       << InputExpr->getSourceRange();
418     return StmtError();
419   }
420 
421   return NS;
422 }
423 
424 ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
425                                            SourceLocation TemplateKWLoc,
426                                            UnqualifiedId &Id,
427                                            llvm::InlineAsmIdentifierInfo &Info,
428                                            bool IsUnevaluatedContext) {
429   Info.clear();
430 
431   if (IsUnevaluatedContext)
432     PushExpressionEvaluationContext(UnevaluatedAbstract,
433                                     ReuseLambdaContextDecl);
434 
435   ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
436                                         /*trailing lparen*/ false,
437                                         /*is & operand*/ false,
438                                         /*CorrectionCandidateCallback=*/nullptr,
439                                         /*IsInlineAsmIdentifier=*/ true);
440 
441   if (IsUnevaluatedContext)
442     PopExpressionEvaluationContext();
443 
444   if (!Result.isUsable()) return Result;
445 
446   Result = CheckPlaceholderExpr(Result.get());
447   if (!Result.isUsable()) return Result;
448 
449   // Referring to parameters is not allowed in naked functions.
450   if (CheckNakedParmReference(Result.get(), *this))
451     return ExprError();
452 
453   QualType T = Result.get()->getType();
454 
455   // For now, reject dependent types.
456   if (T->isDependentType()) {
457     Diag(Id.getLocStart(), diag::err_asm_incomplete_type) << T;
458     return ExprError();
459   }
460 
461   // Any sort of function type is fine.
462   if (T->isFunctionType()) {
463     return Result;
464   }
465 
466   // Otherwise, it needs to be a complete type.
467   if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
468     return ExprError();
469   }
470 
471   // Compute the type size (and array length if applicable?).
472   Info.Type = Info.Size = Context.getTypeSizeInChars(T).getQuantity();
473   if (T->isArrayType()) {
474     const ArrayType *ATy = Context.getAsArrayType(T);
475     Info.Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
476     Info.Length = Info.Size / Info.Type;
477   }
478 
479   // We can work with the expression as long as it's not an r-value.
480   if (!Result.get()->isRValue())
481     Info.IsVarDecl = true;
482 
483   return Result;
484 }
485 
486 bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
487                                 unsigned &Offset, SourceLocation AsmLoc) {
488   Offset = 0;
489   LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
490                           LookupOrdinaryName);
491 
492   if (!LookupName(BaseResult, getCurScope()))
493     return true;
494 
495   if (!BaseResult.isSingleResult())
496     return true;
497 
498   const RecordType *RT = nullptr;
499   NamedDecl *FoundDecl = BaseResult.getFoundDecl();
500   if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
501     RT = VD->getType()->getAs<RecordType>();
502   else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
503     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
504     RT = TD->getUnderlyingType()->getAs<RecordType>();
505   } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
506     RT = TD->getTypeForDecl()->getAs<RecordType>();
507   if (!RT)
508     return true;
509 
510   if (RequireCompleteType(AsmLoc, QualType(RT, 0), 0))
511     return true;
512 
513   LookupResult FieldResult(*this, &Context.Idents.get(Member), SourceLocation(),
514                            LookupMemberName);
515 
516   if (!LookupQualifiedName(FieldResult, RT->getDecl()))
517     return true;
518 
519   // FIXME: Handle IndirectFieldDecl?
520   FieldDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
521   if (!FD)
522     return true;
523 
524   const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
525   unsigned i = FD->getFieldIndex();
526   CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
527   Offset = (unsigned)Result.getQuantity();
528 
529   return false;
530 }
531 
532 StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
533                                 ArrayRef<Token> AsmToks,
534                                 StringRef AsmString,
535                                 unsigned NumOutputs, unsigned NumInputs,
536                                 ArrayRef<StringRef> Constraints,
537                                 ArrayRef<StringRef> Clobbers,
538                                 ArrayRef<Expr*> Exprs,
539                                 SourceLocation EndLoc) {
540   bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
541   getCurFunction()->setHasBranchProtectedScope();
542   MSAsmStmt *NS =
543     new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
544                             /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
545                             Constraints, Exprs, AsmString,
546                             Clobbers, EndLoc);
547   return NS;
548 }
549 
550 LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
551                                        SourceLocation Location,
552                                        bool AlwaysCreate) {
553   LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
554                                          Location);
555 
556   if (Label->isMSAsmLabel()) {
557     // If we have previously created this label implicitly, mark it as used.
558     Label->markUsed(Context);
559   } else {
560     // Otherwise, insert it, but only resolve it if we have seen the label itself.
561     std::string InternalName;
562     llvm::raw_string_ostream OS(InternalName);
563     // Create an internal name for the label.  The name should not be a valid mangled
564     // name, and should be unique.  We use a dot to make the name an invalid mangled
565     // name.
566     OS << "__MSASMLABEL_." << MSAsmLabelNameCounter++ << "__" << ExternalLabelName;
567     Label->setMSAsmLabel(OS.str());
568   }
569   if (AlwaysCreate) {
570     // The label might have been created implicitly from a previously encountered
571     // goto statement.  So, for both newly created and looked up labels, we mark
572     // them as resolved.
573     Label->setMSAsmLabelResolved();
574   }
575   // Adjust their location for being able to generate accurate diagnostics.
576   Label->setLocation(Location);
577 
578   return Label;
579 }
580