| 1 | //===--- CGStmt.cpp - Emit LLVM Code from 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 contains code to emit Stmt nodes as LLVM code. |
| 10 | // |
| 11 | //===----------------------------------------------------------------------===// |
| 12 | |
| 13 | #include "CGDebugInfo.h" |
| 14 | #include "CGOpenMPRuntime.h" |
| 15 | #include "CodeGenFunction.h" |
| 16 | #include "CodeGenModule.h" |
| 17 | #include "CodeGenPGO.h" |
| 18 | #include "TargetInfo.h" |
| 19 | #include "clang/AST/Attr.h" |
| 20 | #include "clang/AST/Expr.h" |
| 21 | #include "clang/AST/Stmt.h" |
| 22 | #include "clang/AST/StmtVisitor.h" |
| 23 | #include "clang/Basic/Builtins.h" |
| 24 | #include "clang/Basic/DiagnosticSema.h" |
| 25 | #include "clang/Basic/PrettyStackTrace.h" |
| 26 | #include "clang/Basic/SourceManager.h" |
| 27 | #include "clang/Basic/TargetInfo.h" |
| 28 | #include "llvm/ADT/ArrayRef.h" |
| 29 | #include "llvm/ADT/DenseMap.h" |
| 30 | #include "llvm/ADT/SmallSet.h" |
| 31 | #include "llvm/ADT/StringExtras.h" |
| 32 | #include "llvm/IR/Assumptions.h" |
| 33 | #include "llvm/IR/DataLayout.h" |
| 34 | #include "llvm/IR/InlineAsm.h" |
| 35 | #include "llvm/IR/Intrinsics.h" |
| 36 | #include "llvm/IR/MDBuilder.h" |
| 37 | #include "llvm/Support/SaveAndRestore.h" |
| 38 | #include <optional> |
| 39 | |
| 40 | using namespace clang; |
| 41 | using namespace CodeGen; |
| 42 | |
| 43 | //===----------------------------------------------------------------------===// |
| 44 | // Statement Emission |
| 45 | //===----------------------------------------------------------------------===// |
| 46 | |
| 47 | void CodeGenFunction::EmitStopPoint(const Stmt *S) { |
| 48 | if (CGDebugInfo *DI = getDebugInfo()) { |
| 49 | SourceLocation Loc; |
| 50 | Loc = S->getBeginLoc(); |
| 51 | DI->EmitLocation(Builder, Loc); |
| 52 | |
| 53 | LastStopPoint = Loc; |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | void CodeGenFunction::EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs) { |
| 58 | assert(S && "Null statement?" ); |
| 59 | PGO->setCurrentStmt(S); |
| 60 | |
| 61 | // These statements have their own debug info handling. |
| 62 | if (EmitSimpleStmt(S, Attrs)) |
| 63 | return; |
| 64 | |
| 65 | // Check if we are generating unreachable code. |
| 66 | if (!HaveInsertPoint()) { |
| 67 | // If so, and the statement doesn't contain a label, then we do not need to |
| 68 | // generate actual code. This is safe because (1) the current point is |
| 69 | // unreachable, so we don't need to execute the code, and (2) we've already |
| 70 | // handled the statements which update internal data structures (like the |
| 71 | // local variable map) which could be used by subsequent statements. |
| 72 | if (!ContainsLabel(S)) { |
| 73 | // Verify that any decl statements were handled as simple, they may be in |
| 74 | // scope of subsequent reachable statements. |
| 75 | assert(!isa<DeclStmt>(*S) && "Unexpected DeclStmt!" ); |
| 76 | PGO->markStmtMaybeUsed(S); |
| 77 | return; |
| 78 | } |
| 79 | |
| 80 | // Otherwise, make a new block to hold the code. |
| 81 | EnsureInsertPoint(); |
| 82 | } |
| 83 | |
| 84 | // Generate a stoppoint if we are emitting debug info. |
| 85 | EmitStopPoint(S); |
| 86 | |
| 87 | // Ignore all OpenMP directives except for simd if OpenMP with Simd is |
| 88 | // enabled. |
| 89 | if (getLangOpts().OpenMP && getLangOpts().OpenMPSimd) { |
| 90 | if (const auto *D = dyn_cast<OMPExecutableDirective>(Val: S)) { |
| 91 | EmitSimpleOMPExecutableDirective(D: *D); |
| 92 | return; |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | switch (S->getStmtClass()) { |
| 97 | case Stmt::NoStmtClass: |
| 98 | case Stmt::CXXCatchStmtClass: |
| 99 | case Stmt::SEHExceptStmtClass: |
| 100 | case Stmt::SEHFinallyStmtClass: |
| 101 | case Stmt::MSDependentExistsStmtClass: |
| 102 | llvm_unreachable("invalid statement class to emit generically" ); |
| 103 | case Stmt::NullStmtClass: |
| 104 | case Stmt::CompoundStmtClass: |
| 105 | case Stmt::DeclStmtClass: |
| 106 | case Stmt::LabelStmtClass: |
| 107 | case Stmt::AttributedStmtClass: |
| 108 | case Stmt::GotoStmtClass: |
| 109 | case Stmt::BreakStmtClass: |
| 110 | case Stmt::ContinueStmtClass: |
| 111 | case Stmt::DefaultStmtClass: |
| 112 | case Stmt::CaseStmtClass: |
| 113 | case Stmt::DeferStmtClass: |
| 114 | case Stmt::SEHLeaveStmtClass: |
| 115 | case Stmt::SYCLKernelCallStmtClass: |
| 116 | llvm_unreachable("should have emitted these statements as simple" ); |
| 117 | |
| 118 | #define STMT(Type, Base) |
| 119 | #define ABSTRACT_STMT(Op) |
| 120 | #define EXPR(Type, Base) \ |
| 121 | case Stmt::Type##Class: |
| 122 | #include "clang/AST/StmtNodes.inc" |
| 123 | { |
| 124 | // Remember the block we came in on. |
| 125 | llvm::BasicBlock *incoming = Builder.GetInsertBlock(); |
| 126 | assert(incoming && "expression emission must have an insertion point" ); |
| 127 | |
| 128 | EmitIgnoredExpr(E: cast<Expr>(Val: S)); |
| 129 | |
| 130 | llvm::BasicBlock *outgoing = Builder.GetInsertBlock(); |
| 131 | assert(outgoing && "expression emission cleared block!" ); |
| 132 | |
| 133 | // The expression emitters assume (reasonably!) that the insertion |
| 134 | // point is always set. To maintain that, the call-emission code |
| 135 | // for noreturn functions has to enter a new block with no |
| 136 | // predecessors. We want to kill that block and mark the current |
| 137 | // insertion point unreachable in the common case of a call like |
| 138 | // "exit();". Since expression emission doesn't otherwise create |
| 139 | // blocks with no predecessors, we can just test for that. |
| 140 | // However, we must be careful not to do this to our incoming |
| 141 | // block, because *statement* emission does sometimes create |
| 142 | // reachable blocks which will have no predecessors until later in |
| 143 | // the function. This occurs with, e.g., labels that are not |
| 144 | // reachable by fallthrough. |
| 145 | if (incoming != outgoing && outgoing->use_empty()) { |
| 146 | outgoing->eraseFromParent(); |
| 147 | Builder.ClearInsertionPoint(); |
| 148 | } |
| 149 | break; |
| 150 | } |
| 151 | |
| 152 | case Stmt::IndirectGotoStmtClass: |
| 153 | EmitIndirectGotoStmt(S: cast<IndirectGotoStmt>(Val: *S)); break; |
| 154 | |
| 155 | case Stmt::IfStmtClass: EmitIfStmt(S: cast<IfStmt>(Val: *S)); break; |
| 156 | case Stmt::WhileStmtClass: EmitWhileStmt(S: cast<WhileStmt>(Val: *S), Attrs); break; |
| 157 | case Stmt::DoStmtClass: EmitDoStmt(S: cast<DoStmt>(Val: *S), Attrs); break; |
| 158 | case Stmt::ForStmtClass: EmitForStmt(S: cast<ForStmt>(Val: *S), Attrs); break; |
| 159 | |
| 160 | case Stmt::ReturnStmtClass: EmitReturnStmt(S: cast<ReturnStmt>(Val: *S)); break; |
| 161 | |
| 162 | case Stmt::SwitchStmtClass: EmitSwitchStmt(S: cast<SwitchStmt>(Val: *S)); break; |
| 163 | case Stmt::GCCAsmStmtClass: // Intentional fall-through. |
| 164 | case Stmt::MSAsmStmtClass: EmitAsmStmt(S: cast<AsmStmt>(Val: *S)); break; |
| 165 | case Stmt::CoroutineBodyStmtClass: |
| 166 | EmitCoroutineBody(S: cast<CoroutineBodyStmt>(Val: *S)); |
| 167 | break; |
| 168 | case Stmt::CoreturnStmtClass: |
| 169 | EmitCoreturnStmt(S: cast<CoreturnStmt>(Val: *S)); |
| 170 | break; |
| 171 | case Stmt::CapturedStmtClass: { |
| 172 | const CapturedStmt *CS = cast<CapturedStmt>(Val: S); |
| 173 | EmitCapturedStmt(S: *CS, K: CS->getCapturedRegionKind()); |
| 174 | } |
| 175 | break; |
| 176 | case Stmt::ObjCAtTryStmtClass: |
| 177 | EmitObjCAtTryStmt(S: cast<ObjCAtTryStmt>(Val: *S)); |
| 178 | break; |
| 179 | case Stmt::ObjCAtCatchStmtClass: |
| 180 | llvm_unreachable( |
| 181 | "@catch statements should be handled by EmitObjCAtTryStmt" ); |
| 182 | case Stmt::ObjCAtFinallyStmtClass: |
| 183 | llvm_unreachable( |
| 184 | "@finally statements should be handled by EmitObjCAtTryStmt" ); |
| 185 | case Stmt::ObjCAtThrowStmtClass: |
| 186 | EmitObjCAtThrowStmt(S: cast<ObjCAtThrowStmt>(Val: *S)); |
| 187 | break; |
| 188 | case Stmt::ObjCAtSynchronizedStmtClass: |
| 189 | EmitObjCAtSynchronizedStmt(S: cast<ObjCAtSynchronizedStmt>(Val: *S)); |
| 190 | break; |
| 191 | case Stmt::ObjCForCollectionStmtClass: |
| 192 | EmitObjCForCollectionStmt(S: cast<ObjCForCollectionStmt>(Val: *S)); |
| 193 | break; |
| 194 | case Stmt::ObjCAutoreleasePoolStmtClass: |
| 195 | EmitObjCAutoreleasePoolStmt(S: cast<ObjCAutoreleasePoolStmt>(Val: *S)); |
| 196 | break; |
| 197 | |
| 198 | case Stmt::CXXTryStmtClass: |
| 199 | EmitCXXTryStmt(S: cast<CXXTryStmt>(Val: *S)); |
| 200 | break; |
| 201 | case Stmt::CXXForRangeStmtClass: |
| 202 | EmitCXXForRangeStmt(S: cast<CXXForRangeStmt>(Val: *S), Attrs); |
| 203 | break; |
| 204 | case Stmt::SEHTryStmtClass: |
| 205 | EmitSEHTryStmt(S: cast<SEHTryStmt>(Val: *S)); |
| 206 | break; |
| 207 | case Stmt::OMPMetaDirectiveClass: |
| 208 | EmitOMPMetaDirective(S: cast<OMPMetaDirective>(Val: *S)); |
| 209 | break; |
| 210 | case Stmt::OMPCanonicalLoopClass: |
| 211 | EmitOMPCanonicalLoop(S: cast<OMPCanonicalLoop>(Val: S)); |
| 212 | break; |
| 213 | case Stmt::OMPParallelDirectiveClass: |
| 214 | EmitOMPParallelDirective(S: cast<OMPParallelDirective>(Val: *S)); |
| 215 | break; |
| 216 | case Stmt::OMPSimdDirectiveClass: |
| 217 | EmitOMPSimdDirective(S: cast<OMPSimdDirective>(Val: *S)); |
| 218 | break; |
| 219 | case Stmt::OMPTileDirectiveClass: |
| 220 | EmitOMPTileDirective(S: cast<OMPTileDirective>(Val: *S)); |
| 221 | break; |
| 222 | case Stmt::OMPStripeDirectiveClass: |
| 223 | EmitOMPStripeDirective(S: cast<OMPStripeDirective>(Val: *S)); |
| 224 | break; |
| 225 | case Stmt::OMPUnrollDirectiveClass: |
| 226 | EmitOMPUnrollDirective(S: cast<OMPUnrollDirective>(Val: *S)); |
| 227 | break; |
| 228 | case Stmt::OMPReverseDirectiveClass: |
| 229 | EmitOMPReverseDirective(S: cast<OMPReverseDirective>(Val: *S)); |
| 230 | break; |
| 231 | case Stmt::OMPInterchangeDirectiveClass: |
| 232 | EmitOMPInterchangeDirective(S: cast<OMPInterchangeDirective>(Val: *S)); |
| 233 | break; |
| 234 | case Stmt::OMPFuseDirectiveClass: |
| 235 | EmitOMPFuseDirective(S: cast<OMPFuseDirective>(Val: *S)); |
| 236 | break; |
| 237 | case Stmt::OMPForDirectiveClass: |
| 238 | EmitOMPForDirective(S: cast<OMPForDirective>(Val: *S)); |
| 239 | break; |
| 240 | case Stmt::OMPForSimdDirectiveClass: |
| 241 | EmitOMPForSimdDirective(S: cast<OMPForSimdDirective>(Val: *S)); |
| 242 | break; |
| 243 | case Stmt::OMPSectionsDirectiveClass: |
| 244 | EmitOMPSectionsDirective(S: cast<OMPSectionsDirective>(Val: *S)); |
| 245 | break; |
| 246 | case Stmt::OMPSectionDirectiveClass: |
| 247 | EmitOMPSectionDirective(S: cast<OMPSectionDirective>(Val: *S)); |
| 248 | break; |
| 249 | case Stmt::OMPSingleDirectiveClass: |
| 250 | EmitOMPSingleDirective(S: cast<OMPSingleDirective>(Val: *S)); |
| 251 | break; |
| 252 | case Stmt::OMPMasterDirectiveClass: |
| 253 | EmitOMPMasterDirective(S: cast<OMPMasterDirective>(Val: *S)); |
| 254 | break; |
| 255 | case Stmt::OMPCriticalDirectiveClass: |
| 256 | EmitOMPCriticalDirective(S: cast<OMPCriticalDirective>(Val: *S)); |
| 257 | break; |
| 258 | case Stmt::OMPParallelForDirectiveClass: |
| 259 | EmitOMPParallelForDirective(S: cast<OMPParallelForDirective>(Val: *S)); |
| 260 | break; |
| 261 | case Stmt::OMPParallelForSimdDirectiveClass: |
| 262 | EmitOMPParallelForSimdDirective(S: cast<OMPParallelForSimdDirective>(Val: *S)); |
| 263 | break; |
| 264 | case Stmt::OMPParallelMasterDirectiveClass: |
| 265 | EmitOMPParallelMasterDirective(S: cast<OMPParallelMasterDirective>(Val: *S)); |
| 266 | break; |
| 267 | case Stmt::OMPParallelSectionsDirectiveClass: |
| 268 | EmitOMPParallelSectionsDirective(S: cast<OMPParallelSectionsDirective>(Val: *S)); |
| 269 | break; |
| 270 | case Stmt::OMPTaskDirectiveClass: |
| 271 | EmitOMPTaskDirective(S: cast<OMPTaskDirective>(Val: *S)); |
| 272 | break; |
| 273 | case Stmt::OMPTaskyieldDirectiveClass: |
| 274 | EmitOMPTaskyieldDirective(S: cast<OMPTaskyieldDirective>(Val: *S)); |
| 275 | break; |
| 276 | case Stmt::OMPErrorDirectiveClass: |
| 277 | EmitOMPErrorDirective(S: cast<OMPErrorDirective>(Val: *S)); |
| 278 | break; |
| 279 | case Stmt::OMPBarrierDirectiveClass: |
| 280 | EmitOMPBarrierDirective(S: cast<OMPBarrierDirective>(Val: *S)); |
| 281 | break; |
| 282 | case Stmt::OMPTaskwaitDirectiveClass: |
| 283 | EmitOMPTaskwaitDirective(S: cast<OMPTaskwaitDirective>(Val: *S)); |
| 284 | break; |
| 285 | case Stmt::OMPTaskgroupDirectiveClass: |
| 286 | EmitOMPTaskgroupDirective(S: cast<OMPTaskgroupDirective>(Val: *S)); |
| 287 | break; |
| 288 | case Stmt::OMPFlushDirectiveClass: |
| 289 | EmitOMPFlushDirective(S: cast<OMPFlushDirective>(Val: *S)); |
| 290 | break; |
| 291 | case Stmt::OMPDepobjDirectiveClass: |
| 292 | EmitOMPDepobjDirective(S: cast<OMPDepobjDirective>(Val: *S)); |
| 293 | break; |
| 294 | case Stmt::OMPScanDirectiveClass: |
| 295 | EmitOMPScanDirective(S: cast<OMPScanDirective>(Val: *S)); |
| 296 | break; |
| 297 | case Stmt::OMPOrderedDirectiveClass: |
| 298 | EmitOMPOrderedDirective(S: cast<OMPOrderedDirective>(Val: *S)); |
| 299 | break; |
| 300 | case Stmt::OMPAtomicDirectiveClass: |
| 301 | EmitOMPAtomicDirective(S: cast<OMPAtomicDirective>(Val: *S)); |
| 302 | break; |
| 303 | case Stmt::OMPTargetDirectiveClass: |
| 304 | EmitOMPTargetDirective(S: cast<OMPTargetDirective>(Val: *S)); |
| 305 | break; |
| 306 | case Stmt::OMPTeamsDirectiveClass: |
| 307 | EmitOMPTeamsDirective(S: cast<OMPTeamsDirective>(Val: *S)); |
| 308 | break; |
| 309 | case Stmt::OMPCancellationPointDirectiveClass: |
| 310 | EmitOMPCancellationPointDirective(S: cast<OMPCancellationPointDirective>(Val: *S)); |
| 311 | break; |
| 312 | case Stmt::OMPCancelDirectiveClass: |
| 313 | EmitOMPCancelDirective(S: cast<OMPCancelDirective>(Val: *S)); |
| 314 | break; |
| 315 | case Stmt::OMPTargetDataDirectiveClass: |
| 316 | EmitOMPTargetDataDirective(S: cast<OMPTargetDataDirective>(Val: *S)); |
| 317 | break; |
| 318 | case Stmt::OMPTargetEnterDataDirectiveClass: |
| 319 | EmitOMPTargetEnterDataDirective(S: cast<OMPTargetEnterDataDirective>(Val: *S)); |
| 320 | break; |
| 321 | case Stmt::OMPTargetExitDataDirectiveClass: |
| 322 | EmitOMPTargetExitDataDirective(S: cast<OMPTargetExitDataDirective>(Val: *S)); |
| 323 | break; |
| 324 | case Stmt::OMPTargetParallelDirectiveClass: |
| 325 | EmitOMPTargetParallelDirective(S: cast<OMPTargetParallelDirective>(Val: *S)); |
| 326 | break; |
| 327 | case Stmt::OMPTargetParallelForDirectiveClass: |
| 328 | EmitOMPTargetParallelForDirective(S: cast<OMPTargetParallelForDirective>(Val: *S)); |
| 329 | break; |
| 330 | case Stmt::OMPTaskLoopDirectiveClass: |
| 331 | EmitOMPTaskLoopDirective(S: cast<OMPTaskLoopDirective>(Val: *S)); |
| 332 | break; |
| 333 | case Stmt::OMPTaskLoopSimdDirectiveClass: |
| 334 | EmitOMPTaskLoopSimdDirective(S: cast<OMPTaskLoopSimdDirective>(Val: *S)); |
| 335 | break; |
| 336 | case Stmt::OMPMasterTaskLoopDirectiveClass: |
| 337 | EmitOMPMasterTaskLoopDirective(S: cast<OMPMasterTaskLoopDirective>(Val: *S)); |
| 338 | break; |
| 339 | case Stmt::OMPMaskedTaskLoopDirectiveClass: |
| 340 | EmitOMPMaskedTaskLoopDirective(S: cast<OMPMaskedTaskLoopDirective>(Val: *S)); |
| 341 | break; |
| 342 | case Stmt::OMPMasterTaskLoopSimdDirectiveClass: |
| 343 | EmitOMPMasterTaskLoopSimdDirective( |
| 344 | S: cast<OMPMasterTaskLoopSimdDirective>(Val: *S)); |
| 345 | break; |
| 346 | case Stmt::OMPMaskedTaskLoopSimdDirectiveClass: |
| 347 | EmitOMPMaskedTaskLoopSimdDirective( |
| 348 | S: cast<OMPMaskedTaskLoopSimdDirective>(Val: *S)); |
| 349 | break; |
| 350 | case Stmt::OMPParallelMasterTaskLoopDirectiveClass: |
| 351 | EmitOMPParallelMasterTaskLoopDirective( |
| 352 | S: cast<OMPParallelMasterTaskLoopDirective>(Val: *S)); |
| 353 | break; |
| 354 | case Stmt::OMPParallelMaskedTaskLoopDirectiveClass: |
| 355 | EmitOMPParallelMaskedTaskLoopDirective( |
| 356 | S: cast<OMPParallelMaskedTaskLoopDirective>(Val: *S)); |
| 357 | break; |
| 358 | case Stmt::OMPParallelMasterTaskLoopSimdDirectiveClass: |
| 359 | EmitOMPParallelMasterTaskLoopSimdDirective( |
| 360 | S: cast<OMPParallelMasterTaskLoopSimdDirective>(Val: *S)); |
| 361 | break; |
| 362 | case Stmt::OMPParallelMaskedTaskLoopSimdDirectiveClass: |
| 363 | EmitOMPParallelMaskedTaskLoopSimdDirective( |
| 364 | S: cast<OMPParallelMaskedTaskLoopSimdDirective>(Val: *S)); |
| 365 | break; |
| 366 | case Stmt::OMPDistributeDirectiveClass: |
| 367 | EmitOMPDistributeDirective(S: cast<OMPDistributeDirective>(Val: *S)); |
| 368 | break; |
| 369 | case Stmt::OMPTargetUpdateDirectiveClass: |
| 370 | EmitOMPTargetUpdateDirective(S: cast<OMPTargetUpdateDirective>(Val: *S)); |
| 371 | break; |
| 372 | case Stmt::OMPDistributeParallelForDirectiveClass: |
| 373 | EmitOMPDistributeParallelForDirective( |
| 374 | S: cast<OMPDistributeParallelForDirective>(Val: *S)); |
| 375 | break; |
| 376 | case Stmt::OMPDistributeParallelForSimdDirectiveClass: |
| 377 | EmitOMPDistributeParallelForSimdDirective( |
| 378 | S: cast<OMPDistributeParallelForSimdDirective>(Val: *S)); |
| 379 | break; |
| 380 | case Stmt::OMPDistributeSimdDirectiveClass: |
| 381 | EmitOMPDistributeSimdDirective(S: cast<OMPDistributeSimdDirective>(Val: *S)); |
| 382 | break; |
| 383 | case Stmt::OMPTargetParallelForSimdDirectiveClass: |
| 384 | EmitOMPTargetParallelForSimdDirective( |
| 385 | S: cast<OMPTargetParallelForSimdDirective>(Val: *S)); |
| 386 | break; |
| 387 | case Stmt::OMPTargetSimdDirectiveClass: |
| 388 | EmitOMPTargetSimdDirective(S: cast<OMPTargetSimdDirective>(Val: *S)); |
| 389 | break; |
| 390 | case Stmt::OMPTeamsDistributeDirectiveClass: |
| 391 | EmitOMPTeamsDistributeDirective(S: cast<OMPTeamsDistributeDirective>(Val: *S)); |
| 392 | break; |
| 393 | case Stmt::OMPTeamsDistributeSimdDirectiveClass: |
| 394 | EmitOMPTeamsDistributeSimdDirective( |
| 395 | S: cast<OMPTeamsDistributeSimdDirective>(Val: *S)); |
| 396 | break; |
| 397 | case Stmt::OMPTeamsDistributeParallelForSimdDirectiveClass: |
| 398 | EmitOMPTeamsDistributeParallelForSimdDirective( |
| 399 | S: cast<OMPTeamsDistributeParallelForSimdDirective>(Val: *S)); |
| 400 | break; |
| 401 | case Stmt::OMPTeamsDistributeParallelForDirectiveClass: |
| 402 | EmitOMPTeamsDistributeParallelForDirective( |
| 403 | S: cast<OMPTeamsDistributeParallelForDirective>(Val: *S)); |
| 404 | break; |
| 405 | case Stmt::OMPTargetTeamsDirectiveClass: |
| 406 | EmitOMPTargetTeamsDirective(S: cast<OMPTargetTeamsDirective>(Val: *S)); |
| 407 | break; |
| 408 | case Stmt::OMPTargetTeamsDistributeDirectiveClass: |
| 409 | EmitOMPTargetTeamsDistributeDirective( |
| 410 | S: cast<OMPTargetTeamsDistributeDirective>(Val: *S)); |
| 411 | break; |
| 412 | case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass: |
| 413 | EmitOMPTargetTeamsDistributeParallelForDirective( |
| 414 | S: cast<OMPTargetTeamsDistributeParallelForDirective>(Val: *S)); |
| 415 | break; |
| 416 | case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass: |
| 417 | EmitOMPTargetTeamsDistributeParallelForSimdDirective( |
| 418 | S: cast<OMPTargetTeamsDistributeParallelForSimdDirective>(Val: *S)); |
| 419 | break; |
| 420 | case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass: |
| 421 | EmitOMPTargetTeamsDistributeSimdDirective( |
| 422 | S: cast<OMPTargetTeamsDistributeSimdDirective>(Val: *S)); |
| 423 | break; |
| 424 | case Stmt::OMPInteropDirectiveClass: |
| 425 | EmitOMPInteropDirective(S: cast<OMPInteropDirective>(Val: *S)); |
| 426 | break; |
| 427 | case Stmt::OMPDispatchDirectiveClass: |
| 428 | CGM.ErrorUnsupported(S, Type: "OpenMP dispatch directive" ); |
| 429 | break; |
| 430 | case Stmt::OMPScopeDirectiveClass: |
| 431 | EmitOMPScopeDirective(S: cast<OMPScopeDirective>(Val: *S)); |
| 432 | break; |
| 433 | case Stmt::OMPMaskedDirectiveClass: |
| 434 | EmitOMPMaskedDirective(S: cast<OMPMaskedDirective>(Val: *S)); |
| 435 | break; |
| 436 | case Stmt::OMPGenericLoopDirectiveClass: |
| 437 | EmitOMPGenericLoopDirective(S: cast<OMPGenericLoopDirective>(Val: *S)); |
| 438 | break; |
| 439 | case Stmt::OMPTeamsGenericLoopDirectiveClass: |
| 440 | EmitOMPTeamsGenericLoopDirective(S: cast<OMPTeamsGenericLoopDirective>(Val: *S)); |
| 441 | break; |
| 442 | case Stmt::OMPTargetTeamsGenericLoopDirectiveClass: |
| 443 | EmitOMPTargetTeamsGenericLoopDirective( |
| 444 | S: cast<OMPTargetTeamsGenericLoopDirective>(Val: *S)); |
| 445 | break; |
| 446 | case Stmt::OMPParallelGenericLoopDirectiveClass: |
| 447 | EmitOMPParallelGenericLoopDirective( |
| 448 | S: cast<OMPParallelGenericLoopDirective>(Val: *S)); |
| 449 | break; |
| 450 | case Stmt::OMPTargetParallelGenericLoopDirectiveClass: |
| 451 | EmitOMPTargetParallelGenericLoopDirective( |
| 452 | S: cast<OMPTargetParallelGenericLoopDirective>(Val: *S)); |
| 453 | break; |
| 454 | case Stmt::OMPParallelMaskedDirectiveClass: |
| 455 | EmitOMPParallelMaskedDirective(S: cast<OMPParallelMaskedDirective>(Val: *S)); |
| 456 | break; |
| 457 | case Stmt::OMPAssumeDirectiveClass: |
| 458 | EmitOMPAssumeDirective(S: cast<OMPAssumeDirective>(Val: *S)); |
| 459 | break; |
| 460 | case Stmt::OpenACCComputeConstructClass: |
| 461 | EmitOpenACCComputeConstruct(S: cast<OpenACCComputeConstruct>(Val: *S)); |
| 462 | break; |
| 463 | case Stmt::OpenACCLoopConstructClass: |
| 464 | EmitOpenACCLoopConstruct(S: cast<OpenACCLoopConstruct>(Val: *S)); |
| 465 | break; |
| 466 | case Stmt::OpenACCCombinedConstructClass: |
| 467 | EmitOpenACCCombinedConstruct(S: cast<OpenACCCombinedConstruct>(Val: *S)); |
| 468 | break; |
| 469 | case Stmt::OpenACCDataConstructClass: |
| 470 | EmitOpenACCDataConstruct(S: cast<OpenACCDataConstruct>(Val: *S)); |
| 471 | break; |
| 472 | case Stmt::OpenACCEnterDataConstructClass: |
| 473 | EmitOpenACCEnterDataConstruct(S: cast<OpenACCEnterDataConstruct>(Val: *S)); |
| 474 | break; |
| 475 | case Stmt::OpenACCExitDataConstructClass: |
| 476 | EmitOpenACCExitDataConstruct(S: cast<OpenACCExitDataConstruct>(Val: *S)); |
| 477 | break; |
| 478 | case Stmt::OpenACCHostDataConstructClass: |
| 479 | EmitOpenACCHostDataConstruct(S: cast<OpenACCHostDataConstruct>(Val: *S)); |
| 480 | break; |
| 481 | case Stmt::OpenACCWaitConstructClass: |
| 482 | EmitOpenACCWaitConstruct(S: cast<OpenACCWaitConstruct>(Val: *S)); |
| 483 | break; |
| 484 | case Stmt::OpenACCInitConstructClass: |
| 485 | EmitOpenACCInitConstruct(S: cast<OpenACCInitConstruct>(Val: *S)); |
| 486 | break; |
| 487 | case Stmt::OpenACCShutdownConstructClass: |
| 488 | EmitOpenACCShutdownConstruct(S: cast<OpenACCShutdownConstruct>(Val: *S)); |
| 489 | break; |
| 490 | case Stmt::OpenACCSetConstructClass: |
| 491 | EmitOpenACCSetConstruct(S: cast<OpenACCSetConstruct>(Val: *S)); |
| 492 | break; |
| 493 | case Stmt::OpenACCUpdateConstructClass: |
| 494 | EmitOpenACCUpdateConstruct(S: cast<OpenACCUpdateConstruct>(Val: *S)); |
| 495 | break; |
| 496 | case Stmt::OpenACCAtomicConstructClass: |
| 497 | EmitOpenACCAtomicConstruct(S: cast<OpenACCAtomicConstruct>(Val: *S)); |
| 498 | break; |
| 499 | case Stmt::OpenACCCacheConstructClass: |
| 500 | EmitOpenACCCacheConstruct(S: cast<OpenACCCacheConstruct>(Val: *S)); |
| 501 | break; |
| 502 | } |
| 503 | } |
| 504 | |
| 505 | bool CodeGenFunction::EmitSimpleStmt(const Stmt *S, |
| 506 | ArrayRef<const Attr *> Attrs) { |
| 507 | switch (S->getStmtClass()) { |
| 508 | default: |
| 509 | return false; |
| 510 | case Stmt::NullStmtClass: |
| 511 | break; |
| 512 | case Stmt::CompoundStmtClass: |
| 513 | EmitCompoundStmt(S: cast<CompoundStmt>(Val: *S)); |
| 514 | break; |
| 515 | case Stmt::DeclStmtClass: |
| 516 | EmitDeclStmt(S: cast<DeclStmt>(Val: *S)); |
| 517 | break; |
| 518 | case Stmt::LabelStmtClass: |
| 519 | EmitLabelStmt(S: cast<LabelStmt>(Val: *S)); |
| 520 | break; |
| 521 | case Stmt::AttributedStmtClass: |
| 522 | EmitAttributedStmt(S: cast<AttributedStmt>(Val: *S)); |
| 523 | break; |
| 524 | case Stmt::GotoStmtClass: |
| 525 | EmitGotoStmt(S: cast<GotoStmt>(Val: *S)); |
| 526 | break; |
| 527 | case Stmt::BreakStmtClass: |
| 528 | EmitBreakStmt(S: cast<BreakStmt>(Val: *S)); |
| 529 | break; |
| 530 | case Stmt::ContinueStmtClass: |
| 531 | EmitContinueStmt(S: cast<ContinueStmt>(Val: *S)); |
| 532 | break; |
| 533 | case Stmt::DefaultStmtClass: |
| 534 | EmitDefaultStmt(S: cast<DefaultStmt>(Val: *S), Attrs); |
| 535 | break; |
| 536 | case Stmt::CaseStmtClass: |
| 537 | EmitCaseStmt(S: cast<CaseStmt>(Val: *S), Attrs); |
| 538 | break; |
| 539 | case Stmt::DeferStmtClass: |
| 540 | EmitDeferStmt(S: cast<DeferStmt>(Val: *S)); |
| 541 | break; |
| 542 | case Stmt::SEHLeaveStmtClass: |
| 543 | EmitSEHLeaveStmt(S: cast<SEHLeaveStmt>(Val: *S)); |
| 544 | break; |
| 545 | case Stmt::SYCLKernelCallStmtClass: |
| 546 | // SYCL kernel call statements are generated as wrappers around the body |
| 547 | // of functions declared with the sycl_kernel_entry_point attribute. Such |
| 548 | // functions are used to specify how a SYCL kernel (a function object) is |
| 549 | // to be invoked; the SYCL kernel call statement contains a transformed |
| 550 | // variation of the function body and is used to generate a SYCL kernel |
| 551 | // caller function; a function that serves as the device side entry point |
| 552 | // used to execute the SYCL kernel. The sycl_kernel_entry_point attributed |
| 553 | // function is invoked by host code in order to trigger emission of the |
| 554 | // device side SYCL kernel caller function and to generate metadata needed |
| 555 | // by SYCL run-time library implementations; the function is otherwise |
| 556 | // intended to have no effect. As such, the function body is not evaluated |
| 557 | // as part of the invocation during host compilation (and the function |
| 558 | // should not be called or emitted during device compilation); the SYCL |
| 559 | // kernel call statement is thus handled as a null statement for the |
| 560 | // purpose of code generation. |
| 561 | break; |
| 562 | } |
| 563 | return true; |
| 564 | } |
| 565 | |
| 566 | /// EmitCompoundStmt - Emit a compound statement {..} node. If GetLast is true, |
| 567 | /// this captures the expression result of the last sub-statement and returns it |
| 568 | /// (for use by the statement expression extension). |
| 569 | Address CodeGenFunction::EmitCompoundStmt(const CompoundStmt &S, bool GetLast, |
| 570 | AggValueSlot AggSlot) { |
| 571 | PrettyStackTraceLoc CrashInfo(getContext().getSourceManager(),S.getLBracLoc(), |
| 572 | "LLVM IR generation of compound statement ('{}')" ); |
| 573 | |
| 574 | // Keep track of the current cleanup stack depth, including debug scopes. |
| 575 | LexicalScope Scope(*this, S.getSourceRange()); |
| 576 | |
| 577 | return EmitCompoundStmtWithoutScope(S, GetLast, AVS: AggSlot); |
| 578 | } |
| 579 | |
| 580 | Address |
| 581 | CodeGenFunction::EmitCompoundStmtWithoutScope(const CompoundStmt &S, |
| 582 | bool GetLast, |
| 583 | AggValueSlot AggSlot) { |
| 584 | |
| 585 | for (CompoundStmt::const_body_iterator I = S.body_begin(), |
| 586 | E = S.body_end() - GetLast; |
| 587 | I != E; ++I) |
| 588 | EmitStmt(S: *I); |
| 589 | |
| 590 | Address RetAlloca = Address::invalid(); |
| 591 | if (GetLast) { |
| 592 | // We have to special case labels here. They are statements, but when put |
| 593 | // at the end of a statement expression, they yield the value of their |
| 594 | // subexpression. Handle this by walking through all labels we encounter, |
| 595 | // emitting them before we evaluate the subexpr. |
| 596 | // Similar issues arise for attributed statements. |
| 597 | const Stmt *LastStmt = S.body_back(); |
| 598 | while (!isa<Expr>(Val: LastStmt)) { |
| 599 | if (const auto *LS = dyn_cast<LabelStmt>(Val: LastStmt)) { |
| 600 | EmitLabel(D: LS->getDecl()); |
| 601 | LastStmt = LS->getSubStmt(); |
| 602 | } else if (const auto *AS = dyn_cast<AttributedStmt>(Val: LastStmt)) { |
| 603 | // FIXME: Update this if we ever have attributes that affect the |
| 604 | // semantics of an expression. |
| 605 | LastStmt = AS->getSubStmt(); |
| 606 | } else { |
| 607 | llvm_unreachable("unknown value statement" ); |
| 608 | } |
| 609 | } |
| 610 | |
| 611 | EnsureInsertPoint(); |
| 612 | |
| 613 | const Expr *E = cast<Expr>(Val: LastStmt); |
| 614 | QualType ExprTy = E->getType(); |
| 615 | if (hasAggregateEvaluationKind(T: ExprTy)) { |
| 616 | EmitAggExpr(E, AS: AggSlot); |
| 617 | } else { |
| 618 | // We can't return an RValue here because there might be cleanups at |
| 619 | // the end of the StmtExpr. Because of that, we have to emit the result |
| 620 | // here into a temporary alloca. |
| 621 | RetAlloca = CreateMemTemp(T: ExprTy); |
| 622 | EmitAnyExprToMem(E, Location: RetAlloca, Quals: Qualifiers(), |
| 623 | /*IsInit*/ IsInitializer: false); |
| 624 | } |
| 625 | } |
| 626 | |
| 627 | return RetAlloca; |
| 628 | } |
| 629 | |
| 630 | void CodeGenFunction::SimplifyForwardingBlocks(llvm::BasicBlock *BB) { |
| 631 | llvm::BranchInst *BI = dyn_cast<llvm::BranchInst>(Val: BB->getTerminator()); |
| 632 | |
| 633 | // If there is a cleanup stack, then we it isn't worth trying to |
| 634 | // simplify this block (we would need to remove it from the scope map |
| 635 | // and cleanup entry). |
| 636 | if (!EHStack.empty()) |
| 637 | return; |
| 638 | |
| 639 | // Can only simplify direct branches. |
| 640 | if (!BI || !BI->isUnconditional()) |
| 641 | return; |
| 642 | |
| 643 | // Can only simplify empty blocks. |
| 644 | if (BI->getIterator() != BB->begin()) |
| 645 | return; |
| 646 | |
| 647 | BB->replaceAllUsesWith(V: BI->getSuccessor(i: 0)); |
| 648 | BI->eraseFromParent(); |
| 649 | BB->eraseFromParent(); |
| 650 | } |
| 651 | |
| 652 | void CodeGenFunction::EmitBlock(llvm::BasicBlock *BB, bool IsFinished) { |
| 653 | llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); |
| 654 | |
| 655 | // Fall out of the current block (if necessary). |
| 656 | EmitBranch(Block: BB); |
| 657 | |
| 658 | if (IsFinished && BB->use_empty()) { |
| 659 | delete BB; |
| 660 | return; |
| 661 | } |
| 662 | |
| 663 | // Place the block after the current block, if possible, or else at |
| 664 | // the end of the function. |
| 665 | if (CurBB && CurBB->getParent()) |
| 666 | CurFn->insert(Position: std::next(x: CurBB->getIterator()), BB); |
| 667 | else |
| 668 | CurFn->insert(Position: CurFn->end(), BB); |
| 669 | Builder.SetInsertPoint(BB); |
| 670 | } |
| 671 | |
| 672 | void CodeGenFunction::EmitBranch(llvm::BasicBlock *Target) { |
| 673 | // Emit a branch from the current block to the target one if this |
| 674 | // was a real block. If this was just a fall-through block after a |
| 675 | // terminator, don't emit it. |
| 676 | llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); |
| 677 | |
| 678 | if (!CurBB || CurBB->getTerminator()) { |
| 679 | // If there is no insert point or the previous block is already |
| 680 | // terminated, don't touch it. |
| 681 | } else { |
| 682 | // Otherwise, create a fall-through branch. |
| 683 | Builder.CreateBr(Dest: Target); |
| 684 | } |
| 685 | |
| 686 | Builder.ClearInsertionPoint(); |
| 687 | } |
| 688 | |
| 689 | void CodeGenFunction::EmitBlockAfterUses(llvm::BasicBlock *block) { |
| 690 | bool inserted = false; |
| 691 | for (llvm::User *u : block->users()) { |
| 692 | if (llvm::Instruction *insn = dyn_cast<llvm::Instruction>(Val: u)) { |
| 693 | CurFn->insert(Position: std::next(x: insn->getParent()->getIterator()), BB: block); |
| 694 | inserted = true; |
| 695 | break; |
| 696 | } |
| 697 | } |
| 698 | |
| 699 | if (!inserted) |
| 700 | CurFn->insert(Position: CurFn->end(), BB: block); |
| 701 | |
| 702 | Builder.SetInsertPoint(block); |
| 703 | } |
| 704 | |
| 705 | CodeGenFunction::JumpDest |
| 706 | CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) { |
| 707 | JumpDest &Dest = LabelMap[D]; |
| 708 | if (Dest.isValid()) return Dest; |
| 709 | |
| 710 | // Create, but don't insert, the new block. |
| 711 | Dest = JumpDest(createBasicBlock(name: D->getName()), |
| 712 | EHScopeStack::stable_iterator::invalid(), |
| 713 | NextCleanupDestIndex++); |
| 714 | return Dest; |
| 715 | } |
| 716 | |
| 717 | void CodeGenFunction::EmitLabel(const LabelDecl *D) { |
| 718 | // Add this label to the current lexical scope if we're within any |
| 719 | // normal cleanups. Jumps "in" to this label --- when permitted by |
| 720 | // the language --- may need to be routed around such cleanups. |
| 721 | if (EHStack.hasNormalCleanups() && CurLexicalScope) |
| 722 | CurLexicalScope->addLabel(label: D); |
| 723 | |
| 724 | JumpDest &Dest = LabelMap[D]; |
| 725 | |
| 726 | // If we didn't need a forward reference to this label, just go |
| 727 | // ahead and create a destination at the current scope. |
| 728 | if (!Dest.isValid()) { |
| 729 | Dest = getJumpDestInCurrentScope(Name: D->getName()); |
| 730 | |
| 731 | // Otherwise, we need to give this label a target depth and remove |
| 732 | // it from the branch-fixups list. |
| 733 | } else { |
| 734 | assert(!Dest.getScopeDepth().isValid() && "already emitted label!" ); |
| 735 | Dest.setScopeDepth(EHStack.stable_begin()); |
| 736 | ResolveBranchFixups(Target: Dest.getBlock()); |
| 737 | } |
| 738 | |
| 739 | EmitBlock(BB: Dest.getBlock()); |
| 740 | |
| 741 | // Emit debug info for labels. |
| 742 | if (CGDebugInfo *DI = getDebugInfo()) { |
| 743 | if (CGM.getCodeGenOpts().hasReducedDebugInfo()) { |
| 744 | DI->setLocation(D->getLocation()); |
| 745 | DI->EmitLabel(D, Builder); |
| 746 | } |
| 747 | } |
| 748 | |
| 749 | incrementProfileCounter(S: D->getStmt()); |
| 750 | } |
| 751 | |
| 752 | /// Change the cleanup scope of the labels in this lexical scope to |
| 753 | /// match the scope of the enclosing context. |
| 754 | void CodeGenFunction::LexicalScope::rescopeLabels() { |
| 755 | assert(!Labels.empty()); |
| 756 | EHScopeStack::stable_iterator innermostScope |
| 757 | = CGF.EHStack.getInnermostNormalCleanup(); |
| 758 | |
| 759 | // Change the scope depth of all the labels. |
| 760 | for (const LabelDecl *Label : Labels) { |
| 761 | assert(CGF.LabelMap.count(Label)); |
| 762 | JumpDest &dest = CGF.LabelMap.find(Val: Label)->second; |
| 763 | assert(dest.getScopeDepth().isValid()); |
| 764 | assert(innermostScope.encloses(dest.getScopeDepth())); |
| 765 | dest.setScopeDepth(innermostScope); |
| 766 | } |
| 767 | |
| 768 | // Reparent the labels if the new scope also has cleanups. |
| 769 | if (innermostScope != EHScopeStack::stable_end() && ParentScope) { |
| 770 | ParentScope->Labels.append(in_start: Labels.begin(), in_end: Labels.end()); |
| 771 | } |
| 772 | } |
| 773 | |
| 774 | |
| 775 | void CodeGenFunction::EmitLabelStmt(const LabelStmt &S) { |
| 776 | EmitLabel(D: S.getDecl()); |
| 777 | |
| 778 | // IsEHa - emit eha.scope.begin if it's a side entry of a scope |
| 779 | if (getLangOpts().EHAsynch && S.isSideEntry()) |
| 780 | EmitSehCppScopeBegin(); |
| 781 | |
| 782 | EmitStmt(S: S.getSubStmt()); |
| 783 | } |
| 784 | |
| 785 | void CodeGenFunction::EmitAttributedStmt(const AttributedStmt &S) { |
| 786 | bool nomerge = false; |
| 787 | bool noinline = false; |
| 788 | bool alwaysinline = false; |
| 789 | bool noconvergent = false; |
| 790 | HLSLControlFlowHintAttr::Spelling flattenOrBranch = |
| 791 | HLSLControlFlowHintAttr::SpellingNotCalculated; |
| 792 | const CallExpr *musttail = nullptr; |
| 793 | const AtomicAttr *AA = nullptr; |
| 794 | |
| 795 | for (const auto *A : S.getAttrs()) { |
| 796 | switch (A->getKind()) { |
| 797 | default: |
| 798 | break; |
| 799 | case attr::NoMerge: |
| 800 | nomerge = true; |
| 801 | break; |
| 802 | case attr::NoInline: |
| 803 | noinline = true; |
| 804 | break; |
| 805 | case attr::AlwaysInline: |
| 806 | alwaysinline = true; |
| 807 | break; |
| 808 | case attr::NoConvergent: |
| 809 | noconvergent = true; |
| 810 | break; |
| 811 | case attr::MustTail: { |
| 812 | const Stmt *Sub = S.getSubStmt(); |
| 813 | const ReturnStmt *R = cast<ReturnStmt>(Val: Sub); |
| 814 | musttail = cast<CallExpr>(Val: R->getRetValue()->IgnoreParens()); |
| 815 | } break; |
| 816 | case attr::CXXAssume: { |
| 817 | const Expr *Assumption = cast<CXXAssumeAttr>(Val: A)->getAssumption(); |
| 818 | if (getLangOpts().CXXAssumptions && Builder.GetInsertBlock() && |
| 819 | !Assumption->HasSideEffects(Ctx: getContext())) { |
| 820 | llvm::Value *AssumptionVal = EmitCheckedArgForAssume(E: Assumption); |
| 821 | Builder.CreateAssumption(Cond: AssumptionVal); |
| 822 | } |
| 823 | } break; |
| 824 | case attr::Atomic: |
| 825 | AA = cast<AtomicAttr>(Val: A); |
| 826 | break; |
| 827 | case attr::HLSLControlFlowHint: { |
| 828 | flattenOrBranch = cast<HLSLControlFlowHintAttr>(Val: A)->getSemanticSpelling(); |
| 829 | } break; |
| 830 | } |
| 831 | } |
| 832 | SaveAndRestore save_nomerge(InNoMergeAttributedStmt, nomerge); |
| 833 | SaveAndRestore save_noinline(InNoInlineAttributedStmt, noinline); |
| 834 | SaveAndRestore save_alwaysinline(InAlwaysInlineAttributedStmt, alwaysinline); |
| 835 | SaveAndRestore save_noconvergent(InNoConvergentAttributedStmt, noconvergent); |
| 836 | SaveAndRestore save_musttail(MustTailCall, musttail); |
| 837 | SaveAndRestore save_flattenOrBranch(HLSLControlFlowAttr, flattenOrBranch); |
| 838 | CGAtomicOptionsRAII AORAII(CGM, AA); |
| 839 | EmitStmt(S: S.getSubStmt(), Attrs: S.getAttrs()); |
| 840 | } |
| 841 | |
| 842 | void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) { |
| 843 | // If this code is reachable then emit a stop point (if generating |
| 844 | // debug info). We have to do this ourselves because we are on the |
| 845 | // "simple" statement path. |
| 846 | if (HaveInsertPoint()) |
| 847 | EmitStopPoint(S: &S); |
| 848 | |
| 849 | ApplyAtomGroup Grp(getDebugInfo()); |
| 850 | EmitBranchThroughCleanup(Dest: getJumpDestForLabel(D: S.getLabel())); |
| 851 | } |
| 852 | |
| 853 | |
| 854 | void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) { |
| 855 | ApplyAtomGroup Grp(getDebugInfo()); |
| 856 | if (const LabelDecl *Target = S.getConstantTarget()) { |
| 857 | EmitBranchThroughCleanup(Dest: getJumpDestForLabel(D: Target)); |
| 858 | return; |
| 859 | } |
| 860 | |
| 861 | // Ensure that we have an i8* for our PHI node. |
| 862 | llvm::Value *V = Builder.CreateBitCast(V: EmitScalarExpr(E: S.getTarget()), |
| 863 | DestTy: Int8PtrTy, Name: "addr" ); |
| 864 | llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); |
| 865 | |
| 866 | // Get the basic block for the indirect goto. |
| 867 | llvm::BasicBlock *IndGotoBB = GetIndirectGotoBlock(); |
| 868 | |
| 869 | // The first instruction in the block has to be the PHI for the switch dest, |
| 870 | // add an entry for this branch. |
| 871 | cast<llvm::PHINode>(Val: IndGotoBB->begin())->addIncoming(V, BB: CurBB); |
| 872 | |
| 873 | EmitBranch(Target: IndGotoBB); |
| 874 | if (CurBB && CurBB->getTerminator()) |
| 875 | addInstToCurrentSourceAtom(KeyInstruction: CurBB->getTerminator(), Backup: nullptr); |
| 876 | } |
| 877 | |
| 878 | void CodeGenFunction::EmitIfStmt(const IfStmt &S) { |
| 879 | const Stmt *Else = S.getElse(); |
| 880 | |
| 881 | // The else branch of a consteval if statement is always the only branch that |
| 882 | // can be runtime evaluated. |
| 883 | if (S.isConsteval()) { |
| 884 | const Stmt *Executed = S.isNegatedConsteval() ? S.getThen() : Else; |
| 885 | if (Executed) { |
| 886 | RunCleanupsScope ExecutedScope(*this); |
| 887 | EmitStmt(S: Executed); |
| 888 | } |
| 889 | return; |
| 890 | } |
| 891 | |
| 892 | // C99 6.8.4.1: The first substatement is executed if the expression compares |
| 893 | // unequal to 0. The condition must be a scalar type. |
| 894 | LexicalScope ConditionScope(*this, S.getCond()->getSourceRange()); |
| 895 | ApplyDebugLocation DL(*this, S.getCond()); |
| 896 | |
| 897 | if (S.getInit()) |
| 898 | EmitStmt(S: S.getInit()); |
| 899 | |
| 900 | if (S.getConditionVariable()) |
| 901 | EmitDecl(D: *S.getConditionVariable()); |
| 902 | |
| 903 | // If the condition constant folds and can be elided, try to avoid emitting |
| 904 | // the condition and the dead arm of the if/else. |
| 905 | bool CondConstant; |
| 906 | if (ConstantFoldsToSimpleInteger(Cond: S.getCond(), Result&: CondConstant, |
| 907 | AllowLabels: S.isConstexpr())) { |
| 908 | // Figure out which block (then or else) is executed. |
| 909 | const Stmt *Executed = S.getThen(); |
| 910 | const Stmt *Skipped = Else; |
| 911 | if (!CondConstant) // Condition false? |
| 912 | std::swap(a&: Executed, b&: Skipped); |
| 913 | |
| 914 | // If the skipped block has no labels in it, just emit the executed block. |
| 915 | // This avoids emitting dead code and simplifies the CFG substantially. |
| 916 | if (S.isConstexpr() || !ContainsLabel(S: Skipped)) { |
| 917 | incrementProfileCounter(ExecSkip: CondConstant ? UseExecPath : UseSkipPath, S: &S, |
| 918 | /*UseBoth=*/true); |
| 919 | if (Executed) { |
| 920 | MaybeEmitDeferredVarDeclInit(var: S.getConditionVariable()); |
| 921 | RunCleanupsScope ExecutedScope(*this); |
| 922 | EmitStmt(S: Executed); |
| 923 | } |
| 924 | PGO->markStmtMaybeUsed(S: Skipped); |
| 925 | return; |
| 926 | } |
| 927 | } |
| 928 | |
| 929 | auto HasSkip = hasSkipCounter(S: &S); |
| 930 | |
| 931 | // Otherwise, the condition did not fold, or we couldn't elide it. Just emit |
| 932 | // the conditional branch. |
| 933 | llvm::BasicBlock *ThenBlock = createBasicBlock(name: "if.then" ); |
| 934 | llvm::BasicBlock *ContBlock = createBasicBlock(name: "if.end" ); |
| 935 | llvm::BasicBlock *ElseBlock = |
| 936 | (Else || HasSkip ? createBasicBlock(name: "if.else" ) : ContBlock); |
| 937 | // Prefer the PGO based weights over the likelihood attribute. |
| 938 | // When the build isn't optimized the metadata isn't used, so don't generate |
| 939 | // it. |
| 940 | // Also, differentiate between disabled PGO and a never executed branch with |
| 941 | // PGO. Assuming PGO is in use: |
| 942 | // - we want to ignore the [[likely]] attribute if the branch is never |
| 943 | // executed, |
| 944 | // - assuming the profile is poor, preserving the attribute may still be |
| 945 | // beneficial. |
| 946 | // As an approximation, preserve the attribute only if both the branch and the |
| 947 | // parent context were not executed. |
| 948 | Stmt::Likelihood LH = Stmt::LH_None; |
| 949 | uint64_t ThenCount = getProfileCount(S: S.getThen()); |
| 950 | if (!ThenCount && !getCurrentProfileCount() && |
| 951 | CGM.getCodeGenOpts().OptimizationLevel) |
| 952 | LH = Stmt::getLikelihood(Then: S.getThen(), Else); |
| 953 | |
| 954 | // When measuring MC/DC, always fully evaluate the condition up front using |
| 955 | // EvaluateExprAsBool() so that the test vector bitmap can be updated prior to |
| 956 | // executing the body of the if.then or if.else. This is useful for when |
| 957 | // there is a 'return' within the body, but this is particularly beneficial |
| 958 | // when one if-stmt is nested within another if-stmt so that all of the MC/DC |
| 959 | // updates are kept linear and consistent. |
| 960 | if (!CGM.getCodeGenOpts().MCDCCoverage) { |
| 961 | EmitBranchOnBoolExpr(Cond: S.getCond(), TrueBlock: ThenBlock, FalseBlock: ElseBlock, TrueCount: ThenCount, LH, |
| 962 | /*ConditionalOp=*/nullptr, |
| 963 | /*ConditionalDecl=*/S.getConditionVariable()); |
| 964 | } else { |
| 965 | llvm::Value *BoolCondVal = EvaluateExprAsBool(E: S.getCond()); |
| 966 | MaybeEmitDeferredVarDeclInit(var: S.getConditionVariable()); |
| 967 | Builder.CreateCondBr(Cond: BoolCondVal, True: ThenBlock, False: ElseBlock); |
| 968 | } |
| 969 | |
| 970 | // Emit the 'then' code. |
| 971 | EmitBlock(BB: ThenBlock); |
| 972 | incrementProfileCounter(ExecSkip: UseExecPath, S: &S); |
| 973 | { |
| 974 | RunCleanupsScope ThenScope(*this); |
| 975 | EmitStmt(S: S.getThen()); |
| 976 | } |
| 977 | EmitBranch(Target: ContBlock); |
| 978 | |
| 979 | // Emit the 'else' code if present. |
| 980 | if (Else) { |
| 981 | { |
| 982 | // There is no need to emit line number for an unconditional branch. |
| 983 | auto NL = ApplyDebugLocation::CreateEmpty(CGF&: *this); |
| 984 | EmitBlock(BB: ElseBlock); |
| 985 | } |
| 986 | // Add a counter to else block unless it has CounterExpr. |
| 987 | if (HasSkip) |
| 988 | incrementProfileCounter(ExecSkip: UseSkipPath, S: &S); |
| 989 | { |
| 990 | RunCleanupsScope ElseScope(*this); |
| 991 | EmitStmt(S: Else); |
| 992 | } |
| 993 | { |
| 994 | // There is no need to emit line number for an unconditional branch. |
| 995 | auto NL = ApplyDebugLocation::CreateEmpty(CGF&: *this); |
| 996 | EmitBranch(Target: ContBlock); |
| 997 | } |
| 998 | } else if (HasSkip) { |
| 999 | EmitBlock(BB: ElseBlock); |
| 1000 | incrementProfileCounter(ExecSkip: UseSkipPath, S: &S); |
| 1001 | EmitBranch(Target: ContBlock); |
| 1002 | } |
| 1003 | |
| 1004 | // Emit the continuation block for code after the if. |
| 1005 | EmitBlock(BB: ContBlock, IsFinished: true); |
| 1006 | } |
| 1007 | |
| 1008 | bool CodeGenFunction::checkIfLoopMustProgress(const Expr *ControllingExpression, |
| 1009 | bool HasEmptyBody) { |
| 1010 | if (CGM.getCodeGenOpts().getFiniteLoops() == |
| 1011 | CodeGenOptions::FiniteLoopsKind::Never) |
| 1012 | return false; |
| 1013 | |
| 1014 | // Now apply rules for plain C (see 6.8.5.6 in C11). |
| 1015 | // Loops with constant conditions do not have to make progress in any C |
| 1016 | // version. |
| 1017 | // As an extension, we consisider loops whose constant expression |
| 1018 | // can be constant-folded. |
| 1019 | Expr::EvalResult Result; |
| 1020 | bool CondIsConstInt = |
| 1021 | !ControllingExpression || |
| 1022 | (ControllingExpression->EvaluateAsInt(Result, Ctx: getContext()) && |
| 1023 | Result.Val.isInt()); |
| 1024 | |
| 1025 | bool CondIsTrue = CondIsConstInt && (!ControllingExpression || |
| 1026 | Result.Val.getInt().getBoolValue()); |
| 1027 | |
| 1028 | // Loops with non-constant conditions must make progress in C11 and later. |
| 1029 | if (getLangOpts().C11 && !CondIsConstInt) |
| 1030 | return true; |
| 1031 | |
| 1032 | // [C++26][intro.progress] (DR) |
| 1033 | // The implementation may assume that any thread will eventually do one of the |
| 1034 | // following: |
| 1035 | // [...] |
| 1036 | // - continue execution of a trivial infinite loop ([stmt.iter.general]). |
| 1037 | if (CGM.getCodeGenOpts().getFiniteLoops() == |
| 1038 | CodeGenOptions::FiniteLoopsKind::Always || |
| 1039 | getLangOpts().CPlusPlus11) { |
| 1040 | if (HasEmptyBody && CondIsTrue) { |
| 1041 | CurFn->removeFnAttr(Kind: llvm::Attribute::MustProgress); |
| 1042 | return false; |
| 1043 | } |
| 1044 | return true; |
| 1045 | } |
| 1046 | return false; |
| 1047 | } |
| 1048 | |
| 1049 | // [C++26][stmt.iter.general] (DR) |
| 1050 | // A trivially empty iteration statement is an iteration statement matching one |
| 1051 | // of the following forms: |
| 1052 | // - while ( expression ) ; |
| 1053 | // - while ( expression ) { } |
| 1054 | // - do ; while ( expression ) ; |
| 1055 | // - do { } while ( expression ) ; |
| 1056 | // - for ( init-statement expression(opt); ) ; |
| 1057 | // - for ( init-statement expression(opt); ) { } |
| 1058 | template <typename LoopStmt> static bool hasEmptyLoopBody(const LoopStmt &S) { |
| 1059 | if constexpr (std::is_same_v<LoopStmt, ForStmt>) { |
| 1060 | if (S.getInc()) |
| 1061 | return false; |
| 1062 | } |
| 1063 | const Stmt *Body = S.getBody(); |
| 1064 | if (!Body || isa<NullStmt>(Val: Body)) |
| 1065 | return true; |
| 1066 | if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Val: Body)) |
| 1067 | return Compound->body_empty(); |
| 1068 | return false; |
| 1069 | } |
| 1070 | |
| 1071 | void CodeGenFunction::EmitWhileStmt(const WhileStmt &S, |
| 1072 | ArrayRef<const Attr *> WhileAttrs) { |
| 1073 | // Emit the header for the loop, which will also become |
| 1074 | // the continue target. |
| 1075 | JumpDest = getJumpDestInCurrentScope(Name: "while.cond" ); |
| 1076 | EmitBlock(BB: LoopHeader.getBlock()); |
| 1077 | |
| 1078 | if (CGM.shouldEmitConvergenceTokens()) |
| 1079 | ConvergenceTokenStack.push_back( |
| 1080 | Elt: emitConvergenceLoopToken(BB: LoopHeader.getBlock())); |
| 1081 | |
| 1082 | // Create an exit block for when the condition fails, which will |
| 1083 | // also become the break target. |
| 1084 | JumpDest LoopExit = getJumpDestInCurrentScope(Name: "while.end" ); |
| 1085 | |
| 1086 | // Store the blocks to use for break and continue. |
| 1087 | BreakContinueStack.push_back(Elt: BreakContinue(S, LoopExit, LoopHeader)); |
| 1088 | |
| 1089 | // C++ [stmt.while]p2: |
| 1090 | // When the condition of a while statement is a declaration, the |
| 1091 | // scope of the variable that is declared extends from its point |
| 1092 | // of declaration (3.3.2) to the end of the while statement. |
| 1093 | // [...] |
| 1094 | // The object created in a condition is destroyed and created |
| 1095 | // with each iteration of the loop. |
| 1096 | RunCleanupsScope ConditionScope(*this); |
| 1097 | |
| 1098 | if (S.getConditionVariable()) |
| 1099 | EmitDecl(D: *S.getConditionVariable()); |
| 1100 | |
| 1101 | // Evaluate the conditional in the while header. C99 6.8.5.1: The |
| 1102 | // evaluation of the controlling expression takes place before each |
| 1103 | // execution of the loop body. |
| 1104 | llvm::Value *BoolCondVal = EvaluateExprAsBool(E: S.getCond()); |
| 1105 | |
| 1106 | MaybeEmitDeferredVarDeclInit(var: S.getConditionVariable()); |
| 1107 | |
| 1108 | // while(1) is common, avoid extra exit blocks. Be sure |
| 1109 | // to correctly handle break/continue though. |
| 1110 | llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(Val: BoolCondVal); |
| 1111 | bool EmitBoolCondBranch = !C || !C->isOne(); |
| 1112 | const SourceRange &R = S.getSourceRange(); |
| 1113 | LoopStack.push(Header: LoopHeader.getBlock(), Ctx&: CGM.getContext(), CGOpts: CGM.getCodeGenOpts(), |
| 1114 | Attrs: WhileAttrs, StartLoc: SourceLocToDebugLoc(Location: R.getBegin()), |
| 1115 | EndLoc: SourceLocToDebugLoc(Location: R.getEnd()), |
| 1116 | MustProgress: checkIfLoopMustProgress(ControllingExpression: S.getCond(), HasEmptyBody: hasEmptyLoopBody(S))); |
| 1117 | |
| 1118 | // As long as the condition is true, go to the loop body. |
| 1119 | llvm::BasicBlock *LoopBody = createBasicBlock(name: "while.body" ); |
| 1120 | if (EmitBoolCondBranch) { |
| 1121 | llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); |
| 1122 | if (hasSkipCounter(S: &S) || ConditionScope.requiresCleanups()) |
| 1123 | ExitBlock = createBasicBlock(name: "while.exit" ); |
| 1124 | llvm::MDNode *Weights = |
| 1125 | createProfileWeightsForLoop(Cond: S.getCond(), LoopCount: getProfileCount(S: S.getBody())); |
| 1126 | if (!Weights && CGM.getCodeGenOpts().OptimizationLevel) |
| 1127 | BoolCondVal = emitCondLikelihoodViaExpectIntrinsic( |
| 1128 | Cond: BoolCondVal, LH: Stmt::getLikelihood(S: S.getBody())); |
| 1129 | auto *I = Builder.CreateCondBr(Cond: BoolCondVal, True: LoopBody, False: ExitBlock, BranchWeights: Weights); |
| 1130 | // Key Instructions: Emit the condition and branch as separate source |
| 1131 | // location atoms otherwise we may omit a step onto the loop condition in |
| 1132 | // favour of the `while` keyword. |
| 1133 | // FIXME: We could have the branch as the backup location for the condition, |
| 1134 | // which would probably be a better experience. Explore this later. |
| 1135 | if (auto *CondI = dyn_cast<llvm::Instruction>(Val: BoolCondVal)) |
| 1136 | addInstToNewSourceAtom(KeyInstruction: CondI, Backup: nullptr); |
| 1137 | addInstToNewSourceAtom(KeyInstruction: I, Backup: nullptr); |
| 1138 | |
| 1139 | if (ExitBlock != LoopExit.getBlock()) { |
| 1140 | EmitBlock(BB: ExitBlock); |
| 1141 | incrementProfileCounter(ExecSkip: UseSkipPath, S: &S); |
| 1142 | EmitBranchThroughCleanup(Dest: LoopExit); |
| 1143 | } |
| 1144 | } else if (const Attr *A = Stmt::getLikelihoodAttr(S: S.getBody())) { |
| 1145 | CGM.getDiags().Report(Loc: A->getLocation(), |
| 1146 | DiagID: diag::warn_attribute_has_no_effect_on_infinite_loop) |
| 1147 | << A << A->getRange(); |
| 1148 | CGM.getDiags().Report( |
| 1149 | Loc: S.getWhileLoc(), |
| 1150 | DiagID: diag::note_attribute_has_no_effect_on_infinite_loop_here) |
| 1151 | << SourceRange(S.getWhileLoc(), S.getRParenLoc()); |
| 1152 | } |
| 1153 | |
| 1154 | // Emit the loop body. We have to emit this in a cleanup scope |
| 1155 | // because it might be a singleton DeclStmt. |
| 1156 | { |
| 1157 | RunCleanupsScope BodyScope(*this); |
| 1158 | EmitBlock(BB: LoopBody); |
| 1159 | incrementProfileCounter(ExecSkip: UseExecPath, S: &S); |
| 1160 | EmitStmt(S: S.getBody()); |
| 1161 | } |
| 1162 | |
| 1163 | BreakContinueStack.pop_back(); |
| 1164 | |
| 1165 | // Immediately force cleanup. |
| 1166 | ConditionScope.ForceCleanup(); |
| 1167 | |
| 1168 | EmitStopPoint(S: &S); |
| 1169 | // Branch to the loop header again. |
| 1170 | EmitBranch(Target: LoopHeader.getBlock()); |
| 1171 | |
| 1172 | LoopStack.pop(); |
| 1173 | |
| 1174 | // Emit the exit block. |
| 1175 | EmitBlock(BB: LoopExit.getBlock(), IsFinished: true); |
| 1176 | |
| 1177 | // The LoopHeader typically is just a branch if we skipped emitting |
| 1178 | // a branch, try to erase it. |
| 1179 | if (!EmitBoolCondBranch) { |
| 1180 | SimplifyForwardingBlocks(BB: LoopHeader.getBlock()); |
| 1181 | PGO->markStmtAsUsed(Skipped: true, S: &S); |
| 1182 | } |
| 1183 | |
| 1184 | if (CGM.shouldEmitConvergenceTokens()) |
| 1185 | ConvergenceTokenStack.pop_back(); |
| 1186 | } |
| 1187 | |
| 1188 | void CodeGenFunction::EmitDoStmt(const DoStmt &S, |
| 1189 | ArrayRef<const Attr *> DoAttrs) { |
| 1190 | JumpDest LoopExit = getJumpDestInCurrentScope(Name: "do.end" ); |
| 1191 | JumpDest LoopCond = getJumpDestInCurrentScope(Name: "do.cond" ); |
| 1192 | |
| 1193 | uint64_t ParentCount = getCurrentProfileCount(); |
| 1194 | |
| 1195 | // Store the blocks to use for break and continue. |
| 1196 | BreakContinueStack.push_back(Elt: BreakContinue(S, LoopExit, LoopCond)); |
| 1197 | |
| 1198 | // Emit the body of the loop. |
| 1199 | llvm::BasicBlock *LoopBody = createBasicBlock(name: "do.body" ); |
| 1200 | |
| 1201 | EmitBlockWithFallThrough(BB: LoopBody, S: &S); |
| 1202 | |
| 1203 | if (CGM.shouldEmitConvergenceTokens()) |
| 1204 | ConvergenceTokenStack.push_back(Elt: emitConvergenceLoopToken(BB: LoopBody)); |
| 1205 | |
| 1206 | { |
| 1207 | RunCleanupsScope BodyScope(*this); |
| 1208 | EmitStmt(S: S.getBody()); |
| 1209 | } |
| 1210 | |
| 1211 | EmitBlock(BB: LoopCond.getBlock()); |
| 1212 | |
| 1213 | // C99 6.8.5.2: "The evaluation of the controlling expression takes place |
| 1214 | // after each execution of the loop body." |
| 1215 | |
| 1216 | // Evaluate the conditional in the while header. |
| 1217 | // C99 6.8.5p2/p4: The first substatement is executed if the expression |
| 1218 | // compares unequal to 0. The condition must be a scalar type. |
| 1219 | llvm::Value *BoolCondVal = EvaluateExprAsBool(E: S.getCond()); |
| 1220 | |
| 1221 | BreakContinueStack.pop_back(); |
| 1222 | |
| 1223 | // "do {} while (0)" is common in macros, avoid extra blocks. Be sure |
| 1224 | // to correctly handle break/continue though. |
| 1225 | llvm::ConstantInt *C = dyn_cast<llvm::ConstantInt>(Val: BoolCondVal); |
| 1226 | bool EmitBoolCondBranch = !C || !C->isZero(); |
| 1227 | |
| 1228 | const SourceRange &R = S.getSourceRange(); |
| 1229 | LoopStack.push(Header: LoopBody, Ctx&: CGM.getContext(), CGOpts: CGM.getCodeGenOpts(), Attrs: DoAttrs, |
| 1230 | StartLoc: SourceLocToDebugLoc(Location: R.getBegin()), |
| 1231 | EndLoc: SourceLocToDebugLoc(Location: R.getEnd()), |
| 1232 | MustProgress: checkIfLoopMustProgress(ControllingExpression: S.getCond(), HasEmptyBody: hasEmptyLoopBody(S))); |
| 1233 | |
| 1234 | auto *LoopFalse = (hasSkipCounter(S: &S) ? createBasicBlock(name: "do.loopfalse" ) |
| 1235 | : LoopExit.getBlock()); |
| 1236 | |
| 1237 | // As long as the condition is true, iterate the loop. |
| 1238 | if (EmitBoolCondBranch) { |
| 1239 | uint64_t BackedgeCount = getProfileCount(S: S.getBody()) - ParentCount; |
| 1240 | auto *I = Builder.CreateCondBr( |
| 1241 | Cond: BoolCondVal, True: LoopBody, False: LoopFalse, |
| 1242 | BranchWeights: createProfileWeightsForLoop(Cond: S.getCond(), LoopCount: BackedgeCount)); |
| 1243 | |
| 1244 | // Key Instructions: Emit the condition and branch as separate source |
| 1245 | // location atoms otherwise we may omit a step onto the loop condition in |
| 1246 | // favour of the closing brace. |
| 1247 | // FIXME: We could have the branch as the backup location for the condition, |
| 1248 | // which would probably be a better experience (no jumping to the brace). |
| 1249 | if (auto *CondI = dyn_cast<llvm::Instruction>(Val: BoolCondVal)) |
| 1250 | addInstToNewSourceAtom(KeyInstruction: CondI, Backup: nullptr); |
| 1251 | addInstToNewSourceAtom(KeyInstruction: I, Backup: nullptr); |
| 1252 | } |
| 1253 | |
| 1254 | LoopStack.pop(); |
| 1255 | |
| 1256 | if (LoopFalse != LoopExit.getBlock()) { |
| 1257 | EmitBlock(BB: LoopFalse); |
| 1258 | incrementProfileCounter(ExecSkip: UseSkipPath, S: &S, /*UseBoth=*/true); |
| 1259 | } |
| 1260 | |
| 1261 | // Emit the exit block. |
| 1262 | EmitBlock(BB: LoopExit.getBlock()); |
| 1263 | |
| 1264 | // The DoCond block typically is just a branch if we skipped |
| 1265 | // emitting a branch, try to erase it. |
| 1266 | if (!EmitBoolCondBranch) |
| 1267 | SimplifyForwardingBlocks(BB: LoopCond.getBlock()); |
| 1268 | |
| 1269 | if (CGM.shouldEmitConvergenceTokens()) |
| 1270 | ConvergenceTokenStack.pop_back(); |
| 1271 | } |
| 1272 | |
| 1273 | void CodeGenFunction::EmitForStmt(const ForStmt &S, |
| 1274 | ArrayRef<const Attr *> ForAttrs) { |
| 1275 | JumpDest LoopExit = getJumpDestInCurrentScope(Name: "for.end" ); |
| 1276 | |
| 1277 | std::optional<LexicalScope> ForScope; |
| 1278 | if (getLangOpts().C99 || getLangOpts().CPlusPlus) |
| 1279 | ForScope.emplace(args&: *this, args: S.getSourceRange()); |
| 1280 | |
| 1281 | // Evaluate the first part before the loop. |
| 1282 | if (S.getInit()) |
| 1283 | EmitStmt(S: S.getInit()); |
| 1284 | |
| 1285 | // Start the loop with a block that tests the condition. |
| 1286 | // If there's an increment, the continue scope will be overwritten |
| 1287 | // later. |
| 1288 | JumpDest CondDest = getJumpDestInCurrentScope(Name: "for.cond" ); |
| 1289 | llvm::BasicBlock *CondBlock = CondDest.getBlock(); |
| 1290 | EmitBlock(BB: CondBlock); |
| 1291 | |
| 1292 | if (CGM.shouldEmitConvergenceTokens()) |
| 1293 | ConvergenceTokenStack.push_back(Elt: emitConvergenceLoopToken(BB: CondBlock)); |
| 1294 | |
| 1295 | const SourceRange &R = S.getSourceRange(); |
| 1296 | LoopStack.push(Header: CondBlock, Ctx&: CGM.getContext(), CGOpts: CGM.getCodeGenOpts(), Attrs: ForAttrs, |
| 1297 | StartLoc: SourceLocToDebugLoc(Location: R.getBegin()), |
| 1298 | EndLoc: SourceLocToDebugLoc(Location: R.getEnd()), |
| 1299 | MustProgress: checkIfLoopMustProgress(ControllingExpression: S.getCond(), HasEmptyBody: hasEmptyLoopBody(S))); |
| 1300 | |
| 1301 | // Create a cleanup scope for the condition variable cleanups. |
| 1302 | LexicalScope ConditionScope(*this, S.getSourceRange()); |
| 1303 | |
| 1304 | // If the for loop doesn't have an increment we can just use the condition as |
| 1305 | // the continue block. Otherwise, if there is no condition variable, we can |
| 1306 | // form the continue block now. If there is a condition variable, we can't |
| 1307 | // form the continue block until after we've emitted the condition, because |
| 1308 | // the condition is in scope in the increment, but Sema's jump diagnostics |
| 1309 | // ensure that there are no continues from the condition variable that jump |
| 1310 | // to the loop increment. |
| 1311 | JumpDest Continue; |
| 1312 | if (!S.getInc()) |
| 1313 | Continue = CondDest; |
| 1314 | else if (!S.getConditionVariable()) |
| 1315 | Continue = getJumpDestInCurrentScope(Name: "for.inc" ); |
| 1316 | BreakContinueStack.push_back(Elt: BreakContinue(S, LoopExit, Continue)); |
| 1317 | |
| 1318 | if (S.getCond()) { |
| 1319 | // If the for statement has a condition scope, emit the local variable |
| 1320 | // declaration. |
| 1321 | if (S.getConditionVariable()) { |
| 1322 | EmitDecl(D: *S.getConditionVariable()); |
| 1323 | |
| 1324 | // We have entered the condition variable's scope, so we're now able to |
| 1325 | // jump to the continue block. |
| 1326 | Continue = S.getInc() ? getJumpDestInCurrentScope(Name: "for.inc" ) : CondDest; |
| 1327 | BreakContinueStack.back().ContinueBlock = Continue; |
| 1328 | } |
| 1329 | |
| 1330 | llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); |
| 1331 | // If there are any cleanups between here and the loop-exit scope, |
| 1332 | // create a block to stage a loop exit along. |
| 1333 | if (hasSkipCounter(S: &S) || (ForScope && ForScope->requiresCleanups())) |
| 1334 | ExitBlock = createBasicBlock(name: "for.cond.cleanup" ); |
| 1335 | |
| 1336 | // As long as the condition is true, iterate the loop. |
| 1337 | llvm::BasicBlock *ForBody = createBasicBlock(name: "for.body" ); |
| 1338 | |
| 1339 | // C99 6.8.5p2/p4: The first substatement is executed if the expression |
| 1340 | // compares unequal to 0. The condition must be a scalar type. |
| 1341 | llvm::Value *BoolCondVal = EvaluateExprAsBool(E: S.getCond()); |
| 1342 | |
| 1343 | MaybeEmitDeferredVarDeclInit(var: S.getConditionVariable()); |
| 1344 | |
| 1345 | llvm::MDNode *Weights = |
| 1346 | createProfileWeightsForLoop(Cond: S.getCond(), LoopCount: getProfileCount(S: S.getBody())); |
| 1347 | if (!Weights && CGM.getCodeGenOpts().OptimizationLevel) |
| 1348 | BoolCondVal = emitCondLikelihoodViaExpectIntrinsic( |
| 1349 | Cond: BoolCondVal, LH: Stmt::getLikelihood(S: S.getBody())); |
| 1350 | |
| 1351 | auto *I = Builder.CreateCondBr(Cond: BoolCondVal, True: ForBody, False: ExitBlock, BranchWeights: Weights); |
| 1352 | // Key Instructions: Emit the condition and branch as separate atoms to |
| 1353 | // match existing loop stepping behaviour. FIXME: We could have the branch |
| 1354 | // as the backup location for the condition, which would probably be a |
| 1355 | // better experience (no jumping to the brace). |
| 1356 | if (auto *CondI = dyn_cast<llvm::Instruction>(Val: BoolCondVal)) |
| 1357 | addInstToNewSourceAtom(KeyInstruction: CondI, Backup: nullptr); |
| 1358 | addInstToNewSourceAtom(KeyInstruction: I, Backup: nullptr); |
| 1359 | |
| 1360 | if (ExitBlock != LoopExit.getBlock()) { |
| 1361 | EmitBlock(BB: ExitBlock); |
| 1362 | incrementProfileCounter(ExecSkip: UseSkipPath, S: &S); |
| 1363 | EmitBranchThroughCleanup(Dest: LoopExit); |
| 1364 | } |
| 1365 | |
| 1366 | EmitBlock(BB: ForBody); |
| 1367 | } else { |
| 1368 | // Treat it as a non-zero constant. Don't even create a new block for the |
| 1369 | // body, just fall into it. |
| 1370 | PGO->markStmtAsUsed(Skipped: true, S: &S); |
| 1371 | } |
| 1372 | |
| 1373 | incrementProfileCounter(ExecSkip: UseExecPath, S: &S); |
| 1374 | |
| 1375 | { |
| 1376 | // Create a separate cleanup scope for the body, in case it is not |
| 1377 | // a compound statement. |
| 1378 | RunCleanupsScope BodyScope(*this); |
| 1379 | EmitStmt(S: S.getBody()); |
| 1380 | } |
| 1381 | |
| 1382 | // The last block in the loop's body (which unconditionally branches to the |
| 1383 | // `inc` block if there is one). |
| 1384 | auto *FinalBodyBB = Builder.GetInsertBlock(); |
| 1385 | |
| 1386 | // If there is an increment, emit it next. |
| 1387 | if (S.getInc()) { |
| 1388 | EmitBlock(BB: Continue.getBlock()); |
| 1389 | EmitStmt(S: S.getInc()); |
| 1390 | } |
| 1391 | |
| 1392 | BreakContinueStack.pop_back(); |
| 1393 | |
| 1394 | ConditionScope.ForceCleanup(); |
| 1395 | |
| 1396 | EmitStopPoint(S: &S); |
| 1397 | EmitBranch(Target: CondBlock); |
| 1398 | |
| 1399 | if (ForScope) |
| 1400 | ForScope->ForceCleanup(); |
| 1401 | |
| 1402 | LoopStack.pop(); |
| 1403 | |
| 1404 | // Emit the fall-through block. |
| 1405 | EmitBlock(BB: LoopExit.getBlock(), IsFinished: true); |
| 1406 | |
| 1407 | if (CGM.shouldEmitConvergenceTokens()) |
| 1408 | ConvergenceTokenStack.pop_back(); |
| 1409 | |
| 1410 | if (FinalBodyBB) { |
| 1411 | // Key Instructions: We want the for closing brace to be step-able on to |
| 1412 | // match existing behaviour. |
| 1413 | addInstToNewSourceAtom(KeyInstruction: FinalBodyBB->getTerminator(), Backup: nullptr); |
| 1414 | } |
| 1415 | } |
| 1416 | |
| 1417 | void |
| 1418 | CodeGenFunction::EmitCXXForRangeStmt(const CXXForRangeStmt &S, |
| 1419 | ArrayRef<const Attr *> ForAttrs) { |
| 1420 | JumpDest LoopExit = getJumpDestInCurrentScope(Name: "for.end" ); |
| 1421 | |
| 1422 | LexicalScope ForScope(*this, S.getSourceRange()); |
| 1423 | |
| 1424 | // Evaluate the first pieces before the loop. |
| 1425 | if (S.getInit()) |
| 1426 | EmitStmt(S: S.getInit()); |
| 1427 | EmitStmt(S: S.getRangeStmt()); |
| 1428 | EmitStmt(S: S.getBeginStmt()); |
| 1429 | EmitStmt(S: S.getEndStmt()); |
| 1430 | |
| 1431 | // Start the loop with a block that tests the condition. |
| 1432 | // If there's an increment, the continue scope will be overwritten |
| 1433 | // later. |
| 1434 | llvm::BasicBlock *CondBlock = createBasicBlock(name: "for.cond" ); |
| 1435 | EmitBlock(BB: CondBlock); |
| 1436 | |
| 1437 | if (CGM.shouldEmitConvergenceTokens()) |
| 1438 | ConvergenceTokenStack.push_back(Elt: emitConvergenceLoopToken(BB: CondBlock)); |
| 1439 | |
| 1440 | const SourceRange &R = S.getSourceRange(); |
| 1441 | LoopStack.push(Header: CondBlock, Ctx&: CGM.getContext(), CGOpts: CGM.getCodeGenOpts(), Attrs: ForAttrs, |
| 1442 | StartLoc: SourceLocToDebugLoc(Location: R.getBegin()), |
| 1443 | EndLoc: SourceLocToDebugLoc(Location: R.getEnd())); |
| 1444 | |
| 1445 | // If there are any cleanups between here and the loop-exit scope, |
| 1446 | // create a block to stage a loop exit along. |
| 1447 | llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); |
| 1448 | if (hasSkipCounter(S: &S) || ForScope.requiresCleanups()) |
| 1449 | ExitBlock = createBasicBlock(name: "for.cond.cleanup" ); |
| 1450 | |
| 1451 | // The loop body, consisting of the specified body and the loop variable. |
| 1452 | llvm::BasicBlock *ForBody = createBasicBlock(name: "for.body" ); |
| 1453 | |
| 1454 | // The body is executed if the expression, contextually converted |
| 1455 | // to bool, is true. |
| 1456 | llvm::Value *BoolCondVal = EvaluateExprAsBool(E: S.getCond()); |
| 1457 | llvm::MDNode *Weights = |
| 1458 | createProfileWeightsForLoop(Cond: S.getCond(), LoopCount: getProfileCount(S: S.getBody())); |
| 1459 | if (!Weights && CGM.getCodeGenOpts().OptimizationLevel) |
| 1460 | BoolCondVal = emitCondLikelihoodViaExpectIntrinsic( |
| 1461 | Cond: BoolCondVal, LH: Stmt::getLikelihood(S: S.getBody())); |
| 1462 | auto *I = Builder.CreateCondBr(Cond: BoolCondVal, True: ForBody, False: ExitBlock, BranchWeights: Weights); |
| 1463 | // Key Instructions: Emit the condition and branch as separate atoms to |
| 1464 | // match existing loop stepping behaviour. FIXME: We could have the branch as |
| 1465 | // the backup location for the condition, which would probably be a better |
| 1466 | // experience. |
| 1467 | if (auto *CondI = dyn_cast<llvm::Instruction>(Val: BoolCondVal)) |
| 1468 | addInstToNewSourceAtom(KeyInstruction: CondI, Backup: nullptr); |
| 1469 | addInstToNewSourceAtom(KeyInstruction: I, Backup: nullptr); |
| 1470 | |
| 1471 | if (ExitBlock != LoopExit.getBlock()) { |
| 1472 | EmitBlock(BB: ExitBlock); |
| 1473 | incrementProfileCounter(ExecSkip: UseSkipPath, S: &S); |
| 1474 | EmitBranchThroughCleanup(Dest: LoopExit); |
| 1475 | } |
| 1476 | |
| 1477 | EmitBlock(BB: ForBody); |
| 1478 | incrementProfileCounter(ExecSkip: UseExecPath, S: &S); |
| 1479 | |
| 1480 | // Create a block for the increment. In case of a 'continue', we jump there. |
| 1481 | JumpDest Continue = getJumpDestInCurrentScope(Name: "for.inc" ); |
| 1482 | |
| 1483 | // Store the blocks to use for break and continue. |
| 1484 | BreakContinueStack.push_back(Elt: BreakContinue(S, LoopExit, Continue)); |
| 1485 | |
| 1486 | { |
| 1487 | // Create a separate cleanup scope for the loop variable and body. |
| 1488 | LexicalScope BodyScope(*this, S.getSourceRange()); |
| 1489 | EmitStmt(S: S.getLoopVarStmt()); |
| 1490 | EmitStmt(S: S.getBody()); |
| 1491 | } |
| 1492 | // The last block in the loop's body (which unconditionally branches to the |
| 1493 | // `inc` block if there is one). |
| 1494 | auto *FinalBodyBB = Builder.GetInsertBlock(); |
| 1495 | |
| 1496 | EmitStopPoint(S: &S); |
| 1497 | // If there is an increment, emit it next. |
| 1498 | EmitBlock(BB: Continue.getBlock()); |
| 1499 | EmitStmt(S: S.getInc()); |
| 1500 | |
| 1501 | BreakContinueStack.pop_back(); |
| 1502 | |
| 1503 | EmitBranch(Target: CondBlock); |
| 1504 | |
| 1505 | ForScope.ForceCleanup(); |
| 1506 | |
| 1507 | LoopStack.pop(); |
| 1508 | |
| 1509 | // Emit the fall-through block. |
| 1510 | EmitBlock(BB: LoopExit.getBlock(), IsFinished: true); |
| 1511 | |
| 1512 | if (CGM.shouldEmitConvergenceTokens()) |
| 1513 | ConvergenceTokenStack.pop_back(); |
| 1514 | |
| 1515 | if (FinalBodyBB) { |
| 1516 | // We want the for closing brace to be step-able on to match existing |
| 1517 | // behaviour. |
| 1518 | addInstToNewSourceAtom(KeyInstruction: FinalBodyBB->getTerminator(), Backup: nullptr); |
| 1519 | } |
| 1520 | } |
| 1521 | |
| 1522 | void CodeGenFunction::EmitReturnOfRValue(RValue RV, QualType Ty) { |
| 1523 | if (RV.isScalar()) { |
| 1524 | Builder.CreateStore(Val: RV.getScalarVal(), Addr: ReturnValue); |
| 1525 | } else if (RV.isAggregate()) { |
| 1526 | LValue Dest = MakeAddrLValue(Addr: ReturnValue, T: Ty); |
| 1527 | LValue Src = MakeAddrLValue(Addr: RV.getAggregateAddress(), T: Ty); |
| 1528 | EmitAggregateCopy(Dest, Src, EltTy: Ty, MayOverlap: getOverlapForReturnValue()); |
| 1529 | } else { |
| 1530 | EmitStoreOfComplex(V: RV.getComplexVal(), dest: MakeAddrLValue(Addr: ReturnValue, T: Ty), |
| 1531 | /*init*/ isInit: true); |
| 1532 | } |
| 1533 | EmitBranchThroughCleanup(Dest: ReturnBlock); |
| 1534 | } |
| 1535 | |
| 1536 | namespace { |
| 1537 | // RAII struct used to save and restore a return statment's result expression. |
| 1538 | struct SaveRetExprRAII { |
| 1539 | SaveRetExprRAII(const Expr *RetExpr, CodeGenFunction &CGF) |
| 1540 | : OldRetExpr(CGF.RetExpr), CGF(CGF) { |
| 1541 | CGF.RetExpr = RetExpr; |
| 1542 | } |
| 1543 | ~SaveRetExprRAII() { CGF.RetExpr = OldRetExpr; } |
| 1544 | const Expr *OldRetExpr; |
| 1545 | CodeGenFunction &CGF; |
| 1546 | }; |
| 1547 | } // namespace |
| 1548 | |
| 1549 | /// Determine if the given call uses the swiftasync calling convention. |
| 1550 | static bool isSwiftAsyncCallee(const CallExpr *CE) { |
| 1551 | auto calleeQualType = CE->getCallee()->getType(); |
| 1552 | const FunctionType *calleeType = nullptr; |
| 1553 | if (calleeQualType->isFunctionPointerType() || |
| 1554 | calleeQualType->isFunctionReferenceType() || |
| 1555 | calleeQualType->isBlockPointerType() || |
| 1556 | calleeQualType->isMemberFunctionPointerType()) { |
| 1557 | calleeType = calleeQualType->getPointeeType()->castAs<FunctionType>(); |
| 1558 | } else if (auto *ty = dyn_cast<FunctionType>(Val&: calleeQualType)) { |
| 1559 | calleeType = ty; |
| 1560 | } else if (auto CMCE = dyn_cast<CXXMemberCallExpr>(Val: CE)) { |
| 1561 | if (auto methodDecl = CMCE->getMethodDecl()) { |
| 1562 | // getMethodDecl() doesn't handle member pointers at the moment. |
| 1563 | calleeType = methodDecl->getType()->castAs<FunctionType>(); |
| 1564 | } else { |
| 1565 | return false; |
| 1566 | } |
| 1567 | } else { |
| 1568 | return false; |
| 1569 | } |
| 1570 | return calleeType->getCallConv() == CallingConv::CC_SwiftAsync; |
| 1571 | } |
| 1572 | |
| 1573 | /// EmitReturnStmt - Note that due to GCC extensions, this can have an operand |
| 1574 | /// if the function returns void, or may be missing one if the function returns |
| 1575 | /// non-void. Fun stuff :). |
| 1576 | void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) { |
| 1577 | ApplyAtomGroup Grp(getDebugInfo()); |
| 1578 | if (requiresReturnValueCheck()) { |
| 1579 | llvm::Constant *SLoc = EmitCheckSourceLocation(Loc: S.getBeginLoc()); |
| 1580 | auto *SLocPtr = |
| 1581 | new llvm::GlobalVariable(CGM.getModule(), SLoc->getType(), false, |
| 1582 | llvm::GlobalVariable::PrivateLinkage, SLoc); |
| 1583 | SLocPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
| 1584 | CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV: SLocPtr); |
| 1585 | assert(ReturnLocation.isValid() && "No valid return location" ); |
| 1586 | Builder.CreateStore(Val: SLocPtr, Addr: ReturnLocation); |
| 1587 | } |
| 1588 | |
| 1589 | // Returning from an outlined SEH helper is UB, and we already warn on it. |
| 1590 | if (IsOutlinedSEHHelper) { |
| 1591 | Builder.CreateUnreachable(); |
| 1592 | Builder.ClearInsertionPoint(); |
| 1593 | } |
| 1594 | |
| 1595 | // Emit the result value, even if unused, to evaluate the side effects. |
| 1596 | const Expr *RV = S.getRetValue(); |
| 1597 | |
| 1598 | // Record the result expression of the return statement. The recorded |
| 1599 | // expression is used to determine whether a block capture's lifetime should |
| 1600 | // end at the end of the full expression as opposed to the end of the scope |
| 1601 | // enclosing the block expression. |
| 1602 | // |
| 1603 | // This permits a small, easily-implemented exception to our over-conservative |
| 1604 | // rules about not jumping to statements following block literals with |
| 1605 | // non-trivial cleanups. |
| 1606 | SaveRetExprRAII SaveRetExpr(RV, *this); |
| 1607 | |
| 1608 | RunCleanupsScope cleanupScope(*this); |
| 1609 | if (const auto *EWC = dyn_cast_or_null<ExprWithCleanups>(Val: RV)) |
| 1610 | RV = EWC->getSubExpr(); |
| 1611 | |
| 1612 | // If we're in a swiftasynccall function, and the return expression is a |
| 1613 | // call to a swiftasynccall function, mark the call as the musttail call. |
| 1614 | std::optional<llvm::SaveAndRestore<const CallExpr *>> SaveMustTail; |
| 1615 | if (RV && CurFnInfo && |
| 1616 | CurFnInfo->getASTCallingConvention() == CallingConv::CC_SwiftAsync) { |
| 1617 | if (auto CE = dyn_cast<CallExpr>(Val: RV)) { |
| 1618 | if (isSwiftAsyncCallee(CE)) { |
| 1619 | SaveMustTail.emplace(args&: MustTailCall, args&: CE); |
| 1620 | } |
| 1621 | } |
| 1622 | } |
| 1623 | |
| 1624 | // FIXME: Clean this up by using an LValue for ReturnTemp, |
| 1625 | // EmitStoreThroughLValue, and EmitAnyExpr. |
| 1626 | // Check if the NRVO candidate was not globalized in OpenMP mode. |
| 1627 | if (getLangOpts().ElideConstructors && S.getNRVOCandidate() && |
| 1628 | S.getNRVOCandidate()->isNRVOVariable() && |
| 1629 | (!getLangOpts().OpenMP || |
| 1630 | !CGM.getOpenMPRuntime() |
| 1631 | .getAddressOfLocalVariable(CGF&: *this, VD: S.getNRVOCandidate()) |
| 1632 | .isValid())) { |
| 1633 | // Apply the named return value optimization for this return statement, |
| 1634 | // which means doing nothing: the appropriate result has already been |
| 1635 | // constructed into the NRVO variable. |
| 1636 | |
| 1637 | // If there is an NRVO flag for this variable, set it to 1 into indicate |
| 1638 | // that the cleanup code should not destroy the variable. |
| 1639 | if (llvm::Value *NRVOFlag = NRVOFlags[S.getNRVOCandidate()]) |
| 1640 | Builder.CreateFlagStore(Value: Builder.getTrue(), Addr: NRVOFlag); |
| 1641 | } else if (!ReturnValue.isValid() || (RV && RV->getType()->isVoidType())) { |
| 1642 | // Make sure not to return anything, but evaluate the expression |
| 1643 | // for side effects. |
| 1644 | if (RV) { |
| 1645 | EmitAnyExpr(E: RV); |
| 1646 | } |
| 1647 | } else if (!RV) { |
| 1648 | // Do nothing (return value is left uninitialized) |
| 1649 | } else if (FnRetTy->isReferenceType()) { |
| 1650 | // If this function returns a reference, take the address of the expression |
| 1651 | // rather than the value. |
| 1652 | RValue Result = EmitReferenceBindingToExpr(E: RV); |
| 1653 | auto *I = Builder.CreateStore(Val: Result.getScalarVal(), Addr: ReturnValue); |
| 1654 | addInstToCurrentSourceAtom(KeyInstruction: I, Backup: I->getValueOperand()); |
| 1655 | } else { |
| 1656 | switch (getEvaluationKind(T: RV->getType())) { |
| 1657 | case TEK_Scalar: { |
| 1658 | llvm::Value *Ret = EmitScalarExpr(E: RV); |
| 1659 | if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect) { |
| 1660 | EmitStoreOfScalar(value: Ret, lvalue: MakeAddrLValue(Addr: ReturnValue, T: RV->getType()), |
| 1661 | /*isInit*/ true); |
| 1662 | } else { |
| 1663 | auto *I = Builder.CreateStore(Val: Ret, Addr: ReturnValue); |
| 1664 | addInstToCurrentSourceAtom(KeyInstruction: I, Backup: I->getValueOperand()); |
| 1665 | } |
| 1666 | break; |
| 1667 | } |
| 1668 | case TEK_Complex: |
| 1669 | EmitComplexExprIntoLValue(E: RV, dest: MakeAddrLValue(Addr: ReturnValue, T: RV->getType()), |
| 1670 | /*isInit*/ true); |
| 1671 | break; |
| 1672 | case TEK_Aggregate: |
| 1673 | EmitAggExpr(E: RV, AS: AggValueSlot::forAddr( |
| 1674 | addr: ReturnValue, quals: Qualifiers(), |
| 1675 | isDestructed: AggValueSlot::IsDestructed, |
| 1676 | needsGC: AggValueSlot::DoesNotNeedGCBarriers, |
| 1677 | isAliased: AggValueSlot::IsNotAliased, |
| 1678 | mayOverlap: getOverlapForReturnValue())); |
| 1679 | break; |
| 1680 | } |
| 1681 | } |
| 1682 | |
| 1683 | ++NumReturnExprs; |
| 1684 | if (!RV || RV->isEvaluatable(Ctx: getContext())) |
| 1685 | ++NumSimpleReturnExprs; |
| 1686 | |
| 1687 | cleanupScope.ForceCleanup(); |
| 1688 | EmitBranchThroughCleanup(Dest: ReturnBlock); |
| 1689 | } |
| 1690 | |
| 1691 | void CodeGenFunction::EmitDeclStmt(const DeclStmt &S) { |
| 1692 | // As long as debug info is modeled with instructions, we have to ensure we |
| 1693 | // have a place to insert here and write the stop point here. |
| 1694 | if (HaveInsertPoint()) |
| 1695 | EmitStopPoint(S: &S); |
| 1696 | |
| 1697 | for (const auto *I : S.decls()) |
| 1698 | EmitDecl(D: *I, /*EvaluateConditionDecl=*/true); |
| 1699 | } |
| 1700 | |
| 1701 | auto CodeGenFunction::GetDestForLoopControlStmt(const LoopControlStmt &S) |
| 1702 | -> const BreakContinue * { |
| 1703 | if (!S.hasLabelTarget()) |
| 1704 | return &BreakContinueStack.back(); |
| 1705 | |
| 1706 | const Stmt *LoopOrSwitch = S.getNamedLoopOrSwitch(); |
| 1707 | assert(LoopOrSwitch && "break/continue target not set?" ); |
| 1708 | for (const BreakContinue &BC : llvm::reverse(C&: BreakContinueStack)) |
| 1709 | if (BC.LoopOrSwitch == LoopOrSwitch) |
| 1710 | return &BC; |
| 1711 | |
| 1712 | llvm_unreachable("break/continue target not found" ); |
| 1713 | } |
| 1714 | |
| 1715 | void CodeGenFunction::EmitBreakStmt(const BreakStmt &S) { |
| 1716 | assert(!BreakContinueStack.empty() && "break stmt not in a loop or switch!" ); |
| 1717 | |
| 1718 | // If this code is reachable then emit a stop point (if generating |
| 1719 | // debug info). We have to do this ourselves because we are on the |
| 1720 | // "simple" statement path. |
| 1721 | if (HaveInsertPoint()) |
| 1722 | EmitStopPoint(S: &S); |
| 1723 | |
| 1724 | ApplyAtomGroup Grp(getDebugInfo()); |
| 1725 | EmitBranchThroughCleanup(Dest: GetDestForLoopControlStmt(S)->BreakBlock); |
| 1726 | } |
| 1727 | |
| 1728 | void CodeGenFunction::EmitContinueStmt(const ContinueStmt &S) { |
| 1729 | assert(!BreakContinueStack.empty() && "continue stmt not in a loop!" ); |
| 1730 | |
| 1731 | // If this code is reachable then emit a stop point (if generating |
| 1732 | // debug info). We have to do this ourselves because we are on the |
| 1733 | // "simple" statement path. |
| 1734 | if (HaveInsertPoint()) |
| 1735 | EmitStopPoint(S: &S); |
| 1736 | |
| 1737 | ApplyAtomGroup Grp(getDebugInfo()); |
| 1738 | EmitBranchThroughCleanup(Dest: GetDestForLoopControlStmt(S)->ContinueBlock); |
| 1739 | } |
| 1740 | |
| 1741 | /// EmitCaseStmtRange - If case statement range is not too big then |
| 1742 | /// add multiple cases to switch instruction, one for each value within |
| 1743 | /// the range. If range is too big then emit "if" condition check. |
| 1744 | void CodeGenFunction::EmitCaseStmtRange(const CaseStmt &S, |
| 1745 | ArrayRef<const Attr *> Attrs) { |
| 1746 | assert(S.getRHS() && "Expected RHS value in CaseStmt" ); |
| 1747 | |
| 1748 | llvm::APSInt LHS = S.getLHS()->EvaluateKnownConstInt(Ctx: getContext()); |
| 1749 | llvm::APSInt RHS = S.getRHS()->EvaluateKnownConstInt(Ctx: getContext()); |
| 1750 | |
| 1751 | // Emit the code for this case. We do this first to make sure it is |
| 1752 | // properly chained from our predecessor before generating the |
| 1753 | // switch machinery to enter this block. |
| 1754 | llvm::BasicBlock *CaseDest = createBasicBlock(name: "sw.bb" ); |
| 1755 | EmitBlockWithFallThrough(BB: CaseDest, S: &S); |
| 1756 | EmitStmt(S: S.getSubStmt()); |
| 1757 | |
| 1758 | // If range is empty, do nothing. |
| 1759 | if (LHS.isSigned() ? RHS.slt(RHS: LHS) : RHS.ult(RHS: LHS)) |
| 1760 | return; |
| 1761 | |
| 1762 | Stmt::Likelihood LH = Stmt::getLikelihood(Attrs); |
| 1763 | llvm::APInt Range = RHS - LHS; |
| 1764 | // FIXME: parameters such as this should not be hardcoded. |
| 1765 | if (Range.ult(RHS: llvm::APInt(Range.getBitWidth(), 64))) { |
| 1766 | // Range is small enough to add multiple switch instruction cases. |
| 1767 | uint64_t Total = getProfileCount(S: &S); |
| 1768 | unsigned NCases = Range.getZExtValue() + 1; |
| 1769 | // We only have one region counter for the entire set of cases here, so we |
| 1770 | // need to divide the weights evenly between the generated cases, ensuring |
| 1771 | // that the total weight is preserved. E.g., a weight of 5 over three cases |
| 1772 | // will be distributed as weights of 2, 2, and 1. |
| 1773 | uint64_t Weight = Total / NCases, Rem = Total % NCases; |
| 1774 | for (unsigned I = 0; I != NCases; ++I) { |
| 1775 | if (SwitchWeights) |
| 1776 | SwitchWeights->push_back(Elt: Weight + (Rem ? 1 : 0)); |
| 1777 | else if (SwitchLikelihood) |
| 1778 | SwitchLikelihood->push_back(Elt: LH); |
| 1779 | |
| 1780 | if (Rem) |
| 1781 | Rem--; |
| 1782 | SwitchInsn->addCase(OnVal: Builder.getInt(AI: LHS), Dest: CaseDest); |
| 1783 | ++LHS; |
| 1784 | } |
| 1785 | return; |
| 1786 | } |
| 1787 | |
| 1788 | // The range is too big. Emit "if" condition into a new block, |
| 1789 | // making sure to save and restore the current insertion point. |
| 1790 | llvm::BasicBlock *RestoreBB = Builder.GetInsertBlock(); |
| 1791 | |
| 1792 | // Push this test onto the chain of range checks (which terminates |
| 1793 | // in the default basic block). The switch's default will be changed |
| 1794 | // to the top of this chain after switch emission is complete. |
| 1795 | llvm::BasicBlock *FalseDest = CaseRangeBlock; |
| 1796 | CaseRangeBlock = createBasicBlock(name: "sw.caserange" ); |
| 1797 | |
| 1798 | CurFn->insert(Position: CurFn->end(), BB: CaseRangeBlock); |
| 1799 | Builder.SetInsertPoint(CaseRangeBlock); |
| 1800 | |
| 1801 | // Emit range check. |
| 1802 | llvm::Value *Diff = |
| 1803 | Builder.CreateSub(LHS: SwitchInsn->getCondition(), RHS: Builder.getInt(AI: LHS)); |
| 1804 | llvm::Value *Cond = |
| 1805 | Builder.CreateICmpULE(LHS: Diff, RHS: Builder.getInt(AI: Range), Name: "inbounds" ); |
| 1806 | |
| 1807 | llvm::MDNode *Weights = nullptr; |
| 1808 | if (SwitchWeights) { |
| 1809 | uint64_t ThisCount = getProfileCount(S: &S); |
| 1810 | uint64_t DefaultCount = (*SwitchWeights)[0]; |
| 1811 | Weights = createProfileWeights(TrueCount: ThisCount, FalseCount: DefaultCount); |
| 1812 | |
| 1813 | // Since we're chaining the switch default through each large case range, we |
| 1814 | // need to update the weight for the default, ie, the first case, to include |
| 1815 | // this case. |
| 1816 | (*SwitchWeights)[0] += ThisCount; |
| 1817 | } else if (SwitchLikelihood) |
| 1818 | Cond = emitCondLikelihoodViaExpectIntrinsic(Cond, LH); |
| 1819 | |
| 1820 | Builder.CreateCondBr(Cond, True: CaseDest, False: FalseDest, BranchWeights: Weights); |
| 1821 | |
| 1822 | // Restore the appropriate insertion point. |
| 1823 | if (RestoreBB) |
| 1824 | Builder.SetInsertPoint(RestoreBB); |
| 1825 | else |
| 1826 | Builder.ClearInsertionPoint(); |
| 1827 | } |
| 1828 | |
| 1829 | void CodeGenFunction::EmitCaseStmt(const CaseStmt &S, |
| 1830 | ArrayRef<const Attr *> Attrs) { |
| 1831 | // If there is no enclosing switch instance that we're aware of, then this |
| 1832 | // case statement and its block can be elided. This situation only happens |
| 1833 | // when we've constant-folded the switch, are emitting the constant case, |
| 1834 | // and part of the constant case includes another case statement. For |
| 1835 | // instance: switch (4) { case 4: do { case 5: } while (1); } |
| 1836 | if (!SwitchInsn) { |
| 1837 | EmitStmt(S: S.getSubStmt()); |
| 1838 | return; |
| 1839 | } |
| 1840 | |
| 1841 | // Handle case ranges. |
| 1842 | if (S.getRHS()) { |
| 1843 | EmitCaseStmtRange(S, Attrs); |
| 1844 | return; |
| 1845 | } |
| 1846 | |
| 1847 | llvm::ConstantInt *CaseVal = |
| 1848 | Builder.getInt(AI: S.getLHS()->EvaluateKnownConstInt(Ctx: getContext())); |
| 1849 | |
| 1850 | // Emit debuginfo for the case value if it is an enum value. |
| 1851 | const ConstantExpr *CE; |
| 1852 | if (auto ICE = dyn_cast<ImplicitCastExpr>(Val: S.getLHS())) |
| 1853 | CE = dyn_cast<ConstantExpr>(Val: ICE->getSubExpr()); |
| 1854 | else |
| 1855 | CE = dyn_cast<ConstantExpr>(Val: S.getLHS()); |
| 1856 | if (CE) { |
| 1857 | if (auto DE = dyn_cast<DeclRefExpr>(Val: CE->getSubExpr())) |
| 1858 | if (CGDebugInfo *Dbg = getDebugInfo()) |
| 1859 | if (CGM.getCodeGenOpts().hasReducedDebugInfo()) |
| 1860 | Dbg->EmitGlobalVariable(VD: DE->getDecl(), |
| 1861 | Init: APValue(llvm::APSInt(CaseVal->getValue()))); |
| 1862 | } |
| 1863 | |
| 1864 | if (SwitchLikelihood) |
| 1865 | SwitchLikelihood->push_back(Elt: Stmt::getLikelihood(Attrs)); |
| 1866 | |
| 1867 | // If the body of the case is just a 'break', try to not emit an empty block. |
| 1868 | // If we're profiling or we're not optimizing, leave the block in for better |
| 1869 | // debug and coverage analysis. |
| 1870 | if (!CGM.getCodeGenOpts().hasProfileClangInstr() && |
| 1871 | CGM.getCodeGenOpts().OptimizationLevel > 0 && |
| 1872 | isa<BreakStmt>(Val: S.getSubStmt())) { |
| 1873 | JumpDest Block = BreakContinueStack.back().BreakBlock; |
| 1874 | |
| 1875 | // Only do this optimization if there are no cleanups that need emitting. |
| 1876 | if (isObviouslyBranchWithoutCleanups(Dest: Block)) { |
| 1877 | if (SwitchWeights) |
| 1878 | SwitchWeights->push_back(Elt: getProfileCount(S: &S)); |
| 1879 | SwitchInsn->addCase(OnVal: CaseVal, Dest: Block.getBlock()); |
| 1880 | |
| 1881 | // If there was a fallthrough into this case, make sure to redirect it to |
| 1882 | // the end of the switch as well. |
| 1883 | if (Builder.GetInsertBlock()) { |
| 1884 | Builder.CreateBr(Dest: Block.getBlock()); |
| 1885 | Builder.ClearInsertionPoint(); |
| 1886 | } |
| 1887 | return; |
| 1888 | } |
| 1889 | } |
| 1890 | |
| 1891 | llvm::BasicBlock *CaseDest = createBasicBlock(name: "sw.bb" ); |
| 1892 | EmitBlockWithFallThrough(BB: CaseDest, S: &S); |
| 1893 | if (SwitchWeights) |
| 1894 | SwitchWeights->push_back(Elt: getProfileCount(S: &S)); |
| 1895 | SwitchInsn->addCase(OnVal: CaseVal, Dest: CaseDest); |
| 1896 | |
| 1897 | // Recursively emitting the statement is acceptable, but is not wonderful for |
| 1898 | // code where we have many case statements nested together, i.e.: |
| 1899 | // case 1: |
| 1900 | // case 2: |
| 1901 | // case 3: etc. |
| 1902 | // Handling this recursively will create a new block for each case statement |
| 1903 | // that falls through to the next case which is IR intensive. It also causes |
| 1904 | // deep recursion which can run into stack depth limitations. Handle |
| 1905 | // sequential non-range case statements specially. |
| 1906 | // |
| 1907 | // TODO When the next case has a likelihood attribute the code returns to the |
| 1908 | // recursive algorithm. Maybe improve this case if it becomes common practice |
| 1909 | // to use a lot of attributes. |
| 1910 | const CaseStmt *CurCase = &S; |
| 1911 | const CaseStmt *NextCase = dyn_cast<CaseStmt>(Val: S.getSubStmt()); |
| 1912 | |
| 1913 | // Otherwise, iteratively add consecutive cases to this switch stmt. |
| 1914 | while (NextCase && NextCase->getRHS() == nullptr) { |
| 1915 | CurCase = NextCase; |
| 1916 | llvm::ConstantInt *CaseVal = |
| 1917 | Builder.getInt(AI: CurCase->getLHS()->EvaluateKnownConstInt(Ctx: getContext())); |
| 1918 | |
| 1919 | if (SwitchWeights) |
| 1920 | SwitchWeights->push_back(Elt: getProfileCount(S: NextCase)); |
| 1921 | if (CGM.getCodeGenOpts().hasProfileClangInstr()) { |
| 1922 | CaseDest = createBasicBlock(name: "sw.bb" ); |
| 1923 | EmitBlockWithFallThrough(BB: CaseDest, S: CurCase); |
| 1924 | } |
| 1925 | // Since this loop is only executed when the CaseStmt has no attributes |
| 1926 | // use a hard-coded value. |
| 1927 | if (SwitchLikelihood) |
| 1928 | SwitchLikelihood->push_back(Elt: Stmt::LH_None); |
| 1929 | |
| 1930 | SwitchInsn->addCase(OnVal: CaseVal, Dest: CaseDest); |
| 1931 | NextCase = dyn_cast<CaseStmt>(Val: CurCase->getSubStmt()); |
| 1932 | } |
| 1933 | |
| 1934 | // Generate a stop point for debug info if the case statement is |
| 1935 | // followed by a default statement. A fallthrough case before a |
| 1936 | // default case gets its own branch target. |
| 1937 | if (CurCase->getSubStmt()->getStmtClass() == Stmt::DefaultStmtClass) |
| 1938 | EmitStopPoint(S: CurCase); |
| 1939 | |
| 1940 | // Normal default recursion for non-cases. |
| 1941 | EmitStmt(S: CurCase->getSubStmt()); |
| 1942 | } |
| 1943 | |
| 1944 | void CodeGenFunction::EmitDefaultStmt(const DefaultStmt &S, |
| 1945 | ArrayRef<const Attr *> Attrs) { |
| 1946 | // If there is no enclosing switch instance that we're aware of, then this |
| 1947 | // default statement can be elided. This situation only happens when we've |
| 1948 | // constant-folded the switch. |
| 1949 | if (!SwitchInsn) { |
| 1950 | EmitStmt(S: S.getSubStmt()); |
| 1951 | return; |
| 1952 | } |
| 1953 | |
| 1954 | llvm::BasicBlock *DefaultBlock = SwitchInsn->getDefaultDest(); |
| 1955 | assert(DefaultBlock->empty() && |
| 1956 | "EmitDefaultStmt: Default block already defined?" ); |
| 1957 | |
| 1958 | if (SwitchLikelihood) |
| 1959 | SwitchLikelihood->front() = Stmt::getLikelihood(Attrs); |
| 1960 | |
| 1961 | EmitBlockWithFallThrough(BB: DefaultBlock, S: &S); |
| 1962 | |
| 1963 | EmitStmt(S: S.getSubStmt()); |
| 1964 | } |
| 1965 | |
| 1966 | namespace { |
| 1967 | struct EmitDeferredStatement final : EHScopeStack::Cleanup { |
| 1968 | const DeferStmt &Stmt; |
| 1969 | EmitDeferredStatement(const DeferStmt *Stmt) : Stmt(*Stmt) {} |
| 1970 | |
| 1971 | void Emit(CodeGenFunction &CGF, Flags) override { |
| 1972 | // Take care that any cleanups pushed by the body of a '_Defer' statement |
| 1973 | // don't clobber the current cleanup slot value. |
| 1974 | // |
| 1975 | // Assume we have a scope that pushes a cleanup; when that scope is exited, |
| 1976 | // we need to run that cleanup; this is accomplished by emitting the cleanup |
| 1977 | // into a separate block and then branching to that block at scope exit. |
| 1978 | // |
| 1979 | // Where this gets complicated is if we exit the scope in multiple different |
| 1980 | // ways; e.g. in a 'for' loop, we may exit the scope of its body by falling |
| 1981 | // off the end (in which case we need to run the cleanup and then branch to |
| 1982 | // the increment), or by 'break'ing out of the loop (in which case we need |
| 1983 | // to run the cleanup and then branch to the loop exit block); in both cases |
| 1984 | // we first branch to the cleanup block to run the cleanup, but the block we |
| 1985 | // need to jump to *after* running the cleanup is different. |
| 1986 | // |
| 1987 | // This is accomplished using a local integer variable called the 'cleanup |
| 1988 | // slot': before branching to the cleanup block, we store a value into that |
| 1989 | // slot. Then, in the cleanup block, after running the cleanup, we load the |
| 1990 | // value of that variable and 'switch' on it to branch to the appropriate |
| 1991 | // continuation block. |
| 1992 | // |
| 1993 | // The problem that arises once '_Defer' statements are involved is that the |
| 1994 | // body of a '_Defer' is an arbitrary statement which itself can create more |
| 1995 | // cleanups. This means we may end up overwriting the cleanup slot before we |
| 1996 | // ever have a chance to 'switch' on it, which means that once we *do* get |
| 1997 | // to the 'switch', we end up in whatever block the cleanup code happened to |
| 1998 | // pick as the default 'switch' exit label! |
| 1999 | // |
| 2000 | // That is, what is normally supposed to happen is something like: |
| 2001 | // |
| 2002 | // 1. Store 'X' to cleanup slot. |
| 2003 | // 2. Branch to cleanup block. |
| 2004 | // 3. Execute cleanup. |
| 2005 | // 4. Read value from cleanup slot. |
| 2006 | // 5. Branch to the block associated with 'X'. |
| 2007 | // |
| 2008 | // But if we encounter a _Defer' statement that contains a cleanup, then |
| 2009 | // what might instead happen is: |
| 2010 | // |
| 2011 | // 1. Store 'X' to cleanup slot. |
| 2012 | // 2. Branch to cleanup block. |
| 2013 | // 3. Execute cleanup; this ends up pushing another cleanup, so: |
| 2014 | // 3a. Store 'Y' to cleanup slot. |
| 2015 | // 3b. Run steps 2–5 recursively. |
| 2016 | // 4. Read value from cleanup slot, which is now 'Y' instead of 'X'. |
| 2017 | // 5. Branch to the block associated with 'Y'... which doesn't even |
| 2018 | // exist because the value 'Y' is only meaningful for the inner |
| 2019 | // cleanup. The result is we just branch 'somewhere random'. |
| 2020 | // |
| 2021 | // The rest of the cleanup code simply isn't prepared to handle this case |
| 2022 | // because most other cleanups can't push more cleanups, and thus, emitting |
| 2023 | // other cleanups generally cannot clobber the cleanup slot. |
| 2024 | // |
| 2025 | // To prevent this from happening, save the current cleanup slot value and |
| 2026 | // restore it after emitting the '_Defer' statement. |
| 2027 | llvm::Value *SavedCleanupDest = nullptr; |
| 2028 | if (CGF.NormalCleanupDest.isValid()) |
| 2029 | SavedCleanupDest = |
| 2030 | CGF.Builder.CreateLoad(Addr: CGF.NormalCleanupDest, Name: "cleanup.dest.saved" ); |
| 2031 | |
| 2032 | CGF.EmitStmt(S: Stmt.getBody()); |
| 2033 | |
| 2034 | if (SavedCleanupDest && CGF.HaveInsertPoint()) |
| 2035 | CGF.Builder.CreateStore(Val: SavedCleanupDest, Addr: CGF.NormalCleanupDest); |
| 2036 | |
| 2037 | // Cleanups must end with an insert point. |
| 2038 | CGF.EnsureInsertPoint(); |
| 2039 | } |
| 2040 | }; |
| 2041 | } // namespace |
| 2042 | |
| 2043 | void CodeGenFunction::EmitDeferStmt(const DeferStmt &S) { |
| 2044 | EHStack.pushCleanup<EmitDeferredStatement>(Kind: NormalAndEHCleanup, A: &S); |
| 2045 | } |
| 2046 | |
| 2047 | /// CollectStatementsForCase - Given the body of a 'switch' statement and a |
| 2048 | /// constant value that is being switched on, see if we can dead code eliminate |
| 2049 | /// the body of the switch to a simple series of statements to emit. Basically, |
| 2050 | /// on a switch (5) we want to find these statements: |
| 2051 | /// case 5: |
| 2052 | /// printf(...); <-- |
| 2053 | /// ++i; <-- |
| 2054 | /// break; |
| 2055 | /// |
| 2056 | /// and add them to the ResultStmts vector. If it is unsafe to do this |
| 2057 | /// transformation (for example, one of the elided statements contains a label |
| 2058 | /// that might be jumped to), return CSFC_Failure. If we handled it and 'S' |
| 2059 | /// should include statements after it (e.g. the printf() line is a substmt of |
| 2060 | /// the case) then return CSFC_FallThrough. If we handled it and found a break |
| 2061 | /// statement, then return CSFC_Success. |
| 2062 | /// |
| 2063 | /// If Case is non-null, then we are looking for the specified case, checking |
| 2064 | /// that nothing we jump over contains labels. If Case is null, then we found |
| 2065 | /// the case and are looking for the break. |
| 2066 | /// |
| 2067 | /// If the recursive walk actually finds our Case, then we set FoundCase to |
| 2068 | /// true. |
| 2069 | /// |
| 2070 | enum CSFC_Result { CSFC_Failure, CSFC_FallThrough, CSFC_Success }; |
| 2071 | static CSFC_Result CollectStatementsForCase(const Stmt *S, |
| 2072 | const SwitchCase *Case, |
| 2073 | bool &FoundCase, |
| 2074 | SmallVectorImpl<const Stmt*> &ResultStmts) { |
| 2075 | // If this is a null statement, just succeed. |
| 2076 | if (!S) |
| 2077 | return Case ? CSFC_Success : CSFC_FallThrough; |
| 2078 | |
| 2079 | // If this is the switchcase (case 4: or default) that we're looking for, then |
| 2080 | // we're in business. Just add the substatement. |
| 2081 | if (const SwitchCase *SC = dyn_cast<SwitchCase>(Val: S)) { |
| 2082 | if (S == Case) { |
| 2083 | FoundCase = true; |
| 2084 | return CollectStatementsForCase(S: SC->getSubStmt(), Case: nullptr, FoundCase, |
| 2085 | ResultStmts); |
| 2086 | } |
| 2087 | |
| 2088 | // Otherwise, this is some other case or default statement, just ignore it. |
| 2089 | return CollectStatementsForCase(S: SC->getSubStmt(), Case, FoundCase, |
| 2090 | ResultStmts); |
| 2091 | } |
| 2092 | |
| 2093 | // If we are in the live part of the code and we found our break statement, |
| 2094 | // return a success! |
| 2095 | if (!Case && isa<BreakStmt>(Val: S)) |
| 2096 | return CSFC_Success; |
| 2097 | |
| 2098 | // If this is a switch statement, then it might contain the SwitchCase, the |
| 2099 | // break, or neither. |
| 2100 | if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(Val: S)) { |
| 2101 | // Handle this as two cases: we might be looking for the SwitchCase (if so |
| 2102 | // the skipped statements must be skippable) or we might already have it. |
| 2103 | CompoundStmt::const_body_iterator I = CS->body_begin(), E = CS->body_end(); |
| 2104 | bool StartedInLiveCode = FoundCase; |
| 2105 | unsigned StartSize = ResultStmts.size(); |
| 2106 | |
| 2107 | // If we've not found the case yet, scan through looking for it. |
| 2108 | if (Case) { |
| 2109 | // Keep track of whether we see a skipped declaration. The code could be |
| 2110 | // using the declaration even if it is skipped, so we can't optimize out |
| 2111 | // the decl if the kept statements might refer to it. |
| 2112 | bool HadSkippedDecl = false; |
| 2113 | |
| 2114 | // If we're looking for the case, just see if we can skip each of the |
| 2115 | // substatements. |
| 2116 | for (; Case && I != E; ++I) { |
| 2117 | HadSkippedDecl |= CodeGenFunction::mightAddDeclToScope(S: *I); |
| 2118 | |
| 2119 | switch (CollectStatementsForCase(S: *I, Case, FoundCase, ResultStmts)) { |
| 2120 | case CSFC_Failure: return CSFC_Failure; |
| 2121 | case CSFC_Success: |
| 2122 | // A successful result means that either 1) that the statement doesn't |
| 2123 | // have the case and is skippable, or 2) does contain the case value |
| 2124 | // and also contains the break to exit the switch. In the later case, |
| 2125 | // we just verify the rest of the statements are elidable. |
| 2126 | if (FoundCase) { |
| 2127 | // If we found the case and skipped declarations, we can't do the |
| 2128 | // optimization. |
| 2129 | if (HadSkippedDecl) |
| 2130 | return CSFC_Failure; |
| 2131 | |
| 2132 | for (++I; I != E; ++I) |
| 2133 | if (CodeGenFunction::ContainsLabel(S: *I, IgnoreCaseStmts: true)) |
| 2134 | return CSFC_Failure; |
| 2135 | return CSFC_Success; |
| 2136 | } |
| 2137 | break; |
| 2138 | case CSFC_FallThrough: |
| 2139 | // If we have a fallthrough condition, then we must have found the |
| 2140 | // case started to include statements. Consider the rest of the |
| 2141 | // statements in the compound statement as candidates for inclusion. |
| 2142 | assert(FoundCase && "Didn't find case but returned fallthrough?" ); |
| 2143 | // We recursively found Case, so we're not looking for it anymore. |
| 2144 | Case = nullptr; |
| 2145 | |
| 2146 | // If we found the case and skipped declarations, we can't do the |
| 2147 | // optimization. |
| 2148 | if (HadSkippedDecl) |
| 2149 | return CSFC_Failure; |
| 2150 | break; |
| 2151 | } |
| 2152 | } |
| 2153 | |
| 2154 | if (!FoundCase) |
| 2155 | return CSFC_Success; |
| 2156 | |
| 2157 | assert(!HadSkippedDecl && "fallthrough after skipping decl" ); |
| 2158 | } |
| 2159 | |
| 2160 | // If we have statements in our range, then we know that the statements are |
| 2161 | // live and need to be added to the set of statements we're tracking. |
| 2162 | bool AnyDecls = false; |
| 2163 | for (; I != E; ++I) { |
| 2164 | AnyDecls |= CodeGenFunction::mightAddDeclToScope(S: *I); |
| 2165 | |
| 2166 | switch (CollectStatementsForCase(S: *I, Case: nullptr, FoundCase, ResultStmts)) { |
| 2167 | case CSFC_Failure: return CSFC_Failure; |
| 2168 | case CSFC_FallThrough: |
| 2169 | // A fallthrough result means that the statement was simple and just |
| 2170 | // included in ResultStmt, keep adding them afterwards. |
| 2171 | break; |
| 2172 | case CSFC_Success: |
| 2173 | // A successful result means that we found the break statement and |
| 2174 | // stopped statement inclusion. We just ensure that any leftover stmts |
| 2175 | // are skippable and return success ourselves. |
| 2176 | for (++I; I != E; ++I) |
| 2177 | if (CodeGenFunction::ContainsLabel(S: *I, IgnoreCaseStmts: true)) |
| 2178 | return CSFC_Failure; |
| 2179 | return CSFC_Success; |
| 2180 | } |
| 2181 | } |
| 2182 | |
| 2183 | // If we're about to fall out of a scope without hitting a 'break;', we |
| 2184 | // can't perform the optimization if there were any decls in that scope |
| 2185 | // (we'd lose their end-of-lifetime). |
| 2186 | if (AnyDecls) { |
| 2187 | // If the entire compound statement was live, there's one more thing we |
| 2188 | // can try before giving up: emit the whole thing as a single statement. |
| 2189 | // We can do that unless the statement contains a 'break;'. |
| 2190 | // FIXME: Such a break must be at the end of a construct within this one. |
| 2191 | // We could emit this by just ignoring the BreakStmts entirely. |
| 2192 | if (StartedInLiveCode && !CodeGenFunction::containsBreak(S)) { |
| 2193 | ResultStmts.resize(N: StartSize); |
| 2194 | ResultStmts.push_back(Elt: S); |
| 2195 | } else { |
| 2196 | return CSFC_Failure; |
| 2197 | } |
| 2198 | } |
| 2199 | |
| 2200 | return CSFC_FallThrough; |
| 2201 | } |
| 2202 | |
| 2203 | // Okay, this is some other statement that we don't handle explicitly, like a |
| 2204 | // for statement or increment etc. If we are skipping over this statement, |
| 2205 | // just verify it doesn't have labels, which would make it invalid to elide. |
| 2206 | if (Case) { |
| 2207 | if (CodeGenFunction::ContainsLabel(S, IgnoreCaseStmts: true)) |
| 2208 | return CSFC_Failure; |
| 2209 | return CSFC_Success; |
| 2210 | } |
| 2211 | |
| 2212 | // Otherwise, we want to include this statement. Everything is cool with that |
| 2213 | // so long as it doesn't contain a break out of the switch we're in. |
| 2214 | if (CodeGenFunction::containsBreak(S)) return CSFC_Failure; |
| 2215 | |
| 2216 | // Otherwise, everything is great. Include the statement and tell the caller |
| 2217 | // that we fall through and include the next statement as well. |
| 2218 | ResultStmts.push_back(Elt: S); |
| 2219 | return CSFC_FallThrough; |
| 2220 | } |
| 2221 | |
| 2222 | /// FindCaseStatementsForValue - Find the case statement being jumped to and |
| 2223 | /// then invoke CollectStatementsForCase to find the list of statements to emit |
| 2224 | /// for a switch on constant. See the comment above CollectStatementsForCase |
| 2225 | /// for more details. |
| 2226 | static bool FindCaseStatementsForValue(const SwitchStmt &S, |
| 2227 | const llvm::APSInt &ConstantCondValue, |
| 2228 | SmallVectorImpl<const Stmt*> &ResultStmts, |
| 2229 | ASTContext &C, |
| 2230 | const SwitchCase *&ResultCase) { |
| 2231 | // First step, find the switch case that is being branched to. We can do this |
| 2232 | // efficiently by scanning the SwitchCase list. |
| 2233 | const SwitchCase *Case = S.getSwitchCaseList(); |
| 2234 | const DefaultStmt *DefaultCase = nullptr; |
| 2235 | |
| 2236 | for (; Case; Case = Case->getNextSwitchCase()) { |
| 2237 | // It's either a default or case. Just remember the default statement in |
| 2238 | // case we're not jumping to any numbered cases. |
| 2239 | if (const DefaultStmt *DS = dyn_cast<DefaultStmt>(Val: Case)) { |
| 2240 | DefaultCase = DS; |
| 2241 | continue; |
| 2242 | } |
| 2243 | |
| 2244 | // Check to see if this case is the one we're looking for. |
| 2245 | const CaseStmt *CS = cast<CaseStmt>(Val: Case); |
| 2246 | // Don't handle case ranges yet. |
| 2247 | if (CS->getRHS()) return false; |
| 2248 | |
| 2249 | // If we found our case, remember it as 'case'. |
| 2250 | if (CS->getLHS()->EvaluateKnownConstInt(Ctx: C) == ConstantCondValue) |
| 2251 | break; |
| 2252 | } |
| 2253 | |
| 2254 | // If we didn't find a matching case, we use a default if it exists, or we |
| 2255 | // elide the whole switch body! |
| 2256 | if (!Case) { |
| 2257 | // It is safe to elide the body of the switch if it doesn't contain labels |
| 2258 | // etc. If it is safe, return successfully with an empty ResultStmts list. |
| 2259 | if (!DefaultCase) |
| 2260 | return !CodeGenFunction::ContainsLabel(S: &S); |
| 2261 | Case = DefaultCase; |
| 2262 | } |
| 2263 | |
| 2264 | // Ok, we know which case is being jumped to, try to collect all the |
| 2265 | // statements that follow it. This can fail for a variety of reasons. Also, |
| 2266 | // check to see that the recursive walk actually found our case statement. |
| 2267 | // Insane cases like this can fail to find it in the recursive walk since we |
| 2268 | // don't handle every stmt kind: |
| 2269 | // switch (4) { |
| 2270 | // while (1) { |
| 2271 | // case 4: ... |
| 2272 | bool FoundCase = false; |
| 2273 | ResultCase = Case; |
| 2274 | return CollectStatementsForCase(S: S.getBody(), Case, FoundCase, |
| 2275 | ResultStmts) != CSFC_Failure && |
| 2276 | FoundCase; |
| 2277 | } |
| 2278 | |
| 2279 | static std::optional<SmallVector<uint64_t, 16>> |
| 2280 | getLikelihoodWeights(ArrayRef<Stmt::Likelihood> Likelihoods) { |
| 2281 | // Are there enough branches to weight them? |
| 2282 | if (Likelihoods.size() <= 1) |
| 2283 | return std::nullopt; |
| 2284 | |
| 2285 | uint64_t NumUnlikely = 0; |
| 2286 | uint64_t NumNone = 0; |
| 2287 | uint64_t NumLikely = 0; |
| 2288 | for (const auto LH : Likelihoods) { |
| 2289 | switch (LH) { |
| 2290 | case Stmt::LH_Unlikely: |
| 2291 | ++NumUnlikely; |
| 2292 | break; |
| 2293 | case Stmt::LH_None: |
| 2294 | ++NumNone; |
| 2295 | break; |
| 2296 | case Stmt::LH_Likely: |
| 2297 | ++NumLikely; |
| 2298 | break; |
| 2299 | } |
| 2300 | } |
| 2301 | |
| 2302 | // Is there a likelihood attribute used? |
| 2303 | if (NumUnlikely == 0 && NumLikely == 0) |
| 2304 | return std::nullopt; |
| 2305 | |
| 2306 | // When multiple cases share the same code they can be combined during |
| 2307 | // optimization. In that case the weights of the branch will be the sum of |
| 2308 | // the individual weights. Make sure the combined sum of all neutral cases |
| 2309 | // doesn't exceed the value of a single likely attribute. |
| 2310 | // The additions both avoid divisions by 0 and make sure the weights of None |
| 2311 | // don't exceed the weight of Likely. |
| 2312 | const uint64_t Likely = INT32_MAX / (NumLikely + 2); |
| 2313 | const uint64_t None = Likely / (NumNone + 1); |
| 2314 | const uint64_t Unlikely = 0; |
| 2315 | |
| 2316 | SmallVector<uint64_t, 16> Result; |
| 2317 | Result.reserve(N: Likelihoods.size()); |
| 2318 | for (const auto LH : Likelihoods) { |
| 2319 | switch (LH) { |
| 2320 | case Stmt::LH_Unlikely: |
| 2321 | Result.push_back(Elt: Unlikely); |
| 2322 | break; |
| 2323 | case Stmt::LH_None: |
| 2324 | Result.push_back(Elt: None); |
| 2325 | break; |
| 2326 | case Stmt::LH_Likely: |
| 2327 | Result.push_back(Elt: Likely); |
| 2328 | break; |
| 2329 | } |
| 2330 | } |
| 2331 | |
| 2332 | return Result; |
| 2333 | } |
| 2334 | |
| 2335 | void CodeGenFunction::EmitSwitchStmt(const SwitchStmt &S) { |
| 2336 | // Handle nested switch statements. |
| 2337 | llvm::SwitchInst *SavedSwitchInsn = SwitchInsn; |
| 2338 | SmallVector<uint64_t, 16> *SavedSwitchWeights = SwitchWeights; |
| 2339 | SmallVector<Stmt::Likelihood, 16> *SavedSwitchLikelihood = SwitchLikelihood; |
| 2340 | llvm::BasicBlock *SavedCRBlock = CaseRangeBlock; |
| 2341 | |
| 2342 | // See if we can constant fold the condition of the switch and therefore only |
| 2343 | // emit the live case statement (if any) of the switch. |
| 2344 | llvm::APSInt ConstantCondValue; |
| 2345 | if (ConstantFoldsToSimpleInteger(Cond: S.getCond(), Result&: ConstantCondValue)) { |
| 2346 | SmallVector<const Stmt*, 4> CaseStmts; |
| 2347 | const SwitchCase *Case = nullptr; |
| 2348 | if (FindCaseStatementsForValue(S, ConstantCondValue, ResultStmts&: CaseStmts, |
| 2349 | C&: getContext(), ResultCase&: Case)) { |
| 2350 | if (Case) |
| 2351 | incrementProfileCounter(S: Case); |
| 2352 | RunCleanupsScope ExecutedScope(*this); |
| 2353 | |
| 2354 | if (S.getInit()) |
| 2355 | EmitStmt(S: S.getInit()); |
| 2356 | |
| 2357 | // Emit the condition variable if needed inside the entire cleanup scope |
| 2358 | // used by this special case for constant folded switches. |
| 2359 | if (S.getConditionVariable()) |
| 2360 | EmitDecl(D: *S.getConditionVariable(), /*EvaluateConditionDecl=*/true); |
| 2361 | |
| 2362 | // At this point, we are no longer "within" a switch instance, so |
| 2363 | // we can temporarily enforce this to ensure that any embedded case |
| 2364 | // statements are not emitted. |
| 2365 | SwitchInsn = nullptr; |
| 2366 | |
| 2367 | // Okay, we can dead code eliminate everything except this case. Emit the |
| 2368 | // specified series of statements and we're good. |
| 2369 | for (const Stmt *CaseStmt : CaseStmts) |
| 2370 | EmitStmt(S: CaseStmt); |
| 2371 | incrementProfileCounter(S: &S); |
| 2372 | PGO->markStmtMaybeUsed(S: S.getBody()); |
| 2373 | |
| 2374 | // Now we want to restore the saved switch instance so that nested |
| 2375 | // switches continue to function properly |
| 2376 | SwitchInsn = SavedSwitchInsn; |
| 2377 | |
| 2378 | return; |
| 2379 | } |
| 2380 | } |
| 2381 | |
| 2382 | JumpDest SwitchExit = getJumpDestInCurrentScope(Name: "sw.epilog" ); |
| 2383 | |
| 2384 | RunCleanupsScope ConditionScope(*this); |
| 2385 | |
| 2386 | if (S.getInit()) |
| 2387 | EmitStmt(S: S.getInit()); |
| 2388 | |
| 2389 | if (S.getConditionVariable()) |
| 2390 | EmitDecl(D: *S.getConditionVariable()); |
| 2391 | llvm::Value *CondV = EmitScalarExpr(E: S.getCond()); |
| 2392 | MaybeEmitDeferredVarDeclInit(var: S.getConditionVariable()); |
| 2393 | |
| 2394 | // Create basic block to hold stuff that comes after switch |
| 2395 | // statement. We also need to create a default block now so that |
| 2396 | // explicit case ranges tests can have a place to jump to on |
| 2397 | // failure. |
| 2398 | llvm::BasicBlock *DefaultBlock = createBasicBlock(name: "sw.default" ); |
| 2399 | SwitchInsn = Builder.CreateSwitch(V: CondV, Dest: DefaultBlock); |
| 2400 | addInstToNewSourceAtom(KeyInstruction: SwitchInsn, Backup: CondV); |
| 2401 | |
| 2402 | if (HLSLControlFlowAttr != HLSLControlFlowHintAttr::SpellingNotCalculated) { |
| 2403 | llvm::MDBuilder MDHelper(CGM.getLLVMContext()); |
| 2404 | llvm::ConstantInt *BranchHintConstant = |
| 2405 | HLSLControlFlowAttr == |
| 2406 | HLSLControlFlowHintAttr::Spelling::Microsoft_branch |
| 2407 | ? llvm::ConstantInt::get(Ty: CGM.Int32Ty, V: 1) |
| 2408 | : llvm::ConstantInt::get(Ty: CGM.Int32Ty, V: 2); |
| 2409 | llvm::Metadata *Vals[] = {MDHelper.createString(Str: "hlsl.controlflow.hint" ), |
| 2410 | MDHelper.createConstant(C: BranchHintConstant)}; |
| 2411 | SwitchInsn->setMetadata(Kind: "hlsl.controlflow.hint" , |
| 2412 | Node: llvm::MDNode::get(Context&: CGM.getLLVMContext(), MDs: Vals)); |
| 2413 | } |
| 2414 | |
| 2415 | if (PGO->haveRegionCounts()) { |
| 2416 | // Walk the SwitchCase list to find how many there are. |
| 2417 | uint64_t DefaultCount = 0; |
| 2418 | unsigned NumCases = 0; |
| 2419 | for (const SwitchCase *Case = S.getSwitchCaseList(); |
| 2420 | Case; |
| 2421 | Case = Case->getNextSwitchCase()) { |
| 2422 | if (isa<DefaultStmt>(Val: Case)) |
| 2423 | DefaultCount = getProfileCount(S: Case); |
| 2424 | NumCases += 1; |
| 2425 | } |
| 2426 | SwitchWeights = new SmallVector<uint64_t, 16>(); |
| 2427 | SwitchWeights->reserve(N: NumCases); |
| 2428 | // The default needs to be first. We store the edge count, so we already |
| 2429 | // know the right weight. |
| 2430 | SwitchWeights->push_back(Elt: DefaultCount); |
| 2431 | } else if (CGM.getCodeGenOpts().OptimizationLevel) { |
| 2432 | SwitchLikelihood = new SmallVector<Stmt::Likelihood, 16>(); |
| 2433 | // Initialize the default case. |
| 2434 | SwitchLikelihood->push_back(Elt: Stmt::LH_None); |
| 2435 | } |
| 2436 | |
| 2437 | CaseRangeBlock = DefaultBlock; |
| 2438 | |
| 2439 | // Clear the insertion point to indicate we are in unreachable code. |
| 2440 | Builder.ClearInsertionPoint(); |
| 2441 | |
| 2442 | // All break statements jump to NextBlock. If BreakContinueStack is non-empty |
| 2443 | // then reuse last ContinueBlock. |
| 2444 | JumpDest OuterContinue; |
| 2445 | if (!BreakContinueStack.empty()) |
| 2446 | OuterContinue = BreakContinueStack.back().ContinueBlock; |
| 2447 | |
| 2448 | BreakContinueStack.push_back(Elt: BreakContinue(S, SwitchExit, OuterContinue)); |
| 2449 | |
| 2450 | // Emit switch body. |
| 2451 | EmitStmt(S: S.getBody()); |
| 2452 | |
| 2453 | BreakContinueStack.pop_back(); |
| 2454 | |
| 2455 | // Update the default block in case explicit case range tests have |
| 2456 | // been chained on top. |
| 2457 | SwitchInsn->setDefaultDest(CaseRangeBlock); |
| 2458 | |
| 2459 | // If a default was never emitted: |
| 2460 | if (!DefaultBlock->getParent()) { |
| 2461 | // If we have cleanups, emit the default block so that there's a |
| 2462 | // place to jump through the cleanups from. |
| 2463 | if (ConditionScope.requiresCleanups()) { |
| 2464 | EmitBlock(BB: DefaultBlock); |
| 2465 | |
| 2466 | // Otherwise, just forward the default block to the switch end. |
| 2467 | } else { |
| 2468 | DefaultBlock->replaceAllUsesWith(V: SwitchExit.getBlock()); |
| 2469 | delete DefaultBlock; |
| 2470 | } |
| 2471 | } |
| 2472 | |
| 2473 | ConditionScope.ForceCleanup(); |
| 2474 | |
| 2475 | // Close the last case (or DefaultBlock). |
| 2476 | EmitBranch(Target: SwitchExit.getBlock()); |
| 2477 | |
| 2478 | // Insert a False Counter if SwitchStmt doesn't have DefaultStmt. |
| 2479 | if (hasSkipCounter(S: S.getCond())) { |
| 2480 | auto *ImplicitDefaultBlock = createBasicBlock(name: "sw.false" ); |
| 2481 | EmitBlock(BB: ImplicitDefaultBlock); |
| 2482 | incrementProfileCounter(ExecSkip: UseSkipPath, S: S.getCond()); |
| 2483 | Builder.CreateBr(Dest: SwitchInsn->getDefaultDest()); |
| 2484 | SwitchInsn->setDefaultDest(ImplicitDefaultBlock); |
| 2485 | } |
| 2486 | |
| 2487 | // Emit continuation. |
| 2488 | EmitBlock(BB: SwitchExit.getBlock(), IsFinished: true); |
| 2489 | incrementProfileCounter(S: &S); |
| 2490 | |
| 2491 | // If the switch has a condition wrapped by __builtin_unpredictable, |
| 2492 | // create metadata that specifies that the switch is unpredictable. |
| 2493 | // Don't bother if not optimizing because that metadata would not be used. |
| 2494 | auto *Call = dyn_cast<CallExpr>(Val: S.getCond()); |
| 2495 | if (Call && CGM.getCodeGenOpts().OptimizationLevel != 0) { |
| 2496 | auto *FD = dyn_cast_or_null<FunctionDecl>(Val: Call->getCalleeDecl()); |
| 2497 | if (FD && FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) { |
| 2498 | llvm::MDBuilder MDHelper(getLLVMContext()); |
| 2499 | SwitchInsn->setMetadata(KindID: llvm::LLVMContext::MD_unpredictable, |
| 2500 | Node: MDHelper.createUnpredictable()); |
| 2501 | } |
| 2502 | } |
| 2503 | |
| 2504 | if (SwitchWeights) { |
| 2505 | assert(SwitchWeights->size() == 1 + SwitchInsn->getNumCases() && |
| 2506 | "switch weights do not match switch cases" ); |
| 2507 | // If there's only one jump destination there's no sense weighting it. |
| 2508 | if (SwitchWeights->size() > 1) |
| 2509 | SwitchInsn->setMetadata(KindID: llvm::LLVMContext::MD_prof, |
| 2510 | Node: createProfileWeights(Weights: *SwitchWeights)); |
| 2511 | delete SwitchWeights; |
| 2512 | } else if (SwitchLikelihood) { |
| 2513 | assert(SwitchLikelihood->size() == 1 + SwitchInsn->getNumCases() && |
| 2514 | "switch likelihoods do not match switch cases" ); |
| 2515 | std::optional<SmallVector<uint64_t, 16>> LHW = |
| 2516 | getLikelihoodWeights(Likelihoods: *SwitchLikelihood); |
| 2517 | if (LHW) { |
| 2518 | llvm::MDBuilder MDHelper(CGM.getLLVMContext()); |
| 2519 | SwitchInsn->setMetadata(KindID: llvm::LLVMContext::MD_prof, |
| 2520 | Node: createProfileWeights(Weights: *LHW)); |
| 2521 | } |
| 2522 | delete SwitchLikelihood; |
| 2523 | } |
| 2524 | SwitchInsn = SavedSwitchInsn; |
| 2525 | SwitchWeights = SavedSwitchWeights; |
| 2526 | SwitchLikelihood = SavedSwitchLikelihood; |
| 2527 | CaseRangeBlock = SavedCRBlock; |
| 2528 | } |
| 2529 | |
| 2530 | std::pair<llvm::Value*, llvm::Type *> CodeGenFunction::EmitAsmInputLValue( |
| 2531 | const TargetInfo::ConstraintInfo &Info, LValue InputValue, |
| 2532 | QualType InputType, std::string &ConstraintStr, SourceLocation Loc) { |
| 2533 | if (Info.allowsRegister() || !Info.allowsMemory()) { |
| 2534 | if (CodeGenFunction::hasScalarEvaluationKind(T: InputType)) |
| 2535 | return {EmitLoadOfLValue(V: InputValue, Loc).getScalarVal(), nullptr}; |
| 2536 | |
| 2537 | llvm::Type *Ty = ConvertType(T: InputType); |
| 2538 | uint64_t Size = CGM.getDataLayout().getTypeSizeInBits(Ty); |
| 2539 | if ((Size <= 64 && llvm::isPowerOf2_64(Value: Size)) || |
| 2540 | getTargetHooks().isScalarizableAsmOperand(CGF&: *this, Ty)) { |
| 2541 | Ty = llvm::IntegerType::get(C&: getLLVMContext(), NumBits: Size); |
| 2542 | |
| 2543 | return {Builder.CreateLoad(Addr: InputValue.getAddress().withElementType(ElemTy: Ty)), |
| 2544 | nullptr}; |
| 2545 | } |
| 2546 | } |
| 2547 | |
| 2548 | Address Addr = InputValue.getAddress(); |
| 2549 | ConstraintStr += '*'; |
| 2550 | return {InputValue.getPointer(CGF&: *this), Addr.getElementType()}; |
| 2551 | } |
| 2552 | std::pair<llvm::Value *, llvm::Type *> |
| 2553 | CodeGenFunction::EmitAsmInput(const TargetInfo::ConstraintInfo &Info, |
| 2554 | const Expr *InputExpr, |
| 2555 | std::string &ConstraintStr) { |
| 2556 | // If this can't be a register or memory, i.e., has to be a constant |
| 2557 | // (immediate or symbolic), try to emit it as such. |
| 2558 | if (!Info.allowsRegister() && !Info.allowsMemory()) { |
| 2559 | if (Info.requiresImmediateConstant()) { |
| 2560 | Expr::EvalResult EVResult; |
| 2561 | InputExpr->EvaluateAsRValue(Result&: EVResult, Ctx: getContext(), InConstantContext: true); |
| 2562 | |
| 2563 | llvm::APSInt IntResult; |
| 2564 | if (EVResult.Val.toIntegralConstant(Result&: IntResult, SrcTy: InputExpr->getType(), |
| 2565 | Ctx: getContext())) |
| 2566 | return {llvm::ConstantInt::get(Context&: getLLVMContext(), V: IntResult), nullptr}; |
| 2567 | } |
| 2568 | |
| 2569 | Expr::EvalResult Result; |
| 2570 | if (InputExpr->EvaluateAsInt(Result, Ctx: getContext())) |
| 2571 | return {llvm::ConstantInt::get(Context&: getLLVMContext(), V: Result.Val.getInt()), |
| 2572 | nullptr}; |
| 2573 | } |
| 2574 | |
| 2575 | if (Info.allowsRegister() || !Info.allowsMemory()) |
| 2576 | if (CodeGenFunction::hasScalarEvaluationKind(T: InputExpr->getType())) |
| 2577 | return {EmitScalarExpr(E: InputExpr), nullptr}; |
| 2578 | if (InputExpr->getStmtClass() == Expr::CXXThisExprClass) |
| 2579 | return {EmitScalarExpr(E: InputExpr), nullptr}; |
| 2580 | InputExpr = InputExpr->IgnoreParenNoopCasts(Ctx: getContext()); |
| 2581 | LValue Dest = EmitLValue(E: InputExpr); |
| 2582 | return EmitAsmInputLValue(Info, InputValue: Dest, InputType: InputExpr->getType(), ConstraintStr, |
| 2583 | Loc: InputExpr->getExprLoc()); |
| 2584 | } |
| 2585 | |
| 2586 | /// getAsmSrcLocInfo - Return the !srcloc metadata node to attach to an inline |
| 2587 | /// asm call instruction. The !srcloc MDNode contains a list of constant |
| 2588 | /// integers which are the source locations of the start of each line in the |
| 2589 | /// asm. |
| 2590 | static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str, |
| 2591 | CodeGenFunction &CGF) { |
| 2592 | SmallVector<llvm::Metadata *, 8> Locs; |
| 2593 | // Add the location of the first line to the MDNode. |
| 2594 | Locs.push_back(Elt: llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::get( |
| 2595 | Ty: CGF.Int64Ty, V: Str->getBeginLoc().getRawEncoding()))); |
| 2596 | StringRef StrVal = Str->getString(); |
| 2597 | if (!StrVal.empty()) { |
| 2598 | const SourceManager &SM = CGF.CGM.getContext().getSourceManager(); |
| 2599 | const LangOptions &LangOpts = CGF.CGM.getLangOpts(); |
| 2600 | unsigned StartToken = 0; |
| 2601 | unsigned ByteOffset = 0; |
| 2602 | |
| 2603 | // Add the location of the start of each subsequent line of the asm to the |
| 2604 | // MDNode. |
| 2605 | for (unsigned i = 0, e = StrVal.size() - 1; i != e; ++i) { |
| 2606 | if (StrVal[i] != '\n') continue; |
| 2607 | SourceLocation LineLoc = Str->getLocationOfByte( |
| 2608 | ByteNo: i + 1, SM, Features: LangOpts, Target: CGF.getTarget(), StartToken: &StartToken, StartTokenByteOffset: &ByteOffset); |
| 2609 | Locs.push_back(Elt: llvm::ConstantAsMetadata::get( |
| 2610 | C: llvm::ConstantInt::get(Ty: CGF.Int64Ty, V: LineLoc.getRawEncoding()))); |
| 2611 | } |
| 2612 | } |
| 2613 | |
| 2614 | return llvm::MDNode::get(Context&: CGF.getLLVMContext(), MDs: Locs); |
| 2615 | } |
| 2616 | |
| 2617 | static void UpdateAsmCallInst(llvm::CallBase &Result, bool HasSideEffect, |
| 2618 | bool HasUnwindClobber, bool ReadOnly, |
| 2619 | bool ReadNone, bool NoMerge, bool NoConvergent, |
| 2620 | const AsmStmt &S, |
| 2621 | const std::vector<llvm::Type *> &ResultRegTypes, |
| 2622 | const std::vector<llvm::Type *> &ArgElemTypes, |
| 2623 | CodeGenFunction &CGF, |
| 2624 | std::vector<llvm::Value *> &RegResults) { |
| 2625 | if (!HasUnwindClobber) |
| 2626 | Result.addFnAttr(Kind: llvm::Attribute::NoUnwind); |
| 2627 | |
| 2628 | if (NoMerge) |
| 2629 | Result.addFnAttr(Kind: llvm::Attribute::NoMerge); |
| 2630 | // Attach readnone and readonly attributes. |
| 2631 | if (!HasSideEffect) { |
| 2632 | if (ReadNone) |
| 2633 | Result.setDoesNotAccessMemory(); |
| 2634 | else if (ReadOnly) |
| 2635 | Result.setOnlyReadsMemory(); |
| 2636 | } |
| 2637 | |
| 2638 | // Add elementtype attribute for indirect constraints. |
| 2639 | for (auto Pair : llvm::enumerate(First: ArgElemTypes)) { |
| 2640 | if (Pair.value()) { |
| 2641 | auto Attr = llvm::Attribute::get( |
| 2642 | Context&: CGF.getLLVMContext(), Kind: llvm::Attribute::ElementType, Ty: Pair.value()); |
| 2643 | Result.addParamAttr(ArgNo: Pair.index(), Attr); |
| 2644 | } |
| 2645 | } |
| 2646 | |
| 2647 | // Slap the source location of the inline asm into a !srcloc metadata on the |
| 2648 | // call. |
| 2649 | const StringLiteral *SL; |
| 2650 | if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(Val: &S); |
| 2651 | gccAsmStmt && |
| 2652 | (SL = dyn_cast<StringLiteral>(Val: gccAsmStmt->getAsmStringExpr()))) { |
| 2653 | Result.setMetadata(Kind: "srcloc" , Node: getAsmSrcLocInfo(Str: SL, CGF)); |
| 2654 | } else { |
| 2655 | // At least put the line number on MS inline asm blobs and GCC asm constexpr |
| 2656 | // strings. |
| 2657 | llvm::Constant *Loc = |
| 2658 | llvm::ConstantInt::get(Ty: CGF.Int64Ty, V: S.getAsmLoc().getRawEncoding()); |
| 2659 | Result.setMetadata(Kind: "srcloc" , |
| 2660 | Node: llvm::MDNode::get(Context&: CGF.getLLVMContext(), |
| 2661 | MDs: llvm::ConstantAsMetadata::get(C: Loc))); |
| 2662 | } |
| 2663 | |
| 2664 | // Make inline-asm calls Key for the debug info feature Key Instructions. |
| 2665 | CGF.addInstToNewSourceAtom(KeyInstruction: &Result, Backup: nullptr); |
| 2666 | |
| 2667 | if (!NoConvergent && CGF.getLangOpts().assumeFunctionsAreConvergent()) |
| 2668 | // Conservatively, mark all inline asm blocks in CUDA or OpenCL as |
| 2669 | // convergent (meaning, they may call an intrinsically convergent op, such |
| 2670 | // as bar.sync, and so can't have certain optimizations applied around |
| 2671 | // them) unless it's explicitly marked 'noconvergent'. |
| 2672 | Result.addFnAttr(Kind: llvm::Attribute::Convergent); |
| 2673 | // Extract all of the register value results from the asm. |
| 2674 | if (ResultRegTypes.size() == 1) { |
| 2675 | RegResults.push_back(x: &Result); |
| 2676 | } else { |
| 2677 | for (unsigned i = 0, e = ResultRegTypes.size(); i != e; ++i) { |
| 2678 | llvm::Value *Tmp = CGF.Builder.CreateExtractValue(Agg: &Result, Idxs: i, Name: "asmresult" ); |
| 2679 | RegResults.push_back(x: Tmp); |
| 2680 | } |
| 2681 | } |
| 2682 | } |
| 2683 | |
| 2684 | static void |
| 2685 | EmitAsmStores(CodeGenFunction &CGF, const AsmStmt &S, |
| 2686 | const llvm::ArrayRef<llvm::Value *> RegResults, |
| 2687 | const llvm::ArrayRef<llvm::Type *> ResultRegTypes, |
| 2688 | const llvm::ArrayRef<llvm::Type *> ResultTruncRegTypes, |
| 2689 | const llvm::ArrayRef<LValue> ResultRegDests, |
| 2690 | const llvm::ArrayRef<QualType> ResultRegQualTys, |
| 2691 | const llvm::BitVector &ResultTypeRequiresCast, |
| 2692 | const std::vector<std::optional<std::pair<unsigned, unsigned>>> |
| 2693 | &ResultBounds) { |
| 2694 | CGBuilderTy &Builder = CGF.Builder; |
| 2695 | CodeGenModule &CGM = CGF.CGM; |
| 2696 | llvm::LLVMContext &CTX = CGF.getLLVMContext(); |
| 2697 | |
| 2698 | assert(RegResults.size() == ResultRegTypes.size()); |
| 2699 | assert(RegResults.size() == ResultTruncRegTypes.size()); |
| 2700 | assert(RegResults.size() == ResultRegDests.size()); |
| 2701 | // ResultRegDests can be also populated by addReturnRegisterOutputs() above, |
| 2702 | // in which case its size may grow. |
| 2703 | assert(ResultTypeRequiresCast.size() <= ResultRegDests.size()); |
| 2704 | assert(ResultBounds.size() <= ResultRegDests.size()); |
| 2705 | |
| 2706 | for (unsigned i = 0, e = RegResults.size(); i != e; ++i) { |
| 2707 | llvm::Value *Tmp = RegResults[i]; |
| 2708 | llvm::Type *TruncTy = ResultTruncRegTypes[i]; |
| 2709 | |
| 2710 | if ((i < ResultBounds.size()) && ResultBounds[i].has_value()) { |
| 2711 | const auto [LowerBound, UpperBound] = ResultBounds[i].value(); |
| 2712 | // FIXME: Support for nonzero lower bounds not yet implemented. |
| 2713 | assert(LowerBound == 0 && "Output operand lower bound is not zero." ); |
| 2714 | llvm::Constant *UpperBoundConst = |
| 2715 | llvm::ConstantInt::get(Ty: Tmp->getType(), V: UpperBound); |
| 2716 | llvm::Value *IsBooleanValue = |
| 2717 | Builder.CreateCmp(Pred: llvm::CmpInst::ICMP_ULT, LHS: Tmp, RHS: UpperBoundConst); |
| 2718 | llvm::Function *FnAssume = CGM.getIntrinsic(IID: llvm::Intrinsic::assume); |
| 2719 | Builder.CreateCall(Callee: FnAssume, Args: IsBooleanValue); |
| 2720 | } |
| 2721 | |
| 2722 | // If the result type of the LLVM IR asm doesn't match the result type of |
| 2723 | // the expression, do the conversion. |
| 2724 | if (ResultRegTypes[i] != TruncTy) { |
| 2725 | |
| 2726 | // Truncate the integer result to the right size, note that TruncTy can be |
| 2727 | // a pointer. |
| 2728 | if (TruncTy->isFloatingPointTy()) |
| 2729 | Tmp = Builder.CreateFPTrunc(V: Tmp, DestTy: TruncTy); |
| 2730 | else if (TruncTy->isPointerTy() && Tmp->getType()->isIntegerTy()) { |
| 2731 | uint64_t ResSize = CGM.getDataLayout().getTypeSizeInBits(Ty: TruncTy); |
| 2732 | Tmp = Builder.CreateTrunc( |
| 2733 | V: Tmp, DestTy: llvm::IntegerType::get(C&: CTX, NumBits: (unsigned)ResSize)); |
| 2734 | Tmp = Builder.CreateIntToPtr(V: Tmp, DestTy: TruncTy); |
| 2735 | } else if (Tmp->getType()->isPointerTy() && TruncTy->isIntegerTy()) { |
| 2736 | uint64_t TmpSize = |
| 2737 | CGM.getDataLayout().getTypeSizeInBits(Ty: Tmp->getType()); |
| 2738 | Tmp = Builder.CreatePtrToInt( |
| 2739 | V: Tmp, DestTy: llvm::IntegerType::get(C&: CTX, NumBits: (unsigned)TmpSize)); |
| 2740 | Tmp = Builder.CreateTrunc(V: Tmp, DestTy: TruncTy); |
| 2741 | } else if (Tmp->getType()->isIntegerTy() && TruncTy->isIntegerTy()) { |
| 2742 | Tmp = Builder.CreateZExtOrTrunc(V: Tmp, DestTy: TruncTy); |
| 2743 | } else if (Tmp->getType()->isVectorTy() || TruncTy->isVectorTy()) { |
| 2744 | Tmp = Builder.CreateBitCast(V: Tmp, DestTy: TruncTy); |
| 2745 | } |
| 2746 | } |
| 2747 | |
| 2748 | ApplyAtomGroup Grp(CGF.getDebugInfo()); |
| 2749 | LValue Dest = ResultRegDests[i]; |
| 2750 | // ResultTypeRequiresCast elements correspond to the first |
| 2751 | // ResultTypeRequiresCast.size() elements of RegResults. |
| 2752 | if ((i < ResultTypeRequiresCast.size()) && ResultTypeRequiresCast[i]) { |
| 2753 | unsigned Size = CGF.getContext().getTypeSize(T: ResultRegQualTys[i]); |
| 2754 | Address A = Dest.getAddress().withElementType(ElemTy: ResultRegTypes[i]); |
| 2755 | if (CGF.getTargetHooks().isScalarizableAsmOperand(CGF, Ty: TruncTy)) { |
| 2756 | llvm::StoreInst *S = Builder.CreateStore(Val: Tmp, Addr: A); |
| 2757 | CGF.addInstToCurrentSourceAtom(KeyInstruction: S, Backup: S->getValueOperand()); |
| 2758 | continue; |
| 2759 | } |
| 2760 | |
| 2761 | QualType Ty = |
| 2762 | CGF.getContext().getIntTypeForBitwidth(DestWidth: Size, /*Signed=*/false); |
| 2763 | if (Ty.isNull()) { |
| 2764 | const Expr *OutExpr = S.getOutputExpr(i); |
| 2765 | CGM.getDiags().Report(Loc: OutExpr->getExprLoc(), |
| 2766 | DiagID: diag::err_store_value_to_reg); |
| 2767 | return; |
| 2768 | } |
| 2769 | Dest = CGF.MakeAddrLValue(Addr: A, T: Ty); |
| 2770 | } |
| 2771 | CGF.EmitStoreThroughLValue(Src: RValue::get(V: Tmp), Dst: Dest); |
| 2772 | } |
| 2773 | } |
| 2774 | |
| 2775 | static void EmitHipStdParUnsupportedAsm(CodeGenFunction *CGF, |
| 2776 | const AsmStmt &S) { |
| 2777 | constexpr auto Name = "__ASM__hipstdpar_unsupported" ; |
| 2778 | |
| 2779 | std::string Asm; |
| 2780 | if (auto GCCAsm = dyn_cast<GCCAsmStmt>(Val: &S)) |
| 2781 | Asm = GCCAsm->getAsmString(); |
| 2782 | |
| 2783 | auto &Ctx = CGF->CGM.getLLVMContext(); |
| 2784 | |
| 2785 | auto StrTy = llvm::ConstantDataArray::getString(Context&: Ctx, Initializer: Asm); |
| 2786 | auto FnTy = llvm::FunctionType::get(Result: llvm::Type::getVoidTy(C&: Ctx), |
| 2787 | Params: {StrTy->getType()}, isVarArg: false); |
| 2788 | auto UBF = CGF->CGM.getModule().getOrInsertFunction(Name, T: FnTy); |
| 2789 | |
| 2790 | CGF->Builder.CreateCall(Callee: UBF, Args: {StrTy}); |
| 2791 | } |
| 2792 | |
| 2793 | void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) { |
| 2794 | // Pop all cleanup blocks at the end of the asm statement. |
| 2795 | CodeGenFunction::RunCleanupsScope Cleanups(*this); |
| 2796 | |
| 2797 | // Assemble the final asm string. |
| 2798 | std::string AsmString = S.generateAsmString(C: getContext()); |
| 2799 | |
| 2800 | // Get all the output and input constraints together. |
| 2801 | SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos; |
| 2802 | SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos; |
| 2803 | |
| 2804 | bool IsHipStdPar = getLangOpts().HIPStdPar && getLangOpts().CUDAIsDevice; |
| 2805 | bool IsValidTargetAsm = true; |
| 2806 | for (unsigned i = 0, e = S.getNumOutputs(); i != e && IsValidTargetAsm; i++) { |
| 2807 | StringRef Name; |
| 2808 | if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(Val: &S)) |
| 2809 | Name = GAS->getOutputName(i); |
| 2810 | TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name); |
| 2811 | bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid; |
| 2812 | if (IsHipStdPar && !IsValid) |
| 2813 | IsValidTargetAsm = false; |
| 2814 | else |
| 2815 | assert(IsValid && "Failed to parse output constraint" ); |
| 2816 | OutputConstraintInfos.push_back(Elt: Info); |
| 2817 | } |
| 2818 | |
| 2819 | for (unsigned i = 0, e = S.getNumInputs(); i != e && IsValidTargetAsm; i++) { |
| 2820 | StringRef Name; |
| 2821 | if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(Val: &S)) |
| 2822 | Name = GAS->getInputName(i); |
| 2823 | TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name); |
| 2824 | bool IsValid = |
| 2825 | getTarget().validateInputConstraint(OutputConstraints: OutputConstraintInfos, info&: Info); |
| 2826 | if (IsHipStdPar && !IsValid) |
| 2827 | IsValidTargetAsm = false; |
| 2828 | else |
| 2829 | assert(IsValid && "Failed to parse input constraint" ); |
| 2830 | InputConstraintInfos.push_back(Elt: Info); |
| 2831 | } |
| 2832 | |
| 2833 | if (!IsValidTargetAsm) |
| 2834 | return EmitHipStdParUnsupportedAsm(CGF: this, S); |
| 2835 | |
| 2836 | std::string Constraints; |
| 2837 | |
| 2838 | std::vector<LValue> ResultRegDests; |
| 2839 | std::vector<QualType> ResultRegQualTys; |
| 2840 | std::vector<llvm::Type *> ResultRegTypes; |
| 2841 | std::vector<llvm::Type *> ResultTruncRegTypes; |
| 2842 | std::vector<llvm::Type *> ArgTypes; |
| 2843 | std::vector<llvm::Type *> ArgElemTypes; |
| 2844 | std::vector<llvm::Value*> Args; |
| 2845 | llvm::BitVector ResultTypeRequiresCast; |
| 2846 | std::vector<std::optional<std::pair<unsigned, unsigned>>> ResultBounds; |
| 2847 | |
| 2848 | // Keep track of inout constraints. |
| 2849 | std::string InOutConstraints; |
| 2850 | std::vector<llvm::Value*> InOutArgs; |
| 2851 | std::vector<llvm::Type*> InOutArgTypes; |
| 2852 | std::vector<llvm::Type*> InOutArgElemTypes; |
| 2853 | |
| 2854 | // Keep track of out constraints for tied input operand. |
| 2855 | std::vector<std::string> OutputConstraints; |
| 2856 | |
| 2857 | // Keep track of defined physregs. |
| 2858 | llvm::SmallSet<std::string, 8> PhysRegOutputs; |
| 2859 | |
| 2860 | // An inline asm can be marked readonly if it meets the following conditions: |
| 2861 | // - it doesn't have any sideeffects |
| 2862 | // - it doesn't clobber memory |
| 2863 | // - it doesn't return a value by-reference |
| 2864 | // It can be marked readnone if it doesn't have any input memory constraints |
| 2865 | // in addition to meeting the conditions listed above. |
| 2866 | bool ReadOnly = true, ReadNone = true; |
| 2867 | |
| 2868 | for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) { |
| 2869 | TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i]; |
| 2870 | |
| 2871 | // Simplify the output constraint. |
| 2872 | std::string OutputConstraint(S.getOutputConstraint(i)); |
| 2873 | OutputConstraint = getTarget().simplifyConstraint( |
| 2874 | Constraint: StringRef(OutputConstraint).substr(Start: 1), OutCons: &OutputConstraintInfos); |
| 2875 | |
| 2876 | const Expr *OutExpr = S.getOutputExpr(i); |
| 2877 | OutExpr = OutExpr->IgnoreParenNoopCasts(Ctx: getContext()); |
| 2878 | |
| 2879 | std::string GCCReg; |
| 2880 | OutputConstraint = S.addVariableConstraints( |
| 2881 | Constraint: OutputConstraint, AsmExpr: *OutExpr, Target: getTarget(), EarlyClobber: Info.earlyClobber(), |
| 2882 | UnsupportedCB: [&](const Stmt *UnspStmt, StringRef Msg) { |
| 2883 | CGM.ErrorUnsupported(S: UnspStmt, Type: Msg); |
| 2884 | }, |
| 2885 | GCCReg: &GCCReg); |
| 2886 | // Give an error on multiple outputs to same physreg. |
| 2887 | if (!GCCReg.empty() && !PhysRegOutputs.insert(V: GCCReg).second) |
| 2888 | CGM.Error(loc: S.getAsmLoc(), error: "multiple outputs to hard register: " + GCCReg); |
| 2889 | |
| 2890 | OutputConstraints.push_back(x: OutputConstraint); |
| 2891 | LValue Dest = EmitLValue(E: OutExpr); |
| 2892 | if (!Constraints.empty()) |
| 2893 | Constraints += ','; |
| 2894 | |
| 2895 | // If this is a register output, then make the inline asm return it |
| 2896 | // by-value. If this is a memory result, return the value by-reference. |
| 2897 | QualType QTy = OutExpr->getType(); |
| 2898 | const bool IsScalarOrAggregate = hasScalarEvaluationKind(T: QTy) || |
| 2899 | hasAggregateEvaluationKind(T: QTy); |
| 2900 | if (!Info.allowsMemory() && IsScalarOrAggregate) { |
| 2901 | |
| 2902 | Constraints += "=" + OutputConstraint; |
| 2903 | ResultRegQualTys.push_back(x: QTy); |
| 2904 | ResultRegDests.push_back(x: Dest); |
| 2905 | |
| 2906 | ResultBounds.emplace_back(args: Info.getOutputOperandBounds()); |
| 2907 | |
| 2908 | llvm::Type *Ty = ConvertTypeForMem(T: QTy); |
| 2909 | const bool RequiresCast = Info.allowsRegister() && |
| 2910 | (getTargetHooks().isScalarizableAsmOperand(CGF&: *this, Ty) || |
| 2911 | Ty->isAggregateType()); |
| 2912 | |
| 2913 | ResultTruncRegTypes.push_back(x: Ty); |
| 2914 | ResultTypeRequiresCast.push_back(Val: RequiresCast); |
| 2915 | |
| 2916 | if (RequiresCast) { |
| 2917 | unsigned Size = getContext().getTypeSize(T: QTy); |
| 2918 | if (Size) |
| 2919 | Ty = llvm::IntegerType::get(C&: getLLVMContext(), NumBits: Size); |
| 2920 | else |
| 2921 | CGM.Error(loc: OutExpr->getExprLoc(), error: "output size should not be zero" ); |
| 2922 | } |
| 2923 | ResultRegTypes.push_back(x: Ty); |
| 2924 | // If this output is tied to an input, and if the input is larger, then |
| 2925 | // we need to set the actual result type of the inline asm node to be the |
| 2926 | // same as the input type. |
| 2927 | if (Info.hasMatchingInput()) { |
| 2928 | unsigned InputNo; |
| 2929 | for (InputNo = 0; InputNo != S.getNumInputs(); ++InputNo) { |
| 2930 | TargetInfo::ConstraintInfo &Input = InputConstraintInfos[InputNo]; |
| 2931 | if (Input.hasTiedOperand() && Input.getTiedOperand() == i) |
| 2932 | break; |
| 2933 | } |
| 2934 | assert(InputNo != S.getNumInputs() && "Didn't find matching input!" ); |
| 2935 | |
| 2936 | QualType InputTy = S.getInputExpr(i: InputNo)->getType(); |
| 2937 | QualType OutputType = OutExpr->getType(); |
| 2938 | |
| 2939 | uint64_t InputSize = getContext().getTypeSize(T: InputTy); |
| 2940 | if (getContext().getTypeSize(T: OutputType) < InputSize) { |
| 2941 | // Form the asm to return the value as a larger integer or fp type. |
| 2942 | ResultRegTypes.back() = ConvertType(T: InputTy); |
| 2943 | } |
| 2944 | } |
| 2945 | if (llvm::Type* AdjTy = |
| 2946 | getTargetHooks().adjustInlineAsmType(CGF&: *this, Constraint: OutputConstraint, |
| 2947 | Ty: ResultRegTypes.back())) |
| 2948 | ResultRegTypes.back() = AdjTy; |
| 2949 | else { |
| 2950 | CGM.getDiags().Report(Loc: S.getAsmLoc(), |
| 2951 | DiagID: diag::err_asm_invalid_type_in_input) |
| 2952 | << OutExpr->getType() << OutputConstraint; |
| 2953 | } |
| 2954 | |
| 2955 | // Update largest vector width for any vector types. |
| 2956 | if (auto *VT = dyn_cast<llvm::VectorType>(Val: ResultRegTypes.back())) |
| 2957 | LargestVectorWidth = |
| 2958 | std::max(a: (uint64_t)LargestVectorWidth, |
| 2959 | b: VT->getPrimitiveSizeInBits().getKnownMinValue()); |
| 2960 | } else { |
| 2961 | Address DestAddr = Dest.getAddress(); |
| 2962 | // Matrix types in memory are represented by arrays, but accessed through |
| 2963 | // vector pointers, with the alignment specified on the access operation. |
| 2964 | // For inline assembly, update pointer arguments to use vector pointers. |
| 2965 | // Otherwise there will be a mis-match if the matrix is also an |
| 2966 | // input-argument which is represented as vector. |
| 2967 | if (isa<MatrixType>(Val: OutExpr->getType().getCanonicalType())) |
| 2968 | DestAddr = DestAddr.withElementType(ElemTy: ConvertType(T: OutExpr->getType())); |
| 2969 | |
| 2970 | ArgTypes.push_back(x: DestAddr.getType()); |
| 2971 | ArgElemTypes.push_back(x: DestAddr.getElementType()); |
| 2972 | Args.push_back(x: DestAddr.emitRawPointer(CGF&: *this)); |
| 2973 | Constraints += "=*" ; |
| 2974 | Constraints += OutputConstraint; |
| 2975 | ReadOnly = ReadNone = false; |
| 2976 | } |
| 2977 | |
| 2978 | if (Info.isReadWrite()) { |
| 2979 | InOutConstraints += ','; |
| 2980 | |
| 2981 | const Expr *InputExpr = S.getOutputExpr(i); |
| 2982 | llvm::Value *Arg; |
| 2983 | llvm::Type *ArgElemType; |
| 2984 | std::tie(args&: Arg, args&: ArgElemType) = EmitAsmInputLValue( |
| 2985 | Info, InputValue: Dest, InputType: InputExpr->getType(), ConstraintStr&: InOutConstraints, |
| 2986 | Loc: InputExpr->getExprLoc()); |
| 2987 | |
| 2988 | if (llvm::Type* AdjTy = |
| 2989 | getTargetHooks().adjustInlineAsmType(CGF&: *this, Constraint: OutputConstraint, |
| 2990 | Ty: Arg->getType())) |
| 2991 | Arg = Builder.CreateBitCast(V: Arg, DestTy: AdjTy); |
| 2992 | |
| 2993 | // Update largest vector width for any vector types. |
| 2994 | if (auto *VT = dyn_cast<llvm::VectorType>(Val: Arg->getType())) |
| 2995 | LargestVectorWidth = |
| 2996 | std::max(a: (uint64_t)LargestVectorWidth, |
| 2997 | b: VT->getPrimitiveSizeInBits().getKnownMinValue()); |
| 2998 | // Only tie earlyclobber physregs. |
| 2999 | if (Info.allowsRegister() && (GCCReg.empty() || Info.earlyClobber())) |
| 3000 | InOutConstraints += llvm::utostr(X: i); |
| 3001 | else |
| 3002 | InOutConstraints += OutputConstraint; |
| 3003 | |
| 3004 | InOutArgTypes.push_back(x: Arg->getType()); |
| 3005 | InOutArgElemTypes.push_back(x: ArgElemType); |
| 3006 | InOutArgs.push_back(x: Arg); |
| 3007 | } |
| 3008 | } |
| 3009 | |
| 3010 | // If this is a Microsoft-style asm blob, store the return registers (EAX:EDX) |
| 3011 | // to the return value slot. Only do this when returning in registers. |
| 3012 | if (isa<MSAsmStmt>(Val: &S)) { |
| 3013 | const ABIArgInfo &RetAI = CurFnInfo->getReturnInfo(); |
| 3014 | if (RetAI.isDirect() || RetAI.isExtend()) { |
| 3015 | // Make a fake lvalue for the return value slot. |
| 3016 | LValue ReturnSlot = MakeAddrLValueWithoutTBAA(Addr: ReturnValue, T: FnRetTy); |
| 3017 | CGM.getTargetCodeGenInfo().addReturnRegisterOutputs( |
| 3018 | CGF&: *this, ReturnValue: ReturnSlot, Constraints, ResultRegTypes, ResultTruncRegTypes, |
| 3019 | ResultRegDests, AsmString, NumOutputs: S.getNumOutputs()); |
| 3020 | SawAsmBlock = true; |
| 3021 | } |
| 3022 | } |
| 3023 | |
| 3024 | for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) { |
| 3025 | const Expr *InputExpr = S.getInputExpr(i); |
| 3026 | |
| 3027 | TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i]; |
| 3028 | |
| 3029 | if (Info.allowsMemory()) |
| 3030 | ReadNone = false; |
| 3031 | |
| 3032 | if (!Constraints.empty()) |
| 3033 | Constraints += ','; |
| 3034 | |
| 3035 | // Simplify the input constraint. |
| 3036 | std::string InputConstraint(S.getInputConstraint(i)); |
| 3037 | InputConstraint = |
| 3038 | getTarget().simplifyConstraint(Constraint: InputConstraint, OutCons: &OutputConstraintInfos); |
| 3039 | |
| 3040 | InputConstraint = S.addVariableConstraints( |
| 3041 | Constraint: InputConstraint, AsmExpr: *InputExpr->IgnoreParenNoopCasts(Ctx: getContext()), |
| 3042 | Target: getTarget(), EarlyClobber: false /* No EarlyClobber */, |
| 3043 | UnsupportedCB: [&](const Stmt *UnspStmt, std::string_view Msg) { |
| 3044 | CGM.ErrorUnsupported(S: UnspStmt, Type: Msg); |
| 3045 | }); |
| 3046 | |
| 3047 | std::string ReplaceConstraint (InputConstraint); |
| 3048 | llvm::Value *Arg; |
| 3049 | llvm::Type *ArgElemType; |
| 3050 | std::tie(args&: Arg, args&: ArgElemType) = EmitAsmInput(Info, InputExpr, ConstraintStr&: Constraints); |
| 3051 | |
| 3052 | // If this input argument is tied to a larger output result, extend the |
| 3053 | // input to be the same size as the output. The LLVM backend wants to see |
| 3054 | // the input and output of a matching constraint be the same size. Note |
| 3055 | // that GCC does not define what the top bits are here. We use zext because |
| 3056 | // that is usually cheaper, but LLVM IR should really get an anyext someday. |
| 3057 | if (Info.hasTiedOperand()) { |
| 3058 | unsigned Output = Info.getTiedOperand(); |
| 3059 | QualType OutputType = S.getOutputExpr(i: Output)->getType(); |
| 3060 | QualType InputTy = InputExpr->getType(); |
| 3061 | |
| 3062 | if (getContext().getTypeSize(T: OutputType) > |
| 3063 | getContext().getTypeSize(T: InputTy)) { |
| 3064 | // Use ptrtoint as appropriate so that we can do our extension. |
| 3065 | if (isa<llvm::PointerType>(Val: Arg->getType())) |
| 3066 | Arg = Builder.CreatePtrToInt(V: Arg, DestTy: IntPtrTy); |
| 3067 | llvm::Type *OutputTy = ConvertType(T: OutputType); |
| 3068 | if (isa<llvm::IntegerType>(Val: OutputTy)) |
| 3069 | Arg = Builder.CreateZExt(V: Arg, DestTy: OutputTy); |
| 3070 | else if (isa<llvm::PointerType>(Val: OutputTy)) |
| 3071 | Arg = Builder.CreateZExt(V: Arg, DestTy: IntPtrTy); |
| 3072 | else if (OutputTy->isFloatingPointTy()) |
| 3073 | Arg = Builder.CreateFPExt(V: Arg, DestTy: OutputTy); |
| 3074 | } |
| 3075 | // Deal with the tied operands' constraint code in adjustInlineAsmType. |
| 3076 | ReplaceConstraint = OutputConstraints[Output]; |
| 3077 | } |
| 3078 | if (llvm::Type* AdjTy = |
| 3079 | getTargetHooks().adjustInlineAsmType(CGF&: *this, Constraint: ReplaceConstraint, |
| 3080 | Ty: Arg->getType())) |
| 3081 | Arg = Builder.CreateBitCast(V: Arg, DestTy: AdjTy); |
| 3082 | else |
| 3083 | CGM.getDiags().Report(Loc: S.getAsmLoc(), DiagID: diag::err_asm_invalid_type_in_input) |
| 3084 | << InputExpr->getType() << InputConstraint; |
| 3085 | |
| 3086 | // Update largest vector width for any vector types. |
| 3087 | if (auto *VT = dyn_cast<llvm::VectorType>(Val: Arg->getType())) |
| 3088 | LargestVectorWidth = |
| 3089 | std::max(a: (uint64_t)LargestVectorWidth, |
| 3090 | b: VT->getPrimitiveSizeInBits().getKnownMinValue()); |
| 3091 | |
| 3092 | ArgTypes.push_back(x: Arg->getType()); |
| 3093 | ArgElemTypes.push_back(x: ArgElemType); |
| 3094 | Args.push_back(x: Arg); |
| 3095 | Constraints += InputConstraint; |
| 3096 | } |
| 3097 | |
| 3098 | // Append the "input" part of inout constraints. |
| 3099 | for (unsigned i = 0, e = InOutArgs.size(); i != e; i++) { |
| 3100 | ArgTypes.push_back(x: InOutArgTypes[i]); |
| 3101 | ArgElemTypes.push_back(x: InOutArgElemTypes[i]); |
| 3102 | Args.push_back(x: InOutArgs[i]); |
| 3103 | } |
| 3104 | Constraints += InOutConstraints; |
| 3105 | |
| 3106 | // Labels |
| 3107 | SmallVector<llvm::BasicBlock *, 16> Transfer; |
| 3108 | llvm::BasicBlock *Fallthrough = nullptr; |
| 3109 | bool IsGCCAsmGoto = false; |
| 3110 | if (const auto *GS = dyn_cast<GCCAsmStmt>(Val: &S)) { |
| 3111 | IsGCCAsmGoto = GS->isAsmGoto(); |
| 3112 | if (IsGCCAsmGoto) { |
| 3113 | for (const auto *E : GS->labels()) { |
| 3114 | JumpDest Dest = getJumpDestForLabel(D: E->getLabel()); |
| 3115 | Transfer.push_back(Elt: Dest.getBlock()); |
| 3116 | if (!Constraints.empty()) |
| 3117 | Constraints += ','; |
| 3118 | Constraints += "!i" ; |
| 3119 | } |
| 3120 | Fallthrough = createBasicBlock(name: "asm.fallthrough" ); |
| 3121 | } |
| 3122 | } |
| 3123 | |
| 3124 | bool HasUnwindClobber = false; |
| 3125 | |
| 3126 | // Clobbers |
| 3127 | for (unsigned i = 0, e = S.getNumClobbers(); i != e; i++) { |
| 3128 | std::string Clobber = S.getClobber(i); |
| 3129 | |
| 3130 | if (Clobber == "memory" ) |
| 3131 | ReadOnly = ReadNone = false; |
| 3132 | else if (Clobber == "unwind" ) { |
| 3133 | HasUnwindClobber = true; |
| 3134 | continue; |
| 3135 | } else if (Clobber != "cc" ) { |
| 3136 | Clobber = getTarget().getNormalizedGCCRegisterName(Name: Clobber); |
| 3137 | if (CGM.getCodeGenOpts().StackClashProtector && |
| 3138 | getTarget().isSPRegName(Clobber)) { |
| 3139 | CGM.getDiags().Report(Loc: S.getAsmLoc(), |
| 3140 | DiagID: diag::warn_stack_clash_protection_inline_asm); |
| 3141 | } |
| 3142 | } |
| 3143 | |
| 3144 | if (isa<MSAsmStmt>(Val: &S)) { |
| 3145 | if (Clobber == "eax" || Clobber == "edx" ) { |
| 3146 | if (Constraints.find(s: "=&A" ) != std::string::npos) |
| 3147 | continue; |
| 3148 | std::string::size_type position1 = |
| 3149 | Constraints.find(str: "={" + Clobber + "}" ); |
| 3150 | if (position1 != std::string::npos) { |
| 3151 | Constraints.insert(pos: position1 + 1, s: "&" ); |
| 3152 | continue; |
| 3153 | } |
| 3154 | std::string::size_type position2 = Constraints.find(s: "=A" ); |
| 3155 | if (position2 != std::string::npos) { |
| 3156 | Constraints.insert(pos: position2 + 1, s: "&" ); |
| 3157 | continue; |
| 3158 | } |
| 3159 | } |
| 3160 | } |
| 3161 | if (!Constraints.empty()) |
| 3162 | Constraints += ','; |
| 3163 | |
| 3164 | Constraints += "~{" ; |
| 3165 | Constraints += Clobber; |
| 3166 | Constraints += '}'; |
| 3167 | } |
| 3168 | |
| 3169 | assert(!(HasUnwindClobber && IsGCCAsmGoto) && |
| 3170 | "unwind clobber can't be used with asm goto" ); |
| 3171 | |
| 3172 | // Add machine specific clobbers |
| 3173 | std::string_view MachineClobbers = getTarget().getClobbers(); |
| 3174 | if (!MachineClobbers.empty()) { |
| 3175 | if (!Constraints.empty()) |
| 3176 | Constraints += ','; |
| 3177 | Constraints += MachineClobbers; |
| 3178 | } |
| 3179 | |
| 3180 | llvm::Type *ResultType; |
| 3181 | if (ResultRegTypes.empty()) |
| 3182 | ResultType = VoidTy; |
| 3183 | else if (ResultRegTypes.size() == 1) |
| 3184 | ResultType = ResultRegTypes[0]; |
| 3185 | else |
| 3186 | ResultType = llvm::StructType::get(Context&: getLLVMContext(), Elements: ResultRegTypes); |
| 3187 | |
| 3188 | llvm::FunctionType *FTy = |
| 3189 | llvm::FunctionType::get(Result: ResultType, Params: ArgTypes, isVarArg: false); |
| 3190 | |
| 3191 | bool HasSideEffect = S.isVolatile() || S.getNumOutputs() == 0; |
| 3192 | |
| 3193 | llvm::InlineAsm::AsmDialect GnuAsmDialect = |
| 3194 | CGM.getCodeGenOpts().getInlineAsmDialect() == CodeGenOptions::IAD_ATT |
| 3195 | ? llvm::InlineAsm::AD_ATT |
| 3196 | : llvm::InlineAsm::AD_Intel; |
| 3197 | llvm::InlineAsm::AsmDialect AsmDialect = isa<MSAsmStmt>(Val: &S) ? |
| 3198 | llvm::InlineAsm::AD_Intel : GnuAsmDialect; |
| 3199 | |
| 3200 | llvm::InlineAsm *IA = llvm::InlineAsm::get( |
| 3201 | Ty: FTy, AsmString, Constraints, hasSideEffects: HasSideEffect, |
| 3202 | /* IsAlignStack */ isAlignStack: false, asmDialect: AsmDialect, canThrow: HasUnwindClobber); |
| 3203 | std::vector<llvm::Value*> RegResults; |
| 3204 | llvm::CallBrInst *CBR; |
| 3205 | llvm::DenseMap<llvm::BasicBlock *, SmallVector<llvm::Value *, 4>> |
| 3206 | CBRRegResults; |
| 3207 | if (IsGCCAsmGoto) { |
| 3208 | CBR = Builder.CreateCallBr(Callee: IA, DefaultDest: Fallthrough, IndirectDests: Transfer, Args); |
| 3209 | EmitBlock(BB: Fallthrough); |
| 3210 | UpdateAsmCallInst(Result&: *CBR, HasSideEffect, /*HasUnwindClobber=*/false, ReadOnly, |
| 3211 | ReadNone, NoMerge: InNoMergeAttributedStmt, |
| 3212 | NoConvergent: InNoConvergentAttributedStmt, S, ResultRegTypes, |
| 3213 | ArgElemTypes, CGF&: *this, RegResults); |
| 3214 | // Because we are emitting code top to bottom, we don't have enough |
| 3215 | // information at this point to know precisely whether we have a critical |
| 3216 | // edge. If we have outputs, split all indirect destinations. |
| 3217 | if (!RegResults.empty()) { |
| 3218 | unsigned i = 0; |
| 3219 | for (llvm::BasicBlock *Dest : CBR->getIndirectDests()) { |
| 3220 | llvm::Twine SynthName = Dest->getName() + ".split" ; |
| 3221 | llvm::BasicBlock *SynthBB = createBasicBlock(name: SynthName); |
| 3222 | llvm::IRBuilderBase::InsertPointGuard IPG(Builder); |
| 3223 | Builder.SetInsertPoint(SynthBB); |
| 3224 | |
| 3225 | if (ResultRegTypes.size() == 1) { |
| 3226 | CBRRegResults[SynthBB].push_back(Elt: CBR); |
| 3227 | } else { |
| 3228 | for (unsigned j = 0, e = ResultRegTypes.size(); j != e; ++j) { |
| 3229 | llvm::Value *Tmp = Builder.CreateExtractValue(Agg: CBR, Idxs: j, Name: "asmresult" ); |
| 3230 | CBRRegResults[SynthBB].push_back(Elt: Tmp); |
| 3231 | } |
| 3232 | } |
| 3233 | |
| 3234 | EmitBranch(Target: Dest); |
| 3235 | EmitBlock(BB: SynthBB); |
| 3236 | CBR->setIndirectDest(i: i++, B: SynthBB); |
| 3237 | } |
| 3238 | } |
| 3239 | } else if (HasUnwindClobber) { |
| 3240 | llvm::CallBase *Result = EmitCallOrInvoke(Callee: IA, Args, Name: "" ); |
| 3241 | UpdateAsmCallInst(Result&: *Result, HasSideEffect, /*HasUnwindClobber=*/true, |
| 3242 | ReadOnly, ReadNone, NoMerge: InNoMergeAttributedStmt, |
| 3243 | NoConvergent: InNoConvergentAttributedStmt, S, ResultRegTypes, |
| 3244 | ArgElemTypes, CGF&: *this, RegResults); |
| 3245 | } else { |
| 3246 | llvm::CallInst *Result = |
| 3247 | Builder.CreateCall(Callee: IA, Args, OpBundles: getBundlesForFunclet(Callee: IA)); |
| 3248 | UpdateAsmCallInst(Result&: *Result, HasSideEffect, /*HasUnwindClobber=*/false, |
| 3249 | ReadOnly, ReadNone, NoMerge: InNoMergeAttributedStmt, |
| 3250 | NoConvergent: InNoConvergentAttributedStmt, S, ResultRegTypes, |
| 3251 | ArgElemTypes, CGF&: *this, RegResults); |
| 3252 | } |
| 3253 | |
| 3254 | EmitAsmStores(CGF&: *this, S, RegResults, ResultRegTypes, ResultTruncRegTypes, |
| 3255 | ResultRegDests, ResultRegQualTys, ResultTypeRequiresCast, |
| 3256 | ResultBounds); |
| 3257 | |
| 3258 | // If this is an asm goto with outputs, repeat EmitAsmStores, but with a |
| 3259 | // different insertion point; one for each indirect destination and with |
| 3260 | // CBRRegResults rather than RegResults. |
| 3261 | if (IsGCCAsmGoto && !CBRRegResults.empty()) { |
| 3262 | for (llvm::BasicBlock *Succ : CBR->getIndirectDests()) { |
| 3263 | llvm::IRBuilderBase::InsertPointGuard IPG(Builder); |
| 3264 | Builder.SetInsertPoint(TheBB: Succ, IP: --(Succ->end())); |
| 3265 | EmitAsmStores(CGF&: *this, S, RegResults: CBRRegResults[Succ], ResultRegTypes, |
| 3266 | ResultTruncRegTypes, ResultRegDests, ResultRegQualTys, |
| 3267 | ResultTypeRequiresCast, ResultBounds); |
| 3268 | } |
| 3269 | } |
| 3270 | } |
| 3271 | |
| 3272 | LValue CodeGenFunction::InitCapturedStruct(const CapturedStmt &S) { |
| 3273 | const RecordDecl *RD = S.getCapturedRecordDecl(); |
| 3274 | CanQualType RecordTy = getContext().getCanonicalTagType(TD: RD); |
| 3275 | |
| 3276 | // Initialize the captured struct. |
| 3277 | LValue SlotLV = |
| 3278 | MakeAddrLValue(Addr: CreateMemTemp(T: RecordTy, Name: "agg.captured" ), T: RecordTy); |
| 3279 | |
| 3280 | RecordDecl::field_iterator CurField = RD->field_begin(); |
| 3281 | for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(), |
| 3282 | E = S.capture_init_end(); |
| 3283 | I != E; ++I, ++CurField) { |
| 3284 | LValue LV = EmitLValueForFieldInitialization(Base: SlotLV, Field: *CurField); |
| 3285 | if (CurField->hasCapturedVLAType()) { |
| 3286 | EmitLambdaVLACapture(VAT: CurField->getCapturedVLAType(), LV); |
| 3287 | } else { |
| 3288 | EmitInitializerForField(Field: *CurField, LHS: LV, Init: *I); |
| 3289 | } |
| 3290 | } |
| 3291 | |
| 3292 | return SlotLV; |
| 3293 | } |
| 3294 | |
| 3295 | /// Generate an outlined function for the body of a CapturedStmt, store any |
| 3296 | /// captured variables into the captured struct, and call the outlined function. |
| 3297 | llvm::Function * |
| 3298 | CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K) { |
| 3299 | LValue CapStruct = InitCapturedStruct(S); |
| 3300 | |
| 3301 | // Emit the CapturedDecl |
| 3302 | CodeGenFunction CGF(CGM, true); |
| 3303 | CGCapturedStmtRAII CapInfoRAII(CGF, new CGCapturedStmtInfo(S, K)); |
| 3304 | llvm::Function *F = CGF.GenerateCapturedStmtFunction(S); |
| 3305 | delete CGF.CapturedStmtInfo; |
| 3306 | |
| 3307 | // Emit call to the helper function. |
| 3308 | EmitCallOrInvoke(Callee: F, Args: CapStruct.getPointer(CGF&: *this)); |
| 3309 | |
| 3310 | return F; |
| 3311 | } |
| 3312 | |
| 3313 | Address CodeGenFunction::GenerateCapturedStmtArgument(const CapturedStmt &S) { |
| 3314 | LValue CapStruct = InitCapturedStruct(S); |
| 3315 | return CapStruct.getAddress(); |
| 3316 | } |
| 3317 | |
| 3318 | /// Creates the outlined function for a CapturedStmt. |
| 3319 | llvm::Function * |
| 3320 | CodeGenFunction::GenerateCapturedStmtFunction(const CapturedStmt &S) { |
| 3321 | assert(CapturedStmtInfo && |
| 3322 | "CapturedStmtInfo should be set when generating the captured function" ); |
| 3323 | const CapturedDecl *CD = S.getCapturedDecl(); |
| 3324 | const RecordDecl *RD = S.getCapturedRecordDecl(); |
| 3325 | SourceLocation Loc = S.getBeginLoc(); |
| 3326 | assert(CD->hasBody() && "missing CapturedDecl body" ); |
| 3327 | |
| 3328 | // Build the argument list. |
| 3329 | ASTContext &Ctx = CGM.getContext(); |
| 3330 | FunctionArgList Args; |
| 3331 | Args.append(in_start: CD->param_begin(), in_end: CD->param_end()); |
| 3332 | |
| 3333 | // Create the function declaration. |
| 3334 | const CGFunctionInfo &FuncInfo = |
| 3335 | CGM.getTypes().arrangeBuiltinFunctionDeclaration(resultType: Ctx.VoidTy, args: Args); |
| 3336 | llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(Info: FuncInfo); |
| 3337 | |
| 3338 | llvm::Function *F = |
| 3339 | llvm::Function::Create(Ty: FuncLLVMTy, Linkage: llvm::GlobalValue::InternalLinkage, |
| 3340 | N: CapturedStmtInfo->getHelperName(), M: &CGM.getModule()); |
| 3341 | CGM.SetInternalFunctionAttributes(GD: CD, F, FI: FuncInfo); |
| 3342 | if (!CGM.getCodeGenOpts().SampleProfileFile.empty()) |
| 3343 | F->addFnAttr(Kind: "sample-profile-suffix-elision-policy" , Val: "selected" ); |
| 3344 | if (CD->isNothrow()) |
| 3345 | F->addFnAttr(Kind: llvm::Attribute::NoUnwind); |
| 3346 | |
| 3347 | // Generate the function. |
| 3348 | StartFunction(GD: CD, RetTy: Ctx.VoidTy, Fn: F, FnInfo: FuncInfo, Args, Loc: CD->getLocation(), |
| 3349 | StartLoc: CD->getBody()->getBeginLoc()); |
| 3350 | // Set the context parameter in CapturedStmtInfo. |
| 3351 | Address DeclPtr = GetAddrOfLocalVar(VD: CD->getContextParam()); |
| 3352 | CapturedStmtInfo->setContextValue(Builder.CreateLoad(Addr: DeclPtr)); |
| 3353 | |
| 3354 | // Initialize variable-length arrays. |
| 3355 | LValue Base = MakeNaturalAlignRawAddrLValue( |
| 3356 | V: CapturedStmtInfo->getContextValue(), T: Ctx.getCanonicalTagType(TD: RD)); |
| 3357 | for (auto *FD : RD->fields()) { |
| 3358 | if (FD->hasCapturedVLAType()) { |
| 3359 | auto *ExprArg = |
| 3360 | EmitLoadOfLValue(V: EmitLValueForField(Base, Field: FD), Loc: S.getBeginLoc()) |
| 3361 | .getScalarVal(); |
| 3362 | auto VAT = FD->getCapturedVLAType(); |
| 3363 | VLASizeMap[VAT->getSizeExpr()] = ExprArg; |
| 3364 | } |
| 3365 | } |
| 3366 | |
| 3367 | // If 'this' is captured, load it into CXXThisValue. |
| 3368 | if (CapturedStmtInfo->isCXXThisExprCaptured()) { |
| 3369 | FieldDecl *FD = CapturedStmtInfo->getThisFieldDecl(); |
| 3370 | LValue ThisLValue = EmitLValueForField(Base, Field: FD); |
| 3371 | CXXThisValue = EmitLoadOfLValue(V: ThisLValue, Loc).getScalarVal(); |
| 3372 | } |
| 3373 | |
| 3374 | PGO->assignRegionCounters(GD: GlobalDecl(CD), Fn: F); |
| 3375 | CapturedStmtInfo->EmitBody(CGF&: *this, S: CD->getBody()); |
| 3376 | FinishFunction(EndLoc: CD->getBodyRBrace()); |
| 3377 | |
| 3378 | return F; |
| 3379 | } |
| 3380 | |
| 3381 | // Returns the first convergence entry/loop/anchor instruction found in |BB|. |
| 3382 | // std::nullptr otherwise. |
| 3383 | static llvm::ConvergenceControlInst *getConvergenceToken(llvm::BasicBlock *BB) { |
| 3384 | for (auto &I : *BB) { |
| 3385 | if (auto *CI = dyn_cast<llvm::ConvergenceControlInst>(Val: &I)) |
| 3386 | return CI; |
| 3387 | } |
| 3388 | return nullptr; |
| 3389 | } |
| 3390 | |
| 3391 | llvm::CallBase * |
| 3392 | CodeGenFunction::addConvergenceControlToken(llvm::CallBase *Input) { |
| 3393 | llvm::ConvergenceControlInst *ParentToken = ConvergenceTokenStack.back(); |
| 3394 | assert(ParentToken); |
| 3395 | |
| 3396 | llvm::Value *bundleArgs[] = {ParentToken}; |
| 3397 | llvm::OperandBundleDef OB("convergencectrl" , bundleArgs); |
| 3398 | auto *Output = llvm::CallBase::addOperandBundle( |
| 3399 | CB: Input, ID: llvm::LLVMContext::OB_convergencectrl, OB, InsertPt: Input->getIterator()); |
| 3400 | Input->replaceAllUsesWith(V: Output); |
| 3401 | Input->eraseFromParent(); |
| 3402 | return Output; |
| 3403 | } |
| 3404 | |
| 3405 | llvm::ConvergenceControlInst * |
| 3406 | CodeGenFunction::emitConvergenceLoopToken(llvm::BasicBlock *BB) { |
| 3407 | llvm::ConvergenceControlInst *ParentToken = ConvergenceTokenStack.back(); |
| 3408 | assert(ParentToken); |
| 3409 | return llvm::ConvergenceControlInst::CreateLoop(BB&: *BB, Parent: ParentToken); |
| 3410 | } |
| 3411 | |
| 3412 | llvm::ConvergenceControlInst * |
| 3413 | CodeGenFunction::getOrEmitConvergenceEntryToken(llvm::Function *F) { |
| 3414 | llvm::BasicBlock *BB = &F->getEntryBlock(); |
| 3415 | llvm::ConvergenceControlInst *Token = getConvergenceToken(BB); |
| 3416 | if (Token) |
| 3417 | return Token; |
| 3418 | |
| 3419 | // Adding a convergence token requires the function to be marked as |
| 3420 | // convergent. |
| 3421 | F->setConvergent(); |
| 3422 | return llvm::ConvergenceControlInst::CreateEntry(BB&: *BB); |
| 3423 | } |
| 3424 | |