CodeGenFunction.cpp 46 KB

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