CodeGenFunction.h 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707
  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 CLANG_CODEGEN_CODEGENFUNCTION_H
  14. #define CLANG_CODEGEN_CODEGENFUNCTION_H
  15. #include "clang/AST/Type.h"
  16. #include "clang/AST/ExprCXX.h"
  17. #include "clang/AST/ExprObjC.h"
  18. #include "clang/AST/CharUnits.h"
  19. #include "clang/Frontend/CodeGenOptions.h"
  20. #include "clang/Basic/ABI.h"
  21. #include "clang/Basic/TargetInfo.h"
  22. #include "llvm/ADT/ArrayRef.h"
  23. #include "llvm/ADT/DenseMap.h"
  24. #include "llvm/ADT/SmallVector.h"
  25. #include "llvm/Support/ValueHandle.h"
  26. #include "llvm/Support/Debug.h"
  27. #include "CodeGenModule.h"
  28. #include "CGBuilder.h"
  29. #include "CGDebugInfo.h"
  30. #include "CGValue.h"
  31. namespace llvm {
  32. class BasicBlock;
  33. class LLVMContext;
  34. class MDNode;
  35. class Module;
  36. class SwitchInst;
  37. class Twine;
  38. class Value;
  39. class CallSite;
  40. }
  41. namespace clang {
  42. class ASTContext;
  43. class BlockDecl;
  44. class CXXDestructorDecl;
  45. class CXXForRangeStmt;
  46. class CXXTryStmt;
  47. class Decl;
  48. class LabelDecl;
  49. class EnumConstantDecl;
  50. class FunctionDecl;
  51. class FunctionProtoType;
  52. class LabelStmt;
  53. class ObjCContainerDecl;
  54. class ObjCInterfaceDecl;
  55. class ObjCIvarDecl;
  56. class ObjCMethodDecl;
  57. class ObjCImplementationDecl;
  58. class ObjCPropertyImplDecl;
  59. class TargetInfo;
  60. class TargetCodeGenInfo;
  61. class VarDecl;
  62. class ObjCForCollectionStmt;
  63. class ObjCAtTryStmt;
  64. class ObjCAtThrowStmt;
  65. class ObjCAtSynchronizedStmt;
  66. class ObjCAutoreleasePoolStmt;
  67. namespace CodeGen {
  68. class CodeGenTypes;
  69. class CGFunctionInfo;
  70. class CGRecordLayout;
  71. class CGBlockInfo;
  72. class CGCXXABI;
  73. class BlockFlags;
  74. class BlockFieldFlags;
  75. /// A branch fixup. These are required when emitting a goto to a
  76. /// label which hasn't been emitted yet. The goto is optimistically
  77. /// emitted as a branch to the basic block for the label, and (if it
  78. /// occurs in a scope with non-trivial cleanups) a fixup is added to
  79. /// the innermost cleanup. When a (normal) cleanup is popped, any
  80. /// unresolved fixups in that scope are threaded through the cleanup.
  81. struct BranchFixup {
  82. /// The block containing the terminator which needs to be modified
  83. /// into a switch if this fixup is resolved into the current scope.
  84. /// If null, LatestBranch points directly to the destination.
  85. llvm::BasicBlock *OptimisticBranchBlock;
  86. /// The ultimate destination of the branch.
  87. ///
  88. /// This can be set to null to indicate that this fixup was
  89. /// successfully resolved.
  90. llvm::BasicBlock *Destination;
  91. /// The destination index value.
  92. unsigned DestinationIndex;
  93. /// The initial branch of the fixup.
  94. llvm::BranchInst *InitialBranch;
  95. };
  96. template <class T> struct InvariantValue {
  97. typedef T type;
  98. typedef T saved_type;
  99. static bool needsSaving(type value) { return false; }
  100. static saved_type save(CodeGenFunction &CGF, type value) { return value; }
  101. static type restore(CodeGenFunction &CGF, saved_type value) { return value; }
  102. };
  103. /// A metaprogramming class for ensuring that a value will dominate an
  104. /// arbitrary position in a function.
  105. template <class T> struct DominatingValue : InvariantValue<T> {};
  106. template <class T, bool mightBeInstruction =
  107. llvm::is_base_of<llvm::Value, T>::value &&
  108. !llvm::is_base_of<llvm::Constant, T>::value &&
  109. !llvm::is_base_of<llvm::BasicBlock, T>::value>
  110. struct DominatingPointer;
  111. template <class T> struct DominatingPointer<T,false> : InvariantValue<T*> {};
  112. // template <class T> struct DominatingPointer<T,true> at end of file
  113. template <class T> struct DominatingValue<T*> : DominatingPointer<T> {};
  114. enum CleanupKind {
  115. EHCleanup = 0x1,
  116. NormalCleanup = 0x2,
  117. NormalAndEHCleanup = EHCleanup | NormalCleanup,
  118. InactiveCleanup = 0x4,
  119. InactiveEHCleanup = EHCleanup | InactiveCleanup,
  120. InactiveNormalCleanup = NormalCleanup | InactiveCleanup,
  121. InactiveNormalAndEHCleanup = NormalAndEHCleanup | InactiveCleanup
  122. };
  123. /// A stack of scopes which respond to exceptions, including cleanups
  124. /// and catch blocks.
  125. class EHScopeStack {
  126. public:
  127. /// A saved depth on the scope stack. This is necessary because
  128. /// pushing scopes onto the stack invalidates iterators.
  129. class stable_iterator {
  130. friend class EHScopeStack;
  131. /// Offset from StartOfData to EndOfBuffer.
  132. ptrdiff_t Size;
  133. stable_iterator(ptrdiff_t Size) : Size(Size) {}
  134. public:
  135. static stable_iterator invalid() { return stable_iterator(-1); }
  136. stable_iterator() : Size(-1) {}
  137. bool isValid() const { return Size >= 0; }
  138. /// Returns true if this scope encloses I.
  139. /// Returns false if I is invalid.
  140. /// This scope must be valid.
  141. bool encloses(stable_iterator I) const { return Size <= I.Size; }
  142. /// Returns true if this scope strictly encloses I: that is,
  143. /// if it encloses I and is not I.
  144. /// Returns false is I is invalid.
  145. /// This scope must be valid.
  146. bool strictlyEncloses(stable_iterator I) const { return Size < I.Size; }
  147. friend bool operator==(stable_iterator A, stable_iterator B) {
  148. return A.Size == B.Size;
  149. }
  150. friend bool operator!=(stable_iterator A, stable_iterator B) {
  151. return A.Size != B.Size;
  152. }
  153. };
  154. /// Information for lazily generating a cleanup. Subclasses must be
  155. /// POD-like: cleanups will not be destructed, and they will be
  156. /// allocated on the cleanup stack and freely copied and moved
  157. /// around.
  158. ///
  159. /// Cleanup implementations should generally be declared in an
  160. /// anonymous namespace.
  161. class Cleanup {
  162. // Anchor the construction vtable.
  163. virtual void anchor();
  164. public:
  165. /// Generation flags.
  166. class Flags {
  167. enum {
  168. F_IsForEH = 0x1,
  169. F_IsNormalCleanupKind = 0x2,
  170. F_IsEHCleanupKind = 0x4
  171. };
  172. unsigned flags;
  173. public:
  174. Flags() : flags(0) {}
  175. /// isForEH - true if the current emission is for an EH cleanup.
  176. bool isForEHCleanup() const { return flags & F_IsForEH; }
  177. bool isForNormalCleanup() const { return !isForEHCleanup(); }
  178. void setIsForEHCleanup() { flags |= F_IsForEH; }
  179. bool isNormalCleanupKind() const { return flags & F_IsNormalCleanupKind; }
  180. void setIsNormalCleanupKind() { flags |= F_IsNormalCleanupKind; }
  181. /// isEHCleanupKind - true if the cleanup was pushed as an EH
  182. /// cleanup.
  183. bool isEHCleanupKind() const { return flags & F_IsEHCleanupKind; }
  184. void setIsEHCleanupKind() { flags |= F_IsEHCleanupKind; }
  185. };
  186. // Provide a virtual destructor to suppress a very common warning
  187. // that unfortunately cannot be suppressed without this. Cleanups
  188. // should not rely on this destructor ever being called.
  189. virtual ~Cleanup() {}
  190. /// Emit the cleanup. For normal cleanups, this is run in the
  191. /// same EH context as when the cleanup was pushed, i.e. the
  192. /// immediately-enclosing context of the cleanup scope. For
  193. /// EH cleanups, this is run in a terminate context.
  194. ///
  195. // \param IsForEHCleanup true if this is for an EH cleanup, false
  196. /// if for a normal cleanup.
  197. virtual void Emit(CodeGenFunction &CGF, Flags flags) = 0;
  198. };
  199. /// ConditionalCleanupN stores the saved form of its N parameters,
  200. /// then restores them and performs the cleanup.
  201. template <class T, class A0>
  202. class ConditionalCleanup1 : public Cleanup {
  203. typedef typename DominatingValue<A0>::saved_type A0_saved;
  204. A0_saved a0_saved;
  205. void Emit(CodeGenFunction &CGF, Flags flags) {
  206. A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
  207. T(a0).Emit(CGF, flags);
  208. }
  209. public:
  210. ConditionalCleanup1(A0_saved a0)
  211. : a0_saved(a0) {}
  212. };
  213. template <class T, class A0, class A1>
  214. class ConditionalCleanup2 : public Cleanup {
  215. typedef typename DominatingValue<A0>::saved_type A0_saved;
  216. typedef typename DominatingValue<A1>::saved_type A1_saved;
  217. A0_saved a0_saved;
  218. A1_saved a1_saved;
  219. void Emit(CodeGenFunction &CGF, Flags flags) {
  220. A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
  221. A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
  222. T(a0, a1).Emit(CGF, flags);
  223. }
  224. public:
  225. ConditionalCleanup2(A0_saved a0, A1_saved a1)
  226. : a0_saved(a0), a1_saved(a1) {}
  227. };
  228. template <class T, class A0, class A1, class A2>
  229. class ConditionalCleanup3 : public Cleanup {
  230. typedef typename DominatingValue<A0>::saved_type A0_saved;
  231. typedef typename DominatingValue<A1>::saved_type A1_saved;
  232. typedef typename DominatingValue<A2>::saved_type A2_saved;
  233. A0_saved a0_saved;
  234. A1_saved a1_saved;
  235. A2_saved a2_saved;
  236. void Emit(CodeGenFunction &CGF, Flags flags) {
  237. A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
  238. A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
  239. A2 a2 = DominatingValue<A2>::restore(CGF, a2_saved);
  240. T(a0, a1, a2).Emit(CGF, flags);
  241. }
  242. public:
  243. ConditionalCleanup3(A0_saved a0, A1_saved a1, A2_saved a2)
  244. : a0_saved(a0), a1_saved(a1), a2_saved(a2) {}
  245. };
  246. template <class T, class A0, class A1, class A2, class A3>
  247. class ConditionalCleanup4 : public Cleanup {
  248. typedef typename DominatingValue<A0>::saved_type A0_saved;
  249. typedef typename DominatingValue<A1>::saved_type A1_saved;
  250. typedef typename DominatingValue<A2>::saved_type A2_saved;
  251. typedef typename DominatingValue<A3>::saved_type A3_saved;
  252. A0_saved a0_saved;
  253. A1_saved a1_saved;
  254. A2_saved a2_saved;
  255. A3_saved a3_saved;
  256. void Emit(CodeGenFunction &CGF, Flags flags) {
  257. A0 a0 = DominatingValue<A0>::restore(CGF, a0_saved);
  258. A1 a1 = DominatingValue<A1>::restore(CGF, a1_saved);
  259. A2 a2 = DominatingValue<A2>::restore(CGF, a2_saved);
  260. A3 a3 = DominatingValue<A3>::restore(CGF, a3_saved);
  261. T(a0, a1, a2, a3).Emit(CGF, flags);
  262. }
  263. public:
  264. ConditionalCleanup4(A0_saved a0, A1_saved a1, A2_saved a2, A3_saved a3)
  265. : a0_saved(a0), a1_saved(a1), a2_saved(a2), a3_saved(a3) {}
  266. };
  267. private:
  268. // The implementation for this class is in CGException.h and
  269. // CGException.cpp; the definition is here because it's used as a
  270. // member of CodeGenFunction.
  271. /// The start of the scope-stack buffer, i.e. the allocated pointer
  272. /// for the buffer. All of these pointers are either simultaneously
  273. /// null or simultaneously valid.
  274. char *StartOfBuffer;
  275. /// The end of the buffer.
  276. char *EndOfBuffer;
  277. /// The first valid entry in the buffer.
  278. char *StartOfData;
  279. /// The innermost normal cleanup on the stack.
  280. stable_iterator InnermostNormalCleanup;
  281. /// The innermost EH scope on the stack.
  282. stable_iterator InnermostEHScope;
  283. /// The current set of branch fixups. A branch fixup is a jump to
  284. /// an as-yet unemitted label, i.e. a label for which we don't yet
  285. /// know the EH stack depth. Whenever we pop a cleanup, we have
  286. /// to thread all the current branch fixups through it.
  287. ///
  288. /// Fixups are recorded as the Use of the respective branch or
  289. /// switch statement. The use points to the final destination.
  290. /// When popping out of a cleanup, these uses are threaded through
  291. /// the cleanup and adjusted to point to the new cleanup.
  292. ///
  293. /// Note that branches are allowed to jump into protected scopes
  294. /// in certain situations; e.g. the following code is legal:
  295. /// struct A { ~A(); }; // trivial ctor, non-trivial dtor
  296. /// goto foo;
  297. /// A a;
  298. /// foo:
  299. /// bar();
  300. SmallVector<BranchFixup, 8> BranchFixups;
  301. char *allocate(size_t Size);
  302. void *pushCleanup(CleanupKind K, size_t DataSize);
  303. public:
  304. EHScopeStack() : StartOfBuffer(0), EndOfBuffer(0), StartOfData(0),
  305. InnermostNormalCleanup(stable_end()),
  306. InnermostEHScope(stable_end()) {}
  307. ~EHScopeStack() { delete[] StartOfBuffer; }
  308. // Variadic templates would make this not terrible.
  309. /// Push a lazily-created cleanup on the stack.
  310. template <class T>
  311. void pushCleanup(CleanupKind Kind) {
  312. void *Buffer = pushCleanup(Kind, sizeof(T));
  313. Cleanup *Obj = new(Buffer) T();
  314. (void) Obj;
  315. }
  316. /// Push a lazily-created cleanup on the stack.
  317. template <class T, class A0>
  318. void pushCleanup(CleanupKind Kind, A0 a0) {
  319. void *Buffer = pushCleanup(Kind, sizeof(T));
  320. Cleanup *Obj = new(Buffer) T(a0);
  321. (void) Obj;
  322. }
  323. /// Push a lazily-created cleanup on the stack.
  324. template <class T, class A0, class A1>
  325. void pushCleanup(CleanupKind Kind, A0 a0, A1 a1) {
  326. void *Buffer = pushCleanup(Kind, sizeof(T));
  327. Cleanup *Obj = new(Buffer) T(a0, a1);
  328. (void) Obj;
  329. }
  330. /// Push a lazily-created cleanup on the stack.
  331. template <class T, class A0, class A1, class A2>
  332. void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2) {
  333. void *Buffer = pushCleanup(Kind, sizeof(T));
  334. Cleanup *Obj = new(Buffer) T(a0, a1, a2);
  335. (void) Obj;
  336. }
  337. /// Push a lazily-created cleanup on the stack.
  338. template <class T, class A0, class A1, class A2, class A3>
  339. void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3) {
  340. void *Buffer = pushCleanup(Kind, sizeof(T));
  341. Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3);
  342. (void) Obj;
  343. }
  344. /// Push a lazily-created cleanup on the stack.
  345. template <class T, class A0, class A1, class A2, class A3, class A4>
  346. void pushCleanup(CleanupKind Kind, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4) {
  347. void *Buffer = pushCleanup(Kind, sizeof(T));
  348. Cleanup *Obj = new(Buffer) T(a0, a1, a2, a3, a4);
  349. (void) Obj;
  350. }
  351. // Feel free to add more variants of the following:
  352. /// Push a cleanup with non-constant storage requirements on the
  353. /// stack. The cleanup type must provide an additional static method:
  354. /// static size_t getExtraSize(size_t);
  355. /// The argument to this method will be the value N, which will also
  356. /// be passed as the first argument to the constructor.
  357. ///
  358. /// The data stored in the extra storage must obey the same
  359. /// restrictions as normal cleanup member data.
  360. ///
  361. /// The pointer returned from this method is valid until the cleanup
  362. /// stack is modified.
  363. template <class T, class A0, class A1, class A2>
  364. T *pushCleanupWithExtra(CleanupKind Kind, size_t N, A0 a0, A1 a1, A2 a2) {
  365. void *Buffer = pushCleanup(Kind, sizeof(T) + T::getExtraSize(N));
  366. return new (Buffer) T(N, a0, a1, a2);
  367. }
  368. /// Pops a cleanup scope off the stack. This is private to CGCleanup.cpp.
  369. void popCleanup();
  370. /// Push a set of catch handlers on the stack. The catch is
  371. /// uninitialized and will need to have the given number of handlers
  372. /// set on it.
  373. class EHCatchScope *pushCatch(unsigned NumHandlers);
  374. /// Pops a catch scope off the stack. This is private to CGException.cpp.
  375. void popCatch();
  376. /// Push an exceptions filter on the stack.
  377. class EHFilterScope *pushFilter(unsigned NumFilters);
  378. /// Pops an exceptions filter off the stack.
  379. void popFilter();
  380. /// Push a terminate handler on the stack.
  381. void pushTerminate();
  382. /// Pops a terminate handler off the stack.
  383. void popTerminate();
  384. /// Determines whether the exception-scopes stack is empty.
  385. bool empty() const { return StartOfData == EndOfBuffer; }
  386. bool requiresLandingPad() const {
  387. return InnermostEHScope != stable_end();
  388. }
  389. /// Determines whether there are any normal cleanups on the stack.
  390. bool hasNormalCleanups() const {
  391. return InnermostNormalCleanup != stable_end();
  392. }
  393. /// Returns the innermost normal cleanup on the stack, or
  394. /// stable_end() if there are no normal cleanups.
  395. stable_iterator getInnermostNormalCleanup() const {
  396. return InnermostNormalCleanup;
  397. }
  398. stable_iterator getInnermostActiveNormalCleanup() const;
  399. stable_iterator getInnermostEHScope() const {
  400. return InnermostEHScope;
  401. }
  402. stable_iterator getInnermostActiveEHScope() const;
  403. /// An unstable reference to a scope-stack depth. Invalidated by
  404. /// pushes but not pops.
  405. class iterator;
  406. /// Returns an iterator pointing to the innermost EH scope.
  407. iterator begin() const;
  408. /// Returns an iterator pointing to the outermost EH scope.
  409. iterator end() const;
  410. /// Create a stable reference to the top of the EH stack. The
  411. /// returned reference is valid until that scope is popped off the
  412. /// stack.
  413. stable_iterator stable_begin() const {
  414. return stable_iterator(EndOfBuffer - StartOfData);
  415. }
  416. /// Create a stable reference to the bottom of the EH stack.
  417. static stable_iterator stable_end() {
  418. return stable_iterator(0);
  419. }
  420. /// Translates an iterator into a stable_iterator.
  421. stable_iterator stabilize(iterator it) const;
  422. /// Turn a stable reference to a scope depth into a unstable pointer
  423. /// to the EH stack.
  424. iterator find(stable_iterator save) const;
  425. /// Removes the cleanup pointed to by the given stable_iterator.
  426. void removeCleanup(stable_iterator save);
  427. /// Add a branch fixup to the current cleanup scope.
  428. BranchFixup &addBranchFixup() {
  429. assert(hasNormalCleanups() && "adding fixup in scope without cleanups");
  430. BranchFixups.push_back(BranchFixup());
  431. return BranchFixups.back();
  432. }
  433. unsigned getNumBranchFixups() const { return BranchFixups.size(); }
  434. BranchFixup &getBranchFixup(unsigned I) {
  435. assert(I < getNumBranchFixups());
  436. return BranchFixups[I];
  437. }
  438. /// Pops lazily-removed fixups from the end of the list. This
  439. /// should only be called by procedures which have just popped a
  440. /// cleanup or resolved one or more fixups.
  441. void popNullFixups();
  442. /// Clears the branch-fixups list. This should only be called by
  443. /// ResolveAllBranchFixups.
  444. void clearFixups() { BranchFixups.clear(); }
  445. };
  446. /// CodeGenFunction - This class organizes the per-function state that is used
  447. /// while generating LLVM code.
  448. class CodeGenFunction : public CodeGenTypeCache {
  449. CodeGenFunction(const CodeGenFunction&); // DO NOT IMPLEMENT
  450. void operator=(const CodeGenFunction&); // DO NOT IMPLEMENT
  451. friend class CGCXXABI;
  452. public:
  453. /// A jump destination is an abstract label, branching to which may
  454. /// require a jump out through normal cleanups.
  455. struct JumpDest {
  456. JumpDest() : Block(0), ScopeDepth(), Index(0) {}
  457. JumpDest(llvm::BasicBlock *Block,
  458. EHScopeStack::stable_iterator Depth,
  459. unsigned Index)
  460. : Block(Block), ScopeDepth(Depth), Index(Index) {}
  461. bool isValid() const { return Block != 0; }
  462. llvm::BasicBlock *getBlock() const { return Block; }
  463. EHScopeStack::stable_iterator getScopeDepth() const { return ScopeDepth; }
  464. unsigned getDestIndex() const { return Index; }
  465. private:
  466. llvm::BasicBlock *Block;
  467. EHScopeStack::stable_iterator ScopeDepth;
  468. unsigned Index;
  469. };
  470. CodeGenModule &CGM; // Per-module state.
  471. const TargetInfo &Target;
  472. typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
  473. CGBuilderTy Builder;
  474. /// CurFuncDecl - Holds the Decl for the current function or ObjC method.
  475. /// This excludes BlockDecls.
  476. const Decl *CurFuncDecl;
  477. /// CurCodeDecl - This is the inner-most code context, which includes blocks.
  478. const Decl *CurCodeDecl;
  479. const CGFunctionInfo *CurFnInfo;
  480. QualType FnRetTy;
  481. llvm::Function *CurFn;
  482. /// CurGD - The GlobalDecl for the current function being compiled.
  483. GlobalDecl CurGD;
  484. /// PrologueCleanupDepth - The cleanup depth enclosing all the
  485. /// cleanups associated with the parameters.
  486. EHScopeStack::stable_iterator PrologueCleanupDepth;
  487. /// ReturnBlock - Unified return block.
  488. JumpDest ReturnBlock;
  489. /// ReturnValue - The temporary alloca to hold the return value. This is null
  490. /// iff the function has no return value.
  491. llvm::Value *ReturnValue;
  492. /// AllocaInsertPoint - This is an instruction in the entry block before which
  493. /// we prefer to insert allocas.
  494. llvm::AssertingVH<llvm::Instruction> AllocaInsertPt;
  495. /// BoundsChecking - Emit run-time bounds checks. Higher values mean
  496. /// potentially higher performance penalties.
  497. unsigned char BoundsChecking;
  498. /// CatchUndefined - Emit run-time checks to catch undefined behaviors.
  499. bool CatchUndefined;
  500. /// In ARC, whether we should autorelease the return value.
  501. bool AutoreleaseResult;
  502. const CodeGen::CGBlockInfo *BlockInfo;
  503. llvm::Value *BlockPointer;
  504. llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
  505. FieldDecl *LambdaThisCaptureField;
  506. /// \brief A mapping from NRVO variables to the flags used to indicate
  507. /// when the NRVO has been applied to this variable.
  508. llvm::DenseMap<const VarDecl *, llvm::Value *> NRVOFlags;
  509. EHScopeStack EHStack;
  510. /// i32s containing the indexes of the cleanup destinations.
  511. llvm::AllocaInst *NormalCleanupDest;
  512. unsigned NextCleanupDestIndex;
  513. /// FirstBlockInfo - The head of a singly-linked-list of block layouts.
  514. CGBlockInfo *FirstBlockInfo;
  515. /// EHResumeBlock - Unified block containing a call to llvm.eh.resume.
  516. llvm::BasicBlock *EHResumeBlock;
  517. /// The exception slot. All landing pads write the current exception pointer
  518. /// into this alloca.
  519. llvm::Value *ExceptionSlot;
  520. /// The selector slot. Under the MandatoryCleanup model, all landing pads
  521. /// write the current selector value into this alloca.
  522. llvm::AllocaInst *EHSelectorSlot;
  523. /// Emits a landing pad for the current EH stack.
  524. llvm::BasicBlock *EmitLandingPad();
  525. llvm::BasicBlock *getInvokeDestImpl();
  526. template <class T>
  527. typename DominatingValue<T>::saved_type saveValueInCond(T value) {
  528. return DominatingValue<T>::save(*this, value);
  529. }
  530. public:
  531. /// ObjCEHValueStack - Stack of Objective-C exception values, used for
  532. /// rethrows.
  533. SmallVector<llvm::Value*, 8> ObjCEHValueStack;
  534. /// A class controlling the emission of a finally block.
  535. class FinallyInfo {
  536. /// Where the catchall's edge through the cleanup should go.
  537. JumpDest RethrowDest;
  538. /// A function to call to enter the catch.
  539. llvm::Constant *BeginCatchFn;
  540. /// An i1 variable indicating whether or not the @finally is
  541. /// running for an exception.
  542. llvm::AllocaInst *ForEHVar;
  543. /// An i8* variable into which the exception pointer to rethrow
  544. /// has been saved.
  545. llvm::AllocaInst *SavedExnVar;
  546. public:
  547. void enter(CodeGenFunction &CGF, const Stmt *Finally,
  548. llvm::Constant *beginCatchFn, llvm::Constant *endCatchFn,
  549. llvm::Constant *rethrowFn);
  550. void exit(CodeGenFunction &CGF);
  551. };
  552. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  553. /// current full-expression. Safe against the possibility that
  554. /// we're currently inside a conditionally-evaluated expression.
  555. template <class T, class A0>
  556. void pushFullExprCleanup(CleanupKind kind, A0 a0) {
  557. // If we're not in a conditional branch, or if none of the
  558. // arguments requires saving, then use the unconditional cleanup.
  559. if (!isInConditionalBranch())
  560. return EHStack.pushCleanup<T>(kind, a0);
  561. typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
  562. typedef EHScopeStack::ConditionalCleanup1<T, A0> CleanupType;
  563. EHStack.pushCleanup<CleanupType>(kind, a0_saved);
  564. initFullExprCleanup();
  565. }
  566. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  567. /// current full-expression. Safe against the possibility that
  568. /// we're currently inside a conditionally-evaluated expression.
  569. template <class T, class A0, class A1>
  570. void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1) {
  571. // If we're not in a conditional branch, or if none of the
  572. // arguments requires saving, then use the unconditional cleanup.
  573. if (!isInConditionalBranch())
  574. return EHStack.pushCleanup<T>(kind, a0, a1);
  575. typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
  576. typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
  577. typedef EHScopeStack::ConditionalCleanup2<T, A0, A1> CleanupType;
  578. EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved);
  579. initFullExprCleanup();
  580. }
  581. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  582. /// current full-expression. Safe against the possibility that
  583. /// we're currently inside a conditionally-evaluated expression.
  584. template <class T, class A0, class A1, class A2>
  585. void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2) {
  586. // If we're not in a conditional branch, or if none of the
  587. // arguments requires saving, then use the unconditional cleanup.
  588. if (!isInConditionalBranch()) {
  589. return EHStack.pushCleanup<T>(kind, a0, a1, a2);
  590. }
  591. typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
  592. typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
  593. typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2);
  594. typedef EHScopeStack::ConditionalCleanup3<T, A0, A1, A2> CleanupType;
  595. EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved, a2_saved);
  596. initFullExprCleanup();
  597. }
  598. /// pushFullExprCleanup - Push a cleanup to be run at the end of the
  599. /// current full-expression. Safe against the possibility that
  600. /// we're currently inside a conditionally-evaluated expression.
  601. template <class T, class A0, class A1, class A2, class A3>
  602. void pushFullExprCleanup(CleanupKind kind, A0 a0, A1 a1, A2 a2, A3 a3) {
  603. // If we're not in a conditional branch, or if none of the
  604. // arguments requires saving, then use the unconditional cleanup.
  605. if (!isInConditionalBranch()) {
  606. return EHStack.pushCleanup<T>(kind, a0, a1, a2, a3);
  607. }
  608. typename DominatingValue<A0>::saved_type a0_saved = saveValueInCond(a0);
  609. typename DominatingValue<A1>::saved_type a1_saved = saveValueInCond(a1);
  610. typename DominatingValue<A2>::saved_type a2_saved = saveValueInCond(a2);
  611. typename DominatingValue<A3>::saved_type a3_saved = saveValueInCond(a3);
  612. typedef EHScopeStack::ConditionalCleanup4<T, A0, A1, A2, A3> CleanupType;
  613. EHStack.pushCleanup<CleanupType>(kind, a0_saved, a1_saved,
  614. a2_saved, a3_saved);
  615. initFullExprCleanup();
  616. }
  617. /// Set up the last cleaup that was pushed as a conditional
  618. /// full-expression cleanup.
  619. void initFullExprCleanup();
  620. /// PushDestructorCleanup - Push a cleanup to call the
  621. /// complete-object destructor of an object of the given type at the
  622. /// given address. Does nothing if T is not a C++ class type with a
  623. /// non-trivial destructor.
  624. void PushDestructorCleanup(QualType T, llvm::Value *Addr);
  625. /// PushDestructorCleanup - Push a cleanup to call the
  626. /// complete-object variant of the given destructor on the object at
  627. /// the given address.
  628. void PushDestructorCleanup(const CXXDestructorDecl *Dtor,
  629. llvm::Value *Addr);
  630. /// PopCleanupBlock - Will pop the cleanup entry on the stack and
  631. /// process all branch fixups.
  632. void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
  633. /// DeactivateCleanupBlock - Deactivates the given cleanup block.
  634. /// The block cannot be reactivated. Pops it if it's the top of the
  635. /// stack.
  636. ///
  637. /// \param DominatingIP - An instruction which is known to
  638. /// dominate the current IP (if set) and which lies along
  639. /// all paths of execution between the current IP and the
  640. /// the point at which the cleanup comes into scope.
  641. void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
  642. llvm::Instruction *DominatingIP);
  643. /// ActivateCleanupBlock - Activates an initially-inactive cleanup.
  644. /// Cannot be used to resurrect a deactivated cleanup.
  645. ///
  646. /// \param DominatingIP - An instruction which is known to
  647. /// dominate the current IP (if set) and which lies along
  648. /// all paths of execution between the current IP and the
  649. /// the point at which the cleanup comes into scope.
  650. void ActivateCleanupBlock(EHScopeStack::stable_iterator Cleanup,
  651. llvm::Instruction *DominatingIP);
  652. /// \brief Enters a new scope for capturing cleanups, all of which
  653. /// will be executed once the scope is exited.
  654. class RunCleanupsScope {
  655. EHScopeStack::stable_iterator CleanupStackDepth;
  656. bool OldDidCallStackSave;
  657. bool PerformCleanup;
  658. RunCleanupsScope(const RunCleanupsScope &); // DO NOT IMPLEMENT
  659. RunCleanupsScope &operator=(const RunCleanupsScope &); // DO NOT IMPLEMENT
  660. protected:
  661. CodeGenFunction& CGF;
  662. public:
  663. /// \brief Enter a new cleanup scope.
  664. explicit RunCleanupsScope(CodeGenFunction &CGF)
  665. : PerformCleanup(true), CGF(CGF)
  666. {
  667. CleanupStackDepth = CGF.EHStack.stable_begin();
  668. OldDidCallStackSave = CGF.DidCallStackSave;
  669. CGF.DidCallStackSave = false;
  670. }
  671. /// \brief Exit this cleanup scope, emitting any accumulated
  672. /// cleanups.
  673. ~RunCleanupsScope() {
  674. if (PerformCleanup) {
  675. CGF.DidCallStackSave = OldDidCallStackSave;
  676. CGF.PopCleanupBlocks(CleanupStackDepth);
  677. }
  678. }
  679. /// \brief Determine whether this scope requires any cleanups.
  680. bool requiresCleanups() const {
  681. return CGF.EHStack.stable_begin() != CleanupStackDepth;
  682. }
  683. /// \brief Force the emission of cleanups now, instead of waiting
  684. /// until this object is destroyed.
  685. void ForceCleanup() {
  686. assert(PerformCleanup && "Already forced cleanup");
  687. CGF.DidCallStackSave = OldDidCallStackSave;
  688. CGF.PopCleanupBlocks(CleanupStackDepth);
  689. PerformCleanup = false;
  690. }
  691. };
  692. class LexicalScope: protected RunCleanupsScope {
  693. SourceRange Range;
  694. bool PopDebugStack;
  695. LexicalScope(const LexicalScope &); // DO NOT IMPLEMENT THESE
  696. LexicalScope &operator=(const LexicalScope &);
  697. public:
  698. /// \brief Enter a new cleanup scope.
  699. explicit LexicalScope(CodeGenFunction &CGF, SourceRange Range)
  700. : RunCleanupsScope(CGF), Range(Range), PopDebugStack(true) {
  701. if (CGDebugInfo *DI = CGF.getDebugInfo())
  702. DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
  703. }
  704. /// \brief Exit this cleanup scope, emitting any accumulated
  705. /// cleanups.
  706. ~LexicalScope() {
  707. if (PopDebugStack) {
  708. CGDebugInfo *DI = CGF.getDebugInfo();
  709. if (DI) DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
  710. }
  711. }
  712. /// \brief Force the emission of cleanups now, instead of waiting
  713. /// until this object is destroyed.
  714. void ForceCleanup() {
  715. RunCleanupsScope::ForceCleanup();
  716. if (CGDebugInfo *DI = CGF.getDebugInfo()) {
  717. DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
  718. PopDebugStack = false;
  719. }
  720. }
  721. };
  722. /// PopCleanupBlocks - Takes the old cleanup stack size and emits
  723. /// the cleanup blocks that have been added.
  724. void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
  725. void ResolveBranchFixups(llvm::BasicBlock *Target);
  726. /// The given basic block lies in the current EH scope, but may be a
  727. /// target of a potentially scope-crossing jump; get a stable handle
  728. /// to which we can perform this jump later.
  729. JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target) {
  730. return JumpDest(Target,
  731. EHStack.getInnermostNormalCleanup(),
  732. NextCleanupDestIndex++);
  733. }
  734. /// The given basic block lies in the current EH scope, but may be a
  735. /// target of a potentially scope-crossing jump; get a stable handle
  736. /// to which we can perform this jump later.
  737. JumpDest getJumpDestInCurrentScope(StringRef Name = StringRef()) {
  738. return getJumpDestInCurrentScope(createBasicBlock(Name));
  739. }
  740. /// EmitBranchThroughCleanup - Emit a branch from the current insert
  741. /// block through the normal cleanup handling code (if any) and then
  742. /// on to \arg Dest.
  743. void EmitBranchThroughCleanup(JumpDest Dest);
  744. /// isObviouslyBranchWithoutCleanups - Return true if a branch to the
  745. /// specified destination obviously has no cleanups to run. 'false' is always
  746. /// a conservatively correct answer for this method.
  747. bool isObviouslyBranchWithoutCleanups(JumpDest Dest) const;
  748. /// popCatchScope - Pops the catch scope at the top of the EHScope
  749. /// stack, emitting any required code (other than the catch handlers
  750. /// themselves).
  751. void popCatchScope();
  752. llvm::BasicBlock *getEHResumeBlock();
  753. llvm::BasicBlock *getEHDispatchBlock(EHScopeStack::stable_iterator scope);
  754. /// An object to manage conditionally-evaluated expressions.
  755. class ConditionalEvaluation {
  756. llvm::BasicBlock *StartBB;
  757. public:
  758. ConditionalEvaluation(CodeGenFunction &CGF)
  759. : StartBB(CGF.Builder.GetInsertBlock()) {}
  760. void begin(CodeGenFunction &CGF) {
  761. assert(CGF.OutermostConditional != this);
  762. if (!CGF.OutermostConditional)
  763. CGF.OutermostConditional = this;
  764. }
  765. void end(CodeGenFunction &CGF) {
  766. assert(CGF.OutermostConditional != 0);
  767. if (CGF.OutermostConditional == this)
  768. CGF.OutermostConditional = 0;
  769. }
  770. /// Returns a block which will be executed prior to each
  771. /// evaluation of the conditional code.
  772. llvm::BasicBlock *getStartingBlock() const {
  773. return StartBB;
  774. }
  775. };
  776. /// isInConditionalBranch - Return true if we're currently emitting
  777. /// one branch or the other of a conditional expression.
  778. bool isInConditionalBranch() const { return OutermostConditional != 0; }
  779. void setBeforeOutermostConditional(llvm::Value *value, llvm::Value *addr) {
  780. assert(isInConditionalBranch());
  781. llvm::BasicBlock *block = OutermostConditional->getStartingBlock();
  782. new llvm::StoreInst(value, addr, &block->back());
  783. }
  784. /// An RAII object to record that we're evaluating a statement
  785. /// expression.
  786. class StmtExprEvaluation {
  787. CodeGenFunction &CGF;
  788. /// We have to save the outermost conditional: cleanups in a
  789. /// statement expression aren't conditional just because the
  790. /// StmtExpr is.
  791. ConditionalEvaluation *SavedOutermostConditional;
  792. public:
  793. StmtExprEvaluation(CodeGenFunction &CGF)
  794. : CGF(CGF), SavedOutermostConditional(CGF.OutermostConditional) {
  795. CGF.OutermostConditional = 0;
  796. }
  797. ~StmtExprEvaluation() {
  798. CGF.OutermostConditional = SavedOutermostConditional;
  799. CGF.EnsureInsertPoint();
  800. }
  801. };
  802. /// An object which temporarily prevents a value from being
  803. /// destroyed by aggressive peephole optimizations that assume that
  804. /// all uses of a value have been realized in the IR.
  805. class PeepholeProtection {
  806. llvm::Instruction *Inst;
  807. friend class CodeGenFunction;
  808. public:
  809. PeepholeProtection() : Inst(0) {}
  810. };
  811. /// A non-RAII class containing all the information about a bound
  812. /// opaque value. OpaqueValueMapping, below, is a RAII wrapper for
  813. /// this which makes individual mappings very simple; using this
  814. /// class directly is useful when you have a variable number of
  815. /// opaque values or don't want the RAII functionality for some
  816. /// reason.
  817. class OpaqueValueMappingData {
  818. const OpaqueValueExpr *OpaqueValue;
  819. bool BoundLValue;
  820. CodeGenFunction::PeepholeProtection Protection;
  821. OpaqueValueMappingData(const OpaqueValueExpr *ov,
  822. bool boundLValue)
  823. : OpaqueValue(ov), BoundLValue(boundLValue) {}
  824. public:
  825. OpaqueValueMappingData() : OpaqueValue(0) {}
  826. static bool shouldBindAsLValue(const Expr *expr) {
  827. // gl-values should be bound as l-values for obvious reasons.
  828. // Records should be bound as l-values because IR generation
  829. // always keeps them in memory. Expressions of function type
  830. // act exactly like l-values but are formally required to be
  831. // r-values in C.
  832. return expr->isGLValue() ||
  833. expr->getType()->isRecordType() ||
  834. expr->getType()->isFunctionType();
  835. }
  836. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  837. const OpaqueValueExpr *ov,
  838. const Expr *e) {
  839. if (shouldBindAsLValue(ov))
  840. return bind(CGF, ov, CGF.EmitLValue(e));
  841. return bind(CGF, ov, CGF.EmitAnyExpr(e));
  842. }
  843. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  844. const OpaqueValueExpr *ov,
  845. const LValue &lv) {
  846. assert(shouldBindAsLValue(ov));
  847. CGF.OpaqueLValues.insert(std::make_pair(ov, lv));
  848. return OpaqueValueMappingData(ov, true);
  849. }
  850. static OpaqueValueMappingData bind(CodeGenFunction &CGF,
  851. const OpaqueValueExpr *ov,
  852. const RValue &rv) {
  853. assert(!shouldBindAsLValue(ov));
  854. CGF.OpaqueRValues.insert(std::make_pair(ov, rv));
  855. OpaqueValueMappingData data(ov, false);
  856. // Work around an extremely aggressive peephole optimization in
  857. // EmitScalarConversion which assumes that all other uses of a
  858. // value are extant.
  859. data.Protection = CGF.protectFromPeepholes(rv);
  860. return data;
  861. }
  862. bool isValid() const { return OpaqueValue != 0; }
  863. void clear() { OpaqueValue = 0; }
  864. void unbind(CodeGenFunction &CGF) {
  865. assert(OpaqueValue && "no data to unbind!");
  866. if (BoundLValue) {
  867. CGF.OpaqueLValues.erase(OpaqueValue);
  868. } else {
  869. CGF.OpaqueRValues.erase(OpaqueValue);
  870. CGF.unprotectFromPeepholes(Protection);
  871. }
  872. }
  873. };
  874. /// An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
  875. class OpaqueValueMapping {
  876. CodeGenFunction &CGF;
  877. OpaqueValueMappingData Data;
  878. public:
  879. static bool shouldBindAsLValue(const Expr *expr) {
  880. return OpaqueValueMappingData::shouldBindAsLValue(expr);
  881. }
  882. /// Build the opaque value mapping for the given conditional
  883. /// operator if it's the GNU ?: extension. This is a common
  884. /// enough pattern that the convenience operator is really
  885. /// helpful.
  886. ///
  887. OpaqueValueMapping(CodeGenFunction &CGF,
  888. const AbstractConditionalOperator *op) : CGF(CGF) {
  889. if (isa<ConditionalOperator>(op))
  890. // Leave Data empty.
  891. return;
  892. const BinaryConditionalOperator *e = cast<BinaryConditionalOperator>(op);
  893. Data = OpaqueValueMappingData::bind(CGF, e->getOpaqueValue(),
  894. e->getCommon());
  895. }
  896. OpaqueValueMapping(CodeGenFunction &CGF,
  897. const OpaqueValueExpr *opaqueValue,
  898. LValue lvalue)
  899. : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, lvalue)) {
  900. }
  901. OpaqueValueMapping(CodeGenFunction &CGF,
  902. const OpaqueValueExpr *opaqueValue,
  903. RValue rvalue)
  904. : CGF(CGF), Data(OpaqueValueMappingData::bind(CGF, opaqueValue, rvalue)) {
  905. }
  906. void pop() {
  907. Data.unbind(CGF);
  908. Data.clear();
  909. }
  910. ~OpaqueValueMapping() {
  911. if (Data.isValid()) Data.unbind(CGF);
  912. }
  913. };
  914. /// getByrefValueFieldNumber - Given a declaration, returns the LLVM field
  915. /// number that holds the value.
  916. unsigned getByRefValueLLVMField(const ValueDecl *VD) const;
  917. /// BuildBlockByrefAddress - Computes address location of the
  918. /// variable which is declared as __block.
  919. llvm::Value *BuildBlockByrefAddress(llvm::Value *BaseAddr,
  920. const VarDecl *V);
  921. private:
  922. CGDebugInfo *DebugInfo;
  923. bool DisableDebugInfo;
  924. /// DidCallStackSave - Whether llvm.stacksave has been called. Used to avoid
  925. /// calling llvm.stacksave for multiple VLAs in the same scope.
  926. bool DidCallStackSave;
  927. /// IndirectBranch - The first time an indirect goto is seen we create a block
  928. /// with an indirect branch. Every time we see the address of a label taken,
  929. /// we add the label to the indirect goto. Every subsequent indirect goto is
  930. /// codegen'd as a jump to the IndirectBranch's basic block.
  931. llvm::IndirectBrInst *IndirectBranch;
  932. /// LocalDeclMap - This keeps track of the LLVM allocas or globals for local C
  933. /// decls.
  934. typedef llvm::DenseMap<const Decl*, llvm::Value*> DeclMapTy;
  935. DeclMapTy LocalDeclMap;
  936. /// LabelMap - This keeps track of the LLVM basic block for each C label.
  937. llvm::DenseMap<const LabelDecl*, JumpDest> LabelMap;
  938. // BreakContinueStack - This keeps track of where break and continue
  939. // statements should jump to.
  940. struct BreakContinue {
  941. BreakContinue(JumpDest Break, JumpDest Continue)
  942. : BreakBlock(Break), ContinueBlock(Continue) {}
  943. JumpDest BreakBlock;
  944. JumpDest ContinueBlock;
  945. };
  946. SmallVector<BreakContinue, 8> BreakContinueStack;
  947. /// SwitchInsn - This is nearest current switch instruction. It is null if
  948. /// current context is not in a switch.
  949. llvm::SwitchInst *SwitchInsn;
  950. /// CaseRangeBlock - This block holds if condition check for last case
  951. /// statement range in current switch instruction.
  952. llvm::BasicBlock *CaseRangeBlock;
  953. /// OpaqueLValues - Keeps track of the current set of opaque value
  954. /// expressions.
  955. llvm::DenseMap<const OpaqueValueExpr *, LValue> OpaqueLValues;
  956. llvm::DenseMap<const OpaqueValueExpr *, RValue> OpaqueRValues;
  957. // VLASizeMap - This keeps track of the associated size for each VLA type.
  958. // We track this by the size expression rather than the type itself because
  959. // in certain situations, like a const qualifier applied to an VLA typedef,
  960. // multiple VLA types can share the same size expression.
  961. // FIXME: Maybe this could be a stack of maps that is pushed/popped as we
  962. // enter/leave scopes.
  963. llvm::DenseMap<const Expr*, llvm::Value*> VLASizeMap;
  964. /// A block containing a single 'unreachable' instruction. Created
  965. /// lazily by getUnreachableBlock().
  966. llvm::BasicBlock *UnreachableBlock;
  967. /// CXXThisDecl - When generating code for a C++ member function,
  968. /// this will hold the implicit 'this' declaration.
  969. ImplicitParamDecl *CXXABIThisDecl;
  970. llvm::Value *CXXABIThisValue;
  971. llvm::Value *CXXThisValue;
  972. /// CXXVTTDecl - When generating code for a base object constructor or
  973. /// base object destructor with virtual bases, this will hold the implicit
  974. /// VTT parameter.
  975. ImplicitParamDecl *CXXVTTDecl;
  976. llvm::Value *CXXVTTValue;
  977. /// OutermostConditional - Points to the outermost active
  978. /// conditional control. This is used so that we know if a
  979. /// temporary should be destroyed conditionally.
  980. ConditionalEvaluation *OutermostConditional;
  981. /// ByrefValueInfoMap - For each __block variable, contains a pair of the LLVM
  982. /// type as well as the field number that contains the actual data.
  983. llvm::DenseMap<const ValueDecl *, std::pair<llvm::Type *,
  984. unsigned> > ByRefValueInfo;
  985. llvm::BasicBlock *TerminateLandingPad;
  986. llvm::BasicBlock *TerminateHandler;
  987. llvm::BasicBlock *TrapBB;
  988. public:
  989. CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext=false);
  990. ~CodeGenFunction();
  991. CodeGenTypes &getTypes() const { return CGM.getTypes(); }
  992. ASTContext &getContext() const { return CGM.getContext(); }
  993. CGDebugInfo *getDebugInfo() {
  994. if (DisableDebugInfo)
  995. return NULL;
  996. return DebugInfo;
  997. }
  998. void disableDebugInfo() { DisableDebugInfo = true; }
  999. void enableDebugInfo() { DisableDebugInfo = false; }
  1000. bool shouldUseFusedARCCalls() {
  1001. return CGM.getCodeGenOpts().OptimizationLevel == 0;
  1002. }
  1003. const LangOptions &getLangOpts() const { return CGM.getLangOpts(); }
  1004. /// Returns a pointer to the function's exception object and selector slot,
  1005. /// which is assigned in every landing pad.
  1006. llvm::Value *getExceptionSlot();
  1007. llvm::Value *getEHSelectorSlot();
  1008. /// Returns the contents of the function's exception object and selector
  1009. /// slots.
  1010. llvm::Value *getExceptionFromSlot();
  1011. llvm::Value *getSelectorFromSlot();
  1012. llvm::Value *getNormalCleanupDestSlot();
  1013. llvm::BasicBlock *getUnreachableBlock() {
  1014. if (!UnreachableBlock) {
  1015. UnreachableBlock = createBasicBlock("unreachable");
  1016. new llvm::UnreachableInst(getLLVMContext(), UnreachableBlock);
  1017. }
  1018. return UnreachableBlock;
  1019. }
  1020. llvm::BasicBlock *getInvokeDest() {
  1021. if (!EHStack.requiresLandingPad()) return 0;
  1022. return getInvokeDestImpl();
  1023. }
  1024. llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
  1025. //===--------------------------------------------------------------------===//
  1026. // Cleanups
  1027. //===--------------------------------------------------------------------===//
  1028. typedef void Destroyer(CodeGenFunction &CGF, llvm::Value *addr, QualType ty);
  1029. void pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
  1030. llvm::Value *arrayEndPointer,
  1031. QualType elementType,
  1032. Destroyer *destroyer);
  1033. void pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
  1034. llvm::Value *arrayEnd,
  1035. QualType elementType,
  1036. Destroyer *destroyer);
  1037. void pushDestroy(QualType::DestructionKind dtorKind,
  1038. llvm::Value *addr, QualType type);
  1039. void pushDestroy(CleanupKind kind, llvm::Value *addr, QualType type,
  1040. Destroyer *destroyer, bool useEHCleanupForArray);
  1041. void emitDestroy(llvm::Value *addr, QualType type, Destroyer *destroyer,
  1042. bool useEHCleanupForArray);
  1043. llvm::Function *generateDestroyHelper(llvm::Constant *addr,
  1044. QualType type,
  1045. Destroyer *destroyer,
  1046. bool useEHCleanupForArray);
  1047. void emitArrayDestroy(llvm::Value *begin, llvm::Value *end,
  1048. QualType type, Destroyer *destroyer,
  1049. bool checkZeroLength, bool useEHCleanup);
  1050. Destroyer *getDestroyer(QualType::DestructionKind destructionKind);
  1051. /// Determines whether an EH cleanup is required to destroy a type
  1052. /// with the given destruction kind.
  1053. bool needsEHCleanup(QualType::DestructionKind kind) {
  1054. switch (kind) {
  1055. case QualType::DK_none:
  1056. return false;
  1057. case QualType::DK_cxx_destructor:
  1058. case QualType::DK_objc_weak_lifetime:
  1059. return getLangOpts().Exceptions;
  1060. case QualType::DK_objc_strong_lifetime:
  1061. return getLangOpts().Exceptions &&
  1062. CGM.getCodeGenOpts().ObjCAutoRefCountExceptions;
  1063. }
  1064. llvm_unreachable("bad destruction kind");
  1065. }
  1066. CleanupKind getCleanupKind(QualType::DestructionKind kind) {
  1067. return (needsEHCleanup(kind) ? NormalAndEHCleanup : NormalCleanup);
  1068. }
  1069. //===--------------------------------------------------------------------===//
  1070. // Objective-C
  1071. //===--------------------------------------------------------------------===//
  1072. void GenerateObjCMethod(const ObjCMethodDecl *OMD);
  1073. void StartObjCMethod(const ObjCMethodDecl *MD,
  1074. const ObjCContainerDecl *CD,
  1075. SourceLocation StartLoc);
  1076. /// GenerateObjCGetter - Synthesize an Objective-C property getter function.
  1077. void GenerateObjCGetter(ObjCImplementationDecl *IMP,
  1078. const ObjCPropertyImplDecl *PID);
  1079. void generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
  1080. const ObjCPropertyImplDecl *propImpl,
  1081. const ObjCMethodDecl *GetterMothodDecl,
  1082. llvm::Constant *AtomicHelperFn);
  1083. void GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
  1084. ObjCMethodDecl *MD, bool ctor);
  1085. /// GenerateObjCSetter - Synthesize an Objective-C property setter function
  1086. /// for the given property.
  1087. void GenerateObjCSetter(ObjCImplementationDecl *IMP,
  1088. const ObjCPropertyImplDecl *PID);
  1089. void generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
  1090. const ObjCPropertyImplDecl *propImpl,
  1091. llvm::Constant *AtomicHelperFn);
  1092. bool IndirectObjCSetterArg(const CGFunctionInfo &FI);
  1093. bool IvarTypeWithAggrGCObjects(QualType Ty);
  1094. //===--------------------------------------------------------------------===//
  1095. // Block Bits
  1096. //===--------------------------------------------------------------------===//
  1097. llvm::Value *EmitBlockLiteral(const BlockExpr *);
  1098. llvm::Value *EmitBlockLiteral(const CGBlockInfo &Info);
  1099. static void destroyBlockInfos(CGBlockInfo *info);
  1100. llvm::Constant *BuildDescriptorBlockDecl(const BlockExpr *,
  1101. const CGBlockInfo &Info,
  1102. llvm::StructType *,
  1103. llvm::Constant *BlockVarLayout);
  1104. llvm::Function *GenerateBlockFunction(GlobalDecl GD,
  1105. const CGBlockInfo &Info,
  1106. const Decl *OuterFuncDecl,
  1107. const DeclMapTy &ldm,
  1108. bool IsLambdaConversionToBlock);
  1109. llvm::Constant *GenerateCopyHelperFunction(const CGBlockInfo &blockInfo);
  1110. llvm::Constant *GenerateDestroyHelperFunction(const CGBlockInfo &blockInfo);
  1111. llvm::Constant *GenerateObjCAtomicSetterCopyHelperFunction(
  1112. const ObjCPropertyImplDecl *PID);
  1113. llvm::Constant *GenerateObjCAtomicGetterCopyHelperFunction(
  1114. const ObjCPropertyImplDecl *PID);
  1115. llvm::Value *EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty);
  1116. void BuildBlockRelease(llvm::Value *DeclPtr, BlockFieldFlags flags);
  1117. class AutoVarEmission;
  1118. void emitByrefStructureInit(const AutoVarEmission &emission);
  1119. void enterByrefCleanup(const AutoVarEmission &emission);
  1120. llvm::Value *LoadBlockStruct() {
  1121. assert(BlockPointer && "no block pointer set!");
  1122. return BlockPointer;
  1123. }
  1124. void AllocateBlockCXXThisPointer(const CXXThisExpr *E);
  1125. void AllocateBlockDecl(const DeclRefExpr *E);
  1126. llvm::Value *GetAddrOfBlockDecl(const VarDecl *var, bool ByRef);
  1127. llvm::Type *BuildByRefType(const VarDecl *var);
  1128. void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
  1129. const CGFunctionInfo &FnInfo);
  1130. void StartFunction(GlobalDecl GD, QualType RetTy,
  1131. llvm::Function *Fn,
  1132. const CGFunctionInfo &FnInfo,
  1133. const FunctionArgList &Args,
  1134. SourceLocation StartLoc);
  1135. void EmitConstructorBody(FunctionArgList &Args);
  1136. void EmitDestructorBody(FunctionArgList &Args);
  1137. void EmitFunctionBody(FunctionArgList &Args);
  1138. void EmitForwardingCallToLambda(const CXXRecordDecl *Lambda,
  1139. CallArgList &CallArgs);
  1140. void EmitLambdaToBlockPointerBody(FunctionArgList &Args);
  1141. void EmitLambdaBlockInvokeBody();
  1142. void EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD);
  1143. void EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD);
  1144. /// EmitReturnBlock - Emit the unified return block, trying to avoid its
  1145. /// emission when possible.
  1146. void EmitReturnBlock();
  1147. /// FinishFunction - Complete IR generation of the current function. It is
  1148. /// legal to call this function even if there is no current insertion point.
  1149. void FinishFunction(SourceLocation EndLoc=SourceLocation());
  1150. /// GenerateThunk - Generate a thunk for the given method.
  1151. void GenerateThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
  1152. GlobalDecl GD, const ThunkInfo &Thunk);
  1153. void GenerateVarArgsThunk(llvm::Function *Fn, const CGFunctionInfo &FnInfo,
  1154. GlobalDecl GD, const ThunkInfo &Thunk);
  1155. void EmitCtorPrologue(const CXXConstructorDecl *CD, CXXCtorType Type,
  1156. FunctionArgList &Args);
  1157. void EmitInitializerForField(FieldDecl *Field, LValue LHS, Expr *Init,
  1158. ArrayRef<VarDecl *> ArrayIndexes);
  1159. /// InitializeVTablePointer - Initialize the vtable pointer of the given
  1160. /// subobject.
  1161. ///
  1162. void InitializeVTablePointer(BaseSubobject Base,
  1163. const CXXRecordDecl *NearestVBase,
  1164. CharUnits OffsetFromNearestVBase,
  1165. llvm::Constant *VTable,
  1166. const CXXRecordDecl *VTableClass);
  1167. typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
  1168. void InitializeVTablePointers(BaseSubobject Base,
  1169. const CXXRecordDecl *NearestVBase,
  1170. CharUnits OffsetFromNearestVBase,
  1171. bool BaseIsNonVirtualPrimaryBase,
  1172. llvm::Constant *VTable,
  1173. const CXXRecordDecl *VTableClass,
  1174. VisitedVirtualBasesSetTy& VBases);
  1175. void InitializeVTablePointers(const CXXRecordDecl *ClassDecl);
  1176. /// GetVTablePtr - Return the Value of the vtable pointer member pointed
  1177. /// to by This.
  1178. llvm::Value *GetVTablePtr(llvm::Value *This, llvm::Type *Ty);
  1179. /// EnterDtorCleanups - Enter the cleanups necessary to complete the
  1180. /// given phase of destruction for a destructor. The end result
  1181. /// should call destructors on members and base classes in reverse
  1182. /// order of their construction.
  1183. void EnterDtorCleanups(const CXXDestructorDecl *Dtor, CXXDtorType Type);
  1184. /// ShouldInstrumentFunction - Return true if the current function should be
  1185. /// instrumented with __cyg_profile_func_* calls
  1186. bool ShouldInstrumentFunction();
  1187. /// EmitFunctionInstrumentation - Emit LLVM code to call the specified
  1188. /// instrumentation function with the current function and the call site, if
  1189. /// function instrumentation is enabled.
  1190. void EmitFunctionInstrumentation(const char *Fn);
  1191. /// EmitMCountInstrumentation - Emit call to .mcount.
  1192. void EmitMCountInstrumentation();
  1193. /// EmitFunctionProlog - Emit the target specific LLVM code to load the
  1194. /// arguments for the given function. This is also responsible for naming the
  1195. /// LLVM function arguments.
  1196. void EmitFunctionProlog(const CGFunctionInfo &FI,
  1197. llvm::Function *Fn,
  1198. const FunctionArgList &Args);
  1199. /// EmitFunctionEpilog - Emit the target specific LLVM code to return the
  1200. /// given temporary.
  1201. void EmitFunctionEpilog(const CGFunctionInfo &FI);
  1202. /// EmitStartEHSpec - Emit the start of the exception spec.
  1203. void EmitStartEHSpec(const Decl *D);
  1204. /// EmitEndEHSpec - Emit the end of the exception spec.
  1205. void EmitEndEHSpec(const Decl *D);
  1206. /// getTerminateLandingPad - Return a landing pad that just calls terminate.
  1207. llvm::BasicBlock *getTerminateLandingPad();
  1208. /// getTerminateHandler - Return a handler (not a landing pad, just
  1209. /// a catch handler) that just calls terminate. This is used when
  1210. /// a terminate scope encloses a try.
  1211. llvm::BasicBlock *getTerminateHandler();
  1212. llvm::Type *ConvertTypeForMem(QualType T);
  1213. llvm::Type *ConvertType(QualType T);
  1214. llvm::Type *ConvertType(const TypeDecl *T) {
  1215. return ConvertType(getContext().getTypeDeclType(T));
  1216. }
  1217. /// LoadObjCSelf - Load the value of self. This function is only valid while
  1218. /// generating code for an Objective-C method.
  1219. llvm::Value *LoadObjCSelf();
  1220. /// TypeOfSelfObject - Return type of object that this self represents.
  1221. QualType TypeOfSelfObject();
  1222. /// hasAggregateLLVMType - Return true if the specified AST type will map into
  1223. /// an aggregate LLVM type or is void.
  1224. static bool hasAggregateLLVMType(QualType T);
  1225. /// createBasicBlock - Create an LLVM basic block.
  1226. llvm::BasicBlock *createBasicBlock(StringRef name = "",
  1227. llvm::Function *parent = 0,
  1228. llvm::BasicBlock *before = 0) {
  1229. #ifdef NDEBUG
  1230. return llvm::BasicBlock::Create(getLLVMContext(), "", parent, before);
  1231. #else
  1232. return llvm::BasicBlock::Create(getLLVMContext(), name, parent, before);
  1233. #endif
  1234. }
  1235. /// getBasicBlockForLabel - Return the LLVM basicblock that the specified
  1236. /// label maps to.
  1237. JumpDest getJumpDestForLabel(const LabelDecl *S);
  1238. /// SimplifyForwardingBlocks - If the given basic block is only a branch to
  1239. /// another basic block, simplify it. This assumes that no other code could
  1240. /// potentially reference the basic block.
  1241. void SimplifyForwardingBlocks(llvm::BasicBlock *BB);
  1242. /// EmitBlock - Emit the given block \arg BB and set it as the insert point,
  1243. /// adding a fall-through branch from the current insert block if
  1244. /// necessary. It is legal to call this function even if there is no current
  1245. /// insertion point.
  1246. ///
  1247. /// IsFinished - If true, indicates that the caller has finished emitting
  1248. /// branches to the given block and does not expect to emit code into it. This
  1249. /// means the block can be ignored if it is unreachable.
  1250. void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false);
  1251. /// EmitBlockAfterUses - Emit the given block somewhere hopefully
  1252. /// near its uses, and leave the insertion point in it.
  1253. void EmitBlockAfterUses(llvm::BasicBlock *BB);
  1254. /// EmitBranch - Emit a branch to the specified basic block from the current
  1255. /// insert block, taking care to avoid creation of branches from dummy
  1256. /// blocks. It is legal to call this function even if there is no current
  1257. /// insertion point.
  1258. ///
  1259. /// This function clears the current insertion point. The caller should follow
  1260. /// calls to this function with calls to Emit*Block prior to generation new
  1261. /// code.
  1262. void EmitBranch(llvm::BasicBlock *Block);
  1263. /// HaveInsertPoint - True if an insertion point is defined. If not, this
  1264. /// indicates that the current code being emitted is unreachable.
  1265. bool HaveInsertPoint() const {
  1266. return Builder.GetInsertBlock() != 0;
  1267. }
  1268. /// EnsureInsertPoint - Ensure that an insertion point is defined so that
  1269. /// emitted IR has a place to go. Note that by definition, if this function
  1270. /// creates a block then that block is unreachable; callers may do better to
  1271. /// detect when no insertion point is defined and simply skip IR generation.
  1272. void EnsureInsertPoint() {
  1273. if (!HaveInsertPoint())
  1274. EmitBlock(createBasicBlock());
  1275. }
  1276. /// ErrorUnsupported - Print out an error that codegen doesn't support the
  1277. /// specified stmt yet.
  1278. void ErrorUnsupported(const Stmt *S, const char *Type,
  1279. bool OmitOnError=false);
  1280. //===--------------------------------------------------------------------===//
  1281. // Helpers
  1282. //===--------------------------------------------------------------------===//
  1283. LValue MakeAddrLValue(llvm::Value *V, QualType T,
  1284. CharUnits Alignment = CharUnits()) {
  1285. return LValue::MakeAddr(V, T, Alignment, getContext(),
  1286. CGM.getTBAAInfo(T));
  1287. }
  1288. LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T) {
  1289. CharUnits Alignment;
  1290. if (!T->isIncompleteType())
  1291. Alignment = getContext().getTypeAlignInChars(T);
  1292. return LValue::MakeAddr(V, T, Alignment, getContext(),
  1293. CGM.getTBAAInfo(T));
  1294. }
  1295. /// CreateTempAlloca - This creates a alloca and inserts it into the entry
  1296. /// block. The caller is responsible for setting an appropriate alignment on
  1297. /// the alloca.
  1298. llvm::AllocaInst *CreateTempAlloca(llvm::Type *Ty,
  1299. const Twine &Name = "tmp");
  1300. /// InitTempAlloca - Provide an initial value for the given alloca.
  1301. void InitTempAlloca(llvm::AllocaInst *Alloca, llvm::Value *Value);
  1302. /// CreateIRTemp - Create a temporary IR object of the given type, with
  1303. /// appropriate alignment. This routine should only be used when an temporary
  1304. /// value needs to be stored into an alloca (for example, to avoid explicit
  1305. /// PHI construction), but the type is the IR type, not the type appropriate
  1306. /// for storing in memory.
  1307. llvm::AllocaInst *CreateIRTemp(QualType T, const Twine &Name = "tmp");
  1308. /// CreateMemTemp - Create a temporary memory object of the given type, with
  1309. /// appropriate alignment.
  1310. llvm::AllocaInst *CreateMemTemp(QualType T, const Twine &Name = "tmp");
  1311. /// CreateAggTemp - Create a temporary memory object for the given
  1312. /// aggregate type.
  1313. AggValueSlot CreateAggTemp(QualType T, const Twine &Name = "tmp") {
  1314. CharUnits Alignment = getContext().getTypeAlignInChars(T);
  1315. return AggValueSlot::forAddr(CreateMemTemp(T, Name), Alignment,
  1316. T.getQualifiers(),
  1317. AggValueSlot::IsNotDestructed,
  1318. AggValueSlot::DoesNotNeedGCBarriers,
  1319. AggValueSlot::IsNotAliased);
  1320. }
  1321. /// Emit a cast to void* in the appropriate address space.
  1322. llvm::Value *EmitCastToVoidPtr(llvm::Value *value);
  1323. /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
  1324. /// expression and compare the result against zero, returning an Int1Ty value.
  1325. llvm::Value *EvaluateExprAsBool(const Expr *E);
  1326. /// EmitIgnoredExpr - Emit an expression in a context which ignores the result.
  1327. void EmitIgnoredExpr(const Expr *E);
  1328. /// EmitAnyExpr - Emit code to compute the specified expression which can have
  1329. /// any type. The result is returned as an RValue struct. If this is an
  1330. /// aggregate expression, the aggloc/agglocvolatile arguments indicate where
  1331. /// the result should be returned.
  1332. ///
  1333. /// \param IgnoreResult - True if the resulting value isn't used.
  1334. RValue EmitAnyExpr(const Expr *E,
  1335. AggValueSlot AggSlot = AggValueSlot::ignored(),
  1336. bool IgnoreResult = false);
  1337. // EmitVAListRef - Emit a "reference" to a va_list; this is either the address
  1338. // or the value of the expression, depending on how va_list is defined.
  1339. llvm::Value *EmitVAListRef(const Expr *E);
  1340. /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
  1341. /// always be accessible even if no aggregate location is provided.
  1342. RValue EmitAnyExprToTemp(const Expr *E);
  1343. /// EmitAnyExprToMem - Emits the code necessary to evaluate an
  1344. /// arbitrary expression into the given memory location.
  1345. void EmitAnyExprToMem(const Expr *E, llvm::Value *Location,
  1346. Qualifiers Quals, bool IsInitializer);
  1347. /// EmitExprAsInit - Emits the code necessary to initialize a
  1348. /// location in memory with the given initializer.
  1349. void EmitExprAsInit(const Expr *init, const ValueDecl *D,
  1350. LValue lvalue, bool capturedByInit);
  1351. /// EmitAggregateCopy - Emit an aggrate copy.
  1352. ///
  1353. /// \param isVolatile - True iff either the source or the destination is
  1354. /// volatile.
  1355. void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr,
  1356. QualType EltTy, bool isVolatile=false,
  1357. unsigned Alignment = 0);
  1358. /// StartBlock - Start new block named N. If insert block is a dummy block
  1359. /// then reuse it.
  1360. void StartBlock(const char *N);
  1361. /// GetAddrOfStaticLocalVar - Return the address of a static local variable.
  1362. llvm::Constant *GetAddrOfStaticLocalVar(const VarDecl *BVD) {
  1363. return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
  1364. }
  1365. /// GetAddrOfLocalVar - Return the address of a local variable.
  1366. llvm::Value *GetAddrOfLocalVar(const VarDecl *VD) {
  1367. llvm::Value *Res = LocalDeclMap[VD];
  1368. assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
  1369. return Res;
  1370. }
  1371. /// getOpaqueLValueMapping - Given an opaque value expression (which
  1372. /// must be mapped to an l-value), return its mapping.
  1373. const LValue &getOpaqueLValueMapping(const OpaqueValueExpr *e) {
  1374. assert(OpaqueValueMapping::shouldBindAsLValue(e));
  1375. llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
  1376. it = OpaqueLValues.find(e);
  1377. assert(it != OpaqueLValues.end() && "no mapping for opaque value!");
  1378. return it->second;
  1379. }
  1380. /// getOpaqueRValueMapping - Given an opaque value expression (which
  1381. /// must be mapped to an r-value), return its mapping.
  1382. const RValue &getOpaqueRValueMapping(const OpaqueValueExpr *e) {
  1383. assert(!OpaqueValueMapping::shouldBindAsLValue(e));
  1384. llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
  1385. it = OpaqueRValues.find(e);
  1386. assert(it != OpaqueRValues.end() && "no mapping for opaque value!");
  1387. return it->second;
  1388. }
  1389. /// getAccessedFieldNo - Given an encoded value and a result number, return
  1390. /// the input field number being accessed.
  1391. static unsigned getAccessedFieldNo(unsigned Idx, const llvm::Constant *Elts);
  1392. llvm::BlockAddress *GetAddrOfLabel(const LabelDecl *L);
  1393. llvm::BasicBlock *GetIndirectGotoBlock();
  1394. /// EmitNullInitialization - Generate code to set a value of the given type to
  1395. /// null, If the type contains data member pointers, they will be initialized
  1396. /// to -1 in accordance with the Itanium C++ ABI.
  1397. void EmitNullInitialization(llvm::Value *DestPtr, QualType Ty);
  1398. // EmitVAArg - Generate code to get an argument from the passed in pointer
  1399. // and update it accordingly. The return value is a pointer to the argument.
  1400. // FIXME: We should be able to get rid of this method and use the va_arg
  1401. // instruction in LLVM instead once it works well enough.
  1402. llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty);
  1403. /// emitArrayLength - Compute the length of an array, even if it's a
  1404. /// VLA, and drill down to the base element type.
  1405. llvm::Value *emitArrayLength(const ArrayType *arrayType,
  1406. QualType &baseType,
  1407. llvm::Value *&addr);
  1408. /// EmitVLASize - Capture all the sizes for the VLA expressions in
  1409. /// the given variably-modified type and store them in the VLASizeMap.
  1410. ///
  1411. /// This function can be called with a null (unreachable) insert point.
  1412. void EmitVariablyModifiedType(QualType Ty);
  1413. /// getVLASize - Returns an LLVM value that corresponds to the size,
  1414. /// in non-variably-sized elements, of a variable length array type,
  1415. /// plus that largest non-variably-sized element type. Assumes that
  1416. /// the type has already been emitted with EmitVariablyModifiedType.
  1417. std::pair<llvm::Value*,QualType> getVLASize(const VariableArrayType *vla);
  1418. std::pair<llvm::Value*,QualType> getVLASize(QualType vla);
  1419. /// LoadCXXThis - Load the value of 'this'. This function is only valid while
  1420. /// generating code for an C++ member function.
  1421. llvm::Value *LoadCXXThis() {
  1422. assert(CXXThisValue && "no 'this' value for this function");
  1423. return CXXThisValue;
  1424. }
  1425. /// LoadCXXVTT - Load the VTT parameter to base constructors/destructors have
  1426. /// virtual bases.
  1427. llvm::Value *LoadCXXVTT() {
  1428. assert(CXXVTTValue && "no VTT value for this function");
  1429. return CXXVTTValue;
  1430. }
  1431. /// GetAddressOfBaseOfCompleteClass - Convert the given pointer to a
  1432. /// complete class to the given direct base.
  1433. llvm::Value *
  1434. GetAddressOfDirectBaseInCompleteClass(llvm::Value *Value,
  1435. const CXXRecordDecl *Derived,
  1436. const CXXRecordDecl *Base,
  1437. bool BaseIsVirtual);
  1438. /// GetAddressOfBaseClass - This function will add the necessary delta to the
  1439. /// load of 'this' and returns address of the base class.
  1440. llvm::Value *GetAddressOfBaseClass(llvm::Value *Value,
  1441. const CXXRecordDecl *Derived,
  1442. CastExpr::path_const_iterator PathBegin,
  1443. CastExpr::path_const_iterator PathEnd,
  1444. bool NullCheckValue);
  1445. llvm::Value *GetAddressOfDerivedClass(llvm::Value *Value,
  1446. const CXXRecordDecl *Derived,
  1447. CastExpr::path_const_iterator PathBegin,
  1448. CastExpr::path_const_iterator PathEnd,
  1449. bool NullCheckValue);
  1450. llvm::Value *GetVirtualBaseClassOffset(llvm::Value *This,
  1451. const CXXRecordDecl *ClassDecl,
  1452. const CXXRecordDecl *BaseClassDecl);
  1453. void EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1454. CXXCtorType CtorType,
  1455. const FunctionArgList &Args);
  1456. // It's important not to confuse this and the previous function. Delegating
  1457. // constructors are the C++0x feature. The constructor delegate optimization
  1458. // is used to reduce duplication in the base and complete consturctors where
  1459. // they are substantially the same.
  1460. void EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
  1461. const FunctionArgList &Args);
  1462. void EmitCXXConstructorCall(const CXXConstructorDecl *D, CXXCtorType Type,
  1463. bool ForVirtualBase, llvm::Value *This,
  1464. CallExpr::const_arg_iterator ArgBeg,
  1465. CallExpr::const_arg_iterator ArgEnd);
  1466. void EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
  1467. llvm::Value *This, llvm::Value *Src,
  1468. CallExpr::const_arg_iterator ArgBeg,
  1469. CallExpr::const_arg_iterator ArgEnd);
  1470. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  1471. const ConstantArrayType *ArrayTy,
  1472. llvm::Value *ArrayPtr,
  1473. CallExpr::const_arg_iterator ArgBeg,
  1474. CallExpr::const_arg_iterator ArgEnd,
  1475. bool ZeroInitialization = false);
  1476. void EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
  1477. llvm::Value *NumElements,
  1478. llvm::Value *ArrayPtr,
  1479. CallExpr::const_arg_iterator ArgBeg,
  1480. CallExpr::const_arg_iterator ArgEnd,
  1481. bool ZeroInitialization = false);
  1482. static Destroyer destroyCXXObject;
  1483. void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type,
  1484. bool ForVirtualBase, llvm::Value *This);
  1485. void EmitNewArrayInitializer(const CXXNewExpr *E, QualType elementType,
  1486. llvm::Value *NewPtr, llvm::Value *NumElements);
  1487. void EmitCXXTemporary(const CXXTemporary *Temporary, QualType TempType,
  1488. llvm::Value *Ptr);
  1489. llvm::Value *EmitCXXNewExpr(const CXXNewExpr *E);
  1490. void EmitCXXDeleteExpr(const CXXDeleteExpr *E);
  1491. void EmitDeleteCall(const FunctionDecl *DeleteFD, llvm::Value *Ptr,
  1492. QualType DeleteTy);
  1493. llvm::Value* EmitCXXTypeidExpr(const CXXTypeidExpr *E);
  1494. llvm::Value *EmitDynamicCast(llvm::Value *V, const CXXDynamicCastExpr *DCE);
  1495. void MaybeEmitStdInitializerListCleanup(llvm::Value *loc, const Expr *init);
  1496. void EmitStdInitializerListCleanup(llvm::Value *loc,
  1497. const InitListExpr *init);
  1498. void EmitCheck(llvm::Value *, unsigned Size);
  1499. llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
  1500. bool isInc, bool isPre);
  1501. ComplexPairTy EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
  1502. bool isInc, bool isPre);
  1503. //===--------------------------------------------------------------------===//
  1504. // Declaration Emission
  1505. //===--------------------------------------------------------------------===//
  1506. /// EmitDecl - Emit a declaration.
  1507. ///
  1508. /// This function can be called with a null (unreachable) insert point.
  1509. void EmitDecl(const Decl &D);
  1510. /// EmitVarDecl - Emit a local variable declaration.
  1511. ///
  1512. /// This function can be called with a null (unreachable) insert point.
  1513. void EmitVarDecl(const VarDecl &D);
  1514. void EmitScalarInit(const Expr *init, const ValueDecl *D,
  1515. LValue lvalue, bool capturedByInit);
  1516. void EmitScalarInit(llvm::Value *init, LValue lvalue);
  1517. typedef void SpecialInitFn(CodeGenFunction &Init, const VarDecl &D,
  1518. llvm::Value *Address);
  1519. /// EmitAutoVarDecl - Emit an auto variable declaration.
  1520. ///
  1521. /// This function can be called with a null (unreachable) insert point.
  1522. void EmitAutoVarDecl(const VarDecl &D);
  1523. class AutoVarEmission {
  1524. friend class CodeGenFunction;
  1525. const VarDecl *Variable;
  1526. /// The alignment of the variable.
  1527. CharUnits Alignment;
  1528. /// The address of the alloca. Null if the variable was emitted
  1529. /// as a global constant.
  1530. llvm::Value *Address;
  1531. llvm::Value *NRVOFlag;
  1532. /// True if the variable is a __block variable.
  1533. bool IsByRef;
  1534. /// True if the variable is of aggregate type and has a constant
  1535. /// initializer.
  1536. bool IsConstantAggregate;
  1537. struct Invalid {};
  1538. AutoVarEmission(Invalid) : Variable(0) {}
  1539. AutoVarEmission(const VarDecl &variable)
  1540. : Variable(&variable), Address(0), NRVOFlag(0),
  1541. IsByRef(false), IsConstantAggregate(false) {}
  1542. bool wasEmittedAsGlobal() const { return Address == 0; }
  1543. public:
  1544. static AutoVarEmission invalid() { return AutoVarEmission(Invalid()); }
  1545. /// Returns the address of the object within this declaration.
  1546. /// Note that this does not chase the forwarding pointer for
  1547. /// __block decls.
  1548. llvm::Value *getObjectAddress(CodeGenFunction &CGF) const {
  1549. if (!IsByRef) return Address;
  1550. return CGF.Builder.CreateStructGEP(Address,
  1551. CGF.getByRefValueLLVMField(Variable),
  1552. Variable->getNameAsString());
  1553. }
  1554. };
  1555. AutoVarEmission EmitAutoVarAlloca(const VarDecl &var);
  1556. void EmitAutoVarInit(const AutoVarEmission &emission);
  1557. void EmitAutoVarCleanups(const AutoVarEmission &emission);
  1558. void emitAutoVarTypeCleanup(const AutoVarEmission &emission,
  1559. QualType::DestructionKind dtorKind);
  1560. void EmitStaticVarDecl(const VarDecl &D,
  1561. llvm::GlobalValue::LinkageTypes Linkage);
  1562. /// EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
  1563. void EmitParmDecl(const VarDecl &D, llvm::Value *Arg, unsigned ArgNo);
  1564. /// protectFromPeepholes - Protect a value that we're intending to
  1565. /// store to the side, but which will probably be used later, from
  1566. /// aggressive peepholing optimizations that might delete it.
  1567. ///
  1568. /// Pass the result to unprotectFromPeepholes to declare that
  1569. /// protection is no longer required.
  1570. ///
  1571. /// There's no particular reason why this shouldn't apply to
  1572. /// l-values, it's just that no existing peepholes work on pointers.
  1573. PeepholeProtection protectFromPeepholes(RValue rvalue);
  1574. void unprotectFromPeepholes(PeepholeProtection protection);
  1575. //===--------------------------------------------------------------------===//
  1576. // Statement Emission
  1577. //===--------------------------------------------------------------------===//
  1578. /// EmitStopPoint - Emit a debug stoppoint if we are emitting debug info.
  1579. void EmitStopPoint(const Stmt *S);
  1580. /// EmitStmt - Emit the code for the statement \arg S. It is legal to call
  1581. /// this function even if there is no current insertion point.
  1582. ///
  1583. /// This function may clear the current insertion point; callers should use
  1584. /// EnsureInsertPoint if they wish to subsequently generate code without first
  1585. /// calling EmitBlock, EmitBranch, or EmitStmt.
  1586. void EmitStmt(const Stmt *S);
  1587. /// EmitSimpleStmt - Try to emit a "simple" statement which does not
  1588. /// necessarily require an insertion point or debug information; typically
  1589. /// because the statement amounts to a jump or a container of other
  1590. /// statements.
  1591. ///
  1592. /// \return True if the statement was handled.
  1593. bool EmitSimpleStmt(const Stmt *S);
  1594. RValue EmitCompoundStmt(const CompoundStmt &S, bool GetLast = false,
  1595. AggValueSlot AVS = AggValueSlot::ignored());
  1596. /// EmitLabel - Emit the block for the given label. It is legal to call this
  1597. /// function even if there is no current insertion point.
  1598. void EmitLabel(const LabelDecl *D); // helper for EmitLabelStmt.
  1599. void EmitLabelStmt(const LabelStmt &S);
  1600. void EmitAttributedStmt(const AttributedStmt &S);
  1601. void EmitGotoStmt(const GotoStmt &S);
  1602. void EmitIndirectGotoStmt(const IndirectGotoStmt &S);
  1603. void EmitIfStmt(const IfStmt &S);
  1604. void EmitWhileStmt(const WhileStmt &S);
  1605. void EmitDoStmt(const DoStmt &S);
  1606. void EmitForStmt(const ForStmt &S);
  1607. void EmitReturnStmt(const ReturnStmt &S);
  1608. void EmitDeclStmt(const DeclStmt &S);
  1609. void EmitBreakStmt(const BreakStmt &S);
  1610. void EmitContinueStmt(const ContinueStmt &S);
  1611. void EmitSwitchStmt(const SwitchStmt &S);
  1612. void EmitDefaultStmt(const DefaultStmt &S);
  1613. void EmitCaseStmt(const CaseStmt &S);
  1614. void EmitCaseStmtRange(const CaseStmt &S);
  1615. void EmitAsmStmt(const AsmStmt &S);
  1616. void EmitMSAsmStmt(const MSAsmStmt &S);
  1617. void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
  1618. void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
  1619. void EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S);
  1620. void EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt &S);
  1621. void EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt &S);
  1622. llvm::Constant *getUnwindResumeFn();
  1623. llvm::Constant *getUnwindResumeOrRethrowFn();
  1624. void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  1625. void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock = false);
  1626. void EmitCXXTryStmt(const CXXTryStmt &S);
  1627. void EmitCXXForRangeStmt(const CXXForRangeStmt &S);
  1628. //===--------------------------------------------------------------------===//
  1629. // LValue Expression Emission
  1630. //===--------------------------------------------------------------------===//
  1631. /// GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
  1632. RValue GetUndefRValue(QualType Ty);
  1633. /// EmitUnsupportedRValue - Emit a dummy r-value using the type of E
  1634. /// and issue an ErrorUnsupported style diagnostic (using the
  1635. /// provided Name).
  1636. RValue EmitUnsupportedRValue(const Expr *E,
  1637. const char *Name);
  1638. /// EmitUnsupportedLValue - Emit a dummy l-value using the type of E and issue
  1639. /// an ErrorUnsupported style diagnostic (using the provided Name).
  1640. LValue EmitUnsupportedLValue(const Expr *E,
  1641. const char *Name);
  1642. /// EmitLValue - Emit code to compute a designator that specifies the location
  1643. /// of the expression.
  1644. ///
  1645. /// This can return one of two things: a simple address or a bitfield
  1646. /// reference. In either case, the LLVM Value* in the LValue structure is
  1647. /// guaranteed to be an LLVM pointer type.
  1648. ///
  1649. /// If this returns a bitfield reference, nothing about the pointee type of
  1650. /// the LLVM value is known: For example, it may not be a pointer to an
  1651. /// integer.
  1652. ///
  1653. /// If this returns a normal address, and if the lvalue's C type is fixed
  1654. /// size, this method guarantees that the returned pointer type will point to
  1655. /// an LLVM type of the same size of the lvalue's type. If the lvalue has a
  1656. /// variable length type, this is not possible.
  1657. ///
  1658. LValue EmitLValue(const Expr *E);
  1659. /// EmitCheckedLValue - Same as EmitLValue but additionally we generate
  1660. /// checking code to guard against undefined behavior. This is only
  1661. /// suitable when we know that the address will be used to access the
  1662. /// object.
  1663. LValue EmitCheckedLValue(const Expr *E);
  1664. /// EmitToMemory - Change a scalar value from its value
  1665. /// representation to its in-memory representation.
  1666. llvm::Value *EmitToMemory(llvm::Value *Value, QualType Ty);
  1667. /// EmitFromMemory - Change a scalar value from its memory
  1668. /// representation to its value representation.
  1669. llvm::Value *EmitFromMemory(llvm::Value *Value, QualType Ty);
  1670. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  1671. /// care to appropriately convert from the memory representation to
  1672. /// the LLVM value representation.
  1673. llvm::Value *EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
  1674. unsigned Alignment, QualType Ty,
  1675. llvm::MDNode *TBAAInfo = 0);
  1676. /// EmitLoadOfScalar - Load a scalar value from an address, taking
  1677. /// care to appropriately convert from the memory representation to
  1678. /// the LLVM value representation. The l-value must be a simple
  1679. /// l-value.
  1680. llvm::Value *EmitLoadOfScalar(LValue lvalue);
  1681. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  1682. /// care to appropriately convert from the memory representation to
  1683. /// the LLVM value representation.
  1684. void EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
  1685. bool Volatile, unsigned Alignment, QualType Ty,
  1686. llvm::MDNode *TBAAInfo = 0, bool isInit=false);
  1687. /// EmitStoreOfScalar - Store a scalar value to an address, taking
  1688. /// care to appropriately convert from the memory representation to
  1689. /// the LLVM value representation. The l-value must be a simple
  1690. /// l-value. The isInit flag indicates whether this is an initialization.
  1691. /// If so, atomic qualifiers are ignored and the store is always non-atomic.
  1692. void EmitStoreOfScalar(llvm::Value *value, LValue lvalue, bool isInit=false);
  1693. /// EmitLoadOfLValue - Given an expression that represents a value lvalue,
  1694. /// this method emits the address of the lvalue, then loads the result as an
  1695. /// rvalue, returning the rvalue.
  1696. RValue EmitLoadOfLValue(LValue V);
  1697. RValue EmitLoadOfExtVectorElementLValue(LValue V);
  1698. RValue EmitLoadOfBitfieldLValue(LValue LV);
  1699. /// EmitStoreThroughLValue - Store the specified rvalue into the specified
  1700. /// lvalue, where both are guaranteed to the have the same type, and that type
  1701. /// is 'Ty'.
  1702. void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false);
  1703. void EmitStoreThroughExtVectorComponentLValue(RValue Src, LValue Dst);
  1704. /// EmitStoreThroughLValue - Store Src into Dst with same constraints as
  1705. /// EmitStoreThroughLValue.
  1706. ///
  1707. /// \param Result [out] - If non-null, this will be set to a Value* for the
  1708. /// bit-field contents after the store, appropriate for use as the result of
  1709. /// an assignment to the bit-field.
  1710. void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
  1711. llvm::Value **Result=0);
  1712. /// Emit an l-value for an assignment (simple or compound) of complex type.
  1713. LValue EmitComplexAssignmentLValue(const BinaryOperator *E);
  1714. LValue EmitComplexCompoundAssignmentLValue(const CompoundAssignOperator *E);
  1715. // Note: only available for agg return types
  1716. LValue EmitBinaryOperatorLValue(const BinaryOperator *E);
  1717. LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E);
  1718. // Note: only available for agg return types
  1719. LValue EmitCallExprLValue(const CallExpr *E);
  1720. // Note: only available for agg return types
  1721. LValue EmitVAArgExprLValue(const VAArgExpr *E);
  1722. LValue EmitDeclRefLValue(const DeclRefExpr *E);
  1723. LValue EmitStringLiteralLValue(const StringLiteral *E);
  1724. LValue EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E);
  1725. LValue EmitPredefinedLValue(const PredefinedExpr *E);
  1726. LValue EmitUnaryOpLValue(const UnaryOperator *E);
  1727. LValue EmitArraySubscriptExpr(const ArraySubscriptExpr *E);
  1728. LValue EmitExtVectorElementExpr(const ExtVectorElementExpr *E);
  1729. LValue EmitMemberExpr(const MemberExpr *E);
  1730. LValue EmitObjCIsaExpr(const ObjCIsaExpr *E);
  1731. LValue EmitCompoundLiteralLValue(const CompoundLiteralExpr *E);
  1732. LValue EmitInitListLValue(const InitListExpr *E);
  1733. LValue EmitConditionalOperatorLValue(const AbstractConditionalOperator *E);
  1734. LValue EmitCastLValue(const CastExpr *E);
  1735. LValue EmitNullInitializationLValue(const CXXScalarValueInitExpr *E);
  1736. LValue EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
  1737. LValue EmitOpaqueValueLValue(const OpaqueValueExpr *e);
  1738. RValue EmitRValueForField(LValue LV, const FieldDecl *FD);
  1739. class ConstantEmission {
  1740. llvm::PointerIntPair<llvm::Constant*, 1, bool> ValueAndIsReference;
  1741. ConstantEmission(llvm::Constant *C, bool isReference)
  1742. : ValueAndIsReference(C, isReference) {}
  1743. public:
  1744. ConstantEmission() {}
  1745. static ConstantEmission forReference(llvm::Constant *C) {
  1746. return ConstantEmission(C, true);
  1747. }
  1748. static ConstantEmission forValue(llvm::Constant *C) {
  1749. return ConstantEmission(C, false);
  1750. }
  1751. operator bool() const { return ValueAndIsReference.getOpaqueValue() != 0; }
  1752. bool isReference() const { return ValueAndIsReference.getInt(); }
  1753. LValue getReferenceLValue(CodeGenFunction &CGF, Expr *refExpr) const {
  1754. assert(isReference());
  1755. return CGF.MakeNaturalAlignAddrLValue(ValueAndIsReference.getPointer(),
  1756. refExpr->getType());
  1757. }
  1758. llvm::Constant *getValue() const {
  1759. assert(!isReference());
  1760. return ValueAndIsReference.getPointer();
  1761. }
  1762. };
  1763. ConstantEmission tryEmitAsConstant(DeclRefExpr *refExpr);
  1764. RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e,
  1765. AggValueSlot slot = AggValueSlot::ignored());
  1766. LValue EmitPseudoObjectLValue(const PseudoObjectExpr *e);
  1767. llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
  1768. const ObjCIvarDecl *Ivar);
  1769. LValue EmitLValueForAnonRecordField(llvm::Value* Base,
  1770. const IndirectFieldDecl* Field,
  1771. unsigned CVRQualifiers);
  1772. LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
  1773. /// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
  1774. /// if the Field is a reference, this will return the address of the reference
  1775. /// and not the address of the value stored in the reference.
  1776. LValue EmitLValueForFieldInitialization(LValue Base,
  1777. const FieldDecl* Field);
  1778. LValue EmitLValueForIvar(QualType ObjectTy,
  1779. llvm::Value* Base, const ObjCIvarDecl *Ivar,
  1780. unsigned CVRQualifiers);
  1781. LValue EmitCXXConstructLValue(const CXXConstructExpr *E);
  1782. LValue EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E);
  1783. LValue EmitLambdaLValue(const LambdaExpr *E);
  1784. LValue EmitCXXTypeidLValue(const CXXTypeidExpr *E);
  1785. LValue EmitObjCMessageExprLValue(const ObjCMessageExpr *E);
  1786. LValue EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E);
  1787. LValue EmitStmtExprLValue(const StmtExpr *E);
  1788. LValue EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E);
  1789. LValue EmitObjCSelectorLValue(const ObjCSelectorExpr *E);
  1790. void EmitDeclRefExprDbgValue(const DeclRefExpr *E, llvm::Constant *Init);
  1791. //===--------------------------------------------------------------------===//
  1792. // Scalar Expression Emission
  1793. //===--------------------------------------------------------------------===//
  1794. /// EmitCall - Generate a call of the given function, expecting the given
  1795. /// result type, and using the given argument list which specifies both the
  1796. /// LLVM arguments and the types they were derived from.
  1797. ///
  1798. /// \param TargetDecl - If given, the decl of the function in a direct call;
  1799. /// used to set attributes on the call (noreturn, etc.).
  1800. RValue EmitCall(const CGFunctionInfo &FnInfo,
  1801. llvm::Value *Callee,
  1802. ReturnValueSlot ReturnValue,
  1803. const CallArgList &Args,
  1804. const Decl *TargetDecl = 0,
  1805. llvm::Instruction **callOrInvoke = 0);
  1806. RValue EmitCall(QualType FnType, llvm::Value *Callee,
  1807. ReturnValueSlot ReturnValue,
  1808. CallExpr::const_arg_iterator ArgBeg,
  1809. CallExpr::const_arg_iterator ArgEnd,
  1810. const Decl *TargetDecl = 0);
  1811. RValue EmitCallExpr(const CallExpr *E,
  1812. ReturnValueSlot ReturnValue = ReturnValueSlot());
  1813. llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
  1814. ArrayRef<llvm::Value *> Args,
  1815. const Twine &Name = "");
  1816. llvm::CallSite EmitCallOrInvoke(llvm::Value *Callee,
  1817. const Twine &Name = "");
  1818. llvm::Value *BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
  1819. llvm::Type *Ty);
  1820. llvm::Value *BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
  1821. llvm::Value *This, llvm::Type *Ty);
  1822. llvm::Value *BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
  1823. NestedNameSpecifier *Qual,
  1824. llvm::Type *Ty);
  1825. llvm::Value *BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD,
  1826. CXXDtorType Type,
  1827. const CXXRecordDecl *RD);
  1828. RValue EmitCXXMemberCall(const CXXMethodDecl *MD,
  1829. llvm::Value *Callee,
  1830. ReturnValueSlot ReturnValue,
  1831. llvm::Value *This,
  1832. llvm::Value *VTT,
  1833. CallExpr::const_arg_iterator ArgBeg,
  1834. CallExpr::const_arg_iterator ArgEnd);
  1835. RValue EmitCXXMemberCallExpr(const CXXMemberCallExpr *E,
  1836. ReturnValueSlot ReturnValue);
  1837. RValue EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
  1838. ReturnValueSlot ReturnValue);
  1839. llvm::Value *EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
  1840. const CXXMethodDecl *MD,
  1841. llvm::Value *This);
  1842. RValue EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
  1843. const CXXMethodDecl *MD,
  1844. ReturnValueSlot ReturnValue);
  1845. RValue EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
  1846. ReturnValueSlot ReturnValue);
  1847. RValue EmitBuiltinExpr(const FunctionDecl *FD,
  1848. unsigned BuiltinID, const CallExpr *E);
  1849. RValue EmitBlockCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue);
  1850. /// EmitTargetBuiltinExpr - Emit the given builtin call. Returns 0 if the call
  1851. /// is unhandled by the current target.
  1852. llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  1853. llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  1854. llvm::Value *EmitNeonCall(llvm::Function *F,
  1855. SmallVectorImpl<llvm::Value*> &O,
  1856. const char *name,
  1857. unsigned shift = 0, bool rightshift = false);
  1858. llvm::Value *EmitNeonSplat(llvm::Value *V, llvm::Constant *Idx);
  1859. llvm::Value *EmitNeonShiftVector(llvm::Value *V, llvm::Type *Ty,
  1860. bool negateForRightShift);
  1861. llvm::Value *BuildVector(ArrayRef<llvm::Value*> Ops);
  1862. llvm::Value *EmitX86BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  1863. llvm::Value *EmitHexagonBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  1864. llvm::Value *EmitPPCBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  1865. llvm::Value *EmitMipsBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
  1866. llvm::Value *EmitObjCProtocolExpr(const ObjCProtocolExpr *E);
  1867. llvm::Value *EmitObjCStringLiteral(const ObjCStringLiteral *E);
  1868. llvm::Value *EmitObjCBoxedExpr(const ObjCBoxedExpr *E);
  1869. llvm::Value *EmitObjCArrayLiteral(const ObjCArrayLiteral *E);
  1870. llvm::Value *EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
  1871. llvm::Value *EmitObjCCollectionLiteral(const Expr *E,
  1872. const ObjCMethodDecl *MethodWithObjects);
  1873. llvm::Value *EmitObjCSelectorExpr(const ObjCSelectorExpr *E);
  1874. RValue EmitObjCMessageExpr(const ObjCMessageExpr *E,
  1875. ReturnValueSlot Return = ReturnValueSlot());
  1876. /// Retrieves the default cleanup kind for an ARC cleanup.
  1877. /// Except under -fobjc-arc-eh, ARC cleanups are normal-only.
  1878. CleanupKind getARCCleanupKind() {
  1879. return CGM.getCodeGenOpts().ObjCAutoRefCountExceptions
  1880. ? NormalAndEHCleanup : NormalCleanup;
  1881. }
  1882. // ARC primitives.
  1883. void EmitARCInitWeak(llvm::Value *value, llvm::Value *addr);
  1884. void EmitARCDestroyWeak(llvm::Value *addr);
  1885. llvm::Value *EmitARCLoadWeak(llvm::Value *addr);
  1886. llvm::Value *EmitARCLoadWeakRetained(llvm::Value *addr);
  1887. llvm::Value *EmitARCStoreWeak(llvm::Value *value, llvm::Value *addr,
  1888. bool ignored);
  1889. void EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src);
  1890. void EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src);
  1891. llvm::Value *EmitARCRetainAutorelease(QualType type, llvm::Value *value);
  1892. llvm::Value *EmitARCRetainAutoreleaseNonBlock(llvm::Value *value);
  1893. llvm::Value *EmitARCStoreStrong(LValue lvalue, llvm::Value *value,
  1894. bool ignored);
  1895. llvm::Value *EmitARCStoreStrongCall(llvm::Value *addr, llvm::Value *value,
  1896. bool ignored);
  1897. llvm::Value *EmitARCRetain(QualType type, llvm::Value *value);
  1898. llvm::Value *EmitARCRetainNonBlock(llvm::Value *value);
  1899. llvm::Value *EmitARCRetainBlock(llvm::Value *value, bool mandatory);
  1900. void EmitARCRelease(llvm::Value *value, bool precise);
  1901. llvm::Value *EmitARCAutorelease(llvm::Value *value);
  1902. llvm::Value *EmitARCAutoreleaseReturnValue(llvm::Value *value);
  1903. llvm::Value *EmitARCRetainAutoreleaseReturnValue(llvm::Value *value);
  1904. llvm::Value *EmitARCRetainAutoreleasedReturnValue(llvm::Value *value);
  1905. std::pair<LValue,llvm::Value*>
  1906. EmitARCStoreAutoreleasing(const BinaryOperator *e);
  1907. std::pair<LValue,llvm::Value*>
  1908. EmitARCStoreStrong(const BinaryOperator *e, bool ignored);
  1909. llvm::Value *EmitObjCThrowOperand(const Expr *expr);
  1910. llvm::Value *EmitObjCProduceObject(QualType T, llvm::Value *Ptr);
  1911. llvm::Value *EmitObjCConsumeObject(QualType T, llvm::Value *Ptr);
  1912. llvm::Value *EmitObjCExtendObjectLifetime(QualType T, llvm::Value *Ptr);
  1913. llvm::Value *EmitARCExtendBlockObject(const Expr *expr);
  1914. llvm::Value *EmitARCRetainScalarExpr(const Expr *expr);
  1915. llvm::Value *EmitARCRetainAutoreleaseScalarExpr(const Expr *expr);
  1916. static Destroyer destroyARCStrongImprecise;
  1917. static Destroyer destroyARCStrongPrecise;
  1918. static Destroyer destroyARCWeak;
  1919. void EmitObjCAutoreleasePoolPop(llvm::Value *Ptr);
  1920. llvm::Value *EmitObjCAutoreleasePoolPush();
  1921. llvm::Value *EmitObjCMRRAutoreleasePoolPush();
  1922. void EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr);
  1923. void EmitObjCMRRAutoreleasePoolPop(llvm::Value *Ptr);
  1924. /// EmitReferenceBindingToExpr - Emits a reference binding to the passed in
  1925. /// expression. Will emit a temporary variable if E is not an LValue.
  1926. RValue EmitReferenceBindingToExpr(const Expr* E,
  1927. const NamedDecl *InitializedDecl);
  1928. //===--------------------------------------------------------------------===//
  1929. // Expression Emission
  1930. //===--------------------------------------------------------------------===//
  1931. // Expressions are broken into three classes: scalar, complex, aggregate.
  1932. /// EmitScalarExpr - Emit the computation of the specified expression of LLVM
  1933. /// scalar type, returning the result.
  1934. llvm::Value *EmitScalarExpr(const Expr *E , bool IgnoreResultAssign = false);
  1935. /// EmitScalarConversion - Emit a conversion from the specified type to the
  1936. /// specified destination type, both of which are LLVM scalar types.
  1937. llvm::Value *EmitScalarConversion(llvm::Value *Src, QualType SrcTy,
  1938. QualType DstTy);
  1939. /// EmitComplexToScalarConversion - Emit a conversion from the specified
  1940. /// complex type to the specified destination type, where the destination type
  1941. /// is an LLVM scalar type.
  1942. llvm::Value *EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy,
  1943. QualType DstTy);
  1944. /// EmitAggExpr - Emit the computation of the specified expression
  1945. /// of aggregate type. The result is computed into the given slot,
  1946. /// which may be null to indicate that the value is not needed.
  1947. void EmitAggExpr(const Expr *E, AggValueSlot AS, bool IgnoreResult = false);
  1948. /// EmitAggExprToLValue - Emit the computation of the specified expression of
  1949. /// aggregate type into a temporary LValue.
  1950. LValue EmitAggExprToLValue(const Expr *E);
  1951. /// EmitGCMemmoveCollectable - Emit special API for structs with object
  1952. /// pointers.
  1953. void EmitGCMemmoveCollectable(llvm::Value *DestPtr, llvm::Value *SrcPtr,
  1954. QualType Ty);
  1955. /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
  1956. /// make sure it survives garbage collection until this point.
  1957. void EmitExtendGCLifetime(llvm::Value *object);
  1958. /// EmitComplexExpr - Emit the computation of the specified expression of
  1959. /// complex type, returning the result.
  1960. ComplexPairTy EmitComplexExpr(const Expr *E,
  1961. bool IgnoreReal = false,
  1962. bool IgnoreImag = false);
  1963. /// EmitComplexExprIntoAddr - Emit the computation of the specified expression
  1964. /// of complex type, storing into the specified Value*.
  1965. void EmitComplexExprIntoAddr(const Expr *E, llvm::Value *DestAddr,
  1966. bool DestIsVolatile);
  1967. /// StoreComplexToAddr - Store a complex number into the specified address.
  1968. void StoreComplexToAddr(ComplexPairTy V, llvm::Value *DestAddr,
  1969. bool DestIsVolatile);
  1970. /// LoadComplexFromAddr - Load a complex number from the specified address.
  1971. ComplexPairTy LoadComplexFromAddr(llvm::Value *SrcAddr, bool SrcIsVolatile);
  1972. /// CreateStaticVarDecl - Create a zero-initialized LLVM global for
  1973. /// a static local variable.
  1974. llvm::GlobalVariable *CreateStaticVarDecl(const VarDecl &D,
  1975. const char *Separator,
  1976. llvm::GlobalValue::LinkageTypes Linkage);
  1977. /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
  1978. /// global variable that has already been created for it. If the initializer
  1979. /// has a different type than GV does, this may free GV and return a different
  1980. /// one. Otherwise it just returns GV.
  1981. llvm::GlobalVariable *
  1982. AddInitializerToStaticVarDecl(const VarDecl &D,
  1983. llvm::GlobalVariable *GV);
  1984. /// EmitCXXGlobalVarDeclInit - Create the initializer for a C++
  1985. /// variable with global storage.
  1986. void EmitCXXGlobalVarDeclInit(const VarDecl &D, llvm::Constant *DeclPtr,
  1987. bool PerformInit);
  1988. /// Call atexit() with a function that passes the given argument to
  1989. /// the given function.
  1990. void registerGlobalDtorWithAtExit(llvm::Constant *fn, llvm::Constant *addr);
  1991. /// Emit code in this function to perform a guarded variable
  1992. /// initialization. Guarded initializations are used when it's not
  1993. /// possible to prove that an initialization will be done exactly
  1994. /// once, e.g. with a static local variable or a static data member
  1995. /// of a class template.
  1996. void EmitCXXGuardedInit(const VarDecl &D, llvm::GlobalVariable *DeclPtr,
  1997. bool PerformInit);
  1998. /// GenerateCXXGlobalInitFunc - Generates code for initializing global
  1999. /// variables.
  2000. void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
  2001. llvm::Constant **Decls,
  2002. unsigned NumDecls);
  2003. /// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
  2004. /// variables.
  2005. void GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
  2006. const std::vector<std::pair<llvm::WeakVH,
  2007. llvm::Constant*> > &DtorsAndObjects);
  2008. void GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
  2009. const VarDecl *D,
  2010. llvm::GlobalVariable *Addr,
  2011. bool PerformInit);
  2012. void EmitCXXConstructExpr(const CXXConstructExpr *E, AggValueSlot Dest);
  2013. void EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, llvm::Value *Src,
  2014. const Expr *Exp);
  2015. void enterFullExpression(const ExprWithCleanups *E) {
  2016. if (E->getNumObjects() == 0) return;
  2017. enterNonTrivialFullExpression(E);
  2018. }
  2019. void enterNonTrivialFullExpression(const ExprWithCleanups *E);
  2020. void EmitCXXThrowExpr(const CXXThrowExpr *E);
  2021. void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
  2022. RValue EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest = 0);
  2023. //===--------------------------------------------------------------------===//
  2024. // Annotations Emission
  2025. //===--------------------------------------------------------------------===//
  2026. /// Emit an annotation call (intrinsic or builtin).
  2027. llvm::Value *EmitAnnotationCall(llvm::Value *AnnotationFn,
  2028. llvm::Value *AnnotatedVal,
  2029. llvm::StringRef AnnotationStr,
  2030. SourceLocation Location);
  2031. /// Emit local annotations for the local variable V, declared by D.
  2032. void EmitVarAnnotations(const VarDecl *D, llvm::Value *V);
  2033. /// Emit field annotations for the given field & value. Returns the
  2034. /// annotation result.
  2035. llvm::Value *EmitFieldAnnotations(const FieldDecl *D, llvm::Value *V);
  2036. //===--------------------------------------------------------------------===//
  2037. // Internal Helpers
  2038. //===--------------------------------------------------------------------===//
  2039. /// ContainsLabel - Return true if the statement contains a label in it. If
  2040. /// this statement is not executed normally, it not containing a label means
  2041. /// that we can just remove the code.
  2042. static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts = false);
  2043. /// containsBreak - Return true if the statement contains a break out of it.
  2044. /// If the statement (recursively) contains a switch or loop with a break
  2045. /// inside of it, this is fine.
  2046. static bool containsBreak(const Stmt *S);
  2047. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  2048. /// to a constant, or if it does but contains a label, return false. If it
  2049. /// constant folds return true and set the boolean result in Result.
  2050. bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result);
  2051. /// ConstantFoldsToSimpleInteger - If the specified expression does not fold
  2052. /// to a constant, or if it does but contains a label, return false. If it
  2053. /// constant folds return true and set the folded value.
  2054. bool ConstantFoldsToSimpleInteger(const Expr *Cond, llvm::APInt &Result);
  2055. /// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an
  2056. /// if statement) to the specified blocks. Based on the condition, this might
  2057. /// try to simplify the codegen of the conditional based on the branch.
  2058. void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock,
  2059. llvm::BasicBlock *FalseBlock);
  2060. /// getTrapBB - Create a basic block that will call the trap intrinsic. We'll
  2061. /// generate a branch around the created basic block as necessary.
  2062. llvm::BasicBlock *getTrapBB();
  2063. /// EmitCallArg - Emit a single call argument.
  2064. void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType);
  2065. /// EmitDelegateCallArg - We are performing a delegate call; that
  2066. /// is, the current function is delegating to another one. Produce
  2067. /// a r-value suitable for passing the given parameter.
  2068. void EmitDelegateCallArg(CallArgList &args, const VarDecl *param);
  2069. /// SetFPAccuracy - Set the minimum required accuracy of the given floating
  2070. /// point operation, expressed as the maximum relative error in ulp.
  2071. void SetFPAccuracy(llvm::Value *Val, float Accuracy);
  2072. private:
  2073. llvm::MDNode *getRangeForLoadFromType(QualType Ty);
  2074. void EmitReturnOfRValue(RValue RV, QualType Ty);
  2075. /// ExpandTypeFromArgs - Reconstruct a structure of type \arg Ty
  2076. /// from function arguments into \arg Dst. See ABIArgInfo::Expand.
  2077. ///
  2078. /// \param AI - The first function argument of the expansion.
  2079. /// \return The argument following the last expanded function
  2080. /// argument.
  2081. llvm::Function::arg_iterator
  2082. ExpandTypeFromArgs(QualType Ty, LValue Dst,
  2083. llvm::Function::arg_iterator AI);
  2084. /// ExpandTypeToArgs - Expand an RValue \arg Src, with the LLVM type for \arg
  2085. /// Ty, into individual arguments on the provided vector \arg Args. See
  2086. /// ABIArgInfo::Expand.
  2087. void ExpandTypeToArgs(QualType Ty, RValue Src,
  2088. SmallVector<llvm::Value*, 16> &Args,
  2089. llvm::FunctionType *IRFuncTy);
  2090. llvm::Value* EmitAsmInput(const AsmStmt &S,
  2091. const TargetInfo::ConstraintInfo &Info,
  2092. const Expr *InputExpr, std::string &ConstraintStr);
  2093. llvm::Value* EmitAsmInputLValue(const AsmStmt &S,
  2094. const TargetInfo::ConstraintInfo &Info,
  2095. LValue InputValue, QualType InputType,
  2096. std::string &ConstraintStr);
  2097. /// EmitCallArgs - Emit call arguments for a function.
  2098. /// The CallArgTypeInfo parameter is used for iterating over the known
  2099. /// argument types of the function being called.
  2100. template<typename T>
  2101. void EmitCallArgs(CallArgList& Args, const T* CallArgTypeInfo,
  2102. CallExpr::const_arg_iterator ArgBeg,
  2103. CallExpr::const_arg_iterator ArgEnd) {
  2104. CallExpr::const_arg_iterator Arg = ArgBeg;
  2105. // First, use the argument types that the type info knows about
  2106. if (CallArgTypeInfo) {
  2107. for (typename T::arg_type_iterator I = CallArgTypeInfo->arg_type_begin(),
  2108. E = CallArgTypeInfo->arg_type_end(); I != E; ++I, ++Arg) {
  2109. assert(Arg != ArgEnd && "Running over edge of argument list!");
  2110. QualType ArgType = *I;
  2111. #ifndef NDEBUG
  2112. QualType ActualArgType = Arg->getType();
  2113. if (ArgType->isPointerType() && ActualArgType->isPointerType()) {
  2114. QualType ActualBaseType =
  2115. ActualArgType->getAs<PointerType>()->getPointeeType();
  2116. QualType ArgBaseType =
  2117. ArgType->getAs<PointerType>()->getPointeeType();
  2118. if (ArgBaseType->isVariableArrayType()) {
  2119. if (const VariableArrayType *VAT =
  2120. getContext().getAsVariableArrayType(ActualBaseType)) {
  2121. if (!VAT->getSizeExpr())
  2122. ActualArgType = ArgType;
  2123. }
  2124. }
  2125. }
  2126. assert(getContext().getCanonicalType(ArgType.getNonReferenceType()).
  2127. getTypePtr() ==
  2128. getContext().getCanonicalType(ActualArgType).getTypePtr() &&
  2129. "type mismatch in call argument!");
  2130. #endif
  2131. EmitCallArg(Args, *Arg, ArgType);
  2132. }
  2133. // Either we've emitted all the call args, or we have a call to a
  2134. // variadic function.
  2135. assert((Arg == ArgEnd || CallArgTypeInfo->isVariadic()) &&
  2136. "Extra arguments in non-variadic function!");
  2137. }
  2138. // If we still have any arguments, emit them using the type of the argument.
  2139. for (; Arg != ArgEnd; ++Arg)
  2140. EmitCallArg(Args, *Arg, Arg->getType());
  2141. }
  2142. const TargetCodeGenInfo &getTargetHooks() const {
  2143. return CGM.getTargetCodeGenInfo();
  2144. }
  2145. void EmitDeclMetadata();
  2146. CodeGenModule::ByrefHelpers *
  2147. buildByrefHelpers(llvm::StructType &byrefType,
  2148. const AutoVarEmission &emission);
  2149. void AddObjCARCExceptionMetadata(llvm::Instruction *Inst);
  2150. /// GetPointeeAlignment - Given an expression with a pointer type, find the
  2151. /// alignment of the type referenced by the pointer. Skip over implicit
  2152. /// casts.
  2153. unsigned GetPointeeAlignment(const Expr *Addr);
  2154. /// GetPointeeAlignmentValue - Given an expression with a pointer type, find
  2155. /// the alignment of the type referenced by the pointer. Skip over implicit
  2156. /// casts. Return the alignment as an llvm::Value.
  2157. llvm::Value *GetPointeeAlignmentValue(const Expr *Addr);
  2158. };
  2159. /// Helper class with most of the code for saving a value for a
  2160. /// conditional expression cleanup.
  2161. struct DominatingLLVMValue {
  2162. typedef llvm::PointerIntPair<llvm::Value*, 1, bool> saved_type;
  2163. /// Answer whether the given value needs extra work to be saved.
  2164. static bool needsSaving(llvm::Value *value) {
  2165. // If it's not an instruction, we don't need to save.
  2166. if (!isa<llvm::Instruction>(value)) return false;
  2167. // If it's an instruction in the entry block, we don't need to save.
  2168. llvm::BasicBlock *block = cast<llvm::Instruction>(value)->getParent();
  2169. return (block != &block->getParent()->getEntryBlock());
  2170. }
  2171. /// Try to save the given value.
  2172. static saved_type save(CodeGenFunction &CGF, llvm::Value *value) {
  2173. if (!needsSaving(value)) return saved_type(value, false);
  2174. // Otherwise we need an alloca.
  2175. llvm::Value *alloca =
  2176. CGF.CreateTempAlloca(value->getType(), "cond-cleanup.save");
  2177. CGF.Builder.CreateStore(value, alloca);
  2178. return saved_type(alloca, true);
  2179. }
  2180. static llvm::Value *restore(CodeGenFunction &CGF, saved_type value) {
  2181. if (!value.getInt()) return value.getPointer();
  2182. return CGF.Builder.CreateLoad(value.getPointer());
  2183. }
  2184. };
  2185. /// A partial specialization of DominatingValue for llvm::Values that
  2186. /// might be llvm::Instructions.
  2187. template <class T> struct DominatingPointer<T,true> : DominatingLLVMValue {
  2188. typedef T *type;
  2189. static type restore(CodeGenFunction &CGF, saved_type value) {
  2190. return static_cast<T*>(DominatingLLVMValue::restore(CGF, value));
  2191. }
  2192. };
  2193. /// A specialization of DominatingValue for RValue.
  2194. template <> struct DominatingValue<RValue> {
  2195. typedef RValue type;
  2196. class saved_type {
  2197. enum Kind { ScalarLiteral, ScalarAddress, AggregateLiteral,
  2198. AggregateAddress, ComplexAddress };
  2199. llvm::Value *Value;
  2200. Kind K;
  2201. saved_type(llvm::Value *v, Kind k) : Value(v), K(k) {}
  2202. public:
  2203. static bool needsSaving(RValue value);
  2204. static saved_type save(CodeGenFunction &CGF, RValue value);
  2205. RValue restore(CodeGenFunction &CGF);
  2206. // implementations in CGExprCXX.cpp
  2207. };
  2208. static bool needsSaving(type value) {
  2209. return saved_type::needsSaving(value);
  2210. }
  2211. static saved_type save(CodeGenFunction &CGF, type value) {
  2212. return saved_type::save(CGF, value);
  2213. }
  2214. static type restore(CodeGenFunction &CGF, saved_type value) {
  2215. return value.restore(CGF);
  2216. }
  2217. };
  2218. } // end namespace CodeGen
  2219. } // end namespace clang
  2220. #endif