CodeGenFunction.cpp 80 KB

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