CGExpr.cpp 151 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956
  1. //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
  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 contains code to emit Expr nodes as LLVM code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenFunction.h"
  14. #include "CGCXXABI.h"
  15. #include "CGCall.h"
  16. #include "CGDebugInfo.h"
  17. #include "CGObjCRuntime.h"
  18. #include "CGOpenMPRuntime.h"
  19. #include "CGHLSLRuntime.h" // HLSL Change
  20. #include "CGRecordLayout.h"
  21. #include "CodeGenModule.h"
  22. #include "TargetInfo.h"
  23. #include "clang/AST/ASTContext.h"
  24. #include "clang/AST/Attr.h"
  25. #include "clang/AST/DeclObjC.h"
  26. #include "clang/Frontend/CodeGenOptions.h"
  27. #include "llvm/ADT/Hashing.h"
  28. #include "llvm/ADT/StringExtras.h"
  29. #include "llvm/IR/DataLayout.h"
  30. #include "llvm/IR/Intrinsics.h"
  31. #include "llvm/IR/LLVMContext.h"
  32. #include "llvm/IR/MDBuilder.h"
  33. #include "llvm/Support/ConvertUTF.h"
  34. #include "llvm/Support/MathExtras.h"
  35. using namespace clang;
  36. using namespace CodeGen;
  37. //===--------------------------------------------------------------------===//
  38. // Miscellaneous Helper Methods
  39. //===--------------------------------------------------------------------===//
  40. llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
  41. unsigned addressSpace =
  42. cast<llvm::PointerType>(value->getType())->getAddressSpace();
  43. llvm::PointerType *destType = Int8PtrTy;
  44. if (addressSpace)
  45. destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
  46. if (value->getType() == destType) return value;
  47. return Builder.CreateBitCast(value, destType);
  48. }
  49. /// CreateTempAlloca - This creates a alloca and inserts it into the entry
  50. /// block.
  51. llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
  52. const Twine &Name) {
  53. if (!Builder.isNamePreserving())
  54. return new llvm::AllocaInst(Ty, nullptr, "", AllocaInsertPt);
  55. return new llvm::AllocaInst(Ty, nullptr, Name, AllocaInsertPt);
  56. }
  57. void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
  58. llvm::Value *Init) {
  59. auto *Store = new llvm::StoreInst(Init, Var);
  60. llvm::BasicBlock *Block = AllocaInsertPt->getParent();
  61. Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
  62. }
  63. llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
  64. const Twine &Name) {
  65. llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
  66. // FIXME: Should we prefer the preferred type alignment here?
  67. CharUnits Align = getContext().getTypeAlignInChars(Ty);
  68. Alloc->setAlignment(Align.getQuantity());
  69. return Alloc;
  70. }
  71. llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
  72. const Twine &Name) {
  73. llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
  74. // FIXME: Should we prefer the preferred type alignment here?
  75. CharUnits Align = getContext().getTypeAlignInChars(Ty);
  76. Alloc->setAlignment(Align.getQuantity());
  77. return Alloc;
  78. }
  79. /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
  80. /// expression and compare the result against zero, returning an Int1Ty value.
  81. llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
  82. PGO.setCurrentStmt(E);
  83. if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
  84. llvm::Value *MemPtr = EmitScalarExpr(E);
  85. return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
  86. }
  87. QualType BoolTy = getContext().BoolTy;
  88. if (!E->getType()->isAnyComplexType())
  89. return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
  90. return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
  91. }
  92. /// EmitIgnoredExpr - Emit code to compute the specified expression,
  93. /// ignoring the result.
  94. void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
  95. if (E->isRValue())
  96. return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
  97. // Just emit it as an l-value and drop the result.
  98. EmitLValue(E);
  99. }
  100. /// EmitAnyExpr - Emit code to compute the specified expression which
  101. /// can have any type. The result is returned as an RValue struct.
  102. /// If this is an aggregate expression, AggSlot indicates where the
  103. /// result should be returned.
  104. RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
  105. AggValueSlot aggSlot,
  106. bool ignoreResult) {
  107. switch (getEvaluationKind(E->getType())) {
  108. case TEK_Scalar:
  109. return RValue::get(EmitScalarExpr(E, ignoreResult));
  110. case TEK_Complex:
  111. return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
  112. case TEK_Aggregate:
  113. if (!ignoreResult && aggSlot.isIgnored())
  114. aggSlot = CreateAggTemp(E->getType(), "agg-temp");
  115. EmitAggExpr(E, aggSlot);
  116. return aggSlot.asRValue();
  117. }
  118. llvm_unreachable("bad evaluation kind");
  119. }
  120. /// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
  121. /// always be accessible even if no aggregate location is provided.
  122. RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
  123. AggValueSlot AggSlot = AggValueSlot::ignored();
  124. if (hasAggregateEvaluationKind(E->getType()))
  125. AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
  126. return EmitAnyExpr(E, AggSlot);
  127. }
  128. /// EmitAnyExprToMem - Evaluate an expression into a given memory
  129. /// location.
  130. void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
  131. llvm::Value *Location,
  132. Qualifiers Quals,
  133. bool IsInit) {
  134. // FIXME: This function should take an LValue as an argument.
  135. switch (getEvaluationKind(E->getType())) {
  136. case TEK_Complex:
  137. EmitComplexExprIntoLValue(E,
  138. MakeNaturalAlignAddrLValue(Location, E->getType()),
  139. /*isInit*/ false);
  140. return;
  141. case TEK_Aggregate: {
  142. CharUnits Alignment = getContext().getTypeAlignInChars(E->getType());
  143. EmitAggExpr(E, AggValueSlot::forAddr(Location, Alignment, Quals,
  144. AggValueSlot::IsDestructed_t(IsInit),
  145. AggValueSlot::DoesNotNeedGCBarriers,
  146. AggValueSlot::IsAliased_t(!IsInit)));
  147. return;
  148. }
  149. case TEK_Scalar: {
  150. RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
  151. LValue LV = MakeAddrLValue(Location, E->getType());
  152. EmitStoreThroughLValue(RV, LV);
  153. return;
  154. }
  155. }
  156. llvm_unreachable("bad evaluation kind");
  157. }
  158. static void
  159. pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
  160. const Expr *E, llvm::Value *ReferenceTemporary) {
  161. // Objective-C++ ARC:
  162. // If we are binding a reference to a temporary that has ownership, we
  163. // need to perform retain/release operations on the temporary.
  164. //
  165. // FIXME: This should be looking at E, not M.
  166. if (CGF.getLangOpts().ObjCAutoRefCount &&
  167. M->getType()->isObjCLifetimeType()) {
  168. QualType ObjCARCReferenceLifetimeType = M->getType();
  169. switch (Qualifiers::ObjCLifetime Lifetime =
  170. ObjCARCReferenceLifetimeType.getObjCLifetime()) {
  171. case Qualifiers::OCL_None:
  172. case Qualifiers::OCL_ExplicitNone:
  173. // Carry on to normal cleanup handling.
  174. break;
  175. case Qualifiers::OCL_Autoreleasing:
  176. // Nothing to do; cleaned up by an autorelease pool.
  177. return;
  178. case Qualifiers::OCL_Strong:
  179. case Qualifiers::OCL_Weak:
  180. switch (StorageDuration Duration = M->getStorageDuration()) {
  181. case SD_Static:
  182. // Note: we intentionally do not register a cleanup to release
  183. // the object on program termination.
  184. return;
  185. case SD_Thread:
  186. // FIXME: We should probably register a cleanup in this case.
  187. return;
  188. case SD_Automatic:
  189. case SD_FullExpression:
  190. CodeGenFunction::Destroyer *Destroy;
  191. CleanupKind CleanupKind;
  192. if (Lifetime == Qualifiers::OCL_Strong) {
  193. const ValueDecl *VD = M->getExtendingDecl();
  194. bool Precise =
  195. VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
  196. CleanupKind = CGF.getARCCleanupKind();
  197. Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
  198. : &CodeGenFunction::destroyARCStrongImprecise;
  199. } else {
  200. // __weak objects always get EH cleanups; otherwise, exceptions
  201. // could cause really nasty crashes instead of mere leaks.
  202. CleanupKind = NormalAndEHCleanup;
  203. Destroy = &CodeGenFunction::destroyARCWeak;
  204. }
  205. if (Duration == SD_FullExpression)
  206. CGF.pushDestroy(CleanupKind, ReferenceTemporary,
  207. ObjCARCReferenceLifetimeType, *Destroy,
  208. CleanupKind & EHCleanup);
  209. else
  210. CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
  211. ObjCARCReferenceLifetimeType,
  212. *Destroy, CleanupKind & EHCleanup);
  213. return;
  214. case SD_Dynamic:
  215. llvm_unreachable("temporary cannot have dynamic storage duration");
  216. }
  217. llvm_unreachable("unknown storage duration");
  218. }
  219. }
  220. CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
  221. if (const RecordType *RT =
  222. E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
  223. // Get the destructor for the reference temporary.
  224. auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  225. if (!ClassDecl->hasTrivialDestructor())
  226. ReferenceTemporaryDtor = ClassDecl->getDestructor();
  227. }
  228. if (!ReferenceTemporaryDtor)
  229. return;
  230. // Call the destructor for the temporary.
  231. switch (M->getStorageDuration()) {
  232. case SD_Static:
  233. case SD_Thread: {
  234. llvm::Constant *CleanupFn;
  235. llvm::Constant *CleanupArg;
  236. if (E->getType()->isArrayType()) {
  237. CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
  238. cast<llvm::Constant>(ReferenceTemporary), E->getType(),
  239. CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
  240. dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
  241. CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
  242. } else {
  243. CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
  244. StructorType::Complete);
  245. CleanupArg = cast<llvm::Constant>(ReferenceTemporary);
  246. }
  247. CGF.CGM.getCXXABI().registerGlobalDtor(
  248. CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
  249. break;
  250. }
  251. case SD_FullExpression:
  252. CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
  253. CodeGenFunction::destroyCXXObject,
  254. CGF.getLangOpts().Exceptions);
  255. break;
  256. case SD_Automatic:
  257. CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
  258. ReferenceTemporary, E->getType(),
  259. CodeGenFunction::destroyCXXObject,
  260. CGF.getLangOpts().Exceptions);
  261. break;
  262. case SD_Dynamic:
  263. llvm_unreachable("temporary cannot have dynamic storage duration");
  264. }
  265. }
  266. static llvm::Value *
  267. createReferenceTemporary(CodeGenFunction &CGF,
  268. const MaterializeTemporaryExpr *M, const Expr *Inner) {
  269. switch (M->getStorageDuration()) {
  270. case SD_FullExpression:
  271. case SD_Automatic: {
  272. // If we have a constant temporary array or record try to promote it into a
  273. // constant global under the same rules a normal constant would've been
  274. // promoted. This is easier on the optimizer and generally emits fewer
  275. // instructions.
  276. QualType Ty = Inner->getType();
  277. if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
  278. (Ty->isArrayType() || Ty->isRecordType()) &&
  279. CGF.CGM.isTypeConstant(Ty, true))
  280. if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
  281. auto *GV = new llvm::GlobalVariable(
  282. CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
  283. llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
  284. GV->setAlignment(
  285. CGF.getContext().getTypeAlignInChars(Ty).getQuantity());
  286. // FIXME: Should we put the new global into a COMDAT?
  287. return GV;
  288. }
  289. return CGF.CreateMemTemp(Ty, "ref.tmp");
  290. }
  291. case SD_Thread:
  292. case SD_Static:
  293. return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
  294. case SD_Dynamic:
  295. llvm_unreachable("temporary can't have dynamic storage duration");
  296. }
  297. llvm_unreachable("unknown storage duration");
  298. }
  299. LValue CodeGenFunction::
  300. EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
  301. const Expr *E = M->GetTemporaryExpr();
  302. // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
  303. // as that will cause the lifetime adjustment to be lost for ARC
  304. if (getLangOpts().ObjCAutoRefCount &&
  305. M->getType()->isObjCLifetimeType() &&
  306. M->getType().getObjCLifetime() != Qualifiers::OCL_None &&
  307. M->getType().getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
  308. llvm::Value *Object = createReferenceTemporary(*this, M, E);
  309. if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object)) {
  310. Object = llvm::ConstantExpr::getBitCast(
  311. Var, ConvertTypeForMem(E->getType())->getPointerTo());
  312. // We should not have emitted the initializer for this temporary as a
  313. // constant.
  314. assert(!Var->hasInitializer());
  315. Var->setInitializer(CGM.EmitNullConstant(E->getType()));
  316. }
  317. LValue RefTempDst = MakeAddrLValue(Object, M->getType());
  318. switch (getEvaluationKind(E->getType())) {
  319. default: llvm_unreachable("expected scalar or aggregate expression");
  320. case TEK_Scalar:
  321. EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
  322. break;
  323. case TEK_Aggregate: {
  324. CharUnits Alignment = getContext().getTypeAlignInChars(E->getType());
  325. EmitAggExpr(E, AggValueSlot::forAddr(Object, Alignment,
  326. E->getType().getQualifiers(),
  327. AggValueSlot::IsDestructed,
  328. AggValueSlot::DoesNotNeedGCBarriers,
  329. AggValueSlot::IsNotAliased));
  330. break;
  331. }
  332. }
  333. pushTemporaryCleanup(*this, M, E, Object);
  334. return RefTempDst;
  335. }
  336. SmallVector<const Expr *, 2> CommaLHSs;
  337. SmallVector<SubobjectAdjustment, 2> Adjustments;
  338. E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  339. for (const auto &Ignored : CommaLHSs)
  340. EmitIgnoredExpr(Ignored);
  341. if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
  342. if (opaque->getType()->isRecordType()) {
  343. assert(Adjustments.empty());
  344. return EmitOpaqueValueLValue(opaque);
  345. }
  346. }
  347. // Create and initialize the reference temporary.
  348. llvm::Value *Object = createReferenceTemporary(*this, M, E);
  349. if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object)) {
  350. Object = llvm::ConstantExpr::getBitCast(
  351. Var, ConvertTypeForMem(E->getType())->getPointerTo());
  352. // If the temporary is a global and has a constant initializer or is a
  353. // constant temporary that we promoted to a global, we may have already
  354. // initialized it.
  355. if (!Var->hasInitializer()) {
  356. Var->setInitializer(CGM.EmitNullConstant(E->getType()));
  357. EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
  358. }
  359. } else {
  360. EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
  361. }
  362. pushTemporaryCleanup(*this, M, E, Object);
  363. // Perform derived-to-base casts and/or field accesses, to get from the
  364. // temporary object we created (and, potentially, for which we extended
  365. // the lifetime) to the subobject we're binding the reference to.
  366. for (unsigned I = Adjustments.size(); I != 0; --I) {
  367. SubobjectAdjustment &Adjustment = Adjustments[I-1];
  368. switch (Adjustment.Kind) {
  369. case SubobjectAdjustment::DerivedToBaseAdjustment:
  370. Object =
  371. GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
  372. Adjustment.DerivedToBase.BasePath->path_begin(),
  373. Adjustment.DerivedToBase.BasePath->path_end(),
  374. /*NullCheckValue=*/ false, E->getExprLoc());
  375. break;
  376. case SubobjectAdjustment::FieldAdjustment: {
  377. LValue LV = MakeAddrLValue(Object, E->getType());
  378. LV = EmitLValueForField(LV, Adjustment.Field);
  379. assert(LV.isSimple() &&
  380. "materialized temporary field is not a simple lvalue");
  381. Object = LV.getAddress();
  382. break;
  383. }
  384. case SubobjectAdjustment::MemberPointerAdjustment: {
  385. llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
  386. Object = CGM.getCXXABI().EmitMemberDataPointerAddress(
  387. *this, E, Object, Ptr, Adjustment.Ptr.MPT);
  388. break;
  389. }
  390. }
  391. }
  392. return MakeAddrLValue(Object, M->getType());
  393. }
  394. RValue
  395. CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
  396. // Emit the expression as an lvalue.
  397. LValue LV = EmitLValue(E);
  398. assert(LV.isSimple());
  399. llvm::Value *Value = LV.getAddress();
  400. if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
  401. // C++11 [dcl.ref]p5 (as amended by core issue 453):
  402. // If a glvalue to which a reference is directly bound designates neither
  403. // an existing object or function of an appropriate type nor a region of
  404. // storage of suitable size and alignment to contain an object of the
  405. // reference's type, the behavior is undefined.
  406. QualType Ty = E->getType();
  407. EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
  408. }
  409. return RValue::get(Value);
  410. }
  411. /// getAccessedFieldNo - Given an encoded value and a result number, return the
  412. /// input field number being accessed.
  413. unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
  414. const llvm::Constant *Elts) {
  415. return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
  416. ->getZExtValue();
  417. }
  418. /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
  419. static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
  420. llvm::Value *High) {
  421. llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
  422. llvm::Value *K47 = Builder.getInt64(47);
  423. llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
  424. llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
  425. llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
  426. llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
  427. return Builder.CreateMul(B1, KMul);
  428. }
  429. bool CodeGenFunction::sanitizePerformTypeCheck() const {
  430. return SanOpts.has(SanitizerKind::Null) |
  431. SanOpts.has(SanitizerKind::Alignment) |
  432. SanOpts.has(SanitizerKind::ObjectSize) |
  433. SanOpts.has(SanitizerKind::Vptr);
  434. }
  435. void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
  436. llvm::Value *Address, QualType Ty,
  437. CharUnits Alignment, bool SkipNullCheck) {
  438. if (!sanitizePerformTypeCheck())
  439. return;
  440. // Don't check pointers outside the default address space. The null check
  441. // isn't correct, the object-size check isn't supported by LLVM, and we can't
  442. // communicate the addresses to the runtime handler for the vptr check.
  443. if (Address->getType()->getPointerAddressSpace())
  444. return;
  445. SanitizerScope SanScope(this);
  446. SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
  447. llvm::BasicBlock *Done = nullptr;
  448. bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
  449. TCK == TCK_UpcastToVirtualBase;
  450. if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
  451. !SkipNullCheck) {
  452. // The glvalue must not be an empty glvalue.
  453. llvm::Value *IsNonNull = Builder.CreateICmpNE(
  454. Address, llvm::Constant::getNullValue(Address->getType()));
  455. if (AllowNullPointers) {
  456. // When performing pointer casts, it's OK if the value is null.
  457. // Skip the remaining checks in that case.
  458. Done = createBasicBlock("null");
  459. llvm::BasicBlock *Rest = createBasicBlock("not.null");
  460. Builder.CreateCondBr(IsNonNull, Rest, Done);
  461. EmitBlock(Rest);
  462. } else {
  463. Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
  464. }
  465. }
  466. if (SanOpts.has(SanitizerKind::ObjectSize) && !Ty->isIncompleteType()) {
  467. uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
  468. // The glvalue must refer to a large enough storage region.
  469. // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
  470. // to check this.
  471. // FIXME: Get object address space
  472. llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
  473. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
  474. llvm::Value *Min = Builder.getFalse();
  475. llvm::Value *CastAddr = Builder.CreateBitCast(Address, Int8PtrTy);
  476. llvm::Value *LargeEnough =
  477. Builder.CreateICmpUGE(Builder.CreateCall(F, {CastAddr, Min}),
  478. llvm::ConstantInt::get(IntPtrTy, Size));
  479. Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
  480. }
  481. uint64_t AlignVal = 0;
  482. if (SanOpts.has(SanitizerKind::Alignment)) {
  483. AlignVal = Alignment.getQuantity();
  484. if (!Ty->isIncompleteType() && !AlignVal)
  485. AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
  486. // The glvalue must be suitably aligned.
  487. if (AlignVal) {
  488. llvm::Value *Align =
  489. Builder.CreateAnd(Builder.CreatePtrToInt(Address, IntPtrTy),
  490. llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
  491. llvm::Value *Aligned =
  492. Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
  493. Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
  494. }
  495. }
  496. if (Checks.size() > 0) {
  497. llvm::Constant *StaticData[] = {
  498. EmitCheckSourceLocation(Loc),
  499. EmitCheckTypeDescriptor(Ty),
  500. llvm::ConstantInt::get(SizeTy, AlignVal),
  501. llvm::ConstantInt::get(Int8Ty, TCK)
  502. };
  503. EmitCheck(Checks, "type_mismatch", StaticData, Address);
  504. }
  505. // If possible, check that the vptr indicates that there is a subobject of
  506. // type Ty at offset zero within this object.
  507. //
  508. // C++11 [basic.life]p5,6:
  509. // [For storage which does not refer to an object within its lifetime]
  510. // The program has undefined behavior if:
  511. // -- the [pointer or glvalue] is used to access a non-static data member
  512. // or call a non-static member function
  513. CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  514. if (SanOpts.has(SanitizerKind::Vptr) &&
  515. (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
  516. TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
  517. TCK == TCK_UpcastToVirtualBase) &&
  518. RD && RD->hasDefinition() && RD->isDynamicClass()) {
  519. // Compute a hash of the mangled name of the type.
  520. //
  521. // FIXME: This is not guaranteed to be deterministic! Move to a
  522. // fingerprinting mechanism once LLVM provides one. For the time
  523. // being the implementation happens to be deterministic.
  524. SmallString<64> MangledName;
  525. llvm::raw_svector_ostream Out(MangledName);
  526. CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
  527. Out);
  528. // Blacklist based on the mangled type.
  529. if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
  530. Out.str())) {
  531. llvm::hash_code TypeHash = hash_value(Out.str());
  532. // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
  533. llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
  534. llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
  535. llvm::Value *VPtrAddr = Builder.CreateBitCast(Address, VPtrTy);
  536. llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
  537. llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
  538. llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
  539. Hash = Builder.CreateTrunc(Hash, IntPtrTy);
  540. // Look the hash up in our cache.
  541. const int CacheSize = 128;
  542. llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
  543. llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
  544. "__ubsan_vptr_type_cache");
  545. llvm::Value *Slot = Builder.CreateAnd(Hash,
  546. llvm::ConstantInt::get(IntPtrTy,
  547. CacheSize-1));
  548. llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
  549. llvm::Value *CacheVal =
  550. Builder.CreateLoad(Builder.CreateInBoundsGEP(Cache, Indices));
  551. // If the hash isn't in the cache, call a runtime handler to perform the
  552. // hard work of checking whether the vptr is for an object of the right
  553. // type. This will either fill in the cache and return, or produce a
  554. // diagnostic.
  555. llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
  556. llvm::Constant *StaticData[] = {
  557. EmitCheckSourceLocation(Loc),
  558. EmitCheckTypeDescriptor(Ty),
  559. CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
  560. llvm::ConstantInt::get(Int8Ty, TCK)
  561. };
  562. llvm::Value *DynamicData[] = { Address, Hash };
  563. EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
  564. "dynamic_type_cache_miss", StaticData, DynamicData);
  565. }
  566. }
  567. if (Done) {
  568. Builder.CreateBr(Done);
  569. EmitBlock(Done);
  570. }
  571. }
  572. /// Determine whether this expression refers to a flexible array member in a
  573. /// struct. We disable array bounds checks for such members.
  574. static bool isFlexibleArrayMemberExpr(const Expr *E) {
  575. // For compatibility with existing code, we treat arrays of length 0 or
  576. // 1 as flexible array members.
  577. const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
  578. if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  579. if (CAT->getSize().ugt(1))
  580. return false;
  581. } else if (!isa<IncompleteArrayType>(AT))
  582. return false;
  583. E = E->IgnoreParens();
  584. // A flexible array member must be the last member in the class.
  585. if (const auto *ME = dyn_cast<MemberExpr>(E)) {
  586. // FIXME: If the base type of the member expr is not FD->getParent(),
  587. // this should not be treated as a flexible array member access.
  588. if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  589. RecordDecl::field_iterator FI(
  590. DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
  591. return ++FI == FD->getParent()->field_end();
  592. }
  593. }
  594. return false;
  595. }
  596. /// If Base is known to point to the start of an array, return the length of
  597. /// that array. Return 0 if the length cannot be determined.
  598. static llvm::Value *getArrayIndexingBound(
  599. CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
  600. // For the vector indexing extension, the bound is the number of elements.
  601. if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
  602. IndexedType = Base->getType();
  603. return CGF.Builder.getInt32(VT->getNumElements());
  604. }
  605. Base = Base->IgnoreParens();
  606. if (const auto *CE = dyn_cast<CastExpr>(Base)) {
  607. if (CE->getCastKind() == CK_ArrayToPointerDecay &&
  608. !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
  609. IndexedType = CE->getSubExpr()->getType();
  610. const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
  611. if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
  612. return CGF.Builder.getInt(CAT->getSize());
  613. else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
  614. return CGF.getVLASize(VAT).first;
  615. }
  616. }
  617. return nullptr;
  618. }
  619. void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
  620. llvm::Value *Index, QualType IndexType,
  621. bool Accessed) {
  622. assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
  623. "should not be called unless adding bounds checks");
  624. SanitizerScope SanScope(this);
  625. QualType IndexedType;
  626. llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
  627. if (!Bound)
  628. return;
  629. bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
  630. llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
  631. llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
  632. llvm::Constant *StaticData[] = {
  633. EmitCheckSourceLocation(E->getExprLoc()),
  634. EmitCheckTypeDescriptor(IndexedType),
  635. EmitCheckTypeDescriptor(IndexType)
  636. };
  637. llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
  638. : Builder.CreateICmpULE(IndexVal, BoundVal);
  639. EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds), "out_of_bounds",
  640. StaticData, Index);
  641. }
  642. CodeGenFunction::ComplexPairTy CodeGenFunction::
  643. EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
  644. bool isInc, bool isPre) {
  645. ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
  646. llvm::Value *NextVal;
  647. if (isa<llvm::IntegerType>(InVal.first->getType())) {
  648. uint64_t AmountVal = isInc ? 1 : -1;
  649. NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
  650. // Add the inc/dec to the real part.
  651. NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
  652. } else {
  653. QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
  654. llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
  655. if (!isInc)
  656. FVal.changeSign();
  657. NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
  658. // Add the inc/dec to the real part.
  659. NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
  660. }
  661. ComplexPairTy IncVal(NextVal, InVal.second);
  662. // Store the updated result through the lvalue.
  663. EmitStoreOfComplex(IncVal, LV, /*init*/ false);
  664. // If this is a postinc, return the value read from memory, otherwise use the
  665. // updated value.
  666. return isPre ? IncVal : InVal;
  667. }
  668. //===----------------------------------------------------------------------===//
  669. // LValue Expression Emission
  670. //===----------------------------------------------------------------------===//
  671. RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
  672. if (Ty->isVoidType())
  673. return RValue::get(nullptr);
  674. switch (getEvaluationKind(Ty)) {
  675. case TEK_Complex: {
  676. llvm::Type *EltTy =
  677. ConvertType(Ty->castAs<ComplexType>()->getElementType());
  678. llvm::Value *U = llvm::UndefValue::get(EltTy);
  679. return RValue::getComplex(std::make_pair(U, U));
  680. }
  681. // If this is a use of an undefined aggregate type, the aggregate must have an
  682. // identifiable address. Just because the contents of the value are undefined
  683. // doesn't mean that the address can't be taken and compared.
  684. case TEK_Aggregate: {
  685. llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
  686. return RValue::getAggregate(DestPtr);
  687. }
  688. case TEK_Scalar:
  689. return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
  690. }
  691. llvm_unreachable("bad evaluation kind");
  692. }
  693. RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
  694. const char *Name) {
  695. ErrorUnsupported(E, Name);
  696. return GetUndefRValue(E->getType());
  697. }
  698. LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
  699. const char *Name) {
  700. ErrorUnsupported(E, Name);
  701. llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
  702. return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
  703. }
  704. LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
  705. LValue LV;
  706. if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
  707. LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
  708. else
  709. LV = EmitLValue(E);
  710. if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
  711. EmitTypeCheck(TCK, E->getExprLoc(), LV.getAddress(),
  712. E->getType(), LV.getAlignment());
  713. return LV;
  714. }
  715. /// EmitLValue - Emit code to compute a designator that specifies the location
  716. /// of the expression.
  717. ///
  718. /// This can return one of two things: a simple address or a bitfield reference.
  719. /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
  720. /// an LLVM pointer type.
  721. ///
  722. /// If this returns a bitfield reference, nothing about the pointee type of the
  723. /// LLVM value is known: For example, it may not be a pointer to an integer.
  724. ///
  725. /// If this returns a normal address, and if the lvalue's C type is fixed size,
  726. /// this method guarantees that the returned pointer type will point to an LLVM
  727. /// type of the same size of the lvalue's type. If the lvalue has a variable
  728. /// length type, this is not possible.
  729. ///
  730. LValue CodeGenFunction::EmitLValue(const Expr *E) {
  731. ApplyDebugLocation DL(*this, E);
  732. switch (E->getStmtClass()) {
  733. default: return EmitUnsupportedLValue(E, "l-value expression");
  734. case Expr::ObjCPropertyRefExprClass:
  735. llvm_unreachable("cannot emit a property reference directly");
  736. case Expr::ObjCSelectorExprClass:
  737. return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
  738. case Expr::ObjCIsaExprClass:
  739. return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
  740. case Expr::BinaryOperatorClass:
  741. return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
  742. case Expr::CompoundAssignOperatorClass: {
  743. QualType Ty = E->getType();
  744. if (const AtomicType *AT = Ty->getAs<AtomicType>())
  745. Ty = AT->getValueType();
  746. if (!Ty->isAnyComplexType())
  747. return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
  748. return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
  749. }
  750. case Expr::CallExprClass:
  751. case Expr::CXXMemberCallExprClass:
  752. case Expr::CXXOperatorCallExprClass:
  753. case Expr::UserDefinedLiteralClass:
  754. return EmitCallExprLValue(cast<CallExpr>(E));
  755. case Expr::VAArgExprClass:
  756. return EmitVAArgExprLValue(cast<VAArgExpr>(E));
  757. case Expr::DeclRefExprClass:
  758. return EmitDeclRefLValue(cast<DeclRefExpr>(E));
  759. case Expr::ParenExprClass:
  760. return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
  761. case Expr::GenericSelectionExprClass:
  762. return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
  763. case Expr::PredefinedExprClass:
  764. return EmitPredefinedLValue(cast<PredefinedExpr>(E));
  765. case Expr::StringLiteralClass:
  766. return EmitStringLiteralLValue(cast<StringLiteral>(E));
  767. case Expr::ObjCEncodeExprClass:
  768. return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
  769. case Expr::PseudoObjectExprClass:
  770. return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
  771. case Expr::InitListExprClass:
  772. return EmitInitListLValue(cast<InitListExpr>(E));
  773. case Expr::CXXTemporaryObjectExprClass:
  774. case Expr::CXXConstructExprClass:
  775. return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
  776. case Expr::CXXBindTemporaryExprClass:
  777. return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
  778. case Expr::CXXUuidofExprClass:
  779. return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
  780. case Expr::LambdaExprClass:
  781. return EmitLambdaLValue(cast<LambdaExpr>(E));
  782. case Expr::ExprWithCleanupsClass: {
  783. const auto *cleanups = cast<ExprWithCleanups>(E);
  784. enterFullExpression(cleanups);
  785. RunCleanupsScope Scope(*this);
  786. return EmitLValue(cleanups->getSubExpr());
  787. }
  788. case Expr::CXXDefaultArgExprClass:
  789. return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
  790. case Expr::CXXDefaultInitExprClass: {
  791. CXXDefaultInitExprScope Scope(*this);
  792. return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
  793. }
  794. case Expr::CXXTypeidExprClass:
  795. return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
  796. case Expr::ObjCMessageExprClass:
  797. return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
  798. case Expr::ObjCIvarRefExprClass:
  799. return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
  800. case Expr::StmtExprClass:
  801. return EmitStmtExprLValue(cast<StmtExpr>(E));
  802. case Expr::UnaryOperatorClass:
  803. return EmitUnaryOpLValue(cast<UnaryOperator>(E));
  804. case Expr::ArraySubscriptExprClass:
  805. return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
  806. case Expr::ExtVectorElementExprClass:
  807. return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
  808. // HLSL Change Starts
  809. case Expr::ExtMatrixElementExprClass:
  810. return EmitExtMatrixElementExpr(cast<ExtMatrixElementExpr>(E));
  811. case Expr::HLSLVectorElementExprClass:
  812. return EmitHLSLVectorElementExpr(cast<HLSLVectorElementExpr>(E));
  813. case Expr::CXXThisExprClass:
  814. return MakeAddrLValue(LoadCXXThis(), E->getType());
  815. // HLSL Change Ends
  816. case Expr::MemberExprClass:
  817. return EmitMemberExpr(cast<MemberExpr>(E));
  818. case Expr::CompoundLiteralExprClass:
  819. return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
  820. case Expr::ConditionalOperatorClass:
  821. return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
  822. case Expr::BinaryConditionalOperatorClass:
  823. return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
  824. case Expr::ChooseExprClass:
  825. return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
  826. case Expr::OpaqueValueExprClass:
  827. return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
  828. case Expr::SubstNonTypeTemplateParmExprClass:
  829. return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
  830. case Expr::ImplicitCastExprClass:
  831. case Expr::CStyleCastExprClass:
  832. case Expr::CXXFunctionalCastExprClass:
  833. case Expr::CXXStaticCastExprClass:
  834. case Expr::CXXDynamicCastExprClass:
  835. case Expr::CXXReinterpretCastExprClass:
  836. case Expr::CXXConstCastExprClass:
  837. case Expr::ObjCBridgedCastExprClass:
  838. return EmitCastLValue(cast<CastExpr>(E));
  839. case Expr::MaterializeTemporaryExprClass:
  840. return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
  841. }
  842. }
  843. /// Given an object of the given canonical type, can we safely copy a
  844. /// value out of it based on its initializer?
  845. static bool isConstantEmittableObjectType(QualType type) {
  846. assert(type.isCanonical());
  847. assert(!type->isReferenceType());
  848. // Must be const-qualified but non-volatile.
  849. Qualifiers qs = type.getLocalQualifiers();
  850. if (!qs.hasConst() || qs.hasVolatile()) return false;
  851. // Otherwise, all object types satisfy this except C++ classes with
  852. // mutable subobjects or non-trivial copy/destroy behavior.
  853. if (const auto *RT = dyn_cast<RecordType>(type))
  854. if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  855. if (RD->hasMutableFields() || !RD->isTrivial())
  856. return false;
  857. return true;
  858. }
  859. /// Can we constant-emit a load of a reference to a variable of the
  860. /// given type? This is different from predicates like
  861. /// Decl::isUsableInConstantExpressions because we do want it to apply
  862. /// in situations that don't necessarily satisfy the language's rules
  863. /// for this (e.g. C++'s ODR-use rules). For example, we want to able
  864. /// to do this with const float variables even if those variables
  865. /// aren't marked 'constexpr'.
  866. enum ConstantEmissionKind {
  867. CEK_None,
  868. CEK_AsReferenceOnly,
  869. CEK_AsValueOrReference,
  870. CEK_AsValueOnly
  871. };
  872. static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
  873. type = type.getCanonicalType();
  874. if (const auto *ref = dyn_cast<ReferenceType>(type)) {
  875. if (isConstantEmittableObjectType(ref->getPointeeType()))
  876. return CEK_AsValueOrReference;
  877. return CEK_AsReferenceOnly;
  878. }
  879. if (isConstantEmittableObjectType(type))
  880. return CEK_AsValueOnly;
  881. return CEK_None;
  882. }
  883. /// Try to emit a reference to the given value without producing it as
  884. /// an l-value. This is actually more than an optimization: we can't
  885. /// produce an l-value for variables that we never actually captured
  886. /// in a block or lambda, which means const int variables or constexpr
  887. /// literals or similar.
  888. CodeGenFunction::ConstantEmission
  889. CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
  890. ValueDecl *value = refExpr->getDecl();
  891. // The value needs to be an enum constant or a constant variable.
  892. ConstantEmissionKind CEK;
  893. if (isa<ParmVarDecl>(value)) {
  894. CEK = CEK_None;
  895. } else if (auto *var = dyn_cast<VarDecl>(value)) {
  896. CEK = checkVarTypeForConstantEmission(var->getType());
  897. } else if (isa<EnumConstantDecl>(value)) {
  898. CEK = CEK_AsValueOnly;
  899. } else {
  900. CEK = CEK_None;
  901. }
  902. if (CEK == CEK_None) return ConstantEmission();
  903. Expr::EvalResult result;
  904. bool resultIsReference;
  905. QualType resultType;
  906. // It's best to evaluate all the way as an r-value if that's permitted.
  907. if (CEK != CEK_AsReferenceOnly &&
  908. refExpr->EvaluateAsRValue(result, getContext())) {
  909. resultIsReference = false;
  910. resultType = refExpr->getType();
  911. // Otherwise, try to evaluate as an l-value.
  912. } else if (CEK != CEK_AsValueOnly &&
  913. refExpr->EvaluateAsLValue(result, getContext())) {
  914. resultIsReference = true;
  915. resultType = value->getType();
  916. // Failure.
  917. } else {
  918. return ConstantEmission();
  919. }
  920. // In any case, if the initializer has side-effects, abandon ship.
  921. if (result.HasSideEffects)
  922. return ConstantEmission();
  923. // Emit as a constant.
  924. llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
  925. // Make sure we emit a debug reference to the global variable.
  926. // This should probably fire even for
  927. if (isa<VarDecl>(value)) {
  928. if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
  929. EmitDeclRefExprDbgValue(refExpr, C);
  930. } else {
  931. assert(isa<EnumConstantDecl>(value));
  932. EmitDeclRefExprDbgValue(refExpr, C);
  933. }
  934. // If we emitted a reference constant, we need to dereference that.
  935. if (resultIsReference)
  936. return ConstantEmission::forReference(C);
  937. return ConstantEmission::forValue(C);
  938. }
  939. llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
  940. SourceLocation Loc) {
  941. return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
  942. lvalue.getAlignment().getQuantity(),
  943. lvalue.getType(), Loc, lvalue.getTBAAInfo(),
  944. lvalue.getTBAABaseType(), lvalue.getTBAAOffset());
  945. }
  946. static bool hasBooleanRepresentation(QualType Ty) {
  947. if (Ty->isBooleanType())
  948. return true;
  949. if (const EnumType *ET = Ty->getAs<EnumType>())
  950. return ET->getDecl()->getIntegerType()->isBooleanType();
  951. if (const AtomicType *AT = Ty->getAs<AtomicType>())
  952. return hasBooleanRepresentation(AT->getValueType());
  953. return false;
  954. }
  955. static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
  956. llvm::APInt &Min, llvm::APInt &End,
  957. bool StrictEnums) {
  958. const EnumType *ET = Ty->getAs<EnumType>();
  959. bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
  960. ET && !ET->getDecl()->isFixed();
  961. bool IsBool = hasBooleanRepresentation(Ty);
  962. if (!IsBool && !IsRegularCPlusPlusEnum)
  963. return false;
  964. if (IsBool) {
  965. Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
  966. End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
  967. } else {
  968. const EnumDecl *ED = ET->getDecl();
  969. llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
  970. unsigned Bitwidth = LTy->getScalarSizeInBits();
  971. unsigned NumNegativeBits = ED->getNumNegativeBits();
  972. unsigned NumPositiveBits = ED->getNumPositiveBits();
  973. if (NumNegativeBits) {
  974. unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
  975. assert(NumBits <= Bitwidth);
  976. End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
  977. Min = -End;
  978. } else {
  979. assert(NumPositiveBits <= Bitwidth);
  980. End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
  981. Min = llvm::APInt(Bitwidth, 0);
  982. }
  983. }
  984. return true;
  985. }
  986. llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
  987. llvm::APInt Min, End;
  988. if (!getRangeForType(*this, Ty, Min, End,
  989. CGM.getCodeGenOpts().StrictEnums))
  990. return nullptr;
  991. llvm::MDBuilder MDHelper(getLLVMContext());
  992. return MDHelper.createRange(Min, End);
  993. }
  994. llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
  995. unsigned Alignment, QualType Ty,
  996. SourceLocation Loc,
  997. llvm::MDNode *TBAAInfo,
  998. QualType TBAABaseType,
  999. uint64_t TBAAOffset) {
  1000. // For better performance, handle vector loads differently.
  1001. if (Ty->isVectorType()) {
  1002. llvm::Value *V;
  1003. const llvm::Type *EltTy =
  1004. cast<llvm::PointerType>(Addr->getType())->getElementType();
  1005. const auto *VTy = cast<llvm::VectorType>(EltTy);
  1006. // Handle vectors of size 3, like size 4 for better performance.
  1007. if (VTy->getNumElements() == 3) {
  1008. // Bitcast to vec4 type.
  1009. llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
  1010. 4);
  1011. llvm::PointerType *ptVec4Ty =
  1012. llvm::PointerType::get(vec4Ty,
  1013. (cast<llvm::PointerType>(
  1014. Addr->getType()))->getAddressSpace());
  1015. llvm::Value *Cast = Builder.CreateBitCast(Addr, ptVec4Ty,
  1016. "castToVec4");
  1017. // Now load value.
  1018. llvm::Value *LoadVal = Builder.CreateLoad(Cast, Volatile, "loadVec4");
  1019. // Shuffle vector to get vec3.
  1020. llvm::Constant *Mask[] = {
  1021. llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0),
  1022. llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 1),
  1023. llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 2)
  1024. };
  1025. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1026. V = Builder.CreateShuffleVector(LoadVal,
  1027. llvm::UndefValue::get(vec4Ty),
  1028. MaskV, "extractVec");
  1029. return EmitFromMemory(V, Ty);
  1030. }
  1031. }
  1032. // Atomic operations have to be done on integral types.
  1033. if (Ty->isAtomicType() || typeIsSuitableForInlineAtomic(Ty, Volatile)) {
  1034. LValue lvalue = LValue::MakeAddr(Addr, Ty,
  1035. CharUnits::fromQuantity(Alignment),
  1036. getContext(), TBAAInfo);
  1037. return EmitAtomicLoad(lvalue, Loc).getScalarVal();
  1038. }
  1039. // HLSL Change Begins
  1040. if (hlsl::IsHLSLMatType(Ty)) {
  1041. // Use matrix load to keep major info.
  1042. return CGM.getHLSLRuntime().EmitHLSLMatrixLoad(*this, Addr, Ty);
  1043. }
  1044. // HLSL Change Ends
  1045. llvm::LoadInst *Load = Builder.CreateLoad(Addr);
  1046. if (Volatile)
  1047. Load->setVolatile(true);
  1048. if (Alignment)
  1049. Load->setAlignment(Alignment);
  1050. if (TBAAInfo) {
  1051. llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
  1052. TBAAOffset);
  1053. if (TBAAPath)
  1054. CGM.DecorateInstruction(Load, TBAAPath, false/*ConvertTypeToTag*/);
  1055. }
  1056. bool NeedsBoolCheck =
  1057. SanOpts.has(SanitizerKind::Bool) && hasBooleanRepresentation(Ty);
  1058. bool NeedsEnumCheck =
  1059. SanOpts.has(SanitizerKind::Enum) && Ty->getAs<EnumType>();
  1060. if (NeedsBoolCheck || NeedsEnumCheck) {
  1061. SanitizerScope SanScope(this);
  1062. llvm::APInt Min, End;
  1063. if (getRangeForType(*this, Ty, Min, End, true)) {
  1064. --End;
  1065. llvm::Value *Check;
  1066. if (!Min)
  1067. Check = Builder.CreateICmpULE(
  1068. Load, llvm::ConstantInt::get(getLLVMContext(), End));
  1069. else {
  1070. llvm::Value *Upper = Builder.CreateICmpSLE(
  1071. Load, llvm::ConstantInt::get(getLLVMContext(), End));
  1072. llvm::Value *Lower = Builder.CreateICmpSGE(
  1073. Load, llvm::ConstantInt::get(getLLVMContext(), Min));
  1074. Check = Builder.CreateAnd(Upper, Lower);
  1075. }
  1076. llvm::Constant *StaticArgs[] = {
  1077. EmitCheckSourceLocation(Loc),
  1078. EmitCheckTypeDescriptor(Ty)
  1079. };
  1080. SanitizerMask Kind = NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
  1081. EmitCheck(std::make_pair(Check, Kind), "load_invalid_value", StaticArgs,
  1082. EmitCheckValue(Load));
  1083. }
  1084. } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
  1085. if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
  1086. Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
  1087. return EmitFromMemory(Load, Ty);
  1088. }
  1089. llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
  1090. // Bool has a different representation in memory than in registers.
  1091. if (hasBooleanRepresentation(Ty)) {
  1092. // This should really always be an i1, but sometimes it's already
  1093. // an i8, and it's awkward to track those cases down.
  1094. if (Value->getType()->isIntegerTy(1))
  1095. return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
  1096. assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
  1097. "wrong value rep of bool");
  1098. }
  1099. return Value;
  1100. }
  1101. llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
  1102. // Bool has a different representation in memory than in registers.
  1103. if (hasBooleanRepresentation(Ty)) {
  1104. assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
  1105. "wrong value rep of bool");
  1106. // HLSL Change Begin.
  1107. // Use ne v, 0 to convert to i1 instead of trunc.
  1108. return Builder.CreateICmpNE(
  1109. Value, llvm::ConstantInt::get(Value->getType(), 0), "tobool");
  1110. // HLSL Change End.
  1111. }
  1112. return Value;
  1113. }
  1114. void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
  1115. bool Volatile, unsigned Alignment,
  1116. QualType Ty, llvm::MDNode *TBAAInfo,
  1117. bool isInit, QualType TBAABaseType,
  1118. uint64_t TBAAOffset) {
  1119. // Handle vectors differently to get better performance.
  1120. if (Ty->isVectorType()) {
  1121. llvm::Type *SrcTy = Value->getType();
  1122. auto *VecTy = cast<llvm::VectorType>(SrcTy);
  1123. // Handle vec3 special.
  1124. if (VecTy->getNumElements() == 3) {
  1125. llvm::LLVMContext &VMContext = getLLVMContext();
  1126. // Our source is a vec3, do a shuffle vector to make it a vec4.
  1127. SmallVector<llvm::Constant*, 4> Mask;
  1128. Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
  1129. 0));
  1130. Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
  1131. 1));
  1132. Mask.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
  1133. 2));
  1134. Mask.push_back(llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext)));
  1135. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1136. Value = Builder.CreateShuffleVector(Value,
  1137. llvm::UndefValue::get(VecTy),
  1138. MaskV, "extractVec");
  1139. SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
  1140. }
  1141. auto *DstPtr = cast<llvm::PointerType>(Addr->getType());
  1142. if (DstPtr->getElementType() != SrcTy) {
  1143. llvm::Type *MemTy =
  1144. llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace());
  1145. Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp");
  1146. }
  1147. }
  1148. Value = EmitToMemory(Value, Ty);
  1149. if (Ty->isAtomicType() ||
  1150. (!isInit && typeIsSuitableForInlineAtomic(Ty, Volatile))) {
  1151. EmitAtomicStore(RValue::get(Value),
  1152. LValue::MakeAddr(Addr, Ty,
  1153. CharUnits::fromQuantity(Alignment),
  1154. getContext(), TBAAInfo),
  1155. isInit);
  1156. return;
  1157. }
  1158. // HLSL Change Begins
  1159. if (hlsl::IsHLSLMatType(Ty)) {
  1160. // Use matrix store to keep major info.
  1161. CGM.getHLSLRuntime().EmitHLSLMatrixStore(*this, Value, Addr, Ty);
  1162. return;
  1163. }
  1164. // HLSL Change Ends
  1165. llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
  1166. if (Alignment)
  1167. Store->setAlignment(Alignment);
  1168. if (TBAAInfo) {
  1169. llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
  1170. TBAAOffset);
  1171. if (TBAAPath)
  1172. CGM.DecorateInstruction(Store, TBAAPath, false/*ConvertTypeToTag*/);
  1173. }
  1174. }
  1175. void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
  1176. bool isInit) {
  1177. EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
  1178. lvalue.getAlignment().getQuantity(), lvalue.getType(),
  1179. lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
  1180. lvalue.getTBAAOffset());
  1181. }
  1182. /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
  1183. /// method emits the address of the lvalue, then loads the result as an rvalue,
  1184. /// returning the rvalue.
  1185. RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
  1186. if (LV.isObjCWeak()) {
  1187. // load of a __weak object.
  1188. llvm::Value *AddrWeakObj = LV.getAddress();
  1189. return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
  1190. AddrWeakObj));
  1191. }
  1192. if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
  1193. llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
  1194. Object = EmitObjCConsumeObject(LV.getType(), Object);
  1195. return RValue::get(Object);
  1196. }
  1197. if (LV.isSimple()) {
  1198. assert(!LV.getType()->isFunctionType());
  1199. // Everything needs a load.
  1200. return RValue::get(EmitLoadOfScalar(LV, Loc));
  1201. }
  1202. if (LV.isVectorElt()) {
  1203. llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddr(),
  1204. LV.isVolatileQualified());
  1205. Load->setAlignment(LV.getAlignment().getQuantity());
  1206. return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
  1207. "vecext"));
  1208. }
  1209. // If this is a reference to a subset of the elements of a vector, either
  1210. // shuffle the input or extract/insert them as appropriate.
  1211. if (LV.isExtVectorElt())
  1212. return EmitLoadOfExtVectorElementLValue(LV);
  1213. // Global Register variables always invoke intrinsics
  1214. if (LV.isGlobalReg())
  1215. return EmitLoadOfGlobalRegLValue(LV);
  1216. // HLSL Change Starts
  1217. if (LV.isExtMatrixElt())
  1218. return EmitLoadOfExtMatrixElementLValue(LV);
  1219. // HLSL Change Ends
  1220. assert(LV.isBitField() && "Unknown LValue type!");
  1221. return EmitLoadOfBitfieldLValue(LV);
  1222. }
  1223. RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
  1224. const CGBitFieldInfo &Info = LV.getBitFieldInfo();
  1225. CharUnits Align = LV.getAlignment().alignmentAtOffset(Info.StorageOffset);
  1226. // Get the output type.
  1227. llvm::Type *ResLTy = ConvertType(LV.getType());
  1228. llvm::Value *Ptr = LV.getBitFieldAddr();
  1229. llvm::Value *Val = Builder.CreateAlignedLoad(Ptr, Align.getQuantity(),
  1230. LV.isVolatileQualified(),
  1231. "bf.load");
  1232. if (Info.IsSigned) {
  1233. assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
  1234. unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
  1235. if (HighBits)
  1236. Val = Builder.CreateShl(Val, HighBits, "bf.shl");
  1237. if (Info.Offset + HighBits)
  1238. Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
  1239. } else {
  1240. if (Info.Offset)
  1241. Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
  1242. if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
  1243. Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
  1244. Info.Size),
  1245. "bf.clear");
  1246. }
  1247. Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
  1248. return RValue::get(Val);
  1249. }
  1250. // If this is a reference to a subset of the elements of a vector, create an
  1251. // appropriate shufflevector.
  1252. RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
  1253. llvm::LoadInst *Load = Builder.CreateLoad(LV.getExtVectorAddr(),
  1254. LV.isVolatileQualified());
  1255. Load->setAlignment(LV.getAlignment().getQuantity());
  1256. llvm::Value *Vec = Load;
  1257. const llvm::Constant *Elts = LV.getExtVectorElts();
  1258. // If the result of the expression is a non-vector type, we must be extracting
  1259. // a single element. Just codegen as an extractelement.
  1260. const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
  1261. // HLSL Change Starts
  1262. if (ExprVT == nullptr && getContext().getLangOpts().HLSL)
  1263. ExprVT =
  1264. hlsl::ConvertHLSLVecMatTypeToExtVectorType(getContext(), LV.getType());
  1265. // HLSL Change Ends
  1266. if (!ExprVT) {
  1267. unsigned InIdx = getAccessedFieldNo(0, Elts);
  1268. llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
  1269. return RValue::get(Builder.CreateExtractElement(Vec, Elt));
  1270. }
  1271. // Always use shuffle vector to try to retain the original program structure
  1272. unsigned NumResultElts = ExprVT->getNumElements();
  1273. SmallVector<llvm::Constant*, 4> Mask;
  1274. for (unsigned i = 0; i != NumResultElts; ++i)
  1275. Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
  1276. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1277. Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
  1278. MaskV);
  1279. return RValue::get(Vec);
  1280. }
  1281. /// @brief Generates lvalue for partial ext_vector access.
  1282. llvm::Value *CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
  1283. llvm::Value *VectorAddress = LV.getExtVectorAddr();
  1284. const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
  1285. QualType EQT = ExprVT->getElementType();
  1286. llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
  1287. llvm::Type *VectorElementPtrToTy = VectorElementTy->getPointerTo();
  1288. llvm::Value *CastToPointerElement =
  1289. Builder.CreateBitCast(VectorAddress,
  1290. VectorElementPtrToTy, "conv.ptr.element");
  1291. const llvm::Constant *Elts = LV.getExtVectorElts();
  1292. unsigned ix = getAccessedFieldNo(0, Elts);
  1293. llvm::Value *VectorBasePtrPlusIx =
  1294. Builder.CreateInBoundsGEP(CastToPointerElement,
  1295. llvm::ConstantInt::get(SizeTy, ix), "add.ptr");
  1296. return VectorBasePtrPlusIx;
  1297. }
  1298. /// @brief Load of global gamed gegisters are always calls to intrinsics.
  1299. RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
  1300. assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
  1301. "Bad type for register variable");
  1302. llvm::MDNode *RegName = cast<llvm::MDNode>(
  1303. cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
  1304. // We accept integer and pointer types only
  1305. llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
  1306. llvm::Type *Ty = OrigTy;
  1307. if (OrigTy->isPointerTy())
  1308. Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
  1309. llvm::Type *Types[] = { Ty };
  1310. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
  1311. llvm::Value *Call = Builder.CreateCall(
  1312. F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
  1313. if (OrigTy->isPointerTy())
  1314. Call = Builder.CreateIntToPtr(Call, OrigTy);
  1315. return RValue::get(Call);
  1316. }
  1317. // HLSL Change Starts
  1318. RValue CodeGenFunction::EmitLoadOfExtMatrixElementLValue(LValue LV) {
  1319. // TODO: Matrix swizzle members - emit
  1320. return RValue();
  1321. }
  1322. // HLSL Change Ends
  1323. /// EmitStoreThroughLValue - Store the specified rvalue into the specified
  1324. /// lvalue, where both are guaranteed to the have the same type, and that type
  1325. /// is 'Ty'.
  1326. void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
  1327. bool isInit) {
  1328. if (!Dst.isSimple()) {
  1329. if (Dst.isVectorElt()) {
  1330. // Read/modify/write the vector, inserting the new element.
  1331. llvm::LoadInst *Load = Builder.CreateLoad(Dst.getVectorAddr(),
  1332. Dst.isVolatileQualified());
  1333. Load->setAlignment(Dst.getAlignment().getQuantity());
  1334. llvm::Value *Vec = Load;
  1335. Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
  1336. Dst.getVectorIdx(), "vecins");
  1337. llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getVectorAddr(),
  1338. Dst.isVolatileQualified());
  1339. Store->setAlignment(Dst.getAlignment().getQuantity());
  1340. return;
  1341. }
  1342. // If this is an update of extended vector elements, insert them as
  1343. // appropriate.
  1344. if (Dst.isExtVectorElt())
  1345. return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
  1346. if (Dst.isGlobalReg())
  1347. return EmitStoreThroughGlobalRegLValue(Src, Dst);
  1348. assert(Dst.isBitField() && "Unknown LValue type");
  1349. return EmitStoreThroughBitfieldLValue(Src, Dst);
  1350. }
  1351. // There's special magic for assigning into an ARC-qualified l-value.
  1352. if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
  1353. switch (Lifetime) {
  1354. case Qualifiers::OCL_None:
  1355. llvm_unreachable("present but none");
  1356. case Qualifiers::OCL_ExplicitNone:
  1357. // nothing special
  1358. break;
  1359. case Qualifiers::OCL_Strong:
  1360. EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
  1361. return;
  1362. case Qualifiers::OCL_Weak:
  1363. EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
  1364. return;
  1365. case Qualifiers::OCL_Autoreleasing:
  1366. Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
  1367. Src.getScalarVal()));
  1368. // fall into the normal path
  1369. break;
  1370. }
  1371. }
  1372. if (Dst.isObjCWeak() && !Dst.isNonGC()) {
  1373. // load of a __weak object.
  1374. llvm::Value *LvalueDst = Dst.getAddress();
  1375. llvm::Value *src = Src.getScalarVal();
  1376. CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
  1377. return;
  1378. }
  1379. if (Dst.isObjCStrong() && !Dst.isNonGC()) {
  1380. // load of a __strong object.
  1381. llvm::Value *LvalueDst = Dst.getAddress();
  1382. llvm::Value *src = Src.getScalarVal();
  1383. if (Dst.isObjCIvar()) {
  1384. assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
  1385. llvm::Type *ResultType = ConvertType(getContext().LongTy);
  1386. llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
  1387. llvm::Value *dst = RHS;
  1388. RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
  1389. llvm::Value *LHS =
  1390. Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
  1391. llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
  1392. CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
  1393. BytesBetween);
  1394. } else if (Dst.isGlobalObjCRef()) {
  1395. CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
  1396. Dst.isThreadLocalRef());
  1397. }
  1398. else
  1399. CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
  1400. return;
  1401. }
  1402. assert(Src.isScalar() && "Can't emit an agg store with this method");
  1403. EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
  1404. }
  1405. void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
  1406. llvm::Value **Result) {
  1407. const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
  1408. CharUnits Align = Dst.getAlignment().alignmentAtOffset(Info.StorageOffset);
  1409. llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
  1410. llvm::Value *Ptr = Dst.getBitFieldAddr();
  1411. // Get the source value, truncated to the width of the bit-field.
  1412. llvm::Value *SrcVal = Src.getScalarVal();
  1413. // Cast the source to the storage type and shift it into place.
  1414. SrcVal = Builder.CreateIntCast(SrcVal,
  1415. Ptr->getType()->getPointerElementType(),
  1416. /*IsSigned=*/false);
  1417. llvm::Value *MaskedVal = SrcVal;
  1418. // See if there are other bits in the bitfield's storage we'll need to load
  1419. // and mask together with source before storing.
  1420. if (Info.StorageSize != Info.Size) {
  1421. assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
  1422. llvm::Value *Val = Builder.CreateAlignedLoad(Ptr, Align.getQuantity(),
  1423. Dst.isVolatileQualified(),
  1424. "bf.load");
  1425. // Mask the source value as needed.
  1426. if (!hasBooleanRepresentation(Dst.getType()))
  1427. SrcVal = Builder.CreateAnd(SrcVal,
  1428. llvm::APInt::getLowBitsSet(Info.StorageSize,
  1429. Info.Size),
  1430. "bf.value");
  1431. MaskedVal = SrcVal;
  1432. if (Info.Offset)
  1433. SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
  1434. // Mask out the original value.
  1435. Val = Builder.CreateAnd(Val,
  1436. ~llvm::APInt::getBitsSet(Info.StorageSize,
  1437. Info.Offset,
  1438. Info.Offset + Info.Size),
  1439. "bf.clear");
  1440. // Or together the unchanged values and the source value.
  1441. SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
  1442. } else {
  1443. assert(Info.Offset == 0);
  1444. }
  1445. // Write the new value back out.
  1446. Builder.CreateAlignedStore(SrcVal, Ptr, Align.getQuantity(),
  1447. Dst.isVolatileQualified());
  1448. // Return the new value of the bit-field, if requested.
  1449. if (Result) {
  1450. llvm::Value *ResultVal = MaskedVal;
  1451. // Sign extend the value if needed.
  1452. if (Info.IsSigned) {
  1453. assert(Info.Size <= Info.StorageSize);
  1454. unsigned HighBits = Info.StorageSize - Info.Size;
  1455. if (HighBits) {
  1456. ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
  1457. ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
  1458. }
  1459. }
  1460. ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
  1461. "bf.result.cast");
  1462. *Result = EmitFromMemory(ResultVal, Dst.getType());
  1463. }
  1464. }
  1465. void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
  1466. LValue Dst) {
  1467. // This access turns into a read/modify/write of the vector. Load the input
  1468. // value now.
  1469. llvm::LoadInst *Load = Builder.CreateLoad(Dst.getExtVectorAddr(),
  1470. Dst.isVolatileQualified());
  1471. Load->setAlignment(Dst.getAlignment().getQuantity());
  1472. llvm::Value *Vec = Load;
  1473. const llvm::Constant *Elts = Dst.getExtVectorElts();
  1474. llvm::Value *SrcVal = Src.getScalarVal();
  1475. // HLSL Change Starts
  1476. const VectorType *VTy = Dst.getType()->getAs<VectorType>();
  1477. if (VTy == nullptr && getContext().getLangOpts().HLSL)
  1478. VTy =
  1479. hlsl::ConvertHLSLVecMatTypeToExtVectorType(getContext(), Dst.getType());
  1480. llvm::Value * VecDstPtr = Dst.getExtVectorAddr();
  1481. llvm::Value *Zero = Builder.getInt32(0);
  1482. if (VTy) {
  1483. llvm::Type *VecTy = VecDstPtr->getType()->getPointerElementType();
  1484. unsigned NumSrcElts = VTy->getNumElements();
  1485. if (VecTy->getVectorNumElements() == NumSrcElts) {
  1486. // Full vector write, create one store.
  1487. for (unsigned i = 0; i < VecTy->getVectorNumElements(); i++) {
  1488. if (llvm::Constant *Elt = Elts->getAggregateElement(i)) {
  1489. llvm::Value *SrcElt = Builder.CreateExtractElement(SrcVal, i);
  1490. Vec = Builder.CreateInsertElement(Vec, SrcElt, Elt);
  1491. }
  1492. }
  1493. Builder.CreateStore(Vec, VecDstPtr);
  1494. } else {
  1495. for (unsigned i = 0; i < VecTy->getVectorNumElements(); i++) {
  1496. if (llvm::Constant *Elt = Elts->getAggregateElement(i)) {
  1497. llvm::Value *EltGEP = Builder.CreateGEP(VecDstPtr, {Zero, Elt});
  1498. llvm::Value *SrcElt = Builder.CreateExtractElement(SrcVal, i);
  1499. Builder.CreateStore(SrcElt, EltGEP);
  1500. }
  1501. }
  1502. }
  1503. } else {
  1504. // If the Src is a scalar (not a vector) it must be updating one element.
  1505. llvm::Value *EltGEP = Builder.CreateGEP(
  1506. VecDstPtr, {Zero, Elts->getAggregateElement((unsigned)0)});
  1507. Builder.CreateStore(SrcVal, EltGEP);
  1508. }
  1509. return;
  1510. // HLSL Change Ends
  1511. if (VTy) { // HLSL Change
  1512. unsigned NumSrcElts = VTy->getNumElements();
  1513. unsigned NumDstElts =
  1514. cast<llvm::VectorType>(Vec->getType())->getNumElements();
  1515. if (NumDstElts == NumSrcElts) {
  1516. // Use shuffle vector is the src and destination are the same number of
  1517. // elements and restore the vector mask since it is on the side it will be
  1518. // stored.
  1519. SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
  1520. for (unsigned i = 0; i != NumSrcElts; ++i)
  1521. Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
  1522. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1523. Vec = Builder.CreateShuffleVector(SrcVal,
  1524. llvm::UndefValue::get(Vec->getType()),
  1525. MaskV);
  1526. } else if (NumDstElts > NumSrcElts) {
  1527. // Extended the source vector to the same length and then shuffle it
  1528. // into the destination.
  1529. // FIXME: since we're shuffling with undef, can we just use the indices
  1530. // into that? This could be simpler.
  1531. SmallVector<llvm::Constant*, 4> ExtMask;
  1532. for (unsigned i = 0; i != NumSrcElts; ++i)
  1533. ExtMask.push_back(Builder.getInt32(i));
  1534. ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
  1535. llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
  1536. llvm::Value *ExtSrcVal =
  1537. Builder.CreateShuffleVector(SrcVal,
  1538. llvm::UndefValue::get(SrcVal->getType()),
  1539. ExtMaskV);
  1540. // build identity
  1541. SmallVector<llvm::Constant*, 4> Mask;
  1542. for (unsigned i = 0; i != NumDstElts; ++i)
  1543. Mask.push_back(Builder.getInt32(i));
  1544. // When the vector size is odd and .odd or .hi is used, the last element
  1545. // of the Elts constant array will be one past the size of the vector.
  1546. // Ignore the last element here, if it is greater than the mask size.
  1547. if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
  1548. NumSrcElts--;
  1549. // modify when what gets shuffled in
  1550. for (unsigned i = 0; i != NumSrcElts; ++i)
  1551. Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
  1552. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1553. Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
  1554. } else {
  1555. // We should never shorten the vector
  1556. llvm_unreachable("unexpected shorten vector length");
  1557. }
  1558. } else {
  1559. // If the Src is a scalar (not a vector) it must be updating one element.
  1560. unsigned InIdx = getAccessedFieldNo(0, Elts);
  1561. llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
  1562. Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
  1563. }
  1564. llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getExtVectorAddr(),
  1565. Dst.isVolatileQualified());
  1566. Store->setAlignment(Dst.getAlignment().getQuantity());
  1567. }
  1568. /// @brief Store of global named registers are always calls to intrinsics.
  1569. void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
  1570. assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
  1571. "Bad type for register variable");
  1572. llvm::MDNode *RegName = cast<llvm::MDNode>(
  1573. cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
  1574. assert(RegName && "Register LValue is not metadata");
  1575. // We accept integer and pointer types only
  1576. llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
  1577. llvm::Type *Ty = OrigTy;
  1578. if (OrigTy->isPointerTy())
  1579. Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
  1580. llvm::Type *Types[] = { Ty };
  1581. llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
  1582. llvm::Value *Value = Src.getScalarVal();
  1583. if (OrigTy->isPointerTy())
  1584. Value = Builder.CreatePtrToInt(Value, Ty);
  1585. Builder.CreateCall(
  1586. F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
  1587. }
  1588. // setObjCGCLValueClass - sets class of the lvalue for the purpose of
  1589. // generating write-barries API. It is currently a global, ivar,
  1590. // or neither.
  1591. static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
  1592. LValue &LV,
  1593. bool IsMemberAccess=false) {
  1594. if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
  1595. return;
  1596. if (isa<ObjCIvarRefExpr>(E)) {
  1597. QualType ExpTy = E->getType();
  1598. if (IsMemberAccess && ExpTy->isPointerType()) {
  1599. // If ivar is a structure pointer, assigning to field of
  1600. // this struct follows gcc's behavior and makes it a non-ivar
  1601. // writer-barrier conservatively.
  1602. ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
  1603. if (ExpTy->isRecordType()) {
  1604. LV.setObjCIvar(false);
  1605. return;
  1606. }
  1607. }
  1608. LV.setObjCIvar(true);
  1609. auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
  1610. LV.setBaseIvarExp(Exp->getBase());
  1611. LV.setObjCArray(E->getType()->isArrayType());
  1612. return;
  1613. }
  1614. if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
  1615. if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
  1616. if (VD->hasGlobalStorage()) {
  1617. LV.setGlobalObjCRef(true);
  1618. LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
  1619. }
  1620. }
  1621. LV.setObjCArray(E->getType()->isArrayType());
  1622. return;
  1623. }
  1624. if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
  1625. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1626. return;
  1627. }
  1628. if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
  1629. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1630. if (LV.isObjCIvar()) {
  1631. // If cast is to a structure pointer, follow gcc's behavior and make it
  1632. // a non-ivar write-barrier.
  1633. QualType ExpTy = E->getType();
  1634. if (ExpTy->isPointerType())
  1635. ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
  1636. if (ExpTy->isRecordType())
  1637. LV.setObjCIvar(false);
  1638. }
  1639. return;
  1640. }
  1641. if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
  1642. setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
  1643. return;
  1644. }
  1645. if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
  1646. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1647. return;
  1648. }
  1649. if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
  1650. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1651. return;
  1652. }
  1653. if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
  1654. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1655. return;
  1656. }
  1657. if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
  1658. setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
  1659. if (LV.isObjCIvar() && !LV.isObjCArray())
  1660. // Using array syntax to assigning to what an ivar points to is not
  1661. // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
  1662. LV.setObjCIvar(false);
  1663. else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
  1664. // Using array syntax to assigning to what global points to is not
  1665. // same as assigning to the global itself. {id *G;} G[i] = 0;
  1666. LV.setGlobalObjCRef(false);
  1667. return;
  1668. }
  1669. if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
  1670. setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
  1671. // We don't know if member is an 'ivar', but this flag is looked at
  1672. // only in the context of LV.isObjCIvar().
  1673. LV.setObjCArray(E->getType()->isArrayType());
  1674. return;
  1675. }
  1676. }
  1677. static llvm::Value *
  1678. EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
  1679. llvm::Value *V, llvm::Type *IRType,
  1680. StringRef Name = StringRef()) {
  1681. unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
  1682. return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
  1683. }
  1684. static LValue EmitThreadPrivateVarDeclLValue(
  1685. CodeGenFunction &CGF, const VarDecl *VD, QualType T, llvm::Value *V,
  1686. llvm::Type *RealVarTy, CharUnits Alignment, SourceLocation Loc) {
  1687. V = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, V, Loc);
  1688. V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
  1689. return CGF.MakeAddrLValue(V, T, Alignment);
  1690. }
  1691. static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
  1692. const Expr *E, const VarDecl *VD) {
  1693. QualType T = E->getType();
  1694. // If it's thread_local, emit a call to its wrapper function instead.
  1695. if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
  1696. CGF.CGM.getCXXABI().usesThreadWrapperFunction())
  1697. return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
  1698. llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
  1699. llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
  1700. V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
  1701. CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
  1702. LValue LV;
  1703. // Emit reference to the private copy of the variable if it is an OpenMP
  1704. // threadprivate variable.
  1705. if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
  1706. return EmitThreadPrivateVarDeclLValue(CGF, VD, T, V, RealVarTy, Alignment,
  1707. E->getExprLoc());
  1708. if (VD->getType()->isReferenceType()) {
  1709. llvm::LoadInst *LI = CGF.Builder.CreateLoad(V);
  1710. LI->setAlignment(Alignment.getQuantity());
  1711. V = LI;
  1712. LV = CGF.MakeNaturalAlignAddrLValue(V, T);
  1713. } else {
  1714. LV = CGF.MakeAddrLValue(V, T, Alignment);
  1715. }
  1716. setObjCGCLValueClass(CGF.getContext(), E, LV);
  1717. return LV;
  1718. }
  1719. static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
  1720. const Expr *E, const FunctionDecl *FD) {
  1721. llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
  1722. if (!FD->hasPrototype()) {
  1723. if (const FunctionProtoType *Proto =
  1724. FD->getType()->getAs<FunctionProtoType>()) {
  1725. // Ugly case: for a K&R-style definition, the type of the definition
  1726. // isn't the same as the type of a use. Correct for this with a
  1727. // bitcast.
  1728. QualType NoProtoType =
  1729. CGF.getContext().getFunctionNoProtoType(Proto->getReturnType());
  1730. NoProtoType = CGF.getContext().getPointerType(NoProtoType);
  1731. V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
  1732. }
  1733. }
  1734. CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
  1735. return CGF.MakeAddrLValue(V, E->getType(), Alignment);
  1736. }
  1737. static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
  1738. llvm::Value *ThisValue) {
  1739. QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
  1740. LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
  1741. return CGF.EmitLValueForField(LV, FD);
  1742. }
  1743. /// Named Registers are named metadata pointing to the register name
  1744. /// which will be read from/written to as an argument to the intrinsic
  1745. /// @llvm.read/write_register.
  1746. /// So far, only the name is being passed down, but other options such as
  1747. /// register type, allocation type or even optimization options could be
  1748. /// passed down via the metadata node.
  1749. static LValue EmitGlobalNamedRegister(const VarDecl *VD,
  1750. CodeGenModule &CGM,
  1751. CharUnits Alignment) {
  1752. SmallString<64> Name("llvm.named.register.");
  1753. AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
  1754. assert(Asm->getLabel().size() < 64-Name.size() &&
  1755. "Register name too big");
  1756. Name.append(Asm->getLabel());
  1757. llvm::NamedMDNode *M =
  1758. CGM.getModule().getOrInsertNamedMetadata(Name);
  1759. if (M->getNumOperands() == 0) {
  1760. llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
  1761. Asm->getLabel());
  1762. llvm::Metadata *Ops[] = {Str};
  1763. M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  1764. }
  1765. return LValue::MakeGlobalReg(
  1766. llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0)),
  1767. VD->getType(), Alignment);
  1768. }
  1769. LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
  1770. const NamedDecl *ND = E->getDecl();
  1771. CharUnits Alignment = getContext().getDeclAlign(ND);
  1772. QualType T = E->getType();
  1773. if (const auto *VD = dyn_cast<VarDecl>(ND)) {
  1774. // Global Named registers access via intrinsics only
  1775. if (VD->getStorageClass() == SC_Register &&
  1776. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
  1777. return EmitGlobalNamedRegister(VD, CGM, Alignment);
  1778. // A DeclRefExpr for a reference initialized by a constant expression can
  1779. // appear without being odr-used. Directly emit the constant initializer.
  1780. const Expr *Init = VD->getAnyInitializer(VD);
  1781. if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
  1782. VD->isUsableInConstantExpressions(getContext()) &&
  1783. VD->checkInitIsICE()) {
  1784. llvm::Constant *Val =
  1785. CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
  1786. assert(Val && "failed to emit reference constant expression");
  1787. // FIXME: Eventually we will want to emit vector element references.
  1788. return MakeAddrLValue(Val, T, Alignment);
  1789. }
  1790. // Check for captured variables.
  1791. if (E->refersToEnclosingVariableOrCapture()) {
  1792. if (auto *FD = LambdaCaptureFields.lookup(VD))
  1793. return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
  1794. else if (CapturedStmtInfo) {
  1795. if (auto *V = LocalDeclMap.lookup(VD))
  1796. return MakeAddrLValue(V, T, Alignment);
  1797. else
  1798. return EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
  1799. CapturedStmtInfo->getContextValue());
  1800. }
  1801. assert(isa<BlockDecl>(CurCodeDecl));
  1802. return MakeAddrLValue(GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>()),
  1803. T, Alignment);
  1804. }
  1805. }
  1806. // FIXME: We should be able to assert this for FunctionDecls as well!
  1807. // FIXME: We should be able to assert this for all DeclRefExprs, not just
  1808. // those with a valid source location.
  1809. assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
  1810. !E->getLocation().isValid()) &&
  1811. "Should not use decl without marking it used!");
  1812. if (ND->hasAttr<WeakRefAttr>()) {
  1813. const auto *VD = cast<ValueDecl>(ND);
  1814. llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
  1815. return MakeAddrLValue(Aliasee, T, Alignment);
  1816. }
  1817. if (const auto *VD = dyn_cast<VarDecl>(ND)) {
  1818. // Check if this is a global variable.
  1819. if (VD->hasLinkage() || VD->isStaticDataMember())
  1820. return EmitGlobalVarDeclLValue(*this, E, VD);
  1821. bool isBlockVariable = VD->hasAttr<BlocksAttr>();
  1822. llvm::Value *V = LocalDeclMap.lookup(VD);
  1823. if (!V && VD->isStaticLocal())
  1824. V = CGM.getOrCreateStaticVarDecl(
  1825. *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
  1826. // Check if variable is threadprivate.
  1827. if (V && getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
  1828. return EmitThreadPrivateVarDeclLValue(
  1829. *this, VD, T, V, getTypes().ConvertTypeForMem(VD->getType()),
  1830. Alignment, E->getExprLoc());
  1831. assert(V && "DeclRefExpr not entered in LocalDeclMap?");
  1832. if (isBlockVariable)
  1833. V = BuildBlockByrefAddress(V, VD);
  1834. LValue LV;
  1835. // HLSL Change Begins
  1836. if (getLangOpts().HLSL) {
  1837. // In hlsl, the referent type is for out parameter.
  1838. // No pointer of pointer temp alloca created for it.
  1839. // So always use V directly.
  1840. LV = MakeAddrLValue(V, T, Alignment);
  1841. } else
  1842. // HLSL Change Ends
  1843. if (VD->getType()->isReferenceType()) {
  1844. llvm::LoadInst *LI = Builder.CreateLoad(V);
  1845. LI->setAlignment(Alignment.getQuantity());
  1846. V = LI;
  1847. LV = MakeNaturalAlignAddrLValue(V, T);
  1848. } else {
  1849. LV = MakeAddrLValue(V, T, Alignment);
  1850. }
  1851. bool isLocalStorage = VD->hasLocalStorage();
  1852. bool NonGCable = isLocalStorage &&
  1853. !VD->getType()->isReferenceType() &&
  1854. !isBlockVariable;
  1855. if (NonGCable) {
  1856. LV.getQuals().removeObjCGCAttr();
  1857. LV.setNonGC(true);
  1858. }
  1859. bool isImpreciseLifetime =
  1860. (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
  1861. if (isImpreciseLifetime)
  1862. LV.setARCPreciseLifetime(ARCImpreciseLifetime);
  1863. setObjCGCLValueClass(getContext(), E, LV);
  1864. return LV;
  1865. }
  1866. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  1867. return EmitFunctionDeclLValue(*this, E, FD);
  1868. llvm_unreachable("Unhandled DeclRefExpr");
  1869. }
  1870. LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
  1871. // __extension__ doesn't affect lvalue-ness.
  1872. if (E->getOpcode() == UO_Extension)
  1873. return EmitLValue(E->getSubExpr());
  1874. QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
  1875. switch (E->getOpcode()) {
  1876. default: llvm_unreachable("Unknown unary operator lvalue!");
  1877. case UO_Deref: {
  1878. QualType T = E->getSubExpr()->getType()->getPointeeType();
  1879. assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
  1880. LValue LV = MakeNaturalAlignAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
  1881. LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
  1882. // We should not generate __weak write barrier on indirect reference
  1883. // of a pointer to object; as in void foo (__weak id *param); *param = 0;
  1884. // But, we continue to generate __strong write barrier on indirect write
  1885. // into a pointer to object.
  1886. if (getLangOpts().ObjC1 &&
  1887. getLangOpts().getGC() != LangOptions::NonGC &&
  1888. LV.isObjCWeak())
  1889. LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
  1890. return LV;
  1891. }
  1892. case UO_Real:
  1893. case UO_Imag: {
  1894. LValue LV = EmitLValue(E->getSubExpr());
  1895. assert(LV.isSimple() && "real/imag on non-ordinary l-value");
  1896. llvm::Value *Addr = LV.getAddress();
  1897. // __real is valid on scalars. This is a faster way of testing that.
  1898. // __imag can only produce an rvalue on scalars.
  1899. if (E->getOpcode() == UO_Real &&
  1900. !cast<llvm::PointerType>(Addr->getType())
  1901. ->getElementType()->isStructTy()) {
  1902. assert(E->getSubExpr()->getType()->isArithmeticType());
  1903. return LV;
  1904. }
  1905. assert(E->getSubExpr()->getType()->isAnyComplexType());
  1906. unsigned Idx = E->getOpcode() == UO_Imag;
  1907. return MakeAddrLValue(
  1908. Builder.CreateStructGEP(nullptr, LV.getAddress(), Idx, "idx"), ExprTy);
  1909. }
  1910. case UO_PreInc:
  1911. case UO_PreDec: {
  1912. LValue LV = EmitLValue(E->getSubExpr());
  1913. bool isInc = E->getOpcode() == UO_PreInc;
  1914. if (E->getType()->isAnyComplexType())
  1915. EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
  1916. else
  1917. EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
  1918. return LV;
  1919. }
  1920. }
  1921. }
  1922. LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
  1923. return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
  1924. E->getType());
  1925. }
  1926. LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
  1927. return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
  1928. E->getType());
  1929. }
  1930. LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
  1931. auto SL = E->getFunctionName();
  1932. assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
  1933. StringRef FnName = CurFn->getName();
  1934. if (FnName.startswith("\01"))
  1935. FnName = FnName.substr(1);
  1936. StringRef NameItems[] = {
  1937. PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
  1938. std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
  1939. if (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)) {
  1940. auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str(), 1);
  1941. return MakeAddrLValue(C, E->getType());
  1942. }
  1943. auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
  1944. return MakeAddrLValue(C, E->getType());
  1945. }
  1946. /// Emit a type description suitable for use by a runtime sanitizer library. The
  1947. /// format of a type descriptor is
  1948. ///
  1949. /// \code
  1950. /// { i16 TypeKind, i16 TypeInfo }
  1951. /// \endcode
  1952. ///
  1953. /// followed by an array of i8 containing the type name. TypeKind is 0 for an
  1954. /// integer, 1 for a floating point value, and -1 for anything else.
  1955. llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
  1956. // Only emit each type's descriptor once.
  1957. if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
  1958. return C;
  1959. uint16_t TypeKind = -1;
  1960. uint16_t TypeInfo = 0;
  1961. if (T->isIntegerType()) {
  1962. TypeKind = 0;
  1963. TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
  1964. (T->isSignedIntegerType() ? 1 : 0);
  1965. } else if (T->isFloatingType()) {
  1966. TypeKind = 1;
  1967. TypeInfo = getContext().getTypeSize(T);
  1968. }
  1969. // Format the type name as if for a diagnostic, including quotes and
  1970. // optionally an 'aka'.
  1971. SmallString<32> Buffer;
  1972. CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
  1973. (intptr_t)T.getAsOpaquePtr(),
  1974. StringRef(), StringRef(), None, Buffer,
  1975. None);
  1976. llvm::Constant *Components[] = {
  1977. Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
  1978. llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
  1979. };
  1980. llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
  1981. auto *GV = new llvm::GlobalVariable(
  1982. CGM.getModule(), Descriptor->getType(),
  1983. /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
  1984. GV->setUnnamedAddr(true);
  1985. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
  1986. // Remember the descriptor for this type.
  1987. CGM.setTypeDescriptorInMap(T, GV);
  1988. return GV;
  1989. }
  1990. llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
  1991. llvm::Type *TargetTy = IntPtrTy;
  1992. // Floating-point types which fit into intptr_t are bitcast to integers
  1993. // and then passed directly (after zero-extension, if necessary).
  1994. if (V->getType()->isFloatingPointTy()) {
  1995. unsigned Bits = V->getType()->getPrimitiveSizeInBits();
  1996. if (Bits <= TargetTy->getIntegerBitWidth())
  1997. V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
  1998. Bits));
  1999. }
  2000. // Integers which fit in intptr_t are zero-extended and passed directly.
  2001. if (V->getType()->isIntegerTy() &&
  2002. V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
  2003. return Builder.CreateZExt(V, TargetTy);
  2004. // Pointers are passed directly, everything else is passed by address.
  2005. if (!V->getType()->isPointerTy()) {
  2006. llvm::Value *Ptr = CreateTempAlloca(V->getType());
  2007. Builder.CreateStore(V, Ptr);
  2008. V = Ptr;
  2009. }
  2010. return Builder.CreatePtrToInt(V, TargetTy);
  2011. }
  2012. /// \brief Emit a representation of a SourceLocation for passing to a handler
  2013. /// in a sanitizer runtime library. The format for this data is:
  2014. /// \code
  2015. /// struct SourceLocation {
  2016. /// const char *Filename;
  2017. /// int32_t Line, Column;
  2018. /// };
  2019. /// \endcode
  2020. /// For an invalid SourceLocation, the Filename pointer is null.
  2021. llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
  2022. llvm::Constant *Filename;
  2023. int Line, Column;
  2024. PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
  2025. if (PLoc.isValid()) {
  2026. auto FilenameGV = CGM.GetAddrOfConstantCString(PLoc.getFilename(), ".src");
  2027. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(FilenameGV);
  2028. Filename = FilenameGV;
  2029. Line = PLoc.getLine();
  2030. Column = PLoc.getColumn();
  2031. } else {
  2032. Filename = llvm::Constant::getNullValue(Int8PtrTy);
  2033. Line = Column = 0;
  2034. }
  2035. llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
  2036. Builder.getInt32(Column)};
  2037. return llvm::ConstantStruct::getAnon(Data);
  2038. }
  2039. namespace {
  2040. /// \brief Specify under what conditions this check can be recovered
  2041. enum class CheckRecoverableKind {
  2042. /// Always terminate program execution if this check fails.
  2043. Unrecoverable,
  2044. /// Check supports recovering, runtime has both fatal (noreturn) and
  2045. /// non-fatal handlers for this check.
  2046. Recoverable,
  2047. /// Runtime conditionally aborts, always need to support recovery.
  2048. AlwaysRecoverable
  2049. };
  2050. }
  2051. static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
  2052. assert(llvm::countPopulation(Kind) == 1);
  2053. switch (Kind) {
  2054. case SanitizerKind::Vptr:
  2055. return CheckRecoverableKind::AlwaysRecoverable;
  2056. case SanitizerKind::Return:
  2057. case SanitizerKind::Unreachable:
  2058. return CheckRecoverableKind::Unrecoverable;
  2059. default:
  2060. return CheckRecoverableKind::Recoverable;
  2061. }
  2062. }
  2063. static void emitCheckHandlerCall(CodeGenFunction &CGF,
  2064. llvm::FunctionType *FnType,
  2065. ArrayRef<llvm::Value *> FnArgs,
  2066. StringRef CheckName,
  2067. CheckRecoverableKind RecoverKind, bool IsFatal,
  2068. llvm::BasicBlock *ContBB) {
  2069. assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
  2070. bool NeedsAbortSuffix =
  2071. IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
  2072. std::string FnName = ("__ubsan_handle_" + CheckName +
  2073. (NeedsAbortSuffix ? "_abort" : "")).str();
  2074. bool MayReturn =
  2075. !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
  2076. llvm::AttrBuilder B;
  2077. if (!MayReturn) {
  2078. B.addAttribute(llvm::Attribute::NoReturn)
  2079. .addAttribute(llvm::Attribute::NoUnwind);
  2080. }
  2081. B.addAttribute(llvm::Attribute::UWTable);
  2082. llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
  2083. FnType, FnName,
  2084. llvm::AttributeSet::get(CGF.getLLVMContext(),
  2085. llvm::AttributeSet::FunctionIndex, B));
  2086. llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
  2087. if (!MayReturn) {
  2088. HandlerCall->setDoesNotReturn();
  2089. CGF.Builder.CreateUnreachable();
  2090. } else {
  2091. CGF.Builder.CreateBr(ContBB);
  2092. }
  2093. }
  2094. void CodeGenFunction::EmitCheck(
  2095. ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
  2096. StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
  2097. ArrayRef<llvm::Value *> DynamicArgs) {
  2098. assert(IsSanitizerScope);
  2099. assert(Checked.size() > 0);
  2100. llvm::Value *FatalCond = nullptr;
  2101. llvm::Value *RecoverableCond = nullptr;
  2102. llvm::Value *TrapCond = nullptr;
  2103. for (int i = 0, n = Checked.size(); i < n; ++i) {
  2104. llvm::Value *Check = Checked[i].first;
  2105. // -fsanitize-trap= overrides -fsanitize-recover=.
  2106. llvm::Value *&Cond =
  2107. CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
  2108. ? TrapCond
  2109. : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
  2110. ? RecoverableCond
  2111. : FatalCond;
  2112. Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
  2113. }
  2114. if (TrapCond)
  2115. EmitTrapCheck(TrapCond);
  2116. if (!FatalCond && !RecoverableCond)
  2117. return;
  2118. llvm::Value *JointCond;
  2119. if (FatalCond && RecoverableCond)
  2120. JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
  2121. else
  2122. JointCond = FatalCond ? FatalCond : RecoverableCond;
  2123. assert(JointCond);
  2124. CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
  2125. assert(SanOpts.has(Checked[0].second));
  2126. #ifndef NDEBUG
  2127. for (int i = 1, n = Checked.size(); i < n; ++i) {
  2128. assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
  2129. "All recoverable kinds in a single check must be same!");
  2130. assert(SanOpts.has(Checked[i].second));
  2131. }
  2132. #endif
  2133. llvm::BasicBlock *Cont = createBasicBlock("cont");
  2134. llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
  2135. llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
  2136. // Give hint that we very much don't expect to execute the handler
  2137. // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
  2138. llvm::MDBuilder MDHelper(getLLVMContext());
  2139. llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
  2140. Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
  2141. EmitBlock(Handlers);
  2142. // Emit handler arguments and create handler function type.
  2143. llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
  2144. auto *InfoPtr =
  2145. new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
  2146. llvm::GlobalVariable::PrivateLinkage, Info);
  2147. InfoPtr->setUnnamedAddr(true);
  2148. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
  2149. SmallVector<llvm::Value *, 4> Args;
  2150. SmallVector<llvm::Type *, 4> ArgTypes;
  2151. Args.reserve(DynamicArgs.size() + 1);
  2152. ArgTypes.reserve(DynamicArgs.size() + 1);
  2153. // Handler functions take an i8* pointing to the (handler-specific) static
  2154. // information block, followed by a sequence of intptr_t arguments
  2155. // representing operand values.
  2156. Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
  2157. ArgTypes.push_back(Int8PtrTy);
  2158. for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
  2159. Args.push_back(EmitCheckValue(DynamicArgs[i]));
  2160. ArgTypes.push_back(IntPtrTy);
  2161. }
  2162. llvm::FunctionType *FnType =
  2163. llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
  2164. if (!FatalCond || !RecoverableCond) {
  2165. // Simple case: we need to generate a single handler call, either
  2166. // fatal, or non-fatal.
  2167. emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind,
  2168. (FatalCond != nullptr), Cont);
  2169. } else {
  2170. // Emit two handler calls: first one for set of unrecoverable checks,
  2171. // another one for recoverable.
  2172. llvm::BasicBlock *NonFatalHandlerBB =
  2173. createBasicBlock("non_fatal." + CheckName);
  2174. llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
  2175. Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
  2176. EmitBlock(FatalHandlerBB);
  2177. emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, true,
  2178. NonFatalHandlerBB);
  2179. EmitBlock(NonFatalHandlerBB);
  2180. emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, false,
  2181. Cont);
  2182. }
  2183. EmitBlock(Cont);
  2184. }
  2185. void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
  2186. llvm::BasicBlock *Cont = createBasicBlock("cont");
  2187. // If we're optimizing, collapse all calls to trap down to just one per
  2188. // function to save on code size.
  2189. if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
  2190. TrapBB = createBasicBlock("trap");
  2191. Builder.CreateCondBr(Checked, Cont, TrapBB);
  2192. EmitBlock(TrapBB);
  2193. llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
  2194. TrapCall->setDoesNotReturn();
  2195. TrapCall->setDoesNotThrow();
  2196. Builder.CreateUnreachable();
  2197. } else {
  2198. Builder.CreateCondBr(Checked, Cont, TrapBB);
  2199. }
  2200. EmitBlock(Cont);
  2201. }
  2202. llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
  2203. llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
  2204. if (!CGM.getCodeGenOpts().TrapFuncName.empty())
  2205. TrapCall->addAttribute(llvm::AttributeSet::FunctionIndex,
  2206. "trap-func-name",
  2207. CGM.getCodeGenOpts().TrapFuncName);
  2208. return TrapCall;
  2209. }
  2210. /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
  2211. /// array to pointer, return the array subexpression.
  2212. static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
  2213. // If this isn't just an array->pointer decay, bail out.
  2214. const auto *CE = dyn_cast<CastExpr>(E);
  2215. if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
  2216. return nullptr;
  2217. // If this is a decay from variable width array, bail out.
  2218. const Expr *SubExpr = CE->getSubExpr();
  2219. if (SubExpr->getType()->isVariableArrayType())
  2220. return nullptr;
  2221. return SubExpr;
  2222. }
  2223. LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
  2224. bool Accessed) {
  2225. // The index must always be an integer, which is not an aggregate. Emit it.
  2226. llvm::Value *Idx = EmitScalarExpr(E->getIdx());
  2227. QualType IdxTy = E->getIdx()->getType();
  2228. bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
  2229. if (SanOpts.has(SanitizerKind::ArrayBounds))
  2230. EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
  2231. // If the base is a vector type, then we are forming a vector element lvalue
  2232. // with this subscript.
  2233. if (E->getBase()->getType()->isVectorType() &&
  2234. !isa<ExtVectorElementExpr>(E->getBase())) {
  2235. // Emit the vector as an lvalue to get its address.
  2236. LValue LHS = EmitLValue(E->getBase());
  2237. assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
  2238. return LValue::MakeVectorElt(LHS.getAddress(), Idx,
  2239. E->getBase()->getType(), LHS.getAlignment());
  2240. }
  2241. // Extend or truncate the index type to 32 or 64-bits.
  2242. if (Idx->getType() != IntPtrTy)
  2243. Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
  2244. // HLSL Change Starts
  2245. const Expr *Array = isSimpleArrayDecayOperand(E->getBase());
  2246. assert((!getLangOpts().HLSL || nullptr == Array) &&
  2247. "else array decay snuck in AST for HLSL");
  2248. // HLSL Change Ends
  2249. // We know that the pointer points to a type of the correct size, unless the
  2250. // size is a VLA or Objective-C interface.
  2251. llvm::Value *Address = nullptr;
  2252. CharUnits ArrayAlignment;
  2253. if (isa<ExtVectorElementExpr>(E->getBase())) {
  2254. LValue LV = EmitLValue(E->getBase());
  2255. Address = EmitExtVectorElementLValue(LV);
  2256. Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
  2257. const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
  2258. QualType EQT = ExprVT->getElementType();
  2259. return MakeAddrLValue(Address, EQT,
  2260. getContext().getTypeAlignInChars(EQT));
  2261. }
  2262. else if (const VariableArrayType *vla =
  2263. getContext().getAsVariableArrayType(E->getType())) {
  2264. // The base must be a pointer, which is not an aggregate. Emit
  2265. // it. It needs to be emitted first in case it's what captures
  2266. // the VLA bounds.
  2267. Address = EmitScalarExpr(E->getBase());
  2268. // The element count here is the total number of non-VLA elements.
  2269. llvm::Value *numElements = getVLASize(vla).first;
  2270. // Effectively, the multiply by the VLA size is part of the GEP.
  2271. // GEP indexes are signed, and scaling an index isn't permitted to
  2272. // signed-overflow, so we use the same semantics for our explicit
  2273. // multiply. We suppress this if overflow is not undefined behavior.
  2274. if (getLangOpts().isSignedOverflowDefined()) {
  2275. Idx = Builder.CreateMul(Idx, numElements);
  2276. Address = Builder.CreateGEP(Address, Idx, "arrayidx");
  2277. } else {
  2278. Idx = Builder.CreateNSWMul(Idx, numElements);
  2279. Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
  2280. }
  2281. } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
  2282. // Indexing over an interface, as in "NSString *P; P[4];"
  2283. llvm::Value *InterfaceSize =
  2284. llvm::ConstantInt::get(Idx->getType(),
  2285. getContext().getTypeSizeInChars(OIT).getQuantity());
  2286. Idx = Builder.CreateMul(Idx, InterfaceSize);
  2287. // The base must be a pointer, which is not an aggregate. Emit it.
  2288. llvm::Value *Base = EmitScalarExpr(E->getBase());
  2289. Address = EmitCastToVoidPtr(Base);
  2290. Address = Builder.CreateGEP(Address, Idx, "arrayidx");
  2291. Address = Builder.CreateBitCast(Address, Base->getType());
  2292. } else if (!getLangOpts().HLSL && Array) { // HLSL Change - No Array to pointer decay for HLSL
  2293. // If this is A[i] where A is an array, the frontend will have decayed the
  2294. // base to be a ArrayToPointerDecay implicit cast. While correct, it is
  2295. // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
  2296. // "gep x, i" here. Emit one "gep A, 0, i".
  2297. assert(Array->getType()->isArrayType() &&
  2298. "Array to pointer decay must have array source type!");
  2299. LValue ArrayLV;
  2300. // For simple multidimensional array indexing, set the 'accessed' flag for
  2301. // better bounds-checking of the base expression.
  2302. if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
  2303. ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
  2304. else
  2305. ArrayLV = EmitLValue(Array);
  2306. llvm::Value *ArrayPtr = ArrayLV.getAddress();
  2307. llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
  2308. llvm::Value *Args[] = { Zero, Idx };
  2309. // Propagate the alignment from the array itself to the result.
  2310. ArrayAlignment = ArrayLV.getAlignment();
  2311. if (getLangOpts().isSignedOverflowDefined())
  2312. Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
  2313. else
  2314. Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
  2315. } else {
  2316. // HLSL Change Starts
  2317. const ArrayType *AT = dyn_cast<ArrayType>(E->getBase()->getType()->getCanonicalTypeUnqualified());
  2318. if (getContext().getLangOpts().HLSL && AT) {
  2319. LValue ArrayLV;
  2320. // For simple multidimensional array indexing, set the 'accessed' flag for
  2321. // better bounds-checking of the base expression.
  2322. if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E->getBase()))
  2323. ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
  2324. else
  2325. ArrayLV = EmitLValue(E->getBase());
  2326. llvm::Value *ArrayPtr = ArrayLV.getAddress();
  2327. llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
  2328. llvm::Value *Args[] = { Zero, Idx };
  2329. // Propagate the alignment from the array itself to the result.
  2330. ArrayAlignment = ArrayLV.getAlignment();
  2331. if (getLangOpts().isSignedOverflowDefined())
  2332. Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
  2333. else
  2334. Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
  2335. } else {
  2336. // HLSL Change Ends
  2337. // The base must be a pointer, which is not an aggregate. Emit it.
  2338. llvm::Value *Base = EmitScalarExpr(E->getBase());
  2339. if (getLangOpts().isSignedOverflowDefined())
  2340. Address = Builder.CreateGEP(Base, Idx, "arrayidx");
  2341. else
  2342. Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
  2343. } // HLSL Change
  2344. }
  2345. QualType T = E->getBase()->getType()->getPointeeType();
  2346. // HLSL Change Starts
  2347. if (getContext().getLangOpts().HLSL && T.isNull()) {
  2348. T = QualType(E->getBase()->getType()->getArrayElementTypeNoTypeQual(), 0);
  2349. }
  2350. // HLSL Change Ends
  2351. assert(!T.isNull() &&
  2352. "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
  2353. // Limit the alignment to that of the result type.
  2354. LValue LV;
  2355. if (!ArrayAlignment.isZero()) {
  2356. CharUnits Align = getContext().getTypeAlignInChars(T);
  2357. ArrayAlignment = std::min(Align, ArrayAlignment);
  2358. LV = MakeAddrLValue(Address, T, ArrayAlignment);
  2359. } else {
  2360. LV = MakeNaturalAlignAddrLValue(Address, T);
  2361. }
  2362. LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
  2363. if (getLangOpts().ObjC1 &&
  2364. getLangOpts().getGC() != LangOptions::NonGC) {
  2365. LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
  2366. setObjCGCLValueClass(getContext(), E, LV);
  2367. }
  2368. return LV;
  2369. }
  2370. static
  2371. llvm::Constant *GenerateConstantVector(CGBuilderTy &Builder,
  2372. SmallVectorImpl<unsigned> &Elts) {
  2373. SmallVector<llvm::Constant*, 4> CElts;
  2374. for (unsigned i = 0, e = Elts.size(); i != e; ++i)
  2375. CElts.push_back(Builder.getInt32(Elts[i]));
  2376. return llvm::ConstantVector::get(CElts);
  2377. }
  2378. LValue CodeGenFunction::
  2379. EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
  2380. // Emit the base vector as an l-value.
  2381. LValue Base;
  2382. // ExtVectorElementExpr's base can either be a vector or pointer to vector.
  2383. if (E->isArrow()) {
  2384. // If it is a pointer to a vector, emit the address and form an lvalue with
  2385. // it.
  2386. llvm::Value *Ptr = EmitScalarExpr(E->getBase());
  2387. const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
  2388. Base = MakeAddrLValue(Ptr, PT->getPointeeType());
  2389. Base.getQuals().removeObjCGCAttr();
  2390. } else if (E->getBase()->isGLValue()) {
  2391. // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
  2392. // emit the base as an lvalue.
  2393. assert(E->getBase()->getType()->isVectorType());
  2394. Base = EmitLValue(E->getBase());
  2395. } else {
  2396. // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
  2397. assert(E->getBase()->getType()->isVectorType() &&
  2398. "Result must be a vector");
  2399. llvm::Value *Vec = EmitScalarExpr(E->getBase());
  2400. // Store the vector to memory (because LValue wants an address).
  2401. llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
  2402. Builder.CreateStore(Vec, VecMem);
  2403. Base = MakeAddrLValue(VecMem, E->getBase()->getType());
  2404. }
  2405. QualType type =
  2406. E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
  2407. // Encode the element access list into a vector of unsigned indices.
  2408. SmallVector<unsigned, 4> Indices;
  2409. E->getEncodedElementAccess(Indices);
  2410. if (Base.isSimple()) {
  2411. llvm::Constant *CV = GenerateConstantVector(Builder, Indices);
  2412. return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
  2413. Base.getAlignment());
  2414. }
  2415. assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
  2416. llvm::Constant *BaseElts = Base.getExtVectorElts();
  2417. SmallVector<llvm::Constant *, 4> CElts;
  2418. for (unsigned i = 0, e = Indices.size(); i != e; ++i)
  2419. CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
  2420. llvm::Constant *CV = llvm::ConstantVector::get(CElts);
  2421. return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
  2422. Base.getAlignment());
  2423. }
  2424. // HLSL Change Starts
  2425. LValue
  2426. CodeGenFunction::EmitExtMatrixElementExpr(const ExtMatrixElementExpr *E) {
  2427. LValue Base;
  2428. assert(!E->isArrow() && "ExtMatrixElementExpr's base will not be Arrow");
  2429. if (E->getBase()->isGLValue()) {
  2430. // if the base is an lvalue ( as in the case of foo.x.x),
  2431. // emit the base as an lvalue.
  2432. const Expr *base = E->getBase();
  2433. assert(hlsl::IsHLSLMatType(base->getType()));
  2434. Base = EmitLValue(base);
  2435. } else {
  2436. // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
  2437. assert(hlsl::IsHLSLMatType(E->getBase()->getType()) &&
  2438. "Result must be a vector");
  2439. llvm::Value *Vec = EmitScalarExpr(E->getBase());
  2440. // Store the vector to memory (because LValue wants an address).
  2441. llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
  2442. Builder.CreateStore(Vec, VecMem);
  2443. Base = MakeAddrLValue(VecMem, E->getBase()->getType());
  2444. }
  2445. // Encode the element access list into a vector of unsigned indices.
  2446. SmallVector<unsigned, 4> Indices;
  2447. E->getEncodedElementAccess(Indices);
  2448. llvm::Type *ResultTy =
  2449. ConvertType(getContext().getLValueReferenceType(E->getType()));
  2450. llvm::Value *matBase = nullptr;
  2451. llvm::Constant *CV = nullptr;
  2452. if (Base.isSimple()) {
  2453. SmallVector<llvm::Constant *, 4> CElts;
  2454. for (unsigned i = 0, e = Indices.size(); i != e; ++i)
  2455. CElts.push_back(Builder.getInt32(Indices[i]));
  2456. CV = llvm::ConstantVector::get(CElts);
  2457. matBase = Base.getAddress();
  2458. } else {
  2459. assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
  2460. llvm::Constant *BaseElts = Base.getExtVectorElts();
  2461. SmallVector<llvm::Constant *, 4> CElts;
  2462. for (unsigned i = 0, e = Indices.size(); i != e; ++i)
  2463. CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
  2464. CV = llvm::ConstantVector::get(CElts);
  2465. matBase = Base.getExtVectorAddr();
  2466. }
  2467. llvm::Value *Result = CGM.getHLSLRuntime().EmitHLSLMatrixElement(
  2468. *this, ResultTy, {matBase, CV}, E->getBase()->getType());
  2469. return MakeAddrLValue(Result, E->getType());
  2470. }
  2471. LValue
  2472. CodeGenFunction::EmitHLSLVectorElementExpr(const HLSLVectorElementExpr *E) {
  2473. // Emit the base vector as an l-value.
  2474. // Clone EmitExtVectorElementExpr for now
  2475. // TODO: difference between ExtVector and HlslVector
  2476. LValue Base;
  2477. // ExtVectorElementExpr's base can either be a vector or pointer to vector.
  2478. if (E->isArrow()) {
  2479. // If it is a pointer to a vector, emit the address and form an lvalue with
  2480. // it.
  2481. assert(!getLangOpts().HLSL && "this will not happen for hlsl");
  2482. } else if (E->getBase()->isGLValue()) {
  2483. // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
  2484. // emit the base as an lvalue.
  2485. const Expr *base = E->getBase();
  2486. assert(hlsl::IsHLSLVecType(base->getType()));
  2487. Base = EmitLValue(base);
  2488. } else {
  2489. // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
  2490. assert(hlsl::IsHLSLVecType(E->getBase()->getType()) &&
  2491. "Result must be a vector");
  2492. llvm::Value *Vec = EmitScalarExpr(E->getBase());
  2493. // Store the vector to memory (because LValue wants an address).
  2494. llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
  2495. Builder.CreateStore(Vec, VecMem);
  2496. Base = MakeAddrLValue(VecMem, E->getBase()->getType());
  2497. }
  2498. QualType type =
  2499. E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
  2500. // Encode the element access list into a vector of unsigned indices.
  2501. SmallVector<unsigned, 4> Indices;
  2502. E->getEncodedElementAccess(Indices);
  2503. if (Base.isSimple()) {
  2504. llvm::Constant *CV = GenerateConstantVector(Builder, Indices);
  2505. return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
  2506. Base.getAlignment());
  2507. }
  2508. assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
  2509. llvm::Constant *BaseElts = Base.getExtVectorElts();
  2510. SmallVector<llvm::Constant *, 4> CElts;
  2511. for (unsigned i = 0, e = Indices.size(); i != e; ++i)
  2512. CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
  2513. llvm::Constant *CV = llvm::ConstantVector::get(CElts);
  2514. return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
  2515. Base.getAlignment());
  2516. }
  2517. // HLSL Change Ends
  2518. LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
  2519. Expr *BaseExpr = E->getBase();
  2520. // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
  2521. LValue BaseLV;
  2522. if (E->isArrow()) {
  2523. llvm::Value *Ptr = EmitScalarExpr(BaseExpr);
  2524. QualType PtrTy = BaseExpr->getType()->getPointeeType();
  2525. EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Ptr, PtrTy);
  2526. BaseLV = MakeNaturalAlignAddrLValue(Ptr, PtrTy);
  2527. } else
  2528. BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
  2529. NamedDecl *ND = E->getMemberDecl();
  2530. if (auto *Field = dyn_cast<FieldDecl>(ND)) {
  2531. LValue LV = EmitLValueForField(BaseLV, Field);
  2532. setObjCGCLValueClass(getContext(), E, LV);
  2533. return LV;
  2534. }
  2535. if (auto *VD = dyn_cast<VarDecl>(ND))
  2536. return EmitGlobalVarDeclLValue(*this, E, VD);
  2537. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  2538. return EmitFunctionDeclLValue(*this, E, FD);
  2539. llvm_unreachable("Unhandled member declaration!");
  2540. }
  2541. /// Given that we are currently emitting a lambda, emit an l-value for
  2542. /// one of its members.
  2543. LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
  2544. assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
  2545. assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
  2546. QualType LambdaTagType =
  2547. getContext().getTagDeclType(Field->getParent());
  2548. LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
  2549. return EmitLValueForField(LambdaLV, Field);
  2550. }
  2551. LValue CodeGenFunction::EmitLValueForField(LValue base,
  2552. const FieldDecl *field) {
  2553. if (field->isBitField()) {
  2554. const CGRecordLayout &RL =
  2555. CGM.getTypes().getCGRecordLayout(field->getParent());
  2556. const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
  2557. llvm::Value *Addr = base.getAddress();
  2558. unsigned Idx = RL.getLLVMFieldNo(field);
  2559. if (Idx != 0)
  2560. // For structs, we GEP to the field that the record layout suggests.
  2561. Addr = Builder.CreateStructGEP(nullptr, Addr, Idx, field->getName());
  2562. // Get the access type.
  2563. llvm::Type *PtrTy = llvm::Type::getIntNPtrTy(
  2564. getLLVMContext(), Info.StorageSize,
  2565. CGM.getContext().getTargetAddressSpace(base.getType()));
  2566. if (Addr->getType() != PtrTy)
  2567. Addr = Builder.CreateBitCast(Addr, PtrTy);
  2568. QualType fieldType =
  2569. field->getType().withCVRQualifiers(base.getVRQualifiers());
  2570. return LValue::MakeBitfield(Addr, Info, fieldType, base.getAlignment());
  2571. }
  2572. const RecordDecl *rec = field->getParent();
  2573. QualType type = field->getType();
  2574. CharUnits alignment = getContext().getDeclAlign(field);
  2575. // FIXME: It should be impossible to have an LValue without alignment for a
  2576. // complete type.
  2577. if (!base.getAlignment().isZero())
  2578. alignment = std::min(alignment, base.getAlignment());
  2579. bool mayAlias = rec->hasAttr<MayAliasAttr>();
  2580. llvm::Value *addr = base.getAddress();
  2581. unsigned cvr = base.getVRQualifiers();
  2582. bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
  2583. if (rec->isUnion()) {
  2584. // For unions, there is no pointer adjustment.
  2585. assert(!type->isReferenceType() && "union has reference member");
  2586. // TODO: handle path-aware TBAA for union.
  2587. TBAAPath = false;
  2588. } else {
  2589. // For structs, we GEP to the field that the record layout suggests.
  2590. unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
  2591. addr = Builder.CreateStructGEP(nullptr, addr, idx, field->getName());
  2592. // If this is a reference field, load the reference right now.
  2593. if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
  2594. llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
  2595. if (cvr & Qualifiers::Volatile) load->setVolatile(true);
  2596. load->setAlignment(alignment.getQuantity());
  2597. // Loading the reference will disable path-aware TBAA.
  2598. TBAAPath = false;
  2599. if (CGM.shouldUseTBAA()) {
  2600. llvm::MDNode *tbaa;
  2601. if (mayAlias)
  2602. tbaa = CGM.getTBAAInfo(getContext().CharTy);
  2603. else
  2604. tbaa = CGM.getTBAAInfo(type);
  2605. if (tbaa)
  2606. CGM.DecorateInstruction(load, tbaa);
  2607. }
  2608. addr = load;
  2609. mayAlias = false;
  2610. type = refType->getPointeeType();
  2611. if (type->isIncompleteType())
  2612. alignment = CharUnits();
  2613. else
  2614. alignment = getContext().getTypeAlignInChars(type);
  2615. cvr = 0; // qualifiers don't recursively apply to referencee
  2616. }
  2617. }
  2618. // Make sure that the address is pointing to the right type. This is critical
  2619. // for both unions and structs. A union needs a bitcast, a struct element
  2620. // will need a bitcast if the LLVM type laid out doesn't match the desired
  2621. // type.
  2622. addr = EmitBitCastOfLValueToProperType(*this, addr,
  2623. CGM.getTypes().ConvertTypeForMem(type),
  2624. field->getName());
  2625. if (field->hasAttr<AnnotateAttr>())
  2626. addr = EmitFieldAnnotations(field, addr);
  2627. LValue LV = MakeAddrLValue(addr, type, alignment);
  2628. LV.getQuals().addCVRQualifiers(cvr);
  2629. if (TBAAPath) {
  2630. const ASTRecordLayout &Layout =
  2631. getContext().getASTRecordLayout(field->getParent());
  2632. // Set the base type to be the base type of the base LValue and
  2633. // update offset to be relative to the base type.
  2634. LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
  2635. LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
  2636. Layout.getFieldOffset(field->getFieldIndex()) /
  2637. getContext().getCharWidth());
  2638. }
  2639. // __weak attribute on a field is ignored.
  2640. if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
  2641. LV.getQuals().removeObjCGCAttr();
  2642. // Fields of may_alias structs act like 'char' for TBAA purposes.
  2643. // FIXME: this should get propagated down through anonymous structs
  2644. // and unions.
  2645. if (mayAlias && LV.getTBAAInfo())
  2646. LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
  2647. return LV;
  2648. }
  2649. LValue
  2650. CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
  2651. const FieldDecl *Field) {
  2652. QualType FieldType = Field->getType();
  2653. if (!FieldType->isReferenceType())
  2654. return EmitLValueForField(Base, Field);
  2655. const CGRecordLayout &RL =
  2656. CGM.getTypes().getCGRecordLayout(Field->getParent());
  2657. unsigned idx = RL.getLLVMFieldNo(Field);
  2658. llvm::Value *V = Builder.CreateStructGEP(nullptr, Base.getAddress(), idx);
  2659. assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
  2660. // Make sure that the address is pointing to the right type. This is critical
  2661. // for both unions and structs. A union needs a bitcast, a struct element
  2662. // will need a bitcast if the LLVM type laid out doesn't match the desired
  2663. // type.
  2664. llvm::Type *llvmType = ConvertTypeForMem(FieldType);
  2665. V = EmitBitCastOfLValueToProperType(*this, V, llvmType, Field->getName());
  2666. CharUnits Alignment = getContext().getDeclAlign(Field);
  2667. // FIXME: It should be impossible to have an LValue without alignment for a
  2668. // complete type.
  2669. if (!Base.getAlignment().isZero())
  2670. Alignment = std::min(Alignment, Base.getAlignment());
  2671. return MakeAddrLValue(V, FieldType, Alignment);
  2672. }
  2673. LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
  2674. if (E->isFileScope()) {
  2675. llvm::Value *GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
  2676. return MakeAddrLValue(GlobalPtr, E->getType());
  2677. }
  2678. if (E->getType()->isVariablyModifiedType())
  2679. // make sure to emit the VLA size.
  2680. EmitVariablyModifiedType(E->getType());
  2681. llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
  2682. const Expr *InitExpr = E->getInitializer();
  2683. LValue Result = MakeAddrLValue(DeclPtr, E->getType());
  2684. EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
  2685. /*Init*/ true);
  2686. return Result;
  2687. }
  2688. LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
  2689. if (!E->isGLValue())
  2690. // Initializing an aggregate temporary in C++11: T{...}.
  2691. return EmitAggExprToLValue(E);
  2692. // An lvalue initializer list must be initializing a reference.
  2693. assert(E->getNumInits() == 1 && "reference init with multiple values");
  2694. return EmitLValue(E->getInit(0));
  2695. }
  2696. /// Emit the operand of a glvalue conditional operator. This is either a glvalue
  2697. /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
  2698. /// LValue is returned and the current block has been terminated.
  2699. static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
  2700. const Expr *Operand) {
  2701. if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
  2702. CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
  2703. return None;
  2704. }
  2705. return CGF.EmitLValue(Operand);
  2706. }
  2707. LValue CodeGenFunction::
  2708. EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
  2709. if (!expr->isGLValue()) {
  2710. // ?: here should be an aggregate.
  2711. assert(hasAggregateEvaluationKind(expr->getType()) &&
  2712. "Unexpected conditional operator!");
  2713. return EmitAggExprToLValue(expr);
  2714. }
  2715. OpaqueValueMapping binding(*this, expr);
  2716. const Expr *condExpr = expr->getCond();
  2717. bool CondExprBool;
  2718. if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
  2719. const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
  2720. if (!CondExprBool) std::swap(live, dead);
  2721. if (!ContainsLabel(dead)) {
  2722. // If the true case is live, we need to track its region.
  2723. if (CondExprBool)
  2724. incrementProfileCounter(expr);
  2725. return EmitLValue(live);
  2726. }
  2727. }
  2728. llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
  2729. llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
  2730. llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
  2731. ConditionalEvaluation eval(*this);
  2732. EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
  2733. // Any temporaries created here are conditional.
  2734. EmitBlock(lhsBlock);
  2735. incrementProfileCounter(expr);
  2736. eval.begin(*this);
  2737. Optional<LValue> lhs =
  2738. EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
  2739. eval.end(*this);
  2740. if (lhs && !lhs->isSimple())
  2741. return EmitUnsupportedLValue(expr, "conditional operator");
  2742. lhsBlock = Builder.GetInsertBlock();
  2743. if (lhs)
  2744. Builder.CreateBr(contBlock);
  2745. // Any temporaries created here are conditional.
  2746. EmitBlock(rhsBlock);
  2747. eval.begin(*this);
  2748. Optional<LValue> rhs =
  2749. EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
  2750. eval.end(*this);
  2751. if (rhs && !rhs->isSimple())
  2752. return EmitUnsupportedLValue(expr, "conditional operator");
  2753. rhsBlock = Builder.GetInsertBlock();
  2754. EmitBlock(contBlock);
  2755. if (lhs && rhs) {
  2756. llvm::PHINode *phi = Builder.CreatePHI(lhs->getAddress()->getType(),
  2757. 2, "cond-lvalue");
  2758. phi->addIncoming(lhs->getAddress(), lhsBlock);
  2759. phi->addIncoming(rhs->getAddress(), rhsBlock);
  2760. return MakeAddrLValue(phi, expr->getType());
  2761. } else {
  2762. assert((lhs || rhs) &&
  2763. "both operands of glvalue conditional are throw-expressions?");
  2764. return lhs ? *lhs : *rhs;
  2765. }
  2766. }
  2767. /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
  2768. /// type. If the cast is to a reference, we can have the usual lvalue result,
  2769. /// otherwise if a cast is needed by the code generator in an lvalue context,
  2770. /// then it must mean that we need the address of an aggregate in order to
  2771. /// access one of its members. This can happen for all the reasons that casts
  2772. /// are permitted with aggregate result, including noop aggregate casts, and
  2773. /// cast from scalar to union.
  2774. LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
  2775. // HLSL Change Begins
  2776. if (hlsl::IsHLSLMatType(E->getType()) || hlsl::IsHLSLMatType(E->getSubExpr()->getType())) {
  2777. LValue LV = EmitLValue(E->getSubExpr());
  2778. QualType ToType = getContext().getLValueReferenceType(E->getType());
  2779. llvm::Type *RetTy = ConvertType(ToType);
  2780. // type not changed, LValueToRValue, CStyleCast may go this path
  2781. if (LV.getAddress()->getType() == RetTy)
  2782. return LV;
  2783. llvm::Value *cast = CGM.getHLSLRuntime().EmitHLSLMatrixOperationCall(*this, E, RetTy, { LV.getAddress() });
  2784. return MakeAddrLValue(cast, ToType);
  2785. }
  2786. // HLSL Change Ends
  2787. switch (E->getCastKind()) {
  2788. case CK_ToVoid:
  2789. case CK_BitCast:
  2790. case CK_ArrayToPointerDecay:
  2791. case CK_FunctionToPointerDecay:
  2792. case CK_NullToMemberPointer:
  2793. case CK_NullToPointer:
  2794. case CK_IntegralToPointer:
  2795. case CK_PointerToIntegral:
  2796. case CK_PointerToBoolean:
  2797. case CK_VectorSplat:
  2798. case CK_IntegralCast:
  2799. case CK_IntegralToBoolean:
  2800. case CK_IntegralToFloating:
  2801. case CK_FloatingToIntegral:
  2802. case CK_FloatingToBoolean:
  2803. case CK_FloatingCast:
  2804. case CK_FloatingRealToComplex:
  2805. case CK_FloatingComplexToReal:
  2806. case CK_FloatingComplexToBoolean:
  2807. case CK_FloatingComplexCast:
  2808. case CK_FloatingComplexToIntegralComplex:
  2809. case CK_IntegralRealToComplex:
  2810. case CK_IntegralComplexToReal:
  2811. case CK_IntegralComplexToBoolean:
  2812. case CK_IntegralComplexCast:
  2813. case CK_IntegralComplexToFloatingComplex:
  2814. case CK_DerivedToBaseMemberPointer:
  2815. case CK_BaseToDerivedMemberPointer:
  2816. case CK_MemberPointerToBoolean:
  2817. case CK_ReinterpretMemberPointer:
  2818. case CK_AnyPointerToBlockPointerCast:
  2819. case CK_ARCProduceObject:
  2820. case CK_ARCConsumeObject:
  2821. case CK_ARCReclaimReturnedObject:
  2822. case CK_ARCExtendBlockObject:
  2823. case CK_CopyAndAutoreleaseBlockObject:
  2824. case CK_AddressSpaceConversion:
  2825. return EmitUnsupportedLValue(E, "unexpected cast lvalue");
  2826. case CK_Dependent:
  2827. llvm_unreachable("dependent cast kind in IR gen!");
  2828. case CK_BuiltinFnToFnPtr:
  2829. llvm_unreachable("builtin functions are handled elsewhere");
  2830. // These are never l-values; just use the aggregate emission code.
  2831. case CK_NonAtomicToAtomic:
  2832. case CK_AtomicToNonAtomic:
  2833. return EmitAggExprToLValue(E);
  2834. case CK_Dynamic: {
  2835. LValue LV = EmitLValue(E->getSubExpr());
  2836. llvm::Value *V = LV.getAddress();
  2837. const auto *DCE = cast<CXXDynamicCastExpr>(E);
  2838. return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
  2839. }
  2840. case CK_ConstructorConversion:
  2841. case CK_UserDefinedConversion:
  2842. case CK_CPointerToObjCPointerCast:
  2843. case CK_BlockPointerToObjCPointerCast:
  2844. case CK_NoOp:
  2845. case CK_LValueToRValue:
  2846. return EmitLValue(E->getSubExpr());
  2847. case CK_UncheckedDerivedToBase:
  2848. case CK_DerivedToBase: {
  2849. const RecordType *DerivedClassTy =
  2850. E->getSubExpr()->getType()->getAs<RecordType>();
  2851. auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
  2852. LValue LV = EmitLValue(E->getSubExpr());
  2853. llvm::Value *This = LV.getAddress();
  2854. // Perform the derived-to-base conversion
  2855. llvm::Value *Base = GetAddressOfBaseClass(
  2856. This, DerivedClassDecl, E->path_begin(), E->path_end(),
  2857. /*NullCheckValue=*/false, E->getExprLoc());
  2858. return MakeAddrLValue(Base, E->getType());
  2859. }
  2860. case CK_ToUnion:
  2861. return EmitAggExprToLValue(E);
  2862. case CK_BaseToDerived: {
  2863. const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
  2864. auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
  2865. LValue LV = EmitLValue(E->getSubExpr());
  2866. // Perform the base-to-derived conversion
  2867. llvm::Value *Derived =
  2868. GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
  2869. E->path_begin(), E->path_end(),
  2870. /*NullCheckValue=*/false);
  2871. // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
  2872. // performed and the object is not of the derived type.
  2873. if (sanitizePerformTypeCheck())
  2874. EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
  2875. Derived, E->getType());
  2876. if (SanOpts.has(SanitizerKind::CFIDerivedCast))
  2877. EmitVTablePtrCheckForCast(E->getType(), Derived, /*MayBeNull=*/false,
  2878. CFITCK_DerivedCast, E->getLocStart());
  2879. return MakeAddrLValue(Derived, E->getType());
  2880. }
  2881. case CK_LValueBitCast: {
  2882. // This must be a reinterpret_cast (or c-style equivalent).
  2883. const auto *CE = cast<ExplicitCastExpr>(E);
  2884. LValue LV = EmitLValue(E->getSubExpr());
  2885. llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
  2886. ConvertType(CE->getTypeAsWritten()));
  2887. if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
  2888. EmitVTablePtrCheckForCast(E->getType(), V, /*MayBeNull=*/false,
  2889. CFITCK_UnrelatedCast, E->getLocStart());
  2890. return MakeAddrLValue(V, E->getType());
  2891. }
  2892. case CK_ObjCObjectLValueCast: {
  2893. LValue LV = EmitLValue(E->getSubExpr());
  2894. QualType ToType = getContext().getLValueReferenceType(E->getType());
  2895. llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
  2896. ConvertType(ToType));
  2897. return MakeAddrLValue(V, E->getType());
  2898. }
  2899. // HLSL Change Starts
  2900. case CK_HLSLVectorSplat: {
  2901. LValue LV = EmitLValue(E->getSubExpr());
  2902. llvm::Value *LVal = nullptr;
  2903. if (LV.isSimple())
  2904. LVal = LV.getAddress();
  2905. else if (LV.isExtVectorElt()) {
  2906. llvm::Constant *VecElts = LV.getExtVectorElts();
  2907. LVal = Builder.CreateGEP(
  2908. LV.getExtVectorAddr(),
  2909. {Builder.getInt32(0), VecElts->getAggregateElement((unsigned)0)});
  2910. } else
  2911. // TODO: make sure all cases are supported.
  2912. assert(0 && "not implement cases");
  2913. QualType ToType = getContext().getLValueReferenceType(E->getType());
  2914. // bitcast to target type
  2915. llvm::Type *ResultType = ConvertType(ToType);
  2916. llvm::Value *bitcast = Builder.CreateBitCast(LVal, ResultType);
  2917. return MakeAddrLValue(bitcast, ToType);
  2918. }
  2919. case CK_HLSLVectorTruncationCast: {
  2920. LValue LV = EmitLValue(E->getSubExpr());
  2921. QualType ToType = getContext().getLValueReferenceType(E->getType());
  2922. // bitcast to target type
  2923. llvm::Type *ResultType = ConvertType(ToType);
  2924. llvm::Value *bitcast = Builder.CreateBitCast(LV.getAddress(), ResultType);
  2925. return MakeAddrLValue(bitcast, ToType);
  2926. }
  2927. case CK_HLSLVectorToScalarCast: {
  2928. LValue LV = EmitLValue(E->getSubExpr());
  2929. QualType ToType = getContext().getLValueReferenceType(E->getType());
  2930. llvm::ConstantInt *idxZero = llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0);
  2931. llvm::Value *GEP = Builder.CreateInBoundsGEP(LV.getAddress(), {idxZero, idxZero});
  2932. return MakeAddrLValue(GEP, ToType);
  2933. } break;
  2934. case CK_HLSLCC_IntegralToFloating:
  2935. case CK_HLSLCC_FloatingToIntegral: {
  2936. LValue LV = EmitLValue(E->getSubExpr());
  2937. QualType ToType = getContext().getLValueReferenceType(E->getType());
  2938. // bitcast to target type
  2939. llvm::Type *ResultType = ConvertType(ToType);
  2940. llvm::Value *bitcast = Builder.CreateBitCast(LV.getAddress(), ResultType);
  2941. return MakeAddrLValue(bitcast, ToType);
  2942. }
  2943. case CK_FlatConversion: {
  2944. // Just bitcast.
  2945. QualType ToType = getContext().getLValueReferenceType(E->getType());
  2946. LValue LV = EmitLValue(E->getSubExpr());
  2947. llvm::Value *This = LV.getAddress();
  2948. // bitcast to target type
  2949. llvm::Type *ResultType = ConvertType(ToType);
  2950. llvm::Value *bitcast = Builder.CreateBitCast(This, ResultType);
  2951. return MakeAddrLValue(bitcast, ToType);
  2952. }
  2953. case CK_HLSLDerivedToBase: {
  2954. // HLSL only single inheritance.
  2955. // Just GEP.
  2956. QualType ToType = getContext().getLValueReferenceType(E->getType());
  2957. LValue LV = EmitLValue(E->getSubExpr());
  2958. llvm::Value *This = LV.getAddress();
  2959. // gep to target type
  2960. llvm::Type *ResultType = ConvertType(ToType);
  2961. unsigned level = 0;
  2962. llvm::Type *ToTy = ResultType->getPointerElementType();
  2963. llvm::Type *FromTy = This->getType()->getPointerElementType();
  2964. // For empty struct, just bitcast.
  2965. if (!isa<llvm::StructType>(FromTy->getStructElementType(0))) {
  2966. llvm::Value *bitcast = Builder.CreateBitCast(This, ResultType);
  2967. return MakeAddrLValue(bitcast, ToType);
  2968. }
  2969. while (ToTy != FromTy) {
  2970. FromTy = FromTy->getStructElementType(0);
  2971. ++level;
  2972. }
  2973. llvm::Value *zeroIdx = Builder.getInt32(0);
  2974. SmallVector<llvm::Value *, 2> IdxList(level + 1, zeroIdx);
  2975. llvm::Value *GEP = Builder.CreateInBoundsGEP(This, IdxList);
  2976. return MakeAddrLValue(GEP, ToType);
  2977. }
  2978. // HLSL Change Ends
  2979. case CK_ZeroToOCLEvent:
  2980. llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
  2981. }
  2982. llvm_unreachable("Unhandled lvalue cast kind?");
  2983. }
  2984. LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
  2985. assert(OpaqueValueMappingData::shouldBindAsLValue(e));
  2986. return getOpaqueLValueMapping(e);
  2987. }
  2988. RValue CodeGenFunction::EmitRValueForField(LValue LV,
  2989. const FieldDecl *FD,
  2990. SourceLocation Loc) {
  2991. QualType FT = FD->getType();
  2992. LValue FieldLV = EmitLValueForField(LV, FD);
  2993. switch (getEvaluationKind(FT)) {
  2994. case TEK_Complex:
  2995. return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
  2996. case TEK_Aggregate:
  2997. return FieldLV.asAggregateRValue();
  2998. case TEK_Scalar:
  2999. return EmitLoadOfLValue(FieldLV, Loc);
  3000. }
  3001. llvm_unreachable("bad evaluation kind");
  3002. }
  3003. //===--------------------------------------------------------------------===//
  3004. // Expression Emission
  3005. //===--------------------------------------------------------------------===//
  3006. RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
  3007. ReturnValueSlot ReturnValue) {
  3008. // Builtins never have block type.
  3009. if (E->getCallee()->getType()->isBlockPointerType())
  3010. return EmitBlockCallExpr(E, ReturnValue);
  3011. if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
  3012. return EmitCXXMemberCallExpr(CE, ReturnValue);
  3013. if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
  3014. return EmitCUDAKernelCallExpr(CE, ReturnValue);
  3015. const Decl *TargetDecl = E->getCalleeDecl();
  3016. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
  3017. if (unsigned builtinID = FD->getBuiltinID())
  3018. return EmitBuiltinExpr(FD, builtinID, E, ReturnValue);
  3019. // HLSL Change Starts
  3020. if (getLangOpts().HLSL) {
  3021. if (const NamespaceDecl *ns = dyn_cast<NamespaceDecl>(FD->getParent())) {
  3022. if (ns->getName() == "hlsl") {
  3023. // do hlsl intrinsic generation
  3024. return EmitHLSLBuiltinCallExpr(FD, E, ReturnValue);
  3025. }
  3026. }
  3027. }
  3028. // HLSL Change End
  3029. }
  3030. if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
  3031. if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
  3032. return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
  3033. if (const auto *PseudoDtor =
  3034. dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
  3035. QualType DestroyedType = PseudoDtor->getDestroyedType();
  3036. if (getLangOpts().ObjCAutoRefCount &&
  3037. DestroyedType->isObjCLifetimeType() &&
  3038. (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
  3039. DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
  3040. // Automatic Reference Counting:
  3041. // If the pseudo-expression names a retainable object with weak or
  3042. // strong lifetime, the object shall be released.
  3043. Expr *BaseExpr = PseudoDtor->getBase();
  3044. llvm::Value *BaseValue = nullptr;
  3045. Qualifiers BaseQuals;
  3046. // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
  3047. if (PseudoDtor->isArrow()) {
  3048. BaseValue = EmitScalarExpr(BaseExpr);
  3049. const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
  3050. BaseQuals = PTy->getPointeeType().getQualifiers();
  3051. } else {
  3052. LValue BaseLV = EmitLValue(BaseExpr);
  3053. BaseValue = BaseLV.getAddress();
  3054. QualType BaseTy = BaseExpr->getType();
  3055. BaseQuals = BaseTy.getQualifiers();
  3056. }
  3057. switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
  3058. case Qualifiers::OCL_None:
  3059. case Qualifiers::OCL_ExplicitNone:
  3060. case Qualifiers::OCL_Autoreleasing:
  3061. break;
  3062. case Qualifiers::OCL_Strong:
  3063. EmitARCRelease(Builder.CreateLoad(BaseValue,
  3064. PseudoDtor->getDestroyedType().isVolatileQualified()),
  3065. ARCPreciseLifetime);
  3066. break;
  3067. case Qualifiers::OCL_Weak:
  3068. EmitARCDestroyWeak(BaseValue);
  3069. break;
  3070. }
  3071. } else {
  3072. // C++ [expr.pseudo]p1:
  3073. // The result shall only be used as the operand for the function call
  3074. // operator (), and the result of such a call has type void. The only
  3075. // effect is the evaluation of the postfix-expression before the dot or
  3076. // arrow.
  3077. EmitScalarExpr(E->getCallee());
  3078. }
  3079. return RValue::get(nullptr);
  3080. }
  3081. llvm::Value *Callee = EmitScalarExpr(E->getCallee());
  3082. return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
  3083. TargetDecl);
  3084. }
  3085. LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
  3086. // Comma expressions just emit their LHS then their RHS as an l-value.
  3087. if (E->getOpcode() == BO_Comma) {
  3088. EmitIgnoredExpr(E->getLHS());
  3089. EnsureInsertPoint();
  3090. return EmitLValue(E->getRHS());
  3091. }
  3092. if (E->getOpcode() == BO_PtrMemD ||
  3093. E->getOpcode() == BO_PtrMemI)
  3094. return EmitPointerToDataMemberBinaryExpr(E);
  3095. assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
  3096. // Note that in all of these cases, __block variables need the RHS
  3097. // evaluated first just in case the variable gets moved by the RHS.
  3098. switch (getEvaluationKind(E->getType())) {
  3099. case TEK_Scalar: {
  3100. switch (E->getLHS()->getType().getObjCLifetime()) {
  3101. case Qualifiers::OCL_Strong:
  3102. return EmitARCStoreStrong(E, /*ignored*/ false).first;
  3103. case Qualifiers::OCL_Autoreleasing:
  3104. return EmitARCStoreAutoreleasing(E).first;
  3105. // No reason to do any of these differently.
  3106. case Qualifiers::OCL_None:
  3107. case Qualifiers::OCL_ExplicitNone:
  3108. case Qualifiers::OCL_Weak:
  3109. break;
  3110. }
  3111. RValue RV = EmitAnyExpr(E->getRHS());
  3112. LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
  3113. EmitStoreThroughLValue(RV, LV);
  3114. return LV;
  3115. }
  3116. case TEK_Complex:
  3117. return EmitComplexAssignmentLValue(E);
  3118. case TEK_Aggregate:
  3119. return EmitAggExprToLValue(E);
  3120. }
  3121. llvm_unreachable("bad evaluation kind");
  3122. }
  3123. LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
  3124. RValue RV = EmitCallExpr(E);
  3125. if (!RV.isScalar())
  3126. return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
  3127. assert(E->getCallReturnType(getContext())->isReferenceType() &&
  3128. "Can't have a scalar return unless the return type is a "
  3129. "reference type!");
  3130. return MakeAddrLValue(RV.getScalarVal(), E->getType());
  3131. }
  3132. LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
  3133. // FIXME: This shouldn't require another copy.
  3134. return EmitAggExprToLValue(E);
  3135. }
  3136. LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
  3137. assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
  3138. && "binding l-value to type which needs a temporary");
  3139. AggValueSlot Slot = CreateAggTemp(E->getType());
  3140. EmitCXXConstructExpr(E, Slot);
  3141. return MakeAddrLValue(Slot.getAddr(), E->getType());
  3142. }
  3143. LValue
  3144. CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
  3145. return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
  3146. }
  3147. llvm::Value *CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
  3148. return Builder.CreateBitCast(CGM.GetAddrOfUuidDescriptor(E),
  3149. ConvertType(E->getType())->getPointerTo());
  3150. }
  3151. LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
  3152. return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType());
  3153. }
  3154. LValue
  3155. CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
  3156. AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
  3157. Slot.setExternallyDestructed();
  3158. EmitAggExpr(E->getSubExpr(), Slot);
  3159. EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddr());
  3160. return MakeAddrLValue(Slot.getAddr(), E->getType());
  3161. }
  3162. LValue
  3163. CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
  3164. AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
  3165. EmitLambdaExpr(E, Slot);
  3166. return MakeAddrLValue(Slot.getAddr(), E->getType());
  3167. }
  3168. LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
  3169. RValue RV = EmitObjCMessageExpr(E);
  3170. if (!RV.isScalar())
  3171. return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
  3172. assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
  3173. "Can't have a scalar return unless the return type is a "
  3174. "reference type!");
  3175. return MakeAddrLValue(RV.getScalarVal(), E->getType());
  3176. }
  3177. LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
  3178. llvm::Value *V =
  3179. CGM.getObjCRuntime().GetSelector(*this, E->getSelector(), true);
  3180. return MakeAddrLValue(V, E->getType());
  3181. }
  3182. llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
  3183. const ObjCIvarDecl *Ivar) {
  3184. return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
  3185. }
  3186. LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
  3187. llvm::Value *BaseValue,
  3188. const ObjCIvarDecl *Ivar,
  3189. unsigned CVRQualifiers) {
  3190. return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
  3191. Ivar, CVRQualifiers);
  3192. }
  3193. LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
  3194. // FIXME: A lot of the code below could be shared with EmitMemberExpr.
  3195. llvm::Value *BaseValue = nullptr;
  3196. const Expr *BaseExpr = E->getBase();
  3197. Qualifiers BaseQuals;
  3198. QualType ObjectTy;
  3199. if (E->isArrow()) {
  3200. BaseValue = EmitScalarExpr(BaseExpr);
  3201. ObjectTy = BaseExpr->getType()->getPointeeType();
  3202. BaseQuals = ObjectTy.getQualifiers();
  3203. } else {
  3204. LValue BaseLV = EmitLValue(BaseExpr);
  3205. // FIXME: this isn't right for bitfields.
  3206. BaseValue = BaseLV.getAddress();
  3207. ObjectTy = BaseExpr->getType();
  3208. BaseQuals = ObjectTy.getQualifiers();
  3209. }
  3210. LValue LV =
  3211. EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
  3212. BaseQuals.getCVRQualifiers());
  3213. setObjCGCLValueClass(getContext(), E, LV);
  3214. return LV;
  3215. }
  3216. LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
  3217. // Can only get l-value for message expression returning aggregate type
  3218. RValue RV = EmitAnyExprToTemp(E);
  3219. return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
  3220. }
  3221. RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
  3222. const CallExpr *E, ReturnValueSlot ReturnValue,
  3223. const Decl *TargetDecl, llvm::Value *Chain) {
  3224. // Get the actual function type. The callee type will always be a pointer to
  3225. // function type or a block pointer type.
  3226. assert(CalleeType->isFunctionPointerType() &&
  3227. "Call must have function pointer type!");
  3228. CalleeType = getContext().getCanonicalType(CalleeType);
  3229. const auto *FnType =
  3230. cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
  3231. if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
  3232. (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
  3233. if (llvm::Constant *PrefixSig =
  3234. CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
  3235. SanitizerScope SanScope(this);
  3236. llvm::Constant *FTRTTIConst =
  3237. CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
  3238. llvm::Type *PrefixStructTyElems[] = {
  3239. PrefixSig->getType(),
  3240. FTRTTIConst->getType()
  3241. };
  3242. llvm::StructType *PrefixStructTy = llvm::StructType::get(
  3243. CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
  3244. llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
  3245. Callee, llvm::PointerType::getUnqual(PrefixStructTy));
  3246. llvm::Value *CalleeSigPtr =
  3247. Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
  3248. llvm::Value *CalleeSig = Builder.CreateLoad(CalleeSigPtr);
  3249. llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
  3250. llvm::BasicBlock *Cont = createBasicBlock("cont");
  3251. llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
  3252. Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
  3253. EmitBlock(TypeCheck);
  3254. llvm::Value *CalleeRTTIPtr =
  3255. Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
  3256. llvm::Value *CalleeRTTI = Builder.CreateLoad(CalleeRTTIPtr);
  3257. llvm::Value *CalleeRTTIMatch =
  3258. Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
  3259. llvm::Constant *StaticData[] = {
  3260. EmitCheckSourceLocation(E->getLocStart()),
  3261. EmitCheckTypeDescriptor(CalleeType)
  3262. };
  3263. EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
  3264. "function_type_mismatch", StaticData, Callee);
  3265. Builder.CreateBr(Cont);
  3266. EmitBlock(Cont);
  3267. }
  3268. }
  3269. // HLSL Change Begins
  3270. llvm::SmallVector<LValue, 8> castArgList;
  3271. // The argList of the CallExpr, may be update for out parameter
  3272. llvm::SmallVector<const Stmt *, 8> argList(E->arg_begin(), E->arg_end());
  3273. ConstExprIterator argBegin = argList.data();
  3274. ConstExprIterator argEnd = argList.data() + E->getNumArgs();
  3275. // out param conversion
  3276. CodeGenFunction::HLSLOutParamScope OutParamScope(*this);
  3277. auto MapTemp = [&](const VarDecl *LocalVD, llvm::Value *TmpArg) {
  3278. OutParamScope.addTemp(LocalVD, TmpArg);
  3279. };
  3280. if (getLangOpts().HLSL) {
  3281. if (const FunctionDecl *FD = E->getDirectCallee())
  3282. CGM.getHLSLRuntime().EmitHLSLOutParamConversionInit(*this, FD, E,
  3283. castArgList, argList, MapTemp);
  3284. }
  3285. // HLSL Change Ends
  3286. CallArgList Args;
  3287. if (Chain)
  3288. Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
  3289. CGM.getContext().VoidPtrTy);
  3290. EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), argBegin, argEnd, // HLSL Change - use updated argList
  3291. E->getDirectCallee(), /*ParamsToSkip*/ 0);
  3292. const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
  3293. Args, FnType, /*isChainCall=*/Chain);
  3294. // C99 6.5.2.2p6:
  3295. // If the expression that denotes the called function has a type
  3296. // that does not include a prototype, [the default argument
  3297. // promotions are performed]. If the number of arguments does not
  3298. // equal the number of parameters, the behavior is undefined. If
  3299. // the function is defined with a type that includes a prototype,
  3300. // and either the prototype ends with an ellipsis (, ...) or the
  3301. // types of the arguments after promotion are not compatible with
  3302. // the types of the parameters, the behavior is undefined. If the
  3303. // function is defined with a type that does not include a
  3304. // prototype, and the types of the arguments after promotion are
  3305. // not compatible with those of the parameters after promotion,
  3306. // the behavior is undefined [except in some trivial cases].
  3307. // That is, in the general case, we should assume that a call
  3308. // through an unprototyped function type works like a *non-variadic*
  3309. // call. The way we make this work is to cast to the exact type
  3310. // of the promoted arguments.
  3311. //
  3312. // Chain calls use this same code path to add the invisible chain parameter
  3313. // to the function type.
  3314. if (isa<FunctionNoProtoType>(FnType) || Chain) {
  3315. llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
  3316. CalleeTy = CalleeTy->getPointerTo();
  3317. Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
  3318. }
  3319. RValue CallVal = EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
  3320. // HLSL Change Begins
  3321. // out param conversion
  3322. // conversion and copy back after the call
  3323. if (getLangOpts().HLSL)
  3324. CGM.getHLSLRuntime().EmitHLSLOutParamConversionCopyBack(*this, castArgList);
  3325. // HLSL Change Ends
  3326. return CallVal;
  3327. }
  3328. LValue CodeGenFunction::
  3329. EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
  3330. llvm::Value *BaseV;
  3331. if (E->getOpcode() == BO_PtrMemI)
  3332. BaseV = EmitScalarExpr(E->getLHS());
  3333. else
  3334. BaseV = EmitLValue(E->getLHS()).getAddress();
  3335. llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
  3336. const MemberPointerType *MPT
  3337. = E->getRHS()->getType()->getAs<MemberPointerType>();
  3338. llvm::Value *AddV = CGM.getCXXABI().EmitMemberDataPointerAddress(
  3339. *this, E, BaseV, OffsetV, MPT);
  3340. return MakeAddrLValue(AddV, MPT->getPointeeType());
  3341. }
  3342. /// Given the address of a temporary variable, produce an r-value of
  3343. /// its type.
  3344. RValue CodeGenFunction::convertTempToRValue(llvm::Value *addr,
  3345. QualType type,
  3346. SourceLocation loc) {
  3347. LValue lvalue = MakeNaturalAlignAddrLValue(addr, type);
  3348. switch (getEvaluationKind(type)) {
  3349. case TEK_Complex:
  3350. return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
  3351. case TEK_Aggregate:
  3352. return lvalue.asAggregateRValue();
  3353. case TEK_Scalar:
  3354. return RValue::get(EmitLoadOfScalar(lvalue, loc));
  3355. }
  3356. llvm_unreachable("bad evaluation kind");
  3357. }
  3358. void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
  3359. assert(Val->getType()->isFPOrFPVectorTy());
  3360. if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
  3361. return;
  3362. llvm::MDBuilder MDHelper(getLLVMContext());
  3363. llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
  3364. cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
  3365. }
  3366. namespace {
  3367. struct LValueOrRValue {
  3368. LValue LV;
  3369. RValue RV;
  3370. };
  3371. }
  3372. static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
  3373. const PseudoObjectExpr *E,
  3374. bool forLValue,
  3375. AggValueSlot slot) {
  3376. SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
  3377. // Find the result expression, if any.
  3378. const Expr *resultExpr = E->getResultExpr();
  3379. LValueOrRValue result;
  3380. for (PseudoObjectExpr::const_semantics_iterator
  3381. i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
  3382. const Expr *semantic = *i;
  3383. // If this semantic expression is an opaque value, bind it
  3384. // to the result of its source expression.
  3385. if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
  3386. // If this is the result expression, we may need to evaluate
  3387. // directly into the slot.
  3388. typedef CodeGenFunction::OpaqueValueMappingData OVMA;
  3389. OVMA opaqueData;
  3390. if (ov == resultExpr && ov->isRValue() && !forLValue &&
  3391. CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
  3392. CGF.EmitAggExpr(ov->getSourceExpr(), slot);
  3393. LValue LV = CGF.MakeAddrLValue(slot.getAddr(), ov->getType());
  3394. opaqueData = OVMA::bind(CGF, ov, LV);
  3395. result.RV = slot.asRValue();
  3396. // Otherwise, emit as normal.
  3397. } else {
  3398. opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
  3399. // If this is the result, also evaluate the result now.
  3400. if (ov == resultExpr) {
  3401. if (forLValue)
  3402. result.LV = CGF.EmitLValue(ov);
  3403. else
  3404. result.RV = CGF.EmitAnyExpr(ov, slot);
  3405. }
  3406. }
  3407. opaques.push_back(opaqueData);
  3408. // Otherwise, if the expression is the result, evaluate it
  3409. // and remember the result.
  3410. } else if (semantic == resultExpr) {
  3411. if (forLValue)
  3412. result.LV = CGF.EmitLValue(semantic);
  3413. else
  3414. result.RV = CGF.EmitAnyExpr(semantic, slot);
  3415. // Otherwise, evaluate the expression in an ignored context.
  3416. } else {
  3417. CGF.EmitIgnoredExpr(semantic);
  3418. }
  3419. }
  3420. // Unbind all the opaques now.
  3421. for (unsigned i = 0, e = opaques.size(); i != e; ++i)
  3422. opaques[i].unbind(CGF);
  3423. return result;
  3424. }
  3425. RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
  3426. AggValueSlot slot) {
  3427. return emitPseudoObjectExpr(*this, E, false, slot).RV;
  3428. }
  3429. LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
  3430. return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
  3431. }