CodeGenFunction.cpp 81 KB

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