MemorySanitizer.cpp 141 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667
  1. //===-- MemorySanitizer.cpp - detector of uninitialized reads -------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. /// \file
  10. /// This file is a part of MemorySanitizer, a detector of uninitialized
  11. /// reads.
  12. ///
  13. /// The algorithm of the tool is similar to Memcheck
  14. /// (http://goo.gl/QKbem). We associate a few shadow bits with every
  15. /// byte of the application memory, poison the shadow of the malloc-ed
  16. /// or alloca-ed memory, load the shadow bits on every memory read,
  17. /// propagate the shadow bits through some of the arithmetic
  18. /// instruction (including MOV), store the shadow bits on every memory
  19. /// write, report a bug on some other instructions (e.g. JMP) if the
  20. /// associated shadow is poisoned.
  21. ///
  22. /// But there are differences too. The first and the major one:
  23. /// compiler instrumentation instead of binary instrumentation. This
  24. /// gives us much better register allocation, possible compiler
  25. /// optimizations and a fast start-up. But this brings the major issue
  26. /// as well: msan needs to see all program events, including system
  27. /// calls and reads/writes in system libraries, so we either need to
  28. /// compile *everything* with msan or use a binary translation
  29. /// component (e.g. DynamoRIO) to instrument pre-built libraries.
  30. /// Another difference from Memcheck is that we use 8 shadow bits per
  31. /// byte of application memory and use a direct shadow mapping. This
  32. /// greatly simplifies the instrumentation code and avoids races on
  33. /// shadow updates (Memcheck is single-threaded so races are not a
  34. /// concern there. Memcheck uses 2 shadow bits per byte with a slow
  35. /// path storage that uses 8 bits per byte).
  36. ///
  37. /// The default value of shadow is 0, which means "clean" (not poisoned).
  38. ///
  39. /// Every module initializer should call __msan_init to ensure that the
  40. /// shadow memory is ready. On error, __msan_warning is called. Since
  41. /// parameters and return values may be passed via registers, we have a
  42. /// specialized thread-local shadow for return values
  43. /// (__msan_retval_tls) and parameters (__msan_param_tls).
  44. ///
  45. /// Origin tracking.
  46. ///
  47. /// MemorySanitizer can track origins (allocation points) of all uninitialized
  48. /// values. This behavior is controlled with a flag (msan-track-origins) and is
  49. /// disabled by default.
  50. ///
  51. /// Origins are 4-byte values created and interpreted by the runtime library.
  52. /// They are stored in a second shadow mapping, one 4-byte value for 4 bytes
  53. /// of application memory. Propagation of origins is basically a bunch of
  54. /// "select" instructions that pick the origin of a dirty argument, if an
  55. /// instruction has one.
  56. ///
  57. /// Every 4 aligned, consecutive bytes of application memory have one origin
  58. /// value associated with them. If these bytes contain uninitialized data
  59. /// coming from 2 different allocations, the last store wins. Because of this,
  60. /// MemorySanitizer reports can show unrelated origins, but this is unlikely in
  61. /// practice.
  62. ///
  63. /// Origins are meaningless for fully initialized values, so MemorySanitizer
  64. /// avoids storing origin to memory when a fully initialized value is stored.
  65. /// This way it avoids needless overwritting origin of the 4-byte region on
  66. /// a short (i.e. 1 byte) clean store, and it is also good for performance.
  67. ///
  68. /// Atomic handling.
  69. ///
  70. /// Ideally, every atomic store of application value should update the
  71. /// corresponding shadow location in an atomic way. Unfortunately, atomic store
  72. /// of two disjoint locations can not be done without severe slowdown.
  73. ///
  74. /// Therefore, we implement an approximation that may err on the safe side.
  75. /// In this implementation, every atomically accessed location in the program
  76. /// may only change from (partially) uninitialized to fully initialized, but
  77. /// not the other way around. We load the shadow _after_ the application load,
  78. /// and we store the shadow _before_ the app store. Also, we always store clean
  79. /// shadow (if the application store is atomic). This way, if the store-load
  80. /// pair constitutes a happens-before arc, shadow store and load are correctly
  81. /// ordered such that the load will get either the value that was stored, or
  82. /// some later value (which is always clean).
  83. ///
  84. /// This does not work very well with Compare-And-Swap (CAS) and
  85. /// Read-Modify-Write (RMW) operations. To follow the above logic, CAS and RMW
  86. /// must store the new shadow before the app operation, and load the shadow
  87. /// after the app operation. Computers don't work this way. Current
  88. /// implementation ignores the load aspect of CAS/RMW, always returning a clean
  89. /// value. It implements the store part as a simple atomic store by storing a
  90. /// clean shadow.
  91. //===----------------------------------------------------------------------===//
  92. #include "llvm/ADT/DepthFirstIterator.h"
  93. #include "llvm/ADT/SmallString.h"
  94. #include "llvm/ADT/SmallVector.h"
  95. #include "llvm/ADT/StringExtras.h"
  96. #include "llvm/ADT/Triple.h"
  97. #include "llvm/IR/DataLayout.h"
  98. #include "llvm/IR/Function.h"
  99. #include "llvm/IR/IRBuilder.h"
  100. #include "llvm/IR/InlineAsm.h"
  101. #include "llvm/IR/InstVisitor.h"
  102. #include "llvm/IR/IntrinsicInst.h"
  103. #include "llvm/IR/LLVMContext.h"
  104. #include "llvm/IR/MDBuilder.h"
  105. #include "llvm/IR/Module.h"
  106. #include "llvm/IR/Type.h"
  107. #include "llvm/IR/ValueMap.h"
  108. #include "llvm/Support/CommandLine.h"
  109. #include "llvm/Support/Debug.h"
  110. #include "llvm/Support/raw_ostream.h"
  111. #include "llvm/Transforms/Instrumentation.h"
  112. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  113. #include "llvm/Transforms/Utils/Local.h"
  114. #include "llvm/Transforms/Utils/ModuleUtils.h"
  115. using namespace llvm;
  116. #define DEBUG_TYPE "msan"
  117. static const unsigned kOriginSize = 4;
  118. static const unsigned kMinOriginAlignment = 4;
  119. static const unsigned kShadowTLSAlignment = 8;
  120. // These constants must be kept in sync with the ones in msan.h.
  121. static const unsigned kParamTLSSize = 800;
  122. static const unsigned kRetvalTLSSize = 800;
  123. // Accesses sizes are powers of two: 1, 2, 4, 8.
  124. static const size_t kNumberOfAccessSizes = 4;
  125. /// \brief Track origins of uninitialized values.
  126. ///
  127. /// Adds a section to MemorySanitizer report that points to the allocation
  128. /// (stack or heap) the uninitialized bits came from originally.
  129. static cl::opt<int> ClTrackOrigins("msan-track-origins",
  130. cl::desc("Track origins (allocation sites) of poisoned memory"),
  131. cl::Hidden, cl::init(0));
  132. static cl::opt<bool> ClKeepGoing("msan-keep-going",
  133. cl::desc("keep going after reporting a UMR"),
  134. cl::Hidden, cl::init(false));
  135. static cl::opt<bool> ClPoisonStack("msan-poison-stack",
  136. cl::desc("poison uninitialized stack variables"),
  137. cl::Hidden, cl::init(true));
  138. static cl::opt<bool> ClPoisonStackWithCall("msan-poison-stack-with-call",
  139. cl::desc("poison uninitialized stack variables with a call"),
  140. cl::Hidden, cl::init(false));
  141. static cl::opt<int> ClPoisonStackPattern("msan-poison-stack-pattern",
  142. cl::desc("poison uninitialized stack variables with the given pattern"),
  143. cl::Hidden, cl::init(0xff));
  144. static cl::opt<bool> ClPoisonUndef("msan-poison-undef",
  145. cl::desc("poison undef temps"),
  146. cl::Hidden, cl::init(true));
  147. static cl::opt<bool> ClHandleICmp("msan-handle-icmp",
  148. cl::desc("propagate shadow through ICmpEQ and ICmpNE"),
  149. cl::Hidden, cl::init(true));
  150. static cl::opt<bool> ClHandleICmpExact("msan-handle-icmp-exact",
  151. cl::desc("exact handling of relational integer ICmp"),
  152. cl::Hidden, cl::init(false));
  153. // This flag controls whether we check the shadow of the address
  154. // operand of load or store. Such bugs are very rare, since load from
  155. // a garbage address typically results in SEGV, but still happen
  156. // (e.g. only lower bits of address are garbage, or the access happens
  157. // early at program startup where malloc-ed memory is more likely to
  158. // be zeroed. As of 2012-08-28 this flag adds 20% slowdown.
  159. static cl::opt<bool> ClCheckAccessAddress("msan-check-access-address",
  160. cl::desc("report accesses through a pointer which has poisoned shadow"),
  161. cl::Hidden, cl::init(true));
  162. static cl::opt<bool> ClDumpStrictInstructions("msan-dump-strict-instructions",
  163. cl::desc("print out instructions with default strict semantics"),
  164. cl::Hidden, cl::init(false));
  165. static cl::opt<int> ClInstrumentationWithCallThreshold(
  166. "msan-instrumentation-with-call-threshold",
  167. cl::desc(
  168. "If the function being instrumented requires more than "
  169. "this number of checks and origin stores, use callbacks instead of "
  170. "inline checks (-1 means never use callbacks)."),
  171. cl::Hidden, cl::init(3500));
  172. // This is an experiment to enable handling of cases where shadow is a non-zero
  173. // compile-time constant. For some unexplainable reason they were silently
  174. // ignored in the instrumentation.
  175. static cl::opt<bool> ClCheckConstantShadow("msan-check-constant-shadow",
  176. cl::desc("Insert checks for constant shadow values"),
  177. cl::Hidden, cl::init(false));
  178. // This is off by default because of a bug in gold:
  179. // https://sourceware.org/bugzilla/show_bug.cgi?id=19002
  180. static cl::opt<bool> ClWithComdat("msan-with-comdat",
  181. cl::desc("Place MSan constructors in comdat sections"),
  182. cl::Hidden, cl::init(false));
  183. static const char *const kMsanModuleCtorName = "msan.module_ctor";
  184. static const char *const kMsanInitName = "__msan_init";
  185. namespace {
  186. // Memory map parameters used in application-to-shadow address calculation.
  187. // Offset = (Addr & ~AndMask) ^ XorMask
  188. // Shadow = ShadowBase + Offset
  189. // Origin = OriginBase + Offset
  190. struct MemoryMapParams {
  191. uint64_t AndMask;
  192. uint64_t XorMask;
  193. uint64_t ShadowBase;
  194. uint64_t OriginBase;
  195. };
  196. struct PlatformMemoryMapParams {
  197. const MemoryMapParams *bits32;
  198. const MemoryMapParams *bits64;
  199. };
  200. // i386 Linux
  201. static const MemoryMapParams Linux_I386_MemoryMapParams = {
  202. 0x000080000000, // AndMask
  203. 0, // XorMask (not used)
  204. 0, // ShadowBase (not used)
  205. 0x000040000000, // OriginBase
  206. };
  207. // x86_64 Linux
  208. static const MemoryMapParams Linux_X86_64_MemoryMapParams = {
  209. #ifdef MSAN_LINUX_X86_64_OLD_MAPPING
  210. 0x400000000000, // AndMask
  211. 0, // XorMask (not used)
  212. 0, // ShadowBase (not used)
  213. 0x200000000000, // OriginBase
  214. #else
  215. 0, // AndMask (not used)
  216. 0x500000000000, // XorMask
  217. 0, // ShadowBase (not used)
  218. 0x100000000000, // OriginBase
  219. #endif
  220. };
  221. // mips64 Linux
  222. static const MemoryMapParams Linux_MIPS64_MemoryMapParams = {
  223. 0, // AndMask (not used)
  224. 0x008000000000, // XorMask
  225. 0, // ShadowBase (not used)
  226. 0x002000000000, // OriginBase
  227. };
  228. // ppc64 Linux
  229. static const MemoryMapParams Linux_PowerPC64_MemoryMapParams = {
  230. 0x200000000000, // AndMask
  231. 0x100000000000, // XorMask
  232. 0x080000000000, // ShadowBase
  233. 0x1C0000000000, // OriginBase
  234. };
  235. // aarch64 Linux
  236. static const MemoryMapParams Linux_AArch64_MemoryMapParams = {
  237. 0, // AndMask (not used)
  238. 0x06000000000, // XorMask
  239. 0, // ShadowBase (not used)
  240. 0x01000000000, // OriginBase
  241. };
  242. // i386 FreeBSD
  243. static const MemoryMapParams FreeBSD_I386_MemoryMapParams = {
  244. 0x000180000000, // AndMask
  245. 0x000040000000, // XorMask
  246. 0x000020000000, // ShadowBase
  247. 0x000700000000, // OriginBase
  248. };
  249. // x86_64 FreeBSD
  250. static const MemoryMapParams FreeBSD_X86_64_MemoryMapParams = {
  251. 0xc00000000000, // AndMask
  252. 0x200000000000, // XorMask
  253. 0x100000000000, // ShadowBase
  254. 0x380000000000, // OriginBase
  255. };
  256. static const PlatformMemoryMapParams Linux_X86_MemoryMapParams = {
  257. &Linux_I386_MemoryMapParams,
  258. &Linux_X86_64_MemoryMapParams,
  259. };
  260. static const PlatformMemoryMapParams Linux_MIPS_MemoryMapParams = {
  261. nullptr,
  262. &Linux_MIPS64_MemoryMapParams,
  263. };
  264. static const PlatformMemoryMapParams Linux_PowerPC_MemoryMapParams = {
  265. nullptr,
  266. &Linux_PowerPC64_MemoryMapParams,
  267. };
  268. static const PlatformMemoryMapParams Linux_ARM_MemoryMapParams = {
  269. nullptr,
  270. &Linux_AArch64_MemoryMapParams,
  271. };
  272. static const PlatformMemoryMapParams FreeBSD_X86_MemoryMapParams = {
  273. &FreeBSD_I386_MemoryMapParams,
  274. &FreeBSD_X86_64_MemoryMapParams,
  275. };
  276. /// \brief An instrumentation pass implementing detection of uninitialized
  277. /// reads.
  278. ///
  279. /// MemorySanitizer: instrument the code in module to find
  280. /// uninitialized reads.
  281. class MemorySanitizer : public FunctionPass {
  282. public:
  283. MemorySanitizer(int TrackOrigins = 0, bool Recover = false)
  284. : FunctionPass(ID),
  285. TrackOrigins(std::max(TrackOrigins, (int)ClTrackOrigins)),
  286. Recover(Recover || ClKeepGoing),
  287. WarningFn(nullptr) {}
  288. StringRef getPassName() const override { return "MemorySanitizer"; }
  289. void getAnalysisUsage(AnalysisUsage &AU) const override {
  290. AU.addRequired<TargetLibraryInfoWrapperPass>();
  291. }
  292. bool runOnFunction(Function &F) override;
  293. bool doInitialization(Module &M) override;
  294. static char ID; // Pass identification, replacement for typeid.
  295. private:
  296. void initializeCallbacks(Module &M);
  297. /// \brief Track origins (allocation points) of uninitialized values.
  298. int TrackOrigins;
  299. bool Recover;
  300. LLVMContext *C;
  301. Type *IntptrTy;
  302. Type *OriginTy;
  303. /// \brief Thread-local shadow storage for function parameters.
  304. GlobalVariable *ParamTLS;
  305. /// \brief Thread-local origin storage for function parameters.
  306. GlobalVariable *ParamOriginTLS;
  307. /// \brief Thread-local shadow storage for function return value.
  308. GlobalVariable *RetvalTLS;
  309. /// \brief Thread-local origin storage for function return value.
  310. GlobalVariable *RetvalOriginTLS;
  311. /// \brief Thread-local shadow storage for in-register va_arg function
  312. /// parameters (x86_64-specific).
  313. GlobalVariable *VAArgTLS;
  314. /// \brief Thread-local shadow storage for va_arg overflow area
  315. /// (x86_64-specific).
  316. GlobalVariable *VAArgOverflowSizeTLS;
  317. /// \brief Thread-local space used to pass origin value to the UMR reporting
  318. /// function.
  319. GlobalVariable *OriginTLS;
  320. /// \brief The run-time callback to print a warning.
  321. Value *WarningFn;
  322. // These arrays are indexed by log2(AccessSize).
  323. Value *MaybeWarningFn[kNumberOfAccessSizes];
  324. Value *MaybeStoreOriginFn[kNumberOfAccessSizes];
  325. /// \brief Run-time helper that generates a new origin value for a stack
  326. /// allocation.
  327. Value *MsanSetAllocaOrigin4Fn;
  328. /// \brief Run-time helper that poisons stack on function entry.
  329. Value *MsanPoisonStackFn;
  330. /// \brief Run-time helper that records a store (or any event) of an
  331. /// uninitialized value and returns an updated origin id encoding this info.
  332. Value *MsanChainOriginFn;
  333. /// \brief MSan runtime replacements for memmove, memcpy and memset.
  334. Value *MemmoveFn, *MemcpyFn, *MemsetFn;
  335. /// \brief Memory map parameters used in application-to-shadow calculation.
  336. const MemoryMapParams *MapParams;
  337. MDNode *ColdCallWeights;
  338. /// \brief Branch weights for origin store.
  339. MDNode *OriginStoreWeights;
  340. /// \brief An empty volatile inline asm that prevents callback merge.
  341. InlineAsm *EmptyAsm;
  342. Function *MsanCtorFunction;
  343. friend struct MemorySanitizerVisitor;
  344. friend struct VarArgAMD64Helper;
  345. friend struct VarArgMIPS64Helper;
  346. friend struct VarArgAArch64Helper;
  347. friend struct VarArgPowerPC64Helper;
  348. };
  349. } // anonymous namespace
  350. char MemorySanitizer::ID = 0;
  351. INITIALIZE_PASS_BEGIN(
  352. MemorySanitizer, "msan",
  353. "MemorySanitizer: detects uninitialized reads.", false, false)
  354. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  355. INITIALIZE_PASS_END(
  356. MemorySanitizer, "msan",
  357. "MemorySanitizer: detects uninitialized reads.", false, false)
  358. FunctionPass *llvm::createMemorySanitizerPass(int TrackOrigins, bool Recover) {
  359. return new MemorySanitizer(TrackOrigins, Recover);
  360. }
  361. /// \brief Create a non-const global initialized with the given string.
  362. ///
  363. /// Creates a writable global for Str so that we can pass it to the
  364. /// run-time lib. Runtime uses first 4 bytes of the string to store the
  365. /// frame ID, so the string needs to be mutable.
  366. static GlobalVariable *createPrivateNonConstGlobalForString(Module &M,
  367. StringRef Str) {
  368. Constant *StrConst = ConstantDataArray::getString(M.getContext(), Str);
  369. return new GlobalVariable(M, StrConst->getType(), /*isConstant=*/false,
  370. GlobalValue::PrivateLinkage, StrConst, "");
  371. }
  372. /// \brief Insert extern declaration of runtime-provided functions and globals.
  373. void MemorySanitizer::initializeCallbacks(Module &M) {
  374. // Only do this once.
  375. if (WarningFn)
  376. return;
  377. IRBuilder<> IRB(*C);
  378. // Create the callback.
  379. // FIXME: this function should have "Cold" calling conv,
  380. // which is not yet implemented.
  381. StringRef WarningFnName = Recover ? "__msan_warning"
  382. : "__msan_warning_noreturn";
  383. WarningFn = M.getOrInsertFunction(WarningFnName, IRB.getVoidTy());
  384. for (size_t AccessSizeIndex = 0; AccessSizeIndex < kNumberOfAccessSizes;
  385. AccessSizeIndex++) {
  386. unsigned AccessSize = 1 << AccessSizeIndex;
  387. std::string FunctionName = "__msan_maybe_warning_" + itostr(AccessSize);
  388. MaybeWarningFn[AccessSizeIndex] = M.getOrInsertFunction(
  389. FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
  390. IRB.getInt32Ty());
  391. FunctionName = "__msan_maybe_store_origin_" + itostr(AccessSize);
  392. MaybeStoreOriginFn[AccessSizeIndex] = M.getOrInsertFunction(
  393. FunctionName, IRB.getVoidTy(), IRB.getIntNTy(AccessSize * 8),
  394. IRB.getInt8PtrTy(), IRB.getInt32Ty());
  395. }
  396. MsanSetAllocaOrigin4Fn = M.getOrInsertFunction(
  397. "__msan_set_alloca_origin4", IRB.getVoidTy(), IRB.getInt8PtrTy(), IntptrTy,
  398. IRB.getInt8PtrTy(), IntptrTy);
  399. MsanPoisonStackFn =
  400. M.getOrInsertFunction("__msan_poison_stack", IRB.getVoidTy(),
  401. IRB.getInt8PtrTy(), IntptrTy);
  402. MsanChainOriginFn = M.getOrInsertFunction(
  403. "__msan_chain_origin", IRB.getInt32Ty(), IRB.getInt32Ty());
  404. MemmoveFn = M.getOrInsertFunction(
  405. "__msan_memmove", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
  406. IRB.getInt8PtrTy(), IntptrTy);
  407. MemcpyFn = M.getOrInsertFunction(
  408. "__msan_memcpy", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt8PtrTy(),
  409. IntptrTy);
  410. MemsetFn = M.getOrInsertFunction(
  411. "__msan_memset", IRB.getInt8PtrTy(), IRB.getInt8PtrTy(), IRB.getInt32Ty(),
  412. IntptrTy);
  413. // Create globals.
  414. RetvalTLS = new GlobalVariable(
  415. M, ArrayType::get(IRB.getInt64Ty(), kRetvalTLSSize / 8), false,
  416. GlobalVariable::ExternalLinkage, nullptr, "__msan_retval_tls", nullptr,
  417. GlobalVariable::InitialExecTLSModel);
  418. RetvalOriginTLS = new GlobalVariable(
  419. M, OriginTy, false, GlobalVariable::ExternalLinkage, nullptr,
  420. "__msan_retval_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
  421. ParamTLS = new GlobalVariable(
  422. M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
  423. GlobalVariable::ExternalLinkage, nullptr, "__msan_param_tls", nullptr,
  424. GlobalVariable::InitialExecTLSModel);
  425. ParamOriginTLS = new GlobalVariable(
  426. M, ArrayType::get(OriginTy, kParamTLSSize / 4), false,
  427. GlobalVariable::ExternalLinkage, nullptr, "__msan_param_origin_tls",
  428. nullptr, GlobalVariable::InitialExecTLSModel);
  429. VAArgTLS = new GlobalVariable(
  430. M, ArrayType::get(IRB.getInt64Ty(), kParamTLSSize / 8), false,
  431. GlobalVariable::ExternalLinkage, nullptr, "__msan_va_arg_tls", nullptr,
  432. GlobalVariable::InitialExecTLSModel);
  433. VAArgOverflowSizeTLS = new GlobalVariable(
  434. M, IRB.getInt64Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
  435. "__msan_va_arg_overflow_size_tls", nullptr,
  436. GlobalVariable::InitialExecTLSModel);
  437. OriginTLS = new GlobalVariable(
  438. M, IRB.getInt32Ty(), false, GlobalVariable::ExternalLinkage, nullptr,
  439. "__msan_origin_tls", nullptr, GlobalVariable::InitialExecTLSModel);
  440. // We insert an empty inline asm after __msan_report* to avoid callback merge.
  441. EmptyAsm = InlineAsm::get(FunctionType::get(IRB.getVoidTy(), false),
  442. StringRef(""), StringRef(""),
  443. /*hasSideEffects=*/true);
  444. }
  445. /// \brief Module-level initialization.
  446. ///
  447. /// inserts a call to __msan_init to the module's constructor list.
  448. bool MemorySanitizer::doInitialization(Module &M) {
  449. auto &DL = M.getDataLayout();
  450. Triple TargetTriple(M.getTargetTriple());
  451. switch (TargetTriple.getOS()) {
  452. case Triple::FreeBSD:
  453. switch (TargetTriple.getArch()) {
  454. case Triple::x86_64:
  455. MapParams = FreeBSD_X86_MemoryMapParams.bits64;
  456. break;
  457. case Triple::x86:
  458. MapParams = FreeBSD_X86_MemoryMapParams.bits32;
  459. break;
  460. default:
  461. report_fatal_error("unsupported architecture");
  462. }
  463. break;
  464. case Triple::Linux:
  465. switch (TargetTriple.getArch()) {
  466. case Triple::x86_64:
  467. MapParams = Linux_X86_MemoryMapParams.bits64;
  468. break;
  469. case Triple::x86:
  470. MapParams = Linux_X86_MemoryMapParams.bits32;
  471. break;
  472. case Triple::mips64:
  473. case Triple::mips64el:
  474. MapParams = Linux_MIPS_MemoryMapParams.bits64;
  475. break;
  476. case Triple::ppc64:
  477. case Triple::ppc64le:
  478. MapParams = Linux_PowerPC_MemoryMapParams.bits64;
  479. break;
  480. case Triple::aarch64:
  481. case Triple::aarch64_be:
  482. MapParams = Linux_ARM_MemoryMapParams.bits64;
  483. break;
  484. default:
  485. report_fatal_error("unsupported architecture");
  486. }
  487. break;
  488. default:
  489. report_fatal_error("unsupported operating system");
  490. }
  491. C = &(M.getContext());
  492. IRBuilder<> IRB(*C);
  493. IntptrTy = IRB.getIntPtrTy(DL);
  494. OriginTy = IRB.getInt32Ty();
  495. ColdCallWeights = MDBuilder(*C).createBranchWeights(1, 1000);
  496. OriginStoreWeights = MDBuilder(*C).createBranchWeights(1, 1000);
  497. std::tie(MsanCtorFunction, std::ignore) =
  498. createSanitizerCtorAndInitFunctions(M, kMsanModuleCtorName, kMsanInitName,
  499. /*InitArgTypes=*/{},
  500. /*InitArgs=*/{});
  501. if (ClWithComdat) {
  502. Comdat *MsanCtorComdat = M.getOrInsertComdat(kMsanModuleCtorName);
  503. MsanCtorFunction->setComdat(MsanCtorComdat);
  504. appendToGlobalCtors(M, MsanCtorFunction, 0, MsanCtorFunction);
  505. } else {
  506. appendToGlobalCtors(M, MsanCtorFunction, 0);
  507. }
  508. if (TrackOrigins)
  509. new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
  510. IRB.getInt32(TrackOrigins), "__msan_track_origins");
  511. if (Recover)
  512. new GlobalVariable(M, IRB.getInt32Ty(), true, GlobalValue::WeakODRLinkage,
  513. IRB.getInt32(Recover), "__msan_keep_going");
  514. return true;
  515. }
  516. namespace {
  517. /// \brief A helper class that handles instrumentation of VarArg
  518. /// functions on a particular platform.
  519. ///
  520. /// Implementations are expected to insert the instrumentation
  521. /// necessary to propagate argument shadow through VarArg function
  522. /// calls. Visit* methods are called during an InstVisitor pass over
  523. /// the function, and should avoid creating new basic blocks. A new
  524. /// instance of this class is created for each instrumented function.
  525. struct VarArgHelper {
  526. /// \brief Visit a CallSite.
  527. virtual void visitCallSite(CallSite &CS, IRBuilder<> &IRB) = 0;
  528. /// \brief Visit a va_start call.
  529. virtual void visitVAStartInst(VAStartInst &I) = 0;
  530. /// \brief Visit a va_copy call.
  531. virtual void visitVACopyInst(VACopyInst &I) = 0;
  532. /// \brief Finalize function instrumentation.
  533. ///
  534. /// This method is called after visiting all interesting (see above)
  535. /// instructions in a function.
  536. virtual void finalizeInstrumentation() = 0;
  537. virtual ~VarArgHelper() {}
  538. };
  539. struct MemorySanitizerVisitor;
  540. VarArgHelper*
  541. CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
  542. MemorySanitizerVisitor &Visitor);
  543. unsigned TypeSizeToSizeIndex(unsigned TypeSize) {
  544. if (TypeSize <= 8) return 0;
  545. return Log2_32_Ceil((TypeSize + 7) / 8);
  546. }
  547. /// This class does all the work for a given function. Store and Load
  548. /// instructions store and load corresponding shadow and origin
  549. /// values. Most instructions propagate shadow from arguments to their
  550. /// return values. Certain instructions (most importantly, BranchInst)
  551. /// test their argument shadow and print reports (with a runtime call) if it's
  552. /// non-zero.
  553. struct MemorySanitizerVisitor : public InstVisitor<MemorySanitizerVisitor> {
  554. Function &F;
  555. MemorySanitizer &MS;
  556. SmallVector<PHINode *, 16> ShadowPHINodes, OriginPHINodes;
  557. ValueMap<Value*, Value*> ShadowMap, OriginMap;
  558. std::unique_ptr<VarArgHelper> VAHelper;
  559. const TargetLibraryInfo *TLI;
  560. // The following flags disable parts of MSan instrumentation based on
  561. // blacklist contents and command-line options.
  562. bool InsertChecks;
  563. bool PropagateShadow;
  564. bool PoisonStack;
  565. bool PoisonUndef;
  566. bool CheckReturnValue;
  567. struct ShadowOriginAndInsertPoint {
  568. Value *Shadow;
  569. Value *Origin;
  570. Instruction *OrigIns;
  571. ShadowOriginAndInsertPoint(Value *S, Value *O, Instruction *I)
  572. : Shadow(S), Origin(O), OrigIns(I) { }
  573. };
  574. SmallVector<ShadowOriginAndInsertPoint, 16> InstrumentationList;
  575. SmallVector<StoreInst *, 16> StoreList;
  576. MemorySanitizerVisitor(Function &F, MemorySanitizer &MS)
  577. : F(F), MS(MS), VAHelper(CreateVarArgHelper(F, MS, *this)) {
  578. bool SanitizeFunction = F.hasFnAttribute(Attribute::SanitizeMemory);
  579. InsertChecks = SanitizeFunction;
  580. PropagateShadow = SanitizeFunction;
  581. PoisonStack = SanitizeFunction && ClPoisonStack;
  582. PoisonUndef = SanitizeFunction && ClPoisonUndef;
  583. // FIXME: Consider using SpecialCaseList to specify a list of functions that
  584. // must always return fully initialized values. For now, we hardcode "main".
  585. CheckReturnValue = SanitizeFunction && (F.getName() == "main");
  586. TLI = &MS.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  587. DEBUG(if (!InsertChecks)
  588. dbgs() << "MemorySanitizer is not inserting checks into '"
  589. << F.getName() << "'\n");
  590. }
  591. Value *updateOrigin(Value *V, IRBuilder<> &IRB) {
  592. if (MS.TrackOrigins <= 1) return V;
  593. return IRB.CreateCall(MS.MsanChainOriginFn, V);
  594. }
  595. Value *originToIntptr(IRBuilder<> &IRB, Value *Origin) {
  596. const DataLayout &DL = F.getParent()->getDataLayout();
  597. unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
  598. if (IntptrSize == kOriginSize) return Origin;
  599. assert(IntptrSize == kOriginSize * 2);
  600. Origin = IRB.CreateIntCast(Origin, MS.IntptrTy, /* isSigned */ false);
  601. return IRB.CreateOr(Origin, IRB.CreateShl(Origin, kOriginSize * 8));
  602. }
  603. /// \brief Fill memory range with the given origin value.
  604. void paintOrigin(IRBuilder<> &IRB, Value *Origin, Value *OriginPtr,
  605. unsigned Size, unsigned Alignment) {
  606. const DataLayout &DL = F.getParent()->getDataLayout();
  607. unsigned IntptrAlignment = DL.getABITypeAlignment(MS.IntptrTy);
  608. unsigned IntptrSize = DL.getTypeStoreSize(MS.IntptrTy);
  609. assert(IntptrAlignment >= kMinOriginAlignment);
  610. assert(IntptrSize >= kOriginSize);
  611. unsigned Ofs = 0;
  612. unsigned CurrentAlignment = Alignment;
  613. if (Alignment >= IntptrAlignment && IntptrSize > kOriginSize) {
  614. Value *IntptrOrigin = originToIntptr(IRB, Origin);
  615. Value *IntptrOriginPtr =
  616. IRB.CreatePointerCast(OriginPtr, PointerType::get(MS.IntptrTy, 0));
  617. for (unsigned i = 0; i < Size / IntptrSize; ++i) {
  618. Value *Ptr = i ? IRB.CreateConstGEP1_32(MS.IntptrTy, IntptrOriginPtr, i)
  619. : IntptrOriginPtr;
  620. IRB.CreateAlignedStore(IntptrOrigin, Ptr, CurrentAlignment);
  621. Ofs += IntptrSize / kOriginSize;
  622. CurrentAlignment = IntptrAlignment;
  623. }
  624. }
  625. for (unsigned i = Ofs; i < (Size + kOriginSize - 1) / kOriginSize; ++i) {
  626. Value *GEP =
  627. i ? IRB.CreateConstGEP1_32(nullptr, OriginPtr, i) : OriginPtr;
  628. IRB.CreateAlignedStore(Origin, GEP, CurrentAlignment);
  629. CurrentAlignment = kMinOriginAlignment;
  630. }
  631. }
  632. void storeOrigin(IRBuilder<> &IRB, Value *Addr, Value *Shadow, Value *Origin,
  633. unsigned Alignment, bool AsCall) {
  634. const DataLayout &DL = F.getParent()->getDataLayout();
  635. unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
  636. unsigned StoreSize = DL.getTypeStoreSize(Shadow->getType());
  637. if (Shadow->getType()->isAggregateType()) {
  638. paintOrigin(IRB, updateOrigin(Origin, IRB),
  639. getOriginPtr(Addr, IRB, Alignment), StoreSize,
  640. OriginAlignment);
  641. } else {
  642. Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
  643. Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
  644. if (ConstantShadow) {
  645. if (ClCheckConstantShadow && !ConstantShadow->isZeroValue())
  646. paintOrigin(IRB, updateOrigin(Origin, IRB),
  647. getOriginPtr(Addr, IRB, Alignment), StoreSize,
  648. OriginAlignment);
  649. return;
  650. }
  651. unsigned TypeSizeInBits =
  652. DL.getTypeSizeInBits(ConvertedShadow->getType());
  653. unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
  654. if (AsCall && SizeIndex < kNumberOfAccessSizes) {
  655. Value *Fn = MS.MaybeStoreOriginFn[SizeIndex];
  656. Value *ConvertedShadow2 = IRB.CreateZExt(
  657. ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
  658. IRB.CreateCall(Fn, {ConvertedShadow2,
  659. IRB.CreatePointerCast(Addr, IRB.getInt8PtrTy()),
  660. Origin});
  661. } else {
  662. Value *Cmp = IRB.CreateICmpNE(
  663. ConvertedShadow, getCleanShadow(ConvertedShadow), "_mscmp");
  664. Instruction *CheckTerm = SplitBlockAndInsertIfThen(
  665. Cmp, &*IRB.GetInsertPoint(), false, MS.OriginStoreWeights);
  666. IRBuilder<> IRBNew(CheckTerm);
  667. paintOrigin(IRBNew, updateOrigin(Origin, IRBNew),
  668. getOriginPtr(Addr, IRBNew, Alignment), StoreSize,
  669. OriginAlignment);
  670. }
  671. }
  672. }
  673. void materializeStores(bool InstrumentWithCalls) {
  674. for (StoreInst *SI : StoreList) {
  675. IRBuilder<> IRB(SI);
  676. Value *Val = SI->getValueOperand();
  677. Value *Addr = SI->getPointerOperand();
  678. Value *Shadow = SI->isAtomic() ? getCleanShadow(Val) : getShadow(Val);
  679. Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
  680. StoreInst *NewSI =
  681. IRB.CreateAlignedStore(Shadow, ShadowPtr, SI->getAlignment());
  682. DEBUG(dbgs() << " STORE: " << *NewSI << "\n");
  683. (void)NewSI;
  684. if (ClCheckAccessAddress)
  685. insertShadowCheck(Addr, SI);
  686. if (SI->isAtomic())
  687. SI->setOrdering(addReleaseOrdering(SI->getOrdering()));
  688. if (MS.TrackOrigins && !SI->isAtomic())
  689. storeOrigin(IRB, Addr, Shadow, getOrigin(Val), SI->getAlignment(),
  690. InstrumentWithCalls);
  691. }
  692. }
  693. void materializeOneCheck(Instruction *OrigIns, Value *Shadow, Value *Origin,
  694. bool AsCall) {
  695. IRBuilder<> IRB(OrigIns);
  696. DEBUG(dbgs() << " SHAD0 : " << *Shadow << "\n");
  697. Value *ConvertedShadow = convertToShadowTyNoVec(Shadow, IRB);
  698. DEBUG(dbgs() << " SHAD1 : " << *ConvertedShadow << "\n");
  699. Constant *ConstantShadow = dyn_cast_or_null<Constant>(ConvertedShadow);
  700. if (ConstantShadow) {
  701. if (ClCheckConstantShadow && !ConstantShadow->isZeroValue()) {
  702. if (MS.TrackOrigins) {
  703. IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
  704. MS.OriginTLS);
  705. }
  706. IRB.CreateCall(MS.WarningFn, {});
  707. IRB.CreateCall(MS.EmptyAsm, {});
  708. // FIXME: Insert UnreachableInst if !MS.Recover?
  709. // This may invalidate some of the following checks and needs to be done
  710. // at the very end.
  711. }
  712. return;
  713. }
  714. const DataLayout &DL = OrigIns->getModule()->getDataLayout();
  715. unsigned TypeSizeInBits = DL.getTypeSizeInBits(ConvertedShadow->getType());
  716. unsigned SizeIndex = TypeSizeToSizeIndex(TypeSizeInBits);
  717. if (AsCall && SizeIndex < kNumberOfAccessSizes) {
  718. Value *Fn = MS.MaybeWarningFn[SizeIndex];
  719. Value *ConvertedShadow2 =
  720. IRB.CreateZExt(ConvertedShadow, IRB.getIntNTy(8 * (1 << SizeIndex)));
  721. IRB.CreateCall(Fn, {ConvertedShadow2, MS.TrackOrigins && Origin
  722. ? Origin
  723. : (Value *)IRB.getInt32(0)});
  724. } else {
  725. Value *Cmp = IRB.CreateICmpNE(ConvertedShadow,
  726. getCleanShadow(ConvertedShadow), "_mscmp");
  727. Instruction *CheckTerm = SplitBlockAndInsertIfThen(
  728. Cmp, OrigIns,
  729. /* Unreachable */ !MS.Recover, MS.ColdCallWeights);
  730. IRB.SetInsertPoint(CheckTerm);
  731. if (MS.TrackOrigins) {
  732. IRB.CreateStore(Origin ? (Value *)Origin : (Value *)IRB.getInt32(0),
  733. MS.OriginTLS);
  734. }
  735. IRB.CreateCall(MS.WarningFn, {});
  736. IRB.CreateCall(MS.EmptyAsm, {});
  737. DEBUG(dbgs() << " CHECK: " << *Cmp << "\n");
  738. }
  739. }
  740. void materializeChecks(bool InstrumentWithCalls) {
  741. for (const auto &ShadowData : InstrumentationList) {
  742. Instruction *OrigIns = ShadowData.OrigIns;
  743. Value *Shadow = ShadowData.Shadow;
  744. Value *Origin = ShadowData.Origin;
  745. materializeOneCheck(OrigIns, Shadow, Origin, InstrumentWithCalls);
  746. }
  747. DEBUG(dbgs() << "DONE:\n" << F);
  748. }
  749. /// \brief Add MemorySanitizer instrumentation to a function.
  750. bool runOnFunction() {
  751. MS.initializeCallbacks(*F.getParent());
  752. // In the presence of unreachable blocks, we may see Phi nodes with
  753. // incoming nodes from such blocks. Since InstVisitor skips unreachable
  754. // blocks, such nodes will not have any shadow value associated with them.
  755. // It's easier to remove unreachable blocks than deal with missing shadow.
  756. removeUnreachableBlocks(F);
  757. // Iterate all BBs in depth-first order and create shadow instructions
  758. // for all instructions (where applicable).
  759. // For PHI nodes we create dummy shadow PHIs which will be finalized later.
  760. for (BasicBlock *BB : depth_first(&F.getEntryBlock()))
  761. visit(*BB);
  762. // Finalize PHI nodes.
  763. for (PHINode *PN : ShadowPHINodes) {
  764. PHINode *PNS = cast<PHINode>(getShadow(PN));
  765. PHINode *PNO = MS.TrackOrigins ? cast<PHINode>(getOrigin(PN)) : nullptr;
  766. size_t NumValues = PN->getNumIncomingValues();
  767. for (size_t v = 0; v < NumValues; v++) {
  768. PNS->addIncoming(getShadow(PN, v), PN->getIncomingBlock(v));
  769. if (PNO) PNO->addIncoming(getOrigin(PN, v), PN->getIncomingBlock(v));
  770. }
  771. }
  772. VAHelper->finalizeInstrumentation();
  773. bool InstrumentWithCalls = ClInstrumentationWithCallThreshold >= 0 &&
  774. InstrumentationList.size() + StoreList.size() >
  775. (unsigned)ClInstrumentationWithCallThreshold;
  776. // Delayed instrumentation of StoreInst.
  777. // This may add new checks to be inserted later.
  778. materializeStores(InstrumentWithCalls);
  779. // Insert shadow value checks.
  780. materializeChecks(InstrumentWithCalls);
  781. return true;
  782. }
  783. /// \brief Compute the shadow type that corresponds to a given Value.
  784. Type *getShadowTy(Value *V) {
  785. return getShadowTy(V->getType());
  786. }
  787. /// \brief Compute the shadow type that corresponds to a given Type.
  788. Type *getShadowTy(Type *OrigTy) {
  789. if (!OrigTy->isSized()) {
  790. return nullptr;
  791. }
  792. // For integer type, shadow is the same as the original type.
  793. // This may return weird-sized types like i1.
  794. if (IntegerType *IT = dyn_cast<IntegerType>(OrigTy))
  795. return IT;
  796. const DataLayout &DL = F.getParent()->getDataLayout();
  797. if (VectorType *VT = dyn_cast<VectorType>(OrigTy)) {
  798. uint32_t EltSize = DL.getTypeSizeInBits(VT->getElementType());
  799. return VectorType::get(IntegerType::get(*MS.C, EltSize),
  800. VT->getNumElements());
  801. }
  802. if (ArrayType *AT = dyn_cast<ArrayType>(OrigTy)) {
  803. return ArrayType::get(getShadowTy(AT->getElementType()),
  804. AT->getNumElements());
  805. }
  806. if (StructType *ST = dyn_cast<StructType>(OrigTy)) {
  807. SmallVector<Type*, 4> Elements;
  808. for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
  809. Elements.push_back(getShadowTy(ST->getElementType(i)));
  810. StructType *Res = StructType::get(*MS.C, Elements, ST->isPacked());
  811. DEBUG(dbgs() << "getShadowTy: " << *ST << " ===> " << *Res << "\n");
  812. return Res;
  813. }
  814. uint32_t TypeSize = DL.getTypeSizeInBits(OrigTy);
  815. return IntegerType::get(*MS.C, TypeSize);
  816. }
  817. /// \brief Flatten a vector type.
  818. Type *getShadowTyNoVec(Type *ty) {
  819. if (VectorType *vt = dyn_cast<VectorType>(ty))
  820. return IntegerType::get(*MS.C, vt->getBitWidth());
  821. return ty;
  822. }
  823. /// \brief Convert a shadow value to it's flattened variant.
  824. Value *convertToShadowTyNoVec(Value *V, IRBuilder<> &IRB) {
  825. Type *Ty = V->getType();
  826. Type *NoVecTy = getShadowTyNoVec(Ty);
  827. if (Ty == NoVecTy) return V;
  828. return IRB.CreateBitCast(V, NoVecTy);
  829. }
  830. /// \brief Compute the integer shadow offset that corresponds to a given
  831. /// application address.
  832. ///
  833. /// Offset = (Addr & ~AndMask) ^ XorMask
  834. Value *getShadowPtrOffset(Value *Addr, IRBuilder<> &IRB) {
  835. Value *OffsetLong = IRB.CreatePointerCast(Addr, MS.IntptrTy);
  836. uint64_t AndMask = MS.MapParams->AndMask;
  837. if (AndMask)
  838. OffsetLong =
  839. IRB.CreateAnd(OffsetLong, ConstantInt::get(MS.IntptrTy, ~AndMask));
  840. uint64_t XorMask = MS.MapParams->XorMask;
  841. if (XorMask)
  842. OffsetLong =
  843. IRB.CreateXor(OffsetLong, ConstantInt::get(MS.IntptrTy, XorMask));
  844. return OffsetLong;
  845. }
  846. /// \brief Compute the shadow address that corresponds to a given application
  847. /// address.
  848. ///
  849. /// Shadow = ShadowBase + Offset
  850. Value *getShadowPtr(Value *Addr, Type *ShadowTy,
  851. IRBuilder<> &IRB) {
  852. Value *ShadowLong = getShadowPtrOffset(Addr, IRB);
  853. uint64_t ShadowBase = MS.MapParams->ShadowBase;
  854. if (ShadowBase != 0)
  855. ShadowLong =
  856. IRB.CreateAdd(ShadowLong,
  857. ConstantInt::get(MS.IntptrTy, ShadowBase));
  858. return IRB.CreateIntToPtr(ShadowLong, PointerType::get(ShadowTy, 0));
  859. }
  860. /// \brief Compute the origin address that corresponds to a given application
  861. /// address.
  862. ///
  863. /// OriginAddr = (OriginBase + Offset) & ~3ULL
  864. Value *getOriginPtr(Value *Addr, IRBuilder<> &IRB, unsigned Alignment) {
  865. Value *OriginLong = getShadowPtrOffset(Addr, IRB);
  866. uint64_t OriginBase = MS.MapParams->OriginBase;
  867. if (OriginBase != 0)
  868. OriginLong =
  869. IRB.CreateAdd(OriginLong,
  870. ConstantInt::get(MS.IntptrTy, OriginBase));
  871. if (Alignment < kMinOriginAlignment) {
  872. uint64_t Mask = kMinOriginAlignment - 1;
  873. OriginLong = IRB.CreateAnd(OriginLong,
  874. ConstantInt::get(MS.IntptrTy, ~Mask));
  875. }
  876. return IRB.CreateIntToPtr(OriginLong,
  877. PointerType::get(IRB.getInt32Ty(), 0));
  878. }
  879. /// \brief Compute the shadow address for a given function argument.
  880. ///
  881. /// Shadow = ParamTLS+ArgOffset.
  882. Value *getShadowPtrForArgument(Value *A, IRBuilder<> &IRB,
  883. int ArgOffset) {
  884. Value *Base = IRB.CreatePointerCast(MS.ParamTLS, MS.IntptrTy);
  885. Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
  886. return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
  887. "_msarg");
  888. }
  889. /// \brief Compute the origin address for a given function argument.
  890. Value *getOriginPtrForArgument(Value *A, IRBuilder<> &IRB,
  891. int ArgOffset) {
  892. if (!MS.TrackOrigins) return nullptr;
  893. Value *Base = IRB.CreatePointerCast(MS.ParamOriginTLS, MS.IntptrTy);
  894. Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
  895. return IRB.CreateIntToPtr(Base, PointerType::get(MS.OriginTy, 0),
  896. "_msarg_o");
  897. }
  898. /// \brief Compute the shadow address for a retval.
  899. Value *getShadowPtrForRetval(Value *A, IRBuilder<> &IRB) {
  900. Value *Base = IRB.CreatePointerCast(MS.RetvalTLS, MS.IntptrTy);
  901. return IRB.CreateIntToPtr(Base, PointerType::get(getShadowTy(A), 0),
  902. "_msret");
  903. }
  904. /// \brief Compute the origin address for a retval.
  905. Value *getOriginPtrForRetval(IRBuilder<> &IRB) {
  906. // We keep a single origin for the entire retval. Might be too optimistic.
  907. return MS.RetvalOriginTLS;
  908. }
  909. /// \brief Set SV to be the shadow value for V.
  910. void setShadow(Value *V, Value *SV) {
  911. assert(!ShadowMap.count(V) && "Values may only have one shadow");
  912. ShadowMap[V] = PropagateShadow ? SV : getCleanShadow(V);
  913. }
  914. /// \brief Set Origin to be the origin value for V.
  915. void setOrigin(Value *V, Value *Origin) {
  916. if (!MS.TrackOrigins) return;
  917. assert(!OriginMap.count(V) && "Values may only have one origin");
  918. DEBUG(dbgs() << "ORIGIN: " << *V << " ==> " << *Origin << "\n");
  919. OriginMap[V] = Origin;
  920. }
  921. Constant *getCleanShadow(Type *OrigTy) {
  922. Type *ShadowTy = getShadowTy(OrigTy);
  923. if (!ShadowTy)
  924. return nullptr;
  925. return Constant::getNullValue(ShadowTy);
  926. }
  927. /// \brief Create a clean shadow value for a given value.
  928. ///
  929. /// Clean shadow (all zeroes) means all bits of the value are defined
  930. /// (initialized).
  931. Constant *getCleanShadow(Value *V) {
  932. return getCleanShadow(V->getType());
  933. }
  934. /// \brief Create a dirty shadow of a given shadow type.
  935. Constant *getPoisonedShadow(Type *ShadowTy) {
  936. assert(ShadowTy);
  937. if (isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy))
  938. return Constant::getAllOnesValue(ShadowTy);
  939. if (ArrayType *AT = dyn_cast<ArrayType>(ShadowTy)) {
  940. SmallVector<Constant *, 4> Vals(AT->getNumElements(),
  941. getPoisonedShadow(AT->getElementType()));
  942. return ConstantArray::get(AT, Vals);
  943. }
  944. if (StructType *ST = dyn_cast<StructType>(ShadowTy)) {
  945. SmallVector<Constant *, 4> Vals;
  946. for (unsigned i = 0, n = ST->getNumElements(); i < n; i++)
  947. Vals.push_back(getPoisonedShadow(ST->getElementType(i)));
  948. return ConstantStruct::get(ST, Vals);
  949. }
  950. llvm_unreachable("Unexpected shadow type");
  951. }
  952. /// \brief Create a dirty shadow for a given value.
  953. Constant *getPoisonedShadow(Value *V) {
  954. Type *ShadowTy = getShadowTy(V);
  955. if (!ShadowTy)
  956. return nullptr;
  957. return getPoisonedShadow(ShadowTy);
  958. }
  959. /// \brief Create a clean (zero) origin.
  960. Value *getCleanOrigin() {
  961. return Constant::getNullValue(MS.OriginTy);
  962. }
  963. /// \brief Get the shadow value for a given Value.
  964. ///
  965. /// This function either returns the value set earlier with setShadow,
  966. /// or extracts if from ParamTLS (for function arguments).
  967. Value *getShadow(Value *V) {
  968. if (!PropagateShadow) return getCleanShadow(V);
  969. if (Instruction *I = dyn_cast<Instruction>(V)) {
  970. // For instructions the shadow is already stored in the map.
  971. Value *Shadow = ShadowMap[V];
  972. if (!Shadow) {
  973. DEBUG(dbgs() << "No shadow: " << *V << "\n" << *(I->getParent()));
  974. (void)I;
  975. assert(Shadow && "No shadow for a value");
  976. }
  977. return Shadow;
  978. }
  979. if (UndefValue *U = dyn_cast<UndefValue>(V)) {
  980. Value *AllOnes = PoisonUndef ? getPoisonedShadow(V) : getCleanShadow(V);
  981. DEBUG(dbgs() << "Undef: " << *U << " ==> " << *AllOnes << "\n");
  982. (void)U;
  983. return AllOnes;
  984. }
  985. if (Argument *A = dyn_cast<Argument>(V)) {
  986. // For arguments we compute the shadow on demand and store it in the map.
  987. Value **ShadowPtr = &ShadowMap[V];
  988. if (*ShadowPtr)
  989. return *ShadowPtr;
  990. Function *F = A->getParent();
  991. IRBuilder<> EntryIRB(F->getEntryBlock().getFirstNonPHI());
  992. unsigned ArgOffset = 0;
  993. const DataLayout &DL = F->getParent()->getDataLayout();
  994. for (auto &FArg : F->args()) {
  995. if (!FArg.getType()->isSized()) {
  996. DEBUG(dbgs() << "Arg is not sized\n");
  997. continue;
  998. }
  999. unsigned Size =
  1000. FArg.hasByValAttr()
  1001. ? DL.getTypeAllocSize(FArg.getType()->getPointerElementType())
  1002. : DL.getTypeAllocSize(FArg.getType());
  1003. if (A == &FArg) {
  1004. bool Overflow = ArgOffset + Size > kParamTLSSize;
  1005. Value *Base = getShadowPtrForArgument(&FArg, EntryIRB, ArgOffset);
  1006. if (FArg.hasByValAttr()) {
  1007. // ByVal pointer itself has clean shadow. We copy the actual
  1008. // argument shadow to the underlying memory.
  1009. // Figure out maximal valid memcpy alignment.
  1010. unsigned ArgAlign = FArg.getParamAlignment();
  1011. if (ArgAlign == 0) {
  1012. Type *EltType = A->getType()->getPointerElementType();
  1013. ArgAlign = DL.getABITypeAlignment(EltType);
  1014. }
  1015. if (Overflow) {
  1016. // ParamTLS overflow.
  1017. EntryIRB.CreateMemSet(
  1018. getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB),
  1019. Constant::getNullValue(EntryIRB.getInt8Ty()), Size, ArgAlign);
  1020. } else {
  1021. unsigned CopyAlign = std::min(ArgAlign, kShadowTLSAlignment);
  1022. Value *Cpy = EntryIRB.CreateMemCpy(
  1023. getShadowPtr(V, EntryIRB.getInt8Ty(), EntryIRB), Base, Size,
  1024. CopyAlign);
  1025. DEBUG(dbgs() << " ByValCpy: " << *Cpy << "\n");
  1026. (void)Cpy;
  1027. }
  1028. *ShadowPtr = getCleanShadow(V);
  1029. } else {
  1030. if (Overflow) {
  1031. // ParamTLS overflow.
  1032. *ShadowPtr = getCleanShadow(V);
  1033. } else {
  1034. *ShadowPtr =
  1035. EntryIRB.CreateAlignedLoad(Base, kShadowTLSAlignment);
  1036. }
  1037. }
  1038. DEBUG(dbgs() << " ARG: " << FArg << " ==> " <<
  1039. **ShadowPtr << "\n");
  1040. if (MS.TrackOrigins && !Overflow) {
  1041. Value *OriginPtr =
  1042. getOriginPtrForArgument(&FArg, EntryIRB, ArgOffset);
  1043. setOrigin(A, EntryIRB.CreateLoad(OriginPtr));
  1044. } else {
  1045. setOrigin(A, getCleanOrigin());
  1046. }
  1047. }
  1048. ArgOffset += alignTo(Size, kShadowTLSAlignment);
  1049. }
  1050. assert(*ShadowPtr && "Could not find shadow for an argument");
  1051. return *ShadowPtr;
  1052. }
  1053. // For everything else the shadow is zero.
  1054. return getCleanShadow(V);
  1055. }
  1056. /// \brief Get the shadow for i-th argument of the instruction I.
  1057. Value *getShadow(Instruction *I, int i) {
  1058. return getShadow(I->getOperand(i));
  1059. }
  1060. /// \brief Get the origin for a value.
  1061. Value *getOrigin(Value *V) {
  1062. if (!MS.TrackOrigins) return nullptr;
  1063. if (!PropagateShadow) return getCleanOrigin();
  1064. if (isa<Constant>(V)) return getCleanOrigin();
  1065. assert((isa<Instruction>(V) || isa<Argument>(V)) &&
  1066. "Unexpected value type in getOrigin()");
  1067. Value *Origin = OriginMap[V];
  1068. assert(Origin && "Missing origin");
  1069. return Origin;
  1070. }
  1071. /// \brief Get the origin for i-th argument of the instruction I.
  1072. Value *getOrigin(Instruction *I, int i) {
  1073. return getOrigin(I->getOperand(i));
  1074. }
  1075. /// \brief Remember the place where a shadow check should be inserted.
  1076. ///
  1077. /// This location will be later instrumented with a check that will print a
  1078. /// UMR warning in runtime if the shadow value is not 0.
  1079. void insertShadowCheck(Value *Shadow, Value *Origin, Instruction *OrigIns) {
  1080. assert(Shadow);
  1081. if (!InsertChecks) return;
  1082. #ifndef NDEBUG
  1083. Type *ShadowTy = Shadow->getType();
  1084. assert((isa<IntegerType>(ShadowTy) || isa<VectorType>(ShadowTy)) &&
  1085. "Can only insert checks for integer and vector shadow types");
  1086. #endif
  1087. InstrumentationList.push_back(
  1088. ShadowOriginAndInsertPoint(Shadow, Origin, OrigIns));
  1089. }
  1090. /// \brief Remember the place where a shadow check should be inserted.
  1091. ///
  1092. /// This location will be later instrumented with a check that will print a
  1093. /// UMR warning in runtime if the value is not fully defined.
  1094. void insertShadowCheck(Value *Val, Instruction *OrigIns) {
  1095. assert(Val);
  1096. Value *Shadow, *Origin;
  1097. if (ClCheckConstantShadow) {
  1098. Shadow = getShadow(Val);
  1099. if (!Shadow) return;
  1100. Origin = getOrigin(Val);
  1101. } else {
  1102. Shadow = dyn_cast_or_null<Instruction>(getShadow(Val));
  1103. if (!Shadow) return;
  1104. Origin = dyn_cast_or_null<Instruction>(getOrigin(Val));
  1105. }
  1106. insertShadowCheck(Shadow, Origin, OrigIns);
  1107. }
  1108. AtomicOrdering addReleaseOrdering(AtomicOrdering a) {
  1109. switch (a) {
  1110. case AtomicOrdering::NotAtomic:
  1111. return AtomicOrdering::NotAtomic;
  1112. case AtomicOrdering::Unordered:
  1113. case AtomicOrdering::Monotonic:
  1114. case AtomicOrdering::Release:
  1115. return AtomicOrdering::Release;
  1116. case AtomicOrdering::Acquire:
  1117. case AtomicOrdering::AcquireRelease:
  1118. return AtomicOrdering::AcquireRelease;
  1119. case AtomicOrdering::SequentiallyConsistent:
  1120. return AtomicOrdering::SequentiallyConsistent;
  1121. }
  1122. llvm_unreachable("Unknown ordering");
  1123. }
  1124. AtomicOrdering addAcquireOrdering(AtomicOrdering a) {
  1125. switch (a) {
  1126. case AtomicOrdering::NotAtomic:
  1127. return AtomicOrdering::NotAtomic;
  1128. case AtomicOrdering::Unordered:
  1129. case AtomicOrdering::Monotonic:
  1130. case AtomicOrdering::Acquire:
  1131. return AtomicOrdering::Acquire;
  1132. case AtomicOrdering::Release:
  1133. case AtomicOrdering::AcquireRelease:
  1134. return AtomicOrdering::AcquireRelease;
  1135. case AtomicOrdering::SequentiallyConsistent:
  1136. return AtomicOrdering::SequentiallyConsistent;
  1137. }
  1138. llvm_unreachable("Unknown ordering");
  1139. }
  1140. // ------------------- Visitors.
  1141. /// \brief Instrument LoadInst
  1142. ///
  1143. /// Loads the corresponding shadow and (optionally) origin.
  1144. /// Optionally, checks that the load address is fully defined.
  1145. void visitLoadInst(LoadInst &I) {
  1146. assert(I.getType()->isSized() && "Load type must have size");
  1147. IRBuilder<> IRB(I.getNextNode());
  1148. Type *ShadowTy = getShadowTy(&I);
  1149. Value *Addr = I.getPointerOperand();
  1150. if (PropagateShadow && !I.getMetadata("nosanitize")) {
  1151. Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
  1152. setShadow(&I,
  1153. IRB.CreateAlignedLoad(ShadowPtr, I.getAlignment(), "_msld"));
  1154. } else {
  1155. setShadow(&I, getCleanShadow(&I));
  1156. }
  1157. if (ClCheckAccessAddress)
  1158. insertShadowCheck(I.getPointerOperand(), &I);
  1159. if (I.isAtomic())
  1160. I.setOrdering(addAcquireOrdering(I.getOrdering()));
  1161. if (MS.TrackOrigins) {
  1162. if (PropagateShadow) {
  1163. unsigned Alignment = I.getAlignment();
  1164. unsigned OriginAlignment = std::max(kMinOriginAlignment, Alignment);
  1165. setOrigin(&I, IRB.CreateAlignedLoad(getOriginPtr(Addr, IRB, Alignment),
  1166. OriginAlignment));
  1167. } else {
  1168. setOrigin(&I, getCleanOrigin());
  1169. }
  1170. }
  1171. }
  1172. /// \brief Instrument StoreInst
  1173. ///
  1174. /// Stores the corresponding shadow and (optionally) origin.
  1175. /// Optionally, checks that the store address is fully defined.
  1176. void visitStoreInst(StoreInst &I) {
  1177. StoreList.push_back(&I);
  1178. }
  1179. void handleCASOrRMW(Instruction &I) {
  1180. assert(isa<AtomicRMWInst>(I) || isa<AtomicCmpXchgInst>(I));
  1181. IRBuilder<> IRB(&I);
  1182. Value *Addr = I.getOperand(0);
  1183. Value *ShadowPtr = getShadowPtr(Addr, I.getType(), IRB);
  1184. if (ClCheckAccessAddress)
  1185. insertShadowCheck(Addr, &I);
  1186. // Only test the conditional argument of cmpxchg instruction.
  1187. // The other argument can potentially be uninitialized, but we can not
  1188. // detect this situation reliably without possible false positives.
  1189. if (isa<AtomicCmpXchgInst>(I))
  1190. insertShadowCheck(I.getOperand(1), &I);
  1191. IRB.CreateStore(getCleanShadow(&I), ShadowPtr);
  1192. setShadow(&I, getCleanShadow(&I));
  1193. setOrigin(&I, getCleanOrigin());
  1194. }
  1195. void visitAtomicRMWInst(AtomicRMWInst &I) {
  1196. handleCASOrRMW(I);
  1197. I.setOrdering(addReleaseOrdering(I.getOrdering()));
  1198. }
  1199. void visitAtomicCmpXchgInst(AtomicCmpXchgInst &I) {
  1200. handleCASOrRMW(I);
  1201. I.setSuccessOrdering(addReleaseOrdering(I.getSuccessOrdering()));
  1202. }
  1203. // Vector manipulation.
  1204. void visitExtractElementInst(ExtractElementInst &I) {
  1205. insertShadowCheck(I.getOperand(1), &I);
  1206. IRBuilder<> IRB(&I);
  1207. setShadow(&I, IRB.CreateExtractElement(getShadow(&I, 0), I.getOperand(1),
  1208. "_msprop"));
  1209. setOrigin(&I, getOrigin(&I, 0));
  1210. }
  1211. void visitInsertElementInst(InsertElementInst &I) {
  1212. insertShadowCheck(I.getOperand(2), &I);
  1213. IRBuilder<> IRB(&I);
  1214. setShadow(&I, IRB.CreateInsertElement(getShadow(&I, 0), getShadow(&I, 1),
  1215. I.getOperand(2), "_msprop"));
  1216. setOriginForNaryOp(I);
  1217. }
  1218. void visitShuffleVectorInst(ShuffleVectorInst &I) {
  1219. insertShadowCheck(I.getOperand(2), &I);
  1220. IRBuilder<> IRB(&I);
  1221. setShadow(&I, IRB.CreateShuffleVector(getShadow(&I, 0), getShadow(&I, 1),
  1222. I.getOperand(2), "_msprop"));
  1223. setOriginForNaryOp(I);
  1224. }
  1225. // Casts.
  1226. void visitSExtInst(SExtInst &I) {
  1227. IRBuilder<> IRB(&I);
  1228. setShadow(&I, IRB.CreateSExt(getShadow(&I, 0), I.getType(), "_msprop"));
  1229. setOrigin(&I, getOrigin(&I, 0));
  1230. }
  1231. void visitZExtInst(ZExtInst &I) {
  1232. IRBuilder<> IRB(&I);
  1233. setShadow(&I, IRB.CreateZExt(getShadow(&I, 0), I.getType(), "_msprop"));
  1234. setOrigin(&I, getOrigin(&I, 0));
  1235. }
  1236. void visitTruncInst(TruncInst &I) {
  1237. IRBuilder<> IRB(&I);
  1238. setShadow(&I, IRB.CreateTrunc(getShadow(&I, 0), I.getType(), "_msprop"));
  1239. setOrigin(&I, getOrigin(&I, 0));
  1240. }
  1241. void visitBitCastInst(BitCastInst &I) {
  1242. // Special case: if this is the bitcast (there is exactly 1 allowed) between
  1243. // a musttail call and a ret, don't instrument. New instructions are not
  1244. // allowed after a musttail call.
  1245. if (auto *CI = dyn_cast<CallInst>(I.getOperand(0)))
  1246. if (CI->isMustTailCall())
  1247. return;
  1248. IRBuilder<> IRB(&I);
  1249. setShadow(&I, IRB.CreateBitCast(getShadow(&I, 0), getShadowTy(&I)));
  1250. setOrigin(&I, getOrigin(&I, 0));
  1251. }
  1252. void visitPtrToIntInst(PtrToIntInst &I) {
  1253. IRBuilder<> IRB(&I);
  1254. setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
  1255. "_msprop_ptrtoint"));
  1256. setOrigin(&I, getOrigin(&I, 0));
  1257. }
  1258. void visitIntToPtrInst(IntToPtrInst &I) {
  1259. IRBuilder<> IRB(&I);
  1260. setShadow(&I, IRB.CreateIntCast(getShadow(&I, 0), getShadowTy(&I), false,
  1261. "_msprop_inttoptr"));
  1262. setOrigin(&I, getOrigin(&I, 0));
  1263. }
  1264. void visitFPToSIInst(CastInst& I) { handleShadowOr(I); }
  1265. void visitFPToUIInst(CastInst& I) { handleShadowOr(I); }
  1266. void visitSIToFPInst(CastInst& I) { handleShadowOr(I); }
  1267. void visitUIToFPInst(CastInst& I) { handleShadowOr(I); }
  1268. void visitFPExtInst(CastInst& I) { handleShadowOr(I); }
  1269. void visitFPTruncInst(CastInst& I) { handleShadowOr(I); }
  1270. /// \brief Propagate shadow for bitwise AND.
  1271. ///
  1272. /// This code is exact, i.e. if, for example, a bit in the left argument
  1273. /// is defined and 0, then neither the value not definedness of the
  1274. /// corresponding bit in B don't affect the resulting shadow.
  1275. void visitAnd(BinaryOperator &I) {
  1276. IRBuilder<> IRB(&I);
  1277. // "And" of 0 and a poisoned value results in unpoisoned value.
  1278. // 1&1 => 1; 0&1 => 0; p&1 => p;
  1279. // 1&0 => 0; 0&0 => 0; p&0 => 0;
  1280. // 1&p => p; 0&p => 0; p&p => p;
  1281. // S = (S1 & S2) | (V1 & S2) | (S1 & V2)
  1282. Value *S1 = getShadow(&I, 0);
  1283. Value *S2 = getShadow(&I, 1);
  1284. Value *V1 = I.getOperand(0);
  1285. Value *V2 = I.getOperand(1);
  1286. if (V1->getType() != S1->getType()) {
  1287. V1 = IRB.CreateIntCast(V1, S1->getType(), false);
  1288. V2 = IRB.CreateIntCast(V2, S2->getType(), false);
  1289. }
  1290. Value *S1S2 = IRB.CreateAnd(S1, S2);
  1291. Value *V1S2 = IRB.CreateAnd(V1, S2);
  1292. Value *S1V2 = IRB.CreateAnd(S1, V2);
  1293. setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
  1294. setOriginForNaryOp(I);
  1295. }
  1296. void visitOr(BinaryOperator &I) {
  1297. IRBuilder<> IRB(&I);
  1298. // "Or" of 1 and a poisoned value results in unpoisoned value.
  1299. // 1|1 => 1; 0|1 => 1; p|1 => 1;
  1300. // 1|0 => 1; 0|0 => 0; p|0 => p;
  1301. // 1|p => 1; 0|p => p; p|p => p;
  1302. // S = (S1 & S2) | (~V1 & S2) | (S1 & ~V2)
  1303. Value *S1 = getShadow(&I, 0);
  1304. Value *S2 = getShadow(&I, 1);
  1305. Value *V1 = IRB.CreateNot(I.getOperand(0));
  1306. Value *V2 = IRB.CreateNot(I.getOperand(1));
  1307. if (V1->getType() != S1->getType()) {
  1308. V1 = IRB.CreateIntCast(V1, S1->getType(), false);
  1309. V2 = IRB.CreateIntCast(V2, S2->getType(), false);
  1310. }
  1311. Value *S1S2 = IRB.CreateAnd(S1, S2);
  1312. Value *V1S2 = IRB.CreateAnd(V1, S2);
  1313. Value *S1V2 = IRB.CreateAnd(S1, V2);
  1314. setShadow(&I, IRB.CreateOr(S1S2, IRB.CreateOr(V1S2, S1V2)));
  1315. setOriginForNaryOp(I);
  1316. }
  1317. /// \brief Default propagation of shadow and/or origin.
  1318. ///
  1319. /// This class implements the general case of shadow propagation, used in all
  1320. /// cases where we don't know and/or don't care about what the operation
  1321. /// actually does. It converts all input shadow values to a common type
  1322. /// (extending or truncating as necessary), and bitwise OR's them.
  1323. ///
  1324. /// This is much cheaper than inserting checks (i.e. requiring inputs to be
  1325. /// fully initialized), and less prone to false positives.
  1326. ///
  1327. /// This class also implements the general case of origin propagation. For a
  1328. /// Nary operation, result origin is set to the origin of an argument that is
  1329. /// not entirely initialized. If there is more than one such arguments, the
  1330. /// rightmost of them is picked. It does not matter which one is picked if all
  1331. /// arguments are initialized.
  1332. template <bool CombineShadow>
  1333. class Combiner {
  1334. Value *Shadow;
  1335. Value *Origin;
  1336. IRBuilder<> &IRB;
  1337. MemorySanitizerVisitor *MSV;
  1338. public:
  1339. Combiner(MemorySanitizerVisitor *MSV, IRBuilder<> &IRB) :
  1340. Shadow(nullptr), Origin(nullptr), IRB(IRB), MSV(MSV) {}
  1341. /// \brief Add a pair of shadow and origin values to the mix.
  1342. Combiner &Add(Value *OpShadow, Value *OpOrigin) {
  1343. if (CombineShadow) {
  1344. assert(OpShadow);
  1345. if (!Shadow)
  1346. Shadow = OpShadow;
  1347. else {
  1348. OpShadow = MSV->CreateShadowCast(IRB, OpShadow, Shadow->getType());
  1349. Shadow = IRB.CreateOr(Shadow, OpShadow, "_msprop");
  1350. }
  1351. }
  1352. if (MSV->MS.TrackOrigins) {
  1353. assert(OpOrigin);
  1354. if (!Origin) {
  1355. Origin = OpOrigin;
  1356. } else {
  1357. Constant *ConstOrigin = dyn_cast<Constant>(OpOrigin);
  1358. // No point in adding something that might result in 0 origin value.
  1359. if (!ConstOrigin || !ConstOrigin->isNullValue()) {
  1360. Value *FlatShadow = MSV->convertToShadowTyNoVec(OpShadow, IRB);
  1361. Value *Cond =
  1362. IRB.CreateICmpNE(FlatShadow, MSV->getCleanShadow(FlatShadow));
  1363. Origin = IRB.CreateSelect(Cond, OpOrigin, Origin);
  1364. }
  1365. }
  1366. }
  1367. return *this;
  1368. }
  1369. /// \brief Add an application value to the mix.
  1370. Combiner &Add(Value *V) {
  1371. Value *OpShadow = MSV->getShadow(V);
  1372. Value *OpOrigin = MSV->MS.TrackOrigins ? MSV->getOrigin(V) : nullptr;
  1373. return Add(OpShadow, OpOrigin);
  1374. }
  1375. /// \brief Set the current combined values as the given instruction's shadow
  1376. /// and origin.
  1377. void Done(Instruction *I) {
  1378. if (CombineShadow) {
  1379. assert(Shadow);
  1380. Shadow = MSV->CreateShadowCast(IRB, Shadow, MSV->getShadowTy(I));
  1381. MSV->setShadow(I, Shadow);
  1382. }
  1383. if (MSV->MS.TrackOrigins) {
  1384. assert(Origin);
  1385. MSV->setOrigin(I, Origin);
  1386. }
  1387. }
  1388. };
  1389. typedef Combiner<true> ShadowAndOriginCombiner;
  1390. typedef Combiner<false> OriginCombiner;
  1391. /// \brief Propagate origin for arbitrary operation.
  1392. void setOriginForNaryOp(Instruction &I) {
  1393. if (!MS.TrackOrigins) return;
  1394. IRBuilder<> IRB(&I);
  1395. OriginCombiner OC(this, IRB);
  1396. for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
  1397. OC.Add(OI->get());
  1398. OC.Done(&I);
  1399. }
  1400. size_t VectorOrPrimitiveTypeSizeInBits(Type *Ty) {
  1401. assert(!(Ty->isVectorTy() && Ty->getScalarType()->isPointerTy()) &&
  1402. "Vector of pointers is not a valid shadow type");
  1403. return Ty->isVectorTy() ?
  1404. Ty->getVectorNumElements() * Ty->getScalarSizeInBits() :
  1405. Ty->getPrimitiveSizeInBits();
  1406. }
  1407. /// \brief Cast between two shadow types, extending or truncating as
  1408. /// necessary.
  1409. Value *CreateShadowCast(IRBuilder<> &IRB, Value *V, Type *dstTy,
  1410. bool Signed = false) {
  1411. Type *srcTy = V->getType();
  1412. if (dstTy->isIntegerTy() && srcTy->isIntegerTy())
  1413. return IRB.CreateIntCast(V, dstTy, Signed);
  1414. if (dstTy->isVectorTy() && srcTy->isVectorTy() &&
  1415. dstTy->getVectorNumElements() == srcTy->getVectorNumElements())
  1416. return IRB.CreateIntCast(V, dstTy, Signed);
  1417. size_t srcSizeInBits = VectorOrPrimitiveTypeSizeInBits(srcTy);
  1418. size_t dstSizeInBits = VectorOrPrimitiveTypeSizeInBits(dstTy);
  1419. Value *V1 = IRB.CreateBitCast(V, Type::getIntNTy(*MS.C, srcSizeInBits));
  1420. Value *V2 =
  1421. IRB.CreateIntCast(V1, Type::getIntNTy(*MS.C, dstSizeInBits), Signed);
  1422. return IRB.CreateBitCast(V2, dstTy);
  1423. // TODO: handle struct types.
  1424. }
  1425. /// \brief Cast an application value to the type of its own shadow.
  1426. Value *CreateAppToShadowCast(IRBuilder<> &IRB, Value *V) {
  1427. Type *ShadowTy = getShadowTy(V);
  1428. if (V->getType() == ShadowTy)
  1429. return V;
  1430. if (V->getType()->isPtrOrPtrVectorTy())
  1431. return IRB.CreatePtrToInt(V, ShadowTy);
  1432. else
  1433. return IRB.CreateBitCast(V, ShadowTy);
  1434. }
  1435. /// \brief Propagate shadow for arbitrary operation.
  1436. void handleShadowOr(Instruction &I) {
  1437. IRBuilder<> IRB(&I);
  1438. ShadowAndOriginCombiner SC(this, IRB);
  1439. for (Instruction::op_iterator OI = I.op_begin(); OI != I.op_end(); ++OI)
  1440. SC.Add(OI->get());
  1441. SC.Done(&I);
  1442. }
  1443. // \brief Handle multiplication by constant.
  1444. //
  1445. // Handle a special case of multiplication by constant that may have one or
  1446. // more zeros in the lower bits. This makes corresponding number of lower bits
  1447. // of the result zero as well. We model it by shifting the other operand
  1448. // shadow left by the required number of bits. Effectively, we transform
  1449. // (X * (A * 2**B)) to ((X << B) * A) and instrument (X << B) as (Sx << B).
  1450. // We use multiplication by 2**N instead of shift to cover the case of
  1451. // multiplication by 0, which may occur in some elements of a vector operand.
  1452. void handleMulByConstant(BinaryOperator &I, Constant *ConstArg,
  1453. Value *OtherArg) {
  1454. Constant *ShadowMul;
  1455. Type *Ty = ConstArg->getType();
  1456. if (Ty->isVectorTy()) {
  1457. unsigned NumElements = Ty->getVectorNumElements();
  1458. Type *EltTy = Ty->getSequentialElementType();
  1459. SmallVector<Constant *, 16> Elements;
  1460. for (unsigned Idx = 0; Idx < NumElements; ++Idx) {
  1461. if (ConstantInt *Elt =
  1462. dyn_cast<ConstantInt>(ConstArg->getAggregateElement(Idx))) {
  1463. const APInt &V = Elt->getValue();
  1464. APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
  1465. Elements.push_back(ConstantInt::get(EltTy, V2));
  1466. } else {
  1467. Elements.push_back(ConstantInt::get(EltTy, 1));
  1468. }
  1469. }
  1470. ShadowMul = ConstantVector::get(Elements);
  1471. } else {
  1472. if (ConstantInt *Elt = dyn_cast<ConstantInt>(ConstArg)) {
  1473. const APInt &V = Elt->getValue();
  1474. APInt V2 = APInt(V.getBitWidth(), 1) << V.countTrailingZeros();
  1475. ShadowMul = ConstantInt::get(Ty, V2);
  1476. } else {
  1477. ShadowMul = ConstantInt::get(Ty, 1);
  1478. }
  1479. }
  1480. IRBuilder<> IRB(&I);
  1481. setShadow(&I,
  1482. IRB.CreateMul(getShadow(OtherArg), ShadowMul, "msprop_mul_cst"));
  1483. setOrigin(&I, getOrigin(OtherArg));
  1484. }
  1485. void visitMul(BinaryOperator &I) {
  1486. Constant *constOp0 = dyn_cast<Constant>(I.getOperand(0));
  1487. Constant *constOp1 = dyn_cast<Constant>(I.getOperand(1));
  1488. if (constOp0 && !constOp1)
  1489. handleMulByConstant(I, constOp0, I.getOperand(1));
  1490. else if (constOp1 && !constOp0)
  1491. handleMulByConstant(I, constOp1, I.getOperand(0));
  1492. else
  1493. handleShadowOr(I);
  1494. }
  1495. void visitFAdd(BinaryOperator &I) { handleShadowOr(I); }
  1496. void visitFSub(BinaryOperator &I) { handleShadowOr(I); }
  1497. void visitFMul(BinaryOperator &I) { handleShadowOr(I); }
  1498. void visitAdd(BinaryOperator &I) { handleShadowOr(I); }
  1499. void visitSub(BinaryOperator &I) { handleShadowOr(I); }
  1500. void visitXor(BinaryOperator &I) { handleShadowOr(I); }
  1501. void handleDiv(Instruction &I) {
  1502. IRBuilder<> IRB(&I);
  1503. // Strict on the second argument.
  1504. insertShadowCheck(I.getOperand(1), &I);
  1505. setShadow(&I, getShadow(&I, 0));
  1506. setOrigin(&I, getOrigin(&I, 0));
  1507. }
  1508. void visitUDiv(BinaryOperator &I) { handleDiv(I); }
  1509. void visitSDiv(BinaryOperator &I) { handleDiv(I); }
  1510. void visitFDiv(BinaryOperator &I) { handleDiv(I); }
  1511. void visitURem(BinaryOperator &I) { handleDiv(I); }
  1512. void visitSRem(BinaryOperator &I) { handleDiv(I); }
  1513. void visitFRem(BinaryOperator &I) { handleDiv(I); }
  1514. /// \brief Instrument == and != comparisons.
  1515. ///
  1516. /// Sometimes the comparison result is known even if some of the bits of the
  1517. /// arguments are not.
  1518. void handleEqualityComparison(ICmpInst &I) {
  1519. IRBuilder<> IRB(&I);
  1520. Value *A = I.getOperand(0);
  1521. Value *B = I.getOperand(1);
  1522. Value *Sa = getShadow(A);
  1523. Value *Sb = getShadow(B);
  1524. // Get rid of pointers and vectors of pointers.
  1525. // For ints (and vectors of ints), types of A and Sa match,
  1526. // and this is a no-op.
  1527. A = IRB.CreatePointerCast(A, Sa->getType());
  1528. B = IRB.CreatePointerCast(B, Sb->getType());
  1529. // A == B <==> (C = A^B) == 0
  1530. // A != B <==> (C = A^B) != 0
  1531. // Sc = Sa | Sb
  1532. Value *C = IRB.CreateXor(A, B);
  1533. Value *Sc = IRB.CreateOr(Sa, Sb);
  1534. // Now dealing with i = (C == 0) comparison (or C != 0, does not matter now)
  1535. // Result is defined if one of the following is true
  1536. // * there is a defined 1 bit in C
  1537. // * C is fully defined
  1538. // Si = !(C & ~Sc) && Sc
  1539. Value *Zero = Constant::getNullValue(Sc->getType());
  1540. Value *MinusOne = Constant::getAllOnesValue(Sc->getType());
  1541. Value *Si =
  1542. IRB.CreateAnd(IRB.CreateICmpNE(Sc, Zero),
  1543. IRB.CreateICmpEQ(
  1544. IRB.CreateAnd(IRB.CreateXor(Sc, MinusOne), C), Zero));
  1545. Si->setName("_msprop_icmp");
  1546. setShadow(&I, Si);
  1547. setOriginForNaryOp(I);
  1548. }
  1549. /// \brief Build the lowest possible value of V, taking into account V's
  1550. /// uninitialized bits.
  1551. Value *getLowestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
  1552. bool isSigned) {
  1553. if (isSigned) {
  1554. // Split shadow into sign bit and other bits.
  1555. Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
  1556. Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
  1557. // Maximise the undefined shadow bit, minimize other undefined bits.
  1558. return
  1559. IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaOtherBits)), SaSignBit);
  1560. } else {
  1561. // Minimize undefined bits.
  1562. return IRB.CreateAnd(A, IRB.CreateNot(Sa));
  1563. }
  1564. }
  1565. /// \brief Build the highest possible value of V, taking into account V's
  1566. /// uninitialized bits.
  1567. Value *getHighestPossibleValue(IRBuilder<> &IRB, Value *A, Value *Sa,
  1568. bool isSigned) {
  1569. if (isSigned) {
  1570. // Split shadow into sign bit and other bits.
  1571. Value *SaOtherBits = IRB.CreateLShr(IRB.CreateShl(Sa, 1), 1);
  1572. Value *SaSignBit = IRB.CreateXor(Sa, SaOtherBits);
  1573. // Minimise the undefined shadow bit, maximise other undefined bits.
  1574. return
  1575. IRB.CreateOr(IRB.CreateAnd(A, IRB.CreateNot(SaSignBit)), SaOtherBits);
  1576. } else {
  1577. // Maximize undefined bits.
  1578. return IRB.CreateOr(A, Sa);
  1579. }
  1580. }
  1581. /// \brief Instrument relational comparisons.
  1582. ///
  1583. /// This function does exact shadow propagation for all relational
  1584. /// comparisons of integers, pointers and vectors of those.
  1585. /// FIXME: output seems suboptimal when one of the operands is a constant
  1586. void handleRelationalComparisonExact(ICmpInst &I) {
  1587. IRBuilder<> IRB(&I);
  1588. Value *A = I.getOperand(0);
  1589. Value *B = I.getOperand(1);
  1590. Value *Sa = getShadow(A);
  1591. Value *Sb = getShadow(B);
  1592. // Get rid of pointers and vectors of pointers.
  1593. // For ints (and vectors of ints), types of A and Sa match,
  1594. // and this is a no-op.
  1595. A = IRB.CreatePointerCast(A, Sa->getType());
  1596. B = IRB.CreatePointerCast(B, Sb->getType());
  1597. // Let [a0, a1] be the interval of possible values of A, taking into account
  1598. // its undefined bits. Let [b0, b1] be the interval of possible values of B.
  1599. // Then (A cmp B) is defined iff (a0 cmp b1) == (a1 cmp b0).
  1600. bool IsSigned = I.isSigned();
  1601. Value *S1 = IRB.CreateICmp(I.getPredicate(),
  1602. getLowestPossibleValue(IRB, A, Sa, IsSigned),
  1603. getHighestPossibleValue(IRB, B, Sb, IsSigned));
  1604. Value *S2 = IRB.CreateICmp(I.getPredicate(),
  1605. getHighestPossibleValue(IRB, A, Sa, IsSigned),
  1606. getLowestPossibleValue(IRB, B, Sb, IsSigned));
  1607. Value *Si = IRB.CreateXor(S1, S2);
  1608. setShadow(&I, Si);
  1609. setOriginForNaryOp(I);
  1610. }
  1611. /// \brief Instrument signed relational comparisons.
  1612. ///
  1613. /// Handle sign bit tests: x<0, x>=0, x<=-1, x>-1 by propagating the highest
  1614. /// bit of the shadow. Everything else is delegated to handleShadowOr().
  1615. void handleSignedRelationalComparison(ICmpInst &I) {
  1616. Constant *constOp;
  1617. Value *op = nullptr;
  1618. CmpInst::Predicate pre;
  1619. if ((constOp = dyn_cast<Constant>(I.getOperand(1)))) {
  1620. op = I.getOperand(0);
  1621. pre = I.getPredicate();
  1622. } else if ((constOp = dyn_cast<Constant>(I.getOperand(0)))) {
  1623. op = I.getOperand(1);
  1624. pre = I.getSwappedPredicate();
  1625. } else {
  1626. handleShadowOr(I);
  1627. return;
  1628. }
  1629. if ((constOp->isNullValue() &&
  1630. (pre == CmpInst::ICMP_SLT || pre == CmpInst::ICMP_SGE)) ||
  1631. (constOp->isAllOnesValue() &&
  1632. (pre == CmpInst::ICMP_SGT || pre == CmpInst::ICMP_SLE))) {
  1633. IRBuilder<> IRB(&I);
  1634. Value *Shadow = IRB.CreateICmpSLT(getShadow(op), getCleanShadow(op),
  1635. "_msprop_icmp_s");
  1636. setShadow(&I, Shadow);
  1637. setOrigin(&I, getOrigin(op));
  1638. } else {
  1639. handleShadowOr(I);
  1640. }
  1641. }
  1642. void visitICmpInst(ICmpInst &I) {
  1643. if (!ClHandleICmp) {
  1644. handleShadowOr(I);
  1645. return;
  1646. }
  1647. if (I.isEquality()) {
  1648. handleEqualityComparison(I);
  1649. return;
  1650. }
  1651. assert(I.isRelational());
  1652. if (ClHandleICmpExact) {
  1653. handleRelationalComparisonExact(I);
  1654. return;
  1655. }
  1656. if (I.isSigned()) {
  1657. handleSignedRelationalComparison(I);
  1658. return;
  1659. }
  1660. assert(I.isUnsigned());
  1661. if ((isa<Constant>(I.getOperand(0)) || isa<Constant>(I.getOperand(1)))) {
  1662. handleRelationalComparisonExact(I);
  1663. return;
  1664. }
  1665. handleShadowOr(I);
  1666. }
  1667. void visitFCmpInst(FCmpInst &I) {
  1668. handleShadowOr(I);
  1669. }
  1670. void handleShift(BinaryOperator &I) {
  1671. IRBuilder<> IRB(&I);
  1672. // If any of the S2 bits are poisoned, the whole thing is poisoned.
  1673. // Otherwise perform the same shift on S1.
  1674. Value *S1 = getShadow(&I, 0);
  1675. Value *S2 = getShadow(&I, 1);
  1676. Value *S2Conv = IRB.CreateSExt(IRB.CreateICmpNE(S2, getCleanShadow(S2)),
  1677. S2->getType());
  1678. Value *V2 = I.getOperand(1);
  1679. Value *Shift = IRB.CreateBinOp(I.getOpcode(), S1, V2);
  1680. setShadow(&I, IRB.CreateOr(Shift, S2Conv));
  1681. setOriginForNaryOp(I);
  1682. }
  1683. void visitShl(BinaryOperator &I) { handleShift(I); }
  1684. void visitAShr(BinaryOperator &I) { handleShift(I); }
  1685. void visitLShr(BinaryOperator &I) { handleShift(I); }
  1686. /// \brief Instrument llvm.memmove
  1687. ///
  1688. /// At this point we don't know if llvm.memmove will be inlined or not.
  1689. /// If we don't instrument it and it gets inlined,
  1690. /// our interceptor will not kick in and we will lose the memmove.
  1691. /// If we instrument the call here, but it does not get inlined,
  1692. /// we will memove the shadow twice: which is bad in case
  1693. /// of overlapping regions. So, we simply lower the intrinsic to a call.
  1694. ///
  1695. /// Similar situation exists for memcpy and memset.
  1696. void visitMemMoveInst(MemMoveInst &I) {
  1697. IRBuilder<> IRB(&I);
  1698. IRB.CreateCall(
  1699. MS.MemmoveFn,
  1700. {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
  1701. IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
  1702. IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
  1703. I.eraseFromParent();
  1704. }
  1705. // Similar to memmove: avoid copying shadow twice.
  1706. // This is somewhat unfortunate as it may slowdown small constant memcpys.
  1707. // FIXME: consider doing manual inline for small constant sizes and proper
  1708. // alignment.
  1709. void visitMemCpyInst(MemCpyInst &I) {
  1710. IRBuilder<> IRB(&I);
  1711. IRB.CreateCall(
  1712. MS.MemcpyFn,
  1713. {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
  1714. IRB.CreatePointerCast(I.getArgOperand(1), IRB.getInt8PtrTy()),
  1715. IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
  1716. I.eraseFromParent();
  1717. }
  1718. // Same as memcpy.
  1719. void visitMemSetInst(MemSetInst &I) {
  1720. IRBuilder<> IRB(&I);
  1721. IRB.CreateCall(
  1722. MS.MemsetFn,
  1723. {IRB.CreatePointerCast(I.getArgOperand(0), IRB.getInt8PtrTy()),
  1724. IRB.CreateIntCast(I.getArgOperand(1), IRB.getInt32Ty(), false),
  1725. IRB.CreateIntCast(I.getArgOperand(2), MS.IntptrTy, false)});
  1726. I.eraseFromParent();
  1727. }
  1728. void visitVAStartInst(VAStartInst &I) {
  1729. VAHelper->visitVAStartInst(I);
  1730. }
  1731. void visitVACopyInst(VACopyInst &I) {
  1732. VAHelper->visitVACopyInst(I);
  1733. }
  1734. /// \brief Handle vector store-like intrinsics.
  1735. ///
  1736. /// Instrument intrinsics that look like a simple SIMD store: writes memory,
  1737. /// has 1 pointer argument and 1 vector argument, returns void.
  1738. bool handleVectorStoreIntrinsic(IntrinsicInst &I) {
  1739. IRBuilder<> IRB(&I);
  1740. Value* Addr = I.getArgOperand(0);
  1741. Value *Shadow = getShadow(&I, 1);
  1742. Value *ShadowPtr = getShadowPtr(Addr, Shadow->getType(), IRB);
  1743. // We don't know the pointer alignment (could be unaligned SSE store!).
  1744. // Have to assume to worst case.
  1745. IRB.CreateAlignedStore(Shadow, ShadowPtr, 1);
  1746. if (ClCheckAccessAddress)
  1747. insertShadowCheck(Addr, &I);
  1748. // FIXME: factor out common code from materializeStores
  1749. if (MS.TrackOrigins)
  1750. IRB.CreateStore(getOrigin(&I, 1), getOriginPtr(Addr, IRB, 1));
  1751. return true;
  1752. }
  1753. /// \brief Handle vector load-like intrinsics.
  1754. ///
  1755. /// Instrument intrinsics that look like a simple SIMD load: reads memory,
  1756. /// has 1 pointer argument, returns a vector.
  1757. bool handleVectorLoadIntrinsic(IntrinsicInst &I) {
  1758. IRBuilder<> IRB(&I);
  1759. Value *Addr = I.getArgOperand(0);
  1760. Type *ShadowTy = getShadowTy(&I);
  1761. if (PropagateShadow) {
  1762. Value *ShadowPtr = getShadowPtr(Addr, ShadowTy, IRB);
  1763. // We don't know the pointer alignment (could be unaligned SSE load!).
  1764. // Have to assume to worst case.
  1765. setShadow(&I, IRB.CreateAlignedLoad(ShadowPtr, 1, "_msld"));
  1766. } else {
  1767. setShadow(&I, getCleanShadow(&I));
  1768. }
  1769. if (ClCheckAccessAddress)
  1770. insertShadowCheck(Addr, &I);
  1771. if (MS.TrackOrigins) {
  1772. if (PropagateShadow)
  1773. setOrigin(&I, IRB.CreateLoad(getOriginPtr(Addr, IRB, 1)));
  1774. else
  1775. setOrigin(&I, getCleanOrigin());
  1776. }
  1777. return true;
  1778. }
  1779. /// \brief Handle (SIMD arithmetic)-like intrinsics.
  1780. ///
  1781. /// Instrument intrinsics with any number of arguments of the same type,
  1782. /// equal to the return type. The type should be simple (no aggregates or
  1783. /// pointers; vectors are fine).
  1784. /// Caller guarantees that this intrinsic does not access memory.
  1785. bool maybeHandleSimpleNomemIntrinsic(IntrinsicInst &I) {
  1786. Type *RetTy = I.getType();
  1787. if (!(RetTy->isIntOrIntVectorTy() ||
  1788. RetTy->isFPOrFPVectorTy() ||
  1789. RetTy->isX86_MMXTy()))
  1790. return false;
  1791. unsigned NumArgOperands = I.getNumArgOperands();
  1792. for (unsigned i = 0; i < NumArgOperands; ++i) {
  1793. Type *Ty = I.getArgOperand(i)->getType();
  1794. if (Ty != RetTy)
  1795. return false;
  1796. }
  1797. IRBuilder<> IRB(&I);
  1798. ShadowAndOriginCombiner SC(this, IRB);
  1799. for (unsigned i = 0; i < NumArgOperands; ++i)
  1800. SC.Add(I.getArgOperand(i));
  1801. SC.Done(&I);
  1802. return true;
  1803. }
  1804. /// \brief Heuristically instrument unknown intrinsics.
  1805. ///
  1806. /// The main purpose of this code is to do something reasonable with all
  1807. /// random intrinsics we might encounter, most importantly - SIMD intrinsics.
  1808. /// We recognize several classes of intrinsics by their argument types and
  1809. /// ModRefBehaviour and apply special intrumentation when we are reasonably
  1810. /// sure that we know what the intrinsic does.
  1811. ///
  1812. /// We special-case intrinsics where this approach fails. See llvm.bswap
  1813. /// handling as an example of that.
  1814. bool handleUnknownIntrinsic(IntrinsicInst &I) {
  1815. unsigned NumArgOperands = I.getNumArgOperands();
  1816. if (NumArgOperands == 0)
  1817. return false;
  1818. if (NumArgOperands == 2 &&
  1819. I.getArgOperand(0)->getType()->isPointerTy() &&
  1820. I.getArgOperand(1)->getType()->isVectorTy() &&
  1821. I.getType()->isVoidTy() &&
  1822. !I.onlyReadsMemory()) {
  1823. // This looks like a vector store.
  1824. return handleVectorStoreIntrinsic(I);
  1825. }
  1826. if (NumArgOperands == 1 &&
  1827. I.getArgOperand(0)->getType()->isPointerTy() &&
  1828. I.getType()->isVectorTy() &&
  1829. I.onlyReadsMemory()) {
  1830. // This looks like a vector load.
  1831. return handleVectorLoadIntrinsic(I);
  1832. }
  1833. if (I.doesNotAccessMemory())
  1834. if (maybeHandleSimpleNomemIntrinsic(I))
  1835. return true;
  1836. // FIXME: detect and handle SSE maskstore/maskload
  1837. return false;
  1838. }
  1839. void handleBswap(IntrinsicInst &I) {
  1840. IRBuilder<> IRB(&I);
  1841. Value *Op = I.getArgOperand(0);
  1842. Type *OpType = Op->getType();
  1843. Function *BswapFunc = Intrinsic::getDeclaration(
  1844. F.getParent(), Intrinsic::bswap, makeArrayRef(&OpType, 1));
  1845. setShadow(&I, IRB.CreateCall(BswapFunc, getShadow(Op)));
  1846. setOrigin(&I, getOrigin(Op));
  1847. }
  1848. // \brief Instrument vector convert instrinsic.
  1849. //
  1850. // This function instruments intrinsics like cvtsi2ss:
  1851. // %Out = int_xxx_cvtyyy(%ConvertOp)
  1852. // or
  1853. // %Out = int_xxx_cvtyyy(%CopyOp, %ConvertOp)
  1854. // Intrinsic converts \p NumUsedElements elements of \p ConvertOp to the same
  1855. // number \p Out elements, and (if has 2 arguments) copies the rest of the
  1856. // elements from \p CopyOp.
  1857. // In most cases conversion involves floating-point value which may trigger a
  1858. // hardware exception when not fully initialized. For this reason we require
  1859. // \p ConvertOp[0:NumUsedElements] to be fully initialized and trap otherwise.
  1860. // We copy the shadow of \p CopyOp[NumUsedElements:] to \p
  1861. // Out[NumUsedElements:]. This means that intrinsics without \p CopyOp always
  1862. // return a fully initialized value.
  1863. void handleVectorConvertIntrinsic(IntrinsicInst &I, int NumUsedElements) {
  1864. IRBuilder<> IRB(&I);
  1865. Value *CopyOp, *ConvertOp;
  1866. switch (I.getNumArgOperands()) {
  1867. case 3:
  1868. assert(isa<ConstantInt>(I.getArgOperand(2)) && "Invalid rounding mode");
  1869. case 2:
  1870. CopyOp = I.getArgOperand(0);
  1871. ConvertOp = I.getArgOperand(1);
  1872. break;
  1873. case 1:
  1874. ConvertOp = I.getArgOperand(0);
  1875. CopyOp = nullptr;
  1876. break;
  1877. default:
  1878. llvm_unreachable("Cvt intrinsic with unsupported number of arguments.");
  1879. }
  1880. // The first *NumUsedElements* elements of ConvertOp are converted to the
  1881. // same number of output elements. The rest of the output is copied from
  1882. // CopyOp, or (if not available) filled with zeroes.
  1883. // Combine shadow for elements of ConvertOp that are used in this operation,
  1884. // and insert a check.
  1885. // FIXME: consider propagating shadow of ConvertOp, at least in the case of
  1886. // int->any conversion.
  1887. Value *ConvertShadow = getShadow(ConvertOp);
  1888. Value *AggShadow = nullptr;
  1889. if (ConvertOp->getType()->isVectorTy()) {
  1890. AggShadow = IRB.CreateExtractElement(
  1891. ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), 0));
  1892. for (int i = 1; i < NumUsedElements; ++i) {
  1893. Value *MoreShadow = IRB.CreateExtractElement(
  1894. ConvertShadow, ConstantInt::get(IRB.getInt32Ty(), i));
  1895. AggShadow = IRB.CreateOr(AggShadow, MoreShadow);
  1896. }
  1897. } else {
  1898. AggShadow = ConvertShadow;
  1899. }
  1900. assert(AggShadow->getType()->isIntegerTy());
  1901. insertShadowCheck(AggShadow, getOrigin(ConvertOp), &I);
  1902. // Build result shadow by zero-filling parts of CopyOp shadow that come from
  1903. // ConvertOp.
  1904. if (CopyOp) {
  1905. assert(CopyOp->getType() == I.getType());
  1906. assert(CopyOp->getType()->isVectorTy());
  1907. Value *ResultShadow = getShadow(CopyOp);
  1908. Type *EltTy = ResultShadow->getType()->getVectorElementType();
  1909. for (int i = 0; i < NumUsedElements; ++i) {
  1910. ResultShadow = IRB.CreateInsertElement(
  1911. ResultShadow, ConstantInt::getNullValue(EltTy),
  1912. ConstantInt::get(IRB.getInt32Ty(), i));
  1913. }
  1914. setShadow(&I, ResultShadow);
  1915. setOrigin(&I, getOrigin(CopyOp));
  1916. } else {
  1917. setShadow(&I, getCleanShadow(&I));
  1918. setOrigin(&I, getCleanOrigin());
  1919. }
  1920. }
  1921. // Given a scalar or vector, extract lower 64 bits (or less), and return all
  1922. // zeroes if it is zero, and all ones otherwise.
  1923. Value *Lower64ShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
  1924. if (S->getType()->isVectorTy())
  1925. S = CreateShadowCast(IRB, S, IRB.getInt64Ty(), /* Signed */ true);
  1926. assert(S->getType()->getPrimitiveSizeInBits() <= 64);
  1927. Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
  1928. return CreateShadowCast(IRB, S2, T, /* Signed */ true);
  1929. }
  1930. // Given a vector, extract its first element, and return all
  1931. // zeroes if it is zero, and all ones otherwise.
  1932. Value *LowerElementShadowExtend(IRBuilder<> &IRB, Value *S, Type *T) {
  1933. Value *S1 = IRB.CreateExtractElement(S, (uint64_t)0);
  1934. Value *S2 = IRB.CreateICmpNE(S1, getCleanShadow(S1));
  1935. return CreateShadowCast(IRB, S2, T, /* Signed */ true);
  1936. }
  1937. Value *VariableShadowExtend(IRBuilder<> &IRB, Value *S) {
  1938. Type *T = S->getType();
  1939. assert(T->isVectorTy());
  1940. Value *S2 = IRB.CreateICmpNE(S, getCleanShadow(S));
  1941. return IRB.CreateSExt(S2, T);
  1942. }
  1943. // \brief Instrument vector shift instrinsic.
  1944. //
  1945. // This function instruments intrinsics like int_x86_avx2_psll_w.
  1946. // Intrinsic shifts %In by %ShiftSize bits.
  1947. // %ShiftSize may be a vector. In that case the lower 64 bits determine shift
  1948. // size, and the rest is ignored. Behavior is defined even if shift size is
  1949. // greater than register (or field) width.
  1950. void handleVectorShiftIntrinsic(IntrinsicInst &I, bool Variable) {
  1951. assert(I.getNumArgOperands() == 2);
  1952. IRBuilder<> IRB(&I);
  1953. // If any of the S2 bits are poisoned, the whole thing is poisoned.
  1954. // Otherwise perform the same shift on S1.
  1955. Value *S1 = getShadow(&I, 0);
  1956. Value *S2 = getShadow(&I, 1);
  1957. Value *S2Conv = Variable ? VariableShadowExtend(IRB, S2)
  1958. : Lower64ShadowExtend(IRB, S2, getShadowTy(&I));
  1959. Value *V1 = I.getOperand(0);
  1960. Value *V2 = I.getOperand(1);
  1961. Value *Shift = IRB.CreateCall(I.getCalledValue(),
  1962. {IRB.CreateBitCast(S1, V1->getType()), V2});
  1963. Shift = IRB.CreateBitCast(Shift, getShadowTy(&I));
  1964. setShadow(&I, IRB.CreateOr(Shift, S2Conv));
  1965. setOriginForNaryOp(I);
  1966. }
  1967. // \brief Get an X86_MMX-sized vector type.
  1968. Type *getMMXVectorTy(unsigned EltSizeInBits) {
  1969. const unsigned X86_MMXSizeInBits = 64;
  1970. return VectorType::get(IntegerType::get(*MS.C, EltSizeInBits),
  1971. X86_MMXSizeInBits / EltSizeInBits);
  1972. }
  1973. // \brief Returns a signed counterpart for an (un)signed-saturate-and-pack
  1974. // intrinsic.
  1975. Intrinsic::ID getSignedPackIntrinsic(Intrinsic::ID id) {
  1976. switch (id) {
  1977. case llvm::Intrinsic::x86_sse2_packsswb_128:
  1978. case llvm::Intrinsic::x86_sse2_packuswb_128:
  1979. return llvm::Intrinsic::x86_sse2_packsswb_128;
  1980. case llvm::Intrinsic::x86_sse2_packssdw_128:
  1981. case llvm::Intrinsic::x86_sse41_packusdw:
  1982. return llvm::Intrinsic::x86_sse2_packssdw_128;
  1983. case llvm::Intrinsic::x86_avx2_packsswb:
  1984. case llvm::Intrinsic::x86_avx2_packuswb:
  1985. return llvm::Intrinsic::x86_avx2_packsswb;
  1986. case llvm::Intrinsic::x86_avx2_packssdw:
  1987. case llvm::Intrinsic::x86_avx2_packusdw:
  1988. return llvm::Intrinsic::x86_avx2_packssdw;
  1989. case llvm::Intrinsic::x86_mmx_packsswb:
  1990. case llvm::Intrinsic::x86_mmx_packuswb:
  1991. return llvm::Intrinsic::x86_mmx_packsswb;
  1992. case llvm::Intrinsic::x86_mmx_packssdw:
  1993. return llvm::Intrinsic::x86_mmx_packssdw;
  1994. default:
  1995. llvm_unreachable("unexpected intrinsic id");
  1996. }
  1997. }
  1998. // \brief Instrument vector pack instrinsic.
  1999. //
  2000. // This function instruments intrinsics like x86_mmx_packsswb, that
  2001. // packs elements of 2 input vectors into half as many bits with saturation.
  2002. // Shadow is propagated with the signed variant of the same intrinsic applied
  2003. // to sext(Sa != zeroinitializer), sext(Sb != zeroinitializer).
  2004. // EltSizeInBits is used only for x86mmx arguments.
  2005. void handleVectorPackIntrinsic(IntrinsicInst &I, unsigned EltSizeInBits = 0) {
  2006. assert(I.getNumArgOperands() == 2);
  2007. bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
  2008. IRBuilder<> IRB(&I);
  2009. Value *S1 = getShadow(&I, 0);
  2010. Value *S2 = getShadow(&I, 1);
  2011. assert(isX86_MMX || S1->getType()->isVectorTy());
  2012. // SExt and ICmpNE below must apply to individual elements of input vectors.
  2013. // In case of x86mmx arguments, cast them to appropriate vector types and
  2014. // back.
  2015. Type *T = isX86_MMX ? getMMXVectorTy(EltSizeInBits) : S1->getType();
  2016. if (isX86_MMX) {
  2017. S1 = IRB.CreateBitCast(S1, T);
  2018. S2 = IRB.CreateBitCast(S2, T);
  2019. }
  2020. Value *S1_ext = IRB.CreateSExt(
  2021. IRB.CreateICmpNE(S1, llvm::Constant::getNullValue(T)), T);
  2022. Value *S2_ext = IRB.CreateSExt(
  2023. IRB.CreateICmpNE(S2, llvm::Constant::getNullValue(T)), T);
  2024. if (isX86_MMX) {
  2025. Type *X86_MMXTy = Type::getX86_MMXTy(*MS.C);
  2026. S1_ext = IRB.CreateBitCast(S1_ext, X86_MMXTy);
  2027. S2_ext = IRB.CreateBitCast(S2_ext, X86_MMXTy);
  2028. }
  2029. Function *ShadowFn = Intrinsic::getDeclaration(
  2030. F.getParent(), getSignedPackIntrinsic(I.getIntrinsicID()));
  2031. Value *S =
  2032. IRB.CreateCall(ShadowFn, {S1_ext, S2_ext}, "_msprop_vector_pack");
  2033. if (isX86_MMX) S = IRB.CreateBitCast(S, getShadowTy(&I));
  2034. setShadow(&I, S);
  2035. setOriginForNaryOp(I);
  2036. }
  2037. // \brief Instrument sum-of-absolute-differencies intrinsic.
  2038. void handleVectorSadIntrinsic(IntrinsicInst &I) {
  2039. const unsigned SignificantBitsPerResultElement = 16;
  2040. bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
  2041. Type *ResTy = isX86_MMX ? IntegerType::get(*MS.C, 64) : I.getType();
  2042. unsigned ZeroBitsPerResultElement =
  2043. ResTy->getScalarSizeInBits() - SignificantBitsPerResultElement;
  2044. IRBuilder<> IRB(&I);
  2045. Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
  2046. S = IRB.CreateBitCast(S, ResTy);
  2047. S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
  2048. ResTy);
  2049. S = IRB.CreateLShr(S, ZeroBitsPerResultElement);
  2050. S = IRB.CreateBitCast(S, getShadowTy(&I));
  2051. setShadow(&I, S);
  2052. setOriginForNaryOp(I);
  2053. }
  2054. // \brief Instrument multiply-add intrinsic.
  2055. void handleVectorPmaddIntrinsic(IntrinsicInst &I,
  2056. unsigned EltSizeInBits = 0) {
  2057. bool isX86_MMX = I.getOperand(0)->getType()->isX86_MMXTy();
  2058. Type *ResTy = isX86_MMX ? getMMXVectorTy(EltSizeInBits * 2) : I.getType();
  2059. IRBuilder<> IRB(&I);
  2060. Value *S = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
  2061. S = IRB.CreateBitCast(S, ResTy);
  2062. S = IRB.CreateSExt(IRB.CreateICmpNE(S, Constant::getNullValue(ResTy)),
  2063. ResTy);
  2064. S = IRB.CreateBitCast(S, getShadowTy(&I));
  2065. setShadow(&I, S);
  2066. setOriginForNaryOp(I);
  2067. }
  2068. // \brief Instrument compare-packed intrinsic.
  2069. // Basically, an or followed by sext(icmp ne 0) to end up with all-zeros or
  2070. // all-ones shadow.
  2071. void handleVectorComparePackedIntrinsic(IntrinsicInst &I) {
  2072. IRBuilder<> IRB(&I);
  2073. Type *ResTy = getShadowTy(&I);
  2074. Value *S0 = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
  2075. Value *S = IRB.CreateSExt(
  2076. IRB.CreateICmpNE(S0, Constant::getNullValue(ResTy)), ResTy);
  2077. setShadow(&I, S);
  2078. setOriginForNaryOp(I);
  2079. }
  2080. // \brief Instrument compare-scalar intrinsic.
  2081. // This handles both cmp* intrinsics which return the result in the first
  2082. // element of a vector, and comi* which return the result as i32.
  2083. void handleVectorCompareScalarIntrinsic(IntrinsicInst &I) {
  2084. IRBuilder<> IRB(&I);
  2085. Value *S0 = IRB.CreateOr(getShadow(&I, 0), getShadow(&I, 1));
  2086. Value *S = LowerElementShadowExtend(IRB, S0, getShadowTy(&I));
  2087. setShadow(&I, S);
  2088. setOriginForNaryOp(I);
  2089. }
  2090. void handleStmxcsr(IntrinsicInst &I) {
  2091. IRBuilder<> IRB(&I);
  2092. Value* Addr = I.getArgOperand(0);
  2093. Type *Ty = IRB.getInt32Ty();
  2094. Value *ShadowPtr = getShadowPtr(Addr, Ty, IRB);
  2095. IRB.CreateStore(getCleanShadow(Ty),
  2096. IRB.CreatePointerCast(ShadowPtr, Ty->getPointerTo()));
  2097. if (ClCheckAccessAddress)
  2098. insertShadowCheck(Addr, &I);
  2099. }
  2100. void handleLdmxcsr(IntrinsicInst &I) {
  2101. if (!InsertChecks) return;
  2102. IRBuilder<> IRB(&I);
  2103. Value *Addr = I.getArgOperand(0);
  2104. Type *Ty = IRB.getInt32Ty();
  2105. unsigned Alignment = 1;
  2106. if (ClCheckAccessAddress)
  2107. insertShadowCheck(Addr, &I);
  2108. Value *Shadow = IRB.CreateAlignedLoad(getShadowPtr(Addr, Ty, IRB),
  2109. Alignment, "_ldmxcsr");
  2110. Value *Origin = MS.TrackOrigins
  2111. ? IRB.CreateLoad(getOriginPtr(Addr, IRB, Alignment))
  2112. : getCleanOrigin();
  2113. insertShadowCheck(Shadow, Origin, &I);
  2114. }
  2115. void visitIntrinsicInst(IntrinsicInst &I) {
  2116. switch (I.getIntrinsicID()) {
  2117. case llvm::Intrinsic::bswap:
  2118. handleBswap(I);
  2119. break;
  2120. case llvm::Intrinsic::x86_sse_stmxcsr:
  2121. handleStmxcsr(I);
  2122. break;
  2123. case llvm::Intrinsic::x86_sse_ldmxcsr:
  2124. handleLdmxcsr(I);
  2125. break;
  2126. case llvm::Intrinsic::x86_avx512_vcvtsd2usi64:
  2127. case llvm::Intrinsic::x86_avx512_vcvtsd2usi32:
  2128. case llvm::Intrinsic::x86_avx512_vcvtss2usi64:
  2129. case llvm::Intrinsic::x86_avx512_vcvtss2usi32:
  2130. case llvm::Intrinsic::x86_avx512_cvttss2usi64:
  2131. case llvm::Intrinsic::x86_avx512_cvttss2usi:
  2132. case llvm::Intrinsic::x86_avx512_cvttsd2usi64:
  2133. case llvm::Intrinsic::x86_avx512_cvttsd2usi:
  2134. case llvm::Intrinsic::x86_avx512_cvtusi2sd:
  2135. case llvm::Intrinsic::x86_avx512_cvtusi2ss:
  2136. case llvm::Intrinsic::x86_avx512_cvtusi642sd:
  2137. case llvm::Intrinsic::x86_avx512_cvtusi642ss:
  2138. case llvm::Intrinsic::x86_sse2_cvtsd2si64:
  2139. case llvm::Intrinsic::x86_sse2_cvtsd2si:
  2140. case llvm::Intrinsic::x86_sse2_cvtsd2ss:
  2141. case llvm::Intrinsic::x86_sse2_cvtsi2sd:
  2142. case llvm::Intrinsic::x86_sse2_cvtsi642sd:
  2143. case llvm::Intrinsic::x86_sse2_cvtss2sd:
  2144. case llvm::Intrinsic::x86_sse2_cvttsd2si64:
  2145. case llvm::Intrinsic::x86_sse2_cvttsd2si:
  2146. case llvm::Intrinsic::x86_sse_cvtsi2ss:
  2147. case llvm::Intrinsic::x86_sse_cvtsi642ss:
  2148. case llvm::Intrinsic::x86_sse_cvtss2si64:
  2149. case llvm::Intrinsic::x86_sse_cvtss2si:
  2150. case llvm::Intrinsic::x86_sse_cvttss2si64:
  2151. case llvm::Intrinsic::x86_sse_cvttss2si:
  2152. handleVectorConvertIntrinsic(I, 1);
  2153. break;
  2154. case llvm::Intrinsic::x86_sse_cvtps2pi:
  2155. case llvm::Intrinsic::x86_sse_cvttps2pi:
  2156. handleVectorConvertIntrinsic(I, 2);
  2157. break;
  2158. case llvm::Intrinsic::x86_avx512_psll_w_512:
  2159. case llvm::Intrinsic::x86_avx512_psll_d_512:
  2160. case llvm::Intrinsic::x86_avx512_psll_q_512:
  2161. case llvm::Intrinsic::x86_avx512_pslli_w_512:
  2162. case llvm::Intrinsic::x86_avx512_pslli_d_512:
  2163. case llvm::Intrinsic::x86_avx512_pslli_q_512:
  2164. case llvm::Intrinsic::x86_avx512_psrl_w_512:
  2165. case llvm::Intrinsic::x86_avx512_psrl_d_512:
  2166. case llvm::Intrinsic::x86_avx512_psrl_q_512:
  2167. case llvm::Intrinsic::x86_avx512_psra_w_512:
  2168. case llvm::Intrinsic::x86_avx512_psra_d_512:
  2169. case llvm::Intrinsic::x86_avx512_psra_q_512:
  2170. case llvm::Intrinsic::x86_avx512_psrli_w_512:
  2171. case llvm::Intrinsic::x86_avx512_psrli_d_512:
  2172. case llvm::Intrinsic::x86_avx512_psrli_q_512:
  2173. case llvm::Intrinsic::x86_avx512_psrai_w_512:
  2174. case llvm::Intrinsic::x86_avx512_psrai_d_512:
  2175. case llvm::Intrinsic::x86_avx512_psrai_q_512:
  2176. case llvm::Intrinsic::x86_avx512_psra_q_256:
  2177. case llvm::Intrinsic::x86_avx512_psra_q_128:
  2178. case llvm::Intrinsic::x86_avx512_psrai_q_256:
  2179. case llvm::Intrinsic::x86_avx512_psrai_q_128:
  2180. case llvm::Intrinsic::x86_avx2_psll_w:
  2181. case llvm::Intrinsic::x86_avx2_psll_d:
  2182. case llvm::Intrinsic::x86_avx2_psll_q:
  2183. case llvm::Intrinsic::x86_avx2_pslli_w:
  2184. case llvm::Intrinsic::x86_avx2_pslli_d:
  2185. case llvm::Intrinsic::x86_avx2_pslli_q:
  2186. case llvm::Intrinsic::x86_avx2_psrl_w:
  2187. case llvm::Intrinsic::x86_avx2_psrl_d:
  2188. case llvm::Intrinsic::x86_avx2_psrl_q:
  2189. case llvm::Intrinsic::x86_avx2_psra_w:
  2190. case llvm::Intrinsic::x86_avx2_psra_d:
  2191. case llvm::Intrinsic::x86_avx2_psrli_w:
  2192. case llvm::Intrinsic::x86_avx2_psrli_d:
  2193. case llvm::Intrinsic::x86_avx2_psrli_q:
  2194. case llvm::Intrinsic::x86_avx2_psrai_w:
  2195. case llvm::Intrinsic::x86_avx2_psrai_d:
  2196. case llvm::Intrinsic::x86_sse2_psll_w:
  2197. case llvm::Intrinsic::x86_sse2_psll_d:
  2198. case llvm::Intrinsic::x86_sse2_psll_q:
  2199. case llvm::Intrinsic::x86_sse2_pslli_w:
  2200. case llvm::Intrinsic::x86_sse2_pslli_d:
  2201. case llvm::Intrinsic::x86_sse2_pslli_q:
  2202. case llvm::Intrinsic::x86_sse2_psrl_w:
  2203. case llvm::Intrinsic::x86_sse2_psrl_d:
  2204. case llvm::Intrinsic::x86_sse2_psrl_q:
  2205. case llvm::Intrinsic::x86_sse2_psra_w:
  2206. case llvm::Intrinsic::x86_sse2_psra_d:
  2207. case llvm::Intrinsic::x86_sse2_psrli_w:
  2208. case llvm::Intrinsic::x86_sse2_psrli_d:
  2209. case llvm::Intrinsic::x86_sse2_psrli_q:
  2210. case llvm::Intrinsic::x86_sse2_psrai_w:
  2211. case llvm::Intrinsic::x86_sse2_psrai_d:
  2212. case llvm::Intrinsic::x86_mmx_psll_w:
  2213. case llvm::Intrinsic::x86_mmx_psll_d:
  2214. case llvm::Intrinsic::x86_mmx_psll_q:
  2215. case llvm::Intrinsic::x86_mmx_pslli_w:
  2216. case llvm::Intrinsic::x86_mmx_pslli_d:
  2217. case llvm::Intrinsic::x86_mmx_pslli_q:
  2218. case llvm::Intrinsic::x86_mmx_psrl_w:
  2219. case llvm::Intrinsic::x86_mmx_psrl_d:
  2220. case llvm::Intrinsic::x86_mmx_psrl_q:
  2221. case llvm::Intrinsic::x86_mmx_psra_w:
  2222. case llvm::Intrinsic::x86_mmx_psra_d:
  2223. case llvm::Intrinsic::x86_mmx_psrli_w:
  2224. case llvm::Intrinsic::x86_mmx_psrli_d:
  2225. case llvm::Intrinsic::x86_mmx_psrli_q:
  2226. case llvm::Intrinsic::x86_mmx_psrai_w:
  2227. case llvm::Intrinsic::x86_mmx_psrai_d:
  2228. handleVectorShiftIntrinsic(I, /* Variable */ false);
  2229. break;
  2230. case llvm::Intrinsic::x86_avx2_psllv_d:
  2231. case llvm::Intrinsic::x86_avx2_psllv_d_256:
  2232. case llvm::Intrinsic::x86_avx512_psllv_d_512:
  2233. case llvm::Intrinsic::x86_avx2_psllv_q:
  2234. case llvm::Intrinsic::x86_avx2_psllv_q_256:
  2235. case llvm::Intrinsic::x86_avx512_psllv_q_512:
  2236. case llvm::Intrinsic::x86_avx2_psrlv_d:
  2237. case llvm::Intrinsic::x86_avx2_psrlv_d_256:
  2238. case llvm::Intrinsic::x86_avx512_psrlv_d_512:
  2239. case llvm::Intrinsic::x86_avx2_psrlv_q:
  2240. case llvm::Intrinsic::x86_avx2_psrlv_q_256:
  2241. case llvm::Intrinsic::x86_avx512_psrlv_q_512:
  2242. case llvm::Intrinsic::x86_avx2_psrav_d:
  2243. case llvm::Intrinsic::x86_avx2_psrav_d_256:
  2244. case llvm::Intrinsic::x86_avx512_psrav_d_512:
  2245. case llvm::Intrinsic::x86_avx512_psrav_q_128:
  2246. case llvm::Intrinsic::x86_avx512_psrav_q_256:
  2247. case llvm::Intrinsic::x86_avx512_psrav_q_512:
  2248. handleVectorShiftIntrinsic(I, /* Variable */ true);
  2249. break;
  2250. case llvm::Intrinsic::x86_sse2_packsswb_128:
  2251. case llvm::Intrinsic::x86_sse2_packssdw_128:
  2252. case llvm::Intrinsic::x86_sse2_packuswb_128:
  2253. case llvm::Intrinsic::x86_sse41_packusdw:
  2254. case llvm::Intrinsic::x86_avx2_packsswb:
  2255. case llvm::Intrinsic::x86_avx2_packssdw:
  2256. case llvm::Intrinsic::x86_avx2_packuswb:
  2257. case llvm::Intrinsic::x86_avx2_packusdw:
  2258. handleVectorPackIntrinsic(I);
  2259. break;
  2260. case llvm::Intrinsic::x86_mmx_packsswb:
  2261. case llvm::Intrinsic::x86_mmx_packuswb:
  2262. handleVectorPackIntrinsic(I, 16);
  2263. break;
  2264. case llvm::Intrinsic::x86_mmx_packssdw:
  2265. handleVectorPackIntrinsic(I, 32);
  2266. break;
  2267. case llvm::Intrinsic::x86_mmx_psad_bw:
  2268. case llvm::Intrinsic::x86_sse2_psad_bw:
  2269. case llvm::Intrinsic::x86_avx2_psad_bw:
  2270. handleVectorSadIntrinsic(I);
  2271. break;
  2272. case llvm::Intrinsic::x86_sse2_pmadd_wd:
  2273. case llvm::Intrinsic::x86_avx2_pmadd_wd:
  2274. case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw_128:
  2275. case llvm::Intrinsic::x86_avx2_pmadd_ub_sw:
  2276. handleVectorPmaddIntrinsic(I);
  2277. break;
  2278. case llvm::Intrinsic::x86_ssse3_pmadd_ub_sw:
  2279. handleVectorPmaddIntrinsic(I, 8);
  2280. break;
  2281. case llvm::Intrinsic::x86_mmx_pmadd_wd:
  2282. handleVectorPmaddIntrinsic(I, 16);
  2283. break;
  2284. case llvm::Intrinsic::x86_sse_cmp_ss:
  2285. case llvm::Intrinsic::x86_sse2_cmp_sd:
  2286. case llvm::Intrinsic::x86_sse_comieq_ss:
  2287. case llvm::Intrinsic::x86_sse_comilt_ss:
  2288. case llvm::Intrinsic::x86_sse_comile_ss:
  2289. case llvm::Intrinsic::x86_sse_comigt_ss:
  2290. case llvm::Intrinsic::x86_sse_comige_ss:
  2291. case llvm::Intrinsic::x86_sse_comineq_ss:
  2292. case llvm::Intrinsic::x86_sse_ucomieq_ss:
  2293. case llvm::Intrinsic::x86_sse_ucomilt_ss:
  2294. case llvm::Intrinsic::x86_sse_ucomile_ss:
  2295. case llvm::Intrinsic::x86_sse_ucomigt_ss:
  2296. case llvm::Intrinsic::x86_sse_ucomige_ss:
  2297. case llvm::Intrinsic::x86_sse_ucomineq_ss:
  2298. case llvm::Intrinsic::x86_sse2_comieq_sd:
  2299. case llvm::Intrinsic::x86_sse2_comilt_sd:
  2300. case llvm::Intrinsic::x86_sse2_comile_sd:
  2301. case llvm::Intrinsic::x86_sse2_comigt_sd:
  2302. case llvm::Intrinsic::x86_sse2_comige_sd:
  2303. case llvm::Intrinsic::x86_sse2_comineq_sd:
  2304. case llvm::Intrinsic::x86_sse2_ucomieq_sd:
  2305. case llvm::Intrinsic::x86_sse2_ucomilt_sd:
  2306. case llvm::Intrinsic::x86_sse2_ucomile_sd:
  2307. case llvm::Intrinsic::x86_sse2_ucomigt_sd:
  2308. case llvm::Intrinsic::x86_sse2_ucomige_sd:
  2309. case llvm::Intrinsic::x86_sse2_ucomineq_sd:
  2310. handleVectorCompareScalarIntrinsic(I);
  2311. break;
  2312. case llvm::Intrinsic::x86_sse_cmp_ps:
  2313. case llvm::Intrinsic::x86_sse2_cmp_pd:
  2314. // FIXME: For x86_avx_cmp_pd_256 and x86_avx_cmp_ps_256 this function
  2315. // generates reasonably looking IR that fails in the backend with "Do not
  2316. // know how to split the result of this operator!".
  2317. handleVectorComparePackedIntrinsic(I);
  2318. break;
  2319. default:
  2320. if (!handleUnknownIntrinsic(I))
  2321. visitInstruction(I);
  2322. break;
  2323. }
  2324. }
  2325. void visitCallSite(CallSite CS) {
  2326. Instruction &I = *CS.getInstruction();
  2327. assert((CS.isCall() || CS.isInvoke()) && "Unknown type of CallSite");
  2328. if (CS.isCall()) {
  2329. CallInst *Call = cast<CallInst>(&I);
  2330. // For inline asm, do the usual thing: check argument shadow and mark all
  2331. // outputs as clean. Note that any side effects of the inline asm that are
  2332. // not immediately visible in its constraints are not handled.
  2333. if (Call->isInlineAsm()) {
  2334. visitInstruction(I);
  2335. return;
  2336. }
  2337. assert(!isa<IntrinsicInst>(&I) && "intrinsics are handled elsewhere");
  2338. // We are going to insert code that relies on the fact that the callee
  2339. // will become a non-readonly function after it is instrumented by us. To
  2340. // prevent this code from being optimized out, mark that function
  2341. // non-readonly in advance.
  2342. if (Function *Func = Call->getCalledFunction()) {
  2343. // Clear out readonly/readnone attributes.
  2344. AttrBuilder B;
  2345. B.addAttribute(Attribute::ReadOnly)
  2346. .addAttribute(Attribute::ReadNone);
  2347. Func->removeAttributes(AttributeList::FunctionIndex,
  2348. AttributeList::get(Func->getContext(),
  2349. AttributeList::FunctionIndex,
  2350. B));
  2351. }
  2352. maybeMarkSanitizerLibraryCallNoBuiltin(Call, TLI);
  2353. }
  2354. IRBuilder<> IRB(&I);
  2355. unsigned ArgOffset = 0;
  2356. DEBUG(dbgs() << " CallSite: " << I << "\n");
  2357. for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
  2358. ArgIt != End; ++ArgIt) {
  2359. Value *A = *ArgIt;
  2360. unsigned i = ArgIt - CS.arg_begin();
  2361. if (!A->getType()->isSized()) {
  2362. DEBUG(dbgs() << "Arg " << i << " is not sized: " << I << "\n");
  2363. continue;
  2364. }
  2365. unsigned Size = 0;
  2366. Value *Store = nullptr;
  2367. // Compute the Shadow for arg even if it is ByVal, because
  2368. // in that case getShadow() will copy the actual arg shadow to
  2369. // __msan_param_tls.
  2370. Value *ArgShadow = getShadow(A);
  2371. Value *ArgShadowBase = getShadowPtrForArgument(A, IRB, ArgOffset);
  2372. DEBUG(dbgs() << " Arg#" << i << ": " << *A <<
  2373. " Shadow: " << *ArgShadow << "\n");
  2374. bool ArgIsInitialized = false;
  2375. const DataLayout &DL = F.getParent()->getDataLayout();
  2376. if (CS.paramHasAttr(i + 1, Attribute::ByVal)) {
  2377. assert(A->getType()->isPointerTy() &&
  2378. "ByVal argument is not a pointer!");
  2379. Size = DL.getTypeAllocSize(A->getType()->getPointerElementType());
  2380. if (ArgOffset + Size > kParamTLSSize) break;
  2381. unsigned ParamAlignment = CS.getParamAlignment(i + 1);
  2382. unsigned Alignment = std::min(ParamAlignment, kShadowTLSAlignment);
  2383. Store = IRB.CreateMemCpy(ArgShadowBase,
  2384. getShadowPtr(A, Type::getInt8Ty(*MS.C), IRB),
  2385. Size, Alignment);
  2386. } else {
  2387. Size = DL.getTypeAllocSize(A->getType());
  2388. if (ArgOffset + Size > kParamTLSSize) break;
  2389. Store = IRB.CreateAlignedStore(ArgShadow, ArgShadowBase,
  2390. kShadowTLSAlignment);
  2391. Constant *Cst = dyn_cast<Constant>(ArgShadow);
  2392. if (Cst && Cst->isNullValue()) ArgIsInitialized = true;
  2393. }
  2394. if (MS.TrackOrigins && !ArgIsInitialized)
  2395. IRB.CreateStore(getOrigin(A),
  2396. getOriginPtrForArgument(A, IRB, ArgOffset));
  2397. (void)Store;
  2398. assert(Size != 0 && Store != nullptr);
  2399. DEBUG(dbgs() << " Param:" << *Store << "\n");
  2400. ArgOffset += alignTo(Size, 8);
  2401. }
  2402. DEBUG(dbgs() << " done with call args\n");
  2403. FunctionType *FT =
  2404. cast<FunctionType>(CS.getCalledValue()->getType()->getContainedType(0));
  2405. if (FT->isVarArg()) {
  2406. VAHelper->visitCallSite(CS, IRB);
  2407. }
  2408. // Now, get the shadow for the RetVal.
  2409. if (!I.getType()->isSized()) return;
  2410. // Don't emit the epilogue for musttail call returns.
  2411. if (CS.isCall() && cast<CallInst>(&I)->isMustTailCall()) return;
  2412. IRBuilder<> IRBBefore(&I);
  2413. // Until we have full dynamic coverage, make sure the retval shadow is 0.
  2414. Value *Base = getShadowPtrForRetval(&I, IRBBefore);
  2415. IRBBefore.CreateAlignedStore(getCleanShadow(&I), Base, kShadowTLSAlignment);
  2416. BasicBlock::iterator NextInsn;
  2417. if (CS.isCall()) {
  2418. NextInsn = ++I.getIterator();
  2419. assert(NextInsn != I.getParent()->end());
  2420. } else {
  2421. BasicBlock *NormalDest = cast<InvokeInst>(&I)->getNormalDest();
  2422. if (!NormalDest->getSinglePredecessor()) {
  2423. // FIXME: this case is tricky, so we are just conservative here.
  2424. // Perhaps we need to split the edge between this BB and NormalDest,
  2425. // but a naive attempt to use SplitEdge leads to a crash.
  2426. setShadow(&I, getCleanShadow(&I));
  2427. setOrigin(&I, getCleanOrigin());
  2428. return;
  2429. }
  2430. NextInsn = NormalDest->getFirstInsertionPt();
  2431. assert(NextInsn != NormalDest->end() &&
  2432. "Could not find insertion point for retval shadow load");
  2433. }
  2434. IRBuilder<> IRBAfter(&*NextInsn);
  2435. Value *RetvalShadow =
  2436. IRBAfter.CreateAlignedLoad(getShadowPtrForRetval(&I, IRBAfter),
  2437. kShadowTLSAlignment, "_msret");
  2438. setShadow(&I, RetvalShadow);
  2439. if (MS.TrackOrigins)
  2440. setOrigin(&I, IRBAfter.CreateLoad(getOriginPtrForRetval(IRBAfter)));
  2441. }
  2442. bool isAMustTailRetVal(Value *RetVal) {
  2443. if (auto *I = dyn_cast<BitCastInst>(RetVal)) {
  2444. RetVal = I->getOperand(0);
  2445. }
  2446. if (auto *I = dyn_cast<CallInst>(RetVal)) {
  2447. return I->isMustTailCall();
  2448. }
  2449. return false;
  2450. }
  2451. void visitReturnInst(ReturnInst &I) {
  2452. IRBuilder<> IRB(&I);
  2453. Value *RetVal = I.getReturnValue();
  2454. if (!RetVal) return;
  2455. // Don't emit the epilogue for musttail call returns.
  2456. if (isAMustTailRetVal(RetVal)) return;
  2457. Value *ShadowPtr = getShadowPtrForRetval(RetVal, IRB);
  2458. if (CheckReturnValue) {
  2459. insertShadowCheck(RetVal, &I);
  2460. Value *Shadow = getCleanShadow(RetVal);
  2461. IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
  2462. } else {
  2463. Value *Shadow = getShadow(RetVal);
  2464. IRB.CreateAlignedStore(Shadow, ShadowPtr, kShadowTLSAlignment);
  2465. if (MS.TrackOrigins)
  2466. IRB.CreateStore(getOrigin(RetVal), getOriginPtrForRetval(IRB));
  2467. }
  2468. }
  2469. void visitPHINode(PHINode &I) {
  2470. IRBuilder<> IRB(&I);
  2471. if (!PropagateShadow) {
  2472. setShadow(&I, getCleanShadow(&I));
  2473. setOrigin(&I, getCleanOrigin());
  2474. return;
  2475. }
  2476. ShadowPHINodes.push_back(&I);
  2477. setShadow(&I, IRB.CreatePHI(getShadowTy(&I), I.getNumIncomingValues(),
  2478. "_msphi_s"));
  2479. if (MS.TrackOrigins)
  2480. setOrigin(&I, IRB.CreatePHI(MS.OriginTy, I.getNumIncomingValues(),
  2481. "_msphi_o"));
  2482. }
  2483. void visitAllocaInst(AllocaInst &I) {
  2484. setShadow(&I, getCleanShadow(&I));
  2485. setOrigin(&I, getCleanOrigin());
  2486. IRBuilder<> IRB(I.getNextNode());
  2487. const DataLayout &DL = F.getParent()->getDataLayout();
  2488. uint64_t TypeSize = DL.getTypeAllocSize(I.getAllocatedType());
  2489. Value *Len = ConstantInt::get(MS.IntptrTy, TypeSize);
  2490. if (I.isArrayAllocation())
  2491. Len = IRB.CreateMul(Len, I.getArraySize());
  2492. if (PoisonStack && ClPoisonStackWithCall) {
  2493. IRB.CreateCall(MS.MsanPoisonStackFn,
  2494. {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len});
  2495. } else {
  2496. Value *ShadowBase = getShadowPtr(&I, Type::getInt8PtrTy(*MS.C), IRB);
  2497. Value *PoisonValue = IRB.getInt8(PoisonStack ? ClPoisonStackPattern : 0);
  2498. IRB.CreateMemSet(ShadowBase, PoisonValue, Len, I.getAlignment());
  2499. }
  2500. if (PoisonStack && MS.TrackOrigins) {
  2501. SmallString<2048> StackDescriptionStorage;
  2502. raw_svector_ostream StackDescription(StackDescriptionStorage);
  2503. // We create a string with a description of the stack allocation and
  2504. // pass it into __msan_set_alloca_origin.
  2505. // It will be printed by the run-time if stack-originated UMR is found.
  2506. // The first 4 bytes of the string are set to '----' and will be replaced
  2507. // by __msan_va_arg_overflow_size_tls at the first call.
  2508. StackDescription << "----" << I.getName() << "@" << F.getName();
  2509. Value *Descr =
  2510. createPrivateNonConstGlobalForString(*F.getParent(),
  2511. StackDescription.str());
  2512. IRB.CreateCall(MS.MsanSetAllocaOrigin4Fn,
  2513. {IRB.CreatePointerCast(&I, IRB.getInt8PtrTy()), Len,
  2514. IRB.CreatePointerCast(Descr, IRB.getInt8PtrTy()),
  2515. IRB.CreatePointerCast(&F, MS.IntptrTy)});
  2516. }
  2517. }
  2518. void visitSelectInst(SelectInst& I) {
  2519. IRBuilder<> IRB(&I);
  2520. // a = select b, c, d
  2521. Value *B = I.getCondition();
  2522. Value *C = I.getTrueValue();
  2523. Value *D = I.getFalseValue();
  2524. Value *Sb = getShadow(B);
  2525. Value *Sc = getShadow(C);
  2526. Value *Sd = getShadow(D);
  2527. // Result shadow if condition shadow is 0.
  2528. Value *Sa0 = IRB.CreateSelect(B, Sc, Sd);
  2529. Value *Sa1;
  2530. if (I.getType()->isAggregateType()) {
  2531. // To avoid "sign extending" i1 to an arbitrary aggregate type, we just do
  2532. // an extra "select". This results in much more compact IR.
  2533. // Sa = select Sb, poisoned, (select b, Sc, Sd)
  2534. Sa1 = getPoisonedShadow(getShadowTy(I.getType()));
  2535. } else {
  2536. // Sa = select Sb, [ (c^d) | Sc | Sd ], [ b ? Sc : Sd ]
  2537. // If Sb (condition is poisoned), look for bits in c and d that are equal
  2538. // and both unpoisoned.
  2539. // If !Sb (condition is unpoisoned), simply pick one of Sc and Sd.
  2540. // Cast arguments to shadow-compatible type.
  2541. C = CreateAppToShadowCast(IRB, C);
  2542. D = CreateAppToShadowCast(IRB, D);
  2543. // Result shadow if condition shadow is 1.
  2544. Sa1 = IRB.CreateOr(IRB.CreateXor(C, D), IRB.CreateOr(Sc, Sd));
  2545. }
  2546. Value *Sa = IRB.CreateSelect(Sb, Sa1, Sa0, "_msprop_select");
  2547. setShadow(&I, Sa);
  2548. if (MS.TrackOrigins) {
  2549. // Origins are always i32, so any vector conditions must be flattened.
  2550. // FIXME: consider tracking vector origins for app vectors?
  2551. if (B->getType()->isVectorTy()) {
  2552. Type *FlatTy = getShadowTyNoVec(B->getType());
  2553. B = IRB.CreateICmpNE(IRB.CreateBitCast(B, FlatTy),
  2554. ConstantInt::getNullValue(FlatTy));
  2555. Sb = IRB.CreateICmpNE(IRB.CreateBitCast(Sb, FlatTy),
  2556. ConstantInt::getNullValue(FlatTy));
  2557. }
  2558. // a = select b, c, d
  2559. // Oa = Sb ? Ob : (b ? Oc : Od)
  2560. setOrigin(
  2561. &I, IRB.CreateSelect(Sb, getOrigin(I.getCondition()),
  2562. IRB.CreateSelect(B, getOrigin(I.getTrueValue()),
  2563. getOrigin(I.getFalseValue()))));
  2564. }
  2565. }
  2566. void visitLandingPadInst(LandingPadInst &I) {
  2567. // Do nothing.
  2568. // See http://code.google.com/p/memory-sanitizer/issues/detail?id=1
  2569. setShadow(&I, getCleanShadow(&I));
  2570. setOrigin(&I, getCleanOrigin());
  2571. }
  2572. void visitCatchSwitchInst(CatchSwitchInst &I) {
  2573. setShadow(&I, getCleanShadow(&I));
  2574. setOrigin(&I, getCleanOrigin());
  2575. }
  2576. void visitFuncletPadInst(FuncletPadInst &I) {
  2577. setShadow(&I, getCleanShadow(&I));
  2578. setOrigin(&I, getCleanOrigin());
  2579. }
  2580. void visitGetElementPtrInst(GetElementPtrInst &I) {
  2581. handleShadowOr(I);
  2582. }
  2583. void visitExtractValueInst(ExtractValueInst &I) {
  2584. IRBuilder<> IRB(&I);
  2585. Value *Agg = I.getAggregateOperand();
  2586. DEBUG(dbgs() << "ExtractValue: " << I << "\n");
  2587. Value *AggShadow = getShadow(Agg);
  2588. DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
  2589. Value *ResShadow = IRB.CreateExtractValue(AggShadow, I.getIndices());
  2590. DEBUG(dbgs() << " ResShadow: " << *ResShadow << "\n");
  2591. setShadow(&I, ResShadow);
  2592. setOriginForNaryOp(I);
  2593. }
  2594. void visitInsertValueInst(InsertValueInst &I) {
  2595. IRBuilder<> IRB(&I);
  2596. DEBUG(dbgs() << "InsertValue: " << I << "\n");
  2597. Value *AggShadow = getShadow(I.getAggregateOperand());
  2598. Value *InsShadow = getShadow(I.getInsertedValueOperand());
  2599. DEBUG(dbgs() << " AggShadow: " << *AggShadow << "\n");
  2600. DEBUG(dbgs() << " InsShadow: " << *InsShadow << "\n");
  2601. Value *Res = IRB.CreateInsertValue(AggShadow, InsShadow, I.getIndices());
  2602. DEBUG(dbgs() << " Res: " << *Res << "\n");
  2603. setShadow(&I, Res);
  2604. setOriginForNaryOp(I);
  2605. }
  2606. void dumpInst(Instruction &I) {
  2607. if (CallInst *CI = dyn_cast<CallInst>(&I)) {
  2608. errs() << "ZZZ call " << CI->getCalledFunction()->getName() << "\n";
  2609. } else {
  2610. errs() << "ZZZ " << I.getOpcodeName() << "\n";
  2611. }
  2612. errs() << "QQQ " << I << "\n";
  2613. }
  2614. void visitResumeInst(ResumeInst &I) {
  2615. DEBUG(dbgs() << "Resume: " << I << "\n");
  2616. // Nothing to do here.
  2617. }
  2618. void visitCleanupReturnInst(CleanupReturnInst &CRI) {
  2619. DEBUG(dbgs() << "CleanupReturn: " << CRI << "\n");
  2620. // Nothing to do here.
  2621. }
  2622. void visitCatchReturnInst(CatchReturnInst &CRI) {
  2623. DEBUG(dbgs() << "CatchReturn: " << CRI << "\n");
  2624. // Nothing to do here.
  2625. }
  2626. void visitInstruction(Instruction &I) {
  2627. // Everything else: stop propagating and check for poisoned shadow.
  2628. if (ClDumpStrictInstructions)
  2629. dumpInst(I);
  2630. DEBUG(dbgs() << "DEFAULT: " << I << "\n");
  2631. for (size_t i = 0, n = I.getNumOperands(); i < n; i++)
  2632. insertShadowCheck(I.getOperand(i), &I);
  2633. setShadow(&I, getCleanShadow(&I));
  2634. setOrigin(&I, getCleanOrigin());
  2635. }
  2636. };
  2637. /// \brief AMD64-specific implementation of VarArgHelper.
  2638. struct VarArgAMD64Helper : public VarArgHelper {
  2639. // An unfortunate workaround for asymmetric lowering of va_arg stuff.
  2640. // See a comment in visitCallSite for more details.
  2641. static const unsigned AMD64GpEndOffset = 48; // AMD64 ABI Draft 0.99.6 p3.5.7
  2642. static const unsigned AMD64FpEndOffset = 176;
  2643. Function &F;
  2644. MemorySanitizer &MS;
  2645. MemorySanitizerVisitor &MSV;
  2646. Value *VAArgTLSCopy;
  2647. Value *VAArgOverflowSize;
  2648. SmallVector<CallInst*, 16> VAStartInstrumentationList;
  2649. VarArgAMD64Helper(Function &F, MemorySanitizer &MS,
  2650. MemorySanitizerVisitor &MSV)
  2651. : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
  2652. VAArgOverflowSize(nullptr) {}
  2653. enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
  2654. ArgKind classifyArgument(Value* arg) {
  2655. // A very rough approximation of X86_64 argument classification rules.
  2656. Type *T = arg->getType();
  2657. if (T->isFPOrFPVectorTy() || T->isX86_MMXTy())
  2658. return AK_FloatingPoint;
  2659. if (T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
  2660. return AK_GeneralPurpose;
  2661. if (T->isPointerTy())
  2662. return AK_GeneralPurpose;
  2663. return AK_Memory;
  2664. }
  2665. // For VarArg functions, store the argument shadow in an ABI-specific format
  2666. // that corresponds to va_list layout.
  2667. // We do this because Clang lowers va_arg in the frontend, and this pass
  2668. // only sees the low level code that deals with va_list internals.
  2669. // A much easier alternative (provided that Clang emits va_arg instructions)
  2670. // would have been to associate each live instance of va_list with a copy of
  2671. // MSanParamTLS, and extract shadow on va_arg() call in the argument list
  2672. // order.
  2673. void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
  2674. unsigned GpOffset = 0;
  2675. unsigned FpOffset = AMD64GpEndOffset;
  2676. unsigned OverflowOffset = AMD64FpEndOffset;
  2677. const DataLayout &DL = F.getParent()->getDataLayout();
  2678. for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
  2679. ArgIt != End; ++ArgIt) {
  2680. Value *A = *ArgIt;
  2681. unsigned ArgNo = CS.getArgumentNo(ArgIt);
  2682. bool IsFixed = ArgNo < CS.getFunctionType()->getNumParams();
  2683. bool IsByVal = CS.paramHasAttr(ArgNo + 1, Attribute::ByVal);
  2684. if (IsByVal) {
  2685. // ByVal arguments always go to the overflow area.
  2686. // Fixed arguments passed through the overflow area will be stepped
  2687. // over by va_start, so don't count them towards the offset.
  2688. if (IsFixed)
  2689. continue;
  2690. assert(A->getType()->isPointerTy());
  2691. Type *RealTy = A->getType()->getPointerElementType();
  2692. uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
  2693. Value *Base = getShadowPtrForVAArgument(RealTy, IRB, OverflowOffset);
  2694. OverflowOffset += alignTo(ArgSize, 8);
  2695. IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
  2696. ArgSize, kShadowTLSAlignment);
  2697. } else {
  2698. ArgKind AK = classifyArgument(A);
  2699. if (AK == AK_GeneralPurpose && GpOffset >= AMD64GpEndOffset)
  2700. AK = AK_Memory;
  2701. if (AK == AK_FloatingPoint && FpOffset >= AMD64FpEndOffset)
  2702. AK = AK_Memory;
  2703. Value *Base;
  2704. switch (AK) {
  2705. case AK_GeneralPurpose:
  2706. Base = getShadowPtrForVAArgument(A->getType(), IRB, GpOffset);
  2707. GpOffset += 8;
  2708. break;
  2709. case AK_FloatingPoint:
  2710. Base = getShadowPtrForVAArgument(A->getType(), IRB, FpOffset);
  2711. FpOffset += 16;
  2712. break;
  2713. case AK_Memory:
  2714. if (IsFixed)
  2715. continue;
  2716. uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
  2717. Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
  2718. OverflowOffset += alignTo(ArgSize, 8);
  2719. }
  2720. // Take fixed arguments into account for GpOffset and FpOffset,
  2721. // but don't actually store shadows for them.
  2722. if (IsFixed)
  2723. continue;
  2724. IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
  2725. }
  2726. }
  2727. Constant *OverflowSize =
  2728. ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AMD64FpEndOffset);
  2729. IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
  2730. }
  2731. /// \brief Compute the shadow address for a given va_arg.
  2732. Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
  2733. int ArgOffset) {
  2734. Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
  2735. Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
  2736. return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
  2737. "_msarg");
  2738. }
  2739. void visitVAStartInst(VAStartInst &I) override {
  2740. if (F.getCallingConv() == CallingConv::X86_64_Win64)
  2741. return;
  2742. IRBuilder<> IRB(&I);
  2743. VAStartInstrumentationList.push_back(&I);
  2744. Value *VAListTag = I.getArgOperand(0);
  2745. Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
  2746. // Unpoison the whole __va_list_tag.
  2747. // FIXME: magic ABI constants.
  2748. IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
  2749. /* size */24, /* alignment */8, false);
  2750. }
  2751. void visitVACopyInst(VACopyInst &I) override {
  2752. if (F.getCallingConv() == CallingConv::X86_64_Win64)
  2753. return;
  2754. IRBuilder<> IRB(&I);
  2755. Value *VAListTag = I.getArgOperand(0);
  2756. Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
  2757. // Unpoison the whole __va_list_tag.
  2758. // FIXME: magic ABI constants.
  2759. IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
  2760. /* size */24, /* alignment */8, false);
  2761. }
  2762. void finalizeInstrumentation() override {
  2763. assert(!VAArgOverflowSize && !VAArgTLSCopy &&
  2764. "finalizeInstrumentation called twice");
  2765. if (!VAStartInstrumentationList.empty()) {
  2766. // If there is a va_start in this function, make a backup copy of
  2767. // va_arg_tls somewhere in the function entry block.
  2768. IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
  2769. VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
  2770. Value *CopySize =
  2771. IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AMD64FpEndOffset),
  2772. VAArgOverflowSize);
  2773. VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
  2774. IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
  2775. }
  2776. // Instrument va_start.
  2777. // Copy va_list shadow from the backup copy of the TLS contents.
  2778. for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
  2779. CallInst *OrigInst = VAStartInstrumentationList[i];
  2780. IRBuilder<> IRB(OrigInst->getNextNode());
  2781. Value *VAListTag = OrigInst->getArgOperand(0);
  2782. Value *RegSaveAreaPtrPtr =
  2783. IRB.CreateIntToPtr(
  2784. IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
  2785. ConstantInt::get(MS.IntptrTy, 16)),
  2786. Type::getInt64PtrTy(*MS.C));
  2787. Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
  2788. Value *RegSaveAreaShadowPtr =
  2789. MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
  2790. IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy,
  2791. AMD64FpEndOffset, 16);
  2792. Value *OverflowArgAreaPtrPtr =
  2793. IRB.CreateIntToPtr(
  2794. IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
  2795. ConstantInt::get(MS.IntptrTy, 8)),
  2796. Type::getInt64PtrTy(*MS.C));
  2797. Value *OverflowArgAreaPtr = IRB.CreateLoad(OverflowArgAreaPtrPtr);
  2798. Value *OverflowArgAreaShadowPtr =
  2799. MSV.getShadowPtr(OverflowArgAreaPtr, IRB.getInt8Ty(), IRB);
  2800. Value *SrcPtr = IRB.CreateConstGEP1_32(IRB.getInt8Ty(), VAArgTLSCopy,
  2801. AMD64FpEndOffset);
  2802. IRB.CreateMemCpy(OverflowArgAreaShadowPtr, SrcPtr, VAArgOverflowSize, 16);
  2803. }
  2804. }
  2805. };
  2806. /// \brief MIPS64-specific implementation of VarArgHelper.
  2807. struct VarArgMIPS64Helper : public VarArgHelper {
  2808. Function &F;
  2809. MemorySanitizer &MS;
  2810. MemorySanitizerVisitor &MSV;
  2811. Value *VAArgTLSCopy;
  2812. Value *VAArgSize;
  2813. SmallVector<CallInst*, 16> VAStartInstrumentationList;
  2814. VarArgMIPS64Helper(Function &F, MemorySanitizer &MS,
  2815. MemorySanitizerVisitor &MSV)
  2816. : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
  2817. VAArgSize(nullptr) {}
  2818. void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
  2819. unsigned VAArgOffset = 0;
  2820. const DataLayout &DL = F.getParent()->getDataLayout();
  2821. for (CallSite::arg_iterator ArgIt = CS.arg_begin() +
  2822. CS.getFunctionType()->getNumParams(), End = CS.arg_end();
  2823. ArgIt != End; ++ArgIt) {
  2824. llvm::Triple TargetTriple(F.getParent()->getTargetTriple());
  2825. Value *A = *ArgIt;
  2826. Value *Base;
  2827. uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
  2828. if (TargetTriple.getArch() == llvm::Triple::mips64) {
  2829. // Adjusting the shadow for argument with size < 8 to match the placement
  2830. // of bits in big endian system
  2831. if (ArgSize < 8)
  2832. VAArgOffset += (8 - ArgSize);
  2833. }
  2834. Base = getShadowPtrForVAArgument(A->getType(), IRB, VAArgOffset);
  2835. VAArgOffset += ArgSize;
  2836. VAArgOffset = alignTo(VAArgOffset, 8);
  2837. IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
  2838. }
  2839. Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(), VAArgOffset);
  2840. // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
  2841. // a new class member i.e. it is the total size of all VarArgs.
  2842. IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
  2843. }
  2844. /// \brief Compute the shadow address for a given va_arg.
  2845. Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
  2846. int ArgOffset) {
  2847. Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
  2848. Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
  2849. return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
  2850. "_msarg");
  2851. }
  2852. void visitVAStartInst(VAStartInst &I) override {
  2853. IRBuilder<> IRB(&I);
  2854. VAStartInstrumentationList.push_back(&I);
  2855. Value *VAListTag = I.getArgOperand(0);
  2856. Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
  2857. IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
  2858. /* size */8, /* alignment */8, false);
  2859. }
  2860. void visitVACopyInst(VACopyInst &I) override {
  2861. IRBuilder<> IRB(&I);
  2862. Value *VAListTag = I.getArgOperand(0);
  2863. Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
  2864. // Unpoison the whole __va_list_tag.
  2865. // FIXME: magic ABI constants.
  2866. IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
  2867. /* size */8, /* alignment */8, false);
  2868. }
  2869. void finalizeInstrumentation() override {
  2870. assert(!VAArgSize && !VAArgTLSCopy &&
  2871. "finalizeInstrumentation called twice");
  2872. IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
  2873. VAArgSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
  2874. Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
  2875. VAArgSize);
  2876. if (!VAStartInstrumentationList.empty()) {
  2877. // If there is a va_start in this function, make a backup copy of
  2878. // va_arg_tls somewhere in the function entry block.
  2879. VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
  2880. IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
  2881. }
  2882. // Instrument va_start.
  2883. // Copy va_list shadow from the backup copy of the TLS contents.
  2884. for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
  2885. CallInst *OrigInst = VAStartInstrumentationList[i];
  2886. IRBuilder<> IRB(OrigInst->getNextNode());
  2887. Value *VAListTag = OrigInst->getArgOperand(0);
  2888. Value *RegSaveAreaPtrPtr =
  2889. IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
  2890. Type::getInt64PtrTy(*MS.C));
  2891. Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
  2892. Value *RegSaveAreaShadowPtr =
  2893. MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
  2894. IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy, CopySize, 8);
  2895. }
  2896. }
  2897. };
  2898. /// \brief AArch64-specific implementation of VarArgHelper.
  2899. struct VarArgAArch64Helper : public VarArgHelper {
  2900. static const unsigned kAArch64GrArgSize = 64;
  2901. static const unsigned kAArch64VrArgSize = 128;
  2902. static const unsigned AArch64GrBegOffset = 0;
  2903. static const unsigned AArch64GrEndOffset = kAArch64GrArgSize;
  2904. // Make VR space aligned to 16 bytes.
  2905. static const unsigned AArch64VrBegOffset = AArch64GrEndOffset;
  2906. static const unsigned AArch64VrEndOffset = AArch64VrBegOffset
  2907. + kAArch64VrArgSize;
  2908. static const unsigned AArch64VAEndOffset = AArch64VrEndOffset;
  2909. Function &F;
  2910. MemorySanitizer &MS;
  2911. MemorySanitizerVisitor &MSV;
  2912. Value *VAArgTLSCopy;
  2913. Value *VAArgOverflowSize;
  2914. SmallVector<CallInst*, 16> VAStartInstrumentationList;
  2915. VarArgAArch64Helper(Function &F, MemorySanitizer &MS,
  2916. MemorySanitizerVisitor &MSV)
  2917. : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
  2918. VAArgOverflowSize(nullptr) {}
  2919. enum ArgKind { AK_GeneralPurpose, AK_FloatingPoint, AK_Memory };
  2920. ArgKind classifyArgument(Value* arg) {
  2921. Type *T = arg->getType();
  2922. if (T->isFPOrFPVectorTy())
  2923. return AK_FloatingPoint;
  2924. if ((T->isIntegerTy() && T->getPrimitiveSizeInBits() <= 64)
  2925. || (T->isPointerTy()))
  2926. return AK_GeneralPurpose;
  2927. return AK_Memory;
  2928. }
  2929. // The instrumentation stores the argument shadow in a non ABI-specific
  2930. // format because it does not know which argument is named (since Clang,
  2931. // like x86_64 case, lowers the va_args in the frontend and this pass only
  2932. // sees the low level code that deals with va_list internals).
  2933. // The first seven GR registers are saved in the first 56 bytes of the
  2934. // va_arg tls arra, followers by the first 8 FP/SIMD registers, and then
  2935. // the remaining arguments.
  2936. // Using constant offset within the va_arg TLS array allows fast copy
  2937. // in the finalize instrumentation.
  2938. void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
  2939. unsigned GrOffset = AArch64GrBegOffset;
  2940. unsigned VrOffset = AArch64VrBegOffset;
  2941. unsigned OverflowOffset = AArch64VAEndOffset;
  2942. const DataLayout &DL = F.getParent()->getDataLayout();
  2943. for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
  2944. ArgIt != End; ++ArgIt) {
  2945. Value *A = *ArgIt;
  2946. unsigned ArgNo = CS.getArgumentNo(ArgIt);
  2947. bool IsFixed = ArgNo < CS.getFunctionType()->getNumParams();
  2948. ArgKind AK = classifyArgument(A);
  2949. if (AK == AK_GeneralPurpose && GrOffset >= AArch64GrEndOffset)
  2950. AK = AK_Memory;
  2951. if (AK == AK_FloatingPoint && VrOffset >= AArch64VrEndOffset)
  2952. AK = AK_Memory;
  2953. Value *Base;
  2954. switch (AK) {
  2955. case AK_GeneralPurpose:
  2956. Base = getShadowPtrForVAArgument(A->getType(), IRB, GrOffset);
  2957. GrOffset += 8;
  2958. break;
  2959. case AK_FloatingPoint:
  2960. Base = getShadowPtrForVAArgument(A->getType(), IRB, VrOffset);
  2961. VrOffset += 16;
  2962. break;
  2963. case AK_Memory:
  2964. // Don't count fixed arguments in the overflow area - va_start will
  2965. // skip right over them.
  2966. if (IsFixed)
  2967. continue;
  2968. uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
  2969. Base = getShadowPtrForVAArgument(A->getType(), IRB, OverflowOffset);
  2970. OverflowOffset += alignTo(ArgSize, 8);
  2971. break;
  2972. }
  2973. // Count Gp/Vr fixed arguments to their respective offsets, but don't
  2974. // bother to actually store a shadow.
  2975. if (IsFixed)
  2976. continue;
  2977. IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
  2978. }
  2979. Constant *OverflowSize =
  2980. ConstantInt::get(IRB.getInt64Ty(), OverflowOffset - AArch64VAEndOffset);
  2981. IRB.CreateStore(OverflowSize, MS.VAArgOverflowSizeTLS);
  2982. }
  2983. /// Compute the shadow address for a given va_arg.
  2984. Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
  2985. int ArgOffset) {
  2986. Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
  2987. Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
  2988. return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
  2989. "_msarg");
  2990. }
  2991. void visitVAStartInst(VAStartInst &I) override {
  2992. IRBuilder<> IRB(&I);
  2993. VAStartInstrumentationList.push_back(&I);
  2994. Value *VAListTag = I.getArgOperand(0);
  2995. Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
  2996. // Unpoison the whole __va_list_tag.
  2997. // FIXME: magic ABI constants (size of va_list).
  2998. IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
  2999. /* size */32, /* alignment */8, false);
  3000. }
  3001. void visitVACopyInst(VACopyInst &I) override {
  3002. IRBuilder<> IRB(&I);
  3003. Value *VAListTag = I.getArgOperand(0);
  3004. Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
  3005. // Unpoison the whole __va_list_tag.
  3006. // FIXME: magic ABI constants (size of va_list).
  3007. IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
  3008. /* size */32, /* alignment */8, false);
  3009. }
  3010. // Retrieve a va_list field of 'void*' size.
  3011. Value* getVAField64(IRBuilder<> &IRB, Value *VAListTag, int offset) {
  3012. Value *SaveAreaPtrPtr =
  3013. IRB.CreateIntToPtr(
  3014. IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
  3015. ConstantInt::get(MS.IntptrTy, offset)),
  3016. Type::getInt64PtrTy(*MS.C));
  3017. return IRB.CreateLoad(SaveAreaPtrPtr);
  3018. }
  3019. // Retrieve a va_list field of 'int' size.
  3020. Value* getVAField32(IRBuilder<> &IRB, Value *VAListTag, int offset) {
  3021. Value *SaveAreaPtr =
  3022. IRB.CreateIntToPtr(
  3023. IRB.CreateAdd(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
  3024. ConstantInt::get(MS.IntptrTy, offset)),
  3025. Type::getInt32PtrTy(*MS.C));
  3026. Value *SaveArea32 = IRB.CreateLoad(SaveAreaPtr);
  3027. return IRB.CreateSExt(SaveArea32, MS.IntptrTy);
  3028. }
  3029. void finalizeInstrumentation() override {
  3030. assert(!VAArgOverflowSize && !VAArgTLSCopy &&
  3031. "finalizeInstrumentation called twice");
  3032. if (!VAStartInstrumentationList.empty()) {
  3033. // If there is a va_start in this function, make a backup copy of
  3034. // va_arg_tls somewhere in the function entry block.
  3035. IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
  3036. VAArgOverflowSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
  3037. Value *CopySize =
  3038. IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, AArch64VAEndOffset),
  3039. VAArgOverflowSize);
  3040. VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
  3041. IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
  3042. }
  3043. Value *GrArgSize = ConstantInt::get(MS.IntptrTy, kAArch64GrArgSize);
  3044. Value *VrArgSize = ConstantInt::get(MS.IntptrTy, kAArch64VrArgSize);
  3045. // Instrument va_start, copy va_list shadow from the backup copy of
  3046. // the TLS contents.
  3047. for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
  3048. CallInst *OrigInst = VAStartInstrumentationList[i];
  3049. IRBuilder<> IRB(OrigInst->getNextNode());
  3050. Value *VAListTag = OrigInst->getArgOperand(0);
  3051. // The variadic ABI for AArch64 creates two areas to save the incoming
  3052. // argument registers (one for 64-bit general register xn-x7 and another
  3053. // for 128-bit FP/SIMD vn-v7).
  3054. // We need then to propagate the shadow arguments on both regions
  3055. // 'va::__gr_top + va::__gr_offs' and 'va::__vr_top + va::__vr_offs'.
  3056. // The remaning arguments are saved on shadow for 'va::stack'.
  3057. // One caveat is it requires only to propagate the non-named arguments,
  3058. // however on the call site instrumentation 'all' the arguments are
  3059. // saved. So to copy the shadow values from the va_arg TLS array
  3060. // we need to adjust the offset for both GR and VR fields based on
  3061. // the __{gr,vr}_offs value (since they are stores based on incoming
  3062. // named arguments).
  3063. // Read the stack pointer from the va_list.
  3064. Value *StackSaveAreaPtr = getVAField64(IRB, VAListTag, 0);
  3065. // Read both the __gr_top and __gr_off and add them up.
  3066. Value *GrTopSaveAreaPtr = getVAField64(IRB, VAListTag, 8);
  3067. Value *GrOffSaveArea = getVAField32(IRB, VAListTag, 24);
  3068. Value *GrRegSaveAreaPtr = IRB.CreateAdd(GrTopSaveAreaPtr, GrOffSaveArea);
  3069. // Read both the __vr_top and __vr_off and add them up.
  3070. Value *VrTopSaveAreaPtr = getVAField64(IRB, VAListTag, 16);
  3071. Value *VrOffSaveArea = getVAField32(IRB, VAListTag, 28);
  3072. Value *VrRegSaveAreaPtr = IRB.CreateAdd(VrTopSaveAreaPtr, VrOffSaveArea);
  3073. // It does not know how many named arguments is being used and, on the
  3074. // callsite all the arguments were saved. Since __gr_off is defined as
  3075. // '0 - ((8 - named_gr) * 8)', the idea is to just propagate the variadic
  3076. // argument by ignoring the bytes of shadow from named arguments.
  3077. Value *GrRegSaveAreaShadowPtrOff =
  3078. IRB.CreateAdd(GrArgSize, GrOffSaveArea);
  3079. Value *GrRegSaveAreaShadowPtr =
  3080. MSV.getShadowPtr(GrRegSaveAreaPtr, IRB.getInt8Ty(), IRB);
  3081. Value *GrSrcPtr = IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy,
  3082. GrRegSaveAreaShadowPtrOff);
  3083. Value *GrCopySize = IRB.CreateSub(GrArgSize, GrRegSaveAreaShadowPtrOff);
  3084. IRB.CreateMemCpy(GrRegSaveAreaShadowPtr, GrSrcPtr, GrCopySize, 8);
  3085. // Again, but for FP/SIMD values.
  3086. Value *VrRegSaveAreaShadowPtrOff =
  3087. IRB.CreateAdd(VrArgSize, VrOffSaveArea);
  3088. Value *VrRegSaveAreaShadowPtr =
  3089. MSV.getShadowPtr(VrRegSaveAreaPtr, IRB.getInt8Ty(), IRB);
  3090. Value *VrSrcPtr = IRB.CreateInBoundsGEP(
  3091. IRB.getInt8Ty(),
  3092. IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy,
  3093. IRB.getInt32(AArch64VrBegOffset)),
  3094. VrRegSaveAreaShadowPtrOff);
  3095. Value *VrCopySize = IRB.CreateSub(VrArgSize, VrRegSaveAreaShadowPtrOff);
  3096. IRB.CreateMemCpy(VrRegSaveAreaShadowPtr, VrSrcPtr, VrCopySize, 8);
  3097. // And finally for remaining arguments.
  3098. Value *StackSaveAreaShadowPtr =
  3099. MSV.getShadowPtr(StackSaveAreaPtr, IRB.getInt8Ty(), IRB);
  3100. Value *StackSrcPtr =
  3101. IRB.CreateInBoundsGEP(IRB.getInt8Ty(), VAArgTLSCopy,
  3102. IRB.getInt32(AArch64VAEndOffset));
  3103. IRB.CreateMemCpy(StackSaveAreaShadowPtr, StackSrcPtr,
  3104. VAArgOverflowSize, 16);
  3105. }
  3106. }
  3107. };
  3108. /// \brief PowerPC64-specific implementation of VarArgHelper.
  3109. struct VarArgPowerPC64Helper : public VarArgHelper {
  3110. Function &F;
  3111. MemorySanitizer &MS;
  3112. MemorySanitizerVisitor &MSV;
  3113. Value *VAArgTLSCopy;
  3114. Value *VAArgSize;
  3115. SmallVector<CallInst*, 16> VAStartInstrumentationList;
  3116. VarArgPowerPC64Helper(Function &F, MemorySanitizer &MS,
  3117. MemorySanitizerVisitor &MSV)
  3118. : F(F), MS(MS), MSV(MSV), VAArgTLSCopy(nullptr),
  3119. VAArgSize(nullptr) {}
  3120. void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {
  3121. // For PowerPC, we need to deal with alignment of stack arguments -
  3122. // they are mostly aligned to 8 bytes, but vectors and i128 arrays
  3123. // are aligned to 16 bytes, byvals can be aligned to 8 or 16 bytes,
  3124. // and QPX vectors are aligned to 32 bytes. For that reason, we
  3125. // compute current offset from stack pointer (which is always properly
  3126. // aligned), and offset for the first vararg, then subtract them.
  3127. unsigned VAArgBase;
  3128. llvm::Triple TargetTriple(F.getParent()->getTargetTriple());
  3129. // Parameter save area starts at 48 bytes from frame pointer for ABIv1,
  3130. // and 32 bytes for ABIv2. This is usually determined by target
  3131. // endianness, but in theory could be overriden by function attribute.
  3132. // For simplicity, we ignore it here (it'd only matter for QPX vectors).
  3133. if (TargetTriple.getArch() == llvm::Triple::ppc64)
  3134. VAArgBase = 48;
  3135. else
  3136. VAArgBase = 32;
  3137. unsigned VAArgOffset = VAArgBase;
  3138. const DataLayout &DL = F.getParent()->getDataLayout();
  3139. for (CallSite::arg_iterator ArgIt = CS.arg_begin(), End = CS.arg_end();
  3140. ArgIt != End; ++ArgIt) {
  3141. Value *A = *ArgIt;
  3142. unsigned ArgNo = CS.getArgumentNo(ArgIt);
  3143. bool IsFixed = ArgNo < CS.getFunctionType()->getNumParams();
  3144. bool IsByVal = CS.paramHasAttr(ArgNo + 1, Attribute::ByVal);
  3145. if (IsByVal) {
  3146. assert(A->getType()->isPointerTy());
  3147. Type *RealTy = A->getType()->getPointerElementType();
  3148. uint64_t ArgSize = DL.getTypeAllocSize(RealTy);
  3149. uint64_t ArgAlign = CS.getParamAlignment(ArgNo + 1);
  3150. if (ArgAlign < 8)
  3151. ArgAlign = 8;
  3152. VAArgOffset = alignTo(VAArgOffset, ArgAlign);
  3153. if (!IsFixed) {
  3154. Value *Base = getShadowPtrForVAArgument(RealTy, IRB,
  3155. VAArgOffset - VAArgBase);
  3156. IRB.CreateMemCpy(Base, MSV.getShadowPtr(A, IRB.getInt8Ty(), IRB),
  3157. ArgSize, kShadowTLSAlignment);
  3158. }
  3159. VAArgOffset += alignTo(ArgSize, 8);
  3160. } else {
  3161. Value *Base;
  3162. uint64_t ArgSize = DL.getTypeAllocSize(A->getType());
  3163. uint64_t ArgAlign = 8;
  3164. if (A->getType()->isArrayTy()) {
  3165. // Arrays are aligned to element size, except for long double
  3166. // arrays, which are aligned to 8 bytes.
  3167. Type *ElementTy = A->getType()->getArrayElementType();
  3168. if (!ElementTy->isPPC_FP128Ty())
  3169. ArgAlign = DL.getTypeAllocSize(ElementTy);
  3170. } else if (A->getType()->isVectorTy()) {
  3171. // Vectors are naturally aligned.
  3172. ArgAlign = DL.getTypeAllocSize(A->getType());
  3173. }
  3174. if (ArgAlign < 8)
  3175. ArgAlign = 8;
  3176. VAArgOffset = alignTo(VAArgOffset, ArgAlign);
  3177. if (DL.isBigEndian()) {
  3178. // Adjusting the shadow for argument with size < 8 to match the placement
  3179. // of bits in big endian system
  3180. if (ArgSize < 8)
  3181. VAArgOffset += (8 - ArgSize);
  3182. }
  3183. if (!IsFixed) {
  3184. Base = getShadowPtrForVAArgument(A->getType(), IRB,
  3185. VAArgOffset - VAArgBase);
  3186. IRB.CreateAlignedStore(MSV.getShadow(A), Base, kShadowTLSAlignment);
  3187. }
  3188. VAArgOffset += ArgSize;
  3189. VAArgOffset = alignTo(VAArgOffset, 8);
  3190. }
  3191. if (IsFixed)
  3192. VAArgBase = VAArgOffset;
  3193. }
  3194. Constant *TotalVAArgSize = ConstantInt::get(IRB.getInt64Ty(),
  3195. VAArgOffset - VAArgBase);
  3196. // Here using VAArgOverflowSizeTLS as VAArgSizeTLS to avoid creation of
  3197. // a new class member i.e. it is the total size of all VarArgs.
  3198. IRB.CreateStore(TotalVAArgSize, MS.VAArgOverflowSizeTLS);
  3199. }
  3200. /// \brief Compute the shadow address for a given va_arg.
  3201. Value *getShadowPtrForVAArgument(Type *Ty, IRBuilder<> &IRB,
  3202. int ArgOffset) {
  3203. Value *Base = IRB.CreatePointerCast(MS.VAArgTLS, MS.IntptrTy);
  3204. Base = IRB.CreateAdd(Base, ConstantInt::get(MS.IntptrTy, ArgOffset));
  3205. return IRB.CreateIntToPtr(Base, PointerType::get(MSV.getShadowTy(Ty), 0),
  3206. "_msarg");
  3207. }
  3208. void visitVAStartInst(VAStartInst &I) override {
  3209. IRBuilder<> IRB(&I);
  3210. VAStartInstrumentationList.push_back(&I);
  3211. Value *VAListTag = I.getArgOperand(0);
  3212. Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
  3213. IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
  3214. /* size */8, /* alignment */8, false);
  3215. }
  3216. void visitVACopyInst(VACopyInst &I) override {
  3217. IRBuilder<> IRB(&I);
  3218. Value *VAListTag = I.getArgOperand(0);
  3219. Value *ShadowPtr = MSV.getShadowPtr(VAListTag, IRB.getInt8Ty(), IRB);
  3220. // Unpoison the whole __va_list_tag.
  3221. // FIXME: magic ABI constants.
  3222. IRB.CreateMemSet(ShadowPtr, Constant::getNullValue(IRB.getInt8Ty()),
  3223. /* size */8, /* alignment */8, false);
  3224. }
  3225. void finalizeInstrumentation() override {
  3226. assert(!VAArgSize && !VAArgTLSCopy &&
  3227. "finalizeInstrumentation called twice");
  3228. IRBuilder<> IRB(F.getEntryBlock().getFirstNonPHI());
  3229. VAArgSize = IRB.CreateLoad(MS.VAArgOverflowSizeTLS);
  3230. Value *CopySize = IRB.CreateAdd(ConstantInt::get(MS.IntptrTy, 0),
  3231. VAArgSize);
  3232. if (!VAStartInstrumentationList.empty()) {
  3233. // If there is a va_start in this function, make a backup copy of
  3234. // va_arg_tls somewhere in the function entry block.
  3235. VAArgTLSCopy = IRB.CreateAlloca(Type::getInt8Ty(*MS.C), CopySize);
  3236. IRB.CreateMemCpy(VAArgTLSCopy, MS.VAArgTLS, CopySize, 8);
  3237. }
  3238. // Instrument va_start.
  3239. // Copy va_list shadow from the backup copy of the TLS contents.
  3240. for (size_t i = 0, n = VAStartInstrumentationList.size(); i < n; i++) {
  3241. CallInst *OrigInst = VAStartInstrumentationList[i];
  3242. IRBuilder<> IRB(OrigInst->getNextNode());
  3243. Value *VAListTag = OrigInst->getArgOperand(0);
  3244. Value *RegSaveAreaPtrPtr =
  3245. IRB.CreateIntToPtr(IRB.CreatePtrToInt(VAListTag, MS.IntptrTy),
  3246. Type::getInt64PtrTy(*MS.C));
  3247. Value *RegSaveAreaPtr = IRB.CreateLoad(RegSaveAreaPtrPtr);
  3248. Value *RegSaveAreaShadowPtr =
  3249. MSV.getShadowPtr(RegSaveAreaPtr, IRB.getInt8Ty(), IRB);
  3250. IRB.CreateMemCpy(RegSaveAreaShadowPtr, VAArgTLSCopy, CopySize, 8);
  3251. }
  3252. }
  3253. };
  3254. /// \brief A no-op implementation of VarArgHelper.
  3255. struct VarArgNoOpHelper : public VarArgHelper {
  3256. VarArgNoOpHelper(Function &F, MemorySanitizer &MS,
  3257. MemorySanitizerVisitor &MSV) {}
  3258. void visitCallSite(CallSite &CS, IRBuilder<> &IRB) override {}
  3259. void visitVAStartInst(VAStartInst &I) override {}
  3260. void visitVACopyInst(VACopyInst &I) override {}
  3261. void finalizeInstrumentation() override {}
  3262. };
  3263. VarArgHelper *CreateVarArgHelper(Function &Func, MemorySanitizer &Msan,
  3264. MemorySanitizerVisitor &Visitor) {
  3265. // VarArg handling is only implemented on AMD64. False positives are possible
  3266. // on other platforms.
  3267. llvm::Triple TargetTriple(Func.getParent()->getTargetTriple());
  3268. if (TargetTriple.getArch() == llvm::Triple::x86_64)
  3269. return new VarArgAMD64Helper(Func, Msan, Visitor);
  3270. else if (TargetTriple.getArch() == llvm::Triple::mips64 ||
  3271. TargetTriple.getArch() == llvm::Triple::mips64el)
  3272. return new VarArgMIPS64Helper(Func, Msan, Visitor);
  3273. else if (TargetTriple.getArch() == llvm::Triple::aarch64)
  3274. return new VarArgAArch64Helper(Func, Msan, Visitor);
  3275. else if (TargetTriple.getArch() == llvm::Triple::ppc64 ||
  3276. TargetTriple.getArch() == llvm::Triple::ppc64le)
  3277. return new VarArgPowerPC64Helper(Func, Msan, Visitor);
  3278. else
  3279. return new VarArgNoOpHelper(Func, Msan, Visitor);
  3280. }
  3281. } // anonymous namespace
  3282. bool MemorySanitizer::runOnFunction(Function &F) {
  3283. if (&F == MsanCtorFunction)
  3284. return false;
  3285. MemorySanitizerVisitor Visitor(F, *this);
  3286. // Clear out readonly/readnone attributes.
  3287. AttrBuilder B;
  3288. B.addAttribute(Attribute::ReadOnly)
  3289. .addAttribute(Attribute::ReadNone);
  3290. F.removeAttributes(
  3291. AttributeList::FunctionIndex,
  3292. AttributeList::get(F.getContext(), AttributeList::FunctionIndex, B));
  3293. return Visitor.runOnFunction();
  3294. }