CodeGenFunction.cpp 86 KB

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