1 //===--- SemaStmtAttr.cpp - Statement Attribute Handling ------------------===// 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 stmt-related attribute processing. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/EvaluatedExprVisitor.h" 15 #include "clang/Basic/SourceManager.h" 16 #include "clang/Basic/TargetInfo.h" 17 #include "clang/Sema/DelayedDiagnostic.h" 18 #include "clang/Sema/Lookup.h" 19 #include "clang/Sema/ScopeInfo.h" 20 #include "clang/Sema/SemaInternal.h" 21 #include "llvm/ADT/StringExtras.h" 22 23 using namespace clang; 24 using namespace sema; 25 26 static Attr *handleFallThroughAttr(Sema &S, Stmt *St, const ParsedAttr &A, 27 SourceRange Range) { 28 FallThroughAttr Attr(S.Context, A); 29 if (isa<SwitchCase>(St)) { 30 S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_wrong_target) 31 << A << St->getBeginLoc(); 32 SourceLocation L = S.getLocForEndOfToken(Range.getEnd()); 33 S.Diag(L, diag::note_fallthrough_insert_semi_fixit) 34 << FixItHint::CreateInsertion(L, ";"); 35 return nullptr; 36 } 37 auto *FnScope = S.getCurFunction(); 38 if (FnScope->SwitchStack.empty()) { 39 S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_outside_switch); 40 return nullptr; 41 } 42 43 // If this is spelled as the standard C++17 attribute, but not in C++17, warn 44 // about using it as an extension. 45 if (!S.getLangOpts().CPlusPlus17 && A.isCXX11Attribute() && 46 !A.getScopeName()) 47 S.Diag(A.getLoc(), diag::ext_cxx17_attr) << A; 48 49 FnScope->setHasFallthroughStmt(); 50 return ::new (S.Context) FallThroughAttr(S.Context, A); 51 } 52 53 static Attr *handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A, 54 SourceRange Range) { 55 std::vector<StringRef> DiagnosticIdentifiers; 56 for (unsigned I = 0, E = A.getNumArgs(); I != E; ++I) { 57 StringRef RuleName; 58 59 if (!S.checkStringLiteralArgumentAttr(A, I, RuleName, nullptr)) 60 return nullptr; 61 62 // FIXME: Warn if the rule name is unknown. This is tricky because only 63 // clang-tidy knows about available rules. 64 DiagnosticIdentifiers.push_back(RuleName); 65 } 66 67 return ::new (S.Context) SuppressAttr( 68 S.Context, A, DiagnosticIdentifiers.data(), DiagnosticIdentifiers.size()); 69 } 70 71 static Attr *handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A, 72 SourceRange) { 73 IdentifierLoc *PragmaNameLoc = A.getArgAsIdent(0); 74 IdentifierLoc *OptionLoc = A.getArgAsIdent(1); 75 IdentifierLoc *StateLoc = A.getArgAsIdent(2); 76 Expr *ValueExpr = A.getArgAsExpr(3); 77 78 StringRef PragmaName = 79 llvm::StringSwitch<StringRef>(PragmaNameLoc->Ident->getName()) 80 .Cases("unroll", "nounroll", "unroll_and_jam", "nounroll_and_jam", 81 PragmaNameLoc->Ident->getName()) 82 .Default("clang loop"); 83 84 // This could be handled automatically by adding a Subjects definition in 85 // Attr.td, but that would make the diagnostic behavior worse in this case 86 // because the user spells this attribute as a pragma. 87 if (!isa<DoStmt, ForStmt, CXXForRangeStmt, WhileStmt>(St)) { 88 std::string Pragma = "#pragma " + std::string(PragmaName); 89 S.Diag(St->getBeginLoc(), diag::err_pragma_loop_precedes_nonloop) << Pragma; 90 return nullptr; 91 } 92 93 LoopHintAttr::OptionType Option; 94 LoopHintAttr::LoopHintState State; 95 96 auto SetHints = [&Option, &State](LoopHintAttr::OptionType O, 97 LoopHintAttr::LoopHintState S) { 98 Option = O; 99 State = S; 100 }; 101 102 if (PragmaName == "nounroll") { 103 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable); 104 } else if (PragmaName == "unroll") { 105 // #pragma unroll N 106 if (ValueExpr) 107 SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric); 108 else 109 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Enable); 110 } else if (PragmaName == "nounroll_and_jam") { 111 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Disable); 112 } else if (PragmaName == "unroll_and_jam") { 113 // #pragma unroll_and_jam N 114 if (ValueExpr) 115 SetHints(LoopHintAttr::UnrollAndJamCount, LoopHintAttr::Numeric); 116 else 117 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Enable); 118 } else { 119 // #pragma clang loop ... 120 assert(OptionLoc && OptionLoc->Ident && 121 "Attribute must have valid option info."); 122 Option = llvm::StringSwitch<LoopHintAttr::OptionType>( 123 OptionLoc->Ident->getName()) 124 .Case("vectorize", LoopHintAttr::Vectorize) 125 .Case("vectorize_width", LoopHintAttr::VectorizeWidth) 126 .Case("interleave", LoopHintAttr::Interleave) 127 .Case("vectorize_predicate", LoopHintAttr::VectorizePredicate) 128 .Case("interleave_count", LoopHintAttr::InterleaveCount) 129 .Case("unroll", LoopHintAttr::Unroll) 130 .Case("unroll_count", LoopHintAttr::UnrollCount) 131 .Case("pipeline", LoopHintAttr::PipelineDisabled) 132 .Case("pipeline_initiation_interval", 133 LoopHintAttr::PipelineInitiationInterval) 134 .Case("distribute", LoopHintAttr::Distribute) 135 .Default(LoopHintAttr::Vectorize); 136 if (Option == LoopHintAttr::VectorizeWidth) { 137 assert((ValueExpr || (StateLoc && StateLoc->Ident)) && 138 "Attribute must have a valid value expression or argument."); 139 if (ValueExpr && S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc())) 140 return nullptr; 141 if (StateLoc && StateLoc->Ident && StateLoc->Ident->isStr("scalable")) 142 State = LoopHintAttr::ScalableWidth; 143 else 144 State = LoopHintAttr::FixedWidth; 145 } else if (Option == LoopHintAttr::InterleaveCount || 146 Option == LoopHintAttr::UnrollCount || 147 Option == LoopHintAttr::PipelineInitiationInterval) { 148 assert(ValueExpr && "Attribute must have a valid value expression."); 149 if (S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc())) 150 return nullptr; 151 State = LoopHintAttr::Numeric; 152 } else if (Option == LoopHintAttr::Vectorize || 153 Option == LoopHintAttr::Interleave || 154 Option == LoopHintAttr::VectorizePredicate || 155 Option == LoopHintAttr::Unroll || 156 Option == LoopHintAttr::Distribute || 157 Option == LoopHintAttr::PipelineDisabled) { 158 assert(StateLoc && StateLoc->Ident && "Loop hint must have an argument"); 159 if (StateLoc->Ident->isStr("disable")) 160 State = LoopHintAttr::Disable; 161 else if (StateLoc->Ident->isStr("assume_safety")) 162 State = LoopHintAttr::AssumeSafety; 163 else if (StateLoc->Ident->isStr("full")) 164 State = LoopHintAttr::Full; 165 else if (StateLoc->Ident->isStr("enable")) 166 State = LoopHintAttr::Enable; 167 else 168 llvm_unreachable("bad loop hint argument"); 169 } else 170 llvm_unreachable("bad loop hint"); 171 } 172 173 return LoopHintAttr::CreateImplicit(S.Context, Option, State, ValueExpr, A); 174 } 175 176 namespace { 177 class CallExprFinder : public ConstEvaluatedExprVisitor<CallExprFinder> { 178 bool FoundCallExpr = false; 179 180 public: 181 typedef ConstEvaluatedExprVisitor<CallExprFinder> Inherited; 182 183 CallExprFinder(Sema &S, const Stmt *St) : Inherited(S.Context) { Visit(St); } 184 185 bool foundCallExpr() { return FoundCallExpr; } 186 187 void VisitCallExpr(const CallExpr *E) { FoundCallExpr = true; } 188 void VisitAsmStmt(const AsmStmt *S) { FoundCallExpr = true; } 189 190 void Visit(const Stmt *St) { 191 if (!St) 192 return; 193 ConstEvaluatedExprVisitor<CallExprFinder>::Visit(St); 194 } 195 }; 196 } // namespace 197 198 static Attr *handleNoMergeAttr(Sema &S, Stmt *St, const ParsedAttr &A, 199 SourceRange Range) { 200 NoMergeAttr NMA(S.Context, A); 201 CallExprFinder CEF(S, St); 202 203 if (!CEF.foundCallExpr()) { 204 S.Diag(St->getBeginLoc(), diag::warn_nomerge_attribute_ignored_in_stmt) 205 << NMA.getSpelling(); 206 return nullptr; 207 } 208 209 return ::new (S.Context) NoMergeAttr(S.Context, A); 210 } 211 212 static Attr *handleLikely(Sema &S, Stmt *St, const ParsedAttr &A, 213 SourceRange Range) { 214 215 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName()) 216 S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range; 217 218 return ::new (S.Context) LikelyAttr(S.Context, A); 219 } 220 221 static Attr *handleUnlikely(Sema &S, Stmt *St, const ParsedAttr &A, 222 SourceRange Range) { 223 224 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName()) 225 S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range; 226 227 return ::new (S.Context) UnlikelyAttr(S.Context, A); 228 } 229 230 #define WANT_STMT_MERGE_LOGIC 231 #include "clang/Sema/AttrParsedAttrImpl.inc" 232 #undef WANT_STMT_MERGE_LOGIC 233 234 static void 235 CheckForIncompatibleAttributes(Sema &S, 236 const SmallVectorImpl<const Attr *> &Attrs) { 237 // The vast majority of attributed statements will only have one attribute 238 // on them, so skip all of the checking in the common case. 239 if (Attrs.size() < 2) 240 return; 241 242 // First, check for the easy cases that are table-generated for us. 243 if (!DiagnoseMutualExclusions(S, Attrs)) 244 return; 245 246 // There are 6 categories of loop hints attributes: vectorize, interleave, 247 // unroll, unroll_and_jam, pipeline and distribute. Except for distribute they 248 // come in two variants: a state form and a numeric form. The state form 249 // selectively defaults/enables/disables the transformation for the loop 250 // (for unroll, default indicates full unrolling rather than enabling the 251 // transformation). The numeric form form provides an integer hint (for 252 // example, unroll count) to the transformer. The following array accumulates 253 // the hints encountered while iterating through the attributes to check for 254 // compatibility. 255 struct { 256 const LoopHintAttr *StateAttr; 257 const LoopHintAttr *NumericAttr; 258 } HintAttrs[] = {{nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr}, 259 {nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr}, 260 {nullptr, nullptr}}; 261 262 for (const auto *I : Attrs) { 263 const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I); 264 265 // Skip non loop hint attributes 266 if (!LH) 267 continue; 268 269 LoopHintAttr::OptionType Option = LH->getOption(); 270 enum { 271 Vectorize, 272 Interleave, 273 Unroll, 274 UnrollAndJam, 275 Distribute, 276 Pipeline, 277 VectorizePredicate 278 } Category; 279 switch (Option) { 280 case LoopHintAttr::Vectorize: 281 case LoopHintAttr::VectorizeWidth: 282 Category = Vectorize; 283 break; 284 case LoopHintAttr::Interleave: 285 case LoopHintAttr::InterleaveCount: 286 Category = Interleave; 287 break; 288 case LoopHintAttr::Unroll: 289 case LoopHintAttr::UnrollCount: 290 Category = Unroll; 291 break; 292 case LoopHintAttr::UnrollAndJam: 293 case LoopHintAttr::UnrollAndJamCount: 294 Category = UnrollAndJam; 295 break; 296 case LoopHintAttr::Distribute: 297 // Perform the check for duplicated 'distribute' hints. 298 Category = Distribute; 299 break; 300 case LoopHintAttr::PipelineDisabled: 301 case LoopHintAttr::PipelineInitiationInterval: 302 Category = Pipeline; 303 break; 304 case LoopHintAttr::VectorizePredicate: 305 Category = VectorizePredicate; 306 break; 307 }; 308 309 assert(Category < sizeof(HintAttrs) / sizeof(HintAttrs[0])); 310 auto &CategoryState = HintAttrs[Category]; 311 const LoopHintAttr *PrevAttr; 312 if (Option == LoopHintAttr::Vectorize || 313 Option == LoopHintAttr::Interleave || Option == LoopHintAttr::Unroll || 314 Option == LoopHintAttr::UnrollAndJam || 315 Option == LoopHintAttr::VectorizePredicate || 316 Option == LoopHintAttr::PipelineDisabled || 317 Option == LoopHintAttr::Distribute) { 318 // Enable|Disable|AssumeSafety hint. For example, vectorize(enable). 319 PrevAttr = CategoryState.StateAttr; 320 CategoryState.StateAttr = LH; 321 } else { 322 // Numeric hint. For example, vectorize_width(8). 323 PrevAttr = CategoryState.NumericAttr; 324 CategoryState.NumericAttr = LH; 325 } 326 327 PrintingPolicy Policy(S.Context.getLangOpts()); 328 SourceLocation OptionLoc = LH->getRange().getBegin(); 329 if (PrevAttr) 330 // Cannot specify same type of attribute twice. 331 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility) 332 << /*Duplicate=*/true << PrevAttr->getDiagnosticName(Policy) 333 << LH->getDiagnosticName(Policy); 334 335 if (CategoryState.StateAttr && CategoryState.NumericAttr && 336 (Category == Unroll || Category == UnrollAndJam || 337 CategoryState.StateAttr->getState() == LoopHintAttr::Disable)) { 338 // Disable hints are not compatible with numeric hints of the same 339 // category. As a special case, numeric unroll hints are also not 340 // compatible with enable or full form of the unroll pragma because these 341 // directives indicate full unrolling. 342 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility) 343 << /*Duplicate=*/false 344 << CategoryState.StateAttr->getDiagnosticName(Policy) 345 << CategoryState.NumericAttr->getDiagnosticName(Policy); 346 } 347 } 348 } 349 350 static Attr *handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A, 351 SourceRange Range) { 352 // Although the feature was introduced only in OpenCL C v2.0 s6.11.5, it's 353 // useful for OpenCL 1.x too and doesn't require HW support. 354 // opencl_unroll_hint can have 0 arguments (compiler 355 // determines unrolling factor) or 1 argument (the unroll factor provided 356 // by the user). 357 unsigned UnrollFactor = 0; 358 if (A.getNumArgs() == 1) { 359 Expr *E = A.getArgAsExpr(0); 360 Optional<llvm::APSInt> ArgVal; 361 362 if (!(ArgVal = E->getIntegerConstantExpr(S.Context))) { 363 S.Diag(A.getLoc(), diag::err_attribute_argument_type) 364 << A << AANT_ArgumentIntegerConstant << E->getSourceRange(); 365 return nullptr; 366 } 367 368 int Val = ArgVal->getSExtValue(); 369 if (Val <= 0) { 370 S.Diag(A.getRange().getBegin(), 371 diag::err_attribute_requires_positive_integer) 372 << A << /* positive */ 0; 373 return nullptr; 374 } 375 UnrollFactor = static_cast<unsigned>(Val); 376 } 377 378 return ::new (S.Context) OpenCLUnrollHintAttr(S.Context, A, UnrollFactor); 379 } 380 381 static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A, 382 SourceRange Range) { 383 if (A.isInvalid() || A.getKind() == ParsedAttr::IgnoredAttribute) 384 return nullptr; 385 386 // Unknown attributes are automatically warned on. Target-specific attributes 387 // which do not apply to the current target architecture are treated as 388 // though they were unknown attributes. 389 const TargetInfo *Aux = S.Context.getAuxTargetInfo(); 390 if (A.getKind() == ParsedAttr::UnknownAttribute || 391 !(A.existsInTarget(S.Context.getTargetInfo()) || 392 (S.Context.getLangOpts().SYCLIsDevice && Aux && 393 A.existsInTarget(*Aux)))) { 394 S.Diag(A.getLoc(), A.isDeclspecAttribute() 395 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored 396 : (unsigned)diag::warn_unknown_attribute_ignored) 397 << A << A.getRange(); 398 return nullptr; 399 } 400 401 if (S.checkCommonAttributeFeatures(St, A)) 402 return nullptr; 403 404 switch (A.getKind()) { 405 case ParsedAttr::AT_FallThrough: 406 return handleFallThroughAttr(S, St, A, Range); 407 case ParsedAttr::AT_LoopHint: 408 return handleLoopHintAttr(S, St, A, Range); 409 case ParsedAttr::AT_OpenCLUnrollHint: 410 return handleOpenCLUnrollHint(S, St, A, Range); 411 case ParsedAttr::AT_Suppress: 412 return handleSuppressAttr(S, St, A, Range); 413 case ParsedAttr::AT_NoMerge: 414 return handleNoMergeAttr(S, St, A, Range); 415 case ParsedAttr::AT_Likely: 416 return handleLikely(S, St, A, Range); 417 case ParsedAttr::AT_Unlikely: 418 return handleUnlikely(S, St, A, Range); 419 default: 420 // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a 421 // declaration attribute is not written on a statement, but this code is 422 // needed for attributes in Attr.td that do not list any subjects. 423 S.Diag(A.getRange().getBegin(), diag::err_decl_attribute_invalid_on_stmt) 424 << A << St->getBeginLoc(); 425 return nullptr; 426 } 427 } 428 429 void Sema::ProcessStmtAttributes(Stmt *S, 430 const ParsedAttributesWithRange &InAttrs, 431 SmallVectorImpl<const Attr *> &OutAttrs) { 432 for (const ParsedAttr &AL : InAttrs) { 433 if (const Attr *A = ProcessStmtAttribute(*this, S, AL, InAttrs.Range)) 434 OutAttrs.push_back(A); 435 } 436 437 CheckForIncompatibleAttributes(*this, OutAttrs); 438 } 439