1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This coordinates the per-function state used while generating code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CGCleanup.h" 16 #include "CGCUDARuntime.h" 17 #include "CGCXXABI.h" 18 #include "CGDebugInfo.h" 19 #include "CGOpenMPRuntime.h" 20 #include "CodeGenModule.h" 21 #include "CodeGenPGO.h" 22 #include "TargetInfo.h" 23 #include "clang/AST/ASTContext.h" 24 #include "clang/AST/Decl.h" 25 #include "clang/AST/DeclCXX.h" 26 #include "clang/AST/StmtCXX.h" 27 #include "clang/Basic/Builtins.h" 28 #include "clang/Basic/TargetInfo.h" 29 #include "clang/CodeGen/CGFunctionInfo.h" 30 #include "clang/Frontend/CodeGenOptions.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/Intrinsics.h" 33 #include "llvm/IR/MDBuilder.h" 34 #include "llvm/IR/Operator.h" 35 using namespace clang; 36 using namespace CodeGen; 37 38 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext) 39 : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()), 40 Builder(cgm.getModule().getContext(), llvm::ConstantFolder(), 41 CGBuilderInserterTy(this)), 42 CurFn(nullptr), CapturedStmtInfo(nullptr), 43 SanOpts(CGM.getLangOpts().Sanitize), IsSanitizerScope(false), 44 CurFuncIsThunk(false), AutoreleaseResult(false), SawAsmBlock(false), 45 IsOutlinedSEHHelper(false), BlockInfo(nullptr), BlockPointer(nullptr), 46 LambdaThisCaptureField(nullptr), NormalCleanupDest(nullptr), 47 NextCleanupDestIndex(1), FirstBlockInfo(nullptr), EHResumeBlock(nullptr), 48 ExceptionSlot(nullptr), EHSelectorSlot(nullptr), 49 DebugInfo(CGM.getModuleDebugInfo()), 50 DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(nullptr), 51 PGO(cgm), SwitchInsn(nullptr), SwitchWeights(nullptr), 52 CaseRangeBlock(nullptr), UnreachableBlock(nullptr), NumReturnExprs(0), 53 NumSimpleReturnExprs(0), CXXABIThisDecl(nullptr), 54 CXXABIThisValue(nullptr), CXXThisValue(nullptr), 55 CXXDefaultInitExprThis(nullptr), CXXStructorImplicitParamDecl(nullptr), 56 CXXStructorImplicitParamValue(nullptr), OutermostConditional(nullptr), 57 CurLexicalScope(nullptr), TerminateLandingPad(nullptr), 58 TerminateHandler(nullptr), TrapBB(nullptr) { 59 if (!suppressNewContext) 60 CGM.getCXXABI().getMangleContext().startNewFunction(); 61 62 llvm::FastMathFlags FMF; 63 if (CGM.getLangOpts().FastMath) 64 FMF.setUnsafeAlgebra(); 65 if (CGM.getLangOpts().FiniteMathOnly) { 66 FMF.setNoNaNs(); 67 FMF.setNoInfs(); 68 } 69 if (CGM.getCodeGenOpts().NoNaNsFPMath) { 70 FMF.setNoNaNs(); 71 } 72 if (CGM.getCodeGenOpts().NoSignedZeros) { 73 FMF.setNoSignedZeros(); 74 } 75 if (CGM.getCodeGenOpts().ReciprocalMath) { 76 FMF.setAllowReciprocal(); 77 } 78 Builder.SetFastMathFlags(FMF); 79 } 80 81 CodeGenFunction::~CodeGenFunction() { 82 assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup"); 83 84 // If there are any unclaimed block infos, go ahead and destroy them 85 // now. This can happen if IR-gen gets clever and skips evaluating 86 // something. 87 if (FirstBlockInfo) 88 destroyBlockInfos(FirstBlockInfo); 89 90 if (getLangOpts().OpenMP) { 91 CGM.getOpenMPRuntime().functionFinished(*this); 92 } 93 } 94 95 LValue CodeGenFunction::MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) { 96 CharUnits Alignment; 97 if (CGM.getCXXABI().isTypeInfoCalculable(T)) { 98 Alignment = getContext().getTypeAlignInChars(T); 99 unsigned MaxAlign = getContext().getLangOpts().MaxTypeAlign; 100 if (MaxAlign && Alignment.getQuantity() > MaxAlign && 101 !getContext().isAlignmentRequired(T)) 102 Alignment = CharUnits::fromQuantity(MaxAlign); 103 } 104 return LValue::MakeAddr(V, T, Alignment, getContext(), CGM.getTBAAInfo(T)); 105 } 106 107 llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) { 108 return CGM.getTypes().ConvertTypeForMem(T); 109 } 110 111 llvm::Type *CodeGenFunction::ConvertType(QualType T) { 112 return CGM.getTypes().ConvertType(T); 113 } 114 115 TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) { 116 type = type.getCanonicalType(); 117 while (true) { 118 switch (type->getTypeClass()) { 119 #define TYPE(name, parent) 120 #define ABSTRACT_TYPE(name, parent) 121 #define NON_CANONICAL_TYPE(name, parent) case Type::name: 122 #define DEPENDENT_TYPE(name, parent) case Type::name: 123 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name: 124 #include "clang/AST/TypeNodes.def" 125 llvm_unreachable("non-canonical or dependent type in IR-generation"); 126 127 case Type::Auto: 128 llvm_unreachable("undeduced auto type in IR-generation"); 129 130 // Various scalar types. 131 case Type::Builtin: 132 case Type::Pointer: 133 case Type::BlockPointer: 134 case Type::LValueReference: 135 case Type::RValueReference: 136 case Type::MemberPointer: 137 case Type::Vector: 138 case Type::ExtVector: 139 case Type::FunctionProto: 140 case Type::FunctionNoProto: 141 case Type::Enum: 142 case Type::ObjCObjectPointer: 143 return TEK_Scalar; 144 145 // Complexes. 146 case Type::Complex: 147 return TEK_Complex; 148 149 // Arrays, records, and Objective-C objects. 150 case Type::ConstantArray: 151 case Type::IncompleteArray: 152 case Type::VariableArray: 153 case Type::Record: 154 case Type::ObjCObject: 155 case Type::ObjCInterface: 156 return TEK_Aggregate; 157 158 // We operate on atomic values according to their underlying type. 159 case Type::Atomic: 160 type = cast<AtomicType>(type)->getValueType(); 161 continue; 162 } 163 llvm_unreachable("unknown type kind!"); 164 } 165 } 166 167 llvm::DebugLoc CodeGenFunction::EmitReturnBlock() { 168 // For cleanliness, we try to avoid emitting the return block for 169 // simple cases. 170 llvm::BasicBlock *CurBB = Builder.GetInsertBlock(); 171 172 if (CurBB) { 173 assert(!CurBB->getTerminator() && "Unexpected terminated block."); 174 175 // We have a valid insert point, reuse it if it is empty or there are no 176 // explicit jumps to the return block. 177 if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) { 178 ReturnBlock.getBlock()->replaceAllUsesWith(CurBB); 179 delete ReturnBlock.getBlock(); 180 } else 181 EmitBlock(ReturnBlock.getBlock()); 182 return llvm::DebugLoc(); 183 } 184 185 // Otherwise, if the return block is the target of a single direct 186 // branch then we can just put the code in that block instead. This 187 // cleans up functions which started with a unified return block. 188 if (ReturnBlock.getBlock()->hasOneUse()) { 189 llvm::BranchInst *BI = 190 dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->user_begin()); 191 if (BI && BI->isUnconditional() && 192 BI->getSuccessor(0) == ReturnBlock.getBlock()) { 193 // Record/return the DebugLoc of the simple 'return' expression to be used 194 // later by the actual 'ret' instruction. 195 llvm::DebugLoc Loc = BI->getDebugLoc(); 196 Builder.SetInsertPoint(BI->getParent()); 197 BI->eraseFromParent(); 198 delete ReturnBlock.getBlock(); 199 return Loc; 200 } 201 } 202 203 // FIXME: We are at an unreachable point, there is no reason to emit the block 204 // unless it has uses. However, we still need a place to put the debug 205 // region.end for now. 206 207 EmitBlock(ReturnBlock.getBlock()); 208 return llvm::DebugLoc(); 209 } 210 211 static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) { 212 if (!BB) return; 213 if (!BB->use_empty()) 214 return CGF.CurFn->getBasicBlockList().push_back(BB); 215 delete BB; 216 } 217 218 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) { 219 assert(BreakContinueStack.empty() && 220 "mismatched push/pop in break/continue stack!"); 221 222 bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0 223 && NumSimpleReturnExprs == NumReturnExprs 224 && ReturnBlock.getBlock()->use_empty(); 225 // Usually the return expression is evaluated before the cleanup 226 // code. If the function contains only a simple return statement, 227 // such as a constant, the location before the cleanup code becomes 228 // the last useful breakpoint in the function, because the simple 229 // return expression will be evaluated after the cleanup code. To be 230 // safe, set the debug location for cleanup code to the location of 231 // the return statement. Otherwise the cleanup code should be at the 232 // end of the function's lexical scope. 233 // 234 // If there are multiple branches to the return block, the branch 235 // instructions will get the location of the return statements and 236 // all will be fine. 237 if (CGDebugInfo *DI = getDebugInfo()) { 238 if (OnlySimpleReturnStmts) 239 DI->EmitLocation(Builder, LastStopPoint); 240 else 241 DI->EmitLocation(Builder, EndLoc); 242 } 243 244 // Pop any cleanups that might have been associated with the 245 // parameters. Do this in whatever block we're currently in; it's 246 // important to do this before we enter the return block or return 247 // edges will be *really* confused. 248 bool HasCleanups = EHStack.stable_begin() != PrologueCleanupDepth; 249 bool HasOnlyLifetimeMarkers = 250 HasCleanups && EHStack.containsOnlyLifetimeMarkers(PrologueCleanupDepth); 251 bool EmitRetDbgLoc = !HasCleanups || HasOnlyLifetimeMarkers; 252 if (HasCleanups) { 253 // Make sure the line table doesn't jump back into the body for 254 // the ret after it's been at EndLoc. 255 if (CGDebugInfo *DI = getDebugInfo()) 256 if (OnlySimpleReturnStmts) 257 DI->EmitLocation(Builder, EndLoc); 258 259 PopCleanupBlocks(PrologueCleanupDepth); 260 } 261 262 // Emit function epilog (to return). 263 llvm::DebugLoc Loc = EmitReturnBlock(); 264 265 if (ShouldInstrumentFunction()) 266 EmitFunctionInstrumentation("__cyg_profile_func_exit"); 267 268 // Emit debug descriptor for function end. 269 if (CGDebugInfo *DI = getDebugInfo()) 270 DI->EmitFunctionEnd(Builder); 271 272 // Reset the debug location to that of the simple 'return' expression, if any 273 // rather than that of the end of the function's scope '}'. 274 ApplyDebugLocation AL(*this, Loc); 275 EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc, EndLoc); 276 EmitEndEHSpec(CurCodeDecl); 277 278 assert(EHStack.empty() && 279 "did not remove all scopes from cleanup stack!"); 280 281 // If someone did an indirect goto, emit the indirect goto block at the end of 282 // the function. 283 if (IndirectBranch) { 284 EmitBlock(IndirectBranch->getParent()); 285 Builder.ClearInsertionPoint(); 286 } 287 288 // If some of our locals escaped, insert a call to llvm.localescape in the 289 // entry block. 290 if (!EscapedLocals.empty()) { 291 // Invert the map from local to index into a simple vector. There should be 292 // no holes. 293 SmallVector<llvm::Value *, 4> EscapeArgs; 294 EscapeArgs.resize(EscapedLocals.size()); 295 for (auto &Pair : EscapedLocals) 296 EscapeArgs[Pair.second] = Pair.first; 297 llvm::Function *FrameEscapeFn = llvm::Intrinsic::getDeclaration( 298 &CGM.getModule(), llvm::Intrinsic::localescape); 299 CGBuilderTy(AllocaInsertPt).CreateCall(FrameEscapeFn, EscapeArgs); 300 } 301 302 // Remove the AllocaInsertPt instruction, which is just a convenience for us. 303 llvm::Instruction *Ptr = AllocaInsertPt; 304 AllocaInsertPt = nullptr; 305 Ptr->eraseFromParent(); 306 307 // If someone took the address of a label but never did an indirect goto, we 308 // made a zero entry PHI node, which is illegal, zap it now. 309 if (IndirectBranch) { 310 llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress()); 311 if (PN->getNumIncomingValues() == 0) { 312 PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType())); 313 PN->eraseFromParent(); 314 } 315 } 316 317 EmitIfUsed(*this, EHResumeBlock); 318 EmitIfUsed(*this, TerminateLandingPad); 319 EmitIfUsed(*this, TerminateHandler); 320 EmitIfUsed(*this, UnreachableBlock); 321 322 if (CGM.getCodeGenOpts().EmitDeclMetadata) 323 EmitDeclMetadata(); 324 325 for (SmallVectorImpl<std::pair<llvm::Instruction *, llvm::Value *> >::iterator 326 I = DeferredReplacements.begin(), 327 E = DeferredReplacements.end(); 328 I != E; ++I) { 329 I->first->replaceAllUsesWith(I->second); 330 I->first->eraseFromParent(); 331 } 332 } 333 334 /// ShouldInstrumentFunction - Return true if the current function should be 335 /// instrumented with __cyg_profile_func_* calls 336 bool CodeGenFunction::ShouldInstrumentFunction() { 337 if (!CGM.getCodeGenOpts().InstrumentFunctions) 338 return false; 339 if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>()) 340 return false; 341 return true; 342 } 343 344 /// EmitFunctionInstrumentation - Emit LLVM code to call the specified 345 /// instrumentation function with the current function and the call site, if 346 /// function instrumentation is enabled. 347 void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) { 348 // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site); 349 llvm::PointerType *PointerTy = Int8PtrTy; 350 llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy }; 351 llvm::FunctionType *FunctionTy = 352 llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false); 353 354 llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn); 355 llvm::CallInst *CallSite = Builder.CreateCall( 356 CGM.getIntrinsic(llvm::Intrinsic::returnaddress), 357 llvm::ConstantInt::get(Int32Ty, 0), 358 "callsite"); 359 360 llvm::Value *args[] = { 361 llvm::ConstantExpr::getBitCast(CurFn, PointerTy), 362 CallSite 363 }; 364 365 EmitNounwindRuntimeCall(F, args); 366 } 367 368 void CodeGenFunction::EmitMCountInstrumentation() { 369 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false); 370 371 llvm::Constant *MCountFn = 372 CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName()); 373 EmitNounwindRuntimeCall(MCountFn); 374 } 375 376 // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument 377 // information in the program executable. The argument information stored 378 // includes the argument name, its type, the address and access qualifiers used. 379 static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn, 380 CodeGenModule &CGM, llvm::LLVMContext &Context, 381 SmallVector<llvm::Metadata *, 5> &kernelMDArgs, 382 CGBuilderTy &Builder, ASTContext &ASTCtx) { 383 // Create MDNodes that represent the kernel arg metadata. 384 // Each MDNode is a list in the form of "key", N number of values which is 385 // the same number of values as their are kernel arguments. 386 387 const PrintingPolicy &Policy = ASTCtx.getPrintingPolicy(); 388 389 // MDNode for the kernel argument address space qualifiers. 390 SmallVector<llvm::Metadata *, 8> addressQuals; 391 addressQuals.push_back(llvm::MDString::get(Context, "kernel_arg_addr_space")); 392 393 // MDNode for the kernel argument access qualifiers (images only). 394 SmallVector<llvm::Metadata *, 8> accessQuals; 395 accessQuals.push_back(llvm::MDString::get(Context, "kernel_arg_access_qual")); 396 397 // MDNode for the kernel argument type names. 398 SmallVector<llvm::Metadata *, 8> argTypeNames; 399 argTypeNames.push_back(llvm::MDString::get(Context, "kernel_arg_type")); 400 401 // MDNode for the kernel argument base type names. 402 SmallVector<llvm::Metadata *, 8> argBaseTypeNames; 403 argBaseTypeNames.push_back( 404 llvm::MDString::get(Context, "kernel_arg_base_type")); 405 406 // MDNode for the kernel argument type qualifiers. 407 SmallVector<llvm::Metadata *, 8> argTypeQuals; 408 argTypeQuals.push_back(llvm::MDString::get(Context, "kernel_arg_type_qual")); 409 410 // MDNode for the kernel argument names. 411 SmallVector<llvm::Metadata *, 8> argNames; 412 argNames.push_back(llvm::MDString::get(Context, "kernel_arg_name")); 413 414 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 415 const ParmVarDecl *parm = FD->getParamDecl(i); 416 QualType ty = parm->getType(); 417 std::string typeQuals; 418 419 if (ty->isPointerType()) { 420 QualType pointeeTy = ty->getPointeeType(); 421 422 // Get address qualifier. 423 addressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32( 424 ASTCtx.getTargetAddressSpace(pointeeTy.getAddressSpace())))); 425 426 // Get argument type name. 427 std::string typeName = 428 pointeeTy.getUnqualifiedType().getAsString(Policy) + "*"; 429 430 // Turn "unsigned type" to "utype" 431 std::string::size_type pos = typeName.find("unsigned"); 432 if (pointeeTy.isCanonical() && pos != std::string::npos) 433 typeName.erase(pos+1, 8); 434 435 argTypeNames.push_back(llvm::MDString::get(Context, typeName)); 436 437 std::string baseTypeName = 438 pointeeTy.getUnqualifiedType().getCanonicalType().getAsString( 439 Policy) + 440 "*"; 441 442 // Turn "unsigned type" to "utype" 443 pos = baseTypeName.find("unsigned"); 444 if (pos != std::string::npos) 445 baseTypeName.erase(pos+1, 8); 446 447 argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName)); 448 449 // Get argument type qualifiers: 450 if (ty.isRestrictQualified()) 451 typeQuals = "restrict"; 452 if (pointeeTy.isConstQualified() || 453 (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) 454 typeQuals += typeQuals.empty() ? "const" : " const"; 455 if (pointeeTy.isVolatileQualified()) 456 typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 457 } else { 458 uint32_t AddrSpc = 0; 459 if (ty->isImageType()) 460 AddrSpc = 461 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global); 462 463 addressQuals.push_back( 464 llvm::ConstantAsMetadata::get(Builder.getInt32(AddrSpc))); 465 466 // Get argument type name. 467 std::string typeName = ty.getUnqualifiedType().getAsString(Policy); 468 469 // Turn "unsigned type" to "utype" 470 std::string::size_type pos = typeName.find("unsigned"); 471 if (ty.isCanonical() && pos != std::string::npos) 472 typeName.erase(pos+1, 8); 473 474 argTypeNames.push_back(llvm::MDString::get(Context, typeName)); 475 476 std::string baseTypeName = 477 ty.getUnqualifiedType().getCanonicalType().getAsString(Policy); 478 479 // Turn "unsigned type" to "utype" 480 pos = baseTypeName.find("unsigned"); 481 if (pos != std::string::npos) 482 baseTypeName.erase(pos+1, 8); 483 484 argBaseTypeNames.push_back(llvm::MDString::get(Context, baseTypeName)); 485 486 // Get argument type qualifiers: 487 if (ty.isConstQualified()) 488 typeQuals = "const"; 489 if (ty.isVolatileQualified()) 490 typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 491 } 492 493 argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals)); 494 495 // Get image access qualifier: 496 if (ty->isImageType()) { 497 const OpenCLImageAccessAttr *A = parm->getAttr<OpenCLImageAccessAttr>(); 498 if (A && A->isWriteOnly()) 499 accessQuals.push_back(llvm::MDString::get(Context, "write_only")); 500 else 501 accessQuals.push_back(llvm::MDString::get(Context, "read_only")); 502 // FIXME: what about read_write? 503 } else 504 accessQuals.push_back(llvm::MDString::get(Context, "none")); 505 506 // Get argument name. 507 argNames.push_back(llvm::MDString::get(Context, parm->getName())); 508 } 509 510 kernelMDArgs.push_back(llvm::MDNode::get(Context, addressQuals)); 511 kernelMDArgs.push_back(llvm::MDNode::get(Context, accessQuals)); 512 kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames)); 513 kernelMDArgs.push_back(llvm::MDNode::get(Context, argBaseTypeNames)); 514 kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals)); 515 if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata) 516 kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames)); 517 } 518 519 void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD, 520 llvm::Function *Fn) 521 { 522 if (!FD->hasAttr<OpenCLKernelAttr>()) 523 return; 524 525 llvm::LLVMContext &Context = getLLVMContext(); 526 527 SmallVector<llvm::Metadata *, 5> kernelMDArgs; 528 kernelMDArgs.push_back(llvm::ConstantAsMetadata::get(Fn)); 529 530 GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs, Builder, 531 getContext()); 532 533 if (const VecTypeHintAttr *A = FD->getAttr<VecTypeHintAttr>()) { 534 QualType hintQTy = A->getTypeHint(); 535 const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>(); 536 bool isSignedInteger = 537 hintQTy->isSignedIntegerType() || 538 (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType()); 539 llvm::Metadata *attrMDArgs[] = { 540 llvm::MDString::get(Context, "vec_type_hint"), 541 llvm::ConstantAsMetadata::get(llvm::UndefValue::get( 542 CGM.getTypes().ConvertType(A->getTypeHint()))), 543 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 544 llvm::IntegerType::get(Context, 32), 545 llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0))))}; 546 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs)); 547 } 548 549 if (const WorkGroupSizeHintAttr *A = FD->getAttr<WorkGroupSizeHintAttr>()) { 550 llvm::Metadata *attrMDArgs[] = { 551 llvm::MDString::get(Context, "work_group_size_hint"), 552 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())), 553 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())), 554 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))}; 555 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs)); 556 } 557 558 if (const ReqdWorkGroupSizeAttr *A = FD->getAttr<ReqdWorkGroupSizeAttr>()) { 559 llvm::Metadata *attrMDArgs[] = { 560 llvm::MDString::get(Context, "reqd_work_group_size"), 561 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getXDim())), 562 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getYDim())), 563 llvm::ConstantAsMetadata::get(Builder.getInt32(A->getZDim()))}; 564 kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs)); 565 } 566 567 llvm::MDNode *kernelMDNode = llvm::MDNode::get(Context, kernelMDArgs); 568 llvm::NamedMDNode *OpenCLKernelMetadata = 569 CGM.getModule().getOrInsertNamedMetadata("opencl.kernels"); 570 OpenCLKernelMetadata->addOperand(kernelMDNode); 571 } 572 573 /// Determine whether the function F ends with a return stmt. 574 static bool endsWithReturn(const Decl* F) { 575 const Stmt *Body = nullptr; 576 if (auto *FD = dyn_cast_or_null<FunctionDecl>(F)) 577 Body = FD->getBody(); 578 else if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(F)) 579 Body = OMD->getBody(); 580 581 if (auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) { 582 auto LastStmt = CS->body_rbegin(); 583 if (LastStmt != CS->body_rend()) 584 return isa<ReturnStmt>(*LastStmt); 585 } 586 return false; 587 } 588 589 void CodeGenFunction::StartFunction(GlobalDecl GD, 590 QualType RetTy, 591 llvm::Function *Fn, 592 const CGFunctionInfo &FnInfo, 593 const FunctionArgList &Args, 594 SourceLocation Loc, 595 SourceLocation StartLoc) { 596 assert(!CurFn && 597 "Do not use a CodeGenFunction object for more than one function"); 598 599 const Decl *D = GD.getDecl(); 600 601 DidCallStackSave = false; 602 CurCodeDecl = D; 603 CurFuncDecl = (D ? D->getNonClosureContext() : nullptr); 604 FnRetTy = RetTy; 605 CurFn = Fn; 606 CurFnInfo = &FnInfo; 607 assert(CurFn->isDeclaration() && "Function already has body?"); 608 609 if (CGM.isInSanitizerBlacklist(Fn, Loc)) 610 SanOpts.clear(); 611 612 if (D) { 613 // Apply the no_sanitize* attributes to SanOpts. 614 for (auto Attr : D->specific_attrs<NoSanitizeAttr>()) 615 SanOpts.Mask &= ~Attr->getMask(); 616 } 617 618 // Apply sanitizer attributes to the function. 619 if (SanOpts.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress)) 620 Fn->addFnAttr(llvm::Attribute::SanitizeAddress); 621 if (SanOpts.has(SanitizerKind::Thread)) 622 Fn->addFnAttr(llvm::Attribute::SanitizeThread); 623 if (SanOpts.has(SanitizerKind::Memory)) 624 Fn->addFnAttr(llvm::Attribute::SanitizeMemory); 625 if (SanOpts.has(SanitizerKind::SafeStack)) 626 Fn->addFnAttr(llvm::Attribute::SafeStack); 627 628 // Pass inline keyword to optimizer if it appears explicitly on any 629 // declaration. Also, in the case of -fno-inline attach NoInline 630 // attribute to all function that are not marked AlwaysInline. 631 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 632 if (!CGM.getCodeGenOpts().NoInline) { 633 for (auto RI : FD->redecls()) 634 if (RI->isInlineSpecified()) { 635 Fn->addFnAttr(llvm::Attribute::InlineHint); 636 break; 637 } 638 } else if (!FD->hasAttr<AlwaysInlineAttr>()) 639 Fn->addFnAttr(llvm::Attribute::NoInline); 640 } 641 642 if (getLangOpts().OpenCL) { 643 // Add metadata for a kernel function. 644 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) 645 EmitOpenCLKernelMetadata(FD, Fn); 646 } 647 648 // If we are checking function types, emit a function type signature as 649 // prologue data. 650 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function)) { 651 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) { 652 if (llvm::Constant *PrologueSig = 653 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) { 654 llvm::Constant *FTRTTIConst = 655 CGM.GetAddrOfRTTIDescriptor(FD->getType(), /*ForEH=*/true); 656 llvm::Constant *PrologueStructElems[] = { PrologueSig, FTRTTIConst }; 657 llvm::Constant *PrologueStructConst = 658 llvm::ConstantStruct::getAnon(PrologueStructElems, /*Packed=*/true); 659 Fn->setPrologueData(PrologueStructConst); 660 } 661 } 662 } 663 664 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn); 665 666 // Create a marker to make it easy to insert allocas into the entryblock 667 // later. Don't create this with the builder, because we don't want it 668 // folded. 669 llvm::Value *Undef = llvm::UndefValue::get(Int32Ty); 670 AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB); 671 if (Builder.isNamePreserving()) 672 AllocaInsertPt->setName("allocapt"); 673 674 ReturnBlock = getJumpDestInCurrentScope("return"); 675 676 Builder.SetInsertPoint(EntryBB); 677 678 // Emit subprogram debug descriptor. 679 if (CGDebugInfo *DI = getDebugInfo()) { 680 SmallVector<QualType, 16> ArgTypes; 681 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 682 i != e; ++i) { 683 ArgTypes.push_back((*i)->getType()); 684 } 685 686 QualType FnType = 687 getContext().getFunctionType(RetTy, ArgTypes, 688 FunctionProtoType::ExtProtoInfo()); 689 DI->EmitFunctionStart(GD, Loc, StartLoc, FnType, CurFn, Builder); 690 } 691 692 if (ShouldInstrumentFunction()) 693 EmitFunctionInstrumentation("__cyg_profile_func_enter"); 694 695 if (CGM.getCodeGenOpts().InstrumentForProfiling) 696 EmitMCountInstrumentation(); 697 698 if (RetTy->isVoidType()) { 699 // Void type; nothing to return. 700 ReturnValue = nullptr; 701 702 // Count the implicit return. 703 if (!endsWithReturn(D)) 704 ++NumReturnExprs; 705 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect && 706 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) { 707 // Indirect aggregate return; emit returned value directly into sret slot. 708 // This reduces code size, and affects correctness in C++. 709 auto AI = CurFn->arg_begin(); 710 if (CurFnInfo->getReturnInfo().isSRetAfterThis()) 711 ++AI; 712 ReturnValue = AI; 713 } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca && 714 !hasScalarEvaluationKind(CurFnInfo->getReturnType())) { 715 // Load the sret pointer from the argument struct and return into that. 716 unsigned Idx = CurFnInfo->getReturnInfo().getInAllocaFieldIndex(); 717 llvm::Function::arg_iterator EI = CurFn->arg_end(); 718 --EI; 719 llvm::Value *Addr = Builder.CreateStructGEP(nullptr, EI, Idx); 720 ReturnValue = Builder.CreateLoad(Addr, "agg.result"); 721 } else { 722 ReturnValue = CreateIRTemp(RetTy, "retval"); 723 724 // Tell the epilog emitter to autorelease the result. We do this 725 // now so that various specialized functions can suppress it 726 // during their IR-generation. 727 if (getLangOpts().ObjCAutoRefCount && 728 !CurFnInfo->isReturnsRetained() && 729 RetTy->isObjCRetainableType()) 730 AutoreleaseResult = true; 731 } 732 733 EmitStartEHSpec(CurCodeDecl); 734 735 PrologueCleanupDepth = EHStack.stable_begin(); 736 EmitFunctionProlog(*CurFnInfo, CurFn, Args); 737 738 if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) { 739 CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 740 const CXXMethodDecl *MD = cast<CXXMethodDecl>(D); 741 if (MD->getParent()->isLambda() && 742 MD->getOverloadedOperator() == OO_Call) { 743 // We're in a lambda; figure out the captures. 744 MD->getParent()->getCaptureFields(LambdaCaptureFields, 745 LambdaThisCaptureField); 746 if (LambdaThisCaptureField) { 747 // If this lambda captures this, load it. 748 LValue ThisLValue = EmitLValueForLambdaField(LambdaThisCaptureField); 749 CXXThisValue = EmitLoadOfLValue(ThisLValue, 750 SourceLocation()).getScalarVal(); 751 } 752 for (auto *FD : MD->getParent()->fields()) { 753 if (FD->hasCapturedVLAType()) { 754 auto *ExprArg = EmitLoadOfLValue(EmitLValueForLambdaField(FD), 755 SourceLocation()).getScalarVal(); 756 auto VAT = FD->getCapturedVLAType(); 757 VLASizeMap[VAT->getSizeExpr()] = ExprArg; 758 } 759 } 760 } else { 761 // Not in a lambda; just use 'this' from the method. 762 // FIXME: Should we generate a new load for each use of 'this'? The 763 // fast register allocator would be happier... 764 CXXThisValue = CXXABIThisValue; 765 } 766 } 767 768 // If any of the arguments have a variably modified type, make sure to 769 // emit the type size. 770 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 771 i != e; ++i) { 772 const VarDecl *VD = *i; 773 774 // Dig out the type as written from ParmVarDecls; it's unclear whether 775 // the standard (C99 6.9.1p10) requires this, but we're following the 776 // precedent set by gcc. 777 QualType Ty; 778 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) 779 Ty = PVD->getOriginalType(); 780 else 781 Ty = VD->getType(); 782 783 if (Ty->isVariablyModifiedType()) 784 EmitVariablyModifiedType(Ty); 785 } 786 // Emit a location at the end of the prologue. 787 if (CGDebugInfo *DI = getDebugInfo()) 788 DI->EmitLocation(Builder, StartLoc); 789 } 790 791 void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args, 792 const Stmt *Body) { 793 incrementProfileCounter(Body); 794 if (const CompoundStmt *S = dyn_cast<CompoundStmt>(Body)) 795 EmitCompoundStmtWithoutScope(*S); 796 else 797 EmitStmt(Body); 798 } 799 800 /// When instrumenting to collect profile data, the counts for some blocks 801 /// such as switch cases need to not include the fall-through counts, so 802 /// emit a branch around the instrumentation code. When not instrumenting, 803 /// this just calls EmitBlock(). 804 void CodeGenFunction::EmitBlockWithFallThrough(llvm::BasicBlock *BB, 805 const Stmt *S) { 806 llvm::BasicBlock *SkipCountBB = nullptr; 807 if (HaveInsertPoint() && CGM.getCodeGenOpts().ProfileInstrGenerate) { 808 // When instrumenting for profiling, the fallthrough to certain 809 // statements needs to skip over the instrumentation code so that we 810 // get an accurate count. 811 SkipCountBB = createBasicBlock("skipcount"); 812 EmitBranch(SkipCountBB); 813 } 814 EmitBlock(BB); 815 uint64_t CurrentCount = getCurrentProfileCount(); 816 incrementProfileCounter(S); 817 setCurrentProfileCount(getCurrentProfileCount() + CurrentCount); 818 if (SkipCountBB) 819 EmitBlock(SkipCountBB); 820 } 821 822 /// Tries to mark the given function nounwind based on the 823 /// non-existence of any throwing calls within it. We believe this is 824 /// lightweight enough to do at -O0. 825 static void TryMarkNoThrow(llvm::Function *F) { 826 // LLVM treats 'nounwind' on a function as part of the type, so we 827 // can't do this on functions that can be overwritten. 828 if (F->mayBeOverridden()) return; 829 830 for (llvm::BasicBlock &BB : *F) 831 for (llvm::Instruction &I : BB) 832 if (I.mayThrow()) 833 return; 834 835 F->setDoesNotThrow(); 836 } 837 838 void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn, 839 const CGFunctionInfo &FnInfo) { 840 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 841 842 // Check if we should generate debug info for this function. 843 if (FD->hasAttr<NoDebugAttr>()) 844 DebugInfo = nullptr; // disable debug info indefinitely for this function 845 846 FunctionArgList Args; 847 QualType ResTy = FD->getReturnType(); 848 849 CurGD = GD; 850 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 851 if (MD && MD->isInstance()) { 852 if (CGM.getCXXABI().HasThisReturn(GD)) 853 ResTy = MD->getThisType(getContext()); 854 else if (CGM.getCXXABI().hasMostDerivedReturn(GD)) 855 ResTy = CGM.getContext().VoidPtrTy; 856 CGM.getCXXABI().buildThisParam(*this, Args); 857 } 858 859 Args.append(FD->param_begin(), FD->param_end()); 860 861 if (MD && (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))) 862 CGM.getCXXABI().addImplicitStructorParams(*this, ResTy, Args); 863 864 SourceRange BodyRange; 865 if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange(); 866 CurEHLocation = BodyRange.getEnd(); 867 868 // Use the location of the start of the function to determine where 869 // the function definition is located. By default use the location 870 // of the declaration as the location for the subprogram. A function 871 // may lack a declaration in the source code if it is created by code 872 // gen. (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk). 873 SourceLocation Loc = FD->getLocation(); 874 875 // If this is a function specialization then use the pattern body 876 // as the location for the function. 877 if (const FunctionDecl *SpecDecl = FD->getTemplateInstantiationPattern()) 878 if (SpecDecl->hasBody(SpecDecl)) 879 Loc = SpecDecl->getLocation(); 880 881 // Emit the standard function prologue. 882 StartFunction(GD, ResTy, Fn, FnInfo, Args, Loc, BodyRange.getBegin()); 883 884 // Generate the body of the function. 885 PGO.checkGlobalDecl(GD); 886 PGO.assignRegionCounters(GD.getDecl(), CurFn); 887 if (isa<CXXDestructorDecl>(FD)) 888 EmitDestructorBody(Args); 889 else if (isa<CXXConstructorDecl>(FD)) 890 EmitConstructorBody(Args); 891 else if (getLangOpts().CUDA && 892 !getLangOpts().CUDAIsDevice && 893 FD->hasAttr<CUDAGlobalAttr>()) 894 CGM.getCUDARuntime().emitDeviceStub(*this, Args); 895 else if (isa<CXXConversionDecl>(FD) && 896 cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) { 897 // The lambda conversion to block pointer is special; the semantics can't be 898 // expressed in the AST, so IRGen needs to special-case it. 899 EmitLambdaToBlockPointerBody(Args); 900 } else if (isa<CXXMethodDecl>(FD) && 901 cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) { 902 // The lambda static invoker function is special, because it forwards or 903 // clones the body of the function call operator (but is actually static). 904 EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD)); 905 } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) && 906 (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() || 907 cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) { 908 // Implicit copy-assignment gets the same special treatment as implicit 909 // copy-constructors. 910 emitImplicitAssignmentOperatorBody(Args); 911 } else if (Stmt *Body = FD->getBody()) { 912 EmitFunctionBody(Args, Body); 913 } else 914 llvm_unreachable("no definition for emitted function"); 915 916 // C++11 [stmt.return]p2: 917 // Flowing off the end of a function [...] results in undefined behavior in 918 // a value-returning function. 919 // C11 6.9.1p12: 920 // If the '}' that terminates a function is reached, and the value of the 921 // function call is used by the caller, the behavior is undefined. 922 if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() && !SawAsmBlock && 923 !FD->getReturnType()->isVoidType() && Builder.GetInsertBlock()) { 924 if (SanOpts.has(SanitizerKind::Return)) { 925 SanitizerScope SanScope(this); 926 llvm::Value *IsFalse = Builder.getFalse(); 927 EmitCheck(std::make_pair(IsFalse, SanitizerKind::Return), 928 "missing_return", EmitCheckSourceLocation(FD->getLocation()), 929 None); 930 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) { 931 EmitTrapCall(llvm::Intrinsic::trap); 932 } 933 Builder.CreateUnreachable(); 934 Builder.ClearInsertionPoint(); 935 } 936 937 // Emit the standard function epilogue. 938 FinishFunction(BodyRange.getEnd()); 939 940 // If we haven't marked the function nothrow through other means, do 941 // a quick pass now to see if we can. 942 if (!CurFn->doesNotThrow()) 943 TryMarkNoThrow(CurFn); 944 } 945 946 /// ContainsLabel - Return true if the statement contains a label in it. If 947 /// this statement is not executed normally, it not containing a label means 948 /// that we can just remove the code. 949 bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) { 950 // Null statement, not a label! 951 if (!S) return false; 952 953 // If this is a label, we have to emit the code, consider something like: 954 // if (0) { ... foo: bar(); } goto foo; 955 // 956 // TODO: If anyone cared, we could track __label__'s, since we know that you 957 // can't jump to one from outside their declared region. 958 if (isa<LabelStmt>(S)) 959 return true; 960 961 // If this is a case/default statement, and we haven't seen a switch, we have 962 // to emit the code. 963 if (isa<SwitchCase>(S) && !IgnoreCaseStmts) 964 return true; 965 966 // If this is a switch statement, we want to ignore cases below it. 967 if (isa<SwitchStmt>(S)) 968 IgnoreCaseStmts = true; 969 970 // Scan subexpressions for verboten labels. 971 for (const Stmt *SubStmt : S->children()) 972 if (ContainsLabel(SubStmt, IgnoreCaseStmts)) 973 return true; 974 975 return false; 976 } 977 978 /// containsBreak - Return true if the statement contains a break out of it. 979 /// If the statement (recursively) contains a switch or loop with a break 980 /// inside of it, this is fine. 981 bool CodeGenFunction::containsBreak(const Stmt *S) { 982 // Null statement, not a label! 983 if (!S) return false; 984 985 // If this is a switch or loop that defines its own break scope, then we can 986 // include it and anything inside of it. 987 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) || 988 isa<ForStmt>(S)) 989 return false; 990 991 if (isa<BreakStmt>(S)) 992 return true; 993 994 // Scan subexpressions for verboten breaks. 995 for (const Stmt *SubStmt : S->children()) 996 if (containsBreak(SubStmt)) 997 return true; 998 999 return false; 1000 } 1001 1002 1003 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 1004 /// to a constant, or if it does but contains a label, return false. If it 1005 /// constant folds return true and set the boolean result in Result. 1006 bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond, 1007 bool &ResultBool) { 1008 llvm::APSInt ResultInt; 1009 if (!ConstantFoldsToSimpleInteger(Cond, ResultInt)) 1010 return false; 1011 1012 ResultBool = ResultInt.getBoolValue(); 1013 return true; 1014 } 1015 1016 /// ConstantFoldsToSimpleInteger - If the specified expression does not fold 1017 /// to a constant, or if it does but contains a label, return false. If it 1018 /// constant folds return true and set the folded value. 1019 bool CodeGenFunction:: 1020 ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &ResultInt) { 1021 // FIXME: Rename and handle conversion of other evaluatable things 1022 // to bool. 1023 llvm::APSInt Int; 1024 if (!Cond->EvaluateAsInt(Int, getContext())) 1025 return false; // Not foldable, not integer or not fully evaluatable. 1026 1027 if (CodeGenFunction::ContainsLabel(Cond)) 1028 return false; // Contains a label. 1029 1030 ResultInt = Int; 1031 return true; 1032 } 1033 1034 1035 1036 /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if 1037 /// statement) to the specified blocks. Based on the condition, this might try 1038 /// to simplify the codegen of the conditional based on the branch. 1039 /// 1040 void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond, 1041 llvm::BasicBlock *TrueBlock, 1042 llvm::BasicBlock *FalseBlock, 1043 uint64_t TrueCount) { 1044 Cond = Cond->IgnoreParens(); 1045 1046 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) { 1047 1048 // Handle X && Y in a condition. 1049 if (CondBOp->getOpcode() == BO_LAnd) { 1050 // If we have "1 && X", simplify the code. "0 && X" would have constant 1051 // folded if the case was simple enough. 1052 bool ConstantBool = false; 1053 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 1054 ConstantBool) { 1055 // br(1 && X) -> br(X). 1056 incrementProfileCounter(CondBOp); 1057 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, 1058 TrueCount); 1059 } 1060 1061 // If we have "X && 1", simplify the code to use an uncond branch. 1062 // "X && 0" would have been constant folded to 0. 1063 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 1064 ConstantBool) { 1065 // br(X && 1) -> br(X). 1066 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock, 1067 TrueCount); 1068 } 1069 1070 // Emit the LHS as a conditional. If the LHS conditional is false, we 1071 // want to jump to the FalseBlock. 1072 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true"); 1073 // The counter tells us how often we evaluate RHS, and all of TrueCount 1074 // can be propagated to that branch. 1075 uint64_t RHSCount = getProfileCount(CondBOp->getRHS()); 1076 1077 ConditionalEvaluation eval(*this); 1078 { 1079 ApplyDebugLocation DL(*this, Cond); 1080 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock, RHSCount); 1081 EmitBlock(LHSTrue); 1082 } 1083 1084 incrementProfileCounter(CondBOp); 1085 setCurrentProfileCount(getProfileCount(CondBOp->getRHS())); 1086 1087 // Any temporaries created here are conditional. 1088 eval.begin(*this); 1089 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, TrueCount); 1090 eval.end(*this); 1091 1092 return; 1093 } 1094 1095 if (CondBOp->getOpcode() == BO_LOr) { 1096 // If we have "0 || X", simplify the code. "1 || X" would have constant 1097 // folded if the case was simple enough. 1098 bool ConstantBool = false; 1099 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) && 1100 !ConstantBool) { 1101 // br(0 || X) -> br(X). 1102 incrementProfileCounter(CondBOp); 1103 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, 1104 TrueCount); 1105 } 1106 1107 // If we have "X || 0", simplify the code to use an uncond branch. 1108 // "X || 1" would have been constant folded to 1. 1109 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) && 1110 !ConstantBool) { 1111 // br(X || 0) -> br(X). 1112 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock, 1113 TrueCount); 1114 } 1115 1116 // Emit the LHS as a conditional. If the LHS conditional is true, we 1117 // want to jump to the TrueBlock. 1118 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false"); 1119 // We have the count for entry to the RHS and for the whole expression 1120 // being true, so we can divy up True count between the short circuit and 1121 // the RHS. 1122 uint64_t LHSCount = 1123 getCurrentProfileCount() - getProfileCount(CondBOp->getRHS()); 1124 uint64_t RHSCount = TrueCount - LHSCount; 1125 1126 ConditionalEvaluation eval(*this); 1127 { 1128 ApplyDebugLocation DL(*this, Cond); 1129 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse, LHSCount); 1130 EmitBlock(LHSFalse); 1131 } 1132 1133 incrementProfileCounter(CondBOp); 1134 setCurrentProfileCount(getProfileCount(CondBOp->getRHS())); 1135 1136 // Any temporaries created here are conditional. 1137 eval.begin(*this); 1138 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock, RHSCount); 1139 1140 eval.end(*this); 1141 1142 return; 1143 } 1144 } 1145 1146 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) { 1147 // br(!x, t, f) -> br(x, f, t) 1148 if (CondUOp->getOpcode() == UO_LNot) { 1149 // Negate the count. 1150 uint64_t FalseCount = getCurrentProfileCount() - TrueCount; 1151 // Negate the condition and swap the destination blocks. 1152 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock, 1153 FalseCount); 1154 } 1155 } 1156 1157 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) { 1158 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f)) 1159 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true"); 1160 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false"); 1161 1162 ConditionalEvaluation cond(*this); 1163 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock, 1164 getProfileCount(CondOp)); 1165 1166 // When computing PGO branch weights, we only know the overall count for 1167 // the true block. This code is essentially doing tail duplication of the 1168 // naive code-gen, introducing new edges for which counts are not 1169 // available. Divide the counts proportionally between the LHS and RHS of 1170 // the conditional operator. 1171 uint64_t LHSScaledTrueCount = 0; 1172 if (TrueCount) { 1173 double LHSRatio = 1174 getProfileCount(CondOp) / (double)getCurrentProfileCount(); 1175 LHSScaledTrueCount = TrueCount * LHSRatio; 1176 } 1177 1178 cond.begin(*this); 1179 EmitBlock(LHSBlock); 1180 incrementProfileCounter(CondOp); 1181 { 1182 ApplyDebugLocation DL(*this, Cond); 1183 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock, 1184 LHSScaledTrueCount); 1185 } 1186 cond.end(*this); 1187 1188 cond.begin(*this); 1189 EmitBlock(RHSBlock); 1190 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock, 1191 TrueCount - LHSScaledTrueCount); 1192 cond.end(*this); 1193 1194 return; 1195 } 1196 1197 if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) { 1198 // Conditional operator handling can give us a throw expression as a 1199 // condition for a case like: 1200 // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f) 1201 // Fold this to: 1202 // br(c, throw x, br(y, t, f)) 1203 EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false); 1204 return; 1205 } 1206 1207 // If the branch has a condition wrapped by __builtin_unpredictable, 1208 // create metadata that specifies that the branch is unpredictable. 1209 // Don't bother if not optimizing because that metadata would not be used. 1210 llvm::MDNode *Unpredictable = nullptr; 1211 if (CGM.getCodeGenOpts().OptimizationLevel != 0) { 1212 if (const CallExpr *Call = dyn_cast<CallExpr>(Cond)) { 1213 const Decl *TargetDecl = Call->getCalleeDecl(); 1214 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) { 1215 if (FD->getBuiltinID() == Builtin::BI__builtin_unpredictable) { 1216 llvm::MDBuilder MDHelper(getLLVMContext()); 1217 Unpredictable = MDHelper.createUnpredictable(); 1218 } 1219 } 1220 } 1221 } 1222 1223 // Create branch weights based on the number of times we get here and the 1224 // number of times the condition should be true. 1225 uint64_t CurrentCount = std::max(getCurrentProfileCount(), TrueCount); 1226 llvm::MDNode *Weights = 1227 createProfileWeights(TrueCount, CurrentCount - TrueCount); 1228 1229 // Emit the code with the fully general case. 1230 llvm::Value *CondV; 1231 { 1232 ApplyDebugLocation DL(*this, Cond); 1233 CondV = EvaluateExprAsBool(Cond); 1234 } 1235 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock, Weights, Unpredictable); 1236 } 1237 1238 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1239 /// specified stmt yet. 1240 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) { 1241 CGM.ErrorUnsupported(S, Type); 1242 } 1243 1244 /// emitNonZeroVLAInit - Emit the "zero" initialization of a 1245 /// variable-length array whose elements have a non-zero bit-pattern. 1246 /// 1247 /// \param baseType the inner-most element type of the array 1248 /// \param src - a char* pointing to the bit-pattern for a single 1249 /// base element of the array 1250 /// \param sizeInChars - the total size of the VLA, in chars 1251 static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType, 1252 llvm::Value *dest, llvm::Value *src, 1253 llvm::Value *sizeInChars) { 1254 std::pair<CharUnits,CharUnits> baseSizeAndAlign 1255 = CGF.getContext().getTypeInfoInChars(baseType); 1256 1257 CGBuilderTy &Builder = CGF.Builder; 1258 1259 llvm::Value *baseSizeInChars 1260 = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity()); 1261 1262 llvm::Type *i8p = Builder.getInt8PtrTy(); 1263 1264 llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin"); 1265 llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end"); 1266 1267 llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock(); 1268 llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop"); 1269 llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont"); 1270 1271 // Make a loop over the VLA. C99 guarantees that the VLA element 1272 // count must be nonzero. 1273 CGF.EmitBlock(loopBB); 1274 1275 llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur"); 1276 cur->addIncoming(begin, originBB); 1277 1278 // memcpy the individual element bit-pattern. 1279 Builder.CreateMemCpy(cur, src, baseSizeInChars, 1280 baseSizeAndAlign.second.getQuantity(), 1281 /*volatile*/ false); 1282 1283 // Go to the next element. 1284 llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), 1285 cur, 1, "vla.next"); 1286 1287 // Leave if that's the end of the VLA. 1288 llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone"); 1289 Builder.CreateCondBr(done, contBB, loopBB); 1290 cur->addIncoming(next, loopBB); 1291 1292 CGF.EmitBlock(contBB); 1293 } 1294 1295 void 1296 CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) { 1297 // Ignore empty classes in C++. 1298 if (getLangOpts().CPlusPlus) { 1299 if (const RecordType *RT = Ty->getAs<RecordType>()) { 1300 if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty()) 1301 return; 1302 } 1303 } 1304 1305 // Cast the dest ptr to the appropriate i8 pointer type. 1306 unsigned DestAS = 1307 cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace(); 1308 llvm::Type *BP = Builder.getInt8PtrTy(DestAS); 1309 if (DestPtr->getType() != BP) 1310 DestPtr = Builder.CreateBitCast(DestPtr, BP); 1311 1312 // Get size and alignment info for this aggregate. 1313 std::pair<CharUnits, CharUnits> TypeInfo = 1314 getContext().getTypeInfoInChars(Ty); 1315 CharUnits Size = TypeInfo.first; 1316 CharUnits Align = TypeInfo.second; 1317 1318 llvm::Value *SizeVal; 1319 const VariableArrayType *vla; 1320 1321 // Don't bother emitting a zero-byte memset. 1322 if (Size.isZero()) { 1323 // But note that getTypeInfo returns 0 for a VLA. 1324 if (const VariableArrayType *vlaType = 1325 dyn_cast_or_null<VariableArrayType>( 1326 getContext().getAsArrayType(Ty))) { 1327 QualType eltType; 1328 llvm::Value *numElts; 1329 std::tie(numElts, eltType) = getVLASize(vlaType); 1330 1331 SizeVal = numElts; 1332 CharUnits eltSize = getContext().getTypeSizeInChars(eltType); 1333 if (!eltSize.isOne()) 1334 SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize)); 1335 vla = vlaType; 1336 } else { 1337 return; 1338 } 1339 } else { 1340 SizeVal = CGM.getSize(Size); 1341 vla = nullptr; 1342 } 1343 1344 // If the type contains a pointer to data member we can't memset it to zero. 1345 // Instead, create a null constant and copy it to the destination. 1346 // TODO: there are other patterns besides zero that we can usefully memset, 1347 // like -1, which happens to be the pattern used by member-pointers. 1348 if (!CGM.getTypes().isZeroInitializable(Ty)) { 1349 // For a VLA, emit a single element, then splat that over the VLA. 1350 if (vla) Ty = getContext().getBaseElementType(vla); 1351 1352 llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty); 1353 1354 llvm::GlobalVariable *NullVariable = 1355 new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(), 1356 /*isConstant=*/true, 1357 llvm::GlobalVariable::PrivateLinkage, 1358 NullConstant, Twine()); 1359 llvm::Value *SrcPtr = 1360 Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy()); 1361 1362 if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal); 1363 1364 // Get and call the appropriate llvm.memcpy overload. 1365 Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false); 1366 return; 1367 } 1368 1369 // Otherwise, just memset the whole thing to zero. This is legal 1370 // because in LLVM, all default initializers (other than the ones we just 1371 // handled above) are guaranteed to have a bit pattern of all zeros. 1372 Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal, 1373 Align.getQuantity(), false); 1374 } 1375 1376 llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) { 1377 // Make sure that there is a block for the indirect goto. 1378 if (!IndirectBranch) 1379 GetIndirectGotoBlock(); 1380 1381 llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock(); 1382 1383 // Make sure the indirect branch includes all of the address-taken blocks. 1384 IndirectBranch->addDestination(BB); 1385 return llvm::BlockAddress::get(CurFn, BB); 1386 } 1387 1388 llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() { 1389 // If we already made the indirect branch for indirect goto, return its block. 1390 if (IndirectBranch) return IndirectBranch->getParent(); 1391 1392 CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto")); 1393 1394 // Create the PHI node that indirect gotos will add entries to. 1395 llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0, 1396 "indirect.goto.dest"); 1397 1398 // Create the indirect branch instruction. 1399 IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal); 1400 return IndirectBranch->getParent(); 1401 } 1402 1403 /// Computes the length of an array in elements, as well as the base 1404 /// element type and a properly-typed first element pointer. 1405 llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType, 1406 QualType &baseType, 1407 llvm::Value *&addr) { 1408 const ArrayType *arrayType = origArrayType; 1409 1410 // If it's a VLA, we have to load the stored size. Note that 1411 // this is the size of the VLA in bytes, not its size in elements. 1412 llvm::Value *numVLAElements = nullptr; 1413 if (isa<VariableArrayType>(arrayType)) { 1414 numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first; 1415 1416 // Walk into all VLAs. This doesn't require changes to addr, 1417 // which has type T* where T is the first non-VLA element type. 1418 do { 1419 QualType elementType = arrayType->getElementType(); 1420 arrayType = getContext().getAsArrayType(elementType); 1421 1422 // If we only have VLA components, 'addr' requires no adjustment. 1423 if (!arrayType) { 1424 baseType = elementType; 1425 return numVLAElements; 1426 } 1427 } while (isa<VariableArrayType>(arrayType)); 1428 1429 // We get out here only if we find a constant array type 1430 // inside the VLA. 1431 } 1432 1433 // We have some number of constant-length arrays, so addr should 1434 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks 1435 // down to the first element of addr. 1436 SmallVector<llvm::Value*, 8> gepIndices; 1437 1438 // GEP down to the array type. 1439 llvm::ConstantInt *zero = Builder.getInt32(0); 1440 gepIndices.push_back(zero); 1441 1442 uint64_t countFromCLAs = 1; 1443 QualType eltType; 1444 1445 llvm::ArrayType *llvmArrayType = 1446 dyn_cast<llvm::ArrayType>( 1447 cast<llvm::PointerType>(addr->getType())->getElementType()); 1448 while (llvmArrayType) { 1449 assert(isa<ConstantArrayType>(arrayType)); 1450 assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue() 1451 == llvmArrayType->getNumElements()); 1452 1453 gepIndices.push_back(zero); 1454 countFromCLAs *= llvmArrayType->getNumElements(); 1455 eltType = arrayType->getElementType(); 1456 1457 llvmArrayType = 1458 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType()); 1459 arrayType = getContext().getAsArrayType(arrayType->getElementType()); 1460 assert((!llvmArrayType || arrayType) && 1461 "LLVM and Clang types are out-of-synch"); 1462 } 1463 1464 if (arrayType) { 1465 // From this point onwards, the Clang array type has been emitted 1466 // as some other type (probably a packed struct). Compute the array 1467 // size, and just emit the 'begin' expression as a bitcast. 1468 while (arrayType) { 1469 countFromCLAs *= 1470 cast<ConstantArrayType>(arrayType)->getSize().getZExtValue(); 1471 eltType = arrayType->getElementType(); 1472 arrayType = getContext().getAsArrayType(eltType); 1473 } 1474 1475 unsigned AddressSpace = addr->getType()->getPointerAddressSpace(); 1476 llvm::Type *BaseType = ConvertType(eltType)->getPointerTo(AddressSpace); 1477 addr = Builder.CreateBitCast(addr, BaseType, "array.begin"); 1478 } else { 1479 // Create the actual GEP. 1480 addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin"); 1481 } 1482 1483 baseType = eltType; 1484 1485 llvm::Value *numElements 1486 = llvm::ConstantInt::get(SizeTy, countFromCLAs); 1487 1488 // If we had any VLA dimensions, factor them in. 1489 if (numVLAElements) 1490 numElements = Builder.CreateNUWMul(numVLAElements, numElements); 1491 1492 return numElements; 1493 } 1494 1495 std::pair<llvm::Value*, QualType> 1496 CodeGenFunction::getVLASize(QualType type) { 1497 const VariableArrayType *vla = getContext().getAsVariableArrayType(type); 1498 assert(vla && "type was not a variable array type!"); 1499 return getVLASize(vla); 1500 } 1501 1502 std::pair<llvm::Value*, QualType> 1503 CodeGenFunction::getVLASize(const VariableArrayType *type) { 1504 // The number of elements so far; always size_t. 1505 llvm::Value *numElements = nullptr; 1506 1507 QualType elementType; 1508 do { 1509 elementType = type->getElementType(); 1510 llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()]; 1511 assert(vlaSize && "no size for VLA!"); 1512 assert(vlaSize->getType() == SizeTy); 1513 1514 if (!numElements) { 1515 numElements = vlaSize; 1516 } else { 1517 // It's undefined behavior if this wraps around, so mark it that way. 1518 // FIXME: Teach -fsanitize=undefined to trap this. 1519 numElements = Builder.CreateNUWMul(numElements, vlaSize); 1520 } 1521 } while ((type = getContext().getAsVariableArrayType(elementType))); 1522 1523 return std::pair<llvm::Value*,QualType>(numElements, elementType); 1524 } 1525 1526 void CodeGenFunction::EmitVariablyModifiedType(QualType type) { 1527 assert(type->isVariablyModifiedType() && 1528 "Must pass variably modified type to EmitVLASizes!"); 1529 1530 EnsureInsertPoint(); 1531 1532 // We're going to walk down into the type and look for VLA 1533 // expressions. 1534 do { 1535 assert(type->isVariablyModifiedType()); 1536 1537 const Type *ty = type.getTypePtr(); 1538 switch (ty->getTypeClass()) { 1539 1540 #define TYPE(Class, Base) 1541 #define ABSTRACT_TYPE(Class, Base) 1542 #define NON_CANONICAL_TYPE(Class, Base) 1543 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 1544 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) 1545 #include "clang/AST/TypeNodes.def" 1546 llvm_unreachable("unexpected dependent type!"); 1547 1548 // These types are never variably-modified. 1549 case Type::Builtin: 1550 case Type::Complex: 1551 case Type::Vector: 1552 case Type::ExtVector: 1553 case Type::Record: 1554 case Type::Enum: 1555 case Type::Elaborated: 1556 case Type::TemplateSpecialization: 1557 case Type::ObjCObject: 1558 case Type::ObjCInterface: 1559 case Type::ObjCObjectPointer: 1560 llvm_unreachable("type class is never variably-modified!"); 1561 1562 case Type::Adjusted: 1563 type = cast<AdjustedType>(ty)->getAdjustedType(); 1564 break; 1565 1566 case Type::Decayed: 1567 type = cast<DecayedType>(ty)->getPointeeType(); 1568 break; 1569 1570 case Type::Pointer: 1571 type = cast<PointerType>(ty)->getPointeeType(); 1572 break; 1573 1574 case Type::BlockPointer: 1575 type = cast<BlockPointerType>(ty)->getPointeeType(); 1576 break; 1577 1578 case Type::LValueReference: 1579 case Type::RValueReference: 1580 type = cast<ReferenceType>(ty)->getPointeeType(); 1581 break; 1582 1583 case Type::MemberPointer: 1584 type = cast<MemberPointerType>(ty)->getPointeeType(); 1585 break; 1586 1587 case Type::ConstantArray: 1588 case Type::IncompleteArray: 1589 // Losing element qualification here is fine. 1590 type = cast<ArrayType>(ty)->getElementType(); 1591 break; 1592 1593 case Type::VariableArray: { 1594 // Losing element qualification here is fine. 1595 const VariableArrayType *vat = cast<VariableArrayType>(ty); 1596 1597 // Unknown size indication requires no size computation. 1598 // Otherwise, evaluate and record it. 1599 if (const Expr *size = vat->getSizeExpr()) { 1600 // It's possible that we might have emitted this already, 1601 // e.g. with a typedef and a pointer to it. 1602 llvm::Value *&entry = VLASizeMap[size]; 1603 if (!entry) { 1604 llvm::Value *Size = EmitScalarExpr(size); 1605 1606 // C11 6.7.6.2p5: 1607 // If the size is an expression that is not an integer constant 1608 // expression [...] each time it is evaluated it shall have a value 1609 // greater than zero. 1610 if (SanOpts.has(SanitizerKind::VLABound) && 1611 size->getType()->isSignedIntegerType()) { 1612 SanitizerScope SanScope(this); 1613 llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType()); 1614 llvm::Constant *StaticArgs[] = { 1615 EmitCheckSourceLocation(size->getLocStart()), 1616 EmitCheckTypeDescriptor(size->getType()) 1617 }; 1618 EmitCheck(std::make_pair(Builder.CreateICmpSGT(Size, Zero), 1619 SanitizerKind::VLABound), 1620 "vla_bound_not_positive", StaticArgs, Size); 1621 } 1622 1623 // Always zexting here would be wrong if it weren't 1624 // undefined behavior to have a negative bound. 1625 entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false); 1626 } 1627 } 1628 type = vat->getElementType(); 1629 break; 1630 } 1631 1632 case Type::FunctionProto: 1633 case Type::FunctionNoProto: 1634 type = cast<FunctionType>(ty)->getReturnType(); 1635 break; 1636 1637 case Type::Paren: 1638 case Type::TypeOf: 1639 case Type::UnaryTransform: 1640 case Type::Attributed: 1641 case Type::SubstTemplateTypeParm: 1642 case Type::PackExpansion: 1643 // Keep walking after single level desugaring. 1644 type = type.getSingleStepDesugaredType(getContext()); 1645 break; 1646 1647 case Type::Typedef: 1648 case Type::Decltype: 1649 case Type::Auto: 1650 // Stop walking: nothing to do. 1651 return; 1652 1653 case Type::TypeOfExpr: 1654 // Stop walking: emit typeof expression. 1655 EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr()); 1656 return; 1657 1658 case Type::Atomic: 1659 type = cast<AtomicType>(ty)->getValueType(); 1660 break; 1661 } 1662 } while (type->isVariablyModifiedType()); 1663 } 1664 1665 llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) { 1666 if (getContext().getBuiltinVaListType()->isArrayType()) 1667 return EmitScalarExpr(E); 1668 return EmitLValue(E).getAddress(); 1669 } 1670 1671 void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E, 1672 llvm::Constant *Init) { 1673 assert (Init && "Invalid DeclRefExpr initializer!"); 1674 if (CGDebugInfo *Dbg = getDebugInfo()) 1675 if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) 1676 Dbg->EmitGlobalVariable(E->getDecl(), Init); 1677 } 1678 1679 CodeGenFunction::PeepholeProtection 1680 CodeGenFunction::protectFromPeepholes(RValue rvalue) { 1681 // At the moment, the only aggressive peephole we do in IR gen 1682 // is trunc(zext) folding, but if we add more, we can easily 1683 // extend this protection. 1684 1685 if (!rvalue.isScalar()) return PeepholeProtection(); 1686 llvm::Value *value = rvalue.getScalarVal(); 1687 if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection(); 1688 1689 // Just make an extra bitcast. 1690 assert(HaveInsertPoint()); 1691 llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "", 1692 Builder.GetInsertBlock()); 1693 1694 PeepholeProtection protection; 1695 protection.Inst = inst; 1696 return protection; 1697 } 1698 1699 void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) { 1700 if (!protection.Inst) return; 1701 1702 // In theory, we could try to duplicate the peepholes now, but whatever. 1703 protection.Inst->eraseFromParent(); 1704 } 1705 1706 llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn, 1707 llvm::Value *AnnotatedVal, 1708 StringRef AnnotationStr, 1709 SourceLocation Location) { 1710 llvm::Value *Args[4] = { 1711 AnnotatedVal, 1712 Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy), 1713 Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy), 1714 CGM.EmitAnnotationLineNo(Location) 1715 }; 1716 return Builder.CreateCall(AnnotationFn, Args); 1717 } 1718 1719 void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) { 1720 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1721 // FIXME We create a new bitcast for every annotation because that's what 1722 // llvm-gcc was doing. 1723 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 1724 EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation), 1725 Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()), 1726 I->getAnnotation(), D->getLocation()); 1727 } 1728 1729 llvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D, 1730 llvm::Value *V) { 1731 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 1732 llvm::Type *VTy = V->getType(); 1733 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation, 1734 CGM.Int8PtrTy); 1735 1736 for (const auto *I : D->specific_attrs<AnnotateAttr>()) { 1737 // FIXME Always emit the cast inst so we can differentiate between 1738 // annotation on the first field of a struct and annotation on the struct 1739 // itself. 1740 if (VTy != CGM.Int8PtrTy) 1741 V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy)); 1742 V = EmitAnnotationCall(F, V, I->getAnnotation(), D->getLocation()); 1743 V = Builder.CreateBitCast(V, VTy); 1744 } 1745 1746 return V; 1747 } 1748 1749 CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { } 1750 1751 CodeGenFunction::SanitizerScope::SanitizerScope(CodeGenFunction *CGF) 1752 : CGF(CGF) { 1753 assert(!CGF->IsSanitizerScope); 1754 CGF->IsSanitizerScope = true; 1755 } 1756 1757 CodeGenFunction::SanitizerScope::~SanitizerScope() { 1758 CGF->IsSanitizerScope = false; 1759 } 1760 1761 void CodeGenFunction::InsertHelper(llvm::Instruction *I, 1762 const llvm::Twine &Name, 1763 llvm::BasicBlock *BB, 1764 llvm::BasicBlock::iterator InsertPt) const { 1765 LoopStack.InsertHelper(I); 1766 if (IsSanitizerScope) 1767 CGM.getSanitizerMetadata()->disableSanitizerForInstruction(I); 1768 } 1769 1770 template <bool PreserveNames> 1771 void CGBuilderInserter<PreserveNames>::InsertHelper( 1772 llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, 1773 llvm::BasicBlock::iterator InsertPt) const { 1774 llvm::IRBuilderDefaultInserter<PreserveNames>::InsertHelper(I, Name, BB, 1775 InsertPt); 1776 if (CGF) 1777 CGF->InsertHelper(I, Name, BB, InsertPt); 1778 } 1779 1780 #ifdef NDEBUG 1781 #define PreserveNames false 1782 #else 1783 #define PreserveNames true 1784 #endif 1785 template void CGBuilderInserter<PreserveNames>::InsertHelper( 1786 llvm::Instruction *I, const llvm::Twine &Name, llvm::BasicBlock *BB, 1787 llvm::BasicBlock::iterator InsertPt) const; 1788 #undef PreserveNames 1789