CodeGenFunction.cpp 46 KB

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