CGExpr.cpp 199 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092
  1. //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This contains code to emit Expr nodes as LLVM code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CGCXXABI.h"
  13. #include "CGCall.h"
  14. #include "CGCleanup.h"
  15. #include "CGDebugInfo.h"
  16. #include "CGObjCRuntime.h"
  17. #include "CGOpenMPRuntime.h"
  18. #include "CGRecordLayout.h"
  19. #include "CodeGenFunction.h"
  20. #include "CodeGenModule.h"
  21. #include "ConstantEmitter.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/AST/NSAPI.h"
  27. #include "clang/Basic/Builtins.h"
  28. #include "clang/Basic/CodeGenOptions.h"
  29. #include "llvm/ADT/Hashing.h"
  30. #include "llvm/ADT/StringExtras.h"
  31. #include "llvm/IR/DataLayout.h"
  32. #include "llvm/IR/Intrinsics.h"
  33. #include "llvm/IR/LLVMContext.h"
  34. #include "llvm/IR/MDBuilder.h"
  35. #include "llvm/Support/ConvertUTF.h"
  36. #include "llvm/Support/MathExtras.h"
  37. #include "llvm/Support/Path.h"
  38. #include "llvm/Transforms/Utils/SanitizerStats.h"
  39. #include <string>
  40. using namespace clang;
  41. using namespace CodeGen;
  42. //===--------------------------------------------------------------------===//
  43. // Miscellaneous Helper Methods
  44. //===--------------------------------------------------------------------===//
  45. llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
  46. unsigned addressSpace =
  47. cast<llvm::PointerType>(value->getType())->getAddressSpace();
  48. llvm::PointerType *destType = Int8PtrTy;
  49. if (addressSpace)
  50. destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
  51. if (value->getType() == destType) return value;
  52. return Builder.CreateBitCast(value, destType);
  53. }
  54. /// CreateTempAlloca - This creates a alloca and inserts it into the entry
  55. /// block.
  56. Address CodeGenFunction::CreateTempAllocaWithoutCast(llvm::Type *Ty,
  57. CharUnits Align,
  58. const Twine &Name,
  59. llvm::Value *ArraySize) {
  60. auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
  61. Alloca->setAlignment(Align.getAsAlign());
  62. return Address(Alloca, Align);
  63. }
  64. /// CreateTempAlloca - This creates a alloca and inserts it into the entry
  65. /// block. The alloca is casted to default address space if necessary.
  66. Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
  67. const Twine &Name,
  68. llvm::Value *ArraySize,
  69. Address *AllocaAddr) {
  70. auto Alloca = CreateTempAllocaWithoutCast(Ty, Align, Name, ArraySize);
  71. if (AllocaAddr)
  72. *AllocaAddr = Alloca;
  73. llvm::Value *V = Alloca.getPointer();
  74. // Alloca always returns a pointer in alloca address space, which may
  75. // be different from the type defined by the language. For example,
  76. // in C++ the auto variables are in the default address space. Therefore
  77. // cast alloca to the default address space when necessary.
  78. if (getASTAllocaAddressSpace() != LangAS::Default) {
  79. auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
  80. llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
  81. // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
  82. // otherwise alloca is inserted at the current insertion point of the
  83. // builder.
  84. if (!ArraySize)
  85. Builder.SetInsertPoint(AllocaInsertPt);
  86. V = getTargetHooks().performAddrSpaceCast(
  87. *this, V, getASTAllocaAddressSpace(), LangAS::Default,
  88. Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
  89. }
  90. return Address(V, Align);
  91. }
  92. /// CreateTempAlloca - This creates an alloca and inserts it into the entry
  93. /// block if \p ArraySize is nullptr, otherwise inserts it at the current
  94. /// insertion point of the builder.
  95. llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
  96. const Twine &Name,
  97. llvm::Value *ArraySize) {
  98. if (ArraySize)
  99. return Builder.CreateAlloca(Ty, ArraySize, Name);
  100. return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
  101. ArraySize, Name, AllocaInsertPt);
  102. }
  103. /// CreateDefaultAlignTempAlloca - This creates an alloca with the
  104. /// default alignment of the corresponding LLVM type, which is *not*
  105. /// guaranteed to be related in any way to the expected alignment of
  106. /// an AST type that might have been lowered to Ty.
  107. Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
  108. const Twine &Name) {
  109. CharUnits Align =
  110. CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
  111. return CreateTempAlloca(Ty, Align, Name);
  112. }
  113. void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
  114. assert(isa<llvm::AllocaInst>(Var.getPointer()));
  115. auto *Store = new llvm::StoreInst(Init, Var.getPointer());
  116. Store->setAlignment(Var.getAlignment().getAsAlign());
  117. llvm::BasicBlock *Block = AllocaInsertPt->getParent();
  118. Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
  119. }
  120. Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
  121. CharUnits Align = getContext().getTypeAlignInChars(Ty);
  122. return CreateTempAlloca(ConvertType(Ty), Align, Name);
  123. }
  124. Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
  125. Address *Alloca) {
  126. // FIXME: Should we prefer the preferred type alignment here?
  127. return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name, Alloca);
  128. }
  129. Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
  130. const Twine &Name, Address *Alloca) {
  131. return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name,
  132. /*ArraySize=*/nullptr, Alloca);
  133. }
  134. Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty, CharUnits Align,
  135. const Twine &Name) {
  136. return CreateTempAllocaWithoutCast(ConvertTypeForMem(Ty), Align, Name);
  137. }
  138. Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty,
  139. const Twine &Name) {
  140. return CreateMemTempWithoutCast(Ty, getContext().getTypeAlignInChars(Ty),
  141. Name);
  142. }
  143. /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
  144. /// expression and compare the result against zero, returning an Int1Ty value.
  145. llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
  146. PGO.setCurrentStmt(E);
  147. if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
  148. llvm::Value *MemPtr = EmitScalarExpr(E);
  149. return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
  150. }
  151. QualType BoolTy = getContext().BoolTy;
  152. SourceLocation Loc = E->getExprLoc();
  153. if (!E->getType()->isAnyComplexType())
  154. return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
  155. return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
  156. Loc);
  157. }
  158. /// EmitIgnoredExpr - Emit code to compute the specified expression,
  159. /// ignoring the result.
  160. void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
  161. if (E->isRValue())
  162. return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
  163. // Just emit it as an l-value and drop the result.
  164. EmitLValue(E);
  165. }
  166. /// EmitAnyExpr - Emit code to compute the specified expression which
  167. /// can have any type. The result is returned as an RValue struct.
  168. /// If this is an aggregate expression, AggSlot indicates where the
  169. /// result should be returned.
  170. RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
  171. AggValueSlot aggSlot,
  172. bool ignoreResult) {
  173. switch (getEvaluationKind(E->getType())) {
  174. case TEK_Scalar:
  175. return RValue::get(EmitScalarExpr(E, ignoreResult));
  176. case TEK_Complex:
  177. return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
  178. case TEK_Aggregate:
  179. if (!ignoreResult && aggSlot.isIgnored())
  180. aggSlot = CreateAggTemp(E->getType(), "agg-temp");
  181. EmitAggExpr(E, aggSlot);
  182. return aggSlot.asRValue();
  183. }
  184. llvm_unreachable("bad evaluation kind");
  185. }
  186. /// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
  187. /// always be accessible even if no aggregate location is provided.
  188. RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
  189. AggValueSlot AggSlot = AggValueSlot::ignored();
  190. if (hasAggregateEvaluationKind(E->getType()))
  191. AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
  192. return EmitAnyExpr(E, AggSlot);
  193. }
  194. /// EmitAnyExprToMem - Evaluate an expression into a given memory
  195. /// location.
  196. void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
  197. Address Location,
  198. Qualifiers Quals,
  199. bool IsInit) {
  200. // FIXME: This function should take an LValue as an argument.
  201. switch (getEvaluationKind(E->getType())) {
  202. case TEK_Complex:
  203. EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
  204. /*isInit*/ false);
  205. return;
  206. case TEK_Aggregate: {
  207. EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
  208. AggValueSlot::IsDestructed_t(IsInit),
  209. AggValueSlot::DoesNotNeedGCBarriers,
  210. AggValueSlot::IsAliased_t(!IsInit),
  211. AggValueSlot::MayOverlap));
  212. return;
  213. }
  214. case TEK_Scalar: {
  215. RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
  216. LValue LV = MakeAddrLValue(Location, E->getType());
  217. EmitStoreThroughLValue(RV, LV);
  218. return;
  219. }
  220. }
  221. llvm_unreachable("bad evaluation kind");
  222. }
  223. static void
  224. pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
  225. const Expr *E, Address ReferenceTemporary) {
  226. // Objective-C++ ARC:
  227. // If we are binding a reference to a temporary that has ownership, we
  228. // need to perform retain/release operations on the temporary.
  229. //
  230. // FIXME: This should be looking at E, not M.
  231. if (auto Lifetime = M->getType().getObjCLifetime()) {
  232. switch (Lifetime) {
  233. case Qualifiers::OCL_None:
  234. case Qualifiers::OCL_ExplicitNone:
  235. // Carry on to normal cleanup handling.
  236. break;
  237. case Qualifiers::OCL_Autoreleasing:
  238. // Nothing to do; cleaned up by an autorelease pool.
  239. return;
  240. case Qualifiers::OCL_Strong:
  241. case Qualifiers::OCL_Weak:
  242. switch (StorageDuration Duration = M->getStorageDuration()) {
  243. case SD_Static:
  244. // Note: we intentionally do not register a cleanup to release
  245. // the object on program termination.
  246. return;
  247. case SD_Thread:
  248. // FIXME: We should probably register a cleanup in this case.
  249. return;
  250. case SD_Automatic:
  251. case SD_FullExpression:
  252. CodeGenFunction::Destroyer *Destroy;
  253. CleanupKind CleanupKind;
  254. if (Lifetime == Qualifiers::OCL_Strong) {
  255. const ValueDecl *VD = M->getExtendingDecl();
  256. bool Precise =
  257. VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
  258. CleanupKind = CGF.getARCCleanupKind();
  259. Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
  260. : &CodeGenFunction::destroyARCStrongImprecise;
  261. } else {
  262. // __weak objects always get EH cleanups; otherwise, exceptions
  263. // could cause really nasty crashes instead of mere leaks.
  264. CleanupKind = NormalAndEHCleanup;
  265. Destroy = &CodeGenFunction::destroyARCWeak;
  266. }
  267. if (Duration == SD_FullExpression)
  268. CGF.pushDestroy(CleanupKind, ReferenceTemporary,
  269. M->getType(), *Destroy,
  270. CleanupKind & EHCleanup);
  271. else
  272. CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
  273. M->getType(),
  274. *Destroy, CleanupKind & EHCleanup);
  275. return;
  276. case SD_Dynamic:
  277. llvm_unreachable("temporary cannot have dynamic storage duration");
  278. }
  279. llvm_unreachable("unknown storage duration");
  280. }
  281. }
  282. CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
  283. if (const RecordType *RT =
  284. E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
  285. // Get the destructor for the reference temporary.
  286. auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
  287. if (!ClassDecl->hasTrivialDestructor())
  288. ReferenceTemporaryDtor = ClassDecl->getDestructor();
  289. }
  290. if (!ReferenceTemporaryDtor)
  291. return;
  292. // Call the destructor for the temporary.
  293. switch (M->getStorageDuration()) {
  294. case SD_Static:
  295. case SD_Thread: {
  296. llvm::FunctionCallee CleanupFn;
  297. llvm::Constant *CleanupArg;
  298. if (E->getType()->isArrayType()) {
  299. CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
  300. ReferenceTemporary, E->getType(),
  301. CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
  302. dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
  303. CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
  304. } else {
  305. CleanupFn = CGF.CGM.getAddrAndTypeOfCXXStructor(
  306. GlobalDecl(ReferenceTemporaryDtor, Dtor_Complete));
  307. CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
  308. }
  309. CGF.CGM.getCXXABI().registerGlobalDtor(
  310. CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
  311. break;
  312. }
  313. case SD_FullExpression:
  314. CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
  315. CodeGenFunction::destroyCXXObject,
  316. CGF.getLangOpts().Exceptions);
  317. break;
  318. case SD_Automatic:
  319. CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
  320. ReferenceTemporary, E->getType(),
  321. CodeGenFunction::destroyCXXObject,
  322. CGF.getLangOpts().Exceptions);
  323. break;
  324. case SD_Dynamic:
  325. llvm_unreachable("temporary cannot have dynamic storage duration");
  326. }
  327. }
  328. static Address createReferenceTemporary(CodeGenFunction &CGF,
  329. const MaterializeTemporaryExpr *M,
  330. const Expr *Inner,
  331. Address *Alloca = nullptr) {
  332. auto &TCG = CGF.getTargetHooks();
  333. switch (M->getStorageDuration()) {
  334. case SD_FullExpression:
  335. case SD_Automatic: {
  336. // If we have a constant temporary array or record try to promote it into a
  337. // constant global under the same rules a normal constant would've been
  338. // promoted. This is easier on the optimizer and generally emits fewer
  339. // instructions.
  340. QualType Ty = Inner->getType();
  341. if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
  342. (Ty->isArrayType() || Ty->isRecordType()) &&
  343. CGF.CGM.isTypeConstant(Ty, true))
  344. if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
  345. if (auto AddrSpace = CGF.getTarget().getConstantAddressSpace()) {
  346. auto AS = AddrSpace.getValue();
  347. auto *GV = new llvm::GlobalVariable(
  348. CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
  349. llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
  350. llvm::GlobalValue::NotThreadLocal,
  351. CGF.getContext().getTargetAddressSpace(AS));
  352. CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
  353. GV->setAlignment(alignment.getAsAlign());
  354. llvm::Constant *C = GV;
  355. if (AS != LangAS::Default)
  356. C = TCG.performAddrSpaceCast(
  357. CGF.CGM, GV, AS, LangAS::Default,
  358. GV->getValueType()->getPointerTo(
  359. CGF.getContext().getTargetAddressSpace(LangAS::Default)));
  360. // FIXME: Should we put the new global into a COMDAT?
  361. return Address(C, alignment);
  362. }
  363. }
  364. return CGF.CreateMemTemp(Ty, "ref.tmp", Alloca);
  365. }
  366. case SD_Thread:
  367. case SD_Static:
  368. return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
  369. case SD_Dynamic:
  370. llvm_unreachable("temporary can't have dynamic storage duration");
  371. }
  372. llvm_unreachable("unknown storage duration");
  373. }
  374. LValue CodeGenFunction::
  375. EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
  376. const Expr *E = M->GetTemporaryExpr();
  377. assert((!M->getExtendingDecl() || !isa<VarDecl>(M->getExtendingDecl()) ||
  378. !cast<VarDecl>(M->getExtendingDecl())->isARCPseudoStrong()) &&
  379. "Reference should never be pseudo-strong!");
  380. // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
  381. // as that will cause the lifetime adjustment to be lost for ARC
  382. auto ownership = M->getType().getObjCLifetime();
  383. if (ownership != Qualifiers::OCL_None &&
  384. ownership != Qualifiers::OCL_ExplicitNone) {
  385. Address Object = createReferenceTemporary(*this, M, E);
  386. if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
  387. Object = Address(llvm::ConstantExpr::getBitCast(Var,
  388. ConvertTypeForMem(E->getType())
  389. ->getPointerTo(Object.getAddressSpace())),
  390. Object.getAlignment());
  391. // createReferenceTemporary will promote the temporary to a global with a
  392. // constant initializer if it can. It can only do this to a value of
  393. // ARC-manageable type if the value is global and therefore "immune" to
  394. // ref-counting operations. Therefore we have no need to emit either a
  395. // dynamic initialization or a cleanup and we can just return the address
  396. // of the temporary.
  397. if (Var->hasInitializer())
  398. return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
  399. Var->setInitializer(CGM.EmitNullConstant(E->getType()));
  400. }
  401. LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
  402. AlignmentSource::Decl);
  403. switch (getEvaluationKind(E->getType())) {
  404. default: llvm_unreachable("expected scalar or aggregate expression");
  405. case TEK_Scalar:
  406. EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
  407. break;
  408. case TEK_Aggregate: {
  409. EmitAggExpr(E, AggValueSlot::forAddr(Object,
  410. E->getType().getQualifiers(),
  411. AggValueSlot::IsDestructed,
  412. AggValueSlot::DoesNotNeedGCBarriers,
  413. AggValueSlot::IsNotAliased,
  414. AggValueSlot::DoesNotOverlap));
  415. break;
  416. }
  417. }
  418. pushTemporaryCleanup(*this, M, E, Object);
  419. return RefTempDst;
  420. }
  421. SmallVector<const Expr *, 2> CommaLHSs;
  422. SmallVector<SubobjectAdjustment, 2> Adjustments;
  423. E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  424. for (const auto &Ignored : CommaLHSs)
  425. EmitIgnoredExpr(Ignored);
  426. if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
  427. if (opaque->getType()->isRecordType()) {
  428. assert(Adjustments.empty());
  429. return EmitOpaqueValueLValue(opaque);
  430. }
  431. }
  432. // Create and initialize the reference temporary.
  433. Address Alloca = Address::invalid();
  434. Address Object = createReferenceTemporary(*this, M, E, &Alloca);
  435. if (auto *Var = dyn_cast<llvm::GlobalVariable>(
  436. Object.getPointer()->stripPointerCasts())) {
  437. Object = Address(llvm::ConstantExpr::getBitCast(
  438. cast<llvm::Constant>(Object.getPointer()),
  439. ConvertTypeForMem(E->getType())->getPointerTo()),
  440. Object.getAlignment());
  441. // If the temporary is a global and has a constant initializer or is a
  442. // constant temporary that we promoted to a global, we may have already
  443. // initialized it.
  444. if (!Var->hasInitializer()) {
  445. Var->setInitializer(CGM.EmitNullConstant(E->getType()));
  446. EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
  447. }
  448. } else {
  449. switch (M->getStorageDuration()) {
  450. case SD_Automatic:
  451. if (auto *Size = EmitLifetimeStart(
  452. CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
  453. Alloca.getPointer())) {
  454. pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
  455. Alloca, Size);
  456. }
  457. break;
  458. case SD_FullExpression: {
  459. if (!ShouldEmitLifetimeMarkers)
  460. break;
  461. // Avoid creating a conditional cleanup just to hold an llvm.lifetime.end
  462. // marker. Instead, start the lifetime of a conditional temporary earlier
  463. // so that it's unconditional. Don't do this with sanitizers which need
  464. // more precise lifetime marks.
  465. ConditionalEvaluation *OldConditional = nullptr;
  466. CGBuilderTy::InsertPoint OldIP;
  467. if (isInConditionalBranch() && !E->getType().isDestructedType() &&
  468. !SanOpts.has(SanitizerKind::HWAddress) &&
  469. !SanOpts.has(SanitizerKind::Memory) &&
  470. !CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) {
  471. OldConditional = OutermostConditional;
  472. OutermostConditional = nullptr;
  473. OldIP = Builder.saveIP();
  474. llvm::BasicBlock *Block = OldConditional->getStartingBlock();
  475. Builder.restoreIP(CGBuilderTy::InsertPoint(
  476. Block, llvm::BasicBlock::iterator(Block->back())));
  477. }
  478. if (auto *Size = EmitLifetimeStart(
  479. CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
  480. Alloca.getPointer())) {
  481. pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Alloca,
  482. Size);
  483. }
  484. if (OldConditional) {
  485. OutermostConditional = OldConditional;
  486. Builder.restoreIP(OldIP);
  487. }
  488. break;
  489. }
  490. default:
  491. break;
  492. }
  493. EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
  494. }
  495. pushTemporaryCleanup(*this, M, E, Object);
  496. // Perform derived-to-base casts and/or field accesses, to get from the
  497. // temporary object we created (and, potentially, for which we extended
  498. // the lifetime) to the subobject we're binding the reference to.
  499. for (unsigned I = Adjustments.size(); I != 0; --I) {
  500. SubobjectAdjustment &Adjustment = Adjustments[I-1];
  501. switch (Adjustment.Kind) {
  502. case SubobjectAdjustment::DerivedToBaseAdjustment:
  503. Object =
  504. GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
  505. Adjustment.DerivedToBase.BasePath->path_begin(),
  506. Adjustment.DerivedToBase.BasePath->path_end(),
  507. /*NullCheckValue=*/ false, E->getExprLoc());
  508. break;
  509. case SubobjectAdjustment::FieldAdjustment: {
  510. LValue LV = MakeAddrLValue(Object, E->getType(), AlignmentSource::Decl);
  511. LV = EmitLValueForField(LV, Adjustment.Field);
  512. assert(LV.isSimple() &&
  513. "materialized temporary field is not a simple lvalue");
  514. Object = LV.getAddress();
  515. break;
  516. }
  517. case SubobjectAdjustment::MemberPointerAdjustment: {
  518. llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
  519. Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
  520. Adjustment.Ptr.MPT);
  521. break;
  522. }
  523. }
  524. }
  525. return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
  526. }
  527. RValue
  528. CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
  529. // Emit the expression as an lvalue.
  530. LValue LV = EmitLValue(E);
  531. assert(LV.isSimple());
  532. llvm::Value *Value = LV.getPointer();
  533. if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
  534. // C++11 [dcl.ref]p5 (as amended by core issue 453):
  535. // If a glvalue to which a reference is directly bound designates neither
  536. // an existing object or function of an appropriate type nor a region of
  537. // storage of suitable size and alignment to contain an object of the
  538. // reference's type, the behavior is undefined.
  539. QualType Ty = E->getType();
  540. EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
  541. }
  542. return RValue::get(Value);
  543. }
  544. /// getAccessedFieldNo - Given an encoded value and a result number, return the
  545. /// input field number being accessed.
  546. unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
  547. const llvm::Constant *Elts) {
  548. return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
  549. ->getZExtValue();
  550. }
  551. /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
  552. static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
  553. llvm::Value *High) {
  554. llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
  555. llvm::Value *K47 = Builder.getInt64(47);
  556. llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
  557. llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
  558. llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
  559. llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
  560. return Builder.CreateMul(B1, KMul);
  561. }
  562. bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
  563. return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
  564. TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation;
  565. }
  566. bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
  567. CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
  568. return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
  569. (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
  570. TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
  571. TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation);
  572. }
  573. bool CodeGenFunction::sanitizePerformTypeCheck() const {
  574. return SanOpts.has(SanitizerKind::Null) |
  575. SanOpts.has(SanitizerKind::Alignment) |
  576. SanOpts.has(SanitizerKind::ObjectSize) |
  577. SanOpts.has(SanitizerKind::Vptr);
  578. }
  579. void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
  580. llvm::Value *Ptr, QualType Ty,
  581. CharUnits Alignment,
  582. SanitizerSet SkippedChecks,
  583. llvm::Value *ArraySize) {
  584. if (!sanitizePerformTypeCheck())
  585. return;
  586. // Don't check pointers outside the default address space. The null check
  587. // isn't correct, the object-size check isn't supported by LLVM, and we can't
  588. // communicate the addresses to the runtime handler for the vptr check.
  589. if (Ptr->getType()->getPointerAddressSpace())
  590. return;
  591. // Don't check pointers to volatile data. The behavior here is implementation-
  592. // defined.
  593. if (Ty.isVolatileQualified())
  594. return;
  595. SanitizerScope SanScope(this);
  596. SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
  597. llvm::BasicBlock *Done = nullptr;
  598. // Quickly determine whether we have a pointer to an alloca. It's possible
  599. // to skip null checks, and some alignment checks, for these pointers. This
  600. // can reduce compile-time significantly.
  601. auto PtrToAlloca = dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCasts());
  602. llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
  603. llvm::Value *IsNonNull = nullptr;
  604. bool IsGuaranteedNonNull =
  605. SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
  606. bool AllowNullPointers = isNullPointerAllowed(TCK);
  607. if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
  608. !IsGuaranteedNonNull) {
  609. // The glvalue must not be an empty glvalue.
  610. IsNonNull = Builder.CreateIsNotNull(Ptr);
  611. // The IR builder can constant-fold the null check if the pointer points to
  612. // a constant.
  613. IsGuaranteedNonNull = IsNonNull == True;
  614. // Skip the null check if the pointer is known to be non-null.
  615. if (!IsGuaranteedNonNull) {
  616. if (AllowNullPointers) {
  617. // When performing pointer casts, it's OK if the value is null.
  618. // Skip the remaining checks in that case.
  619. Done = createBasicBlock("null");
  620. llvm::BasicBlock *Rest = createBasicBlock("not.null");
  621. Builder.CreateCondBr(IsNonNull, Rest, Done);
  622. EmitBlock(Rest);
  623. } else {
  624. Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
  625. }
  626. }
  627. }
  628. if (SanOpts.has(SanitizerKind::ObjectSize) &&
  629. !SkippedChecks.has(SanitizerKind::ObjectSize) &&
  630. !Ty->isIncompleteType()) {
  631. uint64_t TySize = getContext().getTypeSizeInChars(Ty).getQuantity();
  632. llvm::Value *Size = llvm::ConstantInt::get(IntPtrTy, TySize);
  633. if (ArraySize)
  634. Size = Builder.CreateMul(Size, ArraySize);
  635. // Degenerate case: new X[0] does not need an objectsize check.
  636. llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Size);
  637. if (!ConstantSize || !ConstantSize->isNullValue()) {
  638. // The glvalue must refer to a large enough storage region.
  639. // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
  640. // to check this.
  641. // FIXME: Get object address space
  642. llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
  643. llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
  644. llvm::Value *Min = Builder.getFalse();
  645. llvm::Value *NullIsUnknown = Builder.getFalse();
  646. llvm::Value *Dynamic = Builder.getFalse();
  647. llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
  648. llvm::Value *LargeEnough = Builder.CreateICmpUGE(
  649. Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown, Dynamic}), Size);
  650. Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
  651. }
  652. }
  653. uint64_t AlignVal = 0;
  654. llvm::Value *PtrAsInt = nullptr;
  655. if (SanOpts.has(SanitizerKind::Alignment) &&
  656. !SkippedChecks.has(SanitizerKind::Alignment)) {
  657. AlignVal = Alignment.getQuantity();
  658. if (!Ty->isIncompleteType() && !AlignVal)
  659. AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
  660. // The glvalue must be suitably aligned.
  661. if (AlignVal > 1 &&
  662. (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
  663. PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
  664. llvm::Value *Align = Builder.CreateAnd(
  665. PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
  666. llvm::Value *Aligned =
  667. Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
  668. if (Aligned != True)
  669. Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
  670. }
  671. }
  672. if (Checks.size() > 0) {
  673. // Make sure we're not losing information. Alignment needs to be a power of
  674. // 2
  675. assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
  676. llvm::Constant *StaticData[] = {
  677. EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
  678. llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
  679. llvm::ConstantInt::get(Int8Ty, TCK)};
  680. EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
  681. PtrAsInt ? PtrAsInt : Ptr);
  682. }
  683. // If possible, check that the vptr indicates that there is a subobject of
  684. // type Ty at offset zero within this object.
  685. //
  686. // C++11 [basic.life]p5,6:
  687. // [For storage which does not refer to an object within its lifetime]
  688. // The program has undefined behavior if:
  689. // -- the [pointer or glvalue] is used to access a non-static data member
  690. // or call a non-static member function
  691. if (SanOpts.has(SanitizerKind::Vptr) &&
  692. !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
  693. // Ensure that the pointer is non-null before loading it. If there is no
  694. // compile-time guarantee, reuse the run-time null check or emit a new one.
  695. if (!IsGuaranteedNonNull) {
  696. if (!IsNonNull)
  697. IsNonNull = Builder.CreateIsNotNull(Ptr);
  698. if (!Done)
  699. Done = createBasicBlock("vptr.null");
  700. llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
  701. Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
  702. EmitBlock(VptrNotNull);
  703. }
  704. // Compute a hash of the mangled name of the type.
  705. //
  706. // FIXME: This is not guaranteed to be deterministic! Move to a
  707. // fingerprinting mechanism once LLVM provides one. For the time
  708. // being the implementation happens to be deterministic.
  709. SmallString<64> MangledName;
  710. llvm::raw_svector_ostream Out(MangledName);
  711. CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
  712. Out);
  713. // Blacklist based on the mangled type.
  714. if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
  715. SanitizerKind::Vptr, Out.str())) {
  716. llvm::hash_code TypeHash = hash_value(Out.str());
  717. // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
  718. llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
  719. llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
  720. Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
  721. llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
  722. llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
  723. llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
  724. Hash = Builder.CreateTrunc(Hash, IntPtrTy);
  725. // Look the hash up in our cache.
  726. const int CacheSize = 128;
  727. llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
  728. llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
  729. "__ubsan_vptr_type_cache");
  730. llvm::Value *Slot = Builder.CreateAnd(Hash,
  731. llvm::ConstantInt::get(IntPtrTy,
  732. CacheSize-1));
  733. llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
  734. llvm::Value *CacheVal =
  735. Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
  736. getPointerAlign());
  737. // If the hash isn't in the cache, call a runtime handler to perform the
  738. // hard work of checking whether the vptr is for an object of the right
  739. // type. This will either fill in the cache and return, or produce a
  740. // diagnostic.
  741. llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
  742. llvm::Constant *StaticData[] = {
  743. EmitCheckSourceLocation(Loc),
  744. EmitCheckTypeDescriptor(Ty),
  745. CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
  746. llvm::ConstantInt::get(Int8Ty, TCK)
  747. };
  748. llvm::Value *DynamicData[] = { Ptr, Hash };
  749. EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
  750. SanitizerHandler::DynamicTypeCacheMiss, StaticData,
  751. DynamicData);
  752. }
  753. }
  754. if (Done) {
  755. Builder.CreateBr(Done);
  756. EmitBlock(Done);
  757. }
  758. }
  759. /// Determine whether this expression refers to a flexible array member in a
  760. /// struct. We disable array bounds checks for such members.
  761. static bool isFlexibleArrayMemberExpr(const Expr *E) {
  762. // For compatibility with existing code, we treat arrays of length 0 or
  763. // 1 as flexible array members.
  764. const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
  765. if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  766. if (CAT->getSize().ugt(1))
  767. return false;
  768. } else if (!isa<IncompleteArrayType>(AT))
  769. return false;
  770. E = E->IgnoreParens();
  771. // A flexible array member must be the last member in the class.
  772. if (const auto *ME = dyn_cast<MemberExpr>(E)) {
  773. // FIXME: If the base type of the member expr is not FD->getParent(),
  774. // this should not be treated as a flexible array member access.
  775. if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
  776. RecordDecl::field_iterator FI(
  777. DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
  778. return ++FI == FD->getParent()->field_end();
  779. }
  780. } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
  781. return IRE->getDecl()->getNextIvar() == nullptr;
  782. }
  783. return false;
  784. }
  785. llvm::Value *CodeGenFunction::LoadPassedObjectSize(const Expr *E,
  786. QualType EltTy) {
  787. ASTContext &C = getContext();
  788. uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
  789. if (!EltSize)
  790. return nullptr;
  791. auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
  792. if (!ArrayDeclRef)
  793. return nullptr;
  794. auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
  795. if (!ParamDecl)
  796. return nullptr;
  797. auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
  798. if (!POSAttr)
  799. return nullptr;
  800. // Don't load the size if it's a lower bound.
  801. int POSType = POSAttr->getType();
  802. if (POSType != 0 && POSType != 1)
  803. return nullptr;
  804. // Find the implicit size parameter.
  805. auto PassedSizeIt = SizeArguments.find(ParamDecl);
  806. if (PassedSizeIt == SizeArguments.end())
  807. return nullptr;
  808. const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
  809. assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
  810. Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
  811. llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
  812. C.getSizeType(), E->getExprLoc());
  813. llvm::Value *SizeOfElement =
  814. llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
  815. return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
  816. }
  817. /// If Base is known to point to the start of an array, return the length of
  818. /// that array. Return 0 if the length cannot be determined.
  819. static llvm::Value *getArrayIndexingBound(
  820. CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
  821. // For the vector indexing extension, the bound is the number of elements.
  822. if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
  823. IndexedType = Base->getType();
  824. return CGF.Builder.getInt32(VT->getNumElements());
  825. }
  826. Base = Base->IgnoreParens();
  827. if (const auto *CE = dyn_cast<CastExpr>(Base)) {
  828. if (CE->getCastKind() == CK_ArrayToPointerDecay &&
  829. !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
  830. IndexedType = CE->getSubExpr()->getType();
  831. const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
  832. if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
  833. return CGF.Builder.getInt(CAT->getSize());
  834. else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
  835. return CGF.getVLASize(VAT).NumElts;
  836. // Ignore pass_object_size here. It's not applicable on decayed pointers.
  837. }
  838. }
  839. QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
  840. if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
  841. IndexedType = Base->getType();
  842. return POS;
  843. }
  844. return nullptr;
  845. }
  846. void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
  847. llvm::Value *Index, QualType IndexType,
  848. bool Accessed) {
  849. assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
  850. "should not be called unless adding bounds checks");
  851. SanitizerScope SanScope(this);
  852. QualType IndexedType;
  853. llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
  854. if (!Bound)
  855. return;
  856. bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
  857. llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
  858. llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
  859. llvm::Constant *StaticData[] = {
  860. EmitCheckSourceLocation(E->getExprLoc()),
  861. EmitCheckTypeDescriptor(IndexedType),
  862. EmitCheckTypeDescriptor(IndexType)
  863. };
  864. llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
  865. : Builder.CreateICmpULE(IndexVal, BoundVal);
  866. EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
  867. SanitizerHandler::OutOfBounds, StaticData, Index);
  868. }
  869. CodeGenFunction::ComplexPairTy CodeGenFunction::
  870. EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
  871. bool isInc, bool isPre) {
  872. ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
  873. llvm::Value *NextVal;
  874. if (isa<llvm::IntegerType>(InVal.first->getType())) {
  875. uint64_t AmountVal = isInc ? 1 : -1;
  876. NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
  877. // Add the inc/dec to the real part.
  878. NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
  879. } else {
  880. QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
  881. llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
  882. if (!isInc)
  883. FVal.changeSign();
  884. NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
  885. // Add the inc/dec to the real part.
  886. NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
  887. }
  888. ComplexPairTy IncVal(NextVal, InVal.second);
  889. // Store the updated result through the lvalue.
  890. EmitStoreOfComplex(IncVal, LV, /*init*/ false);
  891. // If this is a postinc, return the value read from memory, otherwise use the
  892. // updated value.
  893. return isPre ? IncVal : InVal;
  894. }
  895. void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
  896. CodeGenFunction *CGF) {
  897. // Bind VLAs in the cast type.
  898. if (CGF && E->getType()->isVariablyModifiedType())
  899. CGF->EmitVariablyModifiedType(E->getType());
  900. if (CGDebugInfo *DI = getModuleDebugInfo())
  901. DI->EmitExplicitCastType(E->getType());
  902. }
  903. //===----------------------------------------------------------------------===//
  904. // LValue Expression Emission
  905. //===----------------------------------------------------------------------===//
  906. /// EmitPointerWithAlignment - Given an expression of pointer type, try to
  907. /// derive a more accurate bound on the alignment of the pointer.
  908. Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
  909. LValueBaseInfo *BaseInfo,
  910. TBAAAccessInfo *TBAAInfo) {
  911. // We allow this with ObjC object pointers because of fragile ABIs.
  912. assert(E->getType()->isPointerType() ||
  913. E->getType()->isObjCObjectPointerType());
  914. E = E->IgnoreParens();
  915. // Casts:
  916. if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
  917. if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
  918. CGM.EmitExplicitCastExprType(ECE, this);
  919. switch (CE->getCastKind()) {
  920. // Non-converting casts (but not C's implicit conversion from void*).
  921. case CK_BitCast:
  922. case CK_NoOp:
  923. case CK_AddressSpaceConversion:
  924. if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
  925. if (PtrTy->getPointeeType()->isVoidType())
  926. break;
  927. LValueBaseInfo InnerBaseInfo;
  928. TBAAAccessInfo InnerTBAAInfo;
  929. Address Addr = EmitPointerWithAlignment(CE->getSubExpr(),
  930. &InnerBaseInfo,
  931. &InnerTBAAInfo);
  932. if (BaseInfo) *BaseInfo = InnerBaseInfo;
  933. if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
  934. if (isa<ExplicitCastExpr>(CE)) {
  935. LValueBaseInfo TargetTypeBaseInfo;
  936. TBAAAccessInfo TargetTypeTBAAInfo;
  937. CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
  938. &TargetTypeBaseInfo,
  939. &TargetTypeTBAAInfo);
  940. if (TBAAInfo)
  941. *TBAAInfo = CGM.mergeTBAAInfoForCast(*TBAAInfo,
  942. TargetTypeTBAAInfo);
  943. // If the source l-value is opaque, honor the alignment of the
  944. // casted-to type.
  945. if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
  946. if (BaseInfo)
  947. BaseInfo->mergeForCast(TargetTypeBaseInfo);
  948. Addr = Address(Addr.getPointer(), Align);
  949. }
  950. }
  951. if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
  952. CE->getCastKind() == CK_BitCast) {
  953. if (auto PT = E->getType()->getAs<PointerType>())
  954. EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
  955. /*MayBeNull=*/true,
  956. CodeGenFunction::CFITCK_UnrelatedCast,
  957. CE->getBeginLoc());
  958. }
  959. return CE->getCastKind() != CK_AddressSpaceConversion
  960. ? Builder.CreateBitCast(Addr, ConvertType(E->getType()))
  961. : Builder.CreateAddrSpaceCast(Addr,
  962. ConvertType(E->getType()));
  963. }
  964. break;
  965. // Array-to-pointer decay.
  966. case CK_ArrayToPointerDecay:
  967. return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
  968. // Derived-to-base conversions.
  969. case CK_UncheckedDerivedToBase:
  970. case CK_DerivedToBase: {
  971. // TODO: Support accesses to members of base classes in TBAA. For now, we
  972. // conservatively pretend that the complete object is of the base class
  973. // type.
  974. if (TBAAInfo)
  975. *TBAAInfo = CGM.getTBAAAccessInfo(E->getType());
  976. Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
  977. auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
  978. return GetAddressOfBaseClass(Addr, Derived,
  979. CE->path_begin(), CE->path_end(),
  980. ShouldNullCheckClassCastValue(CE),
  981. CE->getExprLoc());
  982. }
  983. // TODO: Is there any reason to treat base-to-derived conversions
  984. // specially?
  985. default:
  986. break;
  987. }
  988. }
  989. // Unary &.
  990. if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  991. if (UO->getOpcode() == UO_AddrOf) {
  992. LValue LV = EmitLValue(UO->getSubExpr());
  993. if (BaseInfo) *BaseInfo = LV.getBaseInfo();
  994. if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
  995. return LV.getAddress();
  996. }
  997. }
  998. // TODO: conditional operators, comma.
  999. // Otherwise, use the alignment of the type.
  1000. CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo,
  1001. TBAAInfo);
  1002. return Address(EmitScalarExpr(E), Align);
  1003. }
  1004. RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
  1005. if (Ty->isVoidType())
  1006. return RValue::get(nullptr);
  1007. switch (getEvaluationKind(Ty)) {
  1008. case TEK_Complex: {
  1009. llvm::Type *EltTy =
  1010. ConvertType(Ty->castAs<ComplexType>()->getElementType());
  1011. llvm::Value *U = llvm::UndefValue::get(EltTy);
  1012. return RValue::getComplex(std::make_pair(U, U));
  1013. }
  1014. // If this is a use of an undefined aggregate type, the aggregate must have an
  1015. // identifiable address. Just because the contents of the value are undefined
  1016. // doesn't mean that the address can't be taken and compared.
  1017. case TEK_Aggregate: {
  1018. Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
  1019. return RValue::getAggregate(DestPtr);
  1020. }
  1021. case TEK_Scalar:
  1022. return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
  1023. }
  1024. llvm_unreachable("bad evaluation kind");
  1025. }
  1026. RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
  1027. const char *Name) {
  1028. ErrorUnsupported(E, Name);
  1029. return GetUndefRValue(E->getType());
  1030. }
  1031. LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
  1032. const char *Name) {
  1033. ErrorUnsupported(E, Name);
  1034. llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
  1035. return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
  1036. E->getType());
  1037. }
  1038. bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
  1039. const Expr *Base = Obj;
  1040. while (!isa<CXXThisExpr>(Base)) {
  1041. // The result of a dynamic_cast can be null.
  1042. if (isa<CXXDynamicCastExpr>(Base))
  1043. return false;
  1044. if (const auto *CE = dyn_cast<CastExpr>(Base)) {
  1045. Base = CE->getSubExpr();
  1046. } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
  1047. Base = PE->getSubExpr();
  1048. } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
  1049. if (UO->getOpcode() == UO_Extension)
  1050. Base = UO->getSubExpr();
  1051. else
  1052. return false;
  1053. } else {
  1054. return false;
  1055. }
  1056. }
  1057. return true;
  1058. }
  1059. LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
  1060. LValue LV;
  1061. if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
  1062. LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
  1063. else
  1064. LV = EmitLValue(E);
  1065. if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
  1066. SanitizerSet SkippedChecks;
  1067. if (const auto *ME = dyn_cast<MemberExpr>(E)) {
  1068. bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
  1069. if (IsBaseCXXThis)
  1070. SkippedChecks.set(SanitizerKind::Alignment, true);
  1071. if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
  1072. SkippedChecks.set(SanitizerKind::Null, true);
  1073. }
  1074. EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
  1075. E->getType(), LV.getAlignment(), SkippedChecks);
  1076. }
  1077. return LV;
  1078. }
  1079. /// EmitLValue - Emit code to compute a designator that specifies the location
  1080. /// of the expression.
  1081. ///
  1082. /// This can return one of two things: a simple address or a bitfield reference.
  1083. /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
  1084. /// an LLVM pointer type.
  1085. ///
  1086. /// If this returns a bitfield reference, nothing about the pointee type of the
  1087. /// LLVM value is known: For example, it may not be a pointer to an integer.
  1088. ///
  1089. /// If this returns a normal address, and if the lvalue's C type is fixed size,
  1090. /// this method guarantees that the returned pointer type will point to an LLVM
  1091. /// type of the same size of the lvalue's type. If the lvalue has a variable
  1092. /// length type, this is not possible.
  1093. ///
  1094. LValue CodeGenFunction::EmitLValue(const Expr *E) {
  1095. ApplyDebugLocation DL(*this, E);
  1096. switch (E->getStmtClass()) {
  1097. default: return EmitUnsupportedLValue(E, "l-value expression");
  1098. case Expr::ObjCPropertyRefExprClass:
  1099. llvm_unreachable("cannot emit a property reference directly");
  1100. case Expr::ObjCSelectorExprClass:
  1101. return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
  1102. case Expr::ObjCIsaExprClass:
  1103. return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
  1104. case Expr::BinaryOperatorClass:
  1105. return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
  1106. case Expr::CompoundAssignOperatorClass: {
  1107. QualType Ty = E->getType();
  1108. if (const AtomicType *AT = Ty->getAs<AtomicType>())
  1109. Ty = AT->getValueType();
  1110. if (!Ty->isAnyComplexType())
  1111. return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
  1112. return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
  1113. }
  1114. case Expr::CallExprClass:
  1115. case Expr::CXXMemberCallExprClass:
  1116. case Expr::CXXOperatorCallExprClass:
  1117. case Expr::UserDefinedLiteralClass:
  1118. return EmitCallExprLValue(cast<CallExpr>(E));
  1119. case Expr::VAArgExprClass:
  1120. return EmitVAArgExprLValue(cast<VAArgExpr>(E));
  1121. case Expr::DeclRefExprClass:
  1122. return EmitDeclRefLValue(cast<DeclRefExpr>(E));
  1123. case Expr::ConstantExprClass:
  1124. return EmitLValue(cast<ConstantExpr>(E)->getSubExpr());
  1125. case Expr::ParenExprClass:
  1126. return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
  1127. case Expr::GenericSelectionExprClass:
  1128. return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
  1129. case Expr::PredefinedExprClass:
  1130. return EmitPredefinedLValue(cast<PredefinedExpr>(E));
  1131. case Expr::StringLiteralClass:
  1132. return EmitStringLiteralLValue(cast<StringLiteral>(E));
  1133. case Expr::ObjCEncodeExprClass:
  1134. return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
  1135. case Expr::PseudoObjectExprClass:
  1136. return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
  1137. case Expr::InitListExprClass:
  1138. return EmitInitListLValue(cast<InitListExpr>(E));
  1139. case Expr::CXXTemporaryObjectExprClass:
  1140. case Expr::CXXConstructExprClass:
  1141. return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
  1142. case Expr::CXXBindTemporaryExprClass:
  1143. return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
  1144. case Expr::CXXUuidofExprClass:
  1145. return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
  1146. case Expr::LambdaExprClass:
  1147. return EmitAggExprToLValue(E);
  1148. case Expr::ExprWithCleanupsClass: {
  1149. const auto *cleanups = cast<ExprWithCleanups>(E);
  1150. enterFullExpression(cleanups);
  1151. RunCleanupsScope Scope(*this);
  1152. LValue LV = EmitLValue(cleanups->getSubExpr());
  1153. if (LV.isSimple()) {
  1154. // Defend against branches out of gnu statement expressions surrounded by
  1155. // cleanups.
  1156. llvm::Value *V = LV.getPointer();
  1157. Scope.ForceCleanup({&V});
  1158. return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
  1159. getContext(), LV.getBaseInfo(), LV.getTBAAInfo());
  1160. }
  1161. // FIXME: Is it possible to create an ExprWithCleanups that produces a
  1162. // bitfield lvalue or some other non-simple lvalue?
  1163. return LV;
  1164. }
  1165. case Expr::CXXDefaultArgExprClass: {
  1166. auto *DAE = cast<CXXDefaultArgExpr>(E);
  1167. CXXDefaultArgExprScope Scope(*this, DAE);
  1168. return EmitLValue(DAE->getExpr());
  1169. }
  1170. case Expr::CXXDefaultInitExprClass: {
  1171. auto *DIE = cast<CXXDefaultInitExpr>(E);
  1172. CXXDefaultInitExprScope Scope(*this, DIE);
  1173. return EmitLValue(DIE->getExpr());
  1174. }
  1175. case Expr::CXXTypeidExprClass:
  1176. return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
  1177. case Expr::ObjCMessageExprClass:
  1178. return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
  1179. case Expr::ObjCIvarRefExprClass:
  1180. return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
  1181. case Expr::StmtExprClass:
  1182. return EmitStmtExprLValue(cast<StmtExpr>(E));
  1183. case Expr::UnaryOperatorClass:
  1184. return EmitUnaryOpLValue(cast<UnaryOperator>(E));
  1185. case Expr::ArraySubscriptExprClass:
  1186. return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
  1187. case Expr::OMPArraySectionExprClass:
  1188. return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
  1189. case Expr::ExtVectorElementExprClass:
  1190. return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
  1191. case Expr::MemberExprClass:
  1192. return EmitMemberExpr(cast<MemberExpr>(E));
  1193. case Expr::CompoundLiteralExprClass:
  1194. return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
  1195. case Expr::ConditionalOperatorClass:
  1196. return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
  1197. case Expr::BinaryConditionalOperatorClass:
  1198. return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
  1199. case Expr::ChooseExprClass:
  1200. return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
  1201. case Expr::OpaqueValueExprClass:
  1202. return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
  1203. case Expr::SubstNonTypeTemplateParmExprClass:
  1204. return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
  1205. case Expr::ImplicitCastExprClass:
  1206. case Expr::CStyleCastExprClass:
  1207. case Expr::CXXFunctionalCastExprClass:
  1208. case Expr::CXXStaticCastExprClass:
  1209. case Expr::CXXDynamicCastExprClass:
  1210. case Expr::CXXReinterpretCastExprClass:
  1211. case Expr::CXXConstCastExprClass:
  1212. case Expr::ObjCBridgedCastExprClass:
  1213. return EmitCastLValue(cast<CastExpr>(E));
  1214. case Expr::MaterializeTemporaryExprClass:
  1215. return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
  1216. case Expr::CoawaitExprClass:
  1217. return EmitCoawaitLValue(cast<CoawaitExpr>(E));
  1218. case Expr::CoyieldExprClass:
  1219. return EmitCoyieldLValue(cast<CoyieldExpr>(E));
  1220. }
  1221. }
  1222. /// Given an object of the given canonical type, can we safely copy a
  1223. /// value out of it based on its initializer?
  1224. static bool isConstantEmittableObjectType(QualType type) {
  1225. assert(type.isCanonical());
  1226. assert(!type->isReferenceType());
  1227. // Must be const-qualified but non-volatile.
  1228. Qualifiers qs = type.getLocalQualifiers();
  1229. if (!qs.hasConst() || qs.hasVolatile()) return false;
  1230. // Otherwise, all object types satisfy this except C++ classes with
  1231. // mutable subobjects or non-trivial copy/destroy behavior.
  1232. if (const auto *RT = dyn_cast<RecordType>(type))
  1233. if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  1234. if (RD->hasMutableFields() || !RD->isTrivial())
  1235. return false;
  1236. return true;
  1237. }
  1238. /// Can we constant-emit a load of a reference to a variable of the
  1239. /// given type? This is different from predicates like
  1240. /// Decl::mightBeUsableInConstantExpressions because we do want it to apply
  1241. /// in situations that don't necessarily satisfy the language's rules
  1242. /// for this (e.g. C++'s ODR-use rules). For example, we want to able
  1243. /// to do this with const float variables even if those variables
  1244. /// aren't marked 'constexpr'.
  1245. enum ConstantEmissionKind {
  1246. CEK_None,
  1247. CEK_AsReferenceOnly,
  1248. CEK_AsValueOrReference,
  1249. CEK_AsValueOnly
  1250. };
  1251. static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
  1252. type = type.getCanonicalType();
  1253. if (const auto *ref = dyn_cast<ReferenceType>(type)) {
  1254. if (isConstantEmittableObjectType(ref->getPointeeType()))
  1255. return CEK_AsValueOrReference;
  1256. return CEK_AsReferenceOnly;
  1257. }
  1258. if (isConstantEmittableObjectType(type))
  1259. return CEK_AsValueOnly;
  1260. return CEK_None;
  1261. }
  1262. /// Try to emit a reference to the given value without producing it as
  1263. /// an l-value. This is just an optimization, but it avoids us needing
  1264. /// to emit global copies of variables if they're named without triggering
  1265. /// a formal use in a context where we can't emit a direct reference to them,
  1266. /// for instance if a block or lambda or a member of a local class uses a
  1267. /// const int variable or constexpr variable from an enclosing function.
  1268. CodeGenFunction::ConstantEmission
  1269. CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
  1270. ValueDecl *value = refExpr->getDecl();
  1271. // The value needs to be an enum constant or a constant variable.
  1272. ConstantEmissionKind CEK;
  1273. if (isa<ParmVarDecl>(value)) {
  1274. CEK = CEK_None;
  1275. } else if (auto *var = dyn_cast<VarDecl>(value)) {
  1276. CEK = checkVarTypeForConstantEmission(var->getType());
  1277. } else if (isa<EnumConstantDecl>(value)) {
  1278. CEK = CEK_AsValueOnly;
  1279. } else {
  1280. CEK = CEK_None;
  1281. }
  1282. if (CEK == CEK_None) return ConstantEmission();
  1283. Expr::EvalResult result;
  1284. bool resultIsReference;
  1285. QualType resultType;
  1286. // It's best to evaluate all the way as an r-value if that's permitted.
  1287. if (CEK != CEK_AsReferenceOnly &&
  1288. refExpr->EvaluateAsRValue(result, getContext())) {
  1289. resultIsReference = false;
  1290. resultType = refExpr->getType();
  1291. // Otherwise, try to evaluate as an l-value.
  1292. } else if (CEK != CEK_AsValueOnly &&
  1293. refExpr->EvaluateAsLValue(result, getContext())) {
  1294. resultIsReference = true;
  1295. resultType = value->getType();
  1296. // Failure.
  1297. } else {
  1298. return ConstantEmission();
  1299. }
  1300. // In any case, if the initializer has side-effects, abandon ship.
  1301. if (result.HasSideEffects)
  1302. return ConstantEmission();
  1303. // Emit as a constant.
  1304. auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
  1305. result.Val, resultType);
  1306. // Make sure we emit a debug reference to the global variable.
  1307. // This should probably fire even for
  1308. if (isa<VarDecl>(value)) {
  1309. if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
  1310. EmitDeclRefExprDbgValue(refExpr, result.Val);
  1311. } else {
  1312. assert(isa<EnumConstantDecl>(value));
  1313. EmitDeclRefExprDbgValue(refExpr, result.Val);
  1314. }
  1315. // If we emitted a reference constant, we need to dereference that.
  1316. if (resultIsReference)
  1317. return ConstantEmission::forReference(C);
  1318. return ConstantEmission::forValue(C);
  1319. }
  1320. static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
  1321. const MemberExpr *ME) {
  1322. if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
  1323. // Try to emit static variable member expressions as DREs.
  1324. return DeclRefExpr::Create(
  1325. CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
  1326. /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
  1327. ME->getType(), ME->getValueKind(), nullptr, nullptr, ME->isNonOdrUse());
  1328. }
  1329. return nullptr;
  1330. }
  1331. CodeGenFunction::ConstantEmission
  1332. CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
  1333. if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
  1334. return tryEmitAsConstant(DRE);
  1335. return ConstantEmission();
  1336. }
  1337. llvm::Value *CodeGenFunction::emitScalarConstant(
  1338. const CodeGenFunction::ConstantEmission &Constant, Expr *E) {
  1339. assert(Constant && "not a constant");
  1340. if (Constant.isReference())
  1341. return EmitLoadOfLValue(Constant.getReferenceLValue(*this, E),
  1342. E->getExprLoc())
  1343. .getScalarVal();
  1344. return Constant.getValue();
  1345. }
  1346. llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
  1347. SourceLocation Loc) {
  1348. return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
  1349. lvalue.getType(), Loc, lvalue.getBaseInfo(),
  1350. lvalue.getTBAAInfo(), lvalue.isNontemporal());
  1351. }
  1352. static bool hasBooleanRepresentation(QualType Ty) {
  1353. if (Ty->isBooleanType())
  1354. return true;
  1355. if (const EnumType *ET = Ty->getAs<EnumType>())
  1356. return ET->getDecl()->getIntegerType()->isBooleanType();
  1357. if (const AtomicType *AT = Ty->getAs<AtomicType>())
  1358. return hasBooleanRepresentation(AT->getValueType());
  1359. return false;
  1360. }
  1361. static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
  1362. llvm::APInt &Min, llvm::APInt &End,
  1363. bool StrictEnums, bool IsBool) {
  1364. const EnumType *ET = Ty->getAs<EnumType>();
  1365. bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
  1366. ET && !ET->getDecl()->isFixed();
  1367. if (!IsBool && !IsRegularCPlusPlusEnum)
  1368. return false;
  1369. if (IsBool) {
  1370. Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
  1371. End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
  1372. } else {
  1373. const EnumDecl *ED = ET->getDecl();
  1374. llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
  1375. unsigned Bitwidth = LTy->getScalarSizeInBits();
  1376. unsigned NumNegativeBits = ED->getNumNegativeBits();
  1377. unsigned NumPositiveBits = ED->getNumPositiveBits();
  1378. if (NumNegativeBits) {
  1379. unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
  1380. assert(NumBits <= Bitwidth);
  1381. End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
  1382. Min = -End;
  1383. } else {
  1384. assert(NumPositiveBits <= Bitwidth);
  1385. End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
  1386. Min = llvm::APInt(Bitwidth, 0);
  1387. }
  1388. }
  1389. return true;
  1390. }
  1391. llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
  1392. llvm::APInt Min, End;
  1393. if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
  1394. hasBooleanRepresentation(Ty)))
  1395. return nullptr;
  1396. llvm::MDBuilder MDHelper(getLLVMContext());
  1397. return MDHelper.createRange(Min, End);
  1398. }
  1399. bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
  1400. SourceLocation Loc) {
  1401. bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
  1402. bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
  1403. if (!HasBoolCheck && !HasEnumCheck)
  1404. return false;
  1405. bool IsBool = hasBooleanRepresentation(Ty) ||
  1406. NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
  1407. bool NeedsBoolCheck = HasBoolCheck && IsBool;
  1408. bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
  1409. if (!NeedsBoolCheck && !NeedsEnumCheck)
  1410. return false;
  1411. // Single-bit booleans don't need to be checked. Special-case this to avoid
  1412. // a bit width mismatch when handling bitfield values. This is handled by
  1413. // EmitFromMemory for the non-bitfield case.
  1414. if (IsBool &&
  1415. cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
  1416. return false;
  1417. llvm::APInt Min, End;
  1418. if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
  1419. return true;
  1420. auto &Ctx = getLLVMContext();
  1421. SanitizerScope SanScope(this);
  1422. llvm::Value *Check;
  1423. --End;
  1424. if (!Min) {
  1425. Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
  1426. } else {
  1427. llvm::Value *Upper =
  1428. Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
  1429. llvm::Value *Lower =
  1430. Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
  1431. Check = Builder.CreateAnd(Upper, Lower);
  1432. }
  1433. llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
  1434. EmitCheckTypeDescriptor(Ty)};
  1435. SanitizerMask Kind =
  1436. NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
  1437. EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
  1438. StaticArgs, EmitCheckValue(Value));
  1439. return true;
  1440. }
  1441. llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
  1442. QualType Ty,
  1443. SourceLocation Loc,
  1444. LValueBaseInfo BaseInfo,
  1445. TBAAAccessInfo TBAAInfo,
  1446. bool isNontemporal) {
  1447. if (!CGM.getCodeGenOpts().PreserveVec3Type) {
  1448. // For better performance, handle vector loads differently.
  1449. if (Ty->isVectorType()) {
  1450. const llvm::Type *EltTy = Addr.getElementType();
  1451. const auto *VTy = cast<llvm::VectorType>(EltTy);
  1452. // Handle vectors of size 3 like size 4 for better performance.
  1453. if (VTy->getNumElements() == 3) {
  1454. // Bitcast to vec4 type.
  1455. llvm::VectorType *vec4Ty =
  1456. llvm::VectorType::get(VTy->getElementType(), 4);
  1457. Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
  1458. // Now load value.
  1459. llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
  1460. // Shuffle vector to get vec3.
  1461. V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
  1462. {0, 1, 2}, "extractVec");
  1463. return EmitFromMemory(V, Ty);
  1464. }
  1465. }
  1466. }
  1467. // Atomic operations have to be done on integral types.
  1468. LValue AtomicLValue =
  1469. LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
  1470. if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
  1471. return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
  1472. }
  1473. llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
  1474. if (isNontemporal) {
  1475. llvm::MDNode *Node = llvm::MDNode::get(
  1476. Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
  1477. Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
  1478. }
  1479. CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
  1480. if (EmitScalarRangeCheck(Load, Ty, Loc)) {
  1481. // In order to prevent the optimizer from throwing away the check, don't
  1482. // attach range metadata to the load.
  1483. } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
  1484. if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
  1485. Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
  1486. return EmitFromMemory(Load, Ty);
  1487. }
  1488. llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
  1489. // Bool has a different representation in memory than in registers.
  1490. if (hasBooleanRepresentation(Ty)) {
  1491. // This should really always be an i1, but sometimes it's already
  1492. // an i8, and it's awkward to track those cases down.
  1493. if (Value->getType()->isIntegerTy(1))
  1494. return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
  1495. assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
  1496. "wrong value rep of bool");
  1497. }
  1498. return Value;
  1499. }
  1500. llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
  1501. // Bool has a different representation in memory than in registers.
  1502. if (hasBooleanRepresentation(Ty)) {
  1503. assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
  1504. "wrong value rep of bool");
  1505. return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
  1506. }
  1507. return Value;
  1508. }
  1509. void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
  1510. bool Volatile, QualType Ty,
  1511. LValueBaseInfo BaseInfo,
  1512. TBAAAccessInfo TBAAInfo,
  1513. bool isInit, bool isNontemporal) {
  1514. if (!CGM.getCodeGenOpts().PreserveVec3Type) {
  1515. // Handle vectors differently to get better performance.
  1516. if (Ty->isVectorType()) {
  1517. llvm::Type *SrcTy = Value->getType();
  1518. auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
  1519. // Handle vec3 special.
  1520. if (VecTy && VecTy->getNumElements() == 3) {
  1521. // Our source is a vec3, do a shuffle vector to make it a vec4.
  1522. llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
  1523. Builder.getInt32(2),
  1524. llvm::UndefValue::get(Builder.getInt32Ty())};
  1525. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1526. Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
  1527. MaskV, "extractVec");
  1528. SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
  1529. }
  1530. if (Addr.getElementType() != SrcTy) {
  1531. Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
  1532. }
  1533. }
  1534. }
  1535. Value = EmitToMemory(Value, Ty);
  1536. LValue AtomicLValue =
  1537. LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
  1538. if (Ty->isAtomicType() ||
  1539. (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
  1540. EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
  1541. return;
  1542. }
  1543. llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
  1544. if (isNontemporal) {
  1545. llvm::MDNode *Node =
  1546. llvm::MDNode::get(Store->getContext(),
  1547. llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
  1548. Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
  1549. }
  1550. CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
  1551. }
  1552. void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
  1553. bool isInit) {
  1554. EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
  1555. lvalue.getType(), lvalue.getBaseInfo(),
  1556. lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
  1557. }
  1558. /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
  1559. /// method emits the address of the lvalue, then loads the result as an rvalue,
  1560. /// returning the rvalue.
  1561. RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
  1562. if (LV.isObjCWeak()) {
  1563. // load of a __weak object.
  1564. Address AddrWeakObj = LV.getAddress();
  1565. return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
  1566. AddrWeakObj));
  1567. }
  1568. if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
  1569. // In MRC mode, we do a load+autorelease.
  1570. if (!getLangOpts().ObjCAutoRefCount) {
  1571. return RValue::get(EmitARCLoadWeak(LV.getAddress()));
  1572. }
  1573. // In ARC mode, we load retained and then consume the value.
  1574. llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
  1575. Object = EmitObjCConsumeObject(LV.getType(), Object);
  1576. return RValue::get(Object);
  1577. }
  1578. if (LV.isSimple()) {
  1579. assert(!LV.getType()->isFunctionType());
  1580. // Everything needs a load.
  1581. return RValue::get(EmitLoadOfScalar(LV, Loc));
  1582. }
  1583. if (LV.isVectorElt()) {
  1584. llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
  1585. LV.isVolatileQualified());
  1586. return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
  1587. "vecext"));
  1588. }
  1589. // If this is a reference to a subset of the elements of a vector, either
  1590. // shuffle the input or extract/insert them as appropriate.
  1591. if (LV.isExtVectorElt())
  1592. return EmitLoadOfExtVectorElementLValue(LV);
  1593. // Global Register variables always invoke intrinsics
  1594. if (LV.isGlobalReg())
  1595. return EmitLoadOfGlobalRegLValue(LV);
  1596. assert(LV.isBitField() && "Unknown LValue type!");
  1597. return EmitLoadOfBitfieldLValue(LV, Loc);
  1598. }
  1599. RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
  1600. SourceLocation Loc) {
  1601. const CGBitFieldInfo &Info = LV.getBitFieldInfo();
  1602. // Get the output type.
  1603. llvm::Type *ResLTy = ConvertType(LV.getType());
  1604. Address Ptr = LV.getBitFieldAddress();
  1605. llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
  1606. if (Info.IsSigned) {
  1607. assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
  1608. unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
  1609. if (HighBits)
  1610. Val = Builder.CreateShl(Val, HighBits, "bf.shl");
  1611. if (Info.Offset + HighBits)
  1612. Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
  1613. } else {
  1614. if (Info.Offset)
  1615. Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
  1616. if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
  1617. Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
  1618. Info.Size),
  1619. "bf.clear");
  1620. }
  1621. Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
  1622. EmitScalarRangeCheck(Val, LV.getType(), Loc);
  1623. return RValue::get(Val);
  1624. }
  1625. // If this is a reference to a subset of the elements of a vector, create an
  1626. // appropriate shufflevector.
  1627. RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
  1628. llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
  1629. LV.isVolatileQualified());
  1630. const llvm::Constant *Elts = LV.getExtVectorElts();
  1631. // If the result of the expression is a non-vector type, we must be extracting
  1632. // a single element. Just codegen as an extractelement.
  1633. const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
  1634. if (!ExprVT) {
  1635. unsigned InIdx = getAccessedFieldNo(0, Elts);
  1636. llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
  1637. return RValue::get(Builder.CreateExtractElement(Vec, Elt));
  1638. }
  1639. // Always use shuffle vector to try to retain the original program structure
  1640. unsigned NumResultElts = ExprVT->getNumElements();
  1641. SmallVector<llvm::Constant*, 4> Mask;
  1642. for (unsigned i = 0; i != NumResultElts; ++i)
  1643. Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
  1644. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1645. Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
  1646. MaskV);
  1647. return RValue::get(Vec);
  1648. }
  1649. /// Generates lvalue for partial ext_vector access.
  1650. Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
  1651. Address VectorAddress = LV.getExtVectorAddress();
  1652. const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
  1653. QualType EQT = ExprVT->getElementType();
  1654. llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
  1655. Address CastToPointerElement =
  1656. Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
  1657. "conv.ptr.element");
  1658. const llvm::Constant *Elts = LV.getExtVectorElts();
  1659. unsigned ix = getAccessedFieldNo(0, Elts);
  1660. Address VectorBasePtrPlusIx =
  1661. Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
  1662. "vector.elt");
  1663. return VectorBasePtrPlusIx;
  1664. }
  1665. /// Load of global gamed gegisters are always calls to intrinsics.
  1666. RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
  1667. assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
  1668. "Bad type for register variable");
  1669. llvm::MDNode *RegName = cast<llvm::MDNode>(
  1670. cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
  1671. // We accept integer and pointer types only
  1672. llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
  1673. llvm::Type *Ty = OrigTy;
  1674. if (OrigTy->isPointerTy())
  1675. Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
  1676. llvm::Type *Types[] = { Ty };
  1677. llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
  1678. llvm::Value *Call = Builder.CreateCall(
  1679. F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
  1680. if (OrigTy->isPointerTy())
  1681. Call = Builder.CreateIntToPtr(Call, OrigTy);
  1682. return RValue::get(Call);
  1683. }
  1684. /// EmitStoreThroughLValue - Store the specified rvalue into the specified
  1685. /// lvalue, where both are guaranteed to the have the same type, and that type
  1686. /// is 'Ty'.
  1687. void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
  1688. bool isInit) {
  1689. if (!Dst.isSimple()) {
  1690. if (Dst.isVectorElt()) {
  1691. // Read/modify/write the vector, inserting the new element.
  1692. llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
  1693. Dst.isVolatileQualified());
  1694. Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
  1695. Dst.getVectorIdx(), "vecins");
  1696. Builder.CreateStore(Vec, Dst.getVectorAddress(),
  1697. Dst.isVolatileQualified());
  1698. return;
  1699. }
  1700. // If this is an update of extended vector elements, insert them as
  1701. // appropriate.
  1702. if (Dst.isExtVectorElt())
  1703. return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
  1704. if (Dst.isGlobalReg())
  1705. return EmitStoreThroughGlobalRegLValue(Src, Dst);
  1706. assert(Dst.isBitField() && "Unknown LValue type");
  1707. return EmitStoreThroughBitfieldLValue(Src, Dst);
  1708. }
  1709. // There's special magic for assigning into an ARC-qualified l-value.
  1710. if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
  1711. switch (Lifetime) {
  1712. case Qualifiers::OCL_None:
  1713. llvm_unreachable("present but none");
  1714. case Qualifiers::OCL_ExplicitNone:
  1715. // nothing special
  1716. break;
  1717. case Qualifiers::OCL_Strong:
  1718. if (isInit) {
  1719. Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
  1720. break;
  1721. }
  1722. EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
  1723. return;
  1724. case Qualifiers::OCL_Weak:
  1725. if (isInit)
  1726. // Initialize and then skip the primitive store.
  1727. EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
  1728. else
  1729. EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
  1730. return;
  1731. case Qualifiers::OCL_Autoreleasing:
  1732. Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
  1733. Src.getScalarVal()));
  1734. // fall into the normal path
  1735. break;
  1736. }
  1737. }
  1738. if (Dst.isObjCWeak() && !Dst.isNonGC()) {
  1739. // load of a __weak object.
  1740. Address LvalueDst = Dst.getAddress();
  1741. llvm::Value *src = Src.getScalarVal();
  1742. CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
  1743. return;
  1744. }
  1745. if (Dst.isObjCStrong() && !Dst.isNonGC()) {
  1746. // load of a __strong object.
  1747. Address LvalueDst = Dst.getAddress();
  1748. llvm::Value *src = Src.getScalarVal();
  1749. if (Dst.isObjCIvar()) {
  1750. assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
  1751. llvm::Type *ResultType = IntPtrTy;
  1752. Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
  1753. llvm::Value *RHS = dst.getPointer();
  1754. RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
  1755. llvm::Value *LHS =
  1756. Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
  1757. "sub.ptr.lhs.cast");
  1758. llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
  1759. CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
  1760. BytesBetween);
  1761. } else if (Dst.isGlobalObjCRef()) {
  1762. CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
  1763. Dst.isThreadLocalRef());
  1764. }
  1765. else
  1766. CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
  1767. return;
  1768. }
  1769. assert(Src.isScalar() && "Can't emit an agg store with this method");
  1770. EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
  1771. }
  1772. void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
  1773. llvm::Value **Result) {
  1774. const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
  1775. llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
  1776. Address Ptr = Dst.getBitFieldAddress();
  1777. // Get the source value, truncated to the width of the bit-field.
  1778. llvm::Value *SrcVal = Src.getScalarVal();
  1779. // Cast the source to the storage type and shift it into place.
  1780. SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
  1781. /*isSigned=*/false);
  1782. llvm::Value *MaskedVal = SrcVal;
  1783. // See if there are other bits in the bitfield's storage we'll need to load
  1784. // and mask together with source before storing.
  1785. if (Info.StorageSize != Info.Size) {
  1786. assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
  1787. llvm::Value *Val =
  1788. Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
  1789. // Mask the source value as needed.
  1790. if (!hasBooleanRepresentation(Dst.getType()))
  1791. SrcVal = Builder.CreateAnd(SrcVal,
  1792. llvm::APInt::getLowBitsSet(Info.StorageSize,
  1793. Info.Size),
  1794. "bf.value");
  1795. MaskedVal = SrcVal;
  1796. if (Info.Offset)
  1797. SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
  1798. // Mask out the original value.
  1799. Val = Builder.CreateAnd(Val,
  1800. ~llvm::APInt::getBitsSet(Info.StorageSize,
  1801. Info.Offset,
  1802. Info.Offset + Info.Size),
  1803. "bf.clear");
  1804. // Or together the unchanged values and the source value.
  1805. SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
  1806. } else {
  1807. assert(Info.Offset == 0);
  1808. }
  1809. // Write the new value back out.
  1810. Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
  1811. // Return the new value of the bit-field, if requested.
  1812. if (Result) {
  1813. llvm::Value *ResultVal = MaskedVal;
  1814. // Sign extend the value if needed.
  1815. if (Info.IsSigned) {
  1816. assert(Info.Size <= Info.StorageSize);
  1817. unsigned HighBits = Info.StorageSize - Info.Size;
  1818. if (HighBits) {
  1819. ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
  1820. ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
  1821. }
  1822. }
  1823. ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
  1824. "bf.result.cast");
  1825. *Result = EmitFromMemory(ResultVal, Dst.getType());
  1826. }
  1827. }
  1828. void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
  1829. LValue Dst) {
  1830. // This access turns into a read/modify/write of the vector. Load the input
  1831. // value now.
  1832. llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
  1833. Dst.isVolatileQualified());
  1834. const llvm::Constant *Elts = Dst.getExtVectorElts();
  1835. llvm::Value *SrcVal = Src.getScalarVal();
  1836. if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
  1837. unsigned NumSrcElts = VTy->getNumElements();
  1838. unsigned NumDstElts = Vec->getType()->getVectorNumElements();
  1839. if (NumDstElts == NumSrcElts) {
  1840. // Use shuffle vector is the src and destination are the same number of
  1841. // elements and restore the vector mask since it is on the side it will be
  1842. // stored.
  1843. SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
  1844. for (unsigned i = 0; i != NumSrcElts; ++i)
  1845. Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
  1846. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1847. Vec = Builder.CreateShuffleVector(SrcVal,
  1848. llvm::UndefValue::get(Vec->getType()),
  1849. MaskV);
  1850. } else if (NumDstElts > NumSrcElts) {
  1851. // Extended the source vector to the same length and then shuffle it
  1852. // into the destination.
  1853. // FIXME: since we're shuffling with undef, can we just use the indices
  1854. // into that? This could be simpler.
  1855. SmallVector<llvm::Constant*, 4> ExtMask;
  1856. for (unsigned i = 0; i != NumSrcElts; ++i)
  1857. ExtMask.push_back(Builder.getInt32(i));
  1858. ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
  1859. llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
  1860. llvm::Value *ExtSrcVal =
  1861. Builder.CreateShuffleVector(SrcVal,
  1862. llvm::UndefValue::get(SrcVal->getType()),
  1863. ExtMaskV);
  1864. // build identity
  1865. SmallVector<llvm::Constant*, 4> Mask;
  1866. for (unsigned i = 0; i != NumDstElts; ++i)
  1867. Mask.push_back(Builder.getInt32(i));
  1868. // When the vector size is odd and .odd or .hi is used, the last element
  1869. // of the Elts constant array will be one past the size of the vector.
  1870. // Ignore the last element here, if it is greater than the mask size.
  1871. if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
  1872. NumSrcElts--;
  1873. // modify when what gets shuffled in
  1874. for (unsigned i = 0; i != NumSrcElts; ++i)
  1875. Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
  1876. llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
  1877. Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
  1878. } else {
  1879. // We should never shorten the vector
  1880. llvm_unreachable("unexpected shorten vector length");
  1881. }
  1882. } else {
  1883. // If the Src is a scalar (not a vector) it must be updating one element.
  1884. unsigned InIdx = getAccessedFieldNo(0, Elts);
  1885. llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
  1886. Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
  1887. }
  1888. Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
  1889. Dst.isVolatileQualified());
  1890. }
  1891. /// Store of global named registers are always calls to intrinsics.
  1892. void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
  1893. assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
  1894. "Bad type for register variable");
  1895. llvm::MDNode *RegName = cast<llvm::MDNode>(
  1896. cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
  1897. assert(RegName && "Register LValue is not metadata");
  1898. // We accept integer and pointer types only
  1899. llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
  1900. llvm::Type *Ty = OrigTy;
  1901. if (OrigTy->isPointerTy())
  1902. Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
  1903. llvm::Type *Types[] = { Ty };
  1904. llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
  1905. llvm::Value *Value = Src.getScalarVal();
  1906. if (OrigTy->isPointerTy())
  1907. Value = Builder.CreatePtrToInt(Value, Ty);
  1908. Builder.CreateCall(
  1909. F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
  1910. }
  1911. // setObjCGCLValueClass - sets class of the lvalue for the purpose of
  1912. // generating write-barries API. It is currently a global, ivar,
  1913. // or neither.
  1914. static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
  1915. LValue &LV,
  1916. bool IsMemberAccess=false) {
  1917. if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
  1918. return;
  1919. if (isa<ObjCIvarRefExpr>(E)) {
  1920. QualType ExpTy = E->getType();
  1921. if (IsMemberAccess && ExpTy->isPointerType()) {
  1922. // If ivar is a structure pointer, assigning to field of
  1923. // this struct follows gcc's behavior and makes it a non-ivar
  1924. // writer-barrier conservatively.
  1925. ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
  1926. if (ExpTy->isRecordType()) {
  1927. LV.setObjCIvar(false);
  1928. return;
  1929. }
  1930. }
  1931. LV.setObjCIvar(true);
  1932. auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
  1933. LV.setBaseIvarExp(Exp->getBase());
  1934. LV.setObjCArray(E->getType()->isArrayType());
  1935. return;
  1936. }
  1937. if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
  1938. if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
  1939. if (VD->hasGlobalStorage()) {
  1940. LV.setGlobalObjCRef(true);
  1941. LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
  1942. }
  1943. }
  1944. LV.setObjCArray(E->getType()->isArrayType());
  1945. return;
  1946. }
  1947. if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
  1948. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1949. return;
  1950. }
  1951. if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
  1952. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1953. if (LV.isObjCIvar()) {
  1954. // If cast is to a structure pointer, follow gcc's behavior and make it
  1955. // a non-ivar write-barrier.
  1956. QualType ExpTy = E->getType();
  1957. if (ExpTy->isPointerType())
  1958. ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
  1959. if (ExpTy->isRecordType())
  1960. LV.setObjCIvar(false);
  1961. }
  1962. return;
  1963. }
  1964. if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
  1965. setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
  1966. return;
  1967. }
  1968. if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
  1969. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1970. return;
  1971. }
  1972. if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
  1973. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1974. return;
  1975. }
  1976. if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
  1977. setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
  1978. return;
  1979. }
  1980. if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
  1981. setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
  1982. if (LV.isObjCIvar() && !LV.isObjCArray())
  1983. // Using array syntax to assigning to what an ivar points to is not
  1984. // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
  1985. LV.setObjCIvar(false);
  1986. else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
  1987. // Using array syntax to assigning to what global points to is not
  1988. // same as assigning to the global itself. {id *G;} G[i] = 0;
  1989. LV.setGlobalObjCRef(false);
  1990. return;
  1991. }
  1992. if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
  1993. setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
  1994. // We don't know if member is an 'ivar', but this flag is looked at
  1995. // only in the context of LV.isObjCIvar().
  1996. LV.setObjCArray(E->getType()->isArrayType());
  1997. return;
  1998. }
  1999. }
  2000. static llvm::Value *
  2001. EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
  2002. llvm::Value *V, llvm::Type *IRType,
  2003. StringRef Name = StringRef()) {
  2004. unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
  2005. return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
  2006. }
  2007. static LValue EmitThreadPrivateVarDeclLValue(
  2008. CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
  2009. llvm::Type *RealVarTy, SourceLocation Loc) {
  2010. Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
  2011. Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
  2012. return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
  2013. }
  2014. static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF,
  2015. const VarDecl *VD, QualType T) {
  2016. llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
  2017. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
  2018. // Return an invalid address if variable is MT_To and unified
  2019. // memory is not enabled. For all other cases: MT_Link and
  2020. // MT_To with unified memory, return a valid address.
  2021. if (!Res || (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  2022. !CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory()))
  2023. return Address::invalid();
  2024. assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
  2025. (*Res == OMPDeclareTargetDeclAttr::MT_To &&
  2026. CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) &&
  2027. "Expected link clause OR to clause with unified memory enabled.");
  2028. QualType PtrTy = CGF.getContext().getPointerType(VD->getType());
  2029. Address Addr = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
  2030. return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>());
  2031. }
  2032. Address
  2033. CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
  2034. LValueBaseInfo *PointeeBaseInfo,
  2035. TBAAAccessInfo *PointeeTBAAInfo) {
  2036. llvm::LoadInst *Load = Builder.CreateLoad(RefLVal.getAddress(),
  2037. RefLVal.isVolatile());
  2038. CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
  2039. CharUnits Align = getNaturalTypeAlignment(RefLVal.getType()->getPointeeType(),
  2040. PointeeBaseInfo, PointeeTBAAInfo,
  2041. /* forPointeeType= */ true);
  2042. return Address(Load, Align);
  2043. }
  2044. LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) {
  2045. LValueBaseInfo PointeeBaseInfo;
  2046. TBAAAccessInfo PointeeTBAAInfo;
  2047. Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
  2048. &PointeeTBAAInfo);
  2049. return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
  2050. PointeeBaseInfo, PointeeTBAAInfo);
  2051. }
  2052. Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
  2053. const PointerType *PtrTy,
  2054. LValueBaseInfo *BaseInfo,
  2055. TBAAAccessInfo *TBAAInfo) {
  2056. llvm::Value *Addr = Builder.CreateLoad(Ptr);
  2057. return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(),
  2058. BaseInfo, TBAAInfo,
  2059. /*forPointeeType=*/true));
  2060. }
  2061. LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
  2062. const PointerType *PtrTy) {
  2063. LValueBaseInfo BaseInfo;
  2064. TBAAAccessInfo TBAAInfo;
  2065. Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
  2066. return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
  2067. }
  2068. static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
  2069. const Expr *E, const VarDecl *VD) {
  2070. QualType T = E->getType();
  2071. // If it's thread_local, emit a call to its wrapper function instead.
  2072. if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
  2073. CGF.CGM.getCXXABI().usesThreadWrapperFunction(VD))
  2074. return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
  2075. // Check if the variable is marked as declare target with link clause in
  2076. // device codegen.
  2077. if (CGF.getLangOpts().OpenMPIsDevice) {
  2078. Address Addr = emitDeclTargetVarDeclLValue(CGF, VD, T);
  2079. if (Addr.isValid())
  2080. return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
  2081. }
  2082. llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
  2083. llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
  2084. V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
  2085. CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
  2086. Address Addr(V, Alignment);
  2087. // Emit reference to the private copy of the variable if it is an OpenMP
  2088. // threadprivate variable.
  2089. if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
  2090. VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  2091. return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
  2092. E->getExprLoc());
  2093. }
  2094. LValue LV = VD->getType()->isReferenceType() ?
  2095. CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
  2096. AlignmentSource::Decl) :
  2097. CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
  2098. setObjCGCLValueClass(CGF.getContext(), E, LV);
  2099. return LV;
  2100. }
  2101. static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
  2102. const FunctionDecl *FD) {
  2103. if (FD->hasAttr<WeakRefAttr>()) {
  2104. ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
  2105. return aliasee.getPointer();
  2106. }
  2107. llvm::Constant *V = CGM.GetAddrOfFunction(FD);
  2108. if (!FD->hasPrototype()) {
  2109. if (const FunctionProtoType *Proto =
  2110. FD->getType()->getAs<FunctionProtoType>()) {
  2111. // Ugly case: for a K&R-style definition, the type of the definition
  2112. // isn't the same as the type of a use. Correct for this with a
  2113. // bitcast.
  2114. QualType NoProtoType =
  2115. CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
  2116. NoProtoType = CGM.getContext().getPointerType(NoProtoType);
  2117. V = llvm::ConstantExpr::getBitCast(V,
  2118. CGM.getTypes().ConvertType(NoProtoType));
  2119. }
  2120. }
  2121. return V;
  2122. }
  2123. static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
  2124. const Expr *E, const FunctionDecl *FD) {
  2125. llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
  2126. CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
  2127. return CGF.MakeAddrLValue(V, E->getType(), Alignment,
  2128. AlignmentSource::Decl);
  2129. }
  2130. static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
  2131. llvm::Value *ThisValue) {
  2132. QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
  2133. LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
  2134. return CGF.EmitLValueForField(LV, FD);
  2135. }
  2136. /// Named Registers are named metadata pointing to the register name
  2137. /// which will be read from/written to as an argument to the intrinsic
  2138. /// @llvm.read/write_register.
  2139. /// So far, only the name is being passed down, but other options such as
  2140. /// register type, allocation type or even optimization options could be
  2141. /// passed down via the metadata node.
  2142. static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
  2143. SmallString<64> Name("llvm.named.register.");
  2144. AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
  2145. assert(Asm->getLabel().size() < 64-Name.size() &&
  2146. "Register name too big");
  2147. Name.append(Asm->getLabel());
  2148. llvm::NamedMDNode *M =
  2149. CGM.getModule().getOrInsertNamedMetadata(Name);
  2150. if (M->getNumOperands() == 0) {
  2151. llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
  2152. Asm->getLabel());
  2153. llvm::Metadata *Ops[] = {Str};
  2154. M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
  2155. }
  2156. CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
  2157. llvm::Value *Ptr =
  2158. llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
  2159. return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
  2160. }
  2161. /// Determine whether we can emit a reference to \p VD from the current
  2162. /// context, despite not necessarily having seen an odr-use of the variable in
  2163. /// this context.
  2164. static bool canEmitSpuriousReferenceToVariable(CodeGenFunction &CGF,
  2165. const DeclRefExpr *E,
  2166. const VarDecl *VD,
  2167. bool IsConstant) {
  2168. // For a variable declared in an enclosing scope, do not emit a spurious
  2169. // reference even if we have a capture, as that will emit an unwarranted
  2170. // reference to our capture state, and will likely generate worse code than
  2171. // emitting a local copy.
  2172. if (E->refersToEnclosingVariableOrCapture())
  2173. return false;
  2174. // For a local declaration declared in this function, we can always reference
  2175. // it even if we don't have an odr-use.
  2176. if (VD->hasLocalStorage()) {
  2177. return VD->getDeclContext() ==
  2178. dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl);
  2179. }
  2180. // For a global declaration, we can emit a reference to it if we know
  2181. // for sure that we are able to emit a definition of it.
  2182. VD = VD->getDefinition(CGF.getContext());
  2183. if (!VD)
  2184. return false;
  2185. // Don't emit a spurious reference if it might be to a variable that only
  2186. // exists on a different device / target.
  2187. // FIXME: This is unnecessarily broad. Check whether this would actually be a
  2188. // cross-target reference.
  2189. if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA ||
  2190. CGF.getLangOpts().OpenCL) {
  2191. return false;
  2192. }
  2193. // We can emit a spurious reference only if the linkage implies that we'll
  2194. // be emitting a non-interposable symbol that will be retained until link
  2195. // time.
  2196. switch (CGF.CGM.getLLVMLinkageVarDefinition(VD, IsConstant)) {
  2197. case llvm::GlobalValue::ExternalLinkage:
  2198. case llvm::GlobalValue::LinkOnceODRLinkage:
  2199. case llvm::GlobalValue::WeakODRLinkage:
  2200. case llvm::GlobalValue::InternalLinkage:
  2201. case llvm::GlobalValue::PrivateLinkage:
  2202. return true;
  2203. default:
  2204. return false;
  2205. }
  2206. }
  2207. LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
  2208. const NamedDecl *ND = E->getDecl();
  2209. QualType T = E->getType();
  2210. assert(E->isNonOdrUse() != NOUR_Unevaluated &&
  2211. "should not emit an unevaluated operand");
  2212. if (const auto *VD = dyn_cast<VarDecl>(ND)) {
  2213. // Global Named registers access via intrinsics only
  2214. if (VD->getStorageClass() == SC_Register &&
  2215. VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
  2216. return EmitGlobalNamedRegister(VD, CGM);
  2217. // If this DeclRefExpr does not constitute an odr-use of the variable,
  2218. // we're not permitted to emit a reference to it in general, and it might
  2219. // not be captured if capture would be necessary for a use. Emit the
  2220. // constant value directly instead.
  2221. if (E->isNonOdrUse() == NOUR_Constant &&
  2222. (VD->getType()->isReferenceType() ||
  2223. !canEmitSpuriousReferenceToVariable(*this, E, VD, true))) {
  2224. VD->getAnyInitializer(VD);
  2225. llvm::Constant *Val = ConstantEmitter(*this).emitAbstract(
  2226. E->getLocation(), *VD->evaluateValue(), VD->getType());
  2227. assert(Val && "failed to emit constant expression");
  2228. Address Addr = Address::invalid();
  2229. if (!VD->getType()->isReferenceType()) {
  2230. // Spill the constant value to a global.
  2231. Addr = CGM.createUnnamedGlobalFrom(*VD, Val,
  2232. getContext().getDeclAlign(VD));
  2233. llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType());
  2234. auto *PTy = llvm::PointerType::get(
  2235. VarTy, getContext().getTargetAddressSpace(VD->getType()));
  2236. if (PTy != Addr.getType())
  2237. Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy);
  2238. } else {
  2239. // Should we be using the alignment of the constant pointer we emitted?
  2240. CharUnits Alignment =
  2241. getNaturalTypeAlignment(E->getType(),
  2242. /* BaseInfo= */ nullptr,
  2243. /* TBAAInfo= */ nullptr,
  2244. /* forPointeeType= */ true);
  2245. Addr = Address(Val, Alignment);
  2246. }
  2247. return MakeAddrLValue(Addr, T, AlignmentSource::Decl);
  2248. }
  2249. // FIXME: Handle other kinds of non-odr-use DeclRefExprs.
  2250. // Check for captured variables.
  2251. if (E->refersToEnclosingVariableOrCapture()) {
  2252. VD = VD->getCanonicalDecl();
  2253. if (auto *FD = LambdaCaptureFields.lookup(VD))
  2254. return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
  2255. else if (CapturedStmtInfo) {
  2256. auto I = LocalDeclMap.find(VD);
  2257. if (I != LocalDeclMap.end()) {
  2258. if (VD->getType()->isReferenceType())
  2259. return EmitLoadOfReferenceLValue(I->second, VD->getType(),
  2260. AlignmentSource::Decl);
  2261. return MakeAddrLValue(I->second, T);
  2262. }
  2263. LValue CapLVal =
  2264. EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
  2265. CapturedStmtInfo->getContextValue());
  2266. return MakeAddrLValue(
  2267. Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
  2268. CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl),
  2269. CapLVal.getTBAAInfo());
  2270. }
  2271. assert(isa<BlockDecl>(CurCodeDecl));
  2272. Address addr = GetAddrOfBlockDecl(VD);
  2273. return MakeAddrLValue(addr, T, AlignmentSource::Decl);
  2274. }
  2275. }
  2276. // FIXME: We should be able to assert this for FunctionDecls as well!
  2277. // FIXME: We should be able to assert this for all DeclRefExprs, not just
  2278. // those with a valid source location.
  2279. assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
  2280. !E->getLocation().isValid()) &&
  2281. "Should not use decl without marking it used!");
  2282. if (ND->hasAttr<WeakRefAttr>()) {
  2283. const auto *VD = cast<ValueDecl>(ND);
  2284. ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
  2285. return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
  2286. }
  2287. if (const auto *VD = dyn_cast<VarDecl>(ND)) {
  2288. // Check if this is a global variable.
  2289. if (VD->hasLinkage() || VD->isStaticDataMember())
  2290. return EmitGlobalVarDeclLValue(*this, E, VD);
  2291. Address addr = Address::invalid();
  2292. // The variable should generally be present in the local decl map.
  2293. auto iter = LocalDeclMap.find(VD);
  2294. if (iter != LocalDeclMap.end()) {
  2295. addr = iter->second;
  2296. // Otherwise, it might be static local we haven't emitted yet for
  2297. // some reason; most likely, because it's in an outer function.
  2298. } else if (VD->isStaticLocal()) {
  2299. addr = Address(CGM.getOrCreateStaticVarDecl(
  2300. *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false)),
  2301. getContext().getDeclAlign(VD));
  2302. // No other cases for now.
  2303. } else {
  2304. llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
  2305. }
  2306. // Check for OpenMP threadprivate variables.
  2307. if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
  2308. VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
  2309. return EmitThreadPrivateVarDeclLValue(
  2310. *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
  2311. E->getExprLoc());
  2312. }
  2313. // Drill into block byref variables.
  2314. bool isBlockByref = VD->isEscapingByref();
  2315. if (isBlockByref) {
  2316. addr = emitBlockByrefAddress(addr, VD);
  2317. }
  2318. // Drill into reference types.
  2319. LValue LV = VD->getType()->isReferenceType() ?
  2320. EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) :
  2321. MakeAddrLValue(addr, T, AlignmentSource::Decl);
  2322. bool isLocalStorage = VD->hasLocalStorage();
  2323. bool NonGCable = isLocalStorage &&
  2324. !VD->getType()->isReferenceType() &&
  2325. !isBlockByref;
  2326. if (NonGCable) {
  2327. LV.getQuals().removeObjCGCAttr();
  2328. LV.setNonGC(true);
  2329. }
  2330. bool isImpreciseLifetime =
  2331. (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
  2332. if (isImpreciseLifetime)
  2333. LV.setARCPreciseLifetime(ARCImpreciseLifetime);
  2334. setObjCGCLValueClass(getContext(), E, LV);
  2335. return LV;
  2336. }
  2337. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  2338. return EmitFunctionDeclLValue(*this, E, FD);
  2339. // FIXME: While we're emitting a binding from an enclosing scope, all other
  2340. // DeclRefExprs we see should be implicitly treated as if they also refer to
  2341. // an enclosing scope.
  2342. if (const auto *BD = dyn_cast<BindingDecl>(ND))
  2343. return EmitLValue(BD->getBinding());
  2344. llvm_unreachable("Unhandled DeclRefExpr");
  2345. }
  2346. LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
  2347. // __extension__ doesn't affect lvalue-ness.
  2348. if (E->getOpcode() == UO_Extension)
  2349. return EmitLValue(E->getSubExpr());
  2350. QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
  2351. switch (E->getOpcode()) {
  2352. default: llvm_unreachable("Unknown unary operator lvalue!");
  2353. case UO_Deref: {
  2354. QualType T = E->getSubExpr()->getType()->getPointeeType();
  2355. assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
  2356. LValueBaseInfo BaseInfo;
  2357. TBAAAccessInfo TBAAInfo;
  2358. Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
  2359. &TBAAInfo);
  2360. LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
  2361. LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
  2362. // We should not generate __weak write barrier on indirect reference
  2363. // of a pointer to object; as in void foo (__weak id *param); *param = 0;
  2364. // But, we continue to generate __strong write barrier on indirect write
  2365. // into a pointer to object.
  2366. if (getLangOpts().ObjC &&
  2367. getLangOpts().getGC() != LangOptions::NonGC &&
  2368. LV.isObjCWeak())
  2369. LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
  2370. return LV;
  2371. }
  2372. case UO_Real:
  2373. case UO_Imag: {
  2374. LValue LV = EmitLValue(E->getSubExpr());
  2375. assert(LV.isSimple() && "real/imag on non-ordinary l-value");
  2376. // __real is valid on scalars. This is a faster way of testing that.
  2377. // __imag can only produce an rvalue on scalars.
  2378. if (E->getOpcode() == UO_Real &&
  2379. !LV.getAddress().getElementType()->isStructTy()) {
  2380. assert(E->getSubExpr()->getType()->isArithmeticType());
  2381. return LV;
  2382. }
  2383. QualType T = ExprTy->castAs<ComplexType>()->getElementType();
  2384. Address Component =
  2385. (E->getOpcode() == UO_Real
  2386. ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
  2387. : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
  2388. LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
  2389. CGM.getTBAAInfoForSubobject(LV, T));
  2390. ElemLV.getQuals().addQualifiers(LV.getQuals());
  2391. return ElemLV;
  2392. }
  2393. case UO_PreInc:
  2394. case UO_PreDec: {
  2395. LValue LV = EmitLValue(E->getSubExpr());
  2396. bool isInc = E->getOpcode() == UO_PreInc;
  2397. if (E->getType()->isAnyComplexType())
  2398. EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
  2399. else
  2400. EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
  2401. return LV;
  2402. }
  2403. }
  2404. }
  2405. LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
  2406. return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
  2407. E->getType(), AlignmentSource::Decl);
  2408. }
  2409. LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
  2410. return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
  2411. E->getType(), AlignmentSource::Decl);
  2412. }
  2413. LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
  2414. auto SL = E->getFunctionName();
  2415. assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
  2416. StringRef FnName = CurFn->getName();
  2417. if (FnName.startswith("\01"))
  2418. FnName = FnName.substr(1);
  2419. StringRef NameItems[] = {
  2420. PredefinedExpr::getIdentKindName(E->getIdentKind()), FnName};
  2421. std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
  2422. if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) {
  2423. std::string Name = SL->getString();
  2424. if (!Name.empty()) {
  2425. unsigned Discriminator =
  2426. CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
  2427. if (Discriminator)
  2428. Name += "_" + Twine(Discriminator + 1).str();
  2429. auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
  2430. return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
  2431. } else {
  2432. auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
  2433. return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
  2434. }
  2435. }
  2436. auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
  2437. return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
  2438. }
  2439. /// Emit a type description suitable for use by a runtime sanitizer library. The
  2440. /// format of a type descriptor is
  2441. ///
  2442. /// \code
  2443. /// { i16 TypeKind, i16 TypeInfo }
  2444. /// \endcode
  2445. ///
  2446. /// followed by an array of i8 containing the type name. TypeKind is 0 for an
  2447. /// integer, 1 for a floating point value, and -1 for anything else.
  2448. llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
  2449. // Only emit each type's descriptor once.
  2450. if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
  2451. return C;
  2452. uint16_t TypeKind = -1;
  2453. uint16_t TypeInfo = 0;
  2454. if (T->isIntegerType()) {
  2455. TypeKind = 0;
  2456. TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
  2457. (T->isSignedIntegerType() ? 1 : 0);
  2458. } else if (T->isFloatingType()) {
  2459. TypeKind = 1;
  2460. TypeInfo = getContext().getTypeSize(T);
  2461. }
  2462. // Format the type name as if for a diagnostic, including quotes and
  2463. // optionally an 'aka'.
  2464. SmallString<32> Buffer;
  2465. CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
  2466. (intptr_t)T.getAsOpaquePtr(),
  2467. StringRef(), StringRef(), None, Buffer,
  2468. None);
  2469. llvm::Constant *Components[] = {
  2470. Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
  2471. llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
  2472. };
  2473. llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
  2474. auto *GV = new llvm::GlobalVariable(
  2475. CGM.getModule(), Descriptor->getType(),
  2476. /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
  2477. GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  2478. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
  2479. // Remember the descriptor for this type.
  2480. CGM.setTypeDescriptorInMap(T, GV);
  2481. return GV;
  2482. }
  2483. llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
  2484. llvm::Type *TargetTy = IntPtrTy;
  2485. if (V->getType() == TargetTy)
  2486. return V;
  2487. // Floating-point types which fit into intptr_t are bitcast to integers
  2488. // and then passed directly (after zero-extension, if necessary).
  2489. if (V->getType()->isFloatingPointTy()) {
  2490. unsigned Bits = V->getType()->getPrimitiveSizeInBits();
  2491. if (Bits <= TargetTy->getIntegerBitWidth())
  2492. V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
  2493. Bits));
  2494. }
  2495. // Integers which fit in intptr_t are zero-extended and passed directly.
  2496. if (V->getType()->isIntegerTy() &&
  2497. V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
  2498. return Builder.CreateZExt(V, TargetTy);
  2499. // Pointers are passed directly, everything else is passed by address.
  2500. if (!V->getType()->isPointerTy()) {
  2501. Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
  2502. Builder.CreateStore(V, Ptr);
  2503. V = Ptr.getPointer();
  2504. }
  2505. return Builder.CreatePtrToInt(V, TargetTy);
  2506. }
  2507. /// Emit a representation of a SourceLocation for passing to a handler
  2508. /// in a sanitizer runtime library. The format for this data is:
  2509. /// \code
  2510. /// struct SourceLocation {
  2511. /// const char *Filename;
  2512. /// int32_t Line, Column;
  2513. /// };
  2514. /// \endcode
  2515. /// For an invalid SourceLocation, the Filename pointer is null.
  2516. llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
  2517. llvm::Constant *Filename;
  2518. int Line, Column;
  2519. PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
  2520. if (PLoc.isValid()) {
  2521. StringRef FilenameString = PLoc.getFilename();
  2522. int PathComponentsToStrip =
  2523. CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
  2524. if (PathComponentsToStrip < 0) {
  2525. assert(PathComponentsToStrip != INT_MIN);
  2526. int PathComponentsToKeep = -PathComponentsToStrip;
  2527. auto I = llvm::sys::path::rbegin(FilenameString);
  2528. auto E = llvm::sys::path::rend(FilenameString);
  2529. while (I != E && --PathComponentsToKeep)
  2530. ++I;
  2531. FilenameString = FilenameString.substr(I - E);
  2532. } else if (PathComponentsToStrip > 0) {
  2533. auto I = llvm::sys::path::begin(FilenameString);
  2534. auto E = llvm::sys::path::end(FilenameString);
  2535. while (I != E && PathComponentsToStrip--)
  2536. ++I;
  2537. if (I != E)
  2538. FilenameString =
  2539. FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
  2540. else
  2541. FilenameString = llvm::sys::path::filename(FilenameString);
  2542. }
  2543. auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
  2544. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
  2545. cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
  2546. Filename = FilenameGV.getPointer();
  2547. Line = PLoc.getLine();
  2548. Column = PLoc.getColumn();
  2549. } else {
  2550. Filename = llvm::Constant::getNullValue(Int8PtrTy);
  2551. Line = Column = 0;
  2552. }
  2553. llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
  2554. Builder.getInt32(Column)};
  2555. return llvm::ConstantStruct::getAnon(Data);
  2556. }
  2557. namespace {
  2558. /// Specify under what conditions this check can be recovered
  2559. enum class CheckRecoverableKind {
  2560. /// Always terminate program execution if this check fails.
  2561. Unrecoverable,
  2562. /// Check supports recovering, runtime has both fatal (noreturn) and
  2563. /// non-fatal handlers for this check.
  2564. Recoverable,
  2565. /// Runtime conditionally aborts, always need to support recovery.
  2566. AlwaysRecoverable
  2567. };
  2568. }
  2569. static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
  2570. assert(Kind.countPopulation() == 1);
  2571. if (Kind == SanitizerKind::Function || Kind == SanitizerKind::Vptr)
  2572. return CheckRecoverableKind::AlwaysRecoverable;
  2573. else if (Kind == SanitizerKind::Return || Kind == SanitizerKind::Unreachable)
  2574. return CheckRecoverableKind::Unrecoverable;
  2575. else
  2576. return CheckRecoverableKind::Recoverable;
  2577. }
  2578. namespace {
  2579. struct SanitizerHandlerInfo {
  2580. char const *const Name;
  2581. unsigned Version;
  2582. };
  2583. }
  2584. const SanitizerHandlerInfo SanitizerHandlers[] = {
  2585. #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
  2586. LIST_SANITIZER_CHECKS
  2587. #undef SANITIZER_CHECK
  2588. };
  2589. static void emitCheckHandlerCall(CodeGenFunction &CGF,
  2590. llvm::FunctionType *FnType,
  2591. ArrayRef<llvm::Value *> FnArgs,
  2592. SanitizerHandler CheckHandler,
  2593. CheckRecoverableKind RecoverKind, bool IsFatal,
  2594. llvm::BasicBlock *ContBB) {
  2595. assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
  2596. Optional<ApplyDebugLocation> DL;
  2597. if (!CGF.Builder.getCurrentDebugLocation()) {
  2598. // Ensure that the call has at least an artificial debug location.
  2599. DL.emplace(CGF, SourceLocation());
  2600. }
  2601. bool NeedsAbortSuffix =
  2602. IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
  2603. bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
  2604. const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
  2605. const StringRef CheckName = CheckInfo.Name;
  2606. std::string FnName = "__ubsan_handle_" + CheckName.str();
  2607. if (CheckInfo.Version && !MinimalRuntime)
  2608. FnName += "_v" + llvm::utostr(CheckInfo.Version);
  2609. if (MinimalRuntime)
  2610. FnName += "_minimal";
  2611. if (NeedsAbortSuffix)
  2612. FnName += "_abort";
  2613. bool MayReturn =
  2614. !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
  2615. llvm::AttrBuilder B;
  2616. if (!MayReturn) {
  2617. B.addAttribute(llvm::Attribute::NoReturn)
  2618. .addAttribute(llvm::Attribute::NoUnwind);
  2619. }
  2620. B.addAttribute(llvm::Attribute::UWTable);
  2621. llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
  2622. FnType, FnName,
  2623. llvm::AttributeList::get(CGF.getLLVMContext(),
  2624. llvm::AttributeList::FunctionIndex, B),
  2625. /*Local=*/true);
  2626. llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
  2627. if (!MayReturn) {
  2628. HandlerCall->setDoesNotReturn();
  2629. CGF.Builder.CreateUnreachable();
  2630. } else {
  2631. CGF.Builder.CreateBr(ContBB);
  2632. }
  2633. }
  2634. void CodeGenFunction::EmitCheck(
  2635. ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
  2636. SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
  2637. ArrayRef<llvm::Value *> DynamicArgs) {
  2638. assert(IsSanitizerScope);
  2639. assert(Checked.size() > 0);
  2640. assert(CheckHandler >= 0 &&
  2641. size_t(CheckHandler) < llvm::array_lengthof(SanitizerHandlers));
  2642. const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
  2643. llvm::Value *FatalCond = nullptr;
  2644. llvm::Value *RecoverableCond = nullptr;
  2645. llvm::Value *TrapCond = nullptr;
  2646. for (int i = 0, n = Checked.size(); i < n; ++i) {
  2647. llvm::Value *Check = Checked[i].first;
  2648. // -fsanitize-trap= overrides -fsanitize-recover=.
  2649. llvm::Value *&Cond =
  2650. CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
  2651. ? TrapCond
  2652. : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
  2653. ? RecoverableCond
  2654. : FatalCond;
  2655. Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
  2656. }
  2657. if (TrapCond)
  2658. EmitTrapCheck(TrapCond);
  2659. if (!FatalCond && !RecoverableCond)
  2660. return;
  2661. llvm::Value *JointCond;
  2662. if (FatalCond && RecoverableCond)
  2663. JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
  2664. else
  2665. JointCond = FatalCond ? FatalCond : RecoverableCond;
  2666. assert(JointCond);
  2667. CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
  2668. assert(SanOpts.has(Checked[0].second));
  2669. #ifndef NDEBUG
  2670. for (int i = 1, n = Checked.size(); i < n; ++i) {
  2671. assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
  2672. "All recoverable kinds in a single check must be same!");
  2673. assert(SanOpts.has(Checked[i].second));
  2674. }
  2675. #endif
  2676. llvm::BasicBlock *Cont = createBasicBlock("cont");
  2677. llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
  2678. llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
  2679. // Give hint that we very much don't expect to execute the handler
  2680. // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
  2681. llvm::MDBuilder MDHelper(getLLVMContext());
  2682. llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
  2683. Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
  2684. EmitBlock(Handlers);
  2685. // Handler functions take an i8* pointing to the (handler-specific) static
  2686. // information block, followed by a sequence of intptr_t arguments
  2687. // representing operand values.
  2688. SmallVector<llvm::Value *, 4> Args;
  2689. SmallVector<llvm::Type *, 4> ArgTypes;
  2690. if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
  2691. Args.reserve(DynamicArgs.size() + 1);
  2692. ArgTypes.reserve(DynamicArgs.size() + 1);
  2693. // Emit handler arguments and create handler function type.
  2694. if (!StaticArgs.empty()) {
  2695. llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
  2696. auto *InfoPtr =
  2697. new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
  2698. llvm::GlobalVariable::PrivateLinkage, Info);
  2699. InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  2700. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
  2701. Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
  2702. ArgTypes.push_back(Int8PtrTy);
  2703. }
  2704. for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
  2705. Args.push_back(EmitCheckValue(DynamicArgs[i]));
  2706. ArgTypes.push_back(IntPtrTy);
  2707. }
  2708. }
  2709. llvm::FunctionType *FnType =
  2710. llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
  2711. if (!FatalCond || !RecoverableCond) {
  2712. // Simple case: we need to generate a single handler call, either
  2713. // fatal, or non-fatal.
  2714. emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
  2715. (FatalCond != nullptr), Cont);
  2716. } else {
  2717. // Emit two handler calls: first one for set of unrecoverable checks,
  2718. // another one for recoverable.
  2719. llvm::BasicBlock *NonFatalHandlerBB =
  2720. createBasicBlock("non_fatal." + CheckName);
  2721. llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
  2722. Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
  2723. EmitBlock(FatalHandlerBB);
  2724. emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
  2725. NonFatalHandlerBB);
  2726. EmitBlock(NonFatalHandlerBB);
  2727. emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
  2728. Cont);
  2729. }
  2730. EmitBlock(Cont);
  2731. }
  2732. void CodeGenFunction::EmitCfiSlowPathCheck(
  2733. SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
  2734. llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
  2735. llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
  2736. llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
  2737. llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
  2738. llvm::MDBuilder MDHelper(getLLVMContext());
  2739. llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
  2740. BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
  2741. EmitBlock(CheckBB);
  2742. bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
  2743. llvm::CallInst *CheckCall;
  2744. llvm::FunctionCallee SlowPathFn;
  2745. if (WithDiag) {
  2746. llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
  2747. auto *InfoPtr =
  2748. new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
  2749. llvm::GlobalVariable::PrivateLinkage, Info);
  2750. InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  2751. CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
  2752. SlowPathFn = CGM.getModule().getOrInsertFunction(
  2753. "__cfi_slowpath_diag",
  2754. llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
  2755. false));
  2756. CheckCall = Builder.CreateCall(
  2757. SlowPathFn, {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
  2758. } else {
  2759. SlowPathFn = CGM.getModule().getOrInsertFunction(
  2760. "__cfi_slowpath",
  2761. llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
  2762. CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
  2763. }
  2764. CGM.setDSOLocal(
  2765. cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts()));
  2766. CheckCall->setDoesNotThrow();
  2767. EmitBlock(Cont);
  2768. }
  2769. // Emit a stub for __cfi_check function so that the linker knows about this
  2770. // symbol in LTO mode.
  2771. void CodeGenFunction::EmitCfiCheckStub() {
  2772. llvm::Module *M = &CGM.getModule();
  2773. auto &Ctx = M->getContext();
  2774. llvm::Function *F = llvm::Function::Create(
  2775. llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
  2776. llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
  2777. CGM.setDSOLocal(F);
  2778. llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
  2779. // FIXME: consider emitting an intrinsic call like
  2780. // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
  2781. // which can be lowered in CrossDSOCFI pass to the actual contents of
  2782. // __cfi_check. This would allow inlining of __cfi_check calls.
  2783. llvm::CallInst::Create(
  2784. llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
  2785. llvm::ReturnInst::Create(Ctx, nullptr, BB);
  2786. }
  2787. // This function is basically a switch over the CFI failure kind, which is
  2788. // extracted from CFICheckFailData (1st function argument). Each case is either
  2789. // llvm.trap or a call to one of the two runtime handlers, based on
  2790. // -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
  2791. // failure kind) traps, but this should really never happen. CFICheckFailData
  2792. // can be nullptr if the calling module has -fsanitize-trap behavior for this
  2793. // check kind; in this case __cfi_check_fail traps as well.
  2794. void CodeGenFunction::EmitCfiCheckFail() {
  2795. SanitizerScope SanScope(this);
  2796. FunctionArgList Args;
  2797. ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
  2798. ImplicitParamDecl::Other);
  2799. ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
  2800. ImplicitParamDecl::Other);
  2801. Args.push_back(&ArgData);
  2802. Args.push_back(&ArgAddr);
  2803. const CGFunctionInfo &FI =
  2804. CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
  2805. llvm::Function *F = llvm::Function::Create(
  2806. llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
  2807. llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
  2808. F->setVisibility(llvm::GlobalValue::HiddenVisibility);
  2809. StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
  2810. SourceLocation());
  2811. // This function should not be affected by blacklist. This function does
  2812. // not have a source location, but "src:*" would still apply. Revert any
  2813. // changes to SanOpts made in StartFunction.
  2814. SanOpts = CGM.getLangOpts().Sanitize;
  2815. llvm::Value *Data =
  2816. EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
  2817. CGM.getContext().VoidPtrTy, ArgData.getLocation());
  2818. llvm::Value *Addr =
  2819. EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
  2820. CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
  2821. // Data == nullptr means the calling module has trap behaviour for this check.
  2822. llvm::Value *DataIsNotNullPtr =
  2823. Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
  2824. EmitTrapCheck(DataIsNotNullPtr);
  2825. llvm::StructType *SourceLocationTy =
  2826. llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
  2827. llvm::StructType *CfiCheckFailDataTy =
  2828. llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
  2829. llvm::Value *V = Builder.CreateConstGEP2_32(
  2830. CfiCheckFailDataTy,
  2831. Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
  2832. 0);
  2833. Address CheckKindAddr(V, getIntAlign());
  2834. llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
  2835. llvm::Value *AllVtables = llvm::MetadataAsValue::get(
  2836. CGM.getLLVMContext(),
  2837. llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
  2838. llvm::Value *ValidVtable = Builder.CreateZExt(
  2839. Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
  2840. {Addr, AllVtables}),
  2841. IntPtrTy);
  2842. const std::pair<int, SanitizerMask> CheckKinds[] = {
  2843. {CFITCK_VCall, SanitizerKind::CFIVCall},
  2844. {CFITCK_NVCall, SanitizerKind::CFINVCall},
  2845. {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
  2846. {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
  2847. {CFITCK_ICall, SanitizerKind::CFIICall}};
  2848. SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
  2849. for (auto CheckKindMaskPair : CheckKinds) {
  2850. int Kind = CheckKindMaskPair.first;
  2851. SanitizerMask Mask = CheckKindMaskPair.second;
  2852. llvm::Value *Cond =
  2853. Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
  2854. if (CGM.getLangOpts().Sanitize.has(Mask))
  2855. EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
  2856. {Data, Addr, ValidVtable});
  2857. else
  2858. EmitTrapCheck(Cond);
  2859. }
  2860. FinishFunction();
  2861. // The only reference to this function will be created during LTO link.
  2862. // Make sure it survives until then.
  2863. CGM.addUsedGlobal(F);
  2864. }
  2865. void CodeGenFunction::EmitUnreachable(SourceLocation Loc) {
  2866. if (SanOpts.has(SanitizerKind::Unreachable)) {
  2867. SanitizerScope SanScope(this);
  2868. EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
  2869. SanitizerKind::Unreachable),
  2870. SanitizerHandler::BuiltinUnreachable,
  2871. EmitCheckSourceLocation(Loc), None);
  2872. }
  2873. Builder.CreateUnreachable();
  2874. }
  2875. void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
  2876. llvm::BasicBlock *Cont = createBasicBlock("cont");
  2877. // If we're optimizing, collapse all calls to trap down to just one per
  2878. // function to save on code size.
  2879. if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
  2880. TrapBB = createBasicBlock("trap");
  2881. Builder.CreateCondBr(Checked, Cont, TrapBB);
  2882. EmitBlock(TrapBB);
  2883. llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
  2884. TrapCall->setDoesNotReturn();
  2885. TrapCall->setDoesNotThrow();
  2886. Builder.CreateUnreachable();
  2887. } else {
  2888. Builder.CreateCondBr(Checked, Cont, TrapBB);
  2889. }
  2890. EmitBlock(Cont);
  2891. }
  2892. llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
  2893. llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
  2894. if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
  2895. auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
  2896. CGM.getCodeGenOpts().TrapFuncName);
  2897. TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
  2898. }
  2899. return TrapCall;
  2900. }
  2901. Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
  2902. LValueBaseInfo *BaseInfo,
  2903. TBAAAccessInfo *TBAAInfo) {
  2904. assert(E->getType()->isArrayType() &&
  2905. "Array to pointer decay must have array source type!");
  2906. // Expressions of array type can't be bitfields or vector elements.
  2907. LValue LV = EmitLValue(E);
  2908. Address Addr = LV.getAddress();
  2909. // If the array type was an incomplete type, we need to make sure
  2910. // the decay ends up being the right type.
  2911. llvm::Type *NewTy = ConvertType(E->getType());
  2912. Addr = Builder.CreateElementBitCast(Addr, NewTy);
  2913. // Note that VLA pointers are always decayed, so we don't need to do
  2914. // anything here.
  2915. if (!E->getType()->isVariableArrayType()) {
  2916. assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
  2917. "Expected pointer to array");
  2918. Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
  2919. }
  2920. // The result of this decay conversion points to an array element within the
  2921. // base lvalue. However, since TBAA currently does not support representing
  2922. // accesses to elements of member arrays, we conservatively represent accesses
  2923. // to the pointee object as if it had no any base lvalue specified.
  2924. // TODO: Support TBAA for member arrays.
  2925. QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
  2926. if (BaseInfo) *BaseInfo = LV.getBaseInfo();
  2927. if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
  2928. return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
  2929. }
  2930. /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
  2931. /// array to pointer, return the array subexpression.
  2932. static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
  2933. // If this isn't just an array->pointer decay, bail out.
  2934. const auto *CE = dyn_cast<CastExpr>(E);
  2935. if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
  2936. return nullptr;
  2937. // If this is a decay from variable width array, bail out.
  2938. const Expr *SubExpr = CE->getSubExpr();
  2939. if (SubExpr->getType()->isVariableArrayType())
  2940. return nullptr;
  2941. return SubExpr;
  2942. }
  2943. static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
  2944. llvm::Value *ptr,
  2945. ArrayRef<llvm::Value*> indices,
  2946. bool inbounds,
  2947. bool signedIndices,
  2948. SourceLocation loc,
  2949. const llvm::Twine &name = "arrayidx") {
  2950. if (inbounds) {
  2951. return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices,
  2952. CodeGenFunction::NotSubtraction, loc,
  2953. name);
  2954. } else {
  2955. return CGF.Builder.CreateGEP(ptr, indices, name);
  2956. }
  2957. }
  2958. static CharUnits getArrayElementAlign(CharUnits arrayAlign,
  2959. llvm::Value *idx,
  2960. CharUnits eltSize) {
  2961. // If we have a constant index, we can use the exact offset of the
  2962. // element we're accessing.
  2963. if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
  2964. CharUnits offset = constantIdx->getZExtValue() * eltSize;
  2965. return arrayAlign.alignmentAtOffset(offset);
  2966. // Otherwise, use the worst-case alignment for any element.
  2967. } else {
  2968. return arrayAlign.alignmentOfArrayElement(eltSize);
  2969. }
  2970. }
  2971. static QualType getFixedSizeElementType(const ASTContext &ctx,
  2972. const VariableArrayType *vla) {
  2973. QualType eltType;
  2974. do {
  2975. eltType = vla->getElementType();
  2976. } while ((vla = ctx.getAsVariableArrayType(eltType)));
  2977. return eltType;
  2978. }
  2979. static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
  2980. ArrayRef<llvm::Value *> indices,
  2981. QualType eltType, bool inbounds,
  2982. bool signedIndices, SourceLocation loc,
  2983. QualType *arrayType = nullptr,
  2984. const llvm::Twine &name = "arrayidx") {
  2985. // All the indices except that last must be zero.
  2986. #ifndef NDEBUG
  2987. for (auto idx : indices.drop_back())
  2988. assert(isa<llvm::ConstantInt>(idx) &&
  2989. cast<llvm::ConstantInt>(idx)->isZero());
  2990. #endif
  2991. // Determine the element size of the statically-sized base. This is
  2992. // the thing that the indices are expressed in terms of.
  2993. if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
  2994. eltType = getFixedSizeElementType(CGF.getContext(), vla);
  2995. }
  2996. // We can use that to compute the best alignment of the element.
  2997. CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
  2998. CharUnits eltAlign =
  2999. getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
  3000. llvm::Value *eltPtr;
  3001. auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back());
  3002. if (!CGF.IsInPreservedAIRegion || !LastIndex) {
  3003. eltPtr = emitArraySubscriptGEP(
  3004. CGF, addr.getPointer(), indices, inbounds, signedIndices,
  3005. loc, name);
  3006. } else {
  3007. // Remember the original array subscript for bpf target
  3008. unsigned idx = LastIndex->getZExtValue();
  3009. llvm::DIType *DbgInfo = nullptr;
  3010. if (arrayType)
  3011. DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc);
  3012. eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(addr.getPointer(),
  3013. indices.size() - 1,
  3014. idx, DbgInfo);
  3015. }
  3016. return Address(eltPtr, eltAlign);
  3017. }
  3018. LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
  3019. bool Accessed) {
  3020. // The index must always be an integer, which is not an aggregate. Emit it
  3021. // in lexical order (this complexity is, sadly, required by C++17).
  3022. llvm::Value *IdxPre =
  3023. (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
  3024. bool SignedIndices = false;
  3025. auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
  3026. auto *Idx = IdxPre;
  3027. if (E->getLHS() != E->getIdx()) {
  3028. assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
  3029. Idx = EmitScalarExpr(E->getIdx());
  3030. }
  3031. QualType IdxTy = E->getIdx()->getType();
  3032. bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
  3033. SignedIndices |= IdxSigned;
  3034. if (SanOpts.has(SanitizerKind::ArrayBounds))
  3035. EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
  3036. // Extend or truncate the index type to 32 or 64-bits.
  3037. if (Promote && Idx->getType() != IntPtrTy)
  3038. Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
  3039. return Idx;
  3040. };
  3041. IdxPre = nullptr;
  3042. // If the base is a vector type, then we are forming a vector element lvalue
  3043. // with this subscript.
  3044. if (E->getBase()->getType()->isVectorType() &&
  3045. !isa<ExtVectorElementExpr>(E->getBase())) {
  3046. // Emit the vector as an lvalue to get its address.
  3047. LValue LHS = EmitLValue(E->getBase());
  3048. auto *Idx = EmitIdxAfterBase(/*Promote*/false);
  3049. assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
  3050. return LValue::MakeVectorElt(LHS.getAddress(), Idx, E->getBase()->getType(),
  3051. LHS.getBaseInfo(), TBAAAccessInfo());
  3052. }
  3053. // All the other cases basically behave like simple offsetting.
  3054. // Handle the extvector case we ignored above.
  3055. if (isa<ExtVectorElementExpr>(E->getBase())) {
  3056. LValue LV = EmitLValue(E->getBase());
  3057. auto *Idx = EmitIdxAfterBase(/*Promote*/true);
  3058. Address Addr = EmitExtVectorElementLValue(LV);
  3059. QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
  3060. Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
  3061. SignedIndices, E->getExprLoc());
  3062. return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
  3063. CGM.getTBAAInfoForSubobject(LV, EltType));
  3064. }
  3065. LValueBaseInfo EltBaseInfo;
  3066. TBAAAccessInfo EltTBAAInfo;
  3067. Address Addr = Address::invalid();
  3068. if (const VariableArrayType *vla =
  3069. getContext().getAsVariableArrayType(E->getType())) {
  3070. // The base must be a pointer, which is not an aggregate. Emit
  3071. // it. It needs to be emitted first in case it's what captures
  3072. // the VLA bounds.
  3073. Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
  3074. auto *Idx = EmitIdxAfterBase(/*Promote*/true);
  3075. // The element count here is the total number of non-VLA elements.
  3076. llvm::Value *numElements = getVLASize(vla).NumElts;
  3077. // Effectively, the multiply by the VLA size is part of the GEP.
  3078. // GEP indexes are signed, and scaling an index isn't permitted to
  3079. // signed-overflow, so we use the same semantics for our explicit
  3080. // multiply. We suppress this if overflow is not undefined behavior.
  3081. if (getLangOpts().isSignedOverflowDefined()) {
  3082. Idx = Builder.CreateMul(Idx, numElements);
  3083. } else {
  3084. Idx = Builder.CreateNSWMul(Idx, numElements);
  3085. }
  3086. Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
  3087. !getLangOpts().isSignedOverflowDefined(),
  3088. SignedIndices, E->getExprLoc());
  3089. } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
  3090. // Indexing over an interface, as in "NSString *P; P[4];"
  3091. // Emit the base pointer.
  3092. Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
  3093. auto *Idx = EmitIdxAfterBase(/*Promote*/true);
  3094. CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
  3095. llvm::Value *InterfaceSizeVal =
  3096. llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
  3097. llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
  3098. // We don't necessarily build correct LLVM struct types for ObjC
  3099. // interfaces, so we can't rely on GEP to do this scaling
  3100. // correctly, so we need to cast to i8*. FIXME: is this actually
  3101. // true? A lot of other things in the fragile ABI would break...
  3102. llvm::Type *OrigBaseTy = Addr.getType();
  3103. Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
  3104. // Do the GEP.
  3105. CharUnits EltAlign =
  3106. getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
  3107. llvm::Value *EltPtr =
  3108. emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false,
  3109. SignedIndices, E->getExprLoc());
  3110. Addr = Address(EltPtr, EltAlign);
  3111. // Cast back.
  3112. Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
  3113. } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
  3114. // If this is A[i] where A is an array, the frontend will have decayed the
  3115. // base to be a ArrayToPointerDecay implicit cast. While correct, it is
  3116. // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
  3117. // "gep x, i" here. Emit one "gep A, 0, i".
  3118. assert(Array->getType()->isArrayType() &&
  3119. "Array to pointer decay must have array source type!");
  3120. LValue ArrayLV;
  3121. // For simple multidimensional array indexing, set the 'accessed' flag for
  3122. // better bounds-checking of the base expression.
  3123. if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
  3124. ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
  3125. else
  3126. ArrayLV = EmitLValue(Array);
  3127. auto *Idx = EmitIdxAfterBase(/*Promote*/true);
  3128. // Propagate the alignment from the array itself to the result.
  3129. QualType arrayType = Array->getType();
  3130. Addr = emitArraySubscriptGEP(
  3131. *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
  3132. E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
  3133. E->getExprLoc(), &arrayType);
  3134. EltBaseInfo = ArrayLV.getBaseInfo();
  3135. EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
  3136. } else {
  3137. // The base must be a pointer; emit it with an estimate of its alignment.
  3138. Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
  3139. auto *Idx = EmitIdxAfterBase(/*Promote*/true);
  3140. QualType ptrType = E->getBase()->getType();
  3141. Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
  3142. !getLangOpts().isSignedOverflowDefined(),
  3143. SignedIndices, E->getExprLoc(), &ptrType);
  3144. }
  3145. LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
  3146. if (getLangOpts().ObjC &&
  3147. getLangOpts().getGC() != LangOptions::NonGC) {
  3148. LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
  3149. setObjCGCLValueClass(getContext(), E, LV);
  3150. }
  3151. return LV;
  3152. }
  3153. static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
  3154. LValueBaseInfo &BaseInfo,
  3155. TBAAAccessInfo &TBAAInfo,
  3156. QualType BaseTy, QualType ElTy,
  3157. bool IsLowerBound) {
  3158. LValue BaseLVal;
  3159. if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
  3160. BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
  3161. if (BaseTy->isArrayType()) {
  3162. Address Addr = BaseLVal.getAddress();
  3163. BaseInfo = BaseLVal.getBaseInfo();
  3164. // If the array type was an incomplete type, we need to make sure
  3165. // the decay ends up being the right type.
  3166. llvm::Type *NewTy = CGF.ConvertType(BaseTy);
  3167. Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
  3168. // Note that VLA pointers are always decayed, so we don't need to do
  3169. // anything here.
  3170. if (!BaseTy->isVariableArrayType()) {
  3171. assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
  3172. "Expected pointer to array");
  3173. Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
  3174. }
  3175. return CGF.Builder.CreateElementBitCast(Addr,
  3176. CGF.ConvertTypeForMem(ElTy));
  3177. }
  3178. LValueBaseInfo TypeBaseInfo;
  3179. TBAAAccessInfo TypeTBAAInfo;
  3180. CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeBaseInfo,
  3181. &TypeTBAAInfo);
  3182. BaseInfo.mergeForCast(TypeBaseInfo);
  3183. TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
  3184. return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
  3185. }
  3186. return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
  3187. }
  3188. LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
  3189. bool IsLowerBound) {
  3190. QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase());
  3191. QualType ResultExprTy;
  3192. if (auto *AT = getContext().getAsArrayType(BaseTy))
  3193. ResultExprTy = AT->getElementType();
  3194. else
  3195. ResultExprTy = BaseTy->getPointeeType();
  3196. llvm::Value *Idx = nullptr;
  3197. if (IsLowerBound || E->getColonLoc().isInvalid()) {
  3198. // Requesting lower bound or upper bound, but without provided length and
  3199. // without ':' symbol for the default length -> length = 1.
  3200. // Idx = LowerBound ?: 0;
  3201. if (auto *LowerBound = E->getLowerBound()) {
  3202. Idx = Builder.CreateIntCast(
  3203. EmitScalarExpr(LowerBound), IntPtrTy,
  3204. LowerBound->getType()->hasSignedIntegerRepresentation());
  3205. } else
  3206. Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
  3207. } else {
  3208. // Try to emit length or lower bound as constant. If this is possible, 1
  3209. // is subtracted from constant length or lower bound. Otherwise, emit LLVM
  3210. // IR (LB + Len) - 1.
  3211. auto &C = CGM.getContext();
  3212. auto *Length = E->getLength();
  3213. llvm::APSInt ConstLength;
  3214. if (Length) {
  3215. // Idx = LowerBound + Length - 1;
  3216. if (Length->isIntegerConstantExpr(ConstLength, C)) {
  3217. ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
  3218. Length = nullptr;
  3219. }
  3220. auto *LowerBound = E->getLowerBound();
  3221. llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
  3222. if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
  3223. ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
  3224. LowerBound = nullptr;
  3225. }
  3226. if (!Length)
  3227. --ConstLength;
  3228. else if (!LowerBound)
  3229. --ConstLowerBound;
  3230. if (Length || LowerBound) {
  3231. auto *LowerBoundVal =
  3232. LowerBound
  3233. ? Builder.CreateIntCast(
  3234. EmitScalarExpr(LowerBound), IntPtrTy,
  3235. LowerBound->getType()->hasSignedIntegerRepresentation())
  3236. : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
  3237. auto *LengthVal =
  3238. Length
  3239. ? Builder.CreateIntCast(
  3240. EmitScalarExpr(Length), IntPtrTy,
  3241. Length->getType()->hasSignedIntegerRepresentation())
  3242. : llvm::ConstantInt::get(IntPtrTy, ConstLength);
  3243. Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
  3244. /*HasNUW=*/false,
  3245. !getLangOpts().isSignedOverflowDefined());
  3246. if (Length && LowerBound) {
  3247. Idx = Builder.CreateSub(
  3248. Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
  3249. /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
  3250. }
  3251. } else
  3252. Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
  3253. } else {
  3254. // Idx = ArraySize - 1;
  3255. QualType ArrayTy = BaseTy->isPointerType()
  3256. ? E->getBase()->IgnoreParenImpCasts()->getType()
  3257. : BaseTy;
  3258. if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
  3259. Length = VAT->getSizeExpr();
  3260. if (Length->isIntegerConstantExpr(ConstLength, C))
  3261. Length = nullptr;
  3262. } else {
  3263. auto *CAT = C.getAsConstantArrayType(ArrayTy);
  3264. ConstLength = CAT->getSize();
  3265. }
  3266. if (Length) {
  3267. auto *LengthVal = Builder.CreateIntCast(
  3268. EmitScalarExpr(Length), IntPtrTy,
  3269. Length->getType()->hasSignedIntegerRepresentation());
  3270. Idx = Builder.CreateSub(
  3271. LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
  3272. /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
  3273. } else {
  3274. ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
  3275. --ConstLength;
  3276. Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
  3277. }
  3278. }
  3279. }
  3280. assert(Idx);
  3281. Address EltPtr = Address::invalid();
  3282. LValueBaseInfo BaseInfo;
  3283. TBAAAccessInfo TBAAInfo;
  3284. if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
  3285. // The base must be a pointer, which is not an aggregate. Emit
  3286. // it. It needs to be emitted first in case it's what captures
  3287. // the VLA bounds.
  3288. Address Base =
  3289. emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
  3290. BaseTy, VLA->getElementType(), IsLowerBound);
  3291. // The element count here is the total number of non-VLA elements.
  3292. llvm::Value *NumElements = getVLASize(VLA).NumElts;
  3293. // Effectively, the multiply by the VLA size is part of the GEP.
  3294. // GEP indexes are signed, and scaling an index isn't permitted to
  3295. // signed-overflow, so we use the same semantics for our explicit
  3296. // multiply. We suppress this if overflow is not undefined behavior.
  3297. if (getLangOpts().isSignedOverflowDefined())
  3298. Idx = Builder.CreateMul(Idx, NumElements);
  3299. else
  3300. Idx = Builder.CreateNSWMul(Idx, NumElements);
  3301. EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
  3302. !getLangOpts().isSignedOverflowDefined(),
  3303. /*signedIndices=*/false, E->getExprLoc());
  3304. } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
  3305. // If this is A[i] where A is an array, the frontend will have decayed the
  3306. // base to be a ArrayToPointerDecay implicit cast. While correct, it is
  3307. // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
  3308. // "gep x, i" here. Emit one "gep A, 0, i".
  3309. assert(Array->getType()->isArrayType() &&
  3310. "Array to pointer decay must have array source type!");
  3311. LValue ArrayLV;
  3312. // For simple multidimensional array indexing, set the 'accessed' flag for
  3313. // better bounds-checking of the base expression.
  3314. if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
  3315. ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
  3316. else
  3317. ArrayLV = EmitLValue(Array);
  3318. // Propagate the alignment from the array itself to the result.
  3319. EltPtr = emitArraySubscriptGEP(
  3320. *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
  3321. ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
  3322. /*signedIndices=*/false, E->getExprLoc());
  3323. BaseInfo = ArrayLV.getBaseInfo();
  3324. TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
  3325. } else {
  3326. Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
  3327. TBAAInfo, BaseTy, ResultExprTy,
  3328. IsLowerBound);
  3329. EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
  3330. !getLangOpts().isSignedOverflowDefined(),
  3331. /*signedIndices=*/false, E->getExprLoc());
  3332. }
  3333. return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
  3334. }
  3335. LValue CodeGenFunction::
  3336. EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
  3337. // Emit the base vector as an l-value.
  3338. LValue Base;
  3339. // ExtVectorElementExpr's base can either be a vector or pointer to vector.
  3340. if (E->isArrow()) {
  3341. // If it is a pointer to a vector, emit the address and form an lvalue with
  3342. // it.
  3343. LValueBaseInfo BaseInfo;
  3344. TBAAAccessInfo TBAAInfo;
  3345. Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
  3346. const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
  3347. Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
  3348. Base.getQuals().removeObjCGCAttr();
  3349. } else if (E->getBase()->isGLValue()) {
  3350. // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
  3351. // emit the base as an lvalue.
  3352. assert(E->getBase()->getType()->isVectorType());
  3353. Base = EmitLValue(E->getBase());
  3354. } else {
  3355. // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
  3356. assert(E->getBase()->getType()->isVectorType() &&
  3357. "Result must be a vector");
  3358. llvm::Value *Vec = EmitScalarExpr(E->getBase());
  3359. // Store the vector to memory (because LValue wants an address).
  3360. Address VecMem = CreateMemTemp(E->getBase()->getType());
  3361. Builder.CreateStore(Vec, VecMem);
  3362. Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
  3363. AlignmentSource::Decl);
  3364. }
  3365. QualType type =
  3366. E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
  3367. // Encode the element access list into a vector of unsigned indices.
  3368. SmallVector<uint32_t, 4> Indices;
  3369. E->getEncodedElementAccess(Indices);
  3370. if (Base.isSimple()) {
  3371. llvm::Constant *CV =
  3372. llvm::ConstantDataVector::get(getLLVMContext(), Indices);
  3373. return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
  3374. Base.getBaseInfo(), TBAAAccessInfo());
  3375. }
  3376. assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
  3377. llvm::Constant *BaseElts = Base.getExtVectorElts();
  3378. SmallVector<llvm::Constant *, 4> CElts;
  3379. for (unsigned i = 0, e = Indices.size(); i != e; ++i)
  3380. CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
  3381. llvm::Constant *CV = llvm::ConstantVector::get(CElts);
  3382. return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
  3383. Base.getBaseInfo(), TBAAAccessInfo());
  3384. }
  3385. LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
  3386. if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
  3387. EmitIgnoredExpr(E->getBase());
  3388. return EmitDeclRefLValue(DRE);
  3389. }
  3390. Expr *BaseExpr = E->getBase();
  3391. // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
  3392. LValue BaseLV;
  3393. if (E->isArrow()) {
  3394. LValueBaseInfo BaseInfo;
  3395. TBAAAccessInfo TBAAInfo;
  3396. Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
  3397. QualType PtrTy = BaseExpr->getType()->getPointeeType();
  3398. SanitizerSet SkippedChecks;
  3399. bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
  3400. if (IsBaseCXXThis)
  3401. SkippedChecks.set(SanitizerKind::Alignment, true);
  3402. if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
  3403. SkippedChecks.set(SanitizerKind::Null, true);
  3404. EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
  3405. /*Alignment=*/CharUnits::Zero(), SkippedChecks);
  3406. BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
  3407. } else
  3408. BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
  3409. NamedDecl *ND = E->getMemberDecl();
  3410. if (auto *Field = dyn_cast<FieldDecl>(ND)) {
  3411. LValue LV = EmitLValueForField(BaseLV, Field);
  3412. setObjCGCLValueClass(getContext(), E, LV);
  3413. return LV;
  3414. }
  3415. if (const auto *FD = dyn_cast<FunctionDecl>(ND))
  3416. return EmitFunctionDeclLValue(*this, E, FD);
  3417. llvm_unreachable("Unhandled member declaration!");
  3418. }
  3419. /// Given that we are currently emitting a lambda, emit an l-value for
  3420. /// one of its members.
  3421. LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
  3422. assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
  3423. assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
  3424. QualType LambdaTagType =
  3425. getContext().getTagDeclType(Field->getParent());
  3426. LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
  3427. return EmitLValueForField(LambdaLV, Field);
  3428. }
  3429. /// Get the field index in the debug info. The debug info structure/union
  3430. /// will ignore the unnamed bitfields.
  3431. unsigned CodeGenFunction::getDebugInfoFIndex(const RecordDecl *Rec,
  3432. unsigned FieldIndex) {
  3433. unsigned I = 0, Skipped = 0;
  3434. for (auto F : Rec->getDefinition()->fields()) {
  3435. if (I == FieldIndex)
  3436. break;
  3437. if (F->isUnnamedBitfield())
  3438. Skipped++;
  3439. I++;
  3440. }
  3441. return FieldIndex - Skipped;
  3442. }
  3443. /// Get the address of a zero-sized field within a record. The resulting
  3444. /// address doesn't necessarily have the right type.
  3445. static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
  3446. const FieldDecl *Field) {
  3447. CharUnits Offset = CGF.getContext().toCharUnitsFromBits(
  3448. CGF.getContext().getFieldOffset(Field));
  3449. if (Offset.isZero())
  3450. return Base;
  3451. Base = CGF.Builder.CreateElementBitCast(Base, CGF.Int8Ty);
  3452. return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
  3453. }
  3454. /// Drill down to the storage of a field without walking into
  3455. /// reference types.
  3456. ///
  3457. /// The resulting address doesn't necessarily have the right type.
  3458. static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
  3459. const FieldDecl *field) {
  3460. if (field->isZeroSize(CGF.getContext()))
  3461. return emitAddrOfZeroSizeField(CGF, base, field);
  3462. const RecordDecl *rec = field->getParent();
  3463. unsigned idx =
  3464. CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
  3465. return CGF.Builder.CreateStructGEP(base, idx, field->getName());
  3466. }
  3467. static Address emitPreserveStructAccess(CodeGenFunction &CGF, Address base,
  3468. const FieldDecl *field) {
  3469. const RecordDecl *rec = field->getParent();
  3470. llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateRecordType(
  3471. CGF.getContext().getRecordType(rec), rec->getLocation());
  3472. unsigned idx =
  3473. CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
  3474. return CGF.Builder.CreatePreserveStructAccessIndex(
  3475. base, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo);
  3476. }
  3477. static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
  3478. const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
  3479. if (!RD)
  3480. return false;
  3481. if (RD->isDynamicClass())
  3482. return true;
  3483. for (const auto &Base : RD->bases())
  3484. if (hasAnyVptr(Base.getType(), Context))
  3485. return true;
  3486. for (const FieldDecl *Field : RD->fields())
  3487. if (hasAnyVptr(Field->getType(), Context))
  3488. return true;
  3489. return false;
  3490. }
  3491. LValue CodeGenFunction::EmitLValueForField(LValue base,
  3492. const FieldDecl *field) {
  3493. LValueBaseInfo BaseInfo = base.getBaseInfo();
  3494. if (field->isBitField()) {
  3495. const CGRecordLayout &RL =
  3496. CGM.getTypes().getCGRecordLayout(field->getParent());
  3497. const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
  3498. Address Addr = base.getAddress();
  3499. unsigned Idx = RL.getLLVMFieldNo(field);
  3500. if (!IsInPreservedAIRegion) {
  3501. if (Idx != 0)
  3502. // For structs, we GEP to the field that the record layout suggests.
  3503. Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
  3504. } else {
  3505. const RecordDecl *rec = field->getParent();
  3506. llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
  3507. getContext().getRecordType(rec), rec->getLocation());
  3508. Addr = Builder.CreatePreserveStructAccessIndex(Addr, Idx,
  3509. getDebugInfoFIndex(rec, field->getFieldIndex()),
  3510. DbgInfo);
  3511. }
  3512. // Get the access type.
  3513. llvm::Type *FieldIntTy =
  3514. llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
  3515. if (Addr.getElementType() != FieldIntTy)
  3516. Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
  3517. QualType fieldType =
  3518. field->getType().withCVRQualifiers(base.getVRQualifiers());
  3519. // TODO: Support TBAA for bit fields.
  3520. LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
  3521. return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
  3522. TBAAAccessInfo());
  3523. }
  3524. // Fields of may-alias structures are may-alias themselves.
  3525. // FIXME: this should get propagated down through anonymous structs
  3526. // and unions.
  3527. QualType FieldType = field->getType();
  3528. const RecordDecl *rec = field->getParent();
  3529. AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
  3530. LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
  3531. TBAAAccessInfo FieldTBAAInfo;
  3532. if (base.getTBAAInfo().isMayAlias() ||
  3533. rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
  3534. FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
  3535. } else if (rec->isUnion()) {
  3536. // TODO: Support TBAA for unions.
  3537. FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
  3538. } else {
  3539. // If no base type been assigned for the base access, then try to generate
  3540. // one for this base lvalue.
  3541. FieldTBAAInfo = base.getTBAAInfo();
  3542. if (!FieldTBAAInfo.BaseType) {
  3543. FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
  3544. assert(!FieldTBAAInfo.Offset &&
  3545. "Nonzero offset for an access with no base type!");
  3546. }
  3547. // Adjust offset to be relative to the base type.
  3548. const ASTRecordLayout &Layout =
  3549. getContext().getASTRecordLayout(field->getParent());
  3550. unsigned CharWidth = getContext().getCharWidth();
  3551. if (FieldTBAAInfo.BaseType)
  3552. FieldTBAAInfo.Offset +=
  3553. Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
  3554. // Update the final access type and size.
  3555. FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
  3556. FieldTBAAInfo.Size =
  3557. getContext().getTypeSizeInChars(FieldType).getQuantity();
  3558. }
  3559. Address addr = base.getAddress();
  3560. if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
  3561. if (CGM.getCodeGenOpts().StrictVTablePointers &&
  3562. ClassDef->isDynamicClass()) {
  3563. // Getting to any field of dynamic object requires stripping dynamic
  3564. // information provided by invariant.group. This is because accessing
  3565. // fields may leak the real address of dynamic object, which could result
  3566. // in miscompilation when leaked pointer would be compared.
  3567. auto *stripped = Builder.CreateStripInvariantGroup(addr.getPointer());
  3568. addr = Address(stripped, addr.getAlignment());
  3569. }
  3570. }
  3571. unsigned RecordCVR = base.getVRQualifiers();
  3572. if (rec->isUnion()) {
  3573. // For unions, there is no pointer adjustment.
  3574. if (CGM.getCodeGenOpts().StrictVTablePointers &&
  3575. hasAnyVptr(FieldType, getContext()))
  3576. // Because unions can easily skip invariant.barriers, we need to add
  3577. // a barrier every time CXXRecord field with vptr is referenced.
  3578. addr = Address(Builder.CreateLaunderInvariantGroup(addr.getPointer()),
  3579. addr.getAlignment());
  3580. if (IsInPreservedAIRegion) {
  3581. // Remember the original union field index
  3582. llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
  3583. getContext().getRecordType(rec), rec->getLocation());
  3584. addr = Address(
  3585. Builder.CreatePreserveUnionAccessIndex(
  3586. addr.getPointer(), getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo),
  3587. addr.getAlignment());
  3588. }
  3589. if (FieldType->isReferenceType())
  3590. addr = Builder.CreateElementBitCast(
  3591. addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
  3592. } else {
  3593. if (!IsInPreservedAIRegion)
  3594. // For structs, we GEP to the field that the record layout suggests.
  3595. addr = emitAddrOfFieldStorage(*this, addr, field);
  3596. else
  3597. // Remember the original struct field index
  3598. addr = emitPreserveStructAccess(*this, addr, field);
  3599. }
  3600. // If this is a reference field, load the reference right now.
  3601. if (FieldType->isReferenceType()) {
  3602. LValue RefLVal =
  3603. MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
  3604. if (RecordCVR & Qualifiers::Volatile)
  3605. RefLVal.getQuals().addVolatile();
  3606. addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
  3607. // Qualifiers on the struct don't apply to the referencee.
  3608. RecordCVR = 0;
  3609. FieldType = FieldType->getPointeeType();
  3610. }
  3611. // Make sure that the address is pointing to the right type. This is critical
  3612. // for both unions and structs. A union needs a bitcast, a struct element
  3613. // will need a bitcast if the LLVM type laid out doesn't match the desired
  3614. // type.
  3615. addr = Builder.CreateElementBitCast(
  3616. addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
  3617. if (field->hasAttr<AnnotateAttr>())
  3618. addr = EmitFieldAnnotations(field, addr);
  3619. LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
  3620. LV.getQuals().addCVRQualifiers(RecordCVR);
  3621. // __weak attribute on a field is ignored.
  3622. if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
  3623. LV.getQuals().removeObjCGCAttr();
  3624. return LV;
  3625. }
  3626. LValue
  3627. CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
  3628. const FieldDecl *Field) {
  3629. QualType FieldType = Field->getType();
  3630. if (!FieldType->isReferenceType())
  3631. return EmitLValueForField(Base, Field);
  3632. Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
  3633. // Make sure that the address is pointing to the right type.
  3634. llvm::Type *llvmType = ConvertTypeForMem(FieldType);
  3635. V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
  3636. // TODO: Generate TBAA information that describes this access as a structure
  3637. // member access and not just an access to an object of the field's type. This
  3638. // should be similar to what we do in EmitLValueForField().
  3639. LValueBaseInfo BaseInfo = Base.getBaseInfo();
  3640. AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
  3641. LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
  3642. return MakeAddrLValue(V, FieldType, FieldBaseInfo,
  3643. CGM.getTBAAInfoForSubobject(Base, FieldType));
  3644. }
  3645. LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
  3646. if (E->isFileScope()) {
  3647. ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
  3648. return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
  3649. }
  3650. if (E->getType()->isVariablyModifiedType())
  3651. // make sure to emit the VLA size.
  3652. EmitVariablyModifiedType(E->getType());
  3653. Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
  3654. const Expr *InitExpr = E->getInitializer();
  3655. LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
  3656. EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
  3657. /*Init*/ true);
  3658. return Result;
  3659. }
  3660. LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
  3661. if (!E->isGLValue())
  3662. // Initializing an aggregate temporary in C++11: T{...}.
  3663. return EmitAggExprToLValue(E);
  3664. // An lvalue initializer list must be initializing a reference.
  3665. assert(E->isTransparent() && "non-transparent glvalue init list");
  3666. return EmitLValue(E->getInit(0));
  3667. }
  3668. /// Emit the operand of a glvalue conditional operator. This is either a glvalue
  3669. /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
  3670. /// LValue is returned and the current block has been terminated.
  3671. static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
  3672. const Expr *Operand) {
  3673. if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
  3674. CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
  3675. return None;
  3676. }
  3677. return CGF.EmitLValue(Operand);
  3678. }
  3679. LValue CodeGenFunction::
  3680. EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
  3681. if (!expr->isGLValue()) {
  3682. // ?: here should be an aggregate.
  3683. assert(hasAggregateEvaluationKind(expr->getType()) &&
  3684. "Unexpected conditional operator!");
  3685. return EmitAggExprToLValue(expr);
  3686. }
  3687. OpaqueValueMapping binding(*this, expr);
  3688. const Expr *condExpr = expr->getCond();
  3689. bool CondExprBool;
  3690. if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
  3691. const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
  3692. if (!CondExprBool) std::swap(live, dead);
  3693. if (!ContainsLabel(dead)) {
  3694. // If the true case is live, we need to track its region.
  3695. if (CondExprBool)
  3696. incrementProfileCounter(expr);
  3697. return EmitLValue(live);
  3698. }
  3699. }
  3700. llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
  3701. llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
  3702. llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
  3703. ConditionalEvaluation eval(*this);
  3704. EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
  3705. // Any temporaries created here are conditional.
  3706. EmitBlock(lhsBlock);
  3707. incrementProfileCounter(expr);
  3708. eval.begin(*this);
  3709. Optional<LValue> lhs =
  3710. EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
  3711. eval.end(*this);
  3712. if (lhs && !lhs->isSimple())
  3713. return EmitUnsupportedLValue(expr, "conditional operator");
  3714. lhsBlock = Builder.GetInsertBlock();
  3715. if (lhs)
  3716. Builder.CreateBr(contBlock);
  3717. // Any temporaries created here are conditional.
  3718. EmitBlock(rhsBlock);
  3719. eval.begin(*this);
  3720. Optional<LValue> rhs =
  3721. EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
  3722. eval.end(*this);
  3723. if (rhs && !rhs->isSimple())
  3724. return EmitUnsupportedLValue(expr, "conditional operator");
  3725. rhsBlock = Builder.GetInsertBlock();
  3726. EmitBlock(contBlock);
  3727. if (lhs && rhs) {
  3728. llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
  3729. 2, "cond-lvalue");
  3730. phi->addIncoming(lhs->getPointer(), lhsBlock);
  3731. phi->addIncoming(rhs->getPointer(), rhsBlock);
  3732. Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
  3733. AlignmentSource alignSource =
  3734. std::max(lhs->getBaseInfo().getAlignmentSource(),
  3735. rhs->getBaseInfo().getAlignmentSource());
  3736. TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
  3737. lhs->getTBAAInfo(), rhs->getTBAAInfo());
  3738. return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
  3739. TBAAInfo);
  3740. } else {
  3741. assert((lhs || rhs) &&
  3742. "both operands of glvalue conditional are throw-expressions?");
  3743. return lhs ? *lhs : *rhs;
  3744. }
  3745. }
  3746. /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
  3747. /// type. If the cast is to a reference, we can have the usual lvalue result,
  3748. /// otherwise if a cast is needed by the code generator in an lvalue context,
  3749. /// then it must mean that we need the address of an aggregate in order to
  3750. /// access one of its members. This can happen for all the reasons that casts
  3751. /// are permitted with aggregate result, including noop aggregate casts, and
  3752. /// cast from scalar to union.
  3753. LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
  3754. switch (E->getCastKind()) {
  3755. case CK_ToVoid:
  3756. case CK_BitCast:
  3757. case CK_LValueToRValueBitCast:
  3758. case CK_ArrayToPointerDecay:
  3759. case CK_FunctionToPointerDecay:
  3760. case CK_NullToMemberPointer:
  3761. case CK_NullToPointer:
  3762. case CK_IntegralToPointer:
  3763. case CK_PointerToIntegral:
  3764. case CK_PointerToBoolean:
  3765. case CK_VectorSplat:
  3766. case CK_IntegralCast:
  3767. case CK_BooleanToSignedIntegral:
  3768. case CK_IntegralToBoolean:
  3769. case CK_IntegralToFloating:
  3770. case CK_FloatingToIntegral:
  3771. case CK_FloatingToBoolean:
  3772. case CK_FloatingCast:
  3773. case CK_FloatingRealToComplex:
  3774. case CK_FloatingComplexToReal:
  3775. case CK_FloatingComplexToBoolean:
  3776. case CK_FloatingComplexCast:
  3777. case CK_FloatingComplexToIntegralComplex:
  3778. case CK_IntegralRealToComplex:
  3779. case CK_IntegralComplexToReal:
  3780. case CK_IntegralComplexToBoolean:
  3781. case CK_IntegralComplexCast:
  3782. case CK_IntegralComplexToFloatingComplex:
  3783. case CK_DerivedToBaseMemberPointer:
  3784. case CK_BaseToDerivedMemberPointer:
  3785. case CK_MemberPointerToBoolean:
  3786. case CK_ReinterpretMemberPointer:
  3787. case CK_AnyPointerToBlockPointerCast:
  3788. case CK_ARCProduceObject:
  3789. case CK_ARCConsumeObject:
  3790. case CK_ARCReclaimReturnedObject:
  3791. case CK_ARCExtendBlockObject:
  3792. case CK_CopyAndAutoreleaseBlockObject:
  3793. case CK_IntToOCLSampler:
  3794. case CK_FixedPointCast:
  3795. case CK_FixedPointToBoolean:
  3796. case CK_FixedPointToIntegral:
  3797. case CK_IntegralToFixedPoint:
  3798. return EmitUnsupportedLValue(E, "unexpected cast lvalue");
  3799. case CK_Dependent:
  3800. llvm_unreachable("dependent cast kind in IR gen!");
  3801. case CK_BuiltinFnToFnPtr:
  3802. llvm_unreachable("builtin functions are handled elsewhere");
  3803. // These are never l-values; just use the aggregate emission code.
  3804. case CK_NonAtomicToAtomic:
  3805. case CK_AtomicToNonAtomic:
  3806. return EmitAggExprToLValue(E);
  3807. case CK_Dynamic: {
  3808. LValue LV = EmitLValue(E->getSubExpr());
  3809. Address V = LV.getAddress();
  3810. const auto *DCE = cast<CXXDynamicCastExpr>(E);
  3811. return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
  3812. }
  3813. case CK_ConstructorConversion:
  3814. case CK_UserDefinedConversion:
  3815. case CK_CPointerToObjCPointerCast:
  3816. case CK_BlockPointerToObjCPointerCast:
  3817. case CK_NoOp:
  3818. case CK_LValueToRValue:
  3819. return EmitLValue(E->getSubExpr());
  3820. case CK_UncheckedDerivedToBase:
  3821. case CK_DerivedToBase: {
  3822. const RecordType *DerivedClassTy =
  3823. E->getSubExpr()->getType()->getAs<RecordType>();
  3824. auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
  3825. LValue LV = EmitLValue(E->getSubExpr());
  3826. Address This = LV.getAddress();
  3827. // Perform the derived-to-base conversion
  3828. Address Base = GetAddressOfBaseClass(
  3829. This, DerivedClassDecl, E->path_begin(), E->path_end(),
  3830. /*NullCheckValue=*/false, E->getExprLoc());
  3831. // TODO: Support accesses to members of base classes in TBAA. For now, we
  3832. // conservatively pretend that the complete object is of the base class
  3833. // type.
  3834. return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
  3835. CGM.getTBAAInfoForSubobject(LV, E->getType()));
  3836. }
  3837. case CK_ToUnion:
  3838. return EmitAggExprToLValue(E);
  3839. case CK_BaseToDerived: {
  3840. const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
  3841. auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
  3842. LValue LV = EmitLValue(E->getSubExpr());
  3843. // Perform the base-to-derived conversion
  3844. Address Derived =
  3845. GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
  3846. E->path_begin(), E->path_end(),
  3847. /*NullCheckValue=*/false);
  3848. // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
  3849. // performed and the object is not of the derived type.
  3850. if (sanitizePerformTypeCheck())
  3851. EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
  3852. Derived.getPointer(), E->getType());
  3853. if (SanOpts.has(SanitizerKind::CFIDerivedCast))
  3854. EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
  3855. /*MayBeNull=*/false, CFITCK_DerivedCast,
  3856. E->getBeginLoc());
  3857. return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
  3858. CGM.getTBAAInfoForSubobject(LV, E->getType()));
  3859. }
  3860. case CK_LValueBitCast: {
  3861. // This must be a reinterpret_cast (or c-style equivalent).
  3862. const auto *CE = cast<ExplicitCastExpr>(E);
  3863. CGM.EmitExplicitCastExprType(CE, this);
  3864. LValue LV = EmitLValue(E->getSubExpr());
  3865. Address V = Builder.CreateBitCast(LV.getAddress(),
  3866. ConvertType(CE->getTypeAsWritten()));
  3867. if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
  3868. EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
  3869. /*MayBeNull=*/false, CFITCK_UnrelatedCast,
  3870. E->getBeginLoc());
  3871. return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
  3872. CGM.getTBAAInfoForSubobject(LV, E->getType()));
  3873. }
  3874. case CK_AddressSpaceConversion: {
  3875. LValue LV = EmitLValue(E->getSubExpr());
  3876. QualType DestTy = getContext().getPointerType(E->getType());
  3877. llvm::Value *V = getTargetHooks().performAddrSpaceCast(
  3878. *this, LV.getPointer(), E->getSubExpr()->getType().getAddressSpace(),
  3879. E->getType().getAddressSpace(), ConvertType(DestTy));
  3880. return MakeAddrLValue(Address(V, LV.getAddress().getAlignment()),
  3881. E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
  3882. }
  3883. case CK_ObjCObjectLValueCast: {
  3884. LValue LV = EmitLValue(E->getSubExpr());
  3885. Address V = Builder.CreateElementBitCast(LV.getAddress(),
  3886. ConvertType(E->getType()));
  3887. return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
  3888. CGM.getTBAAInfoForSubobject(LV, E->getType()));
  3889. }
  3890. case CK_ZeroToOCLOpaqueType:
  3891. llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
  3892. }
  3893. llvm_unreachable("Unhandled lvalue cast kind?");
  3894. }
  3895. LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
  3896. assert(OpaqueValueMappingData::shouldBindAsLValue(e));
  3897. return getOrCreateOpaqueLValueMapping(e);
  3898. }
  3899. LValue
  3900. CodeGenFunction::getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e) {
  3901. assert(OpaqueValueMapping::shouldBindAsLValue(e));
  3902. llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
  3903. it = OpaqueLValues.find(e);
  3904. if (it != OpaqueLValues.end())
  3905. return it->second;
  3906. assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
  3907. return EmitLValue(e->getSourceExpr());
  3908. }
  3909. RValue
  3910. CodeGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) {
  3911. assert(!OpaqueValueMapping::shouldBindAsLValue(e));
  3912. llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
  3913. it = OpaqueRValues.find(e);
  3914. if (it != OpaqueRValues.end())
  3915. return it->second;
  3916. assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
  3917. return EmitAnyExpr(e->getSourceExpr());
  3918. }
  3919. RValue CodeGenFunction::EmitRValueForField(LValue LV,
  3920. const FieldDecl *FD,
  3921. SourceLocation Loc) {
  3922. QualType FT = FD->getType();
  3923. LValue FieldLV = EmitLValueForField(LV, FD);
  3924. switch (getEvaluationKind(FT)) {
  3925. case TEK_Complex:
  3926. return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
  3927. case TEK_Aggregate:
  3928. return FieldLV.asAggregateRValue();
  3929. case TEK_Scalar:
  3930. // This routine is used to load fields one-by-one to perform a copy, so
  3931. // don't load reference fields.
  3932. if (FD->getType()->isReferenceType())
  3933. return RValue::get(FieldLV.getPointer());
  3934. return EmitLoadOfLValue(FieldLV, Loc);
  3935. }
  3936. llvm_unreachable("bad evaluation kind");
  3937. }
  3938. //===--------------------------------------------------------------------===//
  3939. // Expression Emission
  3940. //===--------------------------------------------------------------------===//
  3941. RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
  3942. ReturnValueSlot ReturnValue) {
  3943. // Builtins never have block type.
  3944. if (E->getCallee()->getType()->isBlockPointerType())
  3945. return EmitBlockCallExpr(E, ReturnValue);
  3946. if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
  3947. return EmitCXXMemberCallExpr(CE, ReturnValue);
  3948. if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
  3949. return EmitCUDAKernelCallExpr(CE, ReturnValue);
  3950. if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
  3951. if (const CXXMethodDecl *MD =
  3952. dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
  3953. return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
  3954. CGCallee callee = EmitCallee(E->getCallee());
  3955. if (callee.isBuiltin()) {
  3956. return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
  3957. E, ReturnValue);
  3958. }
  3959. if (callee.isPseudoDestructor()) {
  3960. return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
  3961. }
  3962. return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
  3963. }
  3964. /// Emit a CallExpr without considering whether it might be a subclass.
  3965. RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
  3966. ReturnValueSlot ReturnValue) {
  3967. CGCallee Callee = EmitCallee(E->getCallee());
  3968. return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
  3969. }
  3970. static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
  3971. if (auto builtinID = FD->getBuiltinID()) {
  3972. return CGCallee::forBuiltin(builtinID, FD);
  3973. }
  3974. llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
  3975. return CGCallee::forDirect(calleePtr, GlobalDecl(FD));
  3976. }
  3977. CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
  3978. E = E->IgnoreParens();
  3979. // Look through function-to-pointer decay.
  3980. if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
  3981. if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
  3982. ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
  3983. return EmitCallee(ICE->getSubExpr());
  3984. }
  3985. // Resolve direct calls.
  3986. } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
  3987. if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
  3988. return EmitDirectCallee(*this, FD);
  3989. }
  3990. } else if (auto ME = dyn_cast<MemberExpr>(E)) {
  3991. if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
  3992. EmitIgnoredExpr(ME->getBase());
  3993. return EmitDirectCallee(*this, FD);
  3994. }
  3995. // Look through template substitutions.
  3996. } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
  3997. return EmitCallee(NTTP->getReplacement());
  3998. // Treat pseudo-destructor calls differently.
  3999. } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
  4000. return CGCallee::forPseudoDestructor(PDE);
  4001. }
  4002. // Otherwise, we have an indirect reference.
  4003. llvm::Value *calleePtr;
  4004. QualType functionType;
  4005. if (auto ptrType = E->getType()->getAs<PointerType>()) {
  4006. calleePtr = EmitScalarExpr(E);
  4007. functionType = ptrType->getPointeeType();
  4008. } else {
  4009. functionType = E->getType();
  4010. calleePtr = EmitLValue(E).getPointer();
  4011. }
  4012. assert(functionType->isFunctionType());
  4013. GlobalDecl GD;
  4014. if (const auto *VD =
  4015. dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
  4016. GD = GlobalDecl(VD);
  4017. CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
  4018. CGCallee callee(calleeInfo, calleePtr);
  4019. return callee;
  4020. }
  4021. LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
  4022. // Comma expressions just emit their LHS then their RHS as an l-value.
  4023. if (E->getOpcode() == BO_Comma) {
  4024. EmitIgnoredExpr(E->getLHS());
  4025. EnsureInsertPoint();
  4026. return EmitLValue(E->getRHS());
  4027. }
  4028. if (E->getOpcode() == BO_PtrMemD ||
  4029. E->getOpcode() == BO_PtrMemI)
  4030. return EmitPointerToDataMemberBinaryExpr(E);
  4031. assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
  4032. // Note that in all of these cases, __block variables need the RHS
  4033. // evaluated first just in case the variable gets moved by the RHS.
  4034. switch (getEvaluationKind(E->getType())) {
  4035. case TEK_Scalar: {
  4036. switch (E->getLHS()->getType().getObjCLifetime()) {
  4037. case Qualifiers::OCL_Strong:
  4038. return EmitARCStoreStrong(E, /*ignored*/ false).first;
  4039. case Qualifiers::OCL_Autoreleasing:
  4040. return EmitARCStoreAutoreleasing(E).first;
  4041. // No reason to do any of these differently.
  4042. case Qualifiers::OCL_None:
  4043. case Qualifiers::OCL_ExplicitNone:
  4044. case Qualifiers::OCL_Weak:
  4045. break;
  4046. }
  4047. RValue RV = EmitAnyExpr(E->getRHS());
  4048. LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
  4049. if (RV.isScalar())
  4050. EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
  4051. EmitStoreThroughLValue(RV, LV);
  4052. return LV;
  4053. }
  4054. case TEK_Complex:
  4055. return EmitComplexAssignmentLValue(E);
  4056. case TEK_Aggregate:
  4057. return EmitAggExprToLValue(E);
  4058. }
  4059. llvm_unreachable("bad evaluation kind");
  4060. }
  4061. LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
  4062. RValue RV = EmitCallExpr(E);
  4063. if (!RV.isScalar())
  4064. return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
  4065. AlignmentSource::Decl);
  4066. assert(E->getCallReturnType(getContext())->isReferenceType() &&
  4067. "Can't have a scalar return unless the return type is a "
  4068. "reference type!");
  4069. return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
  4070. }
  4071. LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
  4072. // FIXME: This shouldn't require another copy.
  4073. return EmitAggExprToLValue(E);
  4074. }
  4075. LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
  4076. assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
  4077. && "binding l-value to type which needs a temporary");
  4078. AggValueSlot Slot = CreateAggTemp(E->getType());
  4079. EmitCXXConstructExpr(E, Slot);
  4080. return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
  4081. }
  4082. LValue
  4083. CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
  4084. return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
  4085. }
  4086. Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
  4087. return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
  4088. ConvertType(E->getType()));
  4089. }
  4090. LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
  4091. return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
  4092. AlignmentSource::Decl);
  4093. }
  4094. LValue
  4095. CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
  4096. AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
  4097. Slot.setExternallyDestructed();
  4098. EmitAggExpr(E->getSubExpr(), Slot);
  4099. EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
  4100. return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
  4101. }
  4102. LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
  4103. RValue RV = EmitObjCMessageExpr(E);
  4104. if (!RV.isScalar())
  4105. return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
  4106. AlignmentSource::Decl);
  4107. assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
  4108. "Can't have a scalar return unless the return type is a "
  4109. "reference type!");
  4110. return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
  4111. }
  4112. LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
  4113. Address V =
  4114. CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
  4115. return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
  4116. }
  4117. llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
  4118. const ObjCIvarDecl *Ivar) {
  4119. return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
  4120. }
  4121. LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
  4122. llvm::Value *BaseValue,
  4123. const ObjCIvarDecl *Ivar,
  4124. unsigned CVRQualifiers) {
  4125. return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
  4126. Ivar, CVRQualifiers);
  4127. }
  4128. LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
  4129. // FIXME: A lot of the code below could be shared with EmitMemberExpr.
  4130. llvm::Value *BaseValue = nullptr;
  4131. const Expr *BaseExpr = E->getBase();
  4132. Qualifiers BaseQuals;
  4133. QualType ObjectTy;
  4134. if (E->isArrow()) {
  4135. BaseValue = EmitScalarExpr(BaseExpr);
  4136. ObjectTy = BaseExpr->getType()->getPointeeType();
  4137. BaseQuals = ObjectTy.getQualifiers();
  4138. } else {
  4139. LValue BaseLV = EmitLValue(BaseExpr);
  4140. BaseValue = BaseLV.getPointer();
  4141. ObjectTy = BaseExpr->getType();
  4142. BaseQuals = ObjectTy.getQualifiers();
  4143. }
  4144. LValue LV =
  4145. EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
  4146. BaseQuals.getCVRQualifiers());
  4147. setObjCGCLValueClass(getContext(), E, LV);
  4148. return LV;
  4149. }
  4150. LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
  4151. // Can only get l-value for message expression returning aggregate type
  4152. RValue RV = EmitAnyExprToTemp(E);
  4153. return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
  4154. AlignmentSource::Decl);
  4155. }
  4156. RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
  4157. const CallExpr *E, ReturnValueSlot ReturnValue,
  4158. llvm::Value *Chain) {
  4159. // Get the actual function type. The callee type will always be a pointer to
  4160. // function type or a block pointer type.
  4161. assert(CalleeType->isFunctionPointerType() &&
  4162. "Call must have function pointer type!");
  4163. const Decl *TargetDecl =
  4164. OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
  4165. CalleeType = getContext().getCanonicalType(CalleeType);
  4166. auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType();
  4167. CGCallee Callee = OrigCallee;
  4168. if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
  4169. (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
  4170. if (llvm::Constant *PrefixSig =
  4171. CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
  4172. SanitizerScope SanScope(this);
  4173. // Remove any (C++17) exception specifications, to allow calling e.g. a
  4174. // noexcept function through a non-noexcept pointer.
  4175. auto ProtoTy =
  4176. getContext().getFunctionTypeWithExceptionSpec(PointeeType, EST_None);
  4177. llvm::Constant *FTRTTIConst =
  4178. CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
  4179. llvm::Type *PrefixStructTyElems[] = {PrefixSig->getType(), Int32Ty};
  4180. llvm::StructType *PrefixStructTy = llvm::StructType::get(
  4181. CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
  4182. llvm::Value *CalleePtr = Callee.getFunctionPointer();
  4183. llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
  4184. CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
  4185. llvm::Value *CalleeSigPtr =
  4186. Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
  4187. llvm::Value *CalleeSig =
  4188. Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
  4189. llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
  4190. llvm::BasicBlock *Cont = createBasicBlock("cont");
  4191. llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
  4192. Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
  4193. EmitBlock(TypeCheck);
  4194. llvm::Value *CalleeRTTIPtr =
  4195. Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
  4196. llvm::Value *CalleeRTTIEncoded =
  4197. Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
  4198. llvm::Value *CalleeRTTI =
  4199. DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded);
  4200. llvm::Value *CalleeRTTIMatch =
  4201. Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
  4202. llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()),
  4203. EmitCheckTypeDescriptor(CalleeType)};
  4204. EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
  4205. SanitizerHandler::FunctionTypeMismatch, StaticData,
  4206. {CalleePtr, CalleeRTTI, FTRTTIConst});
  4207. Builder.CreateBr(Cont);
  4208. EmitBlock(Cont);
  4209. }
  4210. }
  4211. const auto *FnType = cast<FunctionType>(PointeeType);
  4212. // If we are checking indirect calls and this call is indirect, check that the
  4213. // function pointer is a member of the bit set for the function type.
  4214. if (SanOpts.has(SanitizerKind::CFIICall) &&
  4215. (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
  4216. SanitizerScope SanScope(this);
  4217. EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
  4218. llvm::Metadata *MD;
  4219. if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
  4220. MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0));
  4221. else
  4222. MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
  4223. llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
  4224. llvm::Value *CalleePtr = Callee.getFunctionPointer();
  4225. llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
  4226. llvm::Value *TypeTest = Builder.CreateCall(
  4227. CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
  4228. auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
  4229. llvm::Constant *StaticData[] = {
  4230. llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
  4231. EmitCheckSourceLocation(E->getBeginLoc()),
  4232. EmitCheckTypeDescriptor(QualType(FnType, 0)),
  4233. };
  4234. if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
  4235. EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
  4236. CastedCallee, StaticData);
  4237. } else {
  4238. EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
  4239. SanitizerHandler::CFICheckFail, StaticData,
  4240. {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
  4241. }
  4242. }
  4243. CallArgList Args;
  4244. if (Chain)
  4245. Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
  4246. CGM.getContext().VoidPtrTy);
  4247. // C++17 requires that we evaluate arguments to a call using assignment syntax
  4248. // right-to-left, and that we evaluate arguments to certain other operators
  4249. // left-to-right. Note that we allow this to override the order dictated by
  4250. // the calling convention on the MS ABI, which means that parameter
  4251. // destruction order is not necessarily reverse construction order.
  4252. // FIXME: Revisit this based on C++ committee response to unimplementability.
  4253. EvaluationOrder Order = EvaluationOrder::Default;
  4254. if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
  4255. if (OCE->isAssignmentOp())
  4256. Order = EvaluationOrder::ForceRightToLeft;
  4257. else {
  4258. switch (OCE->getOperator()) {
  4259. case OO_LessLess:
  4260. case OO_GreaterGreater:
  4261. case OO_AmpAmp:
  4262. case OO_PipePipe:
  4263. case OO_Comma:
  4264. case OO_ArrowStar:
  4265. Order = EvaluationOrder::ForceLeftToRight;
  4266. break;
  4267. default:
  4268. break;
  4269. }
  4270. }
  4271. }
  4272. EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
  4273. E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
  4274. const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
  4275. Args, FnType, /*ChainCall=*/Chain);
  4276. // C99 6.5.2.2p6:
  4277. // If the expression that denotes the called function has a type
  4278. // that does not include a prototype, [the default argument
  4279. // promotions are performed]. If the number of arguments does not
  4280. // equal the number of parameters, the behavior is undefined. If
  4281. // the function is defined with a type that includes a prototype,
  4282. // and either the prototype ends with an ellipsis (, ...) or the
  4283. // types of the arguments after promotion are not compatible with
  4284. // the types of the parameters, the behavior is undefined. If the
  4285. // function is defined with a type that does not include a
  4286. // prototype, and the types of the arguments after promotion are
  4287. // not compatible with those of the parameters after promotion,
  4288. // the behavior is undefined [except in some trivial cases].
  4289. // That is, in the general case, we should assume that a call
  4290. // through an unprototyped function type works like a *non-variadic*
  4291. // call. The way we make this work is to cast to the exact type
  4292. // of the promoted arguments.
  4293. //
  4294. // Chain calls use this same code path to add the invisible chain parameter
  4295. // to the function type.
  4296. if (isa<FunctionNoProtoType>(FnType) || Chain) {
  4297. llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
  4298. CalleeTy = CalleeTy->getPointerTo();
  4299. llvm::Value *CalleePtr = Callee.getFunctionPointer();
  4300. CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
  4301. Callee.setFunctionPointer(CalleePtr);
  4302. }
  4303. llvm::CallBase *CallOrInvoke = nullptr;
  4304. RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &CallOrInvoke,
  4305. E->getExprLoc());
  4306. // Generate function declaration DISuprogram in order to be used
  4307. // in debug info about call sites.
  4308. if (CGDebugInfo *DI = getDebugInfo()) {
  4309. if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl))
  4310. DI->EmitFuncDeclForCallSite(CallOrInvoke, QualType(FnType, 0),
  4311. CalleeDecl);
  4312. }
  4313. return Call;
  4314. }
  4315. LValue CodeGenFunction::
  4316. EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
  4317. Address BaseAddr = Address::invalid();
  4318. if (E->getOpcode() == BO_PtrMemI) {
  4319. BaseAddr = EmitPointerWithAlignment(E->getLHS());
  4320. } else {
  4321. BaseAddr = EmitLValue(E->getLHS()).getAddress();
  4322. }
  4323. llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
  4324. const MemberPointerType *MPT
  4325. = E->getRHS()->getType()->getAs<MemberPointerType>();
  4326. LValueBaseInfo BaseInfo;
  4327. TBAAAccessInfo TBAAInfo;
  4328. Address MemberAddr =
  4329. EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
  4330. &TBAAInfo);
  4331. return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
  4332. }
  4333. /// Given the address of a temporary variable, produce an r-value of
  4334. /// its type.
  4335. RValue CodeGenFunction::convertTempToRValue(Address addr,
  4336. QualType type,
  4337. SourceLocation loc) {
  4338. LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
  4339. switch (getEvaluationKind(type)) {
  4340. case TEK_Complex:
  4341. return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
  4342. case TEK_Aggregate:
  4343. return lvalue.asAggregateRValue();
  4344. case TEK_Scalar:
  4345. return RValue::get(EmitLoadOfScalar(lvalue, loc));
  4346. }
  4347. llvm_unreachable("bad evaluation kind");
  4348. }
  4349. void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
  4350. assert(Val->getType()->isFPOrFPVectorTy());
  4351. if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
  4352. return;
  4353. llvm::MDBuilder MDHelper(getLLVMContext());
  4354. llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
  4355. cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
  4356. }
  4357. namespace {
  4358. struct LValueOrRValue {
  4359. LValue LV;
  4360. RValue RV;
  4361. };
  4362. }
  4363. static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
  4364. const PseudoObjectExpr *E,
  4365. bool forLValue,
  4366. AggValueSlot slot) {
  4367. SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
  4368. // Find the result expression, if any.
  4369. const Expr *resultExpr = E->getResultExpr();
  4370. LValueOrRValue result;
  4371. for (PseudoObjectExpr::const_semantics_iterator
  4372. i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
  4373. const Expr *semantic = *i;
  4374. // If this semantic expression is an opaque value, bind it
  4375. // to the result of its source expression.
  4376. if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
  4377. // Skip unique OVEs.
  4378. if (ov->isUnique()) {
  4379. assert(ov != resultExpr &&
  4380. "A unique OVE cannot be used as the result expression");
  4381. continue;
  4382. }
  4383. // If this is the result expression, we may need to evaluate
  4384. // directly into the slot.
  4385. typedef CodeGenFunction::OpaqueValueMappingData OVMA;
  4386. OVMA opaqueData;
  4387. if (ov == resultExpr && ov->isRValue() && !forLValue &&
  4388. CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
  4389. CGF.EmitAggExpr(ov->getSourceExpr(), slot);
  4390. LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
  4391. AlignmentSource::Decl);
  4392. opaqueData = OVMA::bind(CGF, ov, LV);
  4393. result.RV = slot.asRValue();
  4394. // Otherwise, emit as normal.
  4395. } else {
  4396. opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
  4397. // If this is the result, also evaluate the result now.
  4398. if (ov == resultExpr) {
  4399. if (forLValue)
  4400. result.LV = CGF.EmitLValue(ov);
  4401. else
  4402. result.RV = CGF.EmitAnyExpr(ov, slot);
  4403. }
  4404. }
  4405. opaques.push_back(opaqueData);
  4406. // Otherwise, if the expression is the result, evaluate it
  4407. // and remember the result.
  4408. } else if (semantic == resultExpr) {
  4409. if (forLValue)
  4410. result.LV = CGF.EmitLValue(semantic);
  4411. else
  4412. result.RV = CGF.EmitAnyExpr(semantic, slot);
  4413. // Otherwise, evaluate the expression in an ignored context.
  4414. } else {
  4415. CGF.EmitIgnoredExpr(semantic);
  4416. }
  4417. }
  4418. // Unbind all the opaques now.
  4419. for (unsigned i = 0, e = opaques.size(); i != e; ++i)
  4420. opaques[i].unbind(CGF);
  4421. return result;
  4422. }
  4423. RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
  4424. AggValueSlot slot) {
  4425. return emitPseudoObjectExpr(*this, E, false, slot).RV;
  4426. }
  4427. LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
  4428. return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
  4429. }