CodeGenFunction.cpp 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462
  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. #include "CodeGenFunction.h"
  14. #include "CGCUDARuntime.h"
  15. #include "CGCXXABI.h"
  16. #include "CGDebugInfo.h"
  17. #include "CodeGenModule.h"
  18. #include "clang/AST/ASTContext.h"
  19. #include "clang/AST/Decl.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/StmtCXX.h"
  22. #include "clang/Basic/OpenCL.h"
  23. #include "clang/Basic/TargetInfo.h"
  24. #include "clang/Frontend/CodeGenOptions.h"
  25. #include "llvm/IR/DataLayout.h"
  26. #include "llvm/IR/Intrinsics.h"
  27. #include "llvm/IR/MDBuilder.h"
  28. #include "llvm/IR/Operator.h"
  29. using namespace clang;
  30. using namespace CodeGen;
  31. CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
  32. : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
  33. Builder(cgm.getModule().getContext()), CapturedStmtInfo(0),
  34. SanitizePerformTypeCheck(CGM.getSanOpts().Null |
  35. CGM.getSanOpts().Alignment |
  36. CGM.getSanOpts().ObjectSize |
  37. CGM.getSanOpts().Vptr),
  38. SanOpts(&CGM.getSanOpts()), AutoreleaseResult(false), BlockInfo(0),
  39. BlockPointer(0), LambdaThisCaptureField(0), NormalCleanupDest(0),
  40. NextCleanupDestIndex(1), FirstBlockInfo(0), EHResumeBlock(0),
  41. ExceptionSlot(0), EHSelectorSlot(0), DebugInfo(CGM.getModuleDebugInfo()),
  42. DisableDebugInfo(false), DidCallStackSave(false), IndirectBranch(0),
  43. SwitchInsn(0), CaseRangeBlock(0), UnreachableBlock(0), NumReturnExprs(0),
  44. NumSimpleReturnExprs(0), CXXABIThisDecl(0), CXXABIThisValue(0),
  45. CXXThisValue(0), CXXDefaultInitExprThis(0),
  46. CXXStructorImplicitParamDecl(0), CXXStructorImplicitParamValue(0),
  47. OutermostConditional(0), CurLexicalScope(0), TerminateLandingPad(0),
  48. TerminateHandler(0), TrapBB(0) {
  49. if (!suppressNewContext)
  50. CGM.getCXXABI().getMangleContext().startNewFunction();
  51. llvm::FastMathFlags FMF;
  52. if (CGM.getLangOpts().FastMath)
  53. FMF.setUnsafeAlgebra();
  54. if (CGM.getLangOpts().FiniteMathOnly) {
  55. FMF.setNoNaNs();
  56. FMF.setNoInfs();
  57. }
  58. Builder.SetFastMathFlags(FMF);
  59. }
  60. CodeGenFunction::~CodeGenFunction() {
  61. assert(LifetimeExtendedCleanupStack.empty() && "failed to emit a cleanup");
  62. // If there are any unclaimed block infos, go ahead and destroy them
  63. // now. This can happen if IR-gen gets clever and skips evaluating
  64. // something.
  65. if (FirstBlockInfo)
  66. destroyBlockInfos(FirstBlockInfo);
  67. }
  68. llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
  69. return CGM.getTypes().ConvertTypeForMem(T);
  70. }
  71. llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  72. return CGM.getTypes().ConvertType(T);
  73. }
  74. TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
  75. type = type.getCanonicalType();
  76. while (true) {
  77. switch (type->getTypeClass()) {
  78. #define TYPE(name, parent)
  79. #define ABSTRACT_TYPE(name, parent)
  80. #define NON_CANONICAL_TYPE(name, parent) case Type::name:
  81. #define DEPENDENT_TYPE(name, parent) case Type::name:
  82. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(name, parent) case Type::name:
  83. #include "clang/AST/TypeNodes.def"
  84. llvm_unreachable("non-canonical or dependent type in IR-generation");
  85. case Type::Auto:
  86. llvm_unreachable("undeduced auto type in IR-generation");
  87. // Various scalar types.
  88. case Type::Builtin:
  89. case Type::Pointer:
  90. case Type::BlockPointer:
  91. case Type::LValueReference:
  92. case Type::RValueReference:
  93. case Type::MemberPointer:
  94. case Type::Vector:
  95. case Type::ExtVector:
  96. case Type::FunctionProto:
  97. case Type::FunctionNoProto:
  98. case Type::Enum:
  99. case Type::ObjCObjectPointer:
  100. return TEK_Scalar;
  101. // Complexes.
  102. case Type::Complex:
  103. return TEK_Complex;
  104. // Arrays, records, and Objective-C objects.
  105. case Type::ConstantArray:
  106. case Type::IncompleteArray:
  107. case Type::VariableArray:
  108. case Type::Record:
  109. case Type::ObjCObject:
  110. case Type::ObjCInterface:
  111. return TEK_Aggregate;
  112. // We operate on atomic values according to their underlying type.
  113. case Type::Atomic:
  114. type = cast<AtomicType>(type)->getValueType();
  115. continue;
  116. }
  117. llvm_unreachable("unknown type kind!");
  118. }
  119. }
  120. void CodeGenFunction::EmitReturnBlock() {
  121. // For cleanliness, we try to avoid emitting the return block for
  122. // simple cases.
  123. llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
  124. if (CurBB) {
  125. assert(!CurBB->getTerminator() && "Unexpected terminated block.");
  126. // We have a valid insert point, reuse it if it is empty or there are no
  127. // explicit jumps to the return block.
  128. if (CurBB->empty() || ReturnBlock.getBlock()->use_empty()) {
  129. ReturnBlock.getBlock()->replaceAllUsesWith(CurBB);
  130. delete ReturnBlock.getBlock();
  131. } else
  132. EmitBlock(ReturnBlock.getBlock());
  133. return;
  134. }
  135. // Otherwise, if the return block is the target of a single direct
  136. // branch then we can just put the code in that block instead. This
  137. // cleans up functions which started with a unified return block.
  138. if (ReturnBlock.getBlock()->hasOneUse()) {
  139. llvm::BranchInst *BI =
  140. dyn_cast<llvm::BranchInst>(*ReturnBlock.getBlock()->use_begin());
  141. if (BI && BI->isUnconditional() &&
  142. BI->getSuccessor(0) == ReturnBlock.getBlock()) {
  143. // Reset insertion point, including debug location, and delete the
  144. // branch. This is really subtle and only works because the next change
  145. // in location will hit the caching in CGDebugInfo::EmitLocation and not
  146. // override this.
  147. Builder.SetCurrentDebugLocation(BI->getDebugLoc());
  148. Builder.SetInsertPoint(BI->getParent());
  149. BI->eraseFromParent();
  150. delete ReturnBlock.getBlock();
  151. return;
  152. }
  153. }
  154. // FIXME: We are at an unreachable point, there is no reason to emit the block
  155. // unless it has uses. However, we still need a place to put the debug
  156. // region.end for now.
  157. EmitBlock(ReturnBlock.getBlock());
  158. }
  159. static void EmitIfUsed(CodeGenFunction &CGF, llvm::BasicBlock *BB) {
  160. if (!BB) return;
  161. if (!BB->use_empty())
  162. return CGF.CurFn->getBasicBlockList().push_back(BB);
  163. delete BB;
  164. }
  165. void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
  166. assert(BreakContinueStack.empty() &&
  167. "mismatched push/pop in break/continue stack!");
  168. bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
  169. && NumSimpleReturnExprs == NumReturnExprs
  170. && ReturnBlock.getBlock()->use_empty();
  171. // Usually the return expression is evaluated before the cleanup
  172. // code. If the function contains only a simple return statement,
  173. // such as a constant, the location before the cleanup code becomes
  174. // the last useful breakpoint in the function, because the simple
  175. // return expression will be evaluated after the cleanup code. To be
  176. // safe, set the debug location for cleanup code to the location of
  177. // the return statement. Otherwise the cleanup code should be at the
  178. // end of the function's lexical scope.
  179. //
  180. // If there are multiple branches to the return block, the branch
  181. // instructions will get the location of the return statements and
  182. // all will be fine.
  183. if (CGDebugInfo *DI = getDebugInfo()) {
  184. if (OnlySimpleReturnStmts)
  185. DI->EmitLocation(Builder, LastStopPoint);
  186. else
  187. DI->EmitLocation(Builder, EndLoc);
  188. }
  189. // Pop any cleanups that might have been associated with the
  190. // parameters. Do this in whatever block we're currently in; it's
  191. // important to do this before we enter the return block or return
  192. // edges will be *really* confused.
  193. bool EmitRetDbgLoc = true;
  194. if (EHStack.stable_begin() != PrologueCleanupDepth) {
  195. PopCleanupBlocks(PrologueCleanupDepth);
  196. // Make sure the line table doesn't jump back into the body for
  197. // the ret after it's been at EndLoc.
  198. EmitRetDbgLoc = false;
  199. if (CGDebugInfo *DI = getDebugInfo())
  200. if (OnlySimpleReturnStmts)
  201. DI->EmitLocation(Builder, EndLoc);
  202. }
  203. // Emit function epilog (to return).
  204. EmitReturnBlock();
  205. if (ShouldInstrumentFunction())
  206. EmitFunctionInstrumentation("__cyg_profile_func_exit");
  207. // Emit debug descriptor for function end.
  208. if (CGDebugInfo *DI = getDebugInfo()) {
  209. DI->EmitFunctionEnd(Builder);
  210. }
  211. EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc);
  212. EmitEndEHSpec(CurCodeDecl);
  213. assert(EHStack.empty() &&
  214. "did not remove all scopes from cleanup stack!");
  215. // If someone did an indirect goto, emit the indirect goto block at the end of
  216. // the function.
  217. if (IndirectBranch) {
  218. EmitBlock(IndirectBranch->getParent());
  219. Builder.ClearInsertionPoint();
  220. }
  221. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  222. llvm::Instruction *Ptr = AllocaInsertPt;
  223. AllocaInsertPt = 0;
  224. Ptr->eraseFromParent();
  225. // If someone took the address of a label but never did an indirect goto, we
  226. // made a zero entry PHI node, which is illegal, zap it now.
  227. if (IndirectBranch) {
  228. llvm::PHINode *PN = cast<llvm::PHINode>(IndirectBranch->getAddress());
  229. if (PN->getNumIncomingValues() == 0) {
  230. PN->replaceAllUsesWith(llvm::UndefValue::get(PN->getType()));
  231. PN->eraseFromParent();
  232. }
  233. }
  234. EmitIfUsed(*this, EHResumeBlock);
  235. EmitIfUsed(*this, TerminateLandingPad);
  236. EmitIfUsed(*this, TerminateHandler);
  237. EmitIfUsed(*this, UnreachableBlock);
  238. if (CGM.getCodeGenOpts().EmitDeclMetadata)
  239. EmitDeclMetadata();
  240. }
  241. /// ShouldInstrumentFunction - Return true if the current function should be
  242. /// instrumented with __cyg_profile_func_* calls
  243. bool CodeGenFunction::ShouldInstrumentFunction() {
  244. if (!CGM.getCodeGenOpts().InstrumentFunctions)
  245. return false;
  246. if (!CurFuncDecl || CurFuncDecl->hasAttr<NoInstrumentFunctionAttr>())
  247. return false;
  248. return true;
  249. }
  250. /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
  251. /// instrumentation function with the current function and the call site, if
  252. /// function instrumentation is enabled.
  253. void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
  254. // void __cyg_profile_func_{enter,exit} (void *this_fn, void *call_site);
  255. llvm::PointerType *PointerTy = Int8PtrTy;
  256. llvm::Type *ProfileFuncArgs[] = { PointerTy, PointerTy };
  257. llvm::FunctionType *FunctionTy =
  258. llvm::FunctionType::get(VoidTy, ProfileFuncArgs, false);
  259. llvm::Constant *F = CGM.CreateRuntimeFunction(FunctionTy, Fn);
  260. llvm::CallInst *CallSite = Builder.CreateCall(
  261. CGM.getIntrinsic(llvm::Intrinsic::returnaddress),
  262. llvm::ConstantInt::get(Int32Ty, 0),
  263. "callsite");
  264. llvm::Value *args[] = {
  265. llvm::ConstantExpr::getBitCast(CurFn, PointerTy),
  266. CallSite
  267. };
  268. EmitNounwindRuntimeCall(F, args);
  269. }
  270. void CodeGenFunction::EmitMCountInstrumentation() {
  271. llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
  272. llvm::Constant *MCountFn =
  273. CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName());
  274. EmitNounwindRuntimeCall(MCountFn);
  275. }
  276. // OpenCL v1.2 s5.6.4.6 allows the compiler to store kernel argument
  277. // information in the program executable. The argument information stored
  278. // includes the argument name, its type, the address and access qualifiers used.
  279. static void GenOpenCLArgMetadata(const FunctionDecl *FD, llvm::Function *Fn,
  280. CodeGenModule &CGM,llvm::LLVMContext &Context,
  281. SmallVector <llvm::Value*, 5> &kernelMDArgs,
  282. CGBuilderTy& Builder, ASTContext &ASTCtx) {
  283. // Create MDNodes that represent the kernel arg metadata.
  284. // Each MDNode is a list in the form of "key", N number of values which is
  285. // the same number of values as their are kernel arguments.
  286. // MDNode for the kernel argument address space qualifiers.
  287. SmallVector<llvm::Value*, 8> addressQuals;
  288. addressQuals.push_back(llvm::MDString::get(Context, "kernel_arg_addr_space"));
  289. // MDNode for the kernel argument access qualifiers (images only).
  290. SmallVector<llvm::Value*, 8> accessQuals;
  291. accessQuals.push_back(llvm::MDString::get(Context, "kernel_arg_access_qual"));
  292. // MDNode for the kernel argument type names.
  293. SmallVector<llvm::Value*, 8> argTypeNames;
  294. argTypeNames.push_back(llvm::MDString::get(Context, "kernel_arg_type"));
  295. // MDNode for the kernel argument type qualifiers.
  296. SmallVector<llvm::Value*, 8> argTypeQuals;
  297. argTypeQuals.push_back(llvm::MDString::get(Context, "kernel_arg_type_qual"));
  298. // MDNode for the kernel argument names.
  299. SmallVector<llvm::Value*, 8> argNames;
  300. argNames.push_back(llvm::MDString::get(Context, "kernel_arg_name"));
  301. for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
  302. const ParmVarDecl *parm = FD->getParamDecl(i);
  303. QualType ty = parm->getType();
  304. std::string typeQuals;
  305. if (ty->isPointerType()) {
  306. QualType pointeeTy = ty->getPointeeType();
  307. // Get address qualifier.
  308. addressQuals.push_back(Builder.getInt32(ASTCtx.getTargetAddressSpace(
  309. pointeeTy.getAddressSpace())));
  310. // Get argument type name.
  311. std::string typeName = pointeeTy.getUnqualifiedType().getAsString() + "*";
  312. // Turn "unsigned type" to "utype"
  313. std::string::size_type pos = typeName.find("unsigned");
  314. if (pos != std::string::npos)
  315. typeName.erase(pos+1, 8);
  316. argTypeNames.push_back(llvm::MDString::get(Context, typeName));
  317. // Get argument type qualifiers:
  318. if (ty.isRestrictQualified())
  319. typeQuals = "restrict";
  320. if (pointeeTy.isConstQualified() ||
  321. (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
  322. typeQuals += typeQuals.empty() ? "const" : " const";
  323. if (pointeeTy.isVolatileQualified())
  324. typeQuals += typeQuals.empty() ? "volatile" : " volatile";
  325. } else {
  326. addressQuals.push_back(Builder.getInt32(0));
  327. // Get argument type name.
  328. std::string typeName = ty.getUnqualifiedType().getAsString();
  329. // Turn "unsigned type" to "utype"
  330. std::string::size_type pos = typeName.find("unsigned");
  331. if (pos != std::string::npos)
  332. typeName.erase(pos+1, 8);
  333. argTypeNames.push_back(llvm::MDString::get(Context, typeName));
  334. // Get argument type qualifiers:
  335. if (ty.isConstQualified())
  336. typeQuals = "const";
  337. if (ty.isVolatileQualified())
  338. typeQuals += typeQuals.empty() ? "volatile" : " volatile";
  339. }
  340. argTypeQuals.push_back(llvm::MDString::get(Context, typeQuals));
  341. // Get image access qualifier:
  342. if (ty->isImageType()) {
  343. if (parm->hasAttr<OpenCLImageAccessAttr>() &&
  344. parm->getAttr<OpenCLImageAccessAttr>()->getAccess() == CLIA_write_only)
  345. accessQuals.push_back(llvm::MDString::get(Context, "write_only"));
  346. else
  347. accessQuals.push_back(llvm::MDString::get(Context, "read_only"));
  348. } else
  349. accessQuals.push_back(llvm::MDString::get(Context, "none"));
  350. // Get argument name.
  351. argNames.push_back(llvm::MDString::get(Context, parm->getName()));
  352. }
  353. kernelMDArgs.push_back(llvm::MDNode::get(Context, addressQuals));
  354. kernelMDArgs.push_back(llvm::MDNode::get(Context, accessQuals));
  355. kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeNames));
  356. kernelMDArgs.push_back(llvm::MDNode::get(Context, argTypeQuals));
  357. kernelMDArgs.push_back(llvm::MDNode::get(Context, argNames));
  358. }
  359. void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  360. llvm::Function *Fn)
  361. {
  362. if (!FD->hasAttr<OpenCLKernelAttr>())
  363. return;
  364. llvm::LLVMContext &Context = getLLVMContext();
  365. SmallVector <llvm::Value*, 5> kernelMDArgs;
  366. kernelMDArgs.push_back(Fn);
  367. if (CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
  368. GenOpenCLArgMetadata(FD, Fn, CGM, Context, kernelMDArgs,
  369. Builder, getContext());
  370. if (FD->hasAttr<VecTypeHintAttr>()) {
  371. VecTypeHintAttr *attr = FD->getAttr<VecTypeHintAttr>();
  372. QualType hintQTy = attr->getTypeHint();
  373. const ExtVectorType *hintEltQTy = hintQTy->getAs<ExtVectorType>();
  374. bool isSignedInteger =
  375. hintQTy->isSignedIntegerType() ||
  376. (hintEltQTy && hintEltQTy->getElementType()->isSignedIntegerType());
  377. llvm::Value *attrMDArgs[] = {
  378. llvm::MDString::get(Context, "vec_type_hint"),
  379. llvm::UndefValue::get(CGM.getTypes().ConvertType(attr->getTypeHint())),
  380. llvm::ConstantInt::get(
  381. llvm::IntegerType::get(Context, 32),
  382. llvm::APInt(32, (uint64_t)(isSignedInteger ? 1 : 0)))
  383. };
  384. kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
  385. }
  386. if (FD->hasAttr<WorkGroupSizeHintAttr>()) {
  387. WorkGroupSizeHintAttr *attr = FD->getAttr<WorkGroupSizeHintAttr>();
  388. llvm::Value *attrMDArgs[] = {
  389. llvm::MDString::get(Context, "work_group_size_hint"),
  390. Builder.getInt32(attr->getXDim()),
  391. Builder.getInt32(attr->getYDim()),
  392. Builder.getInt32(attr->getZDim())
  393. };
  394. kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
  395. }
  396. if (FD->hasAttr<ReqdWorkGroupSizeAttr>()) {
  397. ReqdWorkGroupSizeAttr *attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
  398. llvm::Value *attrMDArgs[] = {
  399. llvm::MDString::get(Context, "reqd_work_group_size"),
  400. Builder.getInt32(attr->getXDim()),
  401. Builder.getInt32(attr->getYDim()),
  402. Builder.getInt32(attr->getZDim())
  403. };
  404. kernelMDArgs.push_back(llvm::MDNode::get(Context, attrMDArgs));
  405. }
  406. llvm::MDNode *kernelMDNode = llvm::MDNode::get(Context, kernelMDArgs);
  407. llvm::NamedMDNode *OpenCLKernelMetadata =
  408. CGM.getModule().getOrInsertNamedMetadata("opencl.kernels");
  409. OpenCLKernelMetadata->addOperand(kernelMDNode);
  410. }
  411. void CodeGenFunction::StartFunction(GlobalDecl GD,
  412. QualType RetTy,
  413. llvm::Function *Fn,
  414. const CGFunctionInfo &FnInfo,
  415. const FunctionArgList &Args,
  416. SourceLocation StartLoc) {
  417. const Decl *D = GD.getDecl();
  418. DidCallStackSave = false;
  419. CurCodeDecl = D;
  420. CurFuncDecl = (D ? D->getNonClosureContext() : 0);
  421. FnRetTy = RetTy;
  422. CurFn = Fn;
  423. CurFnInfo = &FnInfo;
  424. assert(CurFn->isDeclaration() && "Function already has body?");
  425. if (CGM.getSanitizerBlacklist().isIn(*Fn)) {
  426. SanOpts = &SanitizerOptions::Disabled;
  427. SanitizePerformTypeCheck = false;
  428. }
  429. // Pass inline keyword to optimizer if it appears explicitly on any
  430. // declaration.
  431. if (!CGM.getCodeGenOpts().NoInline)
  432. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  433. for (FunctionDecl::redecl_iterator RI = FD->redecls_begin(),
  434. RE = FD->redecls_end(); RI != RE; ++RI)
  435. if (RI->isInlineSpecified()) {
  436. Fn->addFnAttr(llvm::Attribute::InlineHint);
  437. break;
  438. }
  439. if (getLangOpts().OpenCL) {
  440. // Add metadata for a kernel function.
  441. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
  442. EmitOpenCLKernelMetadata(FD, Fn);
  443. }
  444. llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
  445. // Create a marker to make it easy to insert allocas into the entryblock
  446. // later. Don't create this with the builder, because we don't want it
  447. // folded.
  448. llvm::Value *Undef = llvm::UndefValue::get(Int32Ty);
  449. AllocaInsertPt = new llvm::BitCastInst(Undef, Int32Ty, "", EntryBB);
  450. if (Builder.isNamePreserving())
  451. AllocaInsertPt->setName("allocapt");
  452. ReturnBlock = getJumpDestInCurrentScope("return");
  453. Builder.SetInsertPoint(EntryBB);
  454. // Emit subprogram debug descriptor.
  455. if (CGDebugInfo *DI = getDebugInfo()) {
  456. SmallVector<QualType, 16> ArgTypes;
  457. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  458. i != e; ++i) {
  459. ArgTypes.push_back((*i)->getType());
  460. }
  461. QualType FnType =
  462. getContext().getFunctionType(RetTy, ArgTypes,
  463. FunctionProtoType::ExtProtoInfo());
  464. DI->setLocation(StartLoc);
  465. DI->EmitFunctionStart(GD, FnType, CurFn, Builder);
  466. }
  467. if (ShouldInstrumentFunction())
  468. EmitFunctionInstrumentation("__cyg_profile_func_enter");
  469. if (CGM.getCodeGenOpts().InstrumentForProfiling)
  470. EmitMCountInstrumentation();
  471. if (RetTy->isVoidType()) {
  472. // Void type; nothing to return.
  473. ReturnValue = 0;
  474. } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
  475. !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
  476. // Indirect aggregate return; emit returned value directly into sret slot.
  477. // This reduces code size, and affects correctness in C++.
  478. ReturnValue = CurFn->arg_begin();
  479. } else {
  480. ReturnValue = CreateIRTemp(RetTy, "retval");
  481. // Tell the epilog emitter to autorelease the result. We do this
  482. // now so that various specialized functions can suppress it
  483. // during their IR-generation.
  484. if (getLangOpts().ObjCAutoRefCount &&
  485. !CurFnInfo->isReturnsRetained() &&
  486. RetTy->isObjCRetainableType())
  487. AutoreleaseResult = true;
  488. }
  489. EmitStartEHSpec(CurCodeDecl);
  490. PrologueCleanupDepth = EHStack.stable_begin();
  491. EmitFunctionProlog(*CurFnInfo, CurFn, Args);
  492. if (D && isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance()) {
  493. CGM.getCXXABI().EmitInstanceFunctionProlog(*this);
  494. const CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
  495. if (MD->getParent()->isLambda() &&
  496. MD->getOverloadedOperator() == OO_Call) {
  497. // We're in a lambda; figure out the captures.
  498. MD->getParent()->getCaptureFields(LambdaCaptureFields,
  499. LambdaThisCaptureField);
  500. if (LambdaThisCaptureField) {
  501. // If this lambda captures this, load it.
  502. LValue ThisLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
  503. CXXThisValue = EmitLoadOfLValue(ThisLValue).getScalarVal();
  504. }
  505. } else {
  506. // Not in a lambda; just use 'this' from the method.
  507. // FIXME: Should we generate a new load for each use of 'this'? The
  508. // fast register allocator would be happier...
  509. CXXThisValue = CXXABIThisValue;
  510. }
  511. }
  512. // If any of the arguments have a variably modified type, make sure to
  513. // emit the type size.
  514. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  515. i != e; ++i) {
  516. const VarDecl *VD = *i;
  517. // Dig out the type as written from ParmVarDecls; it's unclear whether
  518. // the standard (C99 6.9.1p10) requires this, but we're following the
  519. // precedent set by gcc.
  520. QualType Ty;
  521. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD))
  522. Ty = PVD->getOriginalType();
  523. else
  524. Ty = VD->getType();
  525. if (Ty->isVariablyModifiedType())
  526. EmitVariablyModifiedType(Ty);
  527. }
  528. // Emit a location at the end of the prologue.
  529. if (CGDebugInfo *DI = getDebugInfo())
  530. DI->EmitLocation(Builder, StartLoc);
  531. }
  532. void CodeGenFunction::EmitFunctionBody(FunctionArgList &Args) {
  533. const FunctionDecl *FD = cast<FunctionDecl>(CurGD.getDecl());
  534. assert(FD->getBody());
  535. if (const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody()))
  536. EmitCompoundStmtWithoutScope(*S);
  537. else
  538. EmitStmt(FD->getBody());
  539. }
  540. /// Tries to mark the given function nounwind based on the
  541. /// non-existence of any throwing calls within it. We believe this is
  542. /// lightweight enough to do at -O0.
  543. static void TryMarkNoThrow(llvm::Function *F) {
  544. // LLVM treats 'nounwind' on a function as part of the type, so we
  545. // can't do this on functions that can be overwritten.
  546. if (F->mayBeOverridden()) return;
  547. for (llvm::Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI)
  548. for (llvm::BasicBlock::iterator
  549. BI = FI->begin(), BE = FI->end(); BI != BE; ++BI)
  550. if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(&*BI)) {
  551. if (!Call->doesNotThrow())
  552. return;
  553. } else if (isa<llvm::ResumeInst>(&*BI)) {
  554. return;
  555. }
  556. F->setDoesNotThrow();
  557. }
  558. void CodeGenFunction::GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  559. const CGFunctionInfo &FnInfo) {
  560. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  561. // Check if we should generate debug info for this function.
  562. if (FD->hasAttr<NoDebugAttr>())
  563. DebugInfo = NULL; // disable debug info indefinitely for this function
  564. FunctionArgList Args;
  565. QualType ResTy = FD->getResultType();
  566. CurGD = GD;
  567. const CXXMethodDecl *MD;
  568. if ((MD = dyn_cast<CXXMethodDecl>(FD)) && MD->isInstance()) {
  569. if (CGM.getCXXABI().HasThisReturn(GD))
  570. ResTy = MD->getThisType(getContext());
  571. CGM.getCXXABI().BuildInstanceFunctionParams(*this, ResTy, Args);
  572. }
  573. for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
  574. Args.push_back(FD->getParamDecl(i));
  575. SourceRange BodyRange;
  576. if (Stmt *Body = FD->getBody()) BodyRange = Body->getSourceRange();
  577. CurEHLocation = BodyRange.getEnd();
  578. // Emit the standard function prologue.
  579. StartFunction(GD, ResTy, Fn, FnInfo, Args, BodyRange.getBegin());
  580. // Generate the body of the function.
  581. if (isa<CXXDestructorDecl>(FD))
  582. EmitDestructorBody(Args);
  583. else if (isa<CXXConstructorDecl>(FD))
  584. EmitConstructorBody(Args);
  585. else if (getLangOpts().CUDA &&
  586. !CGM.getCodeGenOpts().CUDAIsDevice &&
  587. FD->hasAttr<CUDAGlobalAttr>())
  588. CGM.getCUDARuntime().EmitDeviceStubBody(*this, Args);
  589. else if (isa<CXXConversionDecl>(FD) &&
  590. cast<CXXConversionDecl>(FD)->isLambdaToBlockPointerConversion()) {
  591. // The lambda conversion to block pointer is special; the semantics can't be
  592. // expressed in the AST, so IRGen needs to special-case it.
  593. EmitLambdaToBlockPointerBody(Args);
  594. } else if (isa<CXXMethodDecl>(FD) &&
  595. cast<CXXMethodDecl>(FD)->isLambdaStaticInvoker()) {
  596. // The lambda "__invoke" function is special, because it forwards or
  597. // clones the body of the function call operator (but is actually static).
  598. EmitLambdaStaticInvokeFunction(cast<CXXMethodDecl>(FD));
  599. } else if (FD->isDefaulted() && isa<CXXMethodDecl>(FD) &&
  600. (cast<CXXMethodDecl>(FD)->isCopyAssignmentOperator() ||
  601. cast<CXXMethodDecl>(FD)->isMoveAssignmentOperator())) {
  602. // Implicit copy-assignment gets the same special treatment as implicit
  603. // copy-constructors.
  604. emitImplicitAssignmentOperatorBody(Args);
  605. }
  606. else
  607. EmitFunctionBody(Args);
  608. // C++11 [stmt.return]p2:
  609. // Flowing off the end of a function [...] results in undefined behavior in
  610. // a value-returning function.
  611. // C11 6.9.1p12:
  612. // If the '}' that terminates a function is reached, and the value of the
  613. // function call is used by the caller, the behavior is undefined.
  614. if (getLangOpts().CPlusPlus && !FD->hasImplicitReturnZero() &&
  615. !FD->getResultType()->isVoidType() && Builder.GetInsertBlock()) {
  616. if (SanOpts->Return)
  617. EmitCheck(Builder.getFalse(), "missing_return",
  618. EmitCheckSourceLocation(FD->getLocation()),
  619. ArrayRef<llvm::Value *>(), CRK_Unrecoverable);
  620. else if (CGM.getCodeGenOpts().OptimizationLevel == 0)
  621. Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::trap));
  622. Builder.CreateUnreachable();
  623. Builder.ClearInsertionPoint();
  624. }
  625. // Emit the standard function epilogue.
  626. FinishFunction(BodyRange.getEnd());
  627. // If we haven't marked the function nothrow through other means, do
  628. // a quick pass now to see if we can.
  629. if (!CurFn->doesNotThrow())
  630. TryMarkNoThrow(CurFn);
  631. }
  632. /// ContainsLabel - Return true if the statement contains a label in it. If
  633. /// this statement is not executed normally, it not containing a label means
  634. /// that we can just remove the code.
  635. bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
  636. // Null statement, not a label!
  637. if (S == 0) return false;
  638. // If this is a label, we have to emit the code, consider something like:
  639. // if (0) { ... foo: bar(); } goto foo;
  640. //
  641. // TODO: If anyone cared, we could track __label__'s, since we know that you
  642. // can't jump to one from outside their declared region.
  643. if (isa<LabelStmt>(S))
  644. return true;
  645. // If this is a case/default statement, and we haven't seen a switch, we have
  646. // to emit the code.
  647. if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
  648. return true;
  649. // If this is a switch statement, we want to ignore cases below it.
  650. if (isa<SwitchStmt>(S))
  651. IgnoreCaseStmts = true;
  652. // Scan subexpressions for verboten labels.
  653. for (Stmt::const_child_range I = S->children(); I; ++I)
  654. if (ContainsLabel(*I, IgnoreCaseStmts))
  655. return true;
  656. return false;
  657. }
  658. /// containsBreak - Return true if the statement contains a break out of it.
  659. /// If the statement (recursively) contains a switch or loop with a break
  660. /// inside of it, this is fine.
  661. bool CodeGenFunction::containsBreak(const Stmt *S) {
  662. // Null statement, not a label!
  663. if (S == 0) return false;
  664. // If this is a switch or loop that defines its own break scope, then we can
  665. // include it and anything inside of it.
  666. if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) || isa<DoStmt>(S) ||
  667. isa<ForStmt>(S))
  668. return false;
  669. if (isa<BreakStmt>(S))
  670. return true;
  671. // Scan subexpressions for verboten breaks.
  672. for (Stmt::const_child_range I = S->children(); I; ++I)
  673. if (containsBreak(*I))
  674. return true;
  675. return false;
  676. }
  677. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  678. /// to a constant, or if it does but contains a label, return false. If it
  679. /// constant folds return true and set the boolean result in Result.
  680. bool CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond,
  681. bool &ResultBool) {
  682. llvm::APSInt ResultInt;
  683. if (!ConstantFoldsToSimpleInteger(Cond, ResultInt))
  684. return false;
  685. ResultBool = ResultInt.getBoolValue();
  686. return true;
  687. }
  688. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  689. /// to a constant, or if it does but contains a label, return false. If it
  690. /// constant folds return true and set the folded value.
  691. bool CodeGenFunction::
  692. ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &ResultInt) {
  693. // FIXME: Rename and handle conversion of other evaluatable things
  694. // to bool.
  695. llvm::APSInt Int;
  696. if (!Cond->EvaluateAsInt(Int, getContext()))
  697. return false; // Not foldable, not integer or not fully evaluatable.
  698. if (CodeGenFunction::ContainsLabel(Cond))
  699. return false; // Contains a label.
  700. ResultInt = Int;
  701. return true;
  702. }
  703. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
  704. /// statement) to the specified blocks. Based on the condition, this might try
  705. /// to simplify the codegen of the conditional based on the branch.
  706. ///
  707. void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
  708. llvm::BasicBlock *TrueBlock,
  709. llvm::BasicBlock *FalseBlock) {
  710. Cond = Cond->IgnoreParens();
  711. if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
  712. // Handle X && Y in a condition.
  713. if (CondBOp->getOpcode() == BO_LAnd) {
  714. // If we have "1 && X", simplify the code. "0 && X" would have constant
  715. // folded if the case was simple enough.
  716. bool ConstantBool = false;
  717. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  718. ConstantBool) {
  719. // br(1 && X) -> br(X).
  720. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  721. }
  722. // If we have "X && 1", simplify the code to use an uncond branch.
  723. // "X && 0" would have been constant folded to 0.
  724. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  725. ConstantBool) {
  726. // br(X && 1) -> br(X).
  727. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
  728. }
  729. // Emit the LHS as a conditional. If the LHS conditional is false, we
  730. // want to jump to the FalseBlock.
  731. llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
  732. ConditionalEvaluation eval(*this);
  733. EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
  734. EmitBlock(LHSTrue);
  735. // Any temporaries created here are conditional.
  736. eval.begin(*this);
  737. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  738. eval.end(*this);
  739. return;
  740. }
  741. if (CondBOp->getOpcode() == BO_LOr) {
  742. // If we have "0 || X", simplify the code. "1 || X" would have constant
  743. // folded if the case was simple enough.
  744. bool ConstantBool = false;
  745. if (ConstantFoldsToSimpleInteger(CondBOp->getLHS(), ConstantBool) &&
  746. !ConstantBool) {
  747. // br(0 || X) -> br(X).
  748. return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  749. }
  750. // If we have "X || 0", simplify the code to use an uncond branch.
  751. // "X || 1" would have been constant folded to 1.
  752. if (ConstantFoldsToSimpleInteger(CondBOp->getRHS(), ConstantBool) &&
  753. !ConstantBool) {
  754. // br(X || 0) -> br(X).
  755. return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
  756. }
  757. // Emit the LHS as a conditional. If the LHS conditional is true, we
  758. // want to jump to the TrueBlock.
  759. llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
  760. ConditionalEvaluation eval(*this);
  761. EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
  762. EmitBlock(LHSFalse);
  763. // Any temporaries created here are conditional.
  764. eval.begin(*this);
  765. EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
  766. eval.end(*this);
  767. return;
  768. }
  769. }
  770. if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
  771. // br(!x, t, f) -> br(x, f, t)
  772. if (CondUOp->getOpcode() == UO_LNot)
  773. return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
  774. }
  775. if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
  776. // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
  777. llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
  778. llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
  779. ConditionalEvaluation cond(*this);
  780. EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
  781. cond.begin(*this);
  782. EmitBlock(LHSBlock);
  783. EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
  784. cond.end(*this);
  785. cond.begin(*this);
  786. EmitBlock(RHSBlock);
  787. EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
  788. cond.end(*this);
  789. return;
  790. }
  791. if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
  792. // Conditional operator handling can give us a throw expression as a
  793. // condition for a case like:
  794. // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
  795. // Fold this to:
  796. // br(c, throw x, br(y, t, f))
  797. EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
  798. return;
  799. }
  800. // Emit the code with the fully general case.
  801. llvm::Value *CondV = EvaluateExprAsBool(Cond);
  802. Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
  803. }
  804. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  805. /// specified stmt yet.
  806. void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
  807. CGM.ErrorUnsupported(S, Type);
  808. }
  809. /// emitNonZeroVLAInit - Emit the "zero" initialization of a
  810. /// variable-length array whose elements have a non-zero bit-pattern.
  811. ///
  812. /// \param baseType the inner-most element type of the array
  813. /// \param src - a char* pointing to the bit-pattern for a single
  814. /// base element of the array
  815. /// \param sizeInChars - the total size of the VLA, in chars
  816. static void emitNonZeroVLAInit(CodeGenFunction &CGF, QualType baseType,
  817. llvm::Value *dest, llvm::Value *src,
  818. llvm::Value *sizeInChars) {
  819. std::pair<CharUnits,CharUnits> baseSizeAndAlign
  820. = CGF.getContext().getTypeInfoInChars(baseType);
  821. CGBuilderTy &Builder = CGF.Builder;
  822. llvm::Value *baseSizeInChars
  823. = llvm::ConstantInt::get(CGF.IntPtrTy, baseSizeAndAlign.first.getQuantity());
  824. llvm::Type *i8p = Builder.getInt8PtrTy();
  825. llvm::Value *begin = Builder.CreateBitCast(dest, i8p, "vla.begin");
  826. llvm::Value *end = Builder.CreateInBoundsGEP(dest, sizeInChars, "vla.end");
  827. llvm::BasicBlock *originBB = CGF.Builder.GetInsertBlock();
  828. llvm::BasicBlock *loopBB = CGF.createBasicBlock("vla-init.loop");
  829. llvm::BasicBlock *contBB = CGF.createBasicBlock("vla-init.cont");
  830. // Make a loop over the VLA. C99 guarantees that the VLA element
  831. // count must be nonzero.
  832. CGF.EmitBlock(loopBB);
  833. llvm::PHINode *cur = Builder.CreatePHI(i8p, 2, "vla.cur");
  834. cur->addIncoming(begin, originBB);
  835. // memcpy the individual element bit-pattern.
  836. Builder.CreateMemCpy(cur, src, baseSizeInChars,
  837. baseSizeAndAlign.second.getQuantity(),
  838. /*volatile*/ false);
  839. // Go to the next element.
  840. llvm::Value *next = Builder.CreateConstInBoundsGEP1_32(cur, 1, "vla.next");
  841. // Leave if that's the end of the VLA.
  842. llvm::Value *done = Builder.CreateICmpEQ(next, end, "vla-init.isdone");
  843. Builder.CreateCondBr(done, contBB, loopBB);
  844. cur->addIncoming(next, loopBB);
  845. CGF.EmitBlock(contBB);
  846. }
  847. void
  848. CodeGenFunction::EmitNullInitialization(llvm::Value *DestPtr, QualType Ty) {
  849. // Ignore empty classes in C++.
  850. if (getLangOpts().CPlusPlus) {
  851. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  852. if (cast<CXXRecordDecl>(RT->getDecl())->isEmpty())
  853. return;
  854. }
  855. }
  856. // Cast the dest ptr to the appropriate i8 pointer type.
  857. unsigned DestAS =
  858. cast<llvm::PointerType>(DestPtr->getType())->getAddressSpace();
  859. llvm::Type *BP = Builder.getInt8PtrTy(DestAS);
  860. if (DestPtr->getType() != BP)
  861. DestPtr = Builder.CreateBitCast(DestPtr, BP);
  862. // Get size and alignment info for this aggregate.
  863. std::pair<CharUnits, CharUnits> TypeInfo =
  864. getContext().getTypeInfoInChars(Ty);
  865. CharUnits Size = TypeInfo.first;
  866. CharUnits Align = TypeInfo.second;
  867. llvm::Value *SizeVal;
  868. const VariableArrayType *vla;
  869. // Don't bother emitting a zero-byte memset.
  870. if (Size.isZero()) {
  871. // But note that getTypeInfo returns 0 for a VLA.
  872. if (const VariableArrayType *vlaType =
  873. dyn_cast_or_null<VariableArrayType>(
  874. getContext().getAsArrayType(Ty))) {
  875. QualType eltType;
  876. llvm::Value *numElts;
  877. llvm::tie(numElts, eltType) = getVLASize(vlaType);
  878. SizeVal = numElts;
  879. CharUnits eltSize = getContext().getTypeSizeInChars(eltType);
  880. if (!eltSize.isOne())
  881. SizeVal = Builder.CreateNUWMul(SizeVal, CGM.getSize(eltSize));
  882. vla = vlaType;
  883. } else {
  884. return;
  885. }
  886. } else {
  887. SizeVal = CGM.getSize(Size);
  888. vla = 0;
  889. }
  890. // If the type contains a pointer to data member we can't memset it to zero.
  891. // Instead, create a null constant and copy it to the destination.
  892. // TODO: there are other patterns besides zero that we can usefully memset,
  893. // like -1, which happens to be the pattern used by member-pointers.
  894. if (!CGM.getTypes().isZeroInitializable(Ty)) {
  895. // For a VLA, emit a single element, then splat that over the VLA.
  896. if (vla) Ty = getContext().getBaseElementType(vla);
  897. llvm::Constant *NullConstant = CGM.EmitNullConstant(Ty);
  898. llvm::GlobalVariable *NullVariable =
  899. new llvm::GlobalVariable(CGM.getModule(), NullConstant->getType(),
  900. /*isConstant=*/true,
  901. llvm::GlobalVariable::PrivateLinkage,
  902. NullConstant, Twine());
  903. llvm::Value *SrcPtr =
  904. Builder.CreateBitCast(NullVariable, Builder.getInt8PtrTy());
  905. if (vla) return emitNonZeroVLAInit(*this, Ty, DestPtr, SrcPtr, SizeVal);
  906. // Get and call the appropriate llvm.memcpy overload.
  907. Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity(), false);
  908. return;
  909. }
  910. // Otherwise, just memset the whole thing to zero. This is legal
  911. // because in LLVM, all default initializers (other than the ones we just
  912. // handled above) are guaranteed to have a bit pattern of all zeros.
  913. Builder.CreateMemSet(DestPtr, Builder.getInt8(0), SizeVal,
  914. Align.getQuantity(), false);
  915. }
  916. llvm::BlockAddress *CodeGenFunction::GetAddrOfLabel(const LabelDecl *L) {
  917. // Make sure that there is a block for the indirect goto.
  918. if (IndirectBranch == 0)
  919. GetIndirectGotoBlock();
  920. llvm::BasicBlock *BB = getJumpDestForLabel(L).getBlock();
  921. // Make sure the indirect branch includes all of the address-taken blocks.
  922. IndirectBranch->addDestination(BB);
  923. return llvm::BlockAddress::get(CurFn, BB);
  924. }
  925. llvm::BasicBlock *CodeGenFunction::GetIndirectGotoBlock() {
  926. // If we already made the indirect branch for indirect goto, return its block.
  927. if (IndirectBranch) return IndirectBranch->getParent();
  928. CGBuilderTy TmpBuilder(createBasicBlock("indirectgoto"));
  929. // Create the PHI node that indirect gotos will add entries to.
  930. llvm::Value *DestVal = TmpBuilder.CreatePHI(Int8PtrTy, 0,
  931. "indirect.goto.dest");
  932. // Create the indirect branch instruction.
  933. IndirectBranch = TmpBuilder.CreateIndirectBr(DestVal);
  934. return IndirectBranch->getParent();
  935. }
  936. /// Computes the length of an array in elements, as well as the base
  937. /// element type and a properly-typed first element pointer.
  938. llvm::Value *CodeGenFunction::emitArrayLength(const ArrayType *origArrayType,
  939. QualType &baseType,
  940. llvm::Value *&addr) {
  941. const ArrayType *arrayType = origArrayType;
  942. // If it's a VLA, we have to load the stored size. Note that
  943. // this is the size of the VLA in bytes, not its size in elements.
  944. llvm::Value *numVLAElements = 0;
  945. if (isa<VariableArrayType>(arrayType)) {
  946. numVLAElements = getVLASize(cast<VariableArrayType>(arrayType)).first;
  947. // Walk into all VLAs. This doesn't require changes to addr,
  948. // which has type T* where T is the first non-VLA element type.
  949. do {
  950. QualType elementType = arrayType->getElementType();
  951. arrayType = getContext().getAsArrayType(elementType);
  952. // If we only have VLA components, 'addr' requires no adjustment.
  953. if (!arrayType) {
  954. baseType = elementType;
  955. return numVLAElements;
  956. }
  957. } while (isa<VariableArrayType>(arrayType));
  958. // We get out here only if we find a constant array type
  959. // inside the VLA.
  960. }
  961. // We have some number of constant-length arrays, so addr should
  962. // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
  963. // down to the first element of addr.
  964. SmallVector<llvm::Value*, 8> gepIndices;
  965. // GEP down to the array type.
  966. llvm::ConstantInt *zero = Builder.getInt32(0);
  967. gepIndices.push_back(zero);
  968. uint64_t countFromCLAs = 1;
  969. QualType eltType;
  970. llvm::ArrayType *llvmArrayType =
  971. dyn_cast<llvm::ArrayType>(
  972. cast<llvm::PointerType>(addr->getType())->getElementType());
  973. while (llvmArrayType) {
  974. assert(isa<ConstantArrayType>(arrayType));
  975. assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
  976. == llvmArrayType->getNumElements());
  977. gepIndices.push_back(zero);
  978. countFromCLAs *= llvmArrayType->getNumElements();
  979. eltType = arrayType->getElementType();
  980. llvmArrayType =
  981. dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
  982. arrayType = getContext().getAsArrayType(arrayType->getElementType());
  983. assert((!llvmArrayType || arrayType) &&
  984. "LLVM and Clang types are out-of-synch");
  985. }
  986. if (arrayType) {
  987. // From this point onwards, the Clang array type has been emitted
  988. // as some other type (probably a packed struct). Compute the array
  989. // size, and just emit the 'begin' expression as a bitcast.
  990. while (arrayType) {
  991. countFromCLAs *=
  992. cast<ConstantArrayType>(arrayType)->getSize().getZExtValue();
  993. eltType = arrayType->getElementType();
  994. arrayType = getContext().getAsArrayType(eltType);
  995. }
  996. unsigned AddressSpace = addr->getType()->getPointerAddressSpace();
  997. llvm::Type *BaseType = ConvertType(eltType)->getPointerTo(AddressSpace);
  998. addr = Builder.CreateBitCast(addr, BaseType, "array.begin");
  999. } else {
  1000. // Create the actual GEP.
  1001. addr = Builder.CreateInBoundsGEP(addr, gepIndices, "array.begin");
  1002. }
  1003. baseType = eltType;
  1004. llvm::Value *numElements
  1005. = llvm::ConstantInt::get(SizeTy, countFromCLAs);
  1006. // If we had any VLA dimensions, factor them in.
  1007. if (numVLAElements)
  1008. numElements = Builder.CreateNUWMul(numVLAElements, numElements);
  1009. return numElements;
  1010. }
  1011. std::pair<llvm::Value*, QualType>
  1012. CodeGenFunction::getVLASize(QualType type) {
  1013. const VariableArrayType *vla = getContext().getAsVariableArrayType(type);
  1014. assert(vla && "type was not a variable array type!");
  1015. return getVLASize(vla);
  1016. }
  1017. std::pair<llvm::Value*, QualType>
  1018. CodeGenFunction::getVLASize(const VariableArrayType *type) {
  1019. // The number of elements so far; always size_t.
  1020. llvm::Value *numElements = 0;
  1021. QualType elementType;
  1022. do {
  1023. elementType = type->getElementType();
  1024. llvm::Value *vlaSize = VLASizeMap[type->getSizeExpr()];
  1025. assert(vlaSize && "no size for VLA!");
  1026. assert(vlaSize->getType() == SizeTy);
  1027. if (!numElements) {
  1028. numElements = vlaSize;
  1029. } else {
  1030. // It's undefined behavior if this wraps around, so mark it that way.
  1031. // FIXME: Teach -fcatch-undefined-behavior to trap this.
  1032. numElements = Builder.CreateNUWMul(numElements, vlaSize);
  1033. }
  1034. } while ((type = getContext().getAsVariableArrayType(elementType)));
  1035. return std::pair<llvm::Value*,QualType>(numElements, elementType);
  1036. }
  1037. void CodeGenFunction::EmitVariablyModifiedType(QualType type) {
  1038. assert(type->isVariablyModifiedType() &&
  1039. "Must pass variably modified type to EmitVLASizes!");
  1040. EnsureInsertPoint();
  1041. // We're going to walk down into the type and look for VLA
  1042. // expressions.
  1043. do {
  1044. assert(type->isVariablyModifiedType());
  1045. const Type *ty = type.getTypePtr();
  1046. switch (ty->getTypeClass()) {
  1047. #define TYPE(Class, Base)
  1048. #define ABSTRACT_TYPE(Class, Base)
  1049. #define NON_CANONICAL_TYPE(Class, Base)
  1050. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1051. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
  1052. #include "clang/AST/TypeNodes.def"
  1053. llvm_unreachable("unexpected dependent type!");
  1054. // These types are never variably-modified.
  1055. case Type::Builtin:
  1056. case Type::Complex:
  1057. case Type::Vector:
  1058. case Type::ExtVector:
  1059. case Type::Record:
  1060. case Type::Enum:
  1061. case Type::Elaborated:
  1062. case Type::TemplateSpecialization:
  1063. case Type::ObjCObject:
  1064. case Type::ObjCInterface:
  1065. case Type::ObjCObjectPointer:
  1066. llvm_unreachable("type class is never variably-modified!");
  1067. case Type::Decayed:
  1068. type = cast<DecayedType>(ty)->getPointeeType();
  1069. break;
  1070. case Type::Pointer:
  1071. type = cast<PointerType>(ty)->getPointeeType();
  1072. break;
  1073. case Type::BlockPointer:
  1074. type = cast<BlockPointerType>(ty)->getPointeeType();
  1075. break;
  1076. case Type::LValueReference:
  1077. case Type::RValueReference:
  1078. type = cast<ReferenceType>(ty)->getPointeeType();
  1079. break;
  1080. case Type::MemberPointer:
  1081. type = cast<MemberPointerType>(ty)->getPointeeType();
  1082. break;
  1083. case Type::ConstantArray:
  1084. case Type::IncompleteArray:
  1085. // Losing element qualification here is fine.
  1086. type = cast<ArrayType>(ty)->getElementType();
  1087. break;
  1088. case Type::VariableArray: {
  1089. // Losing element qualification here is fine.
  1090. const VariableArrayType *vat = cast<VariableArrayType>(ty);
  1091. // Unknown size indication requires no size computation.
  1092. // Otherwise, evaluate and record it.
  1093. if (const Expr *size = vat->getSizeExpr()) {
  1094. // It's possible that we might have emitted this already,
  1095. // e.g. with a typedef and a pointer to it.
  1096. llvm::Value *&entry = VLASizeMap[size];
  1097. if (!entry) {
  1098. llvm::Value *Size = EmitScalarExpr(size);
  1099. // C11 6.7.6.2p5:
  1100. // If the size is an expression that is not an integer constant
  1101. // expression [...] each time it is evaluated it shall have a value
  1102. // greater than zero.
  1103. if (SanOpts->VLABound &&
  1104. size->getType()->isSignedIntegerType()) {
  1105. llvm::Value *Zero = llvm::Constant::getNullValue(Size->getType());
  1106. llvm::Constant *StaticArgs[] = {
  1107. EmitCheckSourceLocation(size->getLocStart()),
  1108. EmitCheckTypeDescriptor(size->getType())
  1109. };
  1110. EmitCheck(Builder.CreateICmpSGT(Size, Zero),
  1111. "vla_bound_not_positive", StaticArgs, Size,
  1112. CRK_Recoverable);
  1113. }
  1114. // Always zexting here would be wrong if it weren't
  1115. // undefined behavior to have a negative bound.
  1116. entry = Builder.CreateIntCast(Size, SizeTy, /*signed*/ false);
  1117. }
  1118. }
  1119. type = vat->getElementType();
  1120. break;
  1121. }
  1122. case Type::FunctionProto:
  1123. case Type::FunctionNoProto:
  1124. type = cast<FunctionType>(ty)->getResultType();
  1125. break;
  1126. case Type::Paren:
  1127. case Type::TypeOf:
  1128. case Type::UnaryTransform:
  1129. case Type::Attributed:
  1130. case Type::SubstTemplateTypeParm:
  1131. case Type::PackExpansion:
  1132. // Keep walking after single level desugaring.
  1133. type = type.getSingleStepDesugaredType(getContext());
  1134. break;
  1135. case Type::Typedef:
  1136. case Type::Decltype:
  1137. case Type::Auto:
  1138. // Stop walking: nothing to do.
  1139. return;
  1140. case Type::TypeOfExpr:
  1141. // Stop walking: emit typeof expression.
  1142. EmitIgnoredExpr(cast<TypeOfExprType>(ty)->getUnderlyingExpr());
  1143. return;
  1144. case Type::Atomic:
  1145. type = cast<AtomicType>(ty)->getValueType();
  1146. break;
  1147. }
  1148. } while (type->isVariablyModifiedType());
  1149. }
  1150. llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
  1151. if (getContext().getBuiltinVaListType()->isArrayType())
  1152. return EmitScalarExpr(E);
  1153. return EmitLValue(E).getAddress();
  1154. }
  1155. void CodeGenFunction::EmitDeclRefExprDbgValue(const DeclRefExpr *E,
  1156. llvm::Constant *Init) {
  1157. assert (Init && "Invalid DeclRefExpr initializer!");
  1158. if (CGDebugInfo *Dbg = getDebugInfo())
  1159. if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
  1160. Dbg->EmitGlobalVariable(E->getDecl(), Init);
  1161. }
  1162. CodeGenFunction::PeepholeProtection
  1163. CodeGenFunction::protectFromPeepholes(RValue rvalue) {
  1164. // At the moment, the only aggressive peephole we do in IR gen
  1165. // is trunc(zext) folding, but if we add more, we can easily
  1166. // extend this protection.
  1167. if (!rvalue.isScalar()) return PeepholeProtection();
  1168. llvm::Value *value = rvalue.getScalarVal();
  1169. if (!isa<llvm::ZExtInst>(value)) return PeepholeProtection();
  1170. // Just make an extra bitcast.
  1171. assert(HaveInsertPoint());
  1172. llvm::Instruction *inst = new llvm::BitCastInst(value, value->getType(), "",
  1173. Builder.GetInsertBlock());
  1174. PeepholeProtection protection;
  1175. protection.Inst = inst;
  1176. return protection;
  1177. }
  1178. void CodeGenFunction::unprotectFromPeepholes(PeepholeProtection protection) {
  1179. if (!protection.Inst) return;
  1180. // In theory, we could try to duplicate the peepholes now, but whatever.
  1181. protection.Inst->eraseFromParent();
  1182. }
  1183. llvm::Value *CodeGenFunction::EmitAnnotationCall(llvm::Value *AnnotationFn,
  1184. llvm::Value *AnnotatedVal,
  1185. StringRef AnnotationStr,
  1186. SourceLocation Location) {
  1187. llvm::Value *Args[4] = {
  1188. AnnotatedVal,
  1189. Builder.CreateBitCast(CGM.EmitAnnotationString(AnnotationStr), Int8PtrTy),
  1190. Builder.CreateBitCast(CGM.EmitAnnotationUnit(Location), Int8PtrTy),
  1191. CGM.EmitAnnotationLineNo(Location)
  1192. };
  1193. return Builder.CreateCall(AnnotationFn, Args);
  1194. }
  1195. void CodeGenFunction::EmitVarAnnotations(const VarDecl *D, llvm::Value *V) {
  1196. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1197. // FIXME We create a new bitcast for every annotation because that's what
  1198. // llvm-gcc was doing.
  1199. for (specific_attr_iterator<AnnotateAttr>
  1200. ai = D->specific_attr_begin<AnnotateAttr>(),
  1201. ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
  1202. EmitAnnotationCall(CGM.getIntrinsic(llvm::Intrinsic::var_annotation),
  1203. Builder.CreateBitCast(V, CGM.Int8PtrTy, V->getName()),
  1204. (*ai)->getAnnotation(), D->getLocation());
  1205. }
  1206. llvm::Value *CodeGenFunction::EmitFieldAnnotations(const FieldDecl *D,
  1207. llvm::Value *V) {
  1208. assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
  1209. llvm::Type *VTy = V->getType();
  1210. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::ptr_annotation,
  1211. CGM.Int8PtrTy);
  1212. for (specific_attr_iterator<AnnotateAttr>
  1213. ai = D->specific_attr_begin<AnnotateAttr>(),
  1214. ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) {
  1215. // FIXME Always emit the cast inst so we can differentiate between
  1216. // annotation on the first field of a struct and annotation on the struct
  1217. // itself.
  1218. if (VTy != CGM.Int8PtrTy)
  1219. V = Builder.Insert(new llvm::BitCastInst(V, CGM.Int8PtrTy));
  1220. V = EmitAnnotationCall(F, V, (*ai)->getAnnotation(), D->getLocation());
  1221. V = Builder.CreateBitCast(V, VTy);
  1222. }
  1223. return V;
  1224. }
  1225. CodeGenFunction::CGCapturedStmtInfo::~CGCapturedStmtInfo() { }