CodeGenFunction.h 132 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167
  1. //===-- CodeGenFunction.h - Per-Function state for LLVM CodeGen -*- C++ -*-===//
  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 is the internal per-function state used for llvm translation.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
  14. #define LLVM_CLANG_LIB_CODEGEN_CODEGENFUNCTION_H
  15. #include "CGBuilder.h"
  16. #include "CGDebugInfo.h"
  17. #include "CGLoopInfo.h"
  18. #include "CGValue.h"
  19. #include "CodeGenModule.h"
  20. #include "CodeGenPGO.h"
  21. #include "EHScopeStack.h"
  22. #include "clang/AST/CharUnits.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/ExprObjC.h"
  25. #include "clang/AST/Type.h"
  26. #include "clang/Basic/ABI.h"
  27. #include "clang/Basic/CapturedStmt.h"
  28. #include "clang/Basic/OpenMPKinds.h"
  29. #include "clang/Basic/TargetInfo.h"
  30. #include "clang/Frontend/CodeGenOptions.h"
  31. #include "llvm/ADT/ArrayRef.h"
  32. #include "llvm/ADT/DenseMap.h"
  33. #include "llvm/ADT/SmallVector.h"
  34. #include "llvm/IR/ValueHandle.h"
  35. #include "llvm/Support/Debug.h"
  36. namespace llvm {
  37. class BasicBlock;
  38. class LLVMContext;
  39. class MDNode;
  40. class Module;
  41. class SwitchInst;
  42. class Twine;
  43. class Value;
  44. class CallSite;
  45. }
  46. namespace clang {
  47. class ASTContext;
  48. class BlockDecl;
  49. class CXXDestructorDecl;
  50. class CXXForRangeStmt;
  51. class CXXTryStmt;
  52. class Decl;
  53. class LabelDecl;
  54. class EnumConstantDecl;
  55. class FunctionDecl;
  56. class FunctionProtoType;
  57. class LabelStmt;
  58. class ObjCContainerDecl;
  59. class ObjCInterfaceDecl;
  60. class ObjCIvarDecl;
  61. class ObjCMethodDecl;
  62. class ObjCImplementationDecl;
  63. class ObjCPropertyImplDecl;
  64. class TargetInfo;
  65. class TargetCodeGenInfo;
  66. class VarDecl;
  67. class ObjCForCollectionStmt;
  68. class ObjCAtTryStmt;
  69. class ObjCAtThrowStmt;
  70. class ObjCAtSynchronizedStmt;
  71. class ObjCAutoreleasePoolStmt;
  72. namespace CodeGen {
  73. class CodeGenTypes;
  74. class CGFunctionInfo;
  75. class CGRecordLayout;
  76. class CGBlockInfo;
  77. class CGCXXABI;
  78. class BlockFlags;
  79. class BlockFieldFlags;
  80. /// The kind of evaluation to perform on values of a particular
  81. /// type. Basically, is the code in CGExprScalar, CGExprComplex, or
  82. /// CGExprAgg?
  83. ///
  84. /// TODO: should vectors maybe be split out into their own thing?
  85. enum TypeEvaluationKind {
  86. TEK_Scalar,
  87. TEK_Complex,
  88. TEK_Aggregate
  89. };
  90. /// CodeGenFunction - This class organizes the per-function state that is used
  91. /// while generating LLVM code.
  92. class CodeGenFunction : public CodeGenTypeCache {
  93. CodeGenFunction(const CodeGenFunction &) = delete;
  94. void operator=(const CodeGenFunction &) = delete;
  95. friend class CGCXXABI;
  96. public:
  97. /// A jump destination is an abstract label, branching to which may
  98. /// require a jump out through normal cleanups.
  99. struct JumpDest {
  100. JumpDest() : Block(nullptr), ScopeDepth(), Index(0) {}
  101. JumpDest(llvm::BasicBlock *Block,
  102. EHScopeStack::stable_iterator Depth,
  103. unsigned Index)
  104. : Block(Block), ScopeDepth(Depth), Index(Index) {}
  105. bool isValid() const { return Block != nullptr; }
  106. llvm::BasicBlock *getBlock() const { return Block; }
  107. EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
  108. unsigned getDestIndex() const { return Index; }
  109. // This should be used cautiously.
  110. void setScopeDepth(EHScopeStack::stable_iterator depth) {
  111. ScopeDepth = depth;
  112. }
  113. private:
  114. llvm::BasicBlock *Block;
  115. EHScopeStack::stable_iterator ScopeDepth;
  116. unsigned Index;
  117. };
  118. CodeGenModule &CGM; // Per-module state.
  119. const TargetInfo &Target;
  120. typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
  121. LoopInfoStack LoopStack;
  122. CGBuilderTy Builder;
  123. /// \brief CGBuilder insert helper. This function is called after an
  124. /// instruction is created using Builder.
  125. void InsertHelper(llvm::Instruction *I, const llvm::Twine &Name,
  126. llvm::BasicBlock *BB,
  127. llvm::BasicBlock::iterator InsertPt) const;
  128. /// CurFuncDecl - Holds the Decl for the current outermost
  129. /// non-closure context.
  130. const Decl *CurFuncDecl;
  131. /// CurCodeDecl - This is the inner-most code context, which includes blocks.
  132. const Decl *CurCodeDecl;
  133. const CGFunctionInfo *CurFnInfo;
  134. QualType FnRetTy;
  135. llvm::Function *CurFn;
  136. /// CurGD - The GlobalDecl for the current function being compiled.
  137. GlobalDecl CurGD;
  138. /// PrologueCleanupDepth - The cleanup depth enclosing all the
  139. /// cleanups associated with the parameters.
  140. EHScopeStack::stable_iterator PrologueCleanupDepth;
  141. /// ReturnBlock - Unified return block.
  142. JumpDest ReturnBlock;
  143. /// ReturnValue - The temporary alloca to hold the return value. This is null
  144. /// iff the function has no return value.
  145. llvm::Value *ReturnValue;
  146. /// AllocaInsertPoint - This is an instruction in the entry block before which
  147. /// we prefer to insert allocas.
  148. llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
  149. /// \brief API for captured statement code generation.
  150. class CGCapturedStmtInfo {
  151. public:
  152. explicit CGCapturedStmtInfo(CapturedRegionKind K = CR_Default)
  153. : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {}
  154. explicit CGCapturedStmtInfo(const CapturedStmt &S,
  155. CapturedRegionKind K = CR_Default)
  156. : Kind(K), ThisValue(nullptr), CXXThisFieldDecl(nullptr) {
  157. RecordDecl::field_iterator Field =
  158. S.getCapturedRecordDecl()->field_begin();
  159. for (CapturedStmt::const_capture_iterator I = S.capture_begin(),
  160. E = S.capture_end();
  161. I != E; ++I, ++Field) {
  162. if (I->capturesThis())
  163. CXXThisFieldDecl = *Field;
  164. else if (I->capturesVariable())
  165. CaptureFields[I->getCapturedVar()] = *Field;
  166. }
  167. }
  168. virtual ~CGCapturedStmtInfo();
  169. CapturedRegionKind getKind() const { return Kind; }
  170. virtual void setContextValue(llvm::Value *V) { ThisValue = V; }
  171. // \brief Retrieve the value of the context parameter.
  172. virtual llvm::Value *getContextValue() const { return ThisValue; }
  173. /// \brief Lookup the captured field decl for a variable.
  174. virtual const FieldDecl *lookup(const VarDecl *VD) const {
  175. return CaptureFields.lookup(VD);
  176. }
  177. bool isCXXThisExprCaptured() const { return getThisFieldDecl() != nullptr; }
  178. virtual FieldDecl *getThisFieldDecl() const { return CXXThisFieldDecl; }
  179. static bool classof(const CGCapturedStmtInfo *) {
  180. return true;
  181. }
  182. /// \brief Emit the captured statement body.
  183. virtual void EmitBody(CodeGenFunction &CGF, const Stmt *S) {
  184. CGF.incrementProfileCounter(S);
  185. CGF.EmitStmt(S);
  186. }
  187. /// \brief Get the name of the capture helper.
  188. virtual StringRef getHelperName() const { return "__captured_stmt"; }
  189. private:
  190. /// \brief The kind of captured statement being generated.
  191. CapturedRegionKind Kind;
  192. /// \brief Keep the map between VarDecl and FieldDecl.
  193. llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields;
  194. /// \brief The base address of the captured record, passed in as the first
  195. /// argument of the parallel region function.
  196. llvm::Value *ThisValue;
  197. /// \brief Captured 'this' type.
  198. FieldDecl *CXXThisFieldDecl;
  199. };
  200. CGCapturedStmtInfo *CapturedStmtInfo;
  201. /// \brief RAII for correct setting/restoring of CapturedStmtInfo.
  202. class CGCapturedStmtRAII {
  203. private:
  204. CodeGenFunction &CGF;
  205. CGCapturedStmtInfo *PrevCapturedStmtInfo;
  206. public:
  207. CGCapturedStmtRAII(CodeGenFunction &CGF,
  208. CGCapturedStmtInfo *NewCapturedStmtInfo)
  209. : CGF(CGF), PrevCapturedStmtInfo(CGF.CapturedStmtInfo) {
  210. CGF.CapturedStmtInfo = NewCapturedStmtInfo;
  211. }
  212. ~CGCapturedStmtRAII() { CGF.CapturedStmtInfo = PrevCapturedStmtInfo; }
  213. };
  214. /// BoundsChecking - Emit run-time bounds checks. Higher values mean
  215. /// potentially higher performance penalties.
  216. unsigned char BoundsChecking;
  217. /// \brief Sanitizers enabled for this function.
  218. SanitizerSet SanOpts;
  219. /// \brief True if CodeGen currently emits code implementing sanitizer checks.
  220. bool IsSanitizerScope;
  221. /// \brief RAII object to set/unset CodeGenFunction::IsSanitizerScope.
  222. class SanitizerScope {
  223. CodeGenFunction *CGF;
  224. public:
  225. SanitizerScope(CodeGenFunction *CGF);
  226. ~SanitizerScope();
  227. };
  228. /// In C++, whether we are code generating a thunk. This controls whether we
  229. /// should emit cleanups.
  230. bool CurFuncIsThunk;
  231. /// In ARC, whether we should autorelease the return value.
  232. bool AutoreleaseResult;
  233. /// Whether we processed a Microsoft-style asm block during CodeGen. These can
  234. /// potentially set the return value.
  235. bool SawAsmBlock;
  236. /// True if the current function is an outlined SEH helper. This can be a
  237. /// finally block or filter expression.
  238. bool IsOutlinedSEHHelper;
  239. const CodeGen::CGBlockInfo *BlockInfo;
  240. llvm::Value *BlockPointer;
  241. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  242. FieldDecl *LambdaThisCaptureField;
  243. /// \brief A mapping from NRVO variables to the flags used to indicate
  244. /// when the NRVO has been applied to this variable.
  245. llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
  246. EHScopeStack EHStack;
  247. llvm::SmallVector<char, 256> LifetimeExtendedCleanupStack;
  248. llvm::SmallVector<const JumpDest *, 2> SEHTryEpilogueStack;
  249. /// Header for data within LifetimeExtendedCleanupStack.
  250. struct LifetimeExtendedCleanupHeader {
  251. /// The size of the following cleanup object.
  252. unsigned Size;
  253. /// The kind of cleanup to push: a value from the CleanupKind enumeration.
  254. CleanupKind Kind;
  255. size_t getSize() const { return Size; }
  256. CleanupKind getKind() const { return Kind; }
  257. };
  258. /// i32s containing the indexes of the cleanup destinations.
  259. llvm::AllocaInst *NormalCleanupDest;
  260. unsigned NextCleanupDestIndex;
  261. /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
  262. CGBlockInfo *FirstBlockInfo;
  263. /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
  264. llvm::BasicBlock *EHResumeBlock;
  265. /// The exception slot. All landing pads write the current exception pointer
  266. /// into this alloca.
  267. llvm::Value *ExceptionSlot;
  268. /// The selector slot. Under the MandatoryCleanup model, all landing pads
  269. /// write the current selector value into this alloca.
  270. llvm::AllocaInst *EHSelectorSlot;
  271. /// A stack of exception code slots. Entering an __except block pushes a slot
  272. /// on the stack and leaving pops one. The __exception_code() intrinsic loads
  273. /// a value from the top of the stack.
  274. SmallVector<llvm::Value *, 1> SEHCodeSlotStack;
  275. /// Value returned by __exception_info intrinsic.
  276. llvm::Value *SEHInfo = nullptr;
  277. /// Emits a landing pad for the current EH stack.
  278. llvm::BasicBlock *EmitLandingPad();
  279. llvm::BasicBlock *getInvokeDestImpl();
  280. template <class T>
  281. typename DominatingValue<T>::saved_type saveValueInCond(T value) {
  282. return DominatingValue<T>::save(*this, value);
  283. }
  284. public:
  285. /// ObjCEHValueStack - Stack of Objective-C exception values, used for
  286. /// rethrows.
  287. SmallVector<llvm::Value*, 8> ObjCEHValueStack;
  288. /// A class controlling the emission of a finally block.
  289. class FinallyInfo {
  290. /// Where the catchall's edge through the cleanup should go.
  291. JumpDest RethrowDest;
  292. /// A function to call to enter the catch.
  293. llvm::Constant *BeginCatchFn;
  294. /// An i1 variable indicating whether or not the @finally is
  295. /// running for an exception.
  296. llvm::AllocaInst *ForEHVar;
  297. /// An i8* variable into which the exception pointer to rethrow
  298. /// has been saved.
  299. llvm::AllocaInst *SavedExnVar;
  300. public:
  301. void enter(CodeGenFunction &CGF, const Stmt *Finally,
  302. llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
  303. llvm::Constant *rethrowFn);
  304. void exit(CodeGenFunction &CGF);
  305. };
  306. /// Returns true inside SEH __try blocks.
  307. bool isSEHTryScope() const { return !SEHTryEpilogueStack.empty(); }
  308. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  309. /// current full-expression. Safe against the possibility that
  310. /// we're currently inside a conditionally-evaluated expression.
  311. template <class T, class... As>
  312. void pushFullExprCleanup(CleanupKind kind, As... A) {
  313. // If we're not in a conditional branch, or if none of the
  314. // arguments requires saving, then use the unconditional cleanup.
  315. if (!isInConditionalBranch())
  316. return EHStack.pushCleanup<T>(kind, A...);
  317. // Stash values in a tuple so we can guarantee the order of saves.
  318. typedef std::tuple<typename DominatingValue<As>::saved_type...> SavedTuple;
  319. SavedTuple Saved{saveValueInCond(A)...};
  320. typedef EHScopeStack::ConditionalCleanup<T, As...> CleanupType;
  321. EHStack.pushCleanupTuple<CleanupType>(kind, Saved);
  322. initFullExprCleanup();
  323. }
  324. /// \brief Queue a cleanup to be pushed after finishing the current
  325. /// full-expression.
  326. template <class T, class... As>
  327. void pushCleanupAfterFullExpr(CleanupKind Kind, As... A) {
  328. assert(!isInConditionalBranch() && "can't defer conditional cleanup");
  329. LifetimeExtendedCleanupHeader Header = { sizeof(T), Kind };
  330. size_t OldSize = LifetimeExtendedCleanupStack.size();
  331. LifetimeExtendedCleanupStack.resize(
  332. LifetimeExtendedCleanupStack.size() + sizeof(Header) + Header.Size);
  333. static_assert(sizeof(Header) % llvm::AlignOf<T>::Alignment == 0,
  334. "Cleanup will be allocated on misaligned address");
  335. char *Buffer = &LifetimeExtendedCleanupStack[OldSize];
  336. new (Buffer) LifetimeExtendedCleanupHeader(Header);
  337. new (Buffer + sizeof(Header)) T(A...);
  338. }
  339. /// Set up the last cleaup that was pushed as a conditional
  340. /// full-expression cleanup.
  341. void initFullExprCleanup();
  342. /// PushDestructorCleanup - Push a cleanup to call the
  343. /// complete-object destructor of an object of the given type at the
  344. /// given address. Does nothing if T is not a C++ class type with a
  345. /// non-trivial destructor.
  346. void PushDestructorCleanup(QualType T, llvm::Value *Addr);
  347. /// PushDestructorCleanup - Push a cleanup to call the
  348. /// complete-object variant of the given destructor on the object at
  349. /// the given address.
  350. void PushDestructorCleanup(const CXXDestructorDecl *Dtor,
  351. llvm::Value *Addr);
  352. /// PopCleanupBlock - Will pop the cleanup entry on the stack and
  353. /// process all branch fixups.
  354. void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
  355. /// DeactivateCleanupBlock - Deactivates the given cleanup block.
  356. /// The block cannot be reactivated. Pops it if it's the top of the
  357. /// stack.
  358. ///
  359. /// \param DominatingIP - An instruction which is known to
  360. /// dominate the current IP (if set) and which lies along
  361. /// all paths of execution between the current IP and the
  362. /// the point at which the cleanup comes into scope.
  363. void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
  364. llvm::Instruction *DominatingIP);
  365. /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
  366. /// Cannot be used to resurrect a deactivated cleanup.
  367. ///
  368. /// \param DominatingIP - An instruction which is known to
  369. /// dominate the current IP (if set) and which lies along
  370. /// all paths of execution between the current IP and the
  371. /// the point at which the cleanup comes into scope.
  372. void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
  373. llvm::Instruction *DominatingIP);
  374. /// \brief Enters a new scope for capturing cleanups, all of which
  375. /// will be executed once the scope is exited.
  376. class RunCleanupsScope {
  377. EHScopeStack::stable_iterator CleanupStackDepth;
  378. size_t LifetimeExtendedCleanupStackSize;
  379. bool OldDidCallStackSave;
  380. protected:
  381. bool PerformCleanup;
  382. private:
  383. RunCleanupsScope(const RunCleanupsScope &) = delete;
  384. void operator=(const RunCleanupsScope &) = delete;
  385. protected:
  386. CodeGenFunction& CGF;
  387. public:
  388. /// \brief Enter a new cleanup scope.
  389. explicit RunCleanupsScope(CodeGenFunction &CGF)
  390. : PerformCleanup(true), CGF(CGF)
  391. {
  392. CleanupStackDepth = CGF.EHStack.stable_begin();
  393. LifetimeExtendedCleanupStackSize =
  394. CGF.LifetimeExtendedCleanupStack.size();
  395. OldDidCallStackSave = CGF.DidCallStackSave;
  396. CGF.DidCallStackSave = false;
  397. }
  398. /// \brief Exit this cleanup scope, emitting any accumulated
  399. /// cleanups.
  400. ~RunCleanupsScope() {
  401. if (PerformCleanup) {
  402. CGF.DidCallStackSave = OldDidCallStackSave;
  403. CGF.PopCleanupBlocks(CleanupStackDepth,
  404. LifetimeExtendedCleanupStackSize);
  405. }
  406. }
  407. /// \brief Determine whether this scope requires any cleanups.
  408. bool requiresCleanups() const {
  409. return CGF.EHStack.stable_begin() != CleanupStackDepth;
  410. }
  411. /// \brief Force the emission of cleanups now, instead of waiting
  412. /// until this object is destroyed.
  413. void ForceCleanup() {
  414. assert(PerformCleanup && "Already forced cleanup");
  415. CGF.DidCallStackSave = OldDidCallStackSave;
  416. CGF.PopCleanupBlocks(CleanupStackDepth,
  417. LifetimeExtendedCleanupStackSize);
  418. PerformCleanup = false;
  419. }
  420. };
  421. class LexicalScope : public RunCleanupsScope {
  422. SourceRange Range;
  423. SmallVector<const LabelDecl*, 4> Labels;
  424. LexicalScope *ParentScope;
  425. LexicalScope(const LexicalScope &) = delete;
  426. void operator=(const LexicalScope &) = delete;
  427. public:
  428. /// \brief Enter a new cleanup scope.
  429. explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
  430. : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
  431. CGF.CurLexicalScope = this;
  432. if (CGDebugInfo *DI = CGF.getDebugInfo())
  433. DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
  434. }
  435. void addLabel(const LabelDecl *label) {
  436. assert(PerformCleanup && "adding label to dead scope?");
  437. Labels.push_back(label);
  438. }
  439. /// \brief Exit this cleanup scope, emitting any accumulated
  440. /// cleanups.
  441. ~LexicalScope() {
  442. if (CGDebugInfo *DI = CGF.getDebugInfo())
  443. DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
  444. // If we should perform a cleanup, force them now. Note that
  445. // this ends the cleanup scope before rescoping any labels.
  446. if (PerformCleanup) {
  447. ApplyDebugLocation DL(CGF, Range.getEnd());
  448. ForceCleanup();
  449. }
  450. }
  451. /// \brief Force the emission of cleanups now, instead of waiting
  452. /// until this object is destroyed.
  453. void ForceCleanup() {
  454. CGF.CurLexicalScope = ParentScope;
  455. RunCleanupsScope::ForceCleanup();
  456. if (!Labels.empty())
  457. rescopeLabels();
  458. }
  459. void rescopeLabels();
  460. };
  461. /// \brief The scope used to remap some variables as private in the OpenMP
  462. /// loop body (or other captured region emitted without outlining), and to
  463. /// restore old vars back on exit.
  464. class OMPPrivateScope : public RunCleanupsScope {
  465. typedef llvm::DenseMap<const VarDecl *, llvm::Value *> VarDeclMapTy;
  466. VarDeclMapTy SavedLocals;
  467. VarDeclMapTy SavedPrivates;
  468. private:
  469. OMPPrivateScope(const OMPPrivateScope &) = delete;
  470. void operator=(const OMPPrivateScope &) = delete;
  471. public:
  472. /// \brief Enter a new OpenMP private scope.
  473. explicit OMPPrivateScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
  474. /// \brief Registers \a LocalVD variable as a private and apply \a
  475. /// PrivateGen function for it to generate corresponding private variable.
  476. /// \a PrivateGen returns an address of the generated private variable.
  477. /// \return true if the variable is registered as private, false if it has
  478. /// been privatized already.
  479. bool
  480. addPrivate(const VarDecl *LocalVD,
  481. const std::function<llvm::Value *()> &PrivateGen) {
  482. assert(PerformCleanup && "adding private to dead scope");
  483. if (SavedLocals.count(LocalVD) > 0) return false;
  484. SavedLocals[LocalVD] = CGF.LocalDeclMap.lookup(LocalVD);
  485. CGF.LocalDeclMap.erase(LocalVD);
  486. SavedPrivates[LocalVD] = PrivateGen();
  487. CGF.LocalDeclMap[LocalVD] = SavedLocals[LocalVD];
  488. return true;
  489. }
  490. /// \brief Privatizes local variables previously registered as private.
  491. /// Registration is separate from the actual privatization to allow
  492. /// initializers use values of the original variables, not the private one.
  493. /// This is important, for example, if the private variable is a class
  494. /// variable initialized by a constructor that references other private
  495. /// variables. But at initialization original variables must be used, not
  496. /// private copies.
  497. /// \return true if at least one variable was privatized, false otherwise.
  498. bool Privatize() {
  499. for (auto VDPair : SavedPrivates) {
  500. CGF.LocalDeclMap[VDPair.first] = VDPair.second;
  501. }
  502. SavedPrivates.clear();
  503. return !SavedLocals.empty();
  504. }
  505. void ForceCleanup() {
  506. RunCleanupsScope::ForceCleanup();
  507. // Remap vars back to the original values.
  508. for (auto I : SavedLocals) {
  509. CGF.LocalDeclMap[I.first] = I.second;
  510. }
  511. SavedLocals.clear();
  512. }
  513. /// \brief Exit scope - all the mapped variables are restored.
  514. ~OMPPrivateScope() {
  515. if (PerformCleanup)
  516. ForceCleanup();
  517. }
  518. };
  519. // HLSL Change Begins
  520. /// \brief The scope used to add temp variables for out parameter in HLSL.
  521. class HLSLOutParamScope : public RunCleanupsScope {
  522. typedef llvm::DenseSet<const VarDecl *> VarDeclSetTy;
  523. VarDeclSetTy SavedLocals;
  524. private:
  525. HLSLOutParamScope(const HLSLOutParamScope &) = delete;
  526. void operator=(const HLSLOutParamScope &) = delete;
  527. void ForceCleanup() {
  528. RunCleanupsScope::ForceCleanup();
  529. // Remap vars back to the original values.
  530. for (auto I : SavedLocals) {
  531. CGF.LocalDeclMap.erase(I);
  532. }
  533. SavedLocals.clear();
  534. }
  535. public:
  536. /// \brief Enter a new OpenMP private scope.
  537. explicit HLSLOutParamScope(CodeGenFunction &CGF) : RunCleanupsScope(CGF) {}
  538. /// \brief Registers \a LocalVD variable as TmpArg
  539. void addTemp(const VarDecl *LocalVD, llvm::Value *TmpArg) {
  540. CGF.LocalDeclMap[LocalVD] = TmpArg;
  541. SavedLocals.insert(LocalVD);
  542. }
  543. /// \brief Exit scope - all the mapped variables are restored.
  544. ~HLSLOutParamScope() { ForceCleanup(); }
  545. };
  546. // HLSL Change Ends
  547. /// \brief Takes the old cleanup stack size and emits the cleanup blocks
  548. /// that have been added.
  549. void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
  550. /// \brief Takes the old cleanup stack size and emits the cleanup blocks
  551. /// that have been added, then adds all lifetime-extended cleanups from
  552. /// the given position to the stack.
  553. void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
  554. size_t OldLifetimeExtendedStackSize);
  555. void ResolveBranchFixups(llvm::BasicBlock *Target);
  556. /// The given basic block lies in the current EH scope, but may be a
  557. /// target of a potentially scope-crossing jump; get a stable handle
  558. /// to which we can perform this jump later.
  559. JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
  560. return JumpDest(Target,
  561. EHStack.getInnermostNormalCleanup(),
  562. NextCleanupDestIndex++);
  563. }
  564. /// The given basic block lies in the current EH scope, but may be a
  565. /// target of a potentially scope-crossing jump; get a stable handle
  566. /// to which we can perform this jump later.
  567. JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
  568. return getJumpDestInCurrentScope(createBasicBlock(Name));
  569. }
  570. /// EmitBranchThroughCleanup - Emit a branch from the current insert
  571. /// block through the normal cleanup handling code (if any) and then
  572. /// on to \arg Dest.
  573. // HLSL Change - allow to use pre-generated branch
  574. void EmitBranchThroughCleanup(JumpDest Dest, llvm::BranchInst *PreExistingBr = nullptr);
  575. /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
  576. /// specified destination obviously has no cleanups to run. 'false' is always
  577. /// a conservatively correct answer for this method.
  578. bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
  579. /// popCatchScope - Pops the catch scope at the top of the EHScope
  580. /// stack, emitting any required code (other than the catch handlers
  581. /// themselves).
  582. void popCatchScope();
  583. llvm::BasicBlock *getEHResumeBlock(bool isCleanup);
  584. llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
  585. /// An object to manage conditionally-evaluated expressions.
  586. class ConditionalEvaluation {
  587. llvm::BasicBlock *StartBB;
  588. public:
  589. ConditionalEvaluation(CodeGenFunction &CGF)
  590. : StartBB(CGF.Builder.GetInsertBlock()) {}
  591. void begin(CodeGenFunction &CGF) {
  592. assert(CGF.OutermostConditional != this);
  593. if (!CGF.OutermostConditional)
  594. CGF.OutermostConditional = this;
  595. }
  596. void end(CodeGenFunction &CGF) {
  597. assert(CGF.OutermostConditional != nullptr);
  598. if (CGF.OutermostConditional == this)
  599. CGF.OutermostConditional = nullptr;
  600. }
  601. /// Returns a block which will be executed prior to each
  602. /// evaluation of the conditional code.
  603. llvm::BasicBlock *getStartingBlock() const {
  604. return StartBB;
  605. }
  606. };
  607. /// isInConditionalBranch - Return true if we're currently emitting
  608. /// one branch or the other of a conditional expression.
  609. bool isInConditionalBranch() const { return OutermostConditional != nullptr; }
  610. void setBeforeOutermostConditional(llvm::Value *value, llvm::Value *addr) {
  611. assert(isInConditionalBranch());
  612. llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
  613. new llvm::StoreInst(value, addr, &block->back());
  614. }
  615. /// An RAII object to record that we're evaluating a statement
  616. /// expression.
  617. class StmtExprEvaluation {
  618. CodeGenFunction &CGF;
  619. /// We have to save the outermost conditional: cleanups in a
  620. /// statement expression aren't conditional just because the
  621. /// StmtExpr is.
  622. ConditionalEvaluation *SavedOutermostConditional;
  623. public:
  624. StmtExprEvaluation(CodeGenFunction &CGF)
  625. : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
  626. CGF.OutermostConditional = nullptr;
  627. }
  628. ~StmtExprEvaluation() {
  629. CGF.OutermostConditional = SavedOutermostConditional;
  630. CGF.EnsureInsertPoint();
  631. }
  632. };
  633. /// An object which temporarily prevents a value from being
  634. /// destroyed by aggressive peephole optimizations that assume that
  635. /// all uses of a value have been realized in the IR.
  636. class PeepholeProtection {
  637. llvm::Instruction *Inst;
  638. friend class CodeGenFunction;
  639. public:
  640. PeepholeProtection() : Inst(nullptr) {}
  641. };
  642. /// A non-RAII class containing all the information about a bound
  643. /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
  644. /// this which makes individual mappings very simple; using this
  645. /// class directly is useful when you have a variable number of
  646. /// opaque values or don't want the RAII functionality for some
  647. /// reason.
  648. class OpaqueValueMappingData {
  649. const OpaqueValueExpr *OpaqueValue;
  650. bool BoundLValue;
  651. CodeGenFunction::PeepholeProtection Protection;
  652. OpaqueValueMappingData(const OpaqueValueExpr *ov,
  653. bool boundLValue)
  654. : OpaqueValue(ov), BoundLValue(boundLValue) {}
  655. public:
  656. OpaqueValueMappingData() : OpaqueValue(nullptr) {}
  657. static bool shouldBindAsLValue(const Expr *expr) {
  658. // gl-values should be bound as l-values for obvious reasons.
  659. // Records should be bound as l-values because IR generation
  660. // always keeps them in memory. Expressions of function type
  661. // act exactly like l-values but are formally required to be
  662. // r-values in C.
  663. return expr->isGLValue() ||
  664. expr->getType()->isFunctionType() ||
  665. hasAggregateEvaluationKind(expr->getType());
  666. }
  667. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  668. const OpaqueValueExpr *ov,
  669. const Expr *e) {
  670. if (shouldBindAsLValue(ov))
  671. return bind(CGF, ov, CGF.EmitLValue(e));
  672. return bind(CGF, ov, CGF.EmitAnyExpr(e));
  673. }
  674. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  675. const OpaqueValueExpr *ov,
  676. const LValue &lv) {
  677. assert(shouldBindAsLValue(ov));
  678. CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
  679. return OpaqueValueMappingData(ov, true);
  680. }
  681. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  682. const OpaqueValueExpr *ov,
  683. const RValue &rv) {
  684. assert(!shouldBindAsLValue(ov));
  685. CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
  686. OpaqueValueMappingData data(ov, false);
  687. // Work around an extremely aggressive peephole optimization in
  688. // EmitScalarConversion which assumes that all other uses of a
  689. // value are extant.
  690. data.Protection = CGF.protectFromPeepholes(rv);
  691. return data;
  692. }
  693. bool isValid() const { return OpaqueValue != nullptr; }
  694. void clear() { OpaqueValue = nullptr; }
  695. void unbind(CodeGenFunction &CGF) {
  696. assert(OpaqueValue && "no data to unbind!");
  697. if (BoundLValue) {
  698. CGF.OpaqueLValues.erase(OpaqueValue);
  699. } else {
  700. CGF.OpaqueRValues.erase(OpaqueValue);
  701. CGF.unprotectFromPeepholes(Protection);
  702. }
  703. }
  704. };
  705. /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
  706. class OpaqueValueMapping {
  707. CodeGenFunction &CGF;
  708. OpaqueValueMappingData Data;
  709. public:
  710. static bool shouldBindAsLValue(const Expr *expr) {
  711. return OpaqueValueMappingData::shouldBindAsLValue(expr);
  712. }
  713. /// Build the opaque value mapping for the given conditional
  714. /// operator if it's the GNU ?: extension. This is a common
  715. /// enough pattern that the convenience operator is really
  716. /// helpful.
  717. ///
  718. OpaqueValueMapping(CodeGenFunction &CGF,
  719. const AbstractConditionalOperator *op) : CGF(CGF) {
  720. if (isa<ConditionalOperator>(op))
  721. // Leave Data empty.
  722. return;
  723. const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
  724. Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
  725. e->getCommon());
  726. }
  727. OpaqueValueMapping(CodeGenFunction &CGF,
  728. const OpaqueValueExpr *opaqueValue,
  729. LValue lvalue)
  730. : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
  731. }
  732. OpaqueValueMapping(CodeGenFunction &CGF,
  733. const OpaqueValueExpr *opaqueValue,
  734. RValue rvalue)
  735. : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
  736. }
  737. void pop() {
  738. Data.unbind(CGF);
  739. Data.clear();
  740. }
  741. ~OpaqueValueMapping() {
  742. if (Data.isValid()) Data.unbind(CGF);
  743. }
  744. };
  745. /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
  746. /// number that holds the value.
  747. std::pair<llvm::Type *, unsigned>
  748. getByRefValueLLVMField(const ValueDecl *VD) const;
  749. /// BuildBlockByrefAddress - Computes address location of the
  750. /// variable which is declared as __block.
  751. llvm::Value *BuildBlockByrefAddress(llvm::Value *BaseAddr,
  752. const VarDecl *V);
  753. private:
  754. CGDebugInfo *DebugInfo;
  755. bool DisableDebugInfo;
  756. /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
  757. /// calling llvm.stacksave for multiple VLAs in the same scope.
  758. bool DidCallStackSave;
  759. /// IndirectBranch - The first time an indirect goto is seen we create a block
  760. /// with an indirect branch. Every time we see the address of a label taken,
  761. /// we add the label to the indirect goto. Every subsequent indirect goto is
  762. /// codegen'd as a jump to the IndirectBranch's basic block.
  763. llvm::IndirectBrInst *IndirectBranch;
  764. /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
  765. /// decls.
  766. typedef llvm::DenseMap<const Decl*, llvm::Value*> DeclMapTy;
  767. DeclMapTy LocalDeclMap;
  768. /// Track escaped local variables with auto storage. Used during SEH
  769. /// outlining to produce a call to llvm.localescape.
  770. llvm::DenseMap<llvm::AllocaInst *, int> EscapedLocals;
  771. /// LabelMap - This keeps track of the LLVM basic block for each C label.
  772. llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
  773. // BreakContinueStack - This keeps track of where break and continue
  774. // statements should jump to.
  775. struct BreakContinue {
  776. BreakContinue(JumpDest Break, JumpDest Continue)
  777. : BreakBlock(Break), ContinueBlock(Continue) {}
  778. JumpDest BreakBlock;
  779. JumpDest ContinueBlock;
  780. };
  781. SmallVector<BreakContinue, 8> BreakContinueStack;
  782. CodeGenPGO PGO;
  783. /// Calculate branch weights appropriate for PGO data
  784. llvm::MDNode *createProfileWeights(uint64_t TrueCount, uint64_t FalseCount);
  785. llvm::MDNode *createProfileWeights(ArrayRef<uint64_t> Weights);
  786. llvm::MDNode *createProfileWeightsForLoop(const Stmt *Cond,
  787. uint64_t LoopCount);
  788. public:
  789. /// Increment the profiler's counter for the given statement.
  790. void incrementProfileCounter(const Stmt *S) {
  791. if (CGM.getCodeGenOpts().ProfileInstrGenerate)
  792. PGO.emitCounterIncrement(Builder, S);
  793. PGO.setCurrentStmt(S);
  794. }
  795. /// Get the profiler's count for the given statement.
  796. uint64_t getProfileCount(const Stmt *S) {
  797. Optional<uint64_t> Count = PGO.getStmtCount(S);
  798. if (!Count.hasValue())
  799. return 0;
  800. return *Count;
  801. }
  802. /// Set the profiler's current count.
  803. void setCurrentProfileCount(uint64_t Count) {
  804. PGO.setCurrentRegionCount(Count);
  805. }
  806. /// Get the profiler's current count. This is generally the count for the most
  807. /// recently incremented counter.
  808. uint64_t getCurrentProfileCount() {
  809. return PGO.getCurrentRegionCount();
  810. }
  811. private:
  812. /// SwitchInsn - This is nearest current switch instruction. It is null if
  813. /// current context is not in a switch.
  814. llvm::SwitchInst *SwitchInsn;
  815. /// The branch weights of SwitchInsn when doing instrumentation based PGO.
  816. SmallVector<uint64_t, 16> *SwitchWeights;
  817. /// CaseRangeBlock - This block holds if condition check for last case
  818. /// statement range in current switch instruction.
  819. llvm::BasicBlock *CaseRangeBlock;
  820. /// OpaqueLValues - Keeps track of the current set of opaque value
  821. /// expressions.
  822. llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
  823. llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
  824. // VLASizeMap - This keeps track of the associated size for each VLA type.
  825. // We track this by the size expression rather than the type itself because
  826. // in certain situations, like a const qualifier applied to an VLA typedef,
  827. // multiple VLA types can share the same size expression.
  828. // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
  829. // enter/leave scopes.
  830. llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
  831. /// A block containing a single 'unreachable' instruction. Created
  832. /// lazily by getUnreachableBlock().
  833. llvm::BasicBlock *UnreachableBlock;
  834. /// Counts of the number return expressions in the function.
  835. unsigned NumReturnExprs;
  836. /// Count the number of simple (constant) return expressions in the function.
  837. unsigned NumSimpleReturnExprs;
  838. /// The last regular (non-return) debug location (breakpoint) in the function.
  839. SourceLocation LastStopPoint;
  840. public:
  841. /// A scope within which we are constructing the fields of an object which
  842. /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
  843. /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
  844. class FieldConstructionScope {
  845. public:
  846. FieldConstructionScope(CodeGenFunction &CGF, llvm::Value *This)
  847. : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
  848. CGF.CXXDefaultInitExprThis = This;
  849. }
  850. ~FieldConstructionScope() {
  851. CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
  852. }
  853. private:
  854. CodeGenFunction &CGF;
  855. llvm::Value *OldCXXDefaultInitExprThis;
  856. };
  857. /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
  858. /// is overridden to be the object under construction.
  859. class CXXDefaultInitExprScope {
  860. public:
  861. CXXDefaultInitExprScope(CodeGenFunction &CGF)
  862. : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue) {
  863. CGF.CXXThisValue = CGF.CXXDefaultInitExprThis;
  864. }
  865. ~CXXDefaultInitExprScope() {
  866. CGF.CXXThisValue = OldCXXThisValue;
  867. }
  868. public:
  869. CodeGenFunction &CGF;
  870. llvm::Value *OldCXXThisValue;
  871. };
  872. private:
  873. /// CXXThisDecl - When generating code for a C++ member function,
  874. /// this will hold the implicit 'this' declaration.
  875. ImplicitParamDecl *CXXABIThisDecl;
  876. llvm::Value *CXXABIThisValue;
  877. llvm::Value *CXXThisValue;
  878. /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
  879. /// this expression.
  880. llvm::Value *CXXDefaultInitExprThis;
  881. /// CXXStructorImplicitParamDecl - When generating code for a constructor or
  882. /// destructor, this will hold the implicit argument (e.g. VTT).
  883. ImplicitParamDecl *CXXStructorImplicitParamDecl;
  884. llvm::Value *CXXStructorImplicitParamValue;
  885. /// OutermostConditional - Points to the outermost active
  886. /// conditional control. This is used so that we know if a
  887. /// temporary should be destroyed conditionally.
  888. ConditionalEvaluation *OutermostConditional;
  889. /// The current lexical scope.
  890. LexicalScope *CurLexicalScope;
  891. /// The current source location that should be used for exception
  892. /// handling code.
  893. SourceLocation CurEHLocation;
  894. /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
  895. /// type as well as the field number that contains the actual data.
  896. llvm::DenseMap<const ValueDecl *, std::pair<llvm::Type *,
  897. unsigned> > ByRefValueInfo;
  898. llvm::BasicBlock *TerminateLandingPad;
  899. llvm::BasicBlock *TerminateHandler;
  900. llvm::BasicBlock *TrapBB;
  901. /// Add a kernel metadata node to the named metadata node 'opencl.kernels'.
  902. /// In the kernel metadata node, reference the kernel function and metadata
  903. /// nodes for its optional attribute qualifiers (OpenCL 1.1 6.7.2):
  904. /// - A node for the vec_type_hint(<type>) qualifier contains string
  905. /// "vec_type_hint", an undefined value of the <type> data type,
  906. /// and a Boolean that is true if the <type> is integer and signed.
  907. /// - A node for the work_group_size_hint(X,Y,Z) qualifier contains string
  908. /// "work_group_size_hint", and three 32-bit integers X, Y and Z.
  909. /// - A node for the reqd_work_group_size(X,Y,Z) qualifier contains string
  910. /// "reqd_work_group_size", and three 32-bit integers X, Y and Z.
  911. void EmitOpenCLKernelMetadata(const FunctionDecl *FD,
  912. llvm::Function *Fn);
  913. public:
  914. CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
  915. ~CodeGenFunction();
  916. CodeGenTypes &getTypes() const { return CGM.getTypes(); }
  917. ASTContext &getContext() const { return CGM.getContext(); }
  918. CGDebugInfo *getDebugInfo() {
  919. if (DisableDebugInfo)
  920. return nullptr;
  921. return DebugInfo;
  922. }
  923. void disableDebugInfo() { DisableDebugInfo = true; }
  924. void enableDebugInfo() { DisableDebugInfo = false; }
  925. bool shouldUseFusedARCCalls() {
  926. return CGM.getCodeGenOpts().OptimizationLevel == 0;
  927. }
  928. const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
  929. /// Returns a pointer to the function's exception object and selector slot,
  930. /// which is assigned in every landing pad.
  931. llvm::Value *getExceptionSlot();
  932. llvm::Value *getEHSelectorSlot();
  933. /// Returns the contents of the function's exception object and selector
  934. /// slots.
  935. llvm::Value *getExceptionFromSlot();
  936. llvm::Value *getSelectorFromSlot();
  937. llvm::Value *getNormalCleanupDestSlot();
  938. llvm::BasicBlock *getUnreachableBlock() {
  939. if (!UnreachableBlock) {
  940. UnreachableBlock = createBasicBlock("unreachable");
  941. new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
  942. }
  943. return UnreachableBlock;
  944. }
  945. llvm::BasicBlock *getInvokeDest() {
  946. #if 0 // HLSL Change - no exception handling
  947. if (!EHStack.requiresLandingPad()) return nullptr;
  948. return getInvokeDestImpl();
  949. #else
  950. return nullptr;
  951. #endif // HLSL Change - no exception handling
  952. }
  953. bool currentFunctionUsesSEHTry() const {
  954. const auto *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl);
  955. return FD && FD->usesSEHTry();
  956. }
  957. const TargetInfo &getTarget() const { return Target; }
  958. llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
  959. //===--------------------------------------------------------------------===//
  960. // Cleanups
  961. //===--------------------------------------------------------------------===//
  962. typedef void Destroyer(CodeGenFunction &CGF, llvm::Value *addr, QualType ty);
  963. void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  964. llvm::Value *arrayEndPointer,
  965. QualType elementType,
  966. Destroyer *destroyer);
  967. void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  968. llvm::Value *arrayEnd,
  969. QualType elementType,
  970. Destroyer *destroyer);
  971. void pushDestroy(QualType::DestructionKind dtorKind,
  972. llvm::Value *addr, QualType type);
  973. void pushEHDestroy(QualType::DestructionKind dtorKind,
  974. llvm::Value *addr, QualType type);
  975. void pushDestroy(CleanupKind kind, llvm::Value *addr, QualType type,
  976. Destroyer *destroyer, bool useEHCleanupForArray);
  977. void pushLifetimeExtendedDestroy(CleanupKind kind, llvm::Value *addr,
  978. QualType type, Destroyer *destroyer,
  979. bool useEHCleanupForArray);
  980. void pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
  981. llvm::Value *CompletePtr,
  982. QualType ElementType);
  983. void pushStackRestore(CleanupKind kind, llvm::Value *SPMem);
  984. void emitDestroy(llvm::Value *addr, QualType type, Destroyer *destroyer,
  985. bool useEHCleanupForArray);
  986. llvm::Function *generateDestroyHelper(llvm::Constant *addr, QualType type,
  987. Destroyer *destroyer,
  988. bool useEHCleanupForArray,
  989. const VarDecl *VD);
  990. void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
  991. QualType type, Destroyer *destroyer,
  992. bool checkZeroLength, bool useEHCleanup);
  993. Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
  994. /// Determines whether an EH cleanup is required to destroy a type
  995. /// with the given destruction kind.
  996. bool needsEHCleanup(QualType::DestructionKind kind) {
  997. switch (kind) {
  998. case QualType::DK_none:
  999. return false;
  1000. case QualType::DK_cxx_destructor:
  1001. case QualType::DK_objc_weak_lifetime:
  1002. return getLangOpts().Exceptions;
  1003. case QualType::DK_objc_strong_lifetime:
  1004. return getLangOpts().Exceptions &&
  1005. CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
  1006. }
  1007. llvm_unreachable("bad destruction kind");
  1008. }
  1009. CleanupKind getCleanupKind(QualType::DestructionKind kind) {
  1010. return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
  1011. }
  1012. //===--------------------------------------------------------------------===//
  1013. // Objective-C
  1014. //===--------------------------------------------------------------------===//
  1015. void GenerateObjCMethod(const ObjCMethodDecl *OMD);
  1016. void StartObjCMethod(const ObjCMethodDecl *MD, const ObjCContainerDecl *CD);
  1017. /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
  1018. void GenerateObjCGetter(ObjCImplementationDecl *IMP,
  1019. const ObjCPropertyImplDecl *PID);
  1020. void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
  1021. const ObjCPropertyImplDecl *propImpl,
  1022. const ObjCMethodDecl *GetterMothodDecl,
  1023. llvm::Constant *AtomicHelperFn);
  1024. void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
  1025. ObjCMethodDecl *MD, bool ctor);
  1026. /// GenerateObjCSetter - Synthesize an Objective-C property setter function
  1027. /// for the given property.
  1028. void GenerateObjCSetter(ObjCImplementationDecl *IMP,
  1029. const ObjCPropertyImplDecl *PID);
  1030. void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
  1031. const ObjCPropertyImplDecl *propImpl,
  1032. llvm::Constant *AtomicHelperFn);
  1033. bool IndirectObjCSetterArg(const CGFunctionInfo &FI);
  1034. bool IvarTypeWithAggrGCObjects(QualType Ty);
  1035. //===--------------------------------------------------------------------===//
  1036. // Block Bits
  1037. //===--------------------------------------------------------------------===//
  1038. llvm::Value *EmitBlockLiteral(const BlockExpr *);
  1039. llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
  1040. static void destroyBlockInfos(CGBlockInfo *info);
  1041. llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
  1042. const CGBlockInfo &Info,
  1043. llvm::StructType *,
  1044. llvm::Constant *BlockVarLayout);
  1045. llvm::Function *GenerateBlockFunction(GlobalDecl GD,
  1046. const CGBlockInfo &Info,
  1047. const DeclMapTy &ldm,
  1048. bool IsLambdaConversionToBlock);
  1049. llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
  1050. llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
  1051. llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
  1052. const ObjCPropertyImplDecl *PID);
  1053. llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
  1054. const ObjCPropertyImplDecl *PID);
  1055. llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
  1056. void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
  1057. class AutoVarEmission;
  1058. void emitByrefStructureInit(const AutoVarEmission &emission);
  1059. void enterByrefCleanup(const AutoVarEmission &emission);
  1060. llvm::Value *LoadBlockStruct() {
  1061. assert(BlockPointer && "no block pointer set!");
  1062. return BlockPointer;
  1063. }
  1064. void AllocateBlockCXXThisPointer(const CXXThisExpr *E);
  1065. void AllocateBlockDecl(const DeclRefExpr *E);
  1066. llvm::Value *GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
  1067. llvm::Type *BuildByRefType(const VarDecl *var);
  1068. void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  1069. const CGFunctionInfo &FnInfo);
  1070. /// \brief Emit code for the start of a function.
  1071. /// \param Loc The location to be associated with the function.
  1072. /// \param StartLoc The location of the function body.
  1073. void StartFunction(GlobalDecl GD,
  1074. QualType RetTy,
  1075. llvm::Function *Fn,
  1076. const CGFunctionInfo &FnInfo,
  1077. const FunctionArgList &Args,
  1078. SourceLocation Loc = SourceLocation(),
  1079. SourceLocation StartLoc = SourceLocation());
  1080. void EmitConstructorBody(FunctionArgList &Args);
  1081. void EmitDestructorBody(FunctionArgList &Args);
  1082. void emitImplicitAssignmentOperatorBody(FunctionArgList &Args);
  1083. void EmitFunctionBody(FunctionArgList &Args, const Stmt *Body);
  1084. void EmitBlockWithFallThrough(llvm::BasicBlock *BB, const Stmt *S);
  1085. void EmitForwardingCallToLambda(const CXXMethodDecl *LambdaCallOperator,
  1086. CallArgList &CallArgs);
  1087. void EmitLambdaToBlockPointerBody(FunctionArgList &Args);
  1088. void EmitLambdaBlockInvokeBody();
  1089. void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
  1090. void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD);
  1091. void EmitAsanPrologueOrEpilogue(bool Prologue);
  1092. /// \brief Emit the unified return block, trying to avoid its emission when
  1093. /// possible.
  1094. /// \return The debug location of the user written return statement if the
  1095. /// return block is is avoided.
  1096. llvm::DebugLoc EmitReturnBlock();
  1097. /// FinishFunction - Complete IR generation of the current function. It is
  1098. /// legal to call this function even if there is no current insertion point.
  1099. void FinishFunction(SourceLocation EndLoc=SourceLocation());
  1100. void StartThunk(llvm::Function *Fn, GlobalDecl GD,
  1101. const CGFunctionInfo &FnInfo);
  1102. void EmitCallAndReturnForThunk(llvm::Value *Callee, const ThunkInfo *Thunk);
  1103. /// Emit a musttail call for a thunk with a potentially adjusted this pointer.
  1104. void EmitMustTailThunk(const CXXMethodDecl *MD, llvm::Value *AdjustedThisPtr,
  1105. llvm::Value *Callee);
  1106. /// Generate a thunk for the given method.
  1107. void generateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
  1108. GlobalDecl GD, const ThunkInfo &Thunk);
  1109. llvm::Function *GenerateVarArgsThunk(llvm::Function *Fn,
  1110. const CGFunctionInfo &FnInfo,
  1111. GlobalDecl GD, const ThunkInfo &Thunk);
  1112. void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
  1113. FunctionArgList &Args);
  1114. void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init,
  1115. ArrayRef<VarDecl *> ArrayIndexes);
  1116. /// InitializeVTablePointer - Initialize the vtable pointer of the given
  1117. /// subobject.
  1118. ///
  1119. void InitializeVTablePointer(BaseSubobject Base,
  1120. const CXXRecordDecl *NearestVBase,
  1121. CharUnits OffsetFromNearestVBase,
  1122. const CXXRecordDecl *VTableClass);
  1123. typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
  1124. void InitializeVTablePointers(BaseSubobject Base,
  1125. const CXXRecordDecl *NearestVBase,
  1126. CharUnits OffsetFromNearestVBase,
  1127. bool BaseIsNonVirtualPrimaryBase,
  1128. const CXXRecordDecl *VTableClass,
  1129. VisitedVirtualBasesSetTy& VBases);
  1130. void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
  1131. /// GetVTablePtr - Return the Value of the vtable pointer member pointed
  1132. /// to by This.
  1133. llvm::Value *GetVTablePtr(llvm::Value *This, llvm::Type *Ty);
  1134. enum CFITypeCheckKind {
  1135. CFITCK_VCall,
  1136. CFITCK_NVCall,
  1137. CFITCK_DerivedCast,
  1138. CFITCK_UnrelatedCast,
  1139. };
  1140. /// \brief Derived is the presumed address of an object of type T after a
  1141. /// cast. If T is a polymorphic class type, emit a check that the virtual
  1142. /// table for Derived belongs to a class derived from T.
  1143. void EmitVTablePtrCheckForCast(QualType T, llvm::Value *Derived,
  1144. bool MayBeNull, CFITypeCheckKind TCK,
  1145. SourceLocation Loc);
  1146. /// EmitVTablePtrCheckForCall - Virtual method MD is being called via VTable.
  1147. /// If vptr CFI is enabled, emit a check that VTable is valid.
  1148. void EmitVTablePtrCheckForCall(const CXXMethodDecl *MD, llvm::Value *VTable,
  1149. CFITypeCheckKind TCK, SourceLocation Loc);
  1150. /// EmitVTablePtrCheck - Emit a check that VTable is a valid virtual table for
  1151. /// RD using llvm.bitset.test.
  1152. void EmitVTablePtrCheck(const CXXRecordDecl *RD, llvm::Value *VTable,
  1153. CFITypeCheckKind TCK, SourceLocation Loc);
  1154. /// CanDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given
  1155. /// expr can be devirtualized.
  1156. bool CanDevirtualizeMemberFunctionCall(const Expr *Base,
  1157. const CXXMethodDecl *MD);
  1158. /// EnterDtorCleanups - Enter the cleanups necessary to complete the
  1159. /// given phase of destruction for a destructor. The end result
  1160. /// should call destructors on members and base classes in reverse
  1161. /// order of their construction.
  1162. void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
  1163. /// ShouldInstrumentFunction - Return true if the current function should be
  1164. /// instrumented with __cyg_profile_func_* calls
  1165. bool ShouldInstrumentFunction();
  1166. /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
  1167. /// instrumentation function with the current function and the call site, if
  1168. /// function instrumentation is enabled.
  1169. void EmitFunctionInstrumentation(const char *Fn);
  1170. /// EmitMCountInstrumentation - Emit call to .mcount.
  1171. void EmitMCountInstrumentation();
  1172. /// EmitFunctionProlog - Emit the target specific LLVM code to load the
  1173. /// arguments for the given function. This is also responsible for naming the
  1174. /// LLVM function arguments.
  1175. void EmitFunctionProlog(const CGFunctionInfo &FI,
  1176. llvm::Function *Fn,
  1177. const FunctionArgList &Args);
  1178. /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
  1179. /// given temporary.
  1180. void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc,
  1181. SourceLocation EndLoc);
  1182. /// EmitStartEHSpec - Emit the start of the exception spec.
  1183. void EmitStartEHSpec(const Decl *D);
  1184. /// EmitEndEHSpec - Emit the end of the exception spec.
  1185. void EmitEndEHSpec(const Decl *D);
  1186. /// getTerminateLandingPad - Return a landing pad that just calls terminate.
  1187. llvm::BasicBlock *getTerminateLandingPad();
  1188. /// getTerminateHandler - Return a handler (not a landing pad, just
  1189. /// a catch handler) that just calls terminate. This is used when
  1190. /// a terminate scope encloses a try.
  1191. llvm::BasicBlock *getTerminateHandler();
  1192. llvm::Type *ConvertTypeForMem(QualType T);
  1193. llvm::Type *ConvertType(QualType T);
  1194. llvm::Type *ConvertType(const TypeDecl *T) {
  1195. return ConvertType(getContext().getTypeDeclType(T));
  1196. }
  1197. /// LoadObjCSelf - Load the value of self. This function is only valid while
  1198. /// generating code for an Objective-C method.
  1199. llvm::Value *LoadObjCSelf();
  1200. /// TypeOfSelfObject - Return type of object that this self represents.
  1201. QualType TypeOfSelfObject();
  1202. /// hasAggregateLLVMType - Return true if the specified AST type will map into
  1203. /// an aggregate LLVM type or is void.
  1204. static TypeEvaluationKind getEvaluationKind(QualType T);
  1205. static bool hasScalarEvaluationKind(QualType T) {
  1206. return getEvaluationKind(T) == TEK_Scalar;
  1207. }
  1208. static bool hasAggregateEvaluationKind(QualType T) {
  1209. return getEvaluationKind(T) == TEK_Aggregate;
  1210. }
  1211. /// createBasicBlock - Create an LLVM basic block.
  1212. llvm::BasicBlock *createBasicBlock(const Twine &name = "",
  1213. llvm::Function *parent = nullptr,
  1214. llvm::BasicBlock *before = nullptr) {
  1215. #ifdef NDEBUG
  1216. return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
  1217. #else
  1218. return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
  1219. #endif
  1220. }
  1221. /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
  1222. /// label maps to.
  1223. JumpDest getJumpDestForLabel(const LabelDecl *S);
  1224. /// SimplifyForwardingBlocks - If the given basic block is only a branch to
  1225. /// another basic block, simplify it. This assumes that no other code could
  1226. /// potentially reference the basic block.
  1227. void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
  1228. /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
  1229. /// adding a fall-through branch from the current insert block if
  1230. /// necessary. It is legal to call this function even if there is no current
  1231. /// insertion point.
  1232. ///
  1233. /// IsFinished - If true, indicates that the caller has finished emitting
  1234. /// branches to the given block and does not expect to emit code into it. This
  1235. /// means the block can be ignored if it is unreachable.
  1236. void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
  1237. /// EmitBlockAfterUses - Emit the given block somewhere hopefully
  1238. /// near its uses, and leave the insertion point in it.
  1239. void EmitBlockAfterUses(llvm::BasicBlock *BB);
  1240. /// EmitBranch - Emit a branch to the specified basic block from the current
  1241. /// insert block, taking care to avoid creation of branches from dummy
  1242. /// blocks. It is legal to call this function even if there is no current
  1243. /// insertion point.
  1244. ///
  1245. /// This function clears the current insertion point. The caller should follow
  1246. /// calls to this function with calls to Emit*Block prior to generation new
  1247. /// code.
  1248. void EmitBranch(llvm::BasicBlock *Block);
  1249. /// HaveInsertPoint - True if an insertion point is defined. If not, this
  1250. /// indicates that the current code being emitted is unreachable.
  1251. bool HaveInsertPoint() const {
  1252. return Builder.GetInsertBlock() != nullptr;
  1253. }
  1254. /// EnsureInsertPoint - Ensure that an insertion point is defined so that
  1255. /// emitted IR has a place to go. Note that by definition, if this function
  1256. /// creates a block then that block is unreachable; callers may do better to
  1257. /// detect when no insertion point is defined and simply skip IR generation.
  1258. void EnsureInsertPoint() {
  1259. if (!HaveInsertPoint())
  1260. EmitBlock(createBasicBlock());
  1261. }
  1262. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1263. /// specified stmt yet.
  1264. void ErrorUnsupported(const Stmt *S, const char *Type);
  1265. //===--------------------------------------------------------------------===//
  1266. // Helpers
  1267. //===--------------------------------------------------------------------===//
  1268. LValue MakeAddrLValue(llvm::Value *V, QualType T,
  1269. CharUnits Alignment = CharUnits()) {
  1270. return LValue::MakeAddr(V, T, Alignment, getContext(),
  1271. CGM.getTBAAInfo(T));
  1272. }
  1273. LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T);
  1274. /// CreateTempAlloca - This creates a alloca and inserts it into the entry
  1275. /// block. The caller is responsible for setting an appropriate alignment on
  1276. /// the alloca.
  1277. llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
  1278. const Twine &Name = "tmp");
  1279. /// InitTempAlloca - Provide an initial value for the given alloca.
  1280. void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value);
  1281. /// CreateIRTemp - Create a temporary IR object of the given type, with
  1282. /// appropriate alignment. This routine should only be used when an temporary
  1283. /// value needs to be stored into an alloca (for example, to avoid explicit
  1284. /// PHI construction), but the type is the IR type, not the type appropriate
  1285. /// for storing in memory.
  1286. llvm::AllocaInst *CreateIRTemp(QualType T, const Twine &Name = "tmp");
  1287. /// CreateMemTemp - Create a temporary memory object of the given type, with
  1288. /// appropriate alignment.
  1289. llvm::AllocaInst *CreateMemTemp(QualType T, const Twine &Name = "tmp");
  1290. /// CreateAggTemp - Create a temporary memory object for the given
  1291. /// aggregate type.
  1292. AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
  1293. CharUnits Alignment = getContext().getTypeAlignInChars(T);
  1294. return AggValueSlot::forAddr(CreateMemTemp(T, Name), Alignment,
  1295. T.getQualifiers(),
  1296. AggValueSlot::IsNotDestructed,
  1297. AggValueSlot::DoesNotNeedGCBarriers,
  1298. AggValueSlot::IsNotAliased);
  1299. }
  1300. /// CreateInAllocaTmp - Create a temporary memory object for the given
  1301. /// aggregate type.
  1302. AggValueSlot CreateInAllocaTmp(QualType T, const Twine &Name = "inalloca");
  1303. /// Emit a cast to void* in the appropriate address space.
  1304. llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
  1305. /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
  1306. /// expression and compare the result against zero, returning an Int1Ty value.
  1307. llvm::Value *EvaluateExprAsBool(const Expr *E);
  1308. /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
  1309. void EmitIgnoredExpr(const Expr *E);
  1310. /// EmitAnyExpr - Emit code to compute the specified expression which can have
  1311. /// any type. The result is returned as an RValue struct. If this is an
  1312. /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
  1313. /// the result should be returned.
  1314. ///
  1315. /// \param ignoreResult True if the resulting value isn't used.
  1316. RValue EmitAnyExpr(const Expr *E,
  1317. AggValueSlot aggSlot = AggValueSlot::ignored(),
  1318. bool ignoreResult = false);
  1319. // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
  1320. // or the value of the expression, depending on how va_list is defined.
  1321. llvm::Value *EmitVAListRef(const Expr *E);
  1322. /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
  1323. /// always be accessible even if no aggregate location is provided.
  1324. RValue EmitAnyExprToTemp(const Expr *E);
  1325. /// EmitAnyExprToMem - Emits the code necessary to evaluate an
  1326. /// arbitrary expression into the given memory location.
  1327. void EmitAnyExprToMem(const Expr *E, llvm::Value *Location,
  1328. Qualifiers Quals, bool IsInitializer);
  1329. void EmitAnyExprToExn(const Expr *E, llvm::Value *Addr);
  1330. /// EmitExprAsInit - Emits the code necessary to initialize a
  1331. /// location in memory with the given initializer.
  1332. void EmitExprAsInit(const Expr *init, const ValueDecl *D, LValue lvalue,
  1333. bool capturedByInit);
  1334. /// hasVolatileMember - returns true if aggregate type has a volatile
  1335. /// member.
  1336. bool hasVolatileMember(QualType T) {
  1337. if (const RecordType *RT = T->getAs<RecordType>()) {
  1338. const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
  1339. return RD->hasVolatileMember();
  1340. }
  1341. return false;
  1342. }
  1343. /// EmitAggregateCopy - Emit an aggregate assignment.
  1344. ///
  1345. /// The difference to EmitAggregateCopy is that tail padding is not copied.
  1346. /// This is required for correctness when assigning non-POD structures in C++.
  1347. void EmitAggregateAssign(llvm::Value *DestPtr, llvm::Value *SrcPtr,
  1348. QualType EltTy) {
  1349. bool IsVolatile = hasVolatileMember(EltTy);
  1350. EmitAggregateCopy(DestPtr, SrcPtr, EltTy, IsVolatile, CharUnits::Zero(),
  1351. true);
  1352. }
  1353. void EmitAggregateCopyCtor(llvm::Value *DestPtr, llvm::Value *SrcPtr,
  1354. QualType DestTy, QualType SrcTy) {
  1355. CharUnits DestTypeAlign = getContext().getTypeAlignInChars(DestTy);
  1356. CharUnits SrcTypeAlign = getContext().getTypeAlignInChars(SrcTy);
  1357. EmitAggregateCopy(DestPtr, SrcPtr, SrcTy, /*IsVolatile=*/false,
  1358. std::min(DestTypeAlign, SrcTypeAlign),
  1359. /*IsAssignment=*/false);
  1360. }
  1361. /// EmitAggregateCopy - Emit an aggregate copy.
  1362. ///
  1363. /// \param isVolatile - True iff either the source or the destination is
  1364. /// volatile.
  1365. /// \param isAssignment - If false, allow padding to be copied. This often
  1366. /// yields more efficient.
  1367. void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
  1368. QualType EltTy, bool isVolatile=false,
  1369. CharUnits Alignment = CharUnits::Zero(),
  1370. bool isAssignment = false);
  1371. /// StartBlock - Start new block named N. If insert block is a dummy block
  1372. /// then reuse it.
  1373. void StartBlock(const char *N);
  1374. /// GetAddrOfLocalVar - Return the address of a local variable.
  1375. llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) {
  1376. llvm::Value *Res = LocalDeclMap[VD];
  1377. assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
  1378. return Res;
  1379. }
  1380. /// getOpaqueLValueMapping - Given an opaque value expression (which
  1381. /// must be mapped to an l-value), return its mapping.
  1382. const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
  1383. assert(OpaqueValueMapping::shouldBindAsLValue(e));
  1384. llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
  1385. it = OpaqueLValues.find(e);
  1386. assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
  1387. return it->second;
  1388. }
  1389. /// getOpaqueRValueMapping - Given an opaque value expression (which
  1390. /// must be mapped to an r-value), return its mapping.
  1391. const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
  1392. assert(!OpaqueValueMapping::shouldBindAsLValue(e));
  1393. llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
  1394. it = OpaqueRValues.find(e);
  1395. assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
  1396. return it->second;
  1397. }
  1398. /// getAccessedFieldNo - Given an encoded value and a result number, return
  1399. /// the input field number being accessed.
  1400. static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
  1401. llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
  1402. llvm::BasicBlock *GetIndirectGotoBlock();
  1403. /// EmitNullInitialization - Generate code to set a value of the given type to
  1404. /// null, If the type contains data member pointers, they will be initialized
  1405. /// to -1 in accordance with the Itanium C++ ABI.
  1406. void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty);
  1407. // EmitVAArg - Generate code to get an argument from the passed in pointer
  1408. // and update it accordingly. The return value is a pointer to the argument.
  1409. // FIXME: We should be able to get rid of this method and use the va_arg
  1410. // instruction in LLVM instead once it works well enough.
  1411. llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
  1412. /// emitArrayLength - Compute the length of an array, even if it's a
  1413. /// VLA, and drill down to the base element type.
  1414. llvm::Value *emitArrayLength(const ArrayType *arrayType,
  1415. QualType &baseType,
  1416. llvm::Value *&addr);
  1417. /// EmitVLASize - Capture all the sizes for the VLA expressions in
  1418. /// the given variably-modified type and store them in the VLASizeMap.
  1419. ///
  1420. /// This function can be called with a null (unreachable) insert point.
  1421. void EmitVariablyModifiedType(QualType Ty);
  1422. /// getVLASize - Returns an LLVM value that corresponds to the size,
  1423. /// in non-variably-sized elements, of a variable length array type,
  1424. /// plus that largest non-variably-sized element type. Assumes that
  1425. /// the type has already been emitted with EmitVariablyModifiedType.
  1426. std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
  1427. std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
  1428. /// LoadCXXThis - Load the value of 'this'. This function is only valid while
  1429. /// generating code for an C++ member function.
  1430. llvm::Value *LoadCXXThis() {
  1431. assert(CXXThisValue && "no 'this' value for this function");
  1432. return CXXThisValue;
  1433. }
  1434. /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
  1435. /// virtual bases.
  1436. // FIXME: Every place that calls LoadCXXVTT is something
  1437. // that needs to be abstracted properly.
  1438. llvm::Value *LoadCXXVTT() {
  1439. assert(CXXStructorImplicitParamValue && "no VTT value for this function");
  1440. return CXXStructorImplicitParamValue;
  1441. }
  1442. /// LoadCXXStructorImplicitParam - Load the implicit parameter
  1443. /// for a constructor/destructor.
  1444. llvm::Value *LoadCXXStructorImplicitParam() {
  1445. assert(CXXStructorImplicitParamValue &&
  1446. "no implicit argument value for this function");
  1447. return CXXStructorImplicitParamValue;
  1448. }
  1449. /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
  1450. /// complete class to the given direct base.
  1451. llvm::Value *
  1452. GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value,
  1453. const CXXRecordDecl *Derived,
  1454. const CXXRecordDecl *Base,
  1455. bool BaseIsVirtual);
  1456. /// GetAddressOfBaseClass - This function will add the necessary delta to the
  1457. /// load of 'this' and returns address of the base class.
  1458. llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
  1459. const CXXRecordDecl *Derived,
  1460. CastExpr::path_const_iterator PathBegin,
  1461. CastExpr::path_const_iterator PathEnd,
  1462. bool NullCheckValue, SourceLocation Loc);
  1463. llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
  1464. const CXXRecordDecl *Derived,
  1465. CastExpr::path_const_iterator PathBegin,
  1466. CastExpr::path_const_iterator PathEnd,
  1467. bool NullCheckValue);
  1468. /// GetVTTParameter - Return the VTT parameter that should be passed to a
  1469. /// base constructor/destructor with virtual bases.
  1470. /// FIXME: VTTs are Itanium ABI-specific, so the definition should move
  1471. /// to ItaniumCXXABI.cpp together with all the references to VTT.
  1472. llvm::Value *GetVTTParameter(GlobalDecl GD, bool ForVirtualBase,
  1473. bool Delegating);
  1474. void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1475. CXXCtorType CtorType,
  1476. const FunctionArgList &Args,
  1477. SourceLocation Loc);
  1478. // It's important not to confuse this and the previous function. Delegating
  1479. // constructors are the C++0x feature. The constructor delegate optimization
  1480. // is used to reduce duplication in the base and complete consturctors where
  1481. // they are substantially the same.
  1482. void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1483. const FunctionArgList &Args);
  1484. void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
  1485. bool ForVirtualBase, bool Delegating,
  1486. llvm::Value *This, const CXXConstructExpr *E);
  1487. void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  1488. llvm::Value *This, llvm::Value *Src,
  1489. const CXXConstructExpr *E);
  1490. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  1491. const ConstantArrayType *ArrayTy,
  1492. llvm::Value *ArrayPtr,
  1493. const CXXConstructExpr *E,
  1494. bool ZeroInitialization = false);
  1495. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  1496. llvm::Value *NumElements,
  1497. llvm::Value *ArrayPtr,
  1498. const CXXConstructExpr *E,
  1499. bool ZeroInitialization = false);
  1500. static Destroyer destroyCXXObject;
  1501. void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
  1502. bool ForVirtualBase, bool Delegating,
  1503. llvm::Value *This);
  1504. void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
  1505. llvm::Type *ElementTy, llvm::Value *NewPtr,
  1506. llvm::Value *NumElements,
  1507. llvm::Value *AllocSizeWithoutCookie);
  1508. void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
  1509. llvm::Value *Ptr);
  1510. llvm::Value *EmitLifetimeStart(uint64_t Size, llvm::Value *Addr);
  1511. void EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr);
  1512. llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
  1513. void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
  1514. void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
  1515. QualType DeleteTy);
  1516. RValue EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
  1517. const Expr *Arg, bool IsDelete);
  1518. llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
  1519. llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
  1520. llvm::Value* EmitCXXUuidofExpr(const CXXUuidofExpr *E);
  1521. /// \brief Situations in which we might emit a check for the suitability of a
  1522. /// pointer or glvalue.
  1523. enum TypeCheckKind {
  1524. /// Checking the operand of a load. Must be suitably sized and aligned.
  1525. TCK_Load,
  1526. /// Checking the destination of a store. Must be suitably sized and aligned.
  1527. TCK_Store,
  1528. /// Checking the bound value in a reference binding. Must be suitably sized
  1529. /// and aligned, but is not required to refer to an object (until the
  1530. /// reference is used), per core issue 453.
  1531. TCK_ReferenceBinding,
  1532. /// Checking the object expression in a non-static data member access. Must
  1533. /// be an object within its lifetime.
  1534. TCK_MemberAccess,
  1535. /// Checking the 'this' pointer for a call to a non-static member function.
  1536. /// Must be an object within its lifetime.
  1537. TCK_MemberCall,
  1538. /// Checking the 'this' pointer for a constructor call.
  1539. TCK_ConstructorCall,
  1540. /// Checking the operand of a static_cast to a derived pointer type. Must be
  1541. /// null or an object within its lifetime.
  1542. TCK_DowncastPointer,
  1543. /// Checking the operand of a static_cast to a derived reference type. Must
  1544. /// be an object within its lifetime.
  1545. TCK_DowncastReference,
  1546. /// Checking the operand of a cast to a base object. Must be suitably sized
  1547. /// and aligned.
  1548. TCK_Upcast,
  1549. /// Checking the operand of a cast to a virtual base object. Must be an
  1550. /// object within its lifetime.
  1551. TCK_UpcastToVirtualBase
  1552. };
  1553. /// \brief Whether any type-checking sanitizers are enabled. If \c false,
  1554. /// calls to EmitTypeCheck can be skipped.
  1555. bool sanitizePerformTypeCheck() const;
  1556. /// \brief Emit a check that \p V is the address of storage of the
  1557. /// appropriate size and alignment for an object of type \p Type.
  1558. void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, llvm::Value *V,
  1559. QualType Type, CharUnits Alignment = CharUnits::Zero(),
  1560. bool SkipNullCheck = false);
  1561. /// \brief Emit a check that \p Base points into an array object, which
  1562. /// we can access at index \p Index. \p Accessed should be \c false if we
  1563. /// this expression is used as an lvalue, for instance in "&Arr[Idx]".
  1564. void EmitBoundsCheck(const Expr *E, const Expr *Base, llvm::Value *Index,
  1565. QualType IndexType, bool Accessed);
  1566. llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  1567. bool isInc, bool isPre);
  1568. ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
  1569. bool isInc, bool isPre);
  1570. void EmitAlignmentAssumption(llvm::Value *PtrValue, unsigned Alignment,
  1571. llvm::Value *OffsetValue = nullptr) {
  1572. Builder.CreateAlignmentAssumption(CGM.getDataLayout(), PtrValue, Alignment,
  1573. OffsetValue);
  1574. }
  1575. //===--------------------------------------------------------------------===//
  1576. // Declaration Emission
  1577. //===--------------------------------------------------------------------===//
  1578. /// EmitDecl - Emit a declaration.
  1579. ///
  1580. /// This function can be called with a null (unreachable) insert point.
  1581. void EmitDecl(const Decl &D);
  1582. /// EmitVarDecl - Emit a local variable declaration.
  1583. ///
  1584. /// This function can be called with a null (unreachable) insert point.
  1585. void EmitVarDecl(const VarDecl &D);
  1586. void EmitScalarInit(const Expr *init, const ValueDecl *D, LValue lvalue,
  1587. bool capturedByInit);
  1588. void EmitScalarInit(llvm::Value *init, LValue lvalue);
  1589. typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
  1590. llvm::Value *Address);
  1591. /// \brief Determine whether the given initializer is trivial in the sense
  1592. /// that it requires no code to be generated.
  1593. bool isTrivialInitializer(const Expr *Init);
  1594. /// EmitAutoVarDecl - Emit an auto variable declaration.
  1595. ///
  1596. /// This function can be called with a null (unreachable) insert point.
  1597. void EmitAutoVarDecl(const VarDecl &D);
  1598. class AutoVarEmission {
  1599. friend class CodeGenFunction;
  1600. const VarDecl *Variable;
  1601. /// The alignment of the variable.
  1602. CharUnits Alignment;
  1603. /// The address of the alloca. Null if the variable was emitted
  1604. /// as a global constant.
  1605. llvm::Value *Address;
  1606. llvm::Value *NRVOFlag;
  1607. /// True if the variable is a __block variable.
  1608. bool IsByRef;
  1609. /// True if the variable is of aggregate type and has a constant
  1610. /// initializer.
  1611. bool IsConstantAggregate;
  1612. /// Non-null if we should use lifetime annotations.
  1613. llvm::Value *SizeForLifetimeMarkers;
  1614. struct Invalid {};
  1615. AutoVarEmission(Invalid) : Variable(nullptr) {}
  1616. AutoVarEmission(const VarDecl &variable)
  1617. : Variable(&variable), Address(nullptr), NRVOFlag(nullptr),
  1618. IsByRef(false), IsConstantAggregate(false),
  1619. SizeForLifetimeMarkers(nullptr) {}
  1620. bool wasEmittedAsGlobal() const { return Address == nullptr; }
  1621. public:
  1622. static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
  1623. bool useLifetimeMarkers() const {
  1624. return SizeForLifetimeMarkers != nullptr;
  1625. }
  1626. llvm::Value *getSizeForLifetimeMarkers() const {
  1627. assert(useLifetimeMarkers());
  1628. return SizeForLifetimeMarkers;
  1629. }
  1630. /// Returns the raw, allocated address, which is not necessarily
  1631. /// the address of the object itself.
  1632. llvm::Value *getAllocatedAddress() const {
  1633. return Address;
  1634. }
  1635. /// Returns the address of the object within this declaration.
  1636. /// Note that this does not chase the forwarding pointer for
  1637. /// __block decls.
  1638. llvm::Value *getObjectAddress(CodeGenFunction &CGF) const {
  1639. if (!IsByRef) return Address;
  1640. auto F = CGF.getByRefValueLLVMField(Variable);
  1641. return CGF.Builder.CreateStructGEP(F.first, Address, F.second,
  1642. Variable->getNameAsString());
  1643. }
  1644. };
  1645. AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
  1646. void EmitAutoVarInit(const AutoVarEmission &emission);
  1647. void EmitAutoVarCleanups(const AutoVarEmission &emission);
  1648. void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
  1649. QualType::DestructionKind dtorKind);
  1650. void EmitStaticVarDecl(const VarDecl &D,
  1651. llvm::GlobalValue::LinkageTypes Linkage);
  1652. /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
  1653. void EmitParmDecl(const VarDecl &D, llvm::Value *Arg, bool ArgIsPointer,
  1654. unsigned ArgNo);
  1655. /// protectFromPeepholes - Protect a value that we're intending to
  1656. /// store to the side, but which will probably be used later, from
  1657. /// aggressive peepholing optimizations that might delete it.
  1658. ///
  1659. /// Pass the result to unprotectFromPeepholes to declare that
  1660. /// protection is no longer required.
  1661. ///
  1662. /// There's no particular reason why this shouldn't apply to
  1663. /// l-values, it's just that no existing peepholes work on pointers.
  1664. PeepholeProtection protectFromPeepholes(RValue rvalue);
  1665. void unprotectFromPeepholes(PeepholeProtection protection);
  1666. //===--------------------------------------------------------------------===//
  1667. // Statement Emission
  1668. //===--------------------------------------------------------------------===//
  1669. /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
  1670. void EmitStopPoint(const Stmt *S);
  1671. /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
  1672. /// this function even if there is no current insertion point.
  1673. ///
  1674. /// This function may clear the current insertion point; callers should use
  1675. /// EnsureInsertPoint if they wish to subsequently generate code without first
  1676. /// calling EmitBlock, EmitBranch, or EmitStmt.
  1677. void EmitStmt(const Stmt *S);
  1678. /// EmitSimpleStmt - Try to emit a "simple" statement which does not
  1679. /// necessarily require an insertion point or debug information; typically
  1680. /// because the statement amounts to a jump or a container of other
  1681. /// statements.
  1682. ///
  1683. /// \return True if the statement was handled.
  1684. bool EmitSimpleStmt(const Stmt *S);
  1685. llvm::Value *EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
  1686. AggValueSlot AVS = AggValueSlot::ignored());
  1687. llvm::Value *EmitCompoundStmtWithoutScope(const CompoundStmt &S,
  1688. bool GetLast = false,
  1689. AggValueSlot AVS =
  1690. AggValueSlot::ignored());
  1691. /// EmitLabel - Emit the block for the given label. It is legal to call this
  1692. /// function even if there is no current insertion point.
  1693. void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
  1694. void EmitLabelStmt(const LabelStmt &S);
  1695. void EmitAttributedStmt(const AttributedStmt &S);
  1696. void EmitGotoStmt(const GotoStmt &S);
  1697. void EmitDiscardStmt(const DiscardStmt &S); // HLSL Change
  1698. void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
  1699. void EmitIfStmt(const IfStmt &S,
  1700. ArrayRef<const Attr *> Attrs = None); // HLSL Change
  1701. void EmitCondBrHints(llvm::LLVMContext &Context, llvm::BranchInst *CondBr,
  1702. ArrayRef<const Attr *> Attrs);
  1703. void EmitWhileStmt(const WhileStmt &S,
  1704. ArrayRef<const Attr *> Attrs = None);
  1705. void EmitDoStmt(const DoStmt &S, ArrayRef<const Attr *> Attrs = None);
  1706. void EmitForStmt(const ForStmt &S,
  1707. ArrayRef<const Attr *> Attrs = None);
  1708. void EmitReturnStmt(const ReturnStmt &S);
  1709. void EmitDeclStmt(const DeclStmt &S);
  1710. void EmitBreakStmt(const BreakStmt &S);
  1711. void EmitContinueStmt(const ContinueStmt &S);
  1712. void EmitSwitchStmt(const SwitchStmt &S,
  1713. ArrayRef<const Attr *> Attrs = None); // HLSL Change
  1714. void EmitDefaultStmt(const DefaultStmt &S);
  1715. void EmitCaseStmt(const CaseStmt &S);
  1716. void EmitCaseStmtRange(const CaseStmt &S);
  1717. void EmitAsmStmt(const AsmStmt &S);
  1718. void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
  1719. void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
  1720. void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
  1721. void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
  1722. void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
  1723. void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  1724. void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  1725. void EmitCXXTryStmt(const CXXTryStmt &S);
  1726. void EmitSEHTryStmt(const SEHTryStmt &S);
  1727. void EmitSEHLeaveStmt(const SEHLeaveStmt &S);
  1728. void EnterSEHTryStmt(const SEHTryStmt &S);
  1729. void ExitSEHTryStmt(const SEHTryStmt &S);
  1730. void startOutlinedSEHHelper(CodeGenFunction &ParentCGF, bool IsFilter,
  1731. const Stmt *OutlinedStmt);
  1732. llvm::Function *GenerateSEHFilterFunction(CodeGenFunction &ParentCGF,
  1733. const SEHExceptStmt &Except);
  1734. llvm::Function *GenerateSEHFinallyFunction(CodeGenFunction &ParentCGF,
  1735. const SEHFinallyStmt &Finally);
  1736. void EmitSEHExceptionCodeSave(CodeGenFunction &ParentCGF,
  1737. llvm::Value *ParentFP,
  1738. llvm::Value *EntryEBP);
  1739. llvm::Value *EmitSEHExceptionCode();
  1740. llvm::Value *EmitSEHExceptionInfo();
  1741. llvm::Value *EmitSEHAbnormalTermination();
  1742. /// Scan the outlined statement for captures from the parent function. For
  1743. /// each capture, mark the capture as escaped and emit a call to
  1744. /// llvm.localrecover. Insert the localrecover result into the LocalDeclMap.
  1745. void EmitCapturedLocals(CodeGenFunction &ParentCGF, const Stmt *OutlinedStmt,
  1746. bool IsFilter);
  1747. /// Recovers the address of a local in a parent function. ParentVar is the
  1748. /// address of the variable used in the immediate parent function. It can
  1749. /// either be an alloca or a call to llvm.localrecover if there are nested
  1750. /// outlined functions. ParentFP is the frame pointer of the outermost parent
  1751. /// frame.
  1752. llvm::Value *recoverAddrOfEscapedLocal(CodeGenFunction &ParentCGF,
  1753. llvm::Value *ParentVar,
  1754. llvm::Value *ParentFP);
  1755. void EmitCXXForRangeStmt(const CXXForRangeStmt &S,
  1756. ArrayRef<const Attr *> Attrs = None);
  1757. LValue InitCapturedStruct(const CapturedStmt &S);
  1758. llvm::Function *EmitCapturedStmt(const CapturedStmt &S, CapturedRegionKind K);
  1759. void GenerateCapturedStmtFunctionProlog(const CapturedStmt &S);
  1760. llvm::Function *GenerateCapturedStmtFunctionEpilog(const CapturedStmt &S);
  1761. llvm::Function *GenerateCapturedStmtFunction(const CapturedStmt &S);
  1762. llvm::Value *GenerateCapturedStmtArgument(const CapturedStmt &S);
  1763. /// \brief Perform element by element copying of arrays with type \a
  1764. /// OriginalType from \a SrcAddr to \a DestAddr using copying procedure
  1765. /// generated by \a CopyGen.
  1766. ///
  1767. /// \param DestAddr Address of the destination array.
  1768. /// \param SrcAddr Address of the source array.
  1769. /// \param OriginalType Type of destination and source arrays.
  1770. /// \param CopyGen Copying procedure that copies value of single array element
  1771. /// to another single array element.
  1772. void EmitOMPAggregateAssign(
  1773. llvm::Value *DestAddr, llvm::Value *SrcAddr, QualType OriginalType,
  1774. const llvm::function_ref<void(llvm::Value *, llvm::Value *)> &CopyGen);
  1775. /// \brief Emit proper copying of data from one variable to another.
  1776. ///
  1777. /// \param OriginalType Original type of the copied variables.
  1778. /// \param DestAddr Destination address.
  1779. /// \param SrcAddr Source address.
  1780. /// \param DestVD Destination variable used in \a CopyExpr (for arrays, has
  1781. /// type of the base array element).
  1782. /// \param SrcVD Source variable used in \a CopyExpr (for arrays, has type of
  1783. /// the base array element).
  1784. /// \param Copy Actual copygin expression for copying data from \a SrcVD to \a
  1785. /// DestVD.
  1786. void EmitOMPCopy(CodeGenFunction &CGF, QualType OriginalType,
  1787. llvm::Value *DestAddr, llvm::Value *SrcAddr,
  1788. const VarDecl *DestVD, const VarDecl *SrcVD,
  1789. const Expr *Copy);
  1790. /// \brief Emit atomic update code for constructs: \a X = \a X \a BO \a E or
  1791. /// \a X = \a E \a BO \a E.
  1792. ///
  1793. /// \param X Value to be updated.
  1794. /// \param E Update value.
  1795. /// \param BO Binary operation for update operation.
  1796. /// \param IsXLHSInRHSPart true if \a X is LHS in RHS part of the update
  1797. /// expression, false otherwise.
  1798. /// \param AO Atomic ordering of the generated atomic instructions.
  1799. /// \param CommonGen Code generator for complex expressions that cannot be
  1800. /// expressed through atomicrmw instruction.
  1801. /// \returns <true, OldAtomicValue> if simple 'atomicrmw' instruction was
  1802. /// generated, <false, RValue::get(nullptr)> otherwise.
  1803. std::pair<bool, RValue> EmitOMPAtomicSimpleUpdateExpr(
  1804. LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart,
  1805. llvm::AtomicOrdering AO, SourceLocation Loc,
  1806. const llvm::function_ref<RValue(RValue)> &CommonGen);
  1807. bool EmitOMPFirstprivateClause(const OMPExecutableDirective &D,
  1808. OMPPrivateScope &PrivateScope);
  1809. void EmitOMPPrivateClause(const OMPExecutableDirective &D,
  1810. OMPPrivateScope &PrivateScope);
  1811. /// \brief Emit code for copyin clause in \a D directive. The next code is
  1812. /// generated at the start of outlined functions for directives:
  1813. /// \code
  1814. /// threadprivate_var1 = master_threadprivate_var1;
  1815. /// operator=(threadprivate_var2, master_threadprivate_var2);
  1816. /// ...
  1817. /// __kmpc_barrier(&loc, global_tid);
  1818. /// \endcode
  1819. ///
  1820. /// \param D OpenMP directive possibly with 'copyin' clause(s).
  1821. /// \returns true if at least one copyin variable is found, false otherwise.
  1822. bool EmitOMPCopyinClause(const OMPExecutableDirective &D);
  1823. /// \brief Emit initial code for lastprivate variables. If some variable is
  1824. /// not also firstprivate, then the default initialization is used. Otherwise
  1825. /// initialization of this variable is performed by EmitOMPFirstprivateClause
  1826. /// method.
  1827. ///
  1828. /// \param D Directive that may have 'lastprivate' directives.
  1829. /// \param PrivateScope Private scope for capturing lastprivate variables for
  1830. /// proper codegen in internal captured statement.
  1831. ///
  1832. /// \returns true if there is at least one lastprivate variable, false
  1833. /// otherwise.
  1834. bool EmitOMPLastprivateClauseInit(const OMPExecutableDirective &D,
  1835. OMPPrivateScope &PrivateScope);
  1836. /// \brief Emit final copying of lastprivate values to original variables at
  1837. /// the end of the worksharing or simd directive.
  1838. ///
  1839. /// \param D Directive that has at least one 'lastprivate' directives.
  1840. /// \param IsLastIterCond Boolean condition that must be set to 'i1 true' if
  1841. /// it is the last iteration of the loop code in associated directive, or to
  1842. /// 'i1 false' otherwise. If this item is nullptr, no final check is required.
  1843. void EmitOMPLastprivateClauseFinal(const OMPExecutableDirective &D,
  1844. llvm::Value *IsLastIterCond = nullptr);
  1845. /// \brief Emit initial code for reduction variables. Creates reduction copies
  1846. /// and initializes them with the values according to OpenMP standard.
  1847. ///
  1848. /// \param D Directive (possibly) with the 'reduction' clause.
  1849. /// \param PrivateScope Private scope for capturing reduction variables for
  1850. /// proper codegen in internal captured statement.
  1851. ///
  1852. void EmitOMPReductionClauseInit(const OMPExecutableDirective &D,
  1853. OMPPrivateScope &PrivateScope);
  1854. /// \brief Emit final update of reduction values to original variables at
  1855. /// the end of the directive.
  1856. ///
  1857. /// \param D Directive that has at least one 'reduction' directives.
  1858. void EmitOMPReductionClauseFinal(const OMPExecutableDirective &D);
  1859. /// \brief Emit initial code for linear variables. Creates private copies
  1860. /// and initializes them with the values according to OpenMP standard.
  1861. ///
  1862. /// \param D Directive (possibly) with the 'linear' clause.
  1863. void EmitOMPLinearClauseInit(const OMPLoopDirective &D);
  1864. void EmitOMPParallelDirective(const OMPParallelDirective &S);
  1865. void EmitOMPSimdDirective(const OMPSimdDirective &S);
  1866. void EmitOMPForDirective(const OMPForDirective &S);
  1867. void EmitOMPForSimdDirective(const OMPForSimdDirective &S);
  1868. void EmitOMPSectionsDirective(const OMPSectionsDirective &S);
  1869. void EmitOMPSectionDirective(const OMPSectionDirective &S);
  1870. void EmitOMPSingleDirective(const OMPSingleDirective &S);
  1871. void EmitOMPMasterDirective(const OMPMasterDirective &S);
  1872. void EmitOMPCriticalDirective(const OMPCriticalDirective &S);
  1873. void EmitOMPParallelForDirective(const OMPParallelForDirective &S);
  1874. void EmitOMPParallelForSimdDirective(const OMPParallelForSimdDirective &S);
  1875. void EmitOMPParallelSectionsDirective(const OMPParallelSectionsDirective &S);
  1876. void EmitOMPTaskDirective(const OMPTaskDirective &S);
  1877. void EmitOMPTaskyieldDirective(const OMPTaskyieldDirective &S);
  1878. void EmitOMPBarrierDirective(const OMPBarrierDirective &S);
  1879. void EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S);
  1880. void EmitOMPTaskgroupDirective(const OMPTaskgroupDirective &S);
  1881. void EmitOMPFlushDirective(const OMPFlushDirective &S);
  1882. void EmitOMPOrderedDirective(const OMPOrderedDirective &S);
  1883. void EmitOMPAtomicDirective(const OMPAtomicDirective &S);
  1884. void EmitOMPTargetDirective(const OMPTargetDirective &S);
  1885. void EmitOMPTeamsDirective(const OMPTeamsDirective &S);
  1886. void
  1887. EmitOMPCancellationPointDirective(const OMPCancellationPointDirective &S);
  1888. void EmitOMPCancelDirective(const OMPCancelDirective &S);
  1889. /// \brief Emit inner loop of the worksharing/simd construct.
  1890. ///
  1891. /// \param S Directive, for which the inner loop must be emitted.
  1892. /// \param RequiresCleanup true, if directive has some associated private
  1893. /// variables.
  1894. /// \param LoopCond Bollean condition for loop continuation.
  1895. /// \param IncExpr Increment expression for loop control variable.
  1896. /// \param BodyGen Generator for the inner body of the inner loop.
  1897. /// \param PostIncGen Genrator for post-increment code (required for ordered
  1898. /// loop directvies).
  1899. void EmitOMPInnerLoop(
  1900. const Stmt &S, bool RequiresCleanup, const Expr *LoopCond,
  1901. const Expr *IncExpr,
  1902. const llvm::function_ref<void(CodeGenFunction &)> &BodyGen,
  1903. const llvm::function_ref<void(CodeGenFunction &)> &PostIncGen);
  1904. JumpDest getOMPCancelDestination(OpenMPDirectiveKind Kind);
  1905. private:
  1906. /// Helpers for the OpenMP loop directives.
  1907. void EmitOMPLoopBody(const OMPLoopDirective &D, JumpDest LoopExit);
  1908. void EmitOMPSimdInit(const OMPLoopDirective &D);
  1909. void EmitOMPSimdFinal(const OMPLoopDirective &D);
  1910. /// \brief Emit code for the worksharing loop-based directive.
  1911. /// \return true, if this construct has any lastprivate clause, false -
  1912. /// otherwise.
  1913. bool EmitOMPWorksharingLoop(const OMPLoopDirective &S);
  1914. void EmitOMPForOuterLoop(OpenMPScheduleClauseKind ScheduleKind,
  1915. const OMPLoopDirective &S,
  1916. OMPPrivateScope &LoopScope, bool Ordered,
  1917. llvm::Value *LB, llvm::Value *UB, llvm::Value *ST,
  1918. llvm::Value *IL, llvm::Value *Chunk);
  1919. /// \brief Emit code for sections directive.
  1920. OpenMPDirectiveKind EmitSections(const OMPExecutableDirective &S);
  1921. public:
  1922. //===--------------------------------------------------------------------===//
  1923. // LValue Expression Emission
  1924. //===--------------------------------------------------------------------===//
  1925. /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
  1926. RValue GetUndefRValue(QualType Ty);
  1927. /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
  1928. /// and issue an ErrorUnsupported style diagnostic (using the
  1929. /// provided Name).
  1930. RValue EmitUnsupportedRValue(const Expr *E,
  1931. const char *Name);
  1932. /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
  1933. /// an ErrorUnsupported style diagnostic (using the provided Name).
  1934. LValue EmitUnsupportedLValue(const Expr *E,
  1935. const char *Name);
  1936. /// EmitLValue - Emit code to compute a designator that specifies the location
  1937. /// of the expression.
  1938. ///
  1939. /// This can return one of two things: a simple address or a bitfield
  1940. /// reference. In either case, the LLVM Value* in the LValue structure is
  1941. /// guaranteed to be an LLVM pointer type.
  1942. ///
  1943. /// If this returns a bitfield reference, nothing about the pointee type of
  1944. /// the LLVM value is known: For example, it may not be a pointer to an
  1945. /// integer.
  1946. ///
  1947. /// If this returns a normal address, and if the lvalue's C type is fixed
  1948. /// size, this method guarantees that the returned pointer type will point to
  1949. /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
  1950. /// variable length type, this is not possible.
  1951. ///
  1952. LValue EmitLValue(const Expr *E);
  1953. /// \brief Same as EmitLValue but additionally we generate checking code to
  1954. /// guard against undefined behavior. This is only suitable when we know
  1955. /// that the address will be used to access the object.
  1956. LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK);
  1957. RValue convertTempToRValue(llvm::Value *addr, QualType type,
  1958. SourceLocation Loc);
  1959. void EmitAtomicInit(Expr *E, LValue lvalue);
  1960. bool LValueIsSuitableForInlineAtomic(LValue Src);
  1961. bool typeIsSuitableForInlineAtomic(QualType Ty, bool IsVolatile) const;
  1962. RValue EmitAtomicLoad(LValue LV, SourceLocation SL,
  1963. AggValueSlot Slot = AggValueSlot::ignored());
  1964. RValue EmitAtomicLoad(LValue lvalue, SourceLocation loc,
  1965. llvm::AtomicOrdering AO, bool IsVolatile = false,
  1966. AggValueSlot slot = AggValueSlot::ignored());
  1967. void EmitAtomicStore(RValue rvalue, LValue lvalue, bool isInit);
  1968. void EmitAtomicStore(RValue rvalue, LValue lvalue, llvm::AtomicOrdering AO,
  1969. bool IsVolatile, bool isInit);
  1970. std::pair<RValue, llvm::Value *> EmitAtomicCompareExchange(
  1971. LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
  1972. llvm::AtomicOrdering Success = llvm::SequentiallyConsistent,
  1973. llvm::AtomicOrdering Failure = llvm::SequentiallyConsistent,
  1974. bool IsWeak = false, AggValueSlot Slot = AggValueSlot::ignored());
  1975. void EmitAtomicUpdate(LValue LVal, llvm::AtomicOrdering AO,
  1976. const llvm::function_ref<RValue(RValue)> &UpdateOp,
  1977. bool IsVolatile);
  1978. /// EmitToMemory - Change a scalar value from its value
  1979. /// representation to its in-memory representation.
  1980. llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
  1981. /// EmitFromMemory - Change a scalar value from its memory
  1982. /// representation to its value representation.
  1983. llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
  1984. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  1985. /// care to appropriately convert from the memory representation to
  1986. /// the LLVM value representation.
  1987. llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
  1988. unsigned Alignment, QualType Ty,
  1989. SourceLocation Loc,
  1990. llvm::MDNode *TBAAInfo = nullptr,
  1991. QualType TBAABaseTy = QualType(),
  1992. uint64_t TBAAOffset = 0);
  1993. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  1994. /// care to appropriately convert from the memory representation to
  1995. /// the LLVM value representation. The l-value must be a simple
  1996. /// l-value.
  1997. llvm::Value *EmitLoadOfScalar(LValue lvalue, SourceLocation Loc);
  1998. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  1999. /// care to appropriately convert from the memory representation to
  2000. /// the LLVM value representation.
  2001. void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
  2002. bool Volatile, unsigned Alignment, QualType Ty,
  2003. llvm::MDNode *TBAAInfo = nullptr, bool isInit = false,
  2004. QualType TBAABaseTy = QualType(),
  2005. uint64_t TBAAOffset = 0);
  2006. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  2007. /// care to appropriately convert from the memory representation to
  2008. /// the LLVM value representation. The l-value must be a simple
  2009. /// l-value. The isInit flag indicates whether this is an initialization.
  2010. /// If so, atomic qualifiers are ignored and the store is always non-atomic.
  2011. void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
  2012. /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
  2013. /// this method emits the address of the lvalue, then loads the result as an
  2014. /// rvalue, returning the rvalue.
  2015. RValue EmitLoadOfLValue(LValue V, SourceLocation Loc);
  2016. RValue EmitLoadOfExtVectorElementLValue(LValue V);
  2017. RValue EmitLoadOfBitfieldLValue(LValue LV);
  2018. RValue EmitLoadOfGlobalRegLValue(LValue LV);
  2019. RValue EmitLoadOfExtMatrixElementLValue(LValue V); // HLSL Change
  2020. /// EmitStoreThroughLValue - Store the specified rvalue into the specified
  2021. /// lvalue, where both are guaranteed to the have the same type, and that type
  2022. /// is 'Ty'.
  2023. void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit = false);
  2024. void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
  2025. void EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst);
  2026. /// EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints
  2027. /// as EmitStoreThroughLValue.
  2028. ///
  2029. /// \param Result [out] - If non-null, this will be set to a Value* for the
  2030. /// bit-field contents after the store, appropriate for use as the result of
  2031. /// an assignment to the bit-field.
  2032. void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
  2033. llvm::Value **Result=nullptr);
  2034. /// Emit an l-value for an assignment (simple or compound) of complex type.
  2035. LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
  2036. LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
  2037. LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E,
  2038. llvm::Value *&Result);
  2039. // Note: only available for agg return types
  2040. LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
  2041. LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
  2042. // Note: only available for agg return types
  2043. LValue EmitCallExprLValue(const CallExpr *E);
  2044. // Note: only available for agg return types
  2045. LValue EmitVAArgExprLValue(const VAArgExpr *E);
  2046. LValue EmitDeclRefLValue(const DeclRefExpr *E);
  2047. LValue EmitReadRegister(const VarDecl *VD);
  2048. LValue EmitStringLiteralLValue(const StringLiteral *E);
  2049. LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
  2050. LValue EmitPredefinedLValue(const PredefinedExpr *E);
  2051. LValue EmitUnaryOpLValue(const UnaryOperator *E);
  2052. LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
  2053. bool Accessed = false);
  2054. LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
  2055. LValue EmitExtMatrixElementExpr(const ExtMatrixElementExpr *E); // HLSL Change
  2056. LValue EmitHLSLVectorElementExpr(const HLSLVectorElementExpr *E); // HLSL Change
  2057. LValue EmitMemberExpr(const MemberExpr *E);
  2058. LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
  2059. LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
  2060. LValue EmitInitListLValue(const InitListExpr *E);
  2061. LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
  2062. LValue EmitCastLValue(const CastExpr *E);
  2063. LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  2064. LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
  2065. llvm::Value *EmitExtVectorElementLValue(LValue V);
  2066. RValue EmitRValueForField(LValue LV, const FieldDecl *FD, SourceLocation Loc);
  2067. class ConstantEmission {
  2068. llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
  2069. ConstantEmission(llvm::Constant *C, bool isReference)
  2070. : ValueAndIsReference(C, isReference) {}
  2071. public:
  2072. ConstantEmission() {}
  2073. static ConstantEmission forReference(llvm::Constant *C) {
  2074. return ConstantEmission(C, true);
  2075. }
  2076. static ConstantEmission forValue(llvm::Constant *C) {
  2077. return ConstantEmission(C, false);
  2078. }
  2079. explicit operator bool() const {
  2080. return ValueAndIsReference.getOpaqueValue() != nullptr;
  2081. }
  2082. bool isReference() const { return ValueAndIsReference.getInt(); }
  2083. LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
  2084. assert(isReference());
  2085. return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
  2086. refExpr->getType());
  2087. }
  2088. llvm::Constant *getValue() const {
  2089. assert(!isReference());
  2090. return ValueAndIsReference.getPointer();
  2091. }
  2092. };
  2093. ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
  2094. RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
  2095. AggValueSlot slot = AggValueSlot::ignored());
  2096. LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
  2097. llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
  2098. const ObjCIvarDecl *Ivar);
  2099. LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
  2100. LValue EmitLValueForLambdaField(const FieldDecl *Field);
  2101. /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
  2102. /// if the Field is a reference, this will return the address of the reference
  2103. /// and not the address of the value stored in the reference.
  2104. LValue EmitLValueForFieldInitialization(LValue Base,
  2105. const FieldDecl* Field);
  2106. LValue EmitLValueForIvar(QualType ObjectTy,
  2107. llvm::Value* Base, const ObjCIvarDecl *Ivar,
  2108. unsigned CVRQualifiers);
  2109. LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
  2110. LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
  2111. LValue EmitLambdaLValue(const LambdaExpr *E);
  2112. LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
  2113. LValue EmitCXXUuidofLValue(const CXXUuidofExpr *E);
  2114. LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
  2115. LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
  2116. LValue EmitStmtExprLValue(const StmtExpr *E);
  2117. LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
  2118. LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
  2119. void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init);
  2120. //===--------------------------------------------------------------------===//
  2121. // Scalar Expression Emission
  2122. //===--------------------------------------------------------------------===//
  2123. /// EmitCall - Generate a call of the given function, expecting the given
  2124. /// result type, and using the given argument list which specifies both the
  2125. /// LLVM arguments and the types they were derived from.
  2126. ///
  2127. /// \param TargetDecl - If given, the decl of the function in a direct call;
  2128. /// used to set attributes on the call (noreturn, etc.).
  2129. RValue EmitCall(const CGFunctionInfo &FnInfo,
  2130. llvm::Value *Callee,
  2131. ReturnValueSlot ReturnValue,
  2132. const CallArgList &Args,
  2133. const Decl *TargetDecl = nullptr,
  2134. llvm::Instruction **callOrInvoke = nullptr);
  2135. RValue EmitCall(QualType FnType, llvm::Value *Callee, const CallExpr *E,
  2136. ReturnValueSlot ReturnValue,
  2137. const Decl *TargetDecl = nullptr,
  2138. llvm::Value *Chain = nullptr);
  2139. RValue EmitCallExpr(const CallExpr *E,
  2140. ReturnValueSlot ReturnValue = ReturnValueSlot());
  2141. llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
  2142. const Twine &name = "");
  2143. llvm::CallInst *EmitRuntimeCall(llvm::Value *callee,
  2144. ArrayRef<llvm::Value*> args,
  2145. const Twine &name = "");
  2146. llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
  2147. const Twine &name = "");
  2148. llvm::CallInst *EmitNounwindRuntimeCall(llvm::Value *callee,
  2149. ArrayRef<llvm::Value*> args,
  2150. const Twine &name = "");
  2151. llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
  2152. ArrayRef<llvm::Value *> Args,
  2153. const Twine &Name = "");
  2154. llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
  2155. const Twine &Name = "");
  2156. llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
  2157. ArrayRef<llvm::Value*> args,
  2158. const Twine &name = "");
  2159. llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee,
  2160. const Twine &name = "");
  2161. void EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
  2162. ArrayRef<llvm::Value*> args);
  2163. llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
  2164. NestedNameSpecifier *Qual,
  2165. llvm::Type *Ty);
  2166. llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
  2167. CXXDtorType Type,
  2168. const CXXRecordDecl *RD);
  2169. RValue
  2170. EmitCXXMemberOrOperatorCall(const CXXMethodDecl *MD, llvm::Value *Callee,
  2171. ReturnValueSlot ReturnValue, llvm::Value *This,
  2172. llvm::Value *ImplicitParam,
  2173. QualType ImplicitParamTy, const CallExpr *E);
  2174. RValue EmitCXXStructorCall(const CXXMethodDecl *MD, llvm::Value *Callee,
  2175. ReturnValueSlot ReturnValue, llvm::Value *This,
  2176. llvm::Value *ImplicitParam,
  2177. QualType ImplicitParamTy, const CallExpr *E,
  2178. StructorType Type);
  2179. RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
  2180. ReturnValueSlot ReturnValue);
  2181. RValue EmitCXXMemberOrOperatorMemberCallExpr(const CallExpr *CE,
  2182. const CXXMethodDecl *MD,
  2183. ReturnValueSlot ReturnValue,
  2184. bool HasQualifier,
  2185. NestedNameSpecifier *Qualifier,
  2186. bool IsArrow, const Expr *Base);
  2187. // Compute the object pointer.
  2188. RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
  2189. ReturnValueSlot ReturnValue);
  2190. RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
  2191. const CXXMethodDecl *MD,
  2192. ReturnValueSlot ReturnValue);
  2193. RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
  2194. ReturnValueSlot ReturnValue);
  2195. // HLSL Change Begins
  2196. RValue EmitHLSLBuiltinCallExpr(const FunctionDecl *FD, const CallExpr *E,
  2197. ReturnValueSlot ReturnValue);
  2198. // HLSL Change Ends
  2199. RValue EmitBuiltinExpr(const FunctionDecl *FD,
  2200. unsigned BuiltinID, const CallExpr *E,
  2201. ReturnValueSlot ReturnValue);
  2202. RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
  2203. /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
  2204. /// is unhandled by the current target.
  2205. llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2206. llvm::Value *EmitAArch64CompareBuiltinExpr(llvm::Value *Op, llvm::Type *Ty,
  2207. const llvm::CmpInst::Predicate Fp,
  2208. const llvm::CmpInst::Predicate Ip,
  2209. const llvm::Twine &Name = "");
  2210. llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2211. llvm::Value *EmitCommonNeonBuiltinExpr(unsigned BuiltinID,
  2212. unsigned LLVMIntrinsic,
  2213. unsigned AltLLVMIntrinsic,
  2214. const char *NameHint,
  2215. unsigned Modifier,
  2216. const CallExpr *E,
  2217. SmallVectorImpl<llvm::Value *> &Ops,
  2218. llvm::Value *Align = nullptr);
  2219. llvm::Function *LookupNeonLLVMIntrinsic(unsigned IntrinsicID,
  2220. unsigned Modifier, llvm::Type *ArgTy,
  2221. const CallExpr *E);
  2222. llvm::Value *EmitNeonCall(llvm::Function *F,
  2223. SmallVectorImpl<llvm::Value*> &O,
  2224. const char *name,
  2225. unsigned shift = 0, bool rightshift = false);
  2226. llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
  2227. llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
  2228. bool negateForRightShift);
  2229. llvm::Value *EmitNeonRShiftImm(llvm::Value *Vec, llvm::Value *Amt,
  2230. llvm::Type *Ty, bool usgn, const char *name);
  2231. // Helper functions for EmitAArch64BuiltinExpr.
  2232. llvm::Value *vectorWrapScalar8(llvm::Value *Op);
  2233. llvm::Value *vectorWrapScalar16(llvm::Value *Op);
  2234. llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2235. llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
  2236. llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2237. llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2238. llvm::Value *EmitAMDGPUBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2239. llvm::Value *EmitSystemZBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2240. llvm::Value *EmitNVPTXBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  2241. llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
  2242. llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
  2243. llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
  2244. llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
  2245. llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
  2246. llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
  2247. const ObjCMethodDecl *MethodWithObjects);
  2248. llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
  2249. RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
  2250. ReturnValueSlot Return = ReturnValueSlot());
  2251. /// Retrieves the default cleanup kind for an ARC cleanup.
  2252. /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
  2253. CleanupKind getARCCleanupKind() {
  2254. return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
  2255. ? NormalAndEHCleanup : NormalCleanup;
  2256. }
  2257. // ARC primitives.
  2258. void EmitARCInitWeak(llvm::Value *value, llvm::Value *addr);
  2259. void EmitARCDestroyWeak(llvm::Value *addr);
  2260. llvm::Value *EmitARCLoadWeak(llvm::Value *addr);
  2261. llvm::Value *EmitARCLoadWeakRetained(llvm::Value *addr);
  2262. llvm::Value *EmitARCStoreWeak(llvm::Value *value, llvm::Value *addr,
  2263. bool ignored);
  2264. void EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src);
  2265. void EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src);
  2266. llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
  2267. llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
  2268. llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
  2269. bool resultIgnored);
  2270. llvm::Value *EmitARCStoreStrongCall(llvm::Value *addr, llvm::Value *value,
  2271. bool resultIgnored);
  2272. llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
  2273. llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
  2274. llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
  2275. void EmitARCDestroyStrong(llvm::Value *addr, ARCPreciseLifetime_t precise);
  2276. void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise);
  2277. llvm::Value *EmitARCAutorelease(llvm::Value *value);
  2278. llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
  2279. llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
  2280. llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
  2281. std::pair<LValue,llvm::Value*>
  2282. EmitARCStoreAutoreleasing(const BinaryOperator *e);
  2283. std::pair<LValue,llvm::Value*>
  2284. EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
  2285. llvm::Value *EmitObjCThrowOperand(const Expr *expr);
  2286. llvm::Value *EmitObjCProduceObject(QualType T, llvm::Value *Ptr);
  2287. llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
  2288. llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
  2289. llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
  2290. llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
  2291. llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
  2292. void EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values);
  2293. static Destroyer destroyARCStrongImprecise;
  2294. static Destroyer destroyARCStrongPrecise;
  2295. static Destroyer destroyARCWeak;
  2296. void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
  2297. llvm::Value *EmitObjCAutoreleasePoolPush();
  2298. llvm::Value *EmitObjCMRRAutoreleasePoolPush();
  2299. void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
  2300. void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
  2301. /// \brief Emits a reference binding to the passed in expression.
  2302. RValue EmitReferenceBindingToExpr(const Expr *E);
  2303. //===--------------------------------------------------------------------===//
  2304. // Expression Emission
  2305. //===--------------------------------------------------------------------===//
  2306. // Expressions are broken into three classes: scalar, complex, aggregate.
  2307. /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
  2308. /// scalar type, returning the result.
  2309. llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
  2310. /// EmitScalarConversion - Emit a conversion from the specified type to the
  2311. /// specified destination type, both of which are LLVM scalar types.
  2312. llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
  2313. QualType DstTy);
  2314. /// EmitComplexToScalarConversion - Emit a conversion from the specified
  2315. /// complex type to the specified destination type, where the destination type
  2316. /// is an LLVM scalar type.
  2317. llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
  2318. QualType DstTy);
  2319. /// EmitAggExpr - Emit the computation of the specified expression
  2320. /// of aggregate type. The result is computed into the given slot,
  2321. /// which may be null to indicate that the value is not needed.
  2322. void EmitAggExpr(const Expr *E, AggValueSlot AS);
  2323. /// EmitAggExprToLValue - Emit the computation of the specified expression of
  2324. /// aggregate type into a temporary LValue.
  2325. LValue EmitAggExprToLValue(const Expr *E);
  2326. /// EmitGCMemmoveCollectable - Emit special API for structs with object
  2327. /// pointers.
  2328. void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
  2329. QualType Ty);
  2330. /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
  2331. /// make sure it survives garbage collection until this point.
  2332. void EmitExtendGCLifetime(llvm::Value *object);
  2333. /// EmitComplexExpr - Emit the computation of the specified expression of
  2334. /// complex type, returning the result.
  2335. ComplexPairTy EmitComplexExpr(const Expr *E,
  2336. bool IgnoreReal = false,
  2337. bool IgnoreImag = false);
  2338. /// EmitComplexExprIntoLValue - Emit the given expression of complex
  2339. /// type and place its result into the specified l-value.
  2340. void EmitComplexExprIntoLValue(const Expr *E, LValue dest, bool isInit);
  2341. /// EmitStoreOfComplex - Store a complex number into the specified l-value.
  2342. void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit);
  2343. /// EmitLoadOfComplex - Load a complex number from the specified l-value.
  2344. ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc);
  2345. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  2346. /// global variable that has already been created for it. If the initializer
  2347. /// has a different type than GV does, this may free GV and return a different
  2348. /// one. Otherwise it just returns GV.
  2349. llvm::GlobalVariable *
  2350. AddInitializerToStaticVarDecl(const VarDecl &D,
  2351. llvm::GlobalVariable *GV);
  2352. /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
  2353. /// variable with global storage.
  2354. void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
  2355. bool PerformInit);
  2356. llvm::Constant *createAtExitStub(const VarDecl &VD, llvm::Constant *Dtor,
  2357. llvm::Constant *Addr);
  2358. /// Call atexit() with a function that passes the given argument to
  2359. /// the given function.
  2360. void registerGlobalDtorWithAtExit(const VarDecl &D, llvm::Constant *fn,
  2361. llvm::Constant *addr);
  2362. /// Emit code in this function to perform a guarded variable
  2363. /// initialization. Guarded initializations are used when it's not
  2364. /// possible to prove that an initialization will be done exactly
  2365. /// once, e.g. with a static local variable or a static data member
  2366. /// of a class template.
  2367. void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
  2368. bool PerformInit);
  2369. /// GenerateCXXGlobalInitFunc - Generates code for initializing global
  2370. /// variables.
  2371. void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
  2372. ArrayRef<llvm::Function *> CXXThreadLocals,
  2373. llvm::GlobalVariable *Guard = nullptr);
  2374. /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
  2375. /// variables.
  2376. void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
  2377. const std::vector<std::pair<llvm::WeakVH,
  2378. llvm::Constant*> > &DtorsAndObjects);
  2379. void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
  2380. const VarDecl *D,
  2381. llvm::GlobalVariable *Addr,
  2382. bool PerformInit);
  2383. void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
  2384. void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src,
  2385. const Expr *Exp);
  2386. void enterFullExpression(const ExprWithCleanups *E) {
  2387. if (E->getNumObjects() == 0) return;
  2388. enterNonTrivialFullExpression(E);
  2389. }
  2390. void enterNonTrivialFullExpression(const ExprWithCleanups *E);
  2391. void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
  2392. void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
  2393. RValue EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest = nullptr);
  2394. //===--------------------------------------------------------------------===//
  2395. // Annotations Emission
  2396. //===--------------------------------------------------------------------===//
  2397. /// Emit an annotation call (intrinsic or builtin).
  2398. llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
  2399. llvm::Value *AnnotatedVal,
  2400. StringRef AnnotationStr,
  2401. SourceLocation Location);
  2402. /// Emit local annotations for the local variable V, declared by D.
  2403. void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
  2404. /// Emit field annotations for the given field & value. Returns the
  2405. /// annotation result.
  2406. llvm::Value *EmitFieldAnnotations(const FieldDecl *D, llvm::Value *V);
  2407. //===--------------------------------------------------------------------===//
  2408. // Internal Helpers
  2409. //===--------------------------------------------------------------------===//
  2410. /// ContainsLabel - Return true if the statement contains a label in it. If
  2411. /// this statement is not executed normally, it not containing a label means
  2412. /// that we can just remove the code.
  2413. static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
  2414. /// containsBreak - Return true if the statement contains a break out of it.
  2415. /// If the statement (recursively) contains a switch or loop with a break
  2416. /// inside of it, this is fine.
  2417. static bool containsBreak(const Stmt *S);
  2418. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  2419. /// to a constant, or if it does but contains a label, return false. If it
  2420. /// constant folds return true and set the boolean result in Result.
  2421. bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result);
  2422. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  2423. /// to a constant, or if it does but contains a label, return false. If it
  2424. /// constant folds return true and set the folded value.
  2425. bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APSInt &Result);
  2426. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
  2427. /// if statement) to the specified blocks. Based on the condition, this might
  2428. /// try to simplify the codegen of the conditional based on the branch.
  2429. /// TrueCount should be the number of times we expect the condition to
  2430. /// evaluate to true based on PGO data.
  2431. void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
  2432. llvm::BasicBlock *FalseBlock, uint64_t TrueCount);
  2433. /// \brief Emit a description of a type in a format suitable for passing to
  2434. /// a runtime sanitizer handler.
  2435. llvm::Constant *EmitCheckTypeDescriptor(QualType T);
  2436. /// \brief Convert a value into a format suitable for passing to a runtime
  2437. /// sanitizer handler.
  2438. llvm::Value *EmitCheckValue(llvm::Value *V);
  2439. /// \brief Emit a description of a source location in a format suitable for
  2440. /// passing to a runtime sanitizer handler.
  2441. llvm::Constant *EmitCheckSourceLocation(SourceLocation Loc);
  2442. /// \brief Create a basic block that will call a handler function in a
  2443. /// sanitizer runtime with the provided arguments, and create a conditional
  2444. /// branch to it.
  2445. void EmitCheck(ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
  2446. StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
  2447. ArrayRef<llvm::Value *> DynamicArgs);
  2448. /// \brief Create a basic block that will call the trap intrinsic, and emit a
  2449. /// conditional branch to it, for the -ftrapv checks.
  2450. void EmitTrapCheck(llvm::Value *Checked);
  2451. /// \brief Emit a call to trap or debugtrap and attach function attribute
  2452. /// "trap-func-name" if specified.
  2453. llvm::CallInst *EmitTrapCall(llvm::Intrinsic::ID IntrID);
  2454. /// \brief Create a check for a function parameter that may potentially be
  2455. /// declared as non-null.
  2456. void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc,
  2457. const FunctionDecl *FD, unsigned ParmNum);
  2458. /// EmitCallArg - Emit a single call argument.
  2459. void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
  2460. /// EmitDelegateCallArg - We are performing a delegate call; that
  2461. /// is, the current function is delegating to another one. Produce
  2462. /// a r-value suitable for passing the given parameter.
  2463. void EmitDelegateCallArg(CallArgList &args, const VarDecl *param,
  2464. SourceLocation loc);
  2465. /// SetFPAccuracy - Set the minimum required accuracy of the given floating
  2466. /// point operation, expressed as the maximum relative error in ulp.
  2467. void SetFPAccuracy(llvm::Value *Val, float Accuracy);
  2468. private:
  2469. llvm::MDNode *getRangeForLoadFromType(QualType Ty);
  2470. void EmitReturnOfRValue(RValue RV, QualType Ty);
  2471. void deferPlaceholderReplacement(llvm::Instruction *Old, llvm::Value *New);
  2472. llvm::SmallVector<std::pair<llvm::Instruction *, llvm::Value *>, 4>
  2473. DeferredReplacements;
  2474. /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
  2475. /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
  2476. ///
  2477. /// \param AI - The first function argument of the expansion.
  2478. void ExpandTypeFromArgs(QualType Ty, LValue Dst,
  2479. SmallVectorImpl<llvm::Argument *>::iterator &AI);
  2480. /// ExpandTypeToArgs - Expand an RValue \arg RV, with the LLVM type for \arg
  2481. /// Ty, into individual arguments on the provided vector \arg IRCallArgs,
  2482. /// starting at index \arg IRCallArgPos. See ABIArgInfo::Expand.
  2483. void ExpandTypeToArgs(QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
  2484. SmallVectorImpl<llvm::Value *> &IRCallArgs,
  2485. unsigned &IRCallArgPos);
  2486. llvm::Value* EmitAsmInput(const TargetInfo::ConstraintInfo &Info,
  2487. const Expr *InputExpr, std::string &ConstraintStr);
  2488. llvm::Value* EmitAsmInputLValue(const TargetInfo::ConstraintInfo &Info,
  2489. LValue InputValue, QualType InputType,
  2490. std::string &ConstraintStr,
  2491. SourceLocation Loc);
  2492. public:
  2493. #ifndef NDEBUG
  2494. // Determine whether the given argument is an Objective-C method
  2495. // that may have type parameters in its signature.
  2496. static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
  2497. const DeclContext *dc = method->getDeclContext();
  2498. if (const ObjCInterfaceDecl *classDecl= dyn_cast<ObjCInterfaceDecl>(dc)) {
  2499. return classDecl->getTypeParamListAsWritten();
  2500. }
  2501. if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
  2502. return catDecl->getTypeParamList();
  2503. }
  2504. return false;
  2505. }
  2506. template<typename T>
  2507. static bool isObjCMethodWithTypeParams(const T *) { return false; }
  2508. #endif
  2509. /// EmitCallArgs - Emit call arguments for a function.
  2510. template <typename T>
  2511. void EmitCallArgs(CallArgList &Args, const T *CallArgTypeInfo,
  2512. CallExpr::const_arg_iterator ArgBeg,
  2513. CallExpr::const_arg_iterator ArgEnd,
  2514. const FunctionDecl *CalleeDecl = nullptr,
  2515. unsigned ParamsToSkip = 0) {
  2516. SmallVector<QualType, 16> ArgTypes;
  2517. CallExpr::const_arg_iterator Arg = ArgBeg;
  2518. assert((ParamsToSkip == 0 || CallArgTypeInfo) &&
  2519. "Can't skip parameters if type info is not provided");
  2520. if (CallArgTypeInfo) {
  2521. #ifndef NDEBUG
  2522. bool isGenericMethod = isObjCMethodWithTypeParams(CallArgTypeInfo);
  2523. #endif
  2524. // First, use the argument types that the type info knows about
  2525. for (auto I = CallArgTypeInfo->param_type_begin() + ParamsToSkip,
  2526. E = CallArgTypeInfo->param_type_end();
  2527. I != E; ++I, ++Arg) {
  2528. assert(Arg != ArgEnd && "Running over edge of argument list!");
  2529. assert((isGenericMethod ||
  2530. ((*I)->isVariablyModifiedType() ||
  2531. (*I).getNonReferenceType()->isObjCRetainableType() ||
  2532. getContext()
  2533. .getCanonicalType((*I).getNonReferenceType())
  2534. .getTypePtr() ==
  2535. getContext()
  2536. .getCanonicalType(Arg->getType())
  2537. .getTypePtr())) &&
  2538. "type mismatch in call argument!");
  2539. ArgTypes.push_back(*I);
  2540. }
  2541. }
  2542. // Either we've emitted all the call args, or we have a call to variadic
  2543. // function.
  2544. assert(
  2545. (Arg == ArgEnd || !CallArgTypeInfo || CallArgTypeInfo->isVariadic()) &&
  2546. "Extra arguments in non-variadic function!");
  2547. // If we still have any arguments, emit them using the type of the argument.
  2548. for (; Arg != ArgEnd; ++Arg)
  2549. ArgTypes.push_back(getVarArgType(*Arg));
  2550. EmitCallArgs(Args, ArgTypes, ArgBeg, ArgEnd, CalleeDecl, ParamsToSkip);
  2551. }
  2552. void EmitCallArgs(CallArgList &Args, ArrayRef<QualType> ArgTypes,
  2553. CallExpr::const_arg_iterator ArgBeg,
  2554. CallExpr::const_arg_iterator ArgEnd,
  2555. const FunctionDecl *CalleeDecl = nullptr,
  2556. unsigned ParamsToSkip = 0);
  2557. private:
  2558. QualType getVarArgType(const Expr *Arg);
  2559. const TargetCodeGenInfo &getTargetHooks() const {
  2560. return CGM.getTargetCodeGenInfo();
  2561. }
  2562. void EmitDeclMetadata();
  2563. CodeGenModule::ByrefHelpers *
  2564. buildByrefHelpers(llvm::StructType &byrefType,
  2565. const AutoVarEmission &emission);
  2566. void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
  2567. /// GetPointeeAlignment - Given an expression with a pointer type, emit the
  2568. /// value and compute our best estimate of the alignment of the pointee.
  2569. std::pair<llvm::Value*, unsigned> EmitPointerWithAlignment(const Expr *Addr);
  2570. llvm::Value *GetValueForARMHint(unsigned BuiltinID);
  2571. };
  2572. /// Helper class with most of the code for saving a value for a
  2573. /// conditional expression cleanup.
  2574. struct DominatingLLVMValue {
  2575. typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
  2576. /// Answer whether the given value needs extra work to be saved.
  2577. static bool needsSaving(llvm::Value *value) {
  2578. // If it's not an instruction, we don't need to save.
  2579. if (!isa<llvm::Instruction>(value)) return false;
  2580. // If it's an instruction in the entry block, we don't need to save.
  2581. llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
  2582. return (block != &block->getParent()->getEntryBlock());
  2583. }
  2584. /// Try to save the given value.
  2585. static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
  2586. if (!needsSaving(value)) return saved_type(value, false);
  2587. // Otherwise we need an alloca.
  2588. llvm::Value *alloca =
  2589. CGF.CreateTempAlloca(value->getType(), "cond-cleanup.save");
  2590. CGF.Builder.CreateStore(value, alloca);
  2591. return saved_type(alloca, true);
  2592. }
  2593. static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
  2594. if (!value.getInt()) return value.getPointer();
  2595. return CGF.Builder.CreateLoad(value.getPointer());
  2596. }
  2597. };
  2598. /// A partial specialization of DominatingValue for llvm::Values that
  2599. /// might be llvm::Instructions.
  2600. template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
  2601. typedef T *type;
  2602. static type restore(CodeGenFunction &CGF, saved_type value) {
  2603. return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
  2604. }
  2605. };
  2606. /// A specialization of DominatingValue for RValue.
  2607. template <> struct DominatingValue<RValue> {
  2608. typedef RValue type;
  2609. class saved_type {
  2610. enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
  2611. AggregateAddress, ComplexAddress };
  2612. llvm::Value *Value;
  2613. Kind K;
  2614. saved_type(llvm::Value *v, Kind k) : Value(v), K(k) {}
  2615. public:
  2616. static bool needsSaving(RValue value);
  2617. static saved_type save(CodeGenFunction &CGF, RValue value);
  2618. RValue restore(CodeGenFunction &CGF);
  2619. // implementations in CGExprCXX.cpp
  2620. };
  2621. static bool needsSaving(type value) {
  2622. return saved_type::needsSaving(value);
  2623. }
  2624. static saved_type save(CodeGenFunction &CGF, type value) {
  2625. return saved_type::save(CGF, value);
  2626. }
  2627. static type restore(CodeGenFunction &CGF, saved_type value) {
  2628. return value.restore(CGF);
  2629. }
  2630. };
  2631. } // end namespace CodeGen
  2632. } // end namespace clang
  2633. #endif