CodeGenFunction.cpp 63 KB

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