CodeGenFunction.cpp 59 KB

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