CodeGenFunction.cpp 68 KB

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