CodeGenFunction.cpp 46 KB

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