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