1 //===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the auto-upgrade helper functions.
10 // This is where deprecated IR intrinsics and other IR features are updated to
11 // current specifications.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/IR/AutoUpgrade.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DIBuilder.h"
19 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/DiagnosticInfo.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/Verifier.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/Regex.h"
30 #include <cstring>
31 using namespace llvm;
32 
33 static void rename(GlobalValue *GV) { GV->setName(GV->getName() + ".old"); }
34 
35 // Upgrade the declarations of the SSE4.1 ptest intrinsics whose arguments have
36 // changed their type from v4f32 to v2i64.
37 static bool UpgradePTESTIntrinsic(Function* F, Intrinsic::ID IID,
38                                   Function *&NewFn) {
39   // Check whether this is an old version of the function, which received
40   // v4f32 arguments.
41   Type *Arg0Type = F->getFunctionType()->getParamType(0);
42   if (Arg0Type != VectorType::get(Type::getFloatTy(F->getContext()), 4))
43     return false;
44 
45   // Yes, it's old, replace it with new version.
46   rename(F);
47   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
48   return true;
49 }
50 
51 // Upgrade the declarations of intrinsic functions whose 8-bit immediate mask
52 // arguments have changed their type from i32 to i8.
53 static bool UpgradeX86IntrinsicsWith8BitMask(Function *F, Intrinsic::ID IID,
54                                              Function *&NewFn) {
55   // Check that the last argument is an i32.
56   Type *LastArgType = F->getFunctionType()->getParamType(
57      F->getFunctionType()->getNumParams() - 1);
58   if (!LastArgType->isIntegerTy(32))
59     return false;
60 
61   // Move this function aside and map down.
62   rename(F);
63   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
64   return true;
65 }
66 
67 static bool ShouldUpgradeX86Intrinsic(Function *F, StringRef Name) {
68   // All of the intrinsics matches below should be marked with which llvm
69   // version started autoupgrading them. At some point in the future we would
70   // like to use this information to remove upgrade code for some older
71   // intrinsics. It is currently undecided how we will determine that future
72   // point.
73   if (Name == "addcarryx.u32" || // Added in 8.0
74       Name == "addcarryx.u64" || // Added in 8.0
75       Name == "addcarry.u32" || // Added in 8.0
76       Name == "addcarry.u64" || // Added in 8.0
77       Name == "subborrow.u32" || // Added in 8.0
78       Name == "subborrow.u64" || // Added in 8.0
79       Name.startswith("sse2.padds.") || // Added in 8.0
80       Name.startswith("sse2.psubs.") || // Added in 8.0
81       Name.startswith("sse2.paddus.") || // Added in 8.0
82       Name.startswith("sse2.psubus.") || // Added in 8.0
83       Name.startswith("avx2.padds.") || // Added in 8.0
84       Name.startswith("avx2.psubs.") || // Added in 8.0
85       Name.startswith("avx2.paddus.") || // Added in 8.0
86       Name.startswith("avx2.psubus.") || // Added in 8.0
87       Name.startswith("avx512.padds.") || // Added in 8.0
88       Name.startswith("avx512.psubs.") || // Added in 8.0
89       Name.startswith("avx512.mask.padds.") || // Added in 8.0
90       Name.startswith("avx512.mask.psubs.") || // Added in 8.0
91       Name.startswith("avx512.mask.paddus.") || // Added in 8.0
92       Name.startswith("avx512.mask.psubus.") || // Added in 8.0
93       Name=="ssse3.pabs.b.128" || // Added in 6.0
94       Name=="ssse3.pabs.w.128" || // Added in 6.0
95       Name=="ssse3.pabs.d.128" || // Added in 6.0
96       Name.startswith("fma4.vfmadd.s") || // Added in 7.0
97       Name.startswith("fma.vfmadd.") || // Added in 7.0
98       Name.startswith("fma.vfmsub.") || // Added in 7.0
99       Name.startswith("fma.vfmaddsub.") || // Added in 7.0
100       Name.startswith("fma.vfmsubadd.") || // Added in 7.0
101       Name.startswith("fma.vfnmadd.") || // Added in 7.0
102       Name.startswith("fma.vfnmsub.") || // Added in 7.0
103       Name.startswith("avx512.mask.vfmadd.") || // Added in 7.0
104       Name.startswith("avx512.mask.vfnmadd.") || // Added in 7.0
105       Name.startswith("avx512.mask.vfnmsub.") || // Added in 7.0
106       Name.startswith("avx512.mask3.vfmadd.") || // Added in 7.0
107       Name.startswith("avx512.maskz.vfmadd.") || // Added in 7.0
108       Name.startswith("avx512.mask3.vfmsub.") || // Added in 7.0
109       Name.startswith("avx512.mask3.vfnmsub.") || // Added in 7.0
110       Name.startswith("avx512.mask.vfmaddsub.") || // Added in 7.0
111       Name.startswith("avx512.maskz.vfmaddsub.") || // Added in 7.0
112       Name.startswith("avx512.mask3.vfmaddsub.") || // Added in 7.0
113       Name.startswith("avx512.mask3.vfmsubadd.") || // Added in 7.0
114       Name.startswith("avx512.mask.shuf.i") || // Added in 6.0
115       Name.startswith("avx512.mask.shuf.f") || // Added in 6.0
116       Name.startswith("avx512.kunpck") || //added in 6.0
117       Name.startswith("avx2.pabs.") || // Added in 6.0
118       Name.startswith("avx512.mask.pabs.") || // Added in 6.0
119       Name.startswith("avx512.broadcastm") || // Added in 6.0
120       Name == "sse.sqrt.ss" || // Added in 7.0
121       Name == "sse2.sqrt.sd" || // Added in 7.0
122       Name.startswith("avx512.mask.sqrt.p") || // Added in 7.0
123       Name.startswith("avx.sqrt.p") || // Added in 7.0
124       Name.startswith("sse2.sqrt.p") || // Added in 7.0
125       Name.startswith("sse.sqrt.p") || // Added in 7.0
126       Name.startswith("avx512.mask.pbroadcast") || // Added in 6.0
127       Name.startswith("sse2.pcmpeq.") || // Added in 3.1
128       Name.startswith("sse2.pcmpgt.") || // Added in 3.1
129       Name.startswith("avx2.pcmpeq.") || // Added in 3.1
130       Name.startswith("avx2.pcmpgt.") || // Added in 3.1
131       Name.startswith("avx512.mask.pcmpeq.") || // Added in 3.9
132       Name.startswith("avx512.mask.pcmpgt.") || // Added in 3.9
133       Name.startswith("avx.vperm2f128.") || // Added in 6.0
134       Name == "avx2.vperm2i128" || // Added in 6.0
135       Name == "sse.add.ss" || // Added in 4.0
136       Name == "sse2.add.sd" || // Added in 4.0
137       Name == "sse.sub.ss" || // Added in 4.0
138       Name == "sse2.sub.sd" || // Added in 4.0
139       Name == "sse.mul.ss" || // Added in 4.0
140       Name == "sse2.mul.sd" || // Added in 4.0
141       Name == "sse.div.ss" || // Added in 4.0
142       Name == "sse2.div.sd" || // Added in 4.0
143       Name == "sse41.pmaxsb" || // Added in 3.9
144       Name == "sse2.pmaxs.w" || // Added in 3.9
145       Name == "sse41.pmaxsd" || // Added in 3.9
146       Name == "sse2.pmaxu.b" || // Added in 3.9
147       Name == "sse41.pmaxuw" || // Added in 3.9
148       Name == "sse41.pmaxud" || // Added in 3.9
149       Name == "sse41.pminsb" || // Added in 3.9
150       Name == "sse2.pmins.w" || // Added in 3.9
151       Name == "sse41.pminsd" || // Added in 3.9
152       Name == "sse2.pminu.b" || // Added in 3.9
153       Name == "sse41.pminuw" || // Added in 3.9
154       Name == "sse41.pminud" || // Added in 3.9
155       Name == "avx512.kand.w" || // Added in 7.0
156       Name == "avx512.kandn.w" || // Added in 7.0
157       Name == "avx512.knot.w" || // Added in 7.0
158       Name == "avx512.kor.w" || // Added in 7.0
159       Name == "avx512.kxor.w" || // Added in 7.0
160       Name == "avx512.kxnor.w" || // Added in 7.0
161       Name == "avx512.kortestc.w" || // Added in 7.0
162       Name == "avx512.kortestz.w" || // Added in 7.0
163       Name.startswith("avx512.mask.pshuf.b.") || // Added in 4.0
164       Name.startswith("avx2.pmax") || // Added in 3.9
165       Name.startswith("avx2.pmin") || // Added in 3.9
166       Name.startswith("avx512.mask.pmax") || // Added in 4.0
167       Name.startswith("avx512.mask.pmin") || // Added in 4.0
168       Name.startswith("avx2.vbroadcast") || // Added in 3.8
169       Name.startswith("avx2.pbroadcast") || // Added in 3.8
170       Name.startswith("avx.vpermil.") || // Added in 3.1
171       Name.startswith("sse2.pshuf") || // Added in 3.9
172       Name.startswith("avx512.pbroadcast") || // Added in 3.9
173       Name.startswith("avx512.mask.broadcast.s") || // Added in 3.9
174       Name.startswith("avx512.mask.movddup") || // Added in 3.9
175       Name.startswith("avx512.mask.movshdup") || // Added in 3.9
176       Name.startswith("avx512.mask.movsldup") || // Added in 3.9
177       Name.startswith("avx512.mask.pshuf.d.") || // Added in 3.9
178       Name.startswith("avx512.mask.pshufl.w.") || // Added in 3.9
179       Name.startswith("avx512.mask.pshufh.w.") || // Added in 3.9
180       Name.startswith("avx512.mask.shuf.p") || // Added in 4.0
181       Name.startswith("avx512.mask.vpermil.p") || // Added in 3.9
182       Name.startswith("avx512.mask.perm.df.") || // Added in 3.9
183       Name.startswith("avx512.mask.perm.di.") || // Added in 3.9
184       Name.startswith("avx512.mask.punpckl") || // Added in 3.9
185       Name.startswith("avx512.mask.punpckh") || // Added in 3.9
186       Name.startswith("avx512.mask.unpckl.") || // Added in 3.9
187       Name.startswith("avx512.mask.unpckh.") || // Added in 3.9
188       Name.startswith("avx512.mask.pand.") || // Added in 3.9
189       Name.startswith("avx512.mask.pandn.") || // Added in 3.9
190       Name.startswith("avx512.mask.por.") || // Added in 3.9
191       Name.startswith("avx512.mask.pxor.") || // Added in 3.9
192       Name.startswith("avx512.mask.and.") || // Added in 3.9
193       Name.startswith("avx512.mask.andn.") || // Added in 3.9
194       Name.startswith("avx512.mask.or.") || // Added in 3.9
195       Name.startswith("avx512.mask.xor.") || // Added in 3.9
196       Name.startswith("avx512.mask.padd.") || // Added in 4.0
197       Name.startswith("avx512.mask.psub.") || // Added in 4.0
198       Name.startswith("avx512.mask.pmull.") || // Added in 4.0
199       Name.startswith("avx512.mask.cvtdq2pd.") || // Added in 4.0
200       Name.startswith("avx512.mask.cvtudq2pd.") || // Added in 4.0
201       Name.startswith("avx512.mask.cvtudq2ps.") || // Added in 7.0 updated 9.0
202       Name.startswith("avx512.mask.cvtqq2pd.") || // Added in 7.0 updated 9.0
203       Name.startswith("avx512.mask.cvtuqq2pd.") || // Added in 7.0 updated 9.0
204       Name.startswith("avx512.mask.cvtdq2ps.") || // Added in 7.0 updated 9.0
205       Name == "avx512.mask.cvtqq2ps.256" || // Added in 9.0
206       Name == "avx512.mask.cvtqq2ps.512" || // Added in 9.0
207       Name == "avx512.mask.cvtuqq2ps.256" || // Added in 9.0
208       Name == "avx512.mask.cvtuqq2ps.512" || // Added in 9.0
209       Name == "avx512.mask.cvtpd2dq.256" || // Added in 7.0
210       Name == "avx512.mask.cvtpd2ps.256" || // Added in 7.0
211       Name == "avx512.mask.cvttpd2dq.256" || // Added in 7.0
212       Name == "avx512.mask.cvttps2dq.128" || // Added in 7.0
213       Name == "avx512.mask.cvttps2dq.256" || // Added in 7.0
214       Name == "avx512.mask.cvtps2pd.128" || // Added in 7.0
215       Name == "avx512.mask.cvtps2pd.256" || // Added in 7.0
216       Name == "avx512.cvtusi2sd" || // Added in 7.0
217       Name.startswith("avx512.mask.permvar.") || // Added in 7.0
218       Name == "sse2.pmulu.dq" || // Added in 7.0
219       Name == "sse41.pmuldq" || // Added in 7.0
220       Name == "avx2.pmulu.dq" || // Added in 7.0
221       Name == "avx2.pmul.dq" || // Added in 7.0
222       Name == "avx512.pmulu.dq.512" || // Added in 7.0
223       Name == "avx512.pmul.dq.512" || // Added in 7.0
224       Name.startswith("avx512.mask.pmul.dq.") || // Added in 4.0
225       Name.startswith("avx512.mask.pmulu.dq.") || // Added in 4.0
226       Name.startswith("avx512.mask.pmul.hr.sw.") || // Added in 7.0
227       Name.startswith("avx512.mask.pmulh.w.") || // Added in 7.0
228       Name.startswith("avx512.mask.pmulhu.w.") || // Added in 7.0
229       Name.startswith("avx512.mask.pmaddw.d.") || // Added in 7.0
230       Name.startswith("avx512.mask.pmaddubs.w.") || // Added in 7.0
231       Name.startswith("avx512.mask.packsswb.") || // Added in 5.0
232       Name.startswith("avx512.mask.packssdw.") || // Added in 5.0
233       Name.startswith("avx512.mask.packuswb.") || // Added in 5.0
234       Name.startswith("avx512.mask.packusdw.") || // Added in 5.0
235       Name.startswith("avx512.mask.cmp.b") || // Added in 5.0
236       Name.startswith("avx512.mask.cmp.d") || // Added in 5.0
237       Name.startswith("avx512.mask.cmp.q") || // Added in 5.0
238       Name.startswith("avx512.mask.cmp.w") || // Added in 5.0
239       Name.startswith("avx512.mask.cmp.p") || // Added in 7.0
240       Name.startswith("avx512.mask.ucmp.") || // Added in 5.0
241       Name.startswith("avx512.cvtb2mask.") || // Added in 7.0
242       Name.startswith("avx512.cvtw2mask.") || // Added in 7.0
243       Name.startswith("avx512.cvtd2mask.") || // Added in 7.0
244       Name.startswith("avx512.cvtq2mask.") || // Added in 7.0
245       Name.startswith("avx512.mask.vpermilvar.") || // Added in 4.0
246       Name.startswith("avx512.mask.psll.d") || // Added in 4.0
247       Name.startswith("avx512.mask.psll.q") || // Added in 4.0
248       Name.startswith("avx512.mask.psll.w") || // Added in 4.0
249       Name.startswith("avx512.mask.psra.d") || // Added in 4.0
250       Name.startswith("avx512.mask.psra.q") || // Added in 4.0
251       Name.startswith("avx512.mask.psra.w") || // Added in 4.0
252       Name.startswith("avx512.mask.psrl.d") || // Added in 4.0
253       Name.startswith("avx512.mask.psrl.q") || // Added in 4.0
254       Name.startswith("avx512.mask.psrl.w") || // Added in 4.0
255       Name.startswith("avx512.mask.pslli") || // Added in 4.0
256       Name.startswith("avx512.mask.psrai") || // Added in 4.0
257       Name.startswith("avx512.mask.psrli") || // Added in 4.0
258       Name.startswith("avx512.mask.psllv") || // Added in 4.0
259       Name.startswith("avx512.mask.psrav") || // Added in 4.0
260       Name.startswith("avx512.mask.psrlv") || // Added in 4.0
261       Name.startswith("sse41.pmovsx") || // Added in 3.8
262       Name.startswith("sse41.pmovzx") || // Added in 3.9
263       Name.startswith("avx2.pmovsx") || // Added in 3.9
264       Name.startswith("avx2.pmovzx") || // Added in 3.9
265       Name.startswith("avx512.mask.pmovsx") || // Added in 4.0
266       Name.startswith("avx512.mask.pmovzx") || // Added in 4.0
267       Name.startswith("avx512.mask.lzcnt.") || // Added in 5.0
268       Name.startswith("avx512.mask.pternlog.") || // Added in 7.0
269       Name.startswith("avx512.maskz.pternlog.") || // Added in 7.0
270       Name.startswith("avx512.mask.vpmadd52") || // Added in 7.0
271       Name.startswith("avx512.maskz.vpmadd52") || // Added in 7.0
272       Name.startswith("avx512.mask.vpermi2var.") || // Added in 7.0
273       Name.startswith("avx512.mask.vpermt2var.") || // Added in 7.0
274       Name.startswith("avx512.maskz.vpermt2var.") || // Added in 7.0
275       Name.startswith("avx512.mask.vpdpbusd.") || // Added in 7.0
276       Name.startswith("avx512.maskz.vpdpbusd.") || // Added in 7.0
277       Name.startswith("avx512.mask.vpdpbusds.") || // Added in 7.0
278       Name.startswith("avx512.maskz.vpdpbusds.") || // Added in 7.0
279       Name.startswith("avx512.mask.vpdpwssd.") || // Added in 7.0
280       Name.startswith("avx512.maskz.vpdpwssd.") || // Added in 7.0
281       Name.startswith("avx512.mask.vpdpwssds.") || // Added in 7.0
282       Name.startswith("avx512.maskz.vpdpwssds.") || // Added in 7.0
283       Name.startswith("avx512.mask.dbpsadbw.") || // Added in 7.0
284       Name.startswith("avx512.mask.vpshld.") || // Added in 7.0
285       Name.startswith("avx512.mask.vpshrd.") || // Added in 7.0
286       Name.startswith("avx512.mask.vpshldv.") || // Added in 8.0
287       Name.startswith("avx512.mask.vpshrdv.") || // Added in 8.0
288       Name.startswith("avx512.maskz.vpshldv.") || // Added in 8.0
289       Name.startswith("avx512.maskz.vpshrdv.") || // Added in 8.0
290       Name.startswith("avx512.vpshld.") || // Added in 8.0
291       Name.startswith("avx512.vpshrd.") || // Added in 8.0
292       Name.startswith("avx512.mask.add.p") || // Added in 7.0. 128/256 in 4.0
293       Name.startswith("avx512.mask.sub.p") || // Added in 7.0. 128/256 in 4.0
294       Name.startswith("avx512.mask.mul.p") || // Added in 7.0. 128/256 in 4.0
295       Name.startswith("avx512.mask.div.p") || // Added in 7.0. 128/256 in 4.0
296       Name.startswith("avx512.mask.max.p") || // Added in 7.0. 128/256 in 5.0
297       Name.startswith("avx512.mask.min.p") || // Added in 7.0. 128/256 in 5.0
298       Name.startswith("avx512.mask.fpclass.p") || // Added in 7.0
299       Name.startswith("avx512.mask.vpshufbitqmb.") || // Added in 8.0
300       Name.startswith("avx512.mask.pmultishift.qb.") || // Added in 8.0
301       Name.startswith("avx512.mask.conflict.") || // Added in 9.0
302       Name == "avx512.mask.pmov.qd.256" || // Added in 9.0
303       Name == "avx512.mask.pmov.qd.512" || // Added in 9.0
304       Name == "avx512.mask.pmov.wb.256" || // Added in 9.0
305       Name == "avx512.mask.pmov.wb.512" || // Added in 9.0
306       Name == "sse.cvtsi2ss" || // Added in 7.0
307       Name == "sse.cvtsi642ss" || // Added in 7.0
308       Name == "sse2.cvtsi2sd" || // Added in 7.0
309       Name == "sse2.cvtsi642sd" || // Added in 7.0
310       Name == "sse2.cvtss2sd" || // Added in 7.0
311       Name == "sse2.cvtdq2pd" || // Added in 3.9
312       Name == "sse2.cvtdq2ps" || // Added in 7.0
313       Name == "sse2.cvtps2pd" || // Added in 3.9
314       Name == "avx.cvtdq2.pd.256" || // Added in 3.9
315       Name == "avx.cvtdq2.ps.256" || // Added in 7.0
316       Name == "avx.cvt.ps2.pd.256" || // Added in 3.9
317       Name.startswith("avx.vinsertf128.") || // Added in 3.7
318       Name == "avx2.vinserti128" || // Added in 3.7
319       Name.startswith("avx512.mask.insert") || // Added in 4.0
320       Name.startswith("avx.vextractf128.") || // Added in 3.7
321       Name == "avx2.vextracti128" || // Added in 3.7
322       Name.startswith("avx512.mask.vextract") || // Added in 4.0
323       Name.startswith("sse4a.movnt.") || // Added in 3.9
324       Name.startswith("avx.movnt.") || // Added in 3.2
325       Name.startswith("avx512.storent.") || // Added in 3.9
326       Name == "sse41.movntdqa" || // Added in 5.0
327       Name == "avx2.movntdqa" || // Added in 5.0
328       Name == "avx512.movntdqa" || // Added in 5.0
329       Name == "sse2.storel.dq" || // Added in 3.9
330       Name.startswith("sse.storeu.") || // Added in 3.9
331       Name.startswith("sse2.storeu.") || // Added in 3.9
332       Name.startswith("avx.storeu.") || // Added in 3.9
333       Name.startswith("avx512.mask.storeu.") || // Added in 3.9
334       Name.startswith("avx512.mask.store.p") || // Added in 3.9
335       Name.startswith("avx512.mask.store.b.") || // Added in 3.9
336       Name.startswith("avx512.mask.store.w.") || // Added in 3.9
337       Name.startswith("avx512.mask.store.d.") || // Added in 3.9
338       Name.startswith("avx512.mask.store.q.") || // Added in 3.9
339       Name == "avx512.mask.store.ss" || // Added in 7.0
340       Name.startswith("avx512.mask.loadu.") || // Added in 3.9
341       Name.startswith("avx512.mask.load.") || // Added in 3.9
342       Name.startswith("avx512.mask.expand.load.") || // Added in 7.0
343       Name.startswith("avx512.mask.compress.store.") || // Added in 7.0
344       Name.startswith("avx512.mask.expand.b") || // Added in 9.0
345       Name.startswith("avx512.mask.expand.w") || // Added in 9.0
346       Name.startswith("avx512.mask.expand.d") || // Added in 9.0
347       Name.startswith("avx512.mask.expand.q") || // Added in 9.0
348       Name.startswith("avx512.mask.expand.p") || // Added in 9.0
349       Name.startswith("avx512.mask.compress.b") || // Added in 9.0
350       Name.startswith("avx512.mask.compress.w") || // Added in 9.0
351       Name.startswith("avx512.mask.compress.d") || // Added in 9.0
352       Name.startswith("avx512.mask.compress.q") || // Added in 9.0
353       Name.startswith("avx512.mask.compress.p") || // Added in 9.0
354       Name == "sse42.crc32.64.8" || // Added in 3.4
355       Name.startswith("avx.vbroadcast.s") || // Added in 3.5
356       Name.startswith("avx512.vbroadcast.s") || // Added in 7.0
357       Name.startswith("avx512.mask.palignr.") || // Added in 3.9
358       Name.startswith("avx512.mask.valign.") || // Added in 4.0
359       Name.startswith("sse2.psll.dq") || // Added in 3.7
360       Name.startswith("sse2.psrl.dq") || // Added in 3.7
361       Name.startswith("avx2.psll.dq") || // Added in 3.7
362       Name.startswith("avx2.psrl.dq") || // Added in 3.7
363       Name.startswith("avx512.psll.dq") || // Added in 3.9
364       Name.startswith("avx512.psrl.dq") || // Added in 3.9
365       Name == "sse41.pblendw" || // Added in 3.7
366       Name.startswith("sse41.blendp") || // Added in 3.7
367       Name.startswith("avx.blend.p") || // Added in 3.7
368       Name == "avx2.pblendw" || // Added in 3.7
369       Name.startswith("avx2.pblendd.") || // Added in 3.7
370       Name.startswith("avx.vbroadcastf128") || // Added in 4.0
371       Name == "avx2.vbroadcasti128" || // Added in 3.7
372       Name.startswith("avx512.mask.broadcastf") || // Added in 6.0
373       Name.startswith("avx512.mask.broadcasti") || // Added in 6.0
374       Name == "xop.vpcmov" || // Added in 3.8
375       Name == "xop.vpcmov.256" || // Added in 5.0
376       Name.startswith("avx512.mask.move.s") || // Added in 4.0
377       Name.startswith("avx512.cvtmask2") || // Added in 5.0
378       Name.startswith("xop.vpcom") || // Added in 3.2, Updated in 9.0
379       Name.startswith("xop.vprot") || // Added in 8.0
380       Name.startswith("avx512.prol") || // Added in 8.0
381       Name.startswith("avx512.pror") || // Added in 8.0
382       Name.startswith("avx512.mask.prorv.") || // Added in 8.0
383       Name.startswith("avx512.mask.pror.") ||  // Added in 8.0
384       Name.startswith("avx512.mask.prolv.") || // Added in 8.0
385       Name.startswith("avx512.mask.prol.") ||  // Added in 8.0
386       Name.startswith("avx512.ptestm") || //Added in 6.0
387       Name.startswith("avx512.ptestnm") || //Added in 6.0
388       Name.startswith("avx512.mask.pavg")) // Added in 6.0
389     return true;
390 
391   return false;
392 }
393 
394 static bool UpgradeX86IntrinsicFunction(Function *F, StringRef Name,
395                                         Function *&NewFn) {
396   // Only handle intrinsics that start with "x86.".
397   if (!Name.startswith("x86."))
398     return false;
399   // Remove "x86." prefix.
400   Name = Name.substr(4);
401 
402   if (ShouldUpgradeX86Intrinsic(F, Name)) {
403     NewFn = nullptr;
404     return true;
405   }
406 
407   if (Name == "rdtscp") { // Added in 8.0
408     // If this intrinsic has 0 operands, it's the new version.
409     if (F->getFunctionType()->getNumParams() == 0)
410       return false;
411 
412     rename(F);
413     NewFn = Intrinsic::getDeclaration(F->getParent(),
414                                       Intrinsic::x86_rdtscp);
415     return true;
416   }
417 
418   // SSE4.1 ptest functions may have an old signature.
419   if (Name.startswith("sse41.ptest")) { // Added in 3.2
420     if (Name.substr(11) == "c")
421       return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestc, NewFn);
422     if (Name.substr(11) == "z")
423       return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestz, NewFn);
424     if (Name.substr(11) == "nzc")
425       return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestnzc, NewFn);
426   }
427   // Several blend and other instructions with masks used the wrong number of
428   // bits.
429   if (Name == "sse41.insertps") // Added in 3.6
430     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_insertps,
431                                             NewFn);
432   if (Name == "sse41.dppd") // Added in 3.6
433     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dppd,
434                                             NewFn);
435   if (Name == "sse41.dpps") // Added in 3.6
436     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dpps,
437                                             NewFn);
438   if (Name == "sse41.mpsadbw") // Added in 3.6
439     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_mpsadbw,
440                                             NewFn);
441   if (Name == "avx.dp.ps.256") // Added in 3.6
442     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx_dp_ps_256,
443                                             NewFn);
444   if (Name == "avx2.mpsadbw") // Added in 3.6
445     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx2_mpsadbw,
446                                             NewFn);
447 
448   // frcz.ss/sd may need to have an argument dropped. Added in 3.2
449   if (Name.startswith("xop.vfrcz.ss") && F->arg_size() == 2) {
450     rename(F);
451     NewFn = Intrinsic::getDeclaration(F->getParent(),
452                                       Intrinsic::x86_xop_vfrcz_ss);
453     return true;
454   }
455   if (Name.startswith("xop.vfrcz.sd") && F->arg_size() == 2) {
456     rename(F);
457     NewFn = Intrinsic::getDeclaration(F->getParent(),
458                                       Intrinsic::x86_xop_vfrcz_sd);
459     return true;
460   }
461   // Upgrade any XOP PERMIL2 index operand still using a float/double vector.
462   if (Name.startswith("xop.vpermil2")) { // Added in 3.9
463     auto Idx = F->getFunctionType()->getParamType(2);
464     if (Idx->isFPOrFPVectorTy()) {
465       rename(F);
466       unsigned IdxSize = Idx->getPrimitiveSizeInBits();
467       unsigned EltSize = Idx->getScalarSizeInBits();
468       Intrinsic::ID Permil2ID;
469       if (EltSize == 64 && IdxSize == 128)
470         Permil2ID = Intrinsic::x86_xop_vpermil2pd;
471       else if (EltSize == 32 && IdxSize == 128)
472         Permil2ID = Intrinsic::x86_xop_vpermil2ps;
473       else if (EltSize == 64 && IdxSize == 256)
474         Permil2ID = Intrinsic::x86_xop_vpermil2pd_256;
475       else
476         Permil2ID = Intrinsic::x86_xop_vpermil2ps_256;
477       NewFn = Intrinsic::getDeclaration(F->getParent(), Permil2ID);
478       return true;
479     }
480   }
481 
482   if (Name == "seh.recoverfp") {
483     NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_recoverfp);
484     return true;
485   }
486 
487   return false;
488 }
489 
490 static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
491   assert(F && "Illegal to upgrade a non-existent Function.");
492 
493   // Upgrade intrinsics "clang.arc.use" which doesn't start with "llvm.".
494   if (F->getName() == "clang.arc.use") {
495     NewFn = nullptr;
496     return true;
497   }
498 
499   // Quickly eliminate it, if it's not a candidate.
500   StringRef Name = F->getName();
501   if (Name.size() <= 8 || !Name.startswith("llvm."))
502     return false;
503   Name = Name.substr(5); // Strip off "llvm."
504 
505   switch (Name[0]) {
506   default: break;
507   case 'a': {
508     if (Name.startswith("arm.rbit") || Name.startswith("aarch64.rbit")) {
509       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::bitreverse,
510                                         F->arg_begin()->getType());
511       return true;
512     }
513     if (Name.startswith("arm.neon.vclz")) {
514       Type* args[2] = {
515         F->arg_begin()->getType(),
516         Type::getInt1Ty(F->getContext())
517       };
518       // Can't use Intrinsic::getDeclaration here as it adds a ".i1" to
519       // the end of the name. Change name from llvm.arm.neon.vclz.* to
520       //  llvm.ctlz.*
521       FunctionType* fType = FunctionType::get(F->getReturnType(), args, false);
522       NewFn = Function::Create(fType, F->getLinkage(), F->getAddressSpace(),
523                                "llvm.ctlz." + Name.substr(14), F->getParent());
524       return true;
525     }
526     if (Name.startswith("arm.neon.vcnt")) {
527       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop,
528                                         F->arg_begin()->getType());
529       return true;
530     }
531     Regex vldRegex("^arm\\.neon\\.vld([1234]|[234]lane)\\.v[a-z0-9]*$");
532     if (vldRegex.match(Name)) {
533       auto fArgs = F->getFunctionType()->params();
534       SmallVector<Type *, 4> Tys(fArgs.begin(), fArgs.end());
535       // Can't use Intrinsic::getDeclaration here as the return types might
536       // then only be structurally equal.
537       FunctionType* fType = FunctionType::get(F->getReturnType(), Tys, false);
538       NewFn = Function::Create(fType, F->getLinkage(), F->getAddressSpace(),
539                                "llvm." + Name + ".p0i8", F->getParent());
540       return true;
541     }
542     Regex vstRegex("^arm\\.neon\\.vst([1234]|[234]lane)\\.v[a-z0-9]*$");
543     if (vstRegex.match(Name)) {
544       static const Intrinsic::ID StoreInts[] = {Intrinsic::arm_neon_vst1,
545                                                 Intrinsic::arm_neon_vst2,
546                                                 Intrinsic::arm_neon_vst3,
547                                                 Intrinsic::arm_neon_vst4};
548 
549       static const Intrinsic::ID StoreLaneInts[] = {
550         Intrinsic::arm_neon_vst2lane, Intrinsic::arm_neon_vst3lane,
551         Intrinsic::arm_neon_vst4lane
552       };
553 
554       auto fArgs = F->getFunctionType()->params();
555       Type *Tys[] = {fArgs[0], fArgs[1]};
556       if (Name.find("lane") == StringRef::npos)
557         NewFn = Intrinsic::getDeclaration(F->getParent(),
558                                           StoreInts[fArgs.size() - 3], Tys);
559       else
560         NewFn = Intrinsic::getDeclaration(F->getParent(),
561                                           StoreLaneInts[fArgs.size() - 5], Tys);
562       return true;
563     }
564     if (Name == "aarch64.thread.pointer" || Name == "arm.thread.pointer") {
565       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::thread_pointer);
566       return true;
567     }
568     if (Name.startswith("aarch64.neon.addp")) {
569       if (F->arg_size() != 2)
570         break; // Invalid IR.
571       auto fArgs = F->getFunctionType()->params();
572       VectorType *ArgTy = dyn_cast<VectorType>(fArgs[0]);
573       if (ArgTy && ArgTy->getElementType()->isFloatingPointTy()) {
574         NewFn = Intrinsic::getDeclaration(F->getParent(),
575                                           Intrinsic::aarch64_neon_faddp, fArgs);
576         return true;
577       }
578     }
579     break;
580   }
581 
582   case 'c': {
583     if (Name.startswith("ctlz.") && F->arg_size() == 1) {
584       rename(F);
585       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
586                                         F->arg_begin()->getType());
587       return true;
588     }
589     if (Name.startswith("cttz.") && F->arg_size() == 1) {
590       rename(F);
591       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::cttz,
592                                         F->arg_begin()->getType());
593       return true;
594     }
595     break;
596   }
597   case 'd': {
598     if (Name == "dbg.value" && F->arg_size() == 4) {
599       rename(F);
600       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::dbg_value);
601       return true;
602     }
603     break;
604   }
605   case 'e': {
606     SmallVector<StringRef, 2> Groups;
607     Regex R("^experimental.vector.reduce.([a-z]+)\\.[fi][0-9]+");
608     if (R.match(Name, &Groups)) {
609       Intrinsic::ID ID = Intrinsic::not_intrinsic;
610       if (Groups[1] == "fadd")
611         ID = Intrinsic::experimental_vector_reduce_v2_fadd;
612       if (Groups[1] == "fmul")
613         ID = Intrinsic::experimental_vector_reduce_v2_fmul;
614 
615       if (ID != Intrinsic::not_intrinsic) {
616         rename(F);
617         auto Args = F->getFunctionType()->params();
618         Type *Tys[] = {F->getFunctionType()->getReturnType(), Args[1]};
619         NewFn = Intrinsic::getDeclaration(F->getParent(), ID, Tys);
620         return true;
621       }
622     }
623     break;
624   }
625   case 'i':
626   case 'l': {
627     bool IsLifetimeStart = Name.startswith("lifetime.start");
628     if (IsLifetimeStart || Name.startswith("invariant.start")) {
629       Intrinsic::ID ID = IsLifetimeStart ?
630         Intrinsic::lifetime_start : Intrinsic::invariant_start;
631       auto Args = F->getFunctionType()->params();
632       Type* ObjectPtr[1] = {Args[1]};
633       if (F->getName() != Intrinsic::getName(ID, ObjectPtr)) {
634         rename(F);
635         NewFn = Intrinsic::getDeclaration(F->getParent(), ID, ObjectPtr);
636         return true;
637       }
638     }
639 
640     bool IsLifetimeEnd = Name.startswith("lifetime.end");
641     if (IsLifetimeEnd || Name.startswith("invariant.end")) {
642       Intrinsic::ID ID = IsLifetimeEnd ?
643         Intrinsic::lifetime_end : Intrinsic::invariant_end;
644 
645       auto Args = F->getFunctionType()->params();
646       Type* ObjectPtr[1] = {Args[IsLifetimeEnd ? 1 : 2]};
647       if (F->getName() != Intrinsic::getName(ID, ObjectPtr)) {
648         rename(F);
649         NewFn = Intrinsic::getDeclaration(F->getParent(), ID, ObjectPtr);
650         return true;
651       }
652     }
653     if (Name.startswith("invariant.group.barrier")) {
654       // Rename invariant.group.barrier to launder.invariant.group
655       auto Args = F->getFunctionType()->params();
656       Type* ObjectPtr[1] = {Args[0]};
657       rename(F);
658       NewFn = Intrinsic::getDeclaration(F->getParent(),
659           Intrinsic::launder_invariant_group, ObjectPtr);
660       return true;
661 
662     }
663 
664     break;
665   }
666   case 'm': {
667     if (Name.startswith("masked.load.")) {
668       Type *Tys[] = { F->getReturnType(), F->arg_begin()->getType() };
669       if (F->getName() != Intrinsic::getName(Intrinsic::masked_load, Tys)) {
670         rename(F);
671         NewFn = Intrinsic::getDeclaration(F->getParent(),
672                                           Intrinsic::masked_load,
673                                           Tys);
674         return true;
675       }
676     }
677     if (Name.startswith("masked.store.")) {
678       auto Args = F->getFunctionType()->params();
679       Type *Tys[] = { Args[0], Args[1] };
680       if (F->getName() != Intrinsic::getName(Intrinsic::masked_store, Tys)) {
681         rename(F);
682         NewFn = Intrinsic::getDeclaration(F->getParent(),
683                                           Intrinsic::masked_store,
684                                           Tys);
685         return true;
686       }
687     }
688     // Renaming gather/scatter intrinsics with no address space overloading
689     // to the new overload which includes an address space
690     if (Name.startswith("masked.gather.")) {
691       Type *Tys[] = {F->getReturnType(), F->arg_begin()->getType()};
692       if (F->getName() != Intrinsic::getName(Intrinsic::masked_gather, Tys)) {
693         rename(F);
694         NewFn = Intrinsic::getDeclaration(F->getParent(),
695                                           Intrinsic::masked_gather, Tys);
696         return true;
697       }
698     }
699     if (Name.startswith("masked.scatter.")) {
700       auto Args = F->getFunctionType()->params();
701       Type *Tys[] = {Args[0], Args[1]};
702       if (F->getName() != Intrinsic::getName(Intrinsic::masked_scatter, Tys)) {
703         rename(F);
704         NewFn = Intrinsic::getDeclaration(F->getParent(),
705                                           Intrinsic::masked_scatter, Tys);
706         return true;
707       }
708     }
709     // Updating the memory intrinsics (memcpy/memmove/memset) that have an
710     // alignment parameter to embedding the alignment as an attribute of
711     // the pointer args.
712     if (Name.startswith("memcpy.") && F->arg_size() == 5) {
713       rename(F);
714       // Get the types of dest, src, and len
715       ArrayRef<Type *> ParamTypes = F->getFunctionType()->params().slice(0, 3);
716       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memcpy,
717                                         ParamTypes);
718       return true;
719     }
720     if (Name.startswith("memmove.") && F->arg_size() == 5) {
721       rename(F);
722       // Get the types of dest, src, and len
723       ArrayRef<Type *> ParamTypes = F->getFunctionType()->params().slice(0, 3);
724       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memmove,
725                                         ParamTypes);
726       return true;
727     }
728     if (Name.startswith("memset.") && F->arg_size() == 5) {
729       rename(F);
730       // Get the types of dest, and len
731       const auto *FT = F->getFunctionType();
732       Type *ParamTypes[2] = {
733           FT->getParamType(0), // Dest
734           FT->getParamType(2)  // len
735       };
736       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memset,
737                                         ParamTypes);
738       return true;
739     }
740     break;
741   }
742   case 'n': {
743     if (Name.startswith("nvvm.")) {
744       Name = Name.substr(5);
745 
746       // The following nvvm intrinsics correspond exactly to an LLVM intrinsic.
747       Intrinsic::ID IID = StringSwitch<Intrinsic::ID>(Name)
748                               .Cases("brev32", "brev64", Intrinsic::bitreverse)
749                               .Case("clz.i", Intrinsic::ctlz)
750                               .Case("popc.i", Intrinsic::ctpop)
751                               .Default(Intrinsic::not_intrinsic);
752       if (IID != Intrinsic::not_intrinsic && F->arg_size() == 1) {
753         NewFn = Intrinsic::getDeclaration(F->getParent(), IID,
754                                           {F->getReturnType()});
755         return true;
756       }
757 
758       // The following nvvm intrinsics correspond exactly to an LLVM idiom, but
759       // not to an intrinsic alone.  We expand them in UpgradeIntrinsicCall.
760       //
761       // TODO: We could add lohi.i2d.
762       bool Expand = StringSwitch<bool>(Name)
763                         .Cases("abs.i", "abs.ll", true)
764                         .Cases("clz.ll", "popc.ll", "h2f", true)
765                         .Cases("max.i", "max.ll", "max.ui", "max.ull", true)
766                         .Cases("min.i", "min.ll", "min.ui", "min.ull", true)
767                         .StartsWith("atomic.load.add.f32.p", true)
768                         .StartsWith("atomic.load.add.f64.p", true)
769                         .Default(false);
770       if (Expand) {
771         NewFn = nullptr;
772         return true;
773       }
774     }
775     break;
776   }
777   case 'o':
778     // We only need to change the name to match the mangling including the
779     // address space.
780     if (Name.startswith("objectsize.")) {
781       Type *Tys[2] = { F->getReturnType(), F->arg_begin()->getType() };
782       if (F->arg_size() == 2 || F->arg_size() == 3 ||
783           F->getName() != Intrinsic::getName(Intrinsic::objectsize, Tys)) {
784         rename(F);
785         NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::objectsize,
786                                           Tys);
787         return true;
788       }
789     }
790     break;
791 
792   case 'p':
793     if (Name == "prefetch") {
794       // Handle address space overloading.
795       Type *Tys[] = {F->arg_begin()->getType()};
796       if (F->getName() != Intrinsic::getName(Intrinsic::prefetch, Tys)) {
797         rename(F);
798         NewFn =
799             Intrinsic::getDeclaration(F->getParent(), Intrinsic::prefetch, Tys);
800         return true;
801       }
802     }
803     break;
804 
805   case 's':
806     if (Name == "stackprotectorcheck") {
807       NewFn = nullptr;
808       return true;
809     }
810     break;
811 
812   case 'x':
813     if (UpgradeX86IntrinsicFunction(F, Name, NewFn))
814       return true;
815   }
816   // Remangle our intrinsic since we upgrade the mangling
817   auto Result = llvm::Intrinsic::remangleIntrinsicFunction(F);
818   if (Result != None) {
819     NewFn = Result.getValue();
820     return true;
821   }
822 
823   //  This may not belong here. This function is effectively being overloaded
824   //  to both detect an intrinsic which needs upgrading, and to provide the
825   //  upgraded form of the intrinsic. We should perhaps have two separate
826   //  functions for this.
827   return false;
828 }
829 
830 bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
831   NewFn = nullptr;
832   bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);
833   assert(F != NewFn && "Intrinsic function upgraded to the same function");
834 
835   // Upgrade intrinsic attributes.  This does not change the function.
836   if (NewFn)
837     F = NewFn;
838   if (Intrinsic::ID id = F->getIntrinsicID())
839     F->setAttributes(Intrinsic::getAttributes(F->getContext(), id));
840   return Upgraded;
841 }
842 
843 GlobalVariable *llvm::UpgradeGlobalVariable(GlobalVariable *GV) {
844   if (!(GV->hasName() && (GV->getName() == "llvm.global_ctors" ||
845                           GV->getName() == "llvm.global_dtors")) ||
846       !GV->hasInitializer())
847     return nullptr;
848   ArrayType *ATy = dyn_cast<ArrayType>(GV->getValueType());
849   if (!ATy)
850     return nullptr;
851   StructType *STy = dyn_cast<StructType>(ATy->getElementType());
852   if (!STy || STy->getNumElements() != 2)
853     return nullptr;
854 
855   LLVMContext &C = GV->getContext();
856   IRBuilder<> IRB(C);
857   auto EltTy = StructType::get(STy->getElementType(0), STy->getElementType(1),
858                                IRB.getInt8PtrTy());
859   Constant *Init = GV->getInitializer();
860   unsigned N = Init->getNumOperands();
861   std::vector<Constant *> NewCtors(N);
862   for (unsigned i = 0; i != N; ++i) {
863     auto Ctor = cast<Constant>(Init->getOperand(i));
864     NewCtors[i] = ConstantStruct::get(
865         EltTy, Ctor->getAggregateElement(0u), Ctor->getAggregateElement(1),
866         Constant::getNullValue(IRB.getInt8PtrTy()));
867   }
868   Constant *NewInit = ConstantArray::get(ArrayType::get(EltTy, N), NewCtors);
869 
870   return new GlobalVariable(NewInit->getType(), false, GV->getLinkage(),
871                             NewInit, GV->getName());
872 }
873 
874 // Handles upgrading SSE2/AVX2/AVX512BW PSLLDQ intrinsics by converting them
875 // to byte shuffles.
876 static Value *UpgradeX86PSLLDQIntrinsics(IRBuilder<> &Builder,
877                                          Value *Op, unsigned Shift) {
878   Type *ResultTy = Op->getType();
879   unsigned NumElts = ResultTy->getVectorNumElements() * 8;
880 
881   // Bitcast from a 64-bit element type to a byte element type.
882   Type *VecTy = VectorType::get(Builder.getInt8Ty(), NumElts);
883   Op = Builder.CreateBitCast(Op, VecTy, "cast");
884 
885   // We'll be shuffling in zeroes.
886   Value *Res = Constant::getNullValue(VecTy);
887 
888   // If shift is less than 16, emit a shuffle to move the bytes. Otherwise,
889   // we'll just return the zero vector.
890   if (Shift < 16) {
891     uint32_t Idxs[64];
892     // 256/512-bit version is split into 2/4 16-byte lanes.
893     for (unsigned l = 0; l != NumElts; l += 16)
894       for (unsigned i = 0; i != 16; ++i) {
895         unsigned Idx = NumElts + i - Shift;
896         if (Idx < NumElts)
897           Idx -= NumElts - 16; // end of lane, switch operand.
898         Idxs[l + i] = Idx + l;
899       }
900 
901     Res = Builder.CreateShuffleVector(Res, Op, makeArrayRef(Idxs, NumElts));
902   }
903 
904   // Bitcast back to a 64-bit element type.
905   return Builder.CreateBitCast(Res, ResultTy, "cast");
906 }
907 
908 // Handles upgrading SSE2/AVX2/AVX512BW PSRLDQ intrinsics by converting them
909 // to byte shuffles.
910 static Value *UpgradeX86PSRLDQIntrinsics(IRBuilder<> &Builder, Value *Op,
911                                          unsigned Shift) {
912   Type *ResultTy = Op->getType();
913   unsigned NumElts = ResultTy->getVectorNumElements() * 8;
914 
915   // Bitcast from a 64-bit element type to a byte element type.
916   Type *VecTy = VectorType::get(Builder.getInt8Ty(), NumElts);
917   Op = Builder.CreateBitCast(Op, VecTy, "cast");
918 
919   // We'll be shuffling in zeroes.
920   Value *Res = Constant::getNullValue(VecTy);
921 
922   // If shift is less than 16, emit a shuffle to move the bytes. Otherwise,
923   // we'll just return the zero vector.
924   if (Shift < 16) {
925     uint32_t Idxs[64];
926     // 256/512-bit version is split into 2/4 16-byte lanes.
927     for (unsigned l = 0; l != NumElts; l += 16)
928       for (unsigned i = 0; i != 16; ++i) {
929         unsigned Idx = i + Shift;
930         if (Idx >= 16)
931           Idx += NumElts - 16; // end of lane, switch operand.
932         Idxs[l + i] = Idx + l;
933       }
934 
935     Res = Builder.CreateShuffleVector(Op, Res, makeArrayRef(Idxs, NumElts));
936   }
937 
938   // Bitcast back to a 64-bit element type.
939   return Builder.CreateBitCast(Res, ResultTy, "cast");
940 }
941 
942 static Value *getX86MaskVec(IRBuilder<> &Builder, Value *Mask,
943                             unsigned NumElts) {
944   llvm::VectorType *MaskTy = llvm::VectorType::get(Builder.getInt1Ty(),
945                              cast<IntegerType>(Mask->getType())->getBitWidth());
946   Mask = Builder.CreateBitCast(Mask, MaskTy);
947 
948   // If we have less than 8 elements, then the starting mask was an i8 and
949   // we need to extract down to the right number of elements.
950   if (NumElts < 8) {
951     uint32_t Indices[4];
952     for (unsigned i = 0; i != NumElts; ++i)
953       Indices[i] = i;
954     Mask = Builder.CreateShuffleVector(Mask, Mask,
955                                        makeArrayRef(Indices, NumElts),
956                                        "extract");
957   }
958 
959   return Mask;
960 }
961 
962 static Value *EmitX86Select(IRBuilder<> &Builder, Value *Mask,
963                             Value *Op0, Value *Op1) {
964   // If the mask is all ones just emit the first operation.
965   if (const auto *C = dyn_cast<Constant>(Mask))
966     if (C->isAllOnesValue())
967       return Op0;
968 
969   Mask = getX86MaskVec(Builder, Mask, Op0->getType()->getVectorNumElements());
970   return Builder.CreateSelect(Mask, Op0, Op1);
971 }
972 
973 static Value *EmitX86ScalarSelect(IRBuilder<> &Builder, Value *Mask,
974                                   Value *Op0, Value *Op1) {
975   // If the mask is all ones just emit the first operation.
976   if (const auto *C = dyn_cast<Constant>(Mask))
977     if (C->isAllOnesValue())
978       return Op0;
979 
980   llvm::VectorType *MaskTy =
981     llvm::VectorType::get(Builder.getInt1Ty(),
982                           Mask->getType()->getIntegerBitWidth());
983   Mask = Builder.CreateBitCast(Mask, MaskTy);
984   Mask = Builder.CreateExtractElement(Mask, (uint64_t)0);
985   return Builder.CreateSelect(Mask, Op0, Op1);
986 }
987 
988 // Handle autoupgrade for masked PALIGNR and VALIGND/Q intrinsics.
989 // PALIGNR handles large immediates by shifting while VALIGN masks the immediate
990 // so we need to handle both cases. VALIGN also doesn't have 128-bit lanes.
991 static Value *UpgradeX86ALIGNIntrinsics(IRBuilder<> &Builder, Value *Op0,
992                                         Value *Op1, Value *Shift,
993                                         Value *Passthru, Value *Mask,
994                                         bool IsVALIGN) {
995   unsigned ShiftVal = cast<llvm::ConstantInt>(Shift)->getZExtValue();
996 
997   unsigned NumElts = Op0->getType()->getVectorNumElements();
998   assert((IsVALIGN || NumElts % 16 == 0) && "Illegal NumElts for PALIGNR!");
999   assert((!IsVALIGN || NumElts <= 16) && "NumElts too large for VALIGN!");
1000   assert(isPowerOf2_32(NumElts) && "NumElts not a power of 2!");
1001 
1002   // Mask the immediate for VALIGN.
1003   if (IsVALIGN)
1004     ShiftVal &= (NumElts - 1);
1005 
1006   // If palignr is shifting the pair of vectors more than the size of two
1007   // lanes, emit zero.
1008   if (ShiftVal >= 32)
1009     return llvm::Constant::getNullValue(Op0->getType());
1010 
1011   // If palignr is shifting the pair of input vectors more than one lane,
1012   // but less than two lanes, convert to shifting in zeroes.
1013   if (ShiftVal > 16) {
1014     ShiftVal -= 16;
1015     Op1 = Op0;
1016     Op0 = llvm::Constant::getNullValue(Op0->getType());
1017   }
1018 
1019   uint32_t Indices[64];
1020   // 256-bit palignr operates on 128-bit lanes so we need to handle that
1021   for (unsigned l = 0; l < NumElts; l += 16) {
1022     for (unsigned i = 0; i != 16; ++i) {
1023       unsigned Idx = ShiftVal + i;
1024       if (!IsVALIGN && Idx >= 16) // Disable wrap for VALIGN.
1025         Idx += NumElts - 16; // End of lane, switch operand.
1026       Indices[l + i] = Idx + l;
1027     }
1028   }
1029 
1030   Value *Align = Builder.CreateShuffleVector(Op1, Op0,
1031                                              makeArrayRef(Indices, NumElts),
1032                                              "palignr");
1033 
1034   return EmitX86Select(Builder, Mask, Align, Passthru);
1035 }
1036 
1037 static Value *UpgradeX86VPERMT2Intrinsics(IRBuilder<> &Builder, CallInst &CI,
1038                                           bool ZeroMask, bool IndexForm) {
1039   Type *Ty = CI.getType();
1040   unsigned VecWidth = Ty->getPrimitiveSizeInBits();
1041   unsigned EltWidth = Ty->getScalarSizeInBits();
1042   bool IsFloat = Ty->isFPOrFPVectorTy();
1043   Intrinsic::ID IID;
1044   if (VecWidth == 128 && EltWidth == 32 && IsFloat)
1045     IID = Intrinsic::x86_avx512_vpermi2var_ps_128;
1046   else if (VecWidth == 128 && EltWidth == 32 && !IsFloat)
1047     IID = Intrinsic::x86_avx512_vpermi2var_d_128;
1048   else if (VecWidth == 128 && EltWidth == 64 && IsFloat)
1049     IID = Intrinsic::x86_avx512_vpermi2var_pd_128;
1050   else if (VecWidth == 128 && EltWidth == 64 && !IsFloat)
1051     IID = Intrinsic::x86_avx512_vpermi2var_q_128;
1052   else if (VecWidth == 256 && EltWidth == 32 && IsFloat)
1053     IID = Intrinsic::x86_avx512_vpermi2var_ps_256;
1054   else if (VecWidth == 256 && EltWidth == 32 && !IsFloat)
1055     IID = Intrinsic::x86_avx512_vpermi2var_d_256;
1056   else if (VecWidth == 256 && EltWidth == 64 && IsFloat)
1057     IID = Intrinsic::x86_avx512_vpermi2var_pd_256;
1058   else if (VecWidth == 256 && EltWidth == 64 && !IsFloat)
1059     IID = Intrinsic::x86_avx512_vpermi2var_q_256;
1060   else if (VecWidth == 512 && EltWidth == 32 && IsFloat)
1061     IID = Intrinsic::x86_avx512_vpermi2var_ps_512;
1062   else if (VecWidth == 512 && EltWidth == 32 && !IsFloat)
1063     IID = Intrinsic::x86_avx512_vpermi2var_d_512;
1064   else if (VecWidth == 512 && EltWidth == 64 && IsFloat)
1065     IID = Intrinsic::x86_avx512_vpermi2var_pd_512;
1066   else if (VecWidth == 512 && EltWidth == 64 && !IsFloat)
1067     IID = Intrinsic::x86_avx512_vpermi2var_q_512;
1068   else if (VecWidth == 128 && EltWidth == 16)
1069     IID = Intrinsic::x86_avx512_vpermi2var_hi_128;
1070   else if (VecWidth == 256 && EltWidth == 16)
1071     IID = Intrinsic::x86_avx512_vpermi2var_hi_256;
1072   else if (VecWidth == 512 && EltWidth == 16)
1073     IID = Intrinsic::x86_avx512_vpermi2var_hi_512;
1074   else if (VecWidth == 128 && EltWidth == 8)
1075     IID = Intrinsic::x86_avx512_vpermi2var_qi_128;
1076   else if (VecWidth == 256 && EltWidth == 8)
1077     IID = Intrinsic::x86_avx512_vpermi2var_qi_256;
1078   else if (VecWidth == 512 && EltWidth == 8)
1079     IID = Intrinsic::x86_avx512_vpermi2var_qi_512;
1080   else
1081     llvm_unreachable("Unexpected intrinsic");
1082 
1083   Value *Args[] = { CI.getArgOperand(0) , CI.getArgOperand(1),
1084                     CI.getArgOperand(2) };
1085 
1086   // If this isn't index form we need to swap operand 0 and 1.
1087   if (!IndexForm)
1088     std::swap(Args[0], Args[1]);
1089 
1090   Value *V = Builder.CreateCall(Intrinsic::getDeclaration(CI.getModule(), IID),
1091                                 Args);
1092   Value *PassThru = ZeroMask ? ConstantAggregateZero::get(Ty)
1093                              : Builder.CreateBitCast(CI.getArgOperand(1),
1094                                                      Ty);
1095   return EmitX86Select(Builder, CI.getArgOperand(3), V, PassThru);
1096 }
1097 
1098 static Value *UpgradeX86AddSubSatIntrinsics(IRBuilder<> &Builder, CallInst &CI,
1099                                             bool IsSigned, bool IsAddition) {
1100   Type *Ty = CI.getType();
1101   Value *Op0 = CI.getOperand(0);
1102   Value *Op1 = CI.getOperand(1);
1103 
1104   Intrinsic::ID IID =
1105       IsSigned ? (IsAddition ? Intrinsic::sadd_sat : Intrinsic::ssub_sat)
1106                : (IsAddition ? Intrinsic::uadd_sat : Intrinsic::usub_sat);
1107   Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID, Ty);
1108   Value *Res = Builder.CreateCall(Intrin, {Op0, Op1});
1109 
1110   if (CI.getNumArgOperands() == 4) { // For masked intrinsics.
1111     Value *VecSrc = CI.getOperand(2);
1112     Value *Mask = CI.getOperand(3);
1113     Res = EmitX86Select(Builder, Mask, Res, VecSrc);
1114   }
1115   return Res;
1116 }
1117 
1118 static Value *upgradeX86Rotate(IRBuilder<> &Builder, CallInst &CI,
1119                                bool IsRotateRight) {
1120   Type *Ty = CI.getType();
1121   Value *Src = CI.getArgOperand(0);
1122   Value *Amt = CI.getArgOperand(1);
1123 
1124   // Amount may be scalar immediate, in which case create a splat vector.
1125   // Funnel shifts amounts are treated as modulo and types are all power-of-2 so
1126   // we only care about the lowest log2 bits anyway.
1127   if (Amt->getType() != Ty) {
1128     unsigned NumElts = Ty->getVectorNumElements();
1129     Amt = Builder.CreateIntCast(Amt, Ty->getScalarType(), false);
1130     Amt = Builder.CreateVectorSplat(NumElts, Amt);
1131   }
1132 
1133   Intrinsic::ID IID = IsRotateRight ? Intrinsic::fshr : Intrinsic::fshl;
1134   Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID, Ty);
1135   Value *Res = Builder.CreateCall(Intrin, {Src, Src, Amt});
1136 
1137   if (CI.getNumArgOperands() == 4) { // For masked intrinsics.
1138     Value *VecSrc = CI.getOperand(2);
1139     Value *Mask = CI.getOperand(3);
1140     Res = EmitX86Select(Builder, Mask, Res, VecSrc);
1141   }
1142   return Res;
1143 }
1144 
1145 static Value *upgradeX86vpcom(IRBuilder<> &Builder, CallInst &CI, unsigned Imm,
1146                               bool IsSigned) {
1147   Type *Ty = CI.getType();
1148   Value *LHS = CI.getArgOperand(0);
1149   Value *RHS = CI.getArgOperand(1);
1150 
1151   CmpInst::Predicate Pred;
1152   switch (Imm) {
1153   case 0x0:
1154     Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1155     break;
1156   case 0x1:
1157     Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1158     break;
1159   case 0x2:
1160     Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1161     break;
1162   case 0x3:
1163     Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1164     break;
1165   case 0x4:
1166     Pred = ICmpInst::ICMP_EQ;
1167     break;
1168   case 0x5:
1169     Pred = ICmpInst::ICMP_NE;
1170     break;
1171   case 0x6:
1172     return Constant::getNullValue(Ty); // FALSE
1173   case 0x7:
1174     return Constant::getAllOnesValue(Ty); // TRUE
1175   default:
1176     llvm_unreachable("Unknown XOP vpcom/vpcomu predicate");
1177   }
1178 
1179   Value *Cmp = Builder.CreateICmp(Pred, LHS, RHS);
1180   Value *Ext = Builder.CreateSExt(Cmp, Ty);
1181   return Ext;
1182 }
1183 
1184 static Value *upgradeX86ConcatShift(IRBuilder<> &Builder, CallInst &CI,
1185                                     bool IsShiftRight, bool ZeroMask) {
1186   Type *Ty = CI.getType();
1187   Value *Op0 = CI.getArgOperand(0);
1188   Value *Op1 = CI.getArgOperand(1);
1189   Value *Amt = CI.getArgOperand(2);
1190 
1191   if (IsShiftRight)
1192     std::swap(Op0, Op1);
1193 
1194   // Amount may be scalar immediate, in which case create a splat vector.
1195   // Funnel shifts amounts are treated as modulo and types are all power-of-2 so
1196   // we only care about the lowest log2 bits anyway.
1197   if (Amt->getType() != Ty) {
1198     unsigned NumElts = Ty->getVectorNumElements();
1199     Amt = Builder.CreateIntCast(Amt, Ty->getScalarType(), false);
1200     Amt = Builder.CreateVectorSplat(NumElts, Amt);
1201   }
1202 
1203   Intrinsic::ID IID = IsShiftRight ? Intrinsic::fshr : Intrinsic::fshl;
1204   Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID, Ty);
1205   Value *Res = Builder.CreateCall(Intrin, {Op0, Op1, Amt});
1206 
1207   unsigned NumArgs = CI.getNumArgOperands();
1208   if (NumArgs >= 4) { // For masked intrinsics.
1209     Value *VecSrc = NumArgs == 5 ? CI.getArgOperand(3) :
1210                     ZeroMask     ? ConstantAggregateZero::get(CI.getType()) :
1211                                    CI.getArgOperand(0);
1212     Value *Mask = CI.getOperand(NumArgs - 1);
1213     Res = EmitX86Select(Builder, Mask, Res, VecSrc);
1214   }
1215   return Res;
1216 }
1217 
1218 static Value *UpgradeMaskedStore(IRBuilder<> &Builder,
1219                                  Value *Ptr, Value *Data, Value *Mask,
1220                                  bool Aligned) {
1221   // Cast the pointer to the right type.
1222   Ptr = Builder.CreateBitCast(Ptr,
1223                               llvm::PointerType::getUnqual(Data->getType()));
1224   unsigned Align =
1225     Aligned ? cast<VectorType>(Data->getType())->getBitWidth() / 8 : 1;
1226 
1227   // If the mask is all ones just emit a regular store.
1228   if (const auto *C = dyn_cast<Constant>(Mask))
1229     if (C->isAllOnesValue())
1230       return Builder.CreateAlignedStore(Data, Ptr, Align);
1231 
1232   // Convert the mask from an integer type to a vector of i1.
1233   unsigned NumElts = Data->getType()->getVectorNumElements();
1234   Mask = getX86MaskVec(Builder, Mask, NumElts);
1235   return Builder.CreateMaskedStore(Data, Ptr, Align, Mask);
1236 }
1237 
1238 static Value *UpgradeMaskedLoad(IRBuilder<> &Builder,
1239                                 Value *Ptr, Value *Passthru, Value *Mask,
1240                                 bool Aligned) {
1241   Type *ValTy = Passthru->getType();
1242   // Cast the pointer to the right type.
1243   Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(ValTy));
1244   unsigned Align =
1245     Aligned ? cast<VectorType>(Passthru->getType())->getBitWidth() / 8 : 1;
1246 
1247   // If the mask is all ones just emit a regular store.
1248   if (const auto *C = dyn_cast<Constant>(Mask))
1249     if (C->isAllOnesValue())
1250       return Builder.CreateAlignedLoad(ValTy, Ptr, Align);
1251 
1252   // Convert the mask from an integer type to a vector of i1.
1253   unsigned NumElts = Passthru->getType()->getVectorNumElements();
1254   Mask = getX86MaskVec(Builder, Mask, NumElts);
1255   return Builder.CreateMaskedLoad(Ptr, Align, Mask, Passthru);
1256 }
1257 
1258 static Value *upgradeAbs(IRBuilder<> &Builder, CallInst &CI) {
1259   Value *Op0 = CI.getArgOperand(0);
1260   llvm::Type *Ty = Op0->getType();
1261   Value *Zero = llvm::Constant::getNullValue(Ty);
1262   Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_SGT, Op0, Zero);
1263   Value *Neg = Builder.CreateNeg(Op0);
1264   Value *Res = Builder.CreateSelect(Cmp, Op0, Neg);
1265 
1266   if (CI.getNumArgOperands() == 3)
1267     Res = EmitX86Select(Builder,CI.getArgOperand(2), Res, CI.getArgOperand(1));
1268 
1269   return Res;
1270 }
1271 
1272 static Value *upgradeIntMinMax(IRBuilder<> &Builder, CallInst &CI,
1273                                ICmpInst::Predicate Pred) {
1274   Value *Op0 = CI.getArgOperand(0);
1275   Value *Op1 = CI.getArgOperand(1);
1276   Value *Cmp = Builder.CreateICmp(Pred, Op0, Op1);
1277   Value *Res = Builder.CreateSelect(Cmp, Op0, Op1);
1278 
1279   if (CI.getNumArgOperands() == 4)
1280     Res = EmitX86Select(Builder, CI.getArgOperand(3), Res, CI.getArgOperand(2));
1281 
1282   return Res;
1283 }
1284 
1285 static Value *upgradePMULDQ(IRBuilder<> &Builder, CallInst &CI, bool IsSigned) {
1286   Type *Ty = CI.getType();
1287 
1288   // Arguments have a vXi32 type so cast to vXi64.
1289   Value *LHS = Builder.CreateBitCast(CI.getArgOperand(0), Ty);
1290   Value *RHS = Builder.CreateBitCast(CI.getArgOperand(1), Ty);
1291 
1292   if (IsSigned) {
1293     // Shift left then arithmetic shift right.
1294     Constant *ShiftAmt = ConstantInt::get(Ty, 32);
1295     LHS = Builder.CreateShl(LHS, ShiftAmt);
1296     LHS = Builder.CreateAShr(LHS, ShiftAmt);
1297     RHS = Builder.CreateShl(RHS, ShiftAmt);
1298     RHS = Builder.CreateAShr(RHS, ShiftAmt);
1299   } else {
1300     // Clear the upper bits.
1301     Constant *Mask = ConstantInt::get(Ty, 0xffffffff);
1302     LHS = Builder.CreateAnd(LHS, Mask);
1303     RHS = Builder.CreateAnd(RHS, Mask);
1304   }
1305 
1306   Value *Res = Builder.CreateMul(LHS, RHS);
1307 
1308   if (CI.getNumArgOperands() == 4)
1309     Res = EmitX86Select(Builder, CI.getArgOperand(3), Res, CI.getArgOperand(2));
1310 
1311   return Res;
1312 }
1313 
1314 // Applying mask on vector of i1's and make sure result is at least 8 bits wide.
1315 static Value *ApplyX86MaskOn1BitsVec(IRBuilder<> &Builder, Value *Vec,
1316                                      Value *Mask) {
1317   unsigned NumElts = Vec->getType()->getVectorNumElements();
1318   if (Mask) {
1319     const auto *C = dyn_cast<Constant>(Mask);
1320     if (!C || !C->isAllOnesValue())
1321       Vec = Builder.CreateAnd(Vec, getX86MaskVec(Builder, Mask, NumElts));
1322   }
1323 
1324   if (NumElts < 8) {
1325     uint32_t Indices[8];
1326     for (unsigned i = 0; i != NumElts; ++i)
1327       Indices[i] = i;
1328     for (unsigned i = NumElts; i != 8; ++i)
1329       Indices[i] = NumElts + i % NumElts;
1330     Vec = Builder.CreateShuffleVector(Vec,
1331                                       Constant::getNullValue(Vec->getType()),
1332                                       Indices);
1333   }
1334   return Builder.CreateBitCast(Vec, Builder.getIntNTy(std::max(NumElts, 8U)));
1335 }
1336 
1337 static Value *upgradeMaskedCompare(IRBuilder<> &Builder, CallInst &CI,
1338                                    unsigned CC, bool Signed) {
1339   Value *Op0 = CI.getArgOperand(0);
1340   unsigned NumElts = Op0->getType()->getVectorNumElements();
1341 
1342   Value *Cmp;
1343   if (CC == 3) {
1344     Cmp = Constant::getNullValue(llvm::VectorType::get(Builder.getInt1Ty(), NumElts));
1345   } else if (CC == 7) {
1346     Cmp = Constant::getAllOnesValue(llvm::VectorType::get(Builder.getInt1Ty(), NumElts));
1347   } else {
1348     ICmpInst::Predicate Pred;
1349     switch (CC) {
1350     default: llvm_unreachable("Unknown condition code");
1351     case 0: Pred = ICmpInst::ICMP_EQ;  break;
1352     case 1: Pred = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; break;
1353     case 2: Pred = Signed ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; break;
1354     case 4: Pred = ICmpInst::ICMP_NE;  break;
1355     case 5: Pred = Signed ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; break;
1356     case 6: Pred = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; break;
1357     }
1358     Cmp = Builder.CreateICmp(Pred, Op0, CI.getArgOperand(1));
1359   }
1360 
1361   Value *Mask = CI.getArgOperand(CI.getNumArgOperands() - 1);
1362 
1363   return ApplyX86MaskOn1BitsVec(Builder, Cmp, Mask);
1364 }
1365 
1366 // Replace a masked intrinsic with an older unmasked intrinsic.
1367 static Value *UpgradeX86MaskedShift(IRBuilder<> &Builder, CallInst &CI,
1368                                     Intrinsic::ID IID) {
1369   Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID);
1370   Value *Rep = Builder.CreateCall(Intrin,
1371                                  { CI.getArgOperand(0), CI.getArgOperand(1) });
1372   return EmitX86Select(Builder, CI.getArgOperand(3), Rep, CI.getArgOperand(2));
1373 }
1374 
1375 static Value* upgradeMaskedMove(IRBuilder<> &Builder, CallInst &CI) {
1376   Value* A = CI.getArgOperand(0);
1377   Value* B = CI.getArgOperand(1);
1378   Value* Src = CI.getArgOperand(2);
1379   Value* Mask = CI.getArgOperand(3);
1380 
1381   Value* AndNode = Builder.CreateAnd(Mask, APInt(8, 1));
1382   Value* Cmp = Builder.CreateIsNotNull(AndNode);
1383   Value* Extract1 = Builder.CreateExtractElement(B, (uint64_t)0);
1384   Value* Extract2 = Builder.CreateExtractElement(Src, (uint64_t)0);
1385   Value* Select = Builder.CreateSelect(Cmp, Extract1, Extract2);
1386   return Builder.CreateInsertElement(A, Select, (uint64_t)0);
1387 }
1388 
1389 
1390 static Value* UpgradeMaskToInt(IRBuilder<> &Builder, CallInst &CI) {
1391   Value* Op = CI.getArgOperand(0);
1392   Type* ReturnOp = CI.getType();
1393   unsigned NumElts = CI.getType()->getVectorNumElements();
1394   Value *Mask = getX86MaskVec(Builder, Op, NumElts);
1395   return Builder.CreateSExt(Mask, ReturnOp, "vpmovm2");
1396 }
1397 
1398 // Replace intrinsic with unmasked version and a select.
1399 static bool upgradeAVX512MaskToSelect(StringRef Name, IRBuilder<> &Builder,
1400                                       CallInst &CI, Value *&Rep) {
1401   Name = Name.substr(12); // Remove avx512.mask.
1402 
1403   unsigned VecWidth = CI.getType()->getPrimitiveSizeInBits();
1404   unsigned EltWidth = CI.getType()->getScalarSizeInBits();
1405   Intrinsic::ID IID;
1406   if (Name.startswith("max.p")) {
1407     if (VecWidth == 128 && EltWidth == 32)
1408       IID = Intrinsic::x86_sse_max_ps;
1409     else if (VecWidth == 128 && EltWidth == 64)
1410       IID = Intrinsic::x86_sse2_max_pd;
1411     else if (VecWidth == 256 && EltWidth == 32)
1412       IID = Intrinsic::x86_avx_max_ps_256;
1413     else if (VecWidth == 256 && EltWidth == 64)
1414       IID = Intrinsic::x86_avx_max_pd_256;
1415     else
1416       llvm_unreachable("Unexpected intrinsic");
1417   } else if (Name.startswith("min.p")) {
1418     if (VecWidth == 128 && EltWidth == 32)
1419       IID = Intrinsic::x86_sse_min_ps;
1420     else if (VecWidth == 128 && EltWidth == 64)
1421       IID = Intrinsic::x86_sse2_min_pd;
1422     else if (VecWidth == 256 && EltWidth == 32)
1423       IID = Intrinsic::x86_avx_min_ps_256;
1424     else if (VecWidth == 256 && EltWidth == 64)
1425       IID = Intrinsic::x86_avx_min_pd_256;
1426     else
1427       llvm_unreachable("Unexpected intrinsic");
1428   } else if (Name.startswith("pshuf.b.")) {
1429     if (VecWidth == 128)
1430       IID = Intrinsic::x86_ssse3_pshuf_b_128;
1431     else if (VecWidth == 256)
1432       IID = Intrinsic::x86_avx2_pshuf_b;
1433     else if (VecWidth == 512)
1434       IID = Intrinsic::x86_avx512_pshuf_b_512;
1435     else
1436       llvm_unreachable("Unexpected intrinsic");
1437   } else if (Name.startswith("pmul.hr.sw.")) {
1438     if (VecWidth == 128)
1439       IID = Intrinsic::x86_ssse3_pmul_hr_sw_128;
1440     else if (VecWidth == 256)
1441       IID = Intrinsic::x86_avx2_pmul_hr_sw;
1442     else if (VecWidth == 512)
1443       IID = Intrinsic::x86_avx512_pmul_hr_sw_512;
1444     else
1445       llvm_unreachable("Unexpected intrinsic");
1446   } else if (Name.startswith("pmulh.w.")) {
1447     if (VecWidth == 128)
1448       IID = Intrinsic::x86_sse2_pmulh_w;
1449     else if (VecWidth == 256)
1450       IID = Intrinsic::x86_avx2_pmulh_w;
1451     else if (VecWidth == 512)
1452       IID = Intrinsic::x86_avx512_pmulh_w_512;
1453     else
1454       llvm_unreachable("Unexpected intrinsic");
1455   } else if (Name.startswith("pmulhu.w.")) {
1456     if (VecWidth == 128)
1457       IID = Intrinsic::x86_sse2_pmulhu_w;
1458     else if (VecWidth == 256)
1459       IID = Intrinsic::x86_avx2_pmulhu_w;
1460     else if (VecWidth == 512)
1461       IID = Intrinsic::x86_avx512_pmulhu_w_512;
1462     else
1463       llvm_unreachable("Unexpected intrinsic");
1464   } else if (Name.startswith("pmaddw.d.")) {
1465     if (VecWidth == 128)
1466       IID = Intrinsic::x86_sse2_pmadd_wd;
1467     else if (VecWidth == 256)
1468       IID = Intrinsic::x86_avx2_pmadd_wd;
1469     else if (VecWidth == 512)
1470       IID = Intrinsic::x86_avx512_pmaddw_d_512;
1471     else
1472       llvm_unreachable("Unexpected intrinsic");
1473   } else if (Name.startswith("pmaddubs.w.")) {
1474     if (VecWidth == 128)
1475       IID = Intrinsic::x86_ssse3_pmadd_ub_sw_128;
1476     else if (VecWidth == 256)
1477       IID = Intrinsic::x86_avx2_pmadd_ub_sw;
1478     else if (VecWidth == 512)
1479       IID = Intrinsic::x86_avx512_pmaddubs_w_512;
1480     else
1481       llvm_unreachable("Unexpected intrinsic");
1482   } else if (Name.startswith("packsswb.")) {
1483     if (VecWidth == 128)
1484       IID = Intrinsic::x86_sse2_packsswb_128;
1485     else if (VecWidth == 256)
1486       IID = Intrinsic::x86_avx2_packsswb;
1487     else if (VecWidth == 512)
1488       IID = Intrinsic::x86_avx512_packsswb_512;
1489     else
1490       llvm_unreachable("Unexpected intrinsic");
1491   } else if (Name.startswith("packssdw.")) {
1492     if (VecWidth == 128)
1493       IID = Intrinsic::x86_sse2_packssdw_128;
1494     else if (VecWidth == 256)
1495       IID = Intrinsic::x86_avx2_packssdw;
1496     else if (VecWidth == 512)
1497       IID = Intrinsic::x86_avx512_packssdw_512;
1498     else
1499       llvm_unreachable("Unexpected intrinsic");
1500   } else if (Name.startswith("packuswb.")) {
1501     if (VecWidth == 128)
1502       IID = Intrinsic::x86_sse2_packuswb_128;
1503     else if (VecWidth == 256)
1504       IID = Intrinsic::x86_avx2_packuswb;
1505     else if (VecWidth == 512)
1506       IID = Intrinsic::x86_avx512_packuswb_512;
1507     else
1508       llvm_unreachable("Unexpected intrinsic");
1509   } else if (Name.startswith("packusdw.")) {
1510     if (VecWidth == 128)
1511       IID = Intrinsic::x86_sse41_packusdw;
1512     else if (VecWidth == 256)
1513       IID = Intrinsic::x86_avx2_packusdw;
1514     else if (VecWidth == 512)
1515       IID = Intrinsic::x86_avx512_packusdw_512;
1516     else
1517       llvm_unreachable("Unexpected intrinsic");
1518   } else if (Name.startswith("vpermilvar.")) {
1519     if (VecWidth == 128 && EltWidth == 32)
1520       IID = Intrinsic::x86_avx_vpermilvar_ps;
1521     else if (VecWidth == 128 && EltWidth == 64)
1522       IID = Intrinsic::x86_avx_vpermilvar_pd;
1523     else if (VecWidth == 256 && EltWidth == 32)
1524       IID = Intrinsic::x86_avx_vpermilvar_ps_256;
1525     else if (VecWidth == 256 && EltWidth == 64)
1526       IID = Intrinsic::x86_avx_vpermilvar_pd_256;
1527     else if (VecWidth == 512 && EltWidth == 32)
1528       IID = Intrinsic::x86_avx512_vpermilvar_ps_512;
1529     else if (VecWidth == 512 && EltWidth == 64)
1530       IID = Intrinsic::x86_avx512_vpermilvar_pd_512;
1531     else
1532       llvm_unreachable("Unexpected intrinsic");
1533   } else if (Name == "cvtpd2dq.256") {
1534     IID = Intrinsic::x86_avx_cvt_pd2dq_256;
1535   } else if (Name == "cvtpd2ps.256") {
1536     IID = Intrinsic::x86_avx_cvt_pd2_ps_256;
1537   } else if (Name == "cvttpd2dq.256") {
1538     IID = Intrinsic::x86_avx_cvtt_pd2dq_256;
1539   } else if (Name == "cvttps2dq.128") {
1540     IID = Intrinsic::x86_sse2_cvttps2dq;
1541   } else if (Name == "cvttps2dq.256") {
1542     IID = Intrinsic::x86_avx_cvtt_ps2dq_256;
1543   } else if (Name.startswith("permvar.")) {
1544     bool IsFloat = CI.getType()->isFPOrFPVectorTy();
1545     if (VecWidth == 256 && EltWidth == 32 && IsFloat)
1546       IID = Intrinsic::x86_avx2_permps;
1547     else if (VecWidth == 256 && EltWidth == 32 && !IsFloat)
1548       IID = Intrinsic::x86_avx2_permd;
1549     else if (VecWidth == 256 && EltWidth == 64 && IsFloat)
1550       IID = Intrinsic::x86_avx512_permvar_df_256;
1551     else if (VecWidth == 256 && EltWidth == 64 && !IsFloat)
1552       IID = Intrinsic::x86_avx512_permvar_di_256;
1553     else if (VecWidth == 512 && EltWidth == 32 && IsFloat)
1554       IID = Intrinsic::x86_avx512_permvar_sf_512;
1555     else if (VecWidth == 512 && EltWidth == 32 && !IsFloat)
1556       IID = Intrinsic::x86_avx512_permvar_si_512;
1557     else if (VecWidth == 512 && EltWidth == 64 && IsFloat)
1558       IID = Intrinsic::x86_avx512_permvar_df_512;
1559     else if (VecWidth == 512 && EltWidth == 64 && !IsFloat)
1560       IID = Intrinsic::x86_avx512_permvar_di_512;
1561     else if (VecWidth == 128 && EltWidth == 16)
1562       IID = Intrinsic::x86_avx512_permvar_hi_128;
1563     else if (VecWidth == 256 && EltWidth == 16)
1564       IID = Intrinsic::x86_avx512_permvar_hi_256;
1565     else if (VecWidth == 512 && EltWidth == 16)
1566       IID = Intrinsic::x86_avx512_permvar_hi_512;
1567     else if (VecWidth == 128 && EltWidth == 8)
1568       IID = Intrinsic::x86_avx512_permvar_qi_128;
1569     else if (VecWidth == 256 && EltWidth == 8)
1570       IID = Intrinsic::x86_avx512_permvar_qi_256;
1571     else if (VecWidth == 512 && EltWidth == 8)
1572       IID = Intrinsic::x86_avx512_permvar_qi_512;
1573     else
1574       llvm_unreachable("Unexpected intrinsic");
1575   } else if (Name.startswith("dbpsadbw.")) {
1576     if (VecWidth == 128)
1577       IID = Intrinsic::x86_avx512_dbpsadbw_128;
1578     else if (VecWidth == 256)
1579       IID = Intrinsic::x86_avx512_dbpsadbw_256;
1580     else if (VecWidth == 512)
1581       IID = Intrinsic::x86_avx512_dbpsadbw_512;
1582     else
1583       llvm_unreachable("Unexpected intrinsic");
1584   } else if (Name.startswith("pmultishift.qb.")) {
1585     if (VecWidth == 128)
1586       IID = Intrinsic::x86_avx512_pmultishift_qb_128;
1587     else if (VecWidth == 256)
1588       IID = Intrinsic::x86_avx512_pmultishift_qb_256;
1589     else if (VecWidth == 512)
1590       IID = Intrinsic::x86_avx512_pmultishift_qb_512;
1591     else
1592       llvm_unreachable("Unexpected intrinsic");
1593   } else if (Name.startswith("conflict.")) {
1594     if (Name[9] == 'd' && VecWidth == 128)
1595       IID = Intrinsic::x86_avx512_conflict_d_128;
1596     else if (Name[9] == 'd' && VecWidth == 256)
1597       IID = Intrinsic::x86_avx512_conflict_d_256;
1598     else if (Name[9] == 'd' && VecWidth == 512)
1599       IID = Intrinsic::x86_avx512_conflict_d_512;
1600     else if (Name[9] == 'q' && VecWidth == 128)
1601       IID = Intrinsic::x86_avx512_conflict_q_128;
1602     else if (Name[9] == 'q' && VecWidth == 256)
1603       IID = Intrinsic::x86_avx512_conflict_q_256;
1604     else if (Name[9] == 'q' && VecWidth == 512)
1605       IID = Intrinsic::x86_avx512_conflict_q_512;
1606     else
1607       llvm_unreachable("Unexpected intrinsic");
1608   } else if (Name.startswith("pavg.")) {
1609     if (Name[5] == 'b' && VecWidth == 128)
1610       IID = Intrinsic::x86_sse2_pavg_b;
1611     else if (Name[5] == 'b' && VecWidth == 256)
1612       IID = Intrinsic::x86_avx2_pavg_b;
1613     else if (Name[5] == 'b' && VecWidth == 512)
1614       IID = Intrinsic::x86_avx512_pavg_b_512;
1615     else if (Name[5] == 'w' && VecWidth == 128)
1616       IID = Intrinsic::x86_sse2_pavg_w;
1617     else if (Name[5] == 'w' && VecWidth == 256)
1618       IID = Intrinsic::x86_avx2_pavg_w;
1619     else if (Name[5] == 'w' && VecWidth == 512)
1620       IID = Intrinsic::x86_avx512_pavg_w_512;
1621     else
1622       llvm_unreachable("Unexpected intrinsic");
1623   } else
1624     return false;
1625 
1626   SmallVector<Value *, 4> Args(CI.arg_operands().begin(),
1627                                CI.arg_operands().end());
1628   Args.pop_back();
1629   Args.pop_back();
1630   Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI.getModule(), IID),
1631                            Args);
1632   unsigned NumArgs = CI.getNumArgOperands();
1633   Rep = EmitX86Select(Builder, CI.getArgOperand(NumArgs - 1), Rep,
1634                       CI.getArgOperand(NumArgs - 2));
1635   return true;
1636 }
1637 
1638 /// Upgrade comment in call to inline asm that represents an objc retain release
1639 /// marker.
1640 void llvm::UpgradeInlineAsmString(std::string *AsmStr) {
1641   size_t Pos;
1642   if (AsmStr->find("mov\tfp") == 0 &&
1643       AsmStr->find("objc_retainAutoreleaseReturnValue") != std::string::npos &&
1644       (Pos = AsmStr->find("# marker")) != std::string::npos) {
1645     AsmStr->replace(Pos, 1, ";");
1646   }
1647   return;
1648 }
1649 
1650 /// Upgrade a call to an old intrinsic. All argument and return casting must be
1651 /// provided to seamlessly integrate with existing context.
1652 void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
1653   Function *F = CI->getCalledFunction();
1654   LLVMContext &C = CI->getContext();
1655   IRBuilder<> Builder(C);
1656   Builder.SetInsertPoint(CI->getParent(), CI->getIterator());
1657 
1658   assert(F && "Intrinsic call is not direct?");
1659 
1660   if (!NewFn) {
1661     // Get the Function's name.
1662     StringRef Name = F->getName();
1663 
1664     // clang.arc.use is an old name for llvm.arc.clang.arc.use. It is dropped
1665     // from upgrader because the optimizer now only recognizes intrinsics for
1666     // ARC runtime calls.
1667     if (Name == "clang.arc.use") {
1668       CI->eraseFromParent();
1669       return;
1670     }
1671 
1672     assert(Name.startswith("llvm.") && "Intrinsic doesn't start with 'llvm.'");
1673     Name = Name.substr(5);
1674 
1675     bool IsX86 = Name.startswith("x86.");
1676     if (IsX86)
1677       Name = Name.substr(4);
1678     bool IsNVVM = Name.startswith("nvvm.");
1679     if (IsNVVM)
1680       Name = Name.substr(5);
1681 
1682     if (IsX86 && Name.startswith("sse4a.movnt.")) {
1683       Module *M = F->getParent();
1684       SmallVector<Metadata *, 1> Elts;
1685       Elts.push_back(
1686           ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
1687       MDNode *Node = MDNode::get(C, Elts);
1688 
1689       Value *Arg0 = CI->getArgOperand(0);
1690       Value *Arg1 = CI->getArgOperand(1);
1691 
1692       // Nontemporal (unaligned) store of the 0'th element of the float/double
1693       // vector.
1694       Type *SrcEltTy = cast<VectorType>(Arg1->getType())->getElementType();
1695       PointerType *EltPtrTy = PointerType::getUnqual(SrcEltTy);
1696       Value *Addr = Builder.CreateBitCast(Arg0, EltPtrTy, "cast");
1697       Value *Extract =
1698           Builder.CreateExtractElement(Arg1, (uint64_t)0, "extractelement");
1699 
1700       StoreInst *SI = Builder.CreateAlignedStore(Extract, Addr, 1);
1701       SI->setMetadata(M->getMDKindID("nontemporal"), Node);
1702 
1703       // Remove intrinsic.
1704       CI->eraseFromParent();
1705       return;
1706     }
1707 
1708     if (IsX86 && (Name.startswith("avx.movnt.") ||
1709                   Name.startswith("avx512.storent."))) {
1710       Module *M = F->getParent();
1711       SmallVector<Metadata *, 1> Elts;
1712       Elts.push_back(
1713           ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
1714       MDNode *Node = MDNode::get(C, Elts);
1715 
1716       Value *Arg0 = CI->getArgOperand(0);
1717       Value *Arg1 = CI->getArgOperand(1);
1718 
1719       // Convert the type of the pointer to a pointer to the stored type.
1720       Value *BC = Builder.CreateBitCast(Arg0,
1721                                         PointerType::getUnqual(Arg1->getType()),
1722                                         "cast");
1723       VectorType *VTy = cast<VectorType>(Arg1->getType());
1724       StoreInst *SI = Builder.CreateAlignedStore(Arg1, BC,
1725                                                  VTy->getBitWidth() / 8);
1726       SI->setMetadata(M->getMDKindID("nontemporal"), Node);
1727 
1728       // Remove intrinsic.
1729       CI->eraseFromParent();
1730       return;
1731     }
1732 
1733     if (IsX86 && Name == "sse2.storel.dq") {
1734       Value *Arg0 = CI->getArgOperand(0);
1735       Value *Arg1 = CI->getArgOperand(1);
1736 
1737       Type *NewVecTy = VectorType::get(Type::getInt64Ty(C), 2);
1738       Value *BC0 = Builder.CreateBitCast(Arg1, NewVecTy, "cast");
1739       Value *Elt = Builder.CreateExtractElement(BC0, (uint64_t)0);
1740       Value *BC = Builder.CreateBitCast(Arg0,
1741                                         PointerType::getUnqual(Elt->getType()),
1742                                         "cast");
1743       Builder.CreateAlignedStore(Elt, BC, 1);
1744 
1745       // Remove intrinsic.
1746       CI->eraseFromParent();
1747       return;
1748     }
1749 
1750     if (IsX86 && (Name.startswith("sse.storeu.") ||
1751                   Name.startswith("sse2.storeu.") ||
1752                   Name.startswith("avx.storeu."))) {
1753       Value *Arg0 = CI->getArgOperand(0);
1754       Value *Arg1 = CI->getArgOperand(1);
1755 
1756       Arg0 = Builder.CreateBitCast(Arg0,
1757                                    PointerType::getUnqual(Arg1->getType()),
1758                                    "cast");
1759       Builder.CreateAlignedStore(Arg1, Arg0, 1);
1760 
1761       // Remove intrinsic.
1762       CI->eraseFromParent();
1763       return;
1764     }
1765 
1766     if (IsX86 && Name == "avx512.mask.store.ss") {
1767       Value *Mask = Builder.CreateAnd(CI->getArgOperand(2), Builder.getInt8(1));
1768       UpgradeMaskedStore(Builder, CI->getArgOperand(0), CI->getArgOperand(1),
1769                          Mask, false);
1770 
1771       // Remove intrinsic.
1772       CI->eraseFromParent();
1773       return;
1774     }
1775 
1776     if (IsX86 && (Name.startswith("avx512.mask.store"))) {
1777       // "avx512.mask.storeu." or "avx512.mask.store."
1778       bool Aligned = Name[17] != 'u'; // "avx512.mask.storeu".
1779       UpgradeMaskedStore(Builder, CI->getArgOperand(0), CI->getArgOperand(1),
1780                          CI->getArgOperand(2), Aligned);
1781 
1782       // Remove intrinsic.
1783       CI->eraseFromParent();
1784       return;
1785     }
1786 
1787     Value *Rep;
1788     // Upgrade packed integer vector compare intrinsics to compare instructions.
1789     if (IsX86 && (Name.startswith("sse2.pcmp") ||
1790                   Name.startswith("avx2.pcmp"))) {
1791       // "sse2.pcpmpeq." "sse2.pcmpgt." "avx2.pcmpeq." or "avx2.pcmpgt."
1792       bool CmpEq = Name[9] == 'e';
1793       Rep = Builder.CreateICmp(CmpEq ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_SGT,
1794                                CI->getArgOperand(0), CI->getArgOperand(1));
1795       Rep = Builder.CreateSExt(Rep, CI->getType(), "");
1796     } else if (IsX86 && (Name.startswith("avx512.broadcastm"))) {
1797       Type *ExtTy = Type::getInt32Ty(C);
1798       if (CI->getOperand(0)->getType()->isIntegerTy(8))
1799         ExtTy = Type::getInt64Ty(C);
1800       unsigned NumElts = CI->getType()->getPrimitiveSizeInBits() /
1801                          ExtTy->getPrimitiveSizeInBits();
1802       Rep = Builder.CreateZExt(CI->getArgOperand(0), ExtTy);
1803       Rep = Builder.CreateVectorSplat(NumElts, Rep);
1804     } else if (IsX86 && (Name == "sse.sqrt.ss" ||
1805                          Name == "sse2.sqrt.sd")) {
1806       Value *Vec = CI->getArgOperand(0);
1807       Value *Elt0 = Builder.CreateExtractElement(Vec, (uint64_t)0);
1808       Function *Intr = Intrinsic::getDeclaration(F->getParent(),
1809                                                  Intrinsic::sqrt, Elt0->getType());
1810       Elt0 = Builder.CreateCall(Intr, Elt0);
1811       Rep = Builder.CreateInsertElement(Vec, Elt0, (uint64_t)0);
1812     } else if (IsX86 && (Name.startswith("avx.sqrt.p") ||
1813                          Name.startswith("sse2.sqrt.p") ||
1814                          Name.startswith("sse.sqrt.p"))) {
1815       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(),
1816                                                          Intrinsic::sqrt,
1817                                                          CI->getType()),
1818                                {CI->getArgOperand(0)});
1819     } else if (IsX86 && (Name.startswith("avx512.mask.sqrt.p"))) {
1820       if (CI->getNumArgOperands() == 4 &&
1821           (!isa<ConstantInt>(CI->getArgOperand(3)) ||
1822            cast<ConstantInt>(CI->getArgOperand(3))->getZExtValue() != 4)) {
1823         Intrinsic::ID IID = Name[18] == 's' ? Intrinsic::x86_avx512_sqrt_ps_512
1824                                             : Intrinsic::x86_avx512_sqrt_pd_512;
1825 
1826         Value *Args[] = { CI->getArgOperand(0), CI->getArgOperand(3) };
1827         Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(),
1828                                                            IID), Args);
1829       } else {
1830         Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(),
1831                                                            Intrinsic::sqrt,
1832                                                            CI->getType()),
1833                                  {CI->getArgOperand(0)});
1834       }
1835       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
1836                           CI->getArgOperand(1));
1837     } else if (IsX86 && (Name.startswith("avx512.ptestm") ||
1838                          Name.startswith("avx512.ptestnm"))) {
1839       Value *Op0 = CI->getArgOperand(0);
1840       Value *Op1 = CI->getArgOperand(1);
1841       Value *Mask = CI->getArgOperand(2);
1842       Rep = Builder.CreateAnd(Op0, Op1);
1843       llvm::Type *Ty = Op0->getType();
1844       Value *Zero = llvm::Constant::getNullValue(Ty);
1845       ICmpInst::Predicate Pred =
1846         Name.startswith("avx512.ptestm") ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
1847       Rep = Builder.CreateICmp(Pred, Rep, Zero);
1848       Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, Mask);
1849     } else if (IsX86 && (Name.startswith("avx512.mask.pbroadcast"))){
1850       unsigned NumElts =
1851           CI->getArgOperand(1)->getType()->getVectorNumElements();
1852       Rep = Builder.CreateVectorSplat(NumElts, CI->getArgOperand(0));
1853       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
1854                           CI->getArgOperand(1));
1855     } else if (IsX86 && (Name.startswith("avx512.kunpck"))) {
1856       unsigned NumElts = CI->getType()->getScalarSizeInBits();
1857       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), NumElts);
1858       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), NumElts);
1859       uint32_t Indices[64];
1860       for (unsigned i = 0; i != NumElts; ++i)
1861         Indices[i] = i;
1862 
1863       // First extract half of each vector. This gives better codegen than
1864       // doing it in a single shuffle.
1865       LHS = Builder.CreateShuffleVector(LHS, LHS,
1866                                         makeArrayRef(Indices, NumElts / 2));
1867       RHS = Builder.CreateShuffleVector(RHS, RHS,
1868                                         makeArrayRef(Indices, NumElts / 2));
1869       // Concat the vectors.
1870       // NOTE: Operands have to be swapped to match intrinsic definition.
1871       Rep = Builder.CreateShuffleVector(RHS, LHS,
1872                                         makeArrayRef(Indices, NumElts));
1873       Rep = Builder.CreateBitCast(Rep, CI->getType());
1874     } else if (IsX86 && Name == "avx512.kand.w") {
1875       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1876       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1877       Rep = Builder.CreateAnd(LHS, RHS);
1878       Rep = Builder.CreateBitCast(Rep, CI->getType());
1879     } else if (IsX86 && Name == "avx512.kandn.w") {
1880       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1881       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1882       LHS = Builder.CreateNot(LHS);
1883       Rep = Builder.CreateAnd(LHS, RHS);
1884       Rep = Builder.CreateBitCast(Rep, CI->getType());
1885     } else if (IsX86 && Name == "avx512.kor.w") {
1886       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1887       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1888       Rep = Builder.CreateOr(LHS, RHS);
1889       Rep = Builder.CreateBitCast(Rep, CI->getType());
1890     } else if (IsX86 && Name == "avx512.kxor.w") {
1891       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1892       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1893       Rep = Builder.CreateXor(LHS, RHS);
1894       Rep = Builder.CreateBitCast(Rep, CI->getType());
1895     } else if (IsX86 && Name == "avx512.kxnor.w") {
1896       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1897       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1898       LHS = Builder.CreateNot(LHS);
1899       Rep = Builder.CreateXor(LHS, RHS);
1900       Rep = Builder.CreateBitCast(Rep, CI->getType());
1901     } else if (IsX86 && Name == "avx512.knot.w") {
1902       Rep = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1903       Rep = Builder.CreateNot(Rep);
1904       Rep = Builder.CreateBitCast(Rep, CI->getType());
1905     } else if (IsX86 &&
1906                (Name == "avx512.kortestz.w" || Name == "avx512.kortestc.w")) {
1907       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1908       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1909       Rep = Builder.CreateOr(LHS, RHS);
1910       Rep = Builder.CreateBitCast(Rep, Builder.getInt16Ty());
1911       Value *C;
1912       if (Name[14] == 'c')
1913         C = ConstantInt::getAllOnesValue(Builder.getInt16Ty());
1914       else
1915         C = ConstantInt::getNullValue(Builder.getInt16Ty());
1916       Rep = Builder.CreateICmpEQ(Rep, C);
1917       Rep = Builder.CreateZExt(Rep, Builder.getInt32Ty());
1918     } else if (IsX86 && (Name == "sse.add.ss" || Name == "sse2.add.sd" ||
1919                          Name == "sse.sub.ss" || Name == "sse2.sub.sd" ||
1920                          Name == "sse.mul.ss" || Name == "sse2.mul.sd" ||
1921                          Name == "sse.div.ss" || Name == "sse2.div.sd")) {
1922       Type *I32Ty = Type::getInt32Ty(C);
1923       Value *Elt0 = Builder.CreateExtractElement(CI->getArgOperand(0),
1924                                                  ConstantInt::get(I32Ty, 0));
1925       Value *Elt1 = Builder.CreateExtractElement(CI->getArgOperand(1),
1926                                                  ConstantInt::get(I32Ty, 0));
1927       Value *EltOp;
1928       if (Name.contains(".add."))
1929         EltOp = Builder.CreateFAdd(Elt0, Elt1);
1930       else if (Name.contains(".sub."))
1931         EltOp = Builder.CreateFSub(Elt0, Elt1);
1932       else if (Name.contains(".mul."))
1933         EltOp = Builder.CreateFMul(Elt0, Elt1);
1934       else
1935         EltOp = Builder.CreateFDiv(Elt0, Elt1);
1936       Rep = Builder.CreateInsertElement(CI->getArgOperand(0), EltOp,
1937                                         ConstantInt::get(I32Ty, 0));
1938     } else if (IsX86 && Name.startswith("avx512.mask.pcmp")) {
1939       // "avx512.mask.pcmpeq." or "avx512.mask.pcmpgt."
1940       bool CmpEq = Name[16] == 'e';
1941       Rep = upgradeMaskedCompare(Builder, *CI, CmpEq ? 0 : 6, true);
1942     } else if (IsX86 && Name.startswith("avx512.mask.vpshufbitqmb.")) {
1943       Type *OpTy = CI->getArgOperand(0)->getType();
1944       unsigned VecWidth = OpTy->getPrimitiveSizeInBits();
1945       Intrinsic::ID IID;
1946       switch (VecWidth) {
1947       default: llvm_unreachable("Unexpected intrinsic");
1948       case 128: IID = Intrinsic::x86_avx512_vpshufbitqmb_128; break;
1949       case 256: IID = Intrinsic::x86_avx512_vpshufbitqmb_256; break;
1950       case 512: IID = Intrinsic::x86_avx512_vpshufbitqmb_512; break;
1951       }
1952 
1953       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
1954                                { CI->getOperand(0), CI->getArgOperand(1) });
1955       Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, CI->getArgOperand(2));
1956     } else if (IsX86 && Name.startswith("avx512.mask.fpclass.p")) {
1957       Type *OpTy = CI->getArgOperand(0)->getType();
1958       unsigned VecWidth = OpTy->getPrimitiveSizeInBits();
1959       unsigned EltWidth = OpTy->getScalarSizeInBits();
1960       Intrinsic::ID IID;
1961       if (VecWidth == 128 && EltWidth == 32)
1962         IID = Intrinsic::x86_avx512_fpclass_ps_128;
1963       else if (VecWidth == 256 && EltWidth == 32)
1964         IID = Intrinsic::x86_avx512_fpclass_ps_256;
1965       else if (VecWidth == 512 && EltWidth == 32)
1966         IID = Intrinsic::x86_avx512_fpclass_ps_512;
1967       else if (VecWidth == 128 && EltWidth == 64)
1968         IID = Intrinsic::x86_avx512_fpclass_pd_128;
1969       else if (VecWidth == 256 && EltWidth == 64)
1970         IID = Intrinsic::x86_avx512_fpclass_pd_256;
1971       else if (VecWidth == 512 && EltWidth == 64)
1972         IID = Intrinsic::x86_avx512_fpclass_pd_512;
1973       else
1974         llvm_unreachable("Unexpected intrinsic");
1975 
1976       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
1977                                { CI->getOperand(0), CI->getArgOperand(1) });
1978       Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, CI->getArgOperand(2));
1979     } else if (IsX86 && Name.startswith("avx512.mask.cmp.p")) {
1980       Type *OpTy = CI->getArgOperand(0)->getType();
1981       unsigned VecWidth = OpTy->getPrimitiveSizeInBits();
1982       unsigned EltWidth = OpTy->getScalarSizeInBits();
1983       Intrinsic::ID IID;
1984       if (VecWidth == 128 && EltWidth == 32)
1985         IID = Intrinsic::x86_avx512_cmp_ps_128;
1986       else if (VecWidth == 256 && EltWidth == 32)
1987         IID = Intrinsic::x86_avx512_cmp_ps_256;
1988       else if (VecWidth == 512 && EltWidth == 32)
1989         IID = Intrinsic::x86_avx512_cmp_ps_512;
1990       else if (VecWidth == 128 && EltWidth == 64)
1991         IID = Intrinsic::x86_avx512_cmp_pd_128;
1992       else if (VecWidth == 256 && EltWidth == 64)
1993         IID = Intrinsic::x86_avx512_cmp_pd_256;
1994       else if (VecWidth == 512 && EltWidth == 64)
1995         IID = Intrinsic::x86_avx512_cmp_pd_512;
1996       else
1997         llvm_unreachable("Unexpected intrinsic");
1998 
1999       SmallVector<Value *, 4> Args;
2000       Args.push_back(CI->getArgOperand(0));
2001       Args.push_back(CI->getArgOperand(1));
2002       Args.push_back(CI->getArgOperand(2));
2003       if (CI->getNumArgOperands() == 5)
2004         Args.push_back(CI->getArgOperand(4));
2005 
2006       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
2007                                Args);
2008       Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, CI->getArgOperand(3));
2009     } else if (IsX86 && Name.startswith("avx512.mask.cmp.") &&
2010                Name[16] != 'p') {
2011       // Integer compare intrinsics.
2012       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2013       Rep = upgradeMaskedCompare(Builder, *CI, Imm, true);
2014     } else if (IsX86 && Name.startswith("avx512.mask.ucmp.")) {
2015       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2016       Rep = upgradeMaskedCompare(Builder, *CI, Imm, false);
2017     } else if (IsX86 && (Name.startswith("avx512.cvtb2mask.") ||
2018                          Name.startswith("avx512.cvtw2mask.") ||
2019                          Name.startswith("avx512.cvtd2mask.") ||
2020                          Name.startswith("avx512.cvtq2mask."))) {
2021       Value *Op = CI->getArgOperand(0);
2022       Value *Zero = llvm::Constant::getNullValue(Op->getType());
2023       Rep = Builder.CreateICmp(ICmpInst::ICMP_SLT, Op, Zero);
2024       Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, nullptr);
2025     } else if(IsX86 && (Name == "ssse3.pabs.b.128" ||
2026                         Name == "ssse3.pabs.w.128" ||
2027                         Name == "ssse3.pabs.d.128" ||
2028                         Name.startswith("avx2.pabs") ||
2029                         Name.startswith("avx512.mask.pabs"))) {
2030       Rep = upgradeAbs(Builder, *CI);
2031     } else if (IsX86 && (Name == "sse41.pmaxsb" ||
2032                          Name == "sse2.pmaxs.w" ||
2033                          Name == "sse41.pmaxsd" ||
2034                          Name.startswith("avx2.pmaxs") ||
2035                          Name.startswith("avx512.mask.pmaxs"))) {
2036       Rep = upgradeIntMinMax(Builder, *CI, ICmpInst::ICMP_SGT);
2037     } else if (IsX86 && (Name == "sse2.pmaxu.b" ||
2038                          Name == "sse41.pmaxuw" ||
2039                          Name == "sse41.pmaxud" ||
2040                          Name.startswith("avx2.pmaxu") ||
2041                          Name.startswith("avx512.mask.pmaxu"))) {
2042       Rep = upgradeIntMinMax(Builder, *CI, ICmpInst::ICMP_UGT);
2043     } else if (IsX86 && (Name == "sse41.pminsb" ||
2044                          Name == "sse2.pmins.w" ||
2045                          Name == "sse41.pminsd" ||
2046                          Name.startswith("avx2.pmins") ||
2047                          Name.startswith("avx512.mask.pmins"))) {
2048       Rep = upgradeIntMinMax(Builder, *CI, ICmpInst::ICMP_SLT);
2049     } else if (IsX86 && (Name == "sse2.pminu.b" ||
2050                          Name == "sse41.pminuw" ||
2051                          Name == "sse41.pminud" ||
2052                          Name.startswith("avx2.pminu") ||
2053                          Name.startswith("avx512.mask.pminu"))) {
2054       Rep = upgradeIntMinMax(Builder, *CI, ICmpInst::ICMP_ULT);
2055     } else if (IsX86 && (Name == "sse2.pmulu.dq" ||
2056                          Name == "avx2.pmulu.dq" ||
2057                          Name == "avx512.pmulu.dq.512" ||
2058                          Name.startswith("avx512.mask.pmulu.dq."))) {
2059       Rep = upgradePMULDQ(Builder, *CI, /*Signed*/false);
2060     } else if (IsX86 && (Name == "sse41.pmuldq" ||
2061                          Name == "avx2.pmul.dq" ||
2062                          Name == "avx512.pmul.dq.512" ||
2063                          Name.startswith("avx512.mask.pmul.dq."))) {
2064       Rep = upgradePMULDQ(Builder, *CI, /*Signed*/true);
2065     } else if (IsX86 && (Name == "sse.cvtsi2ss" ||
2066                          Name == "sse2.cvtsi2sd" ||
2067                          Name == "sse.cvtsi642ss" ||
2068                          Name == "sse2.cvtsi642sd")) {
2069       Rep = Builder.CreateSIToFP(CI->getArgOperand(1),
2070                                  CI->getType()->getVectorElementType());
2071       Rep = Builder.CreateInsertElement(CI->getArgOperand(0), Rep, (uint64_t)0);
2072     } else if (IsX86 && Name == "avx512.cvtusi2sd") {
2073       Rep = Builder.CreateUIToFP(CI->getArgOperand(1),
2074                                  CI->getType()->getVectorElementType());
2075       Rep = Builder.CreateInsertElement(CI->getArgOperand(0), Rep, (uint64_t)0);
2076     } else if (IsX86 && Name == "sse2.cvtss2sd") {
2077       Rep = Builder.CreateExtractElement(CI->getArgOperand(1), (uint64_t)0);
2078       Rep = Builder.CreateFPExt(Rep, CI->getType()->getVectorElementType());
2079       Rep = Builder.CreateInsertElement(CI->getArgOperand(0), Rep, (uint64_t)0);
2080     } else if (IsX86 && (Name == "sse2.cvtdq2pd" ||
2081                          Name == "sse2.cvtdq2ps" ||
2082                          Name == "avx.cvtdq2.pd.256" ||
2083                          Name == "avx.cvtdq2.ps.256" ||
2084                          Name.startswith("avx512.mask.cvtdq2pd.") ||
2085                          Name.startswith("avx512.mask.cvtudq2pd.") ||
2086                          Name.startswith("avx512.mask.cvtdq2ps.") ||
2087                          Name.startswith("avx512.mask.cvtudq2ps.") ||
2088                          Name.startswith("avx512.mask.cvtqq2pd.") ||
2089                          Name.startswith("avx512.mask.cvtuqq2pd.") ||
2090                          Name == "avx512.mask.cvtqq2ps.256" ||
2091                          Name == "avx512.mask.cvtqq2ps.512" ||
2092                          Name == "avx512.mask.cvtuqq2ps.256" ||
2093                          Name == "avx512.mask.cvtuqq2ps.512" ||
2094                          Name == "sse2.cvtps2pd" ||
2095                          Name == "avx.cvt.ps2.pd.256" ||
2096                          Name == "avx512.mask.cvtps2pd.128" ||
2097                          Name == "avx512.mask.cvtps2pd.256")) {
2098       Type *DstTy = CI->getType();
2099       Rep = CI->getArgOperand(0);
2100       Type *SrcTy = Rep->getType();
2101 
2102       unsigned NumDstElts = DstTy->getVectorNumElements();
2103       if (NumDstElts < SrcTy->getVectorNumElements()) {
2104         assert(NumDstElts == 2 && "Unexpected vector size");
2105         uint32_t ShuffleMask[2] = { 0, 1 };
2106         Rep = Builder.CreateShuffleVector(Rep, Rep, ShuffleMask);
2107       }
2108 
2109       bool IsPS2PD = SrcTy->getVectorElementType()->isFloatTy();
2110       bool IsUnsigned = (StringRef::npos != Name.find("cvtu"));
2111       if (IsPS2PD)
2112         Rep = Builder.CreateFPExt(Rep, DstTy, "cvtps2pd");
2113       else if (CI->getNumArgOperands() == 4 &&
2114                (!isa<ConstantInt>(CI->getArgOperand(3)) ||
2115                 cast<ConstantInt>(CI->getArgOperand(3))->getZExtValue() != 4)) {
2116         Intrinsic::ID IID = IsUnsigned ? Intrinsic::x86_avx512_uitofp_round
2117                                        : Intrinsic::x86_avx512_sitofp_round;
2118         Function *F = Intrinsic::getDeclaration(CI->getModule(), IID,
2119                                                 { DstTy, SrcTy });
2120         Rep = Builder.CreateCall(F, { Rep, CI->getArgOperand(3) });
2121       } else {
2122         Rep = IsUnsigned ? Builder.CreateUIToFP(Rep, DstTy, "cvt")
2123                          : Builder.CreateSIToFP(Rep, DstTy, "cvt");
2124       }
2125 
2126       if (CI->getNumArgOperands() >= 3)
2127         Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2128                             CI->getArgOperand(1));
2129     } else if (IsX86 && (Name.startswith("avx512.mask.loadu."))) {
2130       Rep = UpgradeMaskedLoad(Builder, CI->getArgOperand(0),
2131                               CI->getArgOperand(1), CI->getArgOperand(2),
2132                               /*Aligned*/false);
2133     } else if (IsX86 && (Name.startswith("avx512.mask.load."))) {
2134       Rep = UpgradeMaskedLoad(Builder, CI->getArgOperand(0),
2135                               CI->getArgOperand(1),CI->getArgOperand(2),
2136                               /*Aligned*/true);
2137     } else if (IsX86 && Name.startswith("avx512.mask.expand.load.")) {
2138       Type *ResultTy = CI->getType();
2139       Type *PtrTy = ResultTy->getVectorElementType();
2140 
2141       // Cast the pointer to element type.
2142       Value *Ptr = Builder.CreateBitCast(CI->getOperand(0),
2143                                          llvm::PointerType::getUnqual(PtrTy));
2144 
2145       Value *MaskVec = getX86MaskVec(Builder, CI->getArgOperand(2),
2146                                      ResultTy->getVectorNumElements());
2147 
2148       Function *ELd = Intrinsic::getDeclaration(F->getParent(),
2149                                                 Intrinsic::masked_expandload,
2150                                                 ResultTy);
2151       Rep = Builder.CreateCall(ELd, { Ptr, MaskVec, CI->getOperand(1) });
2152     } else if (IsX86 && Name.startswith("avx512.mask.compress.store.")) {
2153       Type *ResultTy = CI->getArgOperand(1)->getType();
2154       Type *PtrTy = ResultTy->getVectorElementType();
2155 
2156       // Cast the pointer to element type.
2157       Value *Ptr = Builder.CreateBitCast(CI->getOperand(0),
2158                                          llvm::PointerType::getUnqual(PtrTy));
2159 
2160       Value *MaskVec = getX86MaskVec(Builder, CI->getArgOperand(2),
2161                                      ResultTy->getVectorNumElements());
2162 
2163       Function *CSt = Intrinsic::getDeclaration(F->getParent(),
2164                                                 Intrinsic::masked_compressstore,
2165                                                 ResultTy);
2166       Rep = Builder.CreateCall(CSt, { CI->getArgOperand(1), Ptr, MaskVec });
2167     } else if (IsX86 && (Name.startswith("avx512.mask.compress.") ||
2168                          Name.startswith("avx512.mask.expand."))) {
2169       Type *ResultTy = CI->getType();
2170 
2171       Value *MaskVec = getX86MaskVec(Builder, CI->getArgOperand(2),
2172                                      ResultTy->getVectorNumElements());
2173 
2174       bool IsCompress = Name[12] == 'c';
2175       Intrinsic::ID IID = IsCompress ? Intrinsic::x86_avx512_mask_compress
2176                                      : Intrinsic::x86_avx512_mask_expand;
2177       Function *Intr = Intrinsic::getDeclaration(F->getParent(), IID, ResultTy);
2178       Rep = Builder.CreateCall(Intr, { CI->getOperand(0), CI->getOperand(1),
2179                                        MaskVec });
2180     } else if (IsX86 && Name.startswith("xop.vpcom")) {
2181       bool IsSigned;
2182       if (Name.endswith("ub") || Name.endswith("uw") || Name.endswith("ud") ||
2183           Name.endswith("uq"))
2184         IsSigned = false;
2185       else if (Name.endswith("b") || Name.endswith("w") || Name.endswith("d") ||
2186                Name.endswith("q"))
2187         IsSigned = true;
2188       else
2189         llvm_unreachable("Unknown suffix");
2190 
2191       unsigned Imm;
2192       if (CI->getNumArgOperands() == 3) {
2193         Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2194       } else {
2195         Name = Name.substr(9); // strip off "xop.vpcom"
2196         if (Name.startswith("lt"))
2197           Imm = 0;
2198         else if (Name.startswith("le"))
2199           Imm = 1;
2200         else if (Name.startswith("gt"))
2201           Imm = 2;
2202         else if (Name.startswith("ge"))
2203           Imm = 3;
2204         else if (Name.startswith("eq"))
2205           Imm = 4;
2206         else if (Name.startswith("ne"))
2207           Imm = 5;
2208         else if (Name.startswith("false"))
2209           Imm = 6;
2210         else if (Name.startswith("true"))
2211           Imm = 7;
2212         else
2213           llvm_unreachable("Unknown condition");
2214       }
2215 
2216       Rep = upgradeX86vpcom(Builder, *CI, Imm, IsSigned);
2217     } else if (IsX86 && Name.startswith("xop.vpcmov")) {
2218       Value *Sel = CI->getArgOperand(2);
2219       Value *NotSel = Builder.CreateNot(Sel);
2220       Value *Sel0 = Builder.CreateAnd(CI->getArgOperand(0), Sel);
2221       Value *Sel1 = Builder.CreateAnd(CI->getArgOperand(1), NotSel);
2222       Rep = Builder.CreateOr(Sel0, Sel1);
2223     } else if (IsX86 && (Name.startswith("xop.vprot") ||
2224                          Name.startswith("avx512.prol") ||
2225                          Name.startswith("avx512.mask.prol"))) {
2226       Rep = upgradeX86Rotate(Builder, *CI, false);
2227     } else if (IsX86 && (Name.startswith("avx512.pror") ||
2228                          Name.startswith("avx512.mask.pror"))) {
2229       Rep = upgradeX86Rotate(Builder, *CI, true);
2230     } else if (IsX86 && (Name.startswith("avx512.vpshld.") ||
2231                          Name.startswith("avx512.mask.vpshld") ||
2232                          Name.startswith("avx512.maskz.vpshld"))) {
2233       bool ZeroMask = Name[11] == 'z';
2234       Rep = upgradeX86ConcatShift(Builder, *CI, false, ZeroMask);
2235     } else if (IsX86 && (Name.startswith("avx512.vpshrd.") ||
2236                          Name.startswith("avx512.mask.vpshrd") ||
2237                          Name.startswith("avx512.maskz.vpshrd"))) {
2238       bool ZeroMask = Name[11] == 'z';
2239       Rep = upgradeX86ConcatShift(Builder, *CI, true, ZeroMask);
2240     } else if (IsX86 && Name == "sse42.crc32.64.8") {
2241       Function *CRC32 = Intrinsic::getDeclaration(F->getParent(),
2242                                                Intrinsic::x86_sse42_crc32_32_8);
2243       Value *Trunc0 = Builder.CreateTrunc(CI->getArgOperand(0), Type::getInt32Ty(C));
2244       Rep = Builder.CreateCall(CRC32, {Trunc0, CI->getArgOperand(1)});
2245       Rep = Builder.CreateZExt(Rep, CI->getType(), "");
2246     } else if (IsX86 && (Name.startswith("avx.vbroadcast.s") ||
2247                          Name.startswith("avx512.vbroadcast.s"))) {
2248       // Replace broadcasts with a series of insertelements.
2249       Type *VecTy = CI->getType();
2250       Type *EltTy = VecTy->getVectorElementType();
2251       unsigned EltNum = VecTy->getVectorNumElements();
2252       Value *Cast = Builder.CreateBitCast(CI->getArgOperand(0),
2253                                           EltTy->getPointerTo());
2254       Value *Load = Builder.CreateLoad(EltTy, Cast);
2255       Type *I32Ty = Type::getInt32Ty(C);
2256       Rep = UndefValue::get(VecTy);
2257       for (unsigned I = 0; I < EltNum; ++I)
2258         Rep = Builder.CreateInsertElement(Rep, Load,
2259                                           ConstantInt::get(I32Ty, I));
2260     } else if (IsX86 && (Name.startswith("sse41.pmovsx") ||
2261                          Name.startswith("sse41.pmovzx") ||
2262                          Name.startswith("avx2.pmovsx") ||
2263                          Name.startswith("avx2.pmovzx") ||
2264                          Name.startswith("avx512.mask.pmovsx") ||
2265                          Name.startswith("avx512.mask.pmovzx"))) {
2266       VectorType *SrcTy = cast<VectorType>(CI->getArgOperand(0)->getType());
2267       VectorType *DstTy = cast<VectorType>(CI->getType());
2268       unsigned NumDstElts = DstTy->getNumElements();
2269 
2270       // Extract a subvector of the first NumDstElts lanes and sign/zero extend.
2271       SmallVector<uint32_t, 8> ShuffleMask(NumDstElts);
2272       for (unsigned i = 0; i != NumDstElts; ++i)
2273         ShuffleMask[i] = i;
2274 
2275       Value *SV = Builder.CreateShuffleVector(
2276           CI->getArgOperand(0), UndefValue::get(SrcTy), ShuffleMask);
2277 
2278       bool DoSext = (StringRef::npos != Name.find("pmovsx"));
2279       Rep = DoSext ? Builder.CreateSExt(SV, DstTy)
2280                    : Builder.CreateZExt(SV, DstTy);
2281       // If there are 3 arguments, it's a masked intrinsic so we need a select.
2282       if (CI->getNumArgOperands() == 3)
2283         Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2284                             CI->getArgOperand(1));
2285     } else if (Name == "avx512.mask.pmov.qd.256" ||
2286                Name == "avx512.mask.pmov.qd.512" ||
2287                Name == "avx512.mask.pmov.wb.256" ||
2288                Name == "avx512.mask.pmov.wb.512") {
2289       Type *Ty = CI->getArgOperand(1)->getType();
2290       Rep = Builder.CreateTrunc(CI->getArgOperand(0), Ty);
2291       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2292                           CI->getArgOperand(1));
2293     } else if (IsX86 && (Name.startswith("avx.vbroadcastf128") ||
2294                          Name == "avx2.vbroadcasti128")) {
2295       // Replace vbroadcastf128/vbroadcasti128 with a vector load+shuffle.
2296       Type *EltTy = CI->getType()->getVectorElementType();
2297       unsigned NumSrcElts = 128 / EltTy->getPrimitiveSizeInBits();
2298       Type *VT = VectorType::get(EltTy, NumSrcElts);
2299       Value *Op = Builder.CreatePointerCast(CI->getArgOperand(0),
2300                                             PointerType::getUnqual(VT));
2301       Value *Load = Builder.CreateAlignedLoad(VT, Op, 1);
2302       if (NumSrcElts == 2)
2303         Rep = Builder.CreateShuffleVector(Load, UndefValue::get(Load->getType()),
2304                                           { 0, 1, 0, 1 });
2305       else
2306         Rep = Builder.CreateShuffleVector(Load, UndefValue::get(Load->getType()),
2307                                           { 0, 1, 2, 3, 0, 1, 2, 3 });
2308     } else if (IsX86 && (Name.startswith("avx512.mask.shuf.i") ||
2309                          Name.startswith("avx512.mask.shuf.f"))) {
2310       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2311       Type *VT = CI->getType();
2312       unsigned NumLanes = VT->getPrimitiveSizeInBits() / 128;
2313       unsigned NumElementsInLane = 128 / VT->getScalarSizeInBits();
2314       unsigned ControlBitsMask = NumLanes - 1;
2315       unsigned NumControlBits = NumLanes / 2;
2316       SmallVector<uint32_t, 8> ShuffleMask(0);
2317 
2318       for (unsigned l = 0; l != NumLanes; ++l) {
2319         unsigned LaneMask = (Imm >> (l * NumControlBits)) & ControlBitsMask;
2320         // We actually need the other source.
2321         if (l >= NumLanes / 2)
2322           LaneMask += NumLanes;
2323         for (unsigned i = 0; i != NumElementsInLane; ++i)
2324           ShuffleMask.push_back(LaneMask * NumElementsInLane + i);
2325       }
2326       Rep = Builder.CreateShuffleVector(CI->getArgOperand(0),
2327                                         CI->getArgOperand(1), ShuffleMask);
2328       Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep,
2329                           CI->getArgOperand(3));
2330     }else if (IsX86 && (Name.startswith("avx512.mask.broadcastf") ||
2331                          Name.startswith("avx512.mask.broadcasti"))) {
2332       unsigned NumSrcElts =
2333                         CI->getArgOperand(0)->getType()->getVectorNumElements();
2334       unsigned NumDstElts = CI->getType()->getVectorNumElements();
2335 
2336       SmallVector<uint32_t, 8> ShuffleMask(NumDstElts);
2337       for (unsigned i = 0; i != NumDstElts; ++i)
2338         ShuffleMask[i] = i % NumSrcElts;
2339 
2340       Rep = Builder.CreateShuffleVector(CI->getArgOperand(0),
2341                                         CI->getArgOperand(0),
2342                                         ShuffleMask);
2343       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2344                           CI->getArgOperand(1));
2345     } else if (IsX86 && (Name.startswith("avx2.pbroadcast") ||
2346                          Name.startswith("avx2.vbroadcast") ||
2347                          Name.startswith("avx512.pbroadcast") ||
2348                          Name.startswith("avx512.mask.broadcast.s"))) {
2349       // Replace vp?broadcasts with a vector shuffle.
2350       Value *Op = CI->getArgOperand(0);
2351       unsigned NumElts = CI->getType()->getVectorNumElements();
2352       Type *MaskTy = VectorType::get(Type::getInt32Ty(C), NumElts);
2353       Rep = Builder.CreateShuffleVector(Op, UndefValue::get(Op->getType()),
2354                                         Constant::getNullValue(MaskTy));
2355 
2356       if (CI->getNumArgOperands() == 3)
2357         Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2358                             CI->getArgOperand(1));
2359     } else if (IsX86 && (Name.startswith("sse2.padds.") ||
2360                          Name.startswith("sse2.psubs.") ||
2361                          Name.startswith("avx2.padds.") ||
2362                          Name.startswith("avx2.psubs.") ||
2363                          Name.startswith("avx512.padds.") ||
2364                          Name.startswith("avx512.psubs.") ||
2365                          Name.startswith("avx512.mask.padds.") ||
2366                          Name.startswith("avx512.mask.psubs."))) {
2367       bool IsAdd = Name.contains(".padds");
2368       Rep = UpgradeX86AddSubSatIntrinsics(Builder, *CI, true, IsAdd);
2369     } else if (IsX86 && (Name.startswith("sse2.paddus.") ||
2370                          Name.startswith("sse2.psubus.") ||
2371                          Name.startswith("avx2.paddus.") ||
2372                          Name.startswith("avx2.psubus.") ||
2373                          Name.startswith("avx512.mask.paddus.") ||
2374                          Name.startswith("avx512.mask.psubus."))) {
2375       bool IsAdd = Name.contains(".paddus");
2376       Rep = UpgradeX86AddSubSatIntrinsics(Builder, *CI, false, IsAdd);
2377     } else if (IsX86 && Name.startswith("avx512.mask.palignr.")) {
2378       Rep = UpgradeX86ALIGNIntrinsics(Builder, CI->getArgOperand(0),
2379                                       CI->getArgOperand(1),
2380                                       CI->getArgOperand(2),
2381                                       CI->getArgOperand(3),
2382                                       CI->getArgOperand(4),
2383                                       false);
2384     } else if (IsX86 && Name.startswith("avx512.mask.valign.")) {
2385       Rep = UpgradeX86ALIGNIntrinsics(Builder, CI->getArgOperand(0),
2386                                       CI->getArgOperand(1),
2387                                       CI->getArgOperand(2),
2388                                       CI->getArgOperand(3),
2389                                       CI->getArgOperand(4),
2390                                       true);
2391     } else if (IsX86 && (Name == "sse2.psll.dq" ||
2392                          Name == "avx2.psll.dq")) {
2393       // 128/256-bit shift left specified in bits.
2394       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2395       Rep = UpgradeX86PSLLDQIntrinsics(Builder, CI->getArgOperand(0),
2396                                        Shift / 8); // Shift is in bits.
2397     } else if (IsX86 && (Name == "sse2.psrl.dq" ||
2398                          Name == "avx2.psrl.dq")) {
2399       // 128/256-bit shift right specified in bits.
2400       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2401       Rep = UpgradeX86PSRLDQIntrinsics(Builder, CI->getArgOperand(0),
2402                                        Shift / 8); // Shift is in bits.
2403     } else if (IsX86 && (Name == "sse2.psll.dq.bs" ||
2404                          Name == "avx2.psll.dq.bs" ||
2405                          Name == "avx512.psll.dq.512")) {
2406       // 128/256/512-bit shift left specified in bytes.
2407       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2408       Rep = UpgradeX86PSLLDQIntrinsics(Builder, CI->getArgOperand(0), Shift);
2409     } else if (IsX86 && (Name == "sse2.psrl.dq.bs" ||
2410                          Name == "avx2.psrl.dq.bs" ||
2411                          Name == "avx512.psrl.dq.512")) {
2412       // 128/256/512-bit shift right specified in bytes.
2413       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2414       Rep = UpgradeX86PSRLDQIntrinsics(Builder, CI->getArgOperand(0), Shift);
2415     } else if (IsX86 && (Name == "sse41.pblendw" ||
2416                          Name.startswith("sse41.blendp") ||
2417                          Name.startswith("avx.blend.p") ||
2418                          Name == "avx2.pblendw" ||
2419                          Name.startswith("avx2.pblendd."))) {
2420       Value *Op0 = CI->getArgOperand(0);
2421       Value *Op1 = CI->getArgOperand(1);
2422       unsigned Imm = cast <ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2423       VectorType *VecTy = cast<VectorType>(CI->getType());
2424       unsigned NumElts = VecTy->getNumElements();
2425 
2426       SmallVector<uint32_t, 16> Idxs(NumElts);
2427       for (unsigned i = 0; i != NumElts; ++i)
2428         Idxs[i] = ((Imm >> (i%8)) & 1) ? i + NumElts : i;
2429 
2430       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
2431     } else if (IsX86 && (Name.startswith("avx.vinsertf128.") ||
2432                          Name == "avx2.vinserti128" ||
2433                          Name.startswith("avx512.mask.insert"))) {
2434       Value *Op0 = CI->getArgOperand(0);
2435       Value *Op1 = CI->getArgOperand(1);
2436       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2437       unsigned DstNumElts = CI->getType()->getVectorNumElements();
2438       unsigned SrcNumElts = Op1->getType()->getVectorNumElements();
2439       unsigned Scale = DstNumElts / SrcNumElts;
2440 
2441       // Mask off the high bits of the immediate value; hardware ignores those.
2442       Imm = Imm % Scale;
2443 
2444       // Extend the second operand into a vector the size of the destination.
2445       Value *UndefV = UndefValue::get(Op1->getType());
2446       SmallVector<uint32_t, 8> Idxs(DstNumElts);
2447       for (unsigned i = 0; i != SrcNumElts; ++i)
2448         Idxs[i] = i;
2449       for (unsigned i = SrcNumElts; i != DstNumElts; ++i)
2450         Idxs[i] = SrcNumElts;
2451       Rep = Builder.CreateShuffleVector(Op1, UndefV, Idxs);
2452 
2453       // Insert the second operand into the first operand.
2454 
2455       // Note that there is no guarantee that instruction lowering will actually
2456       // produce a vinsertf128 instruction for the created shuffles. In
2457       // particular, the 0 immediate case involves no lane changes, so it can
2458       // be handled as a blend.
2459 
2460       // Example of shuffle mask for 32-bit elements:
2461       // Imm = 1  <i32 0, i32 1, i32 2,  i32 3,  i32 8, i32 9, i32 10, i32 11>
2462       // Imm = 0  <i32 8, i32 9, i32 10, i32 11, i32 4, i32 5, i32 6,  i32 7 >
2463 
2464       // First fill with identify mask.
2465       for (unsigned i = 0; i != DstNumElts; ++i)
2466         Idxs[i] = i;
2467       // Then replace the elements where we need to insert.
2468       for (unsigned i = 0; i != SrcNumElts; ++i)
2469         Idxs[i + Imm * SrcNumElts] = i + DstNumElts;
2470       Rep = Builder.CreateShuffleVector(Op0, Rep, Idxs);
2471 
2472       // If the intrinsic has a mask operand, handle that.
2473       if (CI->getNumArgOperands() == 5)
2474         Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep,
2475                             CI->getArgOperand(3));
2476     } else if (IsX86 && (Name.startswith("avx.vextractf128.") ||
2477                          Name == "avx2.vextracti128" ||
2478                          Name.startswith("avx512.mask.vextract"))) {
2479       Value *Op0 = CI->getArgOperand(0);
2480       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2481       unsigned DstNumElts = CI->getType()->getVectorNumElements();
2482       unsigned SrcNumElts = Op0->getType()->getVectorNumElements();
2483       unsigned Scale = SrcNumElts / DstNumElts;
2484 
2485       // Mask off the high bits of the immediate value; hardware ignores those.
2486       Imm = Imm % Scale;
2487 
2488       // Get indexes for the subvector of the input vector.
2489       SmallVector<uint32_t, 8> Idxs(DstNumElts);
2490       for (unsigned i = 0; i != DstNumElts; ++i) {
2491         Idxs[i] = i + (Imm * DstNumElts);
2492       }
2493       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
2494 
2495       // If the intrinsic has a mask operand, handle that.
2496       if (CI->getNumArgOperands() == 4)
2497         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2498                             CI->getArgOperand(2));
2499     } else if (!IsX86 && Name == "stackprotectorcheck") {
2500       Rep = nullptr;
2501     } else if (IsX86 && (Name.startswith("avx512.mask.perm.df.") ||
2502                          Name.startswith("avx512.mask.perm.di."))) {
2503       Value *Op0 = CI->getArgOperand(0);
2504       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2505       VectorType *VecTy = cast<VectorType>(CI->getType());
2506       unsigned NumElts = VecTy->getNumElements();
2507 
2508       SmallVector<uint32_t, 8> Idxs(NumElts);
2509       for (unsigned i = 0; i != NumElts; ++i)
2510         Idxs[i] = (i & ~0x3) + ((Imm >> (2 * (i & 0x3))) & 3);
2511 
2512       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
2513 
2514       if (CI->getNumArgOperands() == 4)
2515         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2516                             CI->getArgOperand(2));
2517     } else if (IsX86 && (Name.startswith("avx.vperm2f128.") ||
2518                          Name == "avx2.vperm2i128")) {
2519       // The immediate permute control byte looks like this:
2520       //    [1:0] - select 128 bits from sources for low half of destination
2521       //    [2]   - ignore
2522       //    [3]   - zero low half of destination
2523       //    [5:4] - select 128 bits from sources for high half of destination
2524       //    [6]   - ignore
2525       //    [7]   - zero high half of destination
2526 
2527       uint8_t Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2528 
2529       unsigned NumElts = CI->getType()->getVectorNumElements();
2530       unsigned HalfSize = NumElts / 2;
2531       SmallVector<uint32_t, 8> ShuffleMask(NumElts);
2532 
2533       // Determine which operand(s) are actually in use for this instruction.
2534       Value *V0 = (Imm & 0x02) ? CI->getArgOperand(1) : CI->getArgOperand(0);
2535       Value *V1 = (Imm & 0x20) ? CI->getArgOperand(1) : CI->getArgOperand(0);
2536 
2537       // If needed, replace operands based on zero mask.
2538       V0 = (Imm & 0x08) ? ConstantAggregateZero::get(CI->getType()) : V0;
2539       V1 = (Imm & 0x80) ? ConstantAggregateZero::get(CI->getType()) : V1;
2540 
2541       // Permute low half of result.
2542       unsigned StartIndex = (Imm & 0x01) ? HalfSize : 0;
2543       for (unsigned i = 0; i < HalfSize; ++i)
2544         ShuffleMask[i] = StartIndex + i;
2545 
2546       // Permute high half of result.
2547       StartIndex = (Imm & 0x10) ? HalfSize : 0;
2548       for (unsigned i = 0; i < HalfSize; ++i)
2549         ShuffleMask[i + HalfSize] = NumElts + StartIndex + i;
2550 
2551       Rep = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2552 
2553     } else if (IsX86 && (Name.startswith("avx.vpermil.") ||
2554                          Name == "sse2.pshuf.d" ||
2555                          Name.startswith("avx512.mask.vpermil.p") ||
2556                          Name.startswith("avx512.mask.pshuf.d."))) {
2557       Value *Op0 = CI->getArgOperand(0);
2558       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2559       VectorType *VecTy = cast<VectorType>(CI->getType());
2560       unsigned NumElts = VecTy->getNumElements();
2561       // Calculate the size of each index in the immediate.
2562       unsigned IdxSize = 64 / VecTy->getScalarSizeInBits();
2563       unsigned IdxMask = ((1 << IdxSize) - 1);
2564 
2565       SmallVector<uint32_t, 8> Idxs(NumElts);
2566       // Lookup the bits for this element, wrapping around the immediate every
2567       // 8-bits. Elements are grouped into sets of 2 or 4 elements so we need
2568       // to offset by the first index of each group.
2569       for (unsigned i = 0; i != NumElts; ++i)
2570         Idxs[i] = ((Imm >> ((i * IdxSize) % 8)) & IdxMask) | (i & ~IdxMask);
2571 
2572       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
2573 
2574       if (CI->getNumArgOperands() == 4)
2575         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2576                             CI->getArgOperand(2));
2577     } else if (IsX86 && (Name == "sse2.pshufl.w" ||
2578                          Name.startswith("avx512.mask.pshufl.w."))) {
2579       Value *Op0 = CI->getArgOperand(0);
2580       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2581       unsigned NumElts = CI->getType()->getVectorNumElements();
2582 
2583       SmallVector<uint32_t, 16> Idxs(NumElts);
2584       for (unsigned l = 0; l != NumElts; l += 8) {
2585         for (unsigned i = 0; i != 4; ++i)
2586           Idxs[i + l] = ((Imm >> (2 * i)) & 0x3) + l;
2587         for (unsigned i = 4; i != 8; ++i)
2588           Idxs[i + l] = i + l;
2589       }
2590 
2591       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
2592 
2593       if (CI->getNumArgOperands() == 4)
2594         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2595                             CI->getArgOperand(2));
2596     } else if (IsX86 && (Name == "sse2.pshufh.w" ||
2597                          Name.startswith("avx512.mask.pshufh.w."))) {
2598       Value *Op0 = CI->getArgOperand(0);
2599       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2600       unsigned NumElts = CI->getType()->getVectorNumElements();
2601 
2602       SmallVector<uint32_t, 16> Idxs(NumElts);
2603       for (unsigned l = 0; l != NumElts; l += 8) {
2604         for (unsigned i = 0; i != 4; ++i)
2605           Idxs[i + l] = i + l;
2606         for (unsigned i = 0; i != 4; ++i)
2607           Idxs[i + l + 4] = ((Imm >> (2 * i)) & 0x3) + 4 + l;
2608       }
2609 
2610       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
2611 
2612       if (CI->getNumArgOperands() == 4)
2613         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2614                             CI->getArgOperand(2));
2615     } else if (IsX86 && Name.startswith("avx512.mask.shuf.p")) {
2616       Value *Op0 = CI->getArgOperand(0);
2617       Value *Op1 = CI->getArgOperand(1);
2618       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2619       unsigned NumElts = CI->getType()->getVectorNumElements();
2620 
2621       unsigned NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
2622       unsigned HalfLaneElts = NumLaneElts / 2;
2623 
2624       SmallVector<uint32_t, 16> Idxs(NumElts);
2625       for (unsigned i = 0; i != NumElts; ++i) {
2626         // Base index is the starting element of the lane.
2627         Idxs[i] = i - (i % NumLaneElts);
2628         // If we are half way through the lane switch to the other source.
2629         if ((i % NumLaneElts) >= HalfLaneElts)
2630           Idxs[i] += NumElts;
2631         // Now select the specific element. By adding HalfLaneElts bits from
2632         // the immediate. Wrapping around the immediate every 8-bits.
2633         Idxs[i] += (Imm >> ((i * HalfLaneElts) % 8)) & ((1 << HalfLaneElts) - 1);
2634       }
2635 
2636       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
2637 
2638       Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep,
2639                           CI->getArgOperand(3));
2640     } else if (IsX86 && (Name.startswith("avx512.mask.movddup") ||
2641                          Name.startswith("avx512.mask.movshdup") ||
2642                          Name.startswith("avx512.mask.movsldup"))) {
2643       Value *Op0 = CI->getArgOperand(0);
2644       unsigned NumElts = CI->getType()->getVectorNumElements();
2645       unsigned NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
2646 
2647       unsigned Offset = 0;
2648       if (Name.startswith("avx512.mask.movshdup."))
2649         Offset = 1;
2650 
2651       SmallVector<uint32_t, 16> Idxs(NumElts);
2652       for (unsigned l = 0; l != NumElts; l += NumLaneElts)
2653         for (unsigned i = 0; i != NumLaneElts; i += 2) {
2654           Idxs[i + l + 0] = i + l + Offset;
2655           Idxs[i + l + 1] = i + l + Offset;
2656         }
2657 
2658       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
2659 
2660       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2661                           CI->getArgOperand(1));
2662     } else if (IsX86 && (Name.startswith("avx512.mask.punpckl") ||
2663                          Name.startswith("avx512.mask.unpckl."))) {
2664       Value *Op0 = CI->getArgOperand(0);
2665       Value *Op1 = CI->getArgOperand(1);
2666       int NumElts = CI->getType()->getVectorNumElements();
2667       int NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
2668 
2669       SmallVector<uint32_t, 64> Idxs(NumElts);
2670       for (int l = 0; l != NumElts; l += NumLaneElts)
2671         for (int i = 0; i != NumLaneElts; ++i)
2672           Idxs[i + l] = l + (i / 2) + NumElts * (i % 2);
2673 
2674       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
2675 
2676       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2677                           CI->getArgOperand(2));
2678     } else if (IsX86 && (Name.startswith("avx512.mask.punpckh") ||
2679                          Name.startswith("avx512.mask.unpckh."))) {
2680       Value *Op0 = CI->getArgOperand(0);
2681       Value *Op1 = CI->getArgOperand(1);
2682       int NumElts = CI->getType()->getVectorNumElements();
2683       int NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
2684 
2685       SmallVector<uint32_t, 64> Idxs(NumElts);
2686       for (int l = 0; l != NumElts; l += NumLaneElts)
2687         for (int i = 0; i != NumLaneElts; ++i)
2688           Idxs[i + l] = (NumLaneElts / 2) + l + (i / 2) + NumElts * (i % 2);
2689 
2690       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
2691 
2692       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2693                           CI->getArgOperand(2));
2694     } else if (IsX86 && (Name.startswith("avx512.mask.and.") ||
2695                          Name.startswith("avx512.mask.pand."))) {
2696       VectorType *FTy = cast<VectorType>(CI->getType());
2697       VectorType *ITy = VectorType::getInteger(FTy);
2698       Rep = Builder.CreateAnd(Builder.CreateBitCast(CI->getArgOperand(0), ITy),
2699                               Builder.CreateBitCast(CI->getArgOperand(1), ITy));
2700       Rep = Builder.CreateBitCast(Rep, FTy);
2701       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2702                           CI->getArgOperand(2));
2703     } else if (IsX86 && (Name.startswith("avx512.mask.andn.") ||
2704                          Name.startswith("avx512.mask.pandn."))) {
2705       VectorType *FTy = cast<VectorType>(CI->getType());
2706       VectorType *ITy = VectorType::getInteger(FTy);
2707       Rep = Builder.CreateNot(Builder.CreateBitCast(CI->getArgOperand(0), ITy));
2708       Rep = Builder.CreateAnd(Rep,
2709                               Builder.CreateBitCast(CI->getArgOperand(1), ITy));
2710       Rep = Builder.CreateBitCast(Rep, FTy);
2711       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2712                           CI->getArgOperand(2));
2713     } else if (IsX86 && (Name.startswith("avx512.mask.or.") ||
2714                          Name.startswith("avx512.mask.por."))) {
2715       VectorType *FTy = cast<VectorType>(CI->getType());
2716       VectorType *ITy = VectorType::getInteger(FTy);
2717       Rep = Builder.CreateOr(Builder.CreateBitCast(CI->getArgOperand(0), ITy),
2718                              Builder.CreateBitCast(CI->getArgOperand(1), ITy));
2719       Rep = Builder.CreateBitCast(Rep, FTy);
2720       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2721                           CI->getArgOperand(2));
2722     } else if (IsX86 && (Name.startswith("avx512.mask.xor.") ||
2723                          Name.startswith("avx512.mask.pxor."))) {
2724       VectorType *FTy = cast<VectorType>(CI->getType());
2725       VectorType *ITy = VectorType::getInteger(FTy);
2726       Rep = Builder.CreateXor(Builder.CreateBitCast(CI->getArgOperand(0), ITy),
2727                               Builder.CreateBitCast(CI->getArgOperand(1), ITy));
2728       Rep = Builder.CreateBitCast(Rep, FTy);
2729       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2730                           CI->getArgOperand(2));
2731     } else if (IsX86 && Name.startswith("avx512.mask.padd.")) {
2732       Rep = Builder.CreateAdd(CI->getArgOperand(0), CI->getArgOperand(1));
2733       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2734                           CI->getArgOperand(2));
2735     } else if (IsX86 && Name.startswith("avx512.mask.psub.")) {
2736       Rep = Builder.CreateSub(CI->getArgOperand(0), CI->getArgOperand(1));
2737       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2738                           CI->getArgOperand(2));
2739     } else if (IsX86 && Name.startswith("avx512.mask.pmull.")) {
2740       Rep = Builder.CreateMul(CI->getArgOperand(0), CI->getArgOperand(1));
2741       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2742                           CI->getArgOperand(2));
2743     } else if (IsX86 && Name.startswith("avx512.mask.add.p")) {
2744       if (Name.endswith(".512")) {
2745         Intrinsic::ID IID;
2746         if (Name[17] == 's')
2747           IID = Intrinsic::x86_avx512_add_ps_512;
2748         else
2749           IID = Intrinsic::x86_avx512_add_pd_512;
2750 
2751         Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
2752                                  { CI->getArgOperand(0), CI->getArgOperand(1),
2753                                    CI->getArgOperand(4) });
2754       } else {
2755         Rep = Builder.CreateFAdd(CI->getArgOperand(0), CI->getArgOperand(1));
2756       }
2757       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2758                           CI->getArgOperand(2));
2759     } else if (IsX86 && Name.startswith("avx512.mask.div.p")) {
2760       if (Name.endswith(".512")) {
2761         Intrinsic::ID IID;
2762         if (Name[17] == 's')
2763           IID = Intrinsic::x86_avx512_div_ps_512;
2764         else
2765           IID = Intrinsic::x86_avx512_div_pd_512;
2766 
2767         Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
2768                                  { CI->getArgOperand(0), CI->getArgOperand(1),
2769                                    CI->getArgOperand(4) });
2770       } else {
2771         Rep = Builder.CreateFDiv(CI->getArgOperand(0), CI->getArgOperand(1));
2772       }
2773       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2774                           CI->getArgOperand(2));
2775     } else if (IsX86 && Name.startswith("avx512.mask.mul.p")) {
2776       if (Name.endswith(".512")) {
2777         Intrinsic::ID IID;
2778         if (Name[17] == 's')
2779           IID = Intrinsic::x86_avx512_mul_ps_512;
2780         else
2781           IID = Intrinsic::x86_avx512_mul_pd_512;
2782 
2783         Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
2784                                  { CI->getArgOperand(0), CI->getArgOperand(1),
2785                                    CI->getArgOperand(4) });
2786       } else {
2787         Rep = Builder.CreateFMul(CI->getArgOperand(0), CI->getArgOperand(1));
2788       }
2789       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2790                           CI->getArgOperand(2));
2791     } else if (IsX86 && Name.startswith("avx512.mask.sub.p")) {
2792       if (Name.endswith(".512")) {
2793         Intrinsic::ID IID;
2794         if (Name[17] == 's')
2795           IID = Intrinsic::x86_avx512_sub_ps_512;
2796         else
2797           IID = Intrinsic::x86_avx512_sub_pd_512;
2798 
2799         Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
2800                                  { CI->getArgOperand(0), CI->getArgOperand(1),
2801                                    CI->getArgOperand(4) });
2802       } else {
2803         Rep = Builder.CreateFSub(CI->getArgOperand(0), CI->getArgOperand(1));
2804       }
2805       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2806                           CI->getArgOperand(2));
2807     } else if (IsX86 && (Name.startswith("avx512.mask.max.p") ||
2808                          Name.startswith("avx512.mask.min.p")) &&
2809                Name.drop_front(18) == ".512") {
2810       bool IsDouble = Name[17] == 'd';
2811       bool IsMin = Name[13] == 'i';
2812       static const Intrinsic::ID MinMaxTbl[2][2] = {
2813         { Intrinsic::x86_avx512_max_ps_512, Intrinsic::x86_avx512_max_pd_512 },
2814         { Intrinsic::x86_avx512_min_ps_512, Intrinsic::x86_avx512_min_pd_512 }
2815       };
2816       Intrinsic::ID IID = MinMaxTbl[IsMin][IsDouble];
2817 
2818       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
2819                                { CI->getArgOperand(0), CI->getArgOperand(1),
2820                                  CI->getArgOperand(4) });
2821       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2822                           CI->getArgOperand(2));
2823     } else if (IsX86 && Name.startswith("avx512.mask.lzcnt.")) {
2824       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(),
2825                                                          Intrinsic::ctlz,
2826                                                          CI->getType()),
2827                                { CI->getArgOperand(0), Builder.getInt1(false) });
2828       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2829                           CI->getArgOperand(1));
2830     } else if (IsX86 && Name.startswith("avx512.mask.psll")) {
2831       bool IsImmediate = Name[16] == 'i' ||
2832                          (Name.size() > 18 && Name[18] == 'i');
2833       bool IsVariable = Name[16] == 'v';
2834       char Size = Name[16] == '.' ? Name[17] :
2835                   Name[17] == '.' ? Name[18] :
2836                   Name[18] == '.' ? Name[19] :
2837                                     Name[20];
2838 
2839       Intrinsic::ID IID;
2840       if (IsVariable && Name[17] != '.') {
2841         if (Size == 'd' && Name[17] == '2') // avx512.mask.psllv2.di
2842           IID = Intrinsic::x86_avx2_psllv_q;
2843         else if (Size == 'd' && Name[17] == '4') // avx512.mask.psllv4.di
2844           IID = Intrinsic::x86_avx2_psllv_q_256;
2845         else if (Size == 's' && Name[17] == '4') // avx512.mask.psllv4.si
2846           IID = Intrinsic::x86_avx2_psllv_d;
2847         else if (Size == 's' && Name[17] == '8') // avx512.mask.psllv8.si
2848           IID = Intrinsic::x86_avx2_psllv_d_256;
2849         else if (Size == 'h' && Name[17] == '8') // avx512.mask.psllv8.hi
2850           IID = Intrinsic::x86_avx512_psllv_w_128;
2851         else if (Size == 'h' && Name[17] == '1') // avx512.mask.psllv16.hi
2852           IID = Intrinsic::x86_avx512_psllv_w_256;
2853         else if (Name[17] == '3' && Name[18] == '2') // avx512.mask.psllv32hi
2854           IID = Intrinsic::x86_avx512_psllv_w_512;
2855         else
2856           llvm_unreachable("Unexpected size");
2857       } else if (Name.endswith(".128")) {
2858         if (Size == 'd') // avx512.mask.psll.d.128, avx512.mask.psll.di.128
2859           IID = IsImmediate ? Intrinsic::x86_sse2_pslli_d
2860                             : Intrinsic::x86_sse2_psll_d;
2861         else if (Size == 'q') // avx512.mask.psll.q.128, avx512.mask.psll.qi.128
2862           IID = IsImmediate ? Intrinsic::x86_sse2_pslli_q
2863                             : Intrinsic::x86_sse2_psll_q;
2864         else if (Size == 'w') // avx512.mask.psll.w.128, avx512.mask.psll.wi.128
2865           IID = IsImmediate ? Intrinsic::x86_sse2_pslli_w
2866                             : Intrinsic::x86_sse2_psll_w;
2867         else
2868           llvm_unreachable("Unexpected size");
2869       } else if (Name.endswith(".256")) {
2870         if (Size == 'd') // avx512.mask.psll.d.256, avx512.mask.psll.di.256
2871           IID = IsImmediate ? Intrinsic::x86_avx2_pslli_d
2872                             : Intrinsic::x86_avx2_psll_d;
2873         else if (Size == 'q') // avx512.mask.psll.q.256, avx512.mask.psll.qi.256
2874           IID = IsImmediate ? Intrinsic::x86_avx2_pslli_q
2875                             : Intrinsic::x86_avx2_psll_q;
2876         else if (Size == 'w') // avx512.mask.psll.w.256, avx512.mask.psll.wi.256
2877           IID = IsImmediate ? Intrinsic::x86_avx2_pslli_w
2878                             : Intrinsic::x86_avx2_psll_w;
2879         else
2880           llvm_unreachable("Unexpected size");
2881       } else {
2882         if (Size == 'd') // psll.di.512, pslli.d, psll.d, psllv.d.512
2883           IID = IsImmediate ? Intrinsic::x86_avx512_pslli_d_512 :
2884                 IsVariable  ? Intrinsic::x86_avx512_psllv_d_512 :
2885                               Intrinsic::x86_avx512_psll_d_512;
2886         else if (Size == 'q') // psll.qi.512, pslli.q, psll.q, psllv.q.512
2887           IID = IsImmediate ? Intrinsic::x86_avx512_pslli_q_512 :
2888                 IsVariable  ? Intrinsic::x86_avx512_psllv_q_512 :
2889                               Intrinsic::x86_avx512_psll_q_512;
2890         else if (Size == 'w') // psll.wi.512, pslli.w, psll.w
2891           IID = IsImmediate ? Intrinsic::x86_avx512_pslli_w_512
2892                             : Intrinsic::x86_avx512_psll_w_512;
2893         else
2894           llvm_unreachable("Unexpected size");
2895       }
2896 
2897       Rep = UpgradeX86MaskedShift(Builder, *CI, IID);
2898     } else if (IsX86 && Name.startswith("avx512.mask.psrl")) {
2899       bool IsImmediate = Name[16] == 'i' ||
2900                          (Name.size() > 18 && Name[18] == 'i');
2901       bool IsVariable = Name[16] == 'v';
2902       char Size = Name[16] == '.' ? Name[17] :
2903                   Name[17] == '.' ? Name[18] :
2904                   Name[18] == '.' ? Name[19] :
2905                                     Name[20];
2906 
2907       Intrinsic::ID IID;
2908       if (IsVariable && Name[17] != '.') {
2909         if (Size == 'd' && Name[17] == '2') // avx512.mask.psrlv2.di
2910           IID = Intrinsic::x86_avx2_psrlv_q;
2911         else if (Size == 'd' && Name[17] == '4') // avx512.mask.psrlv4.di
2912           IID = Intrinsic::x86_avx2_psrlv_q_256;
2913         else if (Size == 's' && Name[17] == '4') // avx512.mask.psrlv4.si
2914           IID = Intrinsic::x86_avx2_psrlv_d;
2915         else if (Size == 's' && Name[17] == '8') // avx512.mask.psrlv8.si
2916           IID = Intrinsic::x86_avx2_psrlv_d_256;
2917         else if (Size == 'h' && Name[17] == '8') // avx512.mask.psrlv8.hi
2918           IID = Intrinsic::x86_avx512_psrlv_w_128;
2919         else if (Size == 'h' && Name[17] == '1') // avx512.mask.psrlv16.hi
2920           IID = Intrinsic::x86_avx512_psrlv_w_256;
2921         else if (Name[17] == '3' && Name[18] == '2') // avx512.mask.psrlv32hi
2922           IID = Intrinsic::x86_avx512_psrlv_w_512;
2923         else
2924           llvm_unreachable("Unexpected size");
2925       } else if (Name.endswith(".128")) {
2926         if (Size == 'd') // avx512.mask.psrl.d.128, avx512.mask.psrl.di.128
2927           IID = IsImmediate ? Intrinsic::x86_sse2_psrli_d
2928                             : Intrinsic::x86_sse2_psrl_d;
2929         else if (Size == 'q') // avx512.mask.psrl.q.128, avx512.mask.psrl.qi.128
2930           IID = IsImmediate ? Intrinsic::x86_sse2_psrli_q
2931                             : Intrinsic::x86_sse2_psrl_q;
2932         else if (Size == 'w') // avx512.mask.psrl.w.128, avx512.mask.psrl.wi.128
2933           IID = IsImmediate ? Intrinsic::x86_sse2_psrli_w
2934                             : Intrinsic::x86_sse2_psrl_w;
2935         else
2936           llvm_unreachable("Unexpected size");
2937       } else if (Name.endswith(".256")) {
2938         if (Size == 'd') // avx512.mask.psrl.d.256, avx512.mask.psrl.di.256
2939           IID = IsImmediate ? Intrinsic::x86_avx2_psrli_d
2940                             : Intrinsic::x86_avx2_psrl_d;
2941         else if (Size == 'q') // avx512.mask.psrl.q.256, avx512.mask.psrl.qi.256
2942           IID = IsImmediate ? Intrinsic::x86_avx2_psrli_q
2943                             : Intrinsic::x86_avx2_psrl_q;
2944         else if (Size == 'w') // avx512.mask.psrl.w.256, avx512.mask.psrl.wi.256
2945           IID = IsImmediate ? Intrinsic::x86_avx2_psrli_w
2946                             : Intrinsic::x86_avx2_psrl_w;
2947         else
2948           llvm_unreachable("Unexpected size");
2949       } else {
2950         if (Size == 'd') // psrl.di.512, psrli.d, psrl.d, psrl.d.512
2951           IID = IsImmediate ? Intrinsic::x86_avx512_psrli_d_512 :
2952                 IsVariable  ? Intrinsic::x86_avx512_psrlv_d_512 :
2953                               Intrinsic::x86_avx512_psrl_d_512;
2954         else if (Size == 'q') // psrl.qi.512, psrli.q, psrl.q, psrl.q.512
2955           IID = IsImmediate ? Intrinsic::x86_avx512_psrli_q_512 :
2956                 IsVariable  ? Intrinsic::x86_avx512_psrlv_q_512 :
2957                               Intrinsic::x86_avx512_psrl_q_512;
2958         else if (Size == 'w') // psrl.wi.512, psrli.w, psrl.w)
2959           IID = IsImmediate ? Intrinsic::x86_avx512_psrli_w_512
2960                             : Intrinsic::x86_avx512_psrl_w_512;
2961         else
2962           llvm_unreachable("Unexpected size");
2963       }
2964 
2965       Rep = UpgradeX86MaskedShift(Builder, *CI, IID);
2966     } else if (IsX86 && Name.startswith("avx512.mask.psra")) {
2967       bool IsImmediate = Name[16] == 'i' ||
2968                          (Name.size() > 18 && Name[18] == 'i');
2969       bool IsVariable = Name[16] == 'v';
2970       char Size = Name[16] == '.' ? Name[17] :
2971                   Name[17] == '.' ? Name[18] :
2972                   Name[18] == '.' ? Name[19] :
2973                                     Name[20];
2974 
2975       Intrinsic::ID IID;
2976       if (IsVariable && Name[17] != '.') {
2977         if (Size == 's' && Name[17] == '4') // avx512.mask.psrav4.si
2978           IID = Intrinsic::x86_avx2_psrav_d;
2979         else if (Size == 's' && Name[17] == '8') // avx512.mask.psrav8.si
2980           IID = Intrinsic::x86_avx2_psrav_d_256;
2981         else if (Size == 'h' && Name[17] == '8') // avx512.mask.psrav8.hi
2982           IID = Intrinsic::x86_avx512_psrav_w_128;
2983         else if (Size == 'h' && Name[17] == '1') // avx512.mask.psrav16.hi
2984           IID = Intrinsic::x86_avx512_psrav_w_256;
2985         else if (Name[17] == '3' && Name[18] == '2') // avx512.mask.psrav32hi
2986           IID = Intrinsic::x86_avx512_psrav_w_512;
2987         else
2988           llvm_unreachable("Unexpected size");
2989       } else if (Name.endswith(".128")) {
2990         if (Size == 'd') // avx512.mask.psra.d.128, avx512.mask.psra.di.128
2991           IID = IsImmediate ? Intrinsic::x86_sse2_psrai_d
2992                             : Intrinsic::x86_sse2_psra_d;
2993         else if (Size == 'q') // avx512.mask.psra.q.128, avx512.mask.psra.qi.128
2994           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_q_128 :
2995                 IsVariable  ? Intrinsic::x86_avx512_psrav_q_128 :
2996                               Intrinsic::x86_avx512_psra_q_128;
2997         else if (Size == 'w') // avx512.mask.psra.w.128, avx512.mask.psra.wi.128
2998           IID = IsImmediate ? Intrinsic::x86_sse2_psrai_w
2999                             : Intrinsic::x86_sse2_psra_w;
3000         else
3001           llvm_unreachable("Unexpected size");
3002       } else if (Name.endswith(".256")) {
3003         if (Size == 'd') // avx512.mask.psra.d.256, avx512.mask.psra.di.256
3004           IID = IsImmediate ? Intrinsic::x86_avx2_psrai_d
3005                             : Intrinsic::x86_avx2_psra_d;
3006         else if (Size == 'q') // avx512.mask.psra.q.256, avx512.mask.psra.qi.256
3007           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_q_256 :
3008                 IsVariable  ? Intrinsic::x86_avx512_psrav_q_256 :
3009                               Intrinsic::x86_avx512_psra_q_256;
3010         else if (Size == 'w') // avx512.mask.psra.w.256, avx512.mask.psra.wi.256
3011           IID = IsImmediate ? Intrinsic::x86_avx2_psrai_w
3012                             : Intrinsic::x86_avx2_psra_w;
3013         else
3014           llvm_unreachable("Unexpected size");
3015       } else {
3016         if (Size == 'd') // psra.di.512, psrai.d, psra.d, psrav.d.512
3017           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_d_512 :
3018                 IsVariable  ? Intrinsic::x86_avx512_psrav_d_512 :
3019                               Intrinsic::x86_avx512_psra_d_512;
3020         else if (Size == 'q') // psra.qi.512, psrai.q, psra.q
3021           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_q_512 :
3022                 IsVariable  ? Intrinsic::x86_avx512_psrav_q_512 :
3023                               Intrinsic::x86_avx512_psra_q_512;
3024         else if (Size == 'w') // psra.wi.512, psrai.w, psra.w
3025           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_w_512
3026                             : Intrinsic::x86_avx512_psra_w_512;
3027         else
3028           llvm_unreachable("Unexpected size");
3029       }
3030 
3031       Rep = UpgradeX86MaskedShift(Builder, *CI, IID);
3032     } else if (IsX86 && Name.startswith("avx512.mask.move.s")) {
3033       Rep = upgradeMaskedMove(Builder, *CI);
3034     } else if (IsX86 && Name.startswith("avx512.cvtmask2")) {
3035       Rep = UpgradeMaskToInt(Builder, *CI);
3036     } else if (IsX86 && Name.endswith(".movntdqa")) {
3037       Module *M = F->getParent();
3038       MDNode *Node = MDNode::get(
3039           C, ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
3040 
3041       Value *Ptr = CI->getArgOperand(0);
3042       VectorType *VTy = cast<VectorType>(CI->getType());
3043 
3044       // Convert the type of the pointer to a pointer to the stored type.
3045       Value *BC =
3046           Builder.CreateBitCast(Ptr, PointerType::getUnqual(VTy), "cast");
3047       LoadInst *LI = Builder.CreateAlignedLoad(VTy, BC, VTy->getBitWidth() / 8);
3048       LI->setMetadata(M->getMDKindID("nontemporal"), Node);
3049       Rep = LI;
3050     } else if (IsX86 && (Name.startswith("fma.vfmadd.") ||
3051                          Name.startswith("fma.vfmsub.") ||
3052                          Name.startswith("fma.vfnmadd.") ||
3053                          Name.startswith("fma.vfnmsub."))) {
3054       bool NegMul = Name[6] == 'n';
3055       bool NegAcc = NegMul ? Name[8] == 's' : Name[7] == 's';
3056       bool IsScalar = NegMul ? Name[12] == 's' : Name[11] == 's';
3057 
3058       Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3059                        CI->getArgOperand(2) };
3060 
3061       if (IsScalar) {
3062         Ops[0] = Builder.CreateExtractElement(Ops[0], (uint64_t)0);
3063         Ops[1] = Builder.CreateExtractElement(Ops[1], (uint64_t)0);
3064         Ops[2] = Builder.CreateExtractElement(Ops[2], (uint64_t)0);
3065       }
3066 
3067       if (NegMul && !IsScalar)
3068         Ops[0] = Builder.CreateFNeg(Ops[0]);
3069       if (NegMul && IsScalar)
3070         Ops[1] = Builder.CreateFNeg(Ops[1]);
3071       if (NegAcc)
3072         Ops[2] = Builder.CreateFNeg(Ops[2]);
3073 
3074       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(),
3075                                                          Intrinsic::fma,
3076                                                          Ops[0]->getType()),
3077                                Ops);
3078 
3079       if (IsScalar)
3080         Rep = Builder.CreateInsertElement(CI->getArgOperand(0), Rep,
3081                                           (uint64_t)0);
3082     } else if (IsX86 && Name.startswith("fma4.vfmadd.s")) {
3083       Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3084                        CI->getArgOperand(2) };
3085 
3086       Ops[0] = Builder.CreateExtractElement(Ops[0], (uint64_t)0);
3087       Ops[1] = Builder.CreateExtractElement(Ops[1], (uint64_t)0);
3088       Ops[2] = Builder.CreateExtractElement(Ops[2], (uint64_t)0);
3089 
3090       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(),
3091                                                          Intrinsic::fma,
3092                                                          Ops[0]->getType()),
3093                                Ops);
3094 
3095       Rep = Builder.CreateInsertElement(Constant::getNullValue(CI->getType()),
3096                                         Rep, (uint64_t)0);
3097     } else if (IsX86 && (Name.startswith("avx512.mask.vfmadd.s") ||
3098                          Name.startswith("avx512.maskz.vfmadd.s") ||
3099                          Name.startswith("avx512.mask3.vfmadd.s") ||
3100                          Name.startswith("avx512.mask3.vfmsub.s") ||
3101                          Name.startswith("avx512.mask3.vfnmsub.s"))) {
3102       bool IsMask3 = Name[11] == '3';
3103       bool IsMaskZ = Name[11] == 'z';
3104       // Drop the "avx512.mask." to make it easier.
3105       Name = Name.drop_front(IsMask3 || IsMaskZ ? 13 : 12);
3106       bool NegMul = Name[2] == 'n';
3107       bool NegAcc = NegMul ? Name[4] == 's' : Name[3] == 's';
3108 
3109       Value *A = CI->getArgOperand(0);
3110       Value *B = CI->getArgOperand(1);
3111       Value *C = CI->getArgOperand(2);
3112 
3113       if (NegMul && (IsMask3 || IsMaskZ))
3114         A = Builder.CreateFNeg(A);
3115       if (NegMul && !(IsMask3 || IsMaskZ))
3116         B = Builder.CreateFNeg(B);
3117       if (NegAcc)
3118         C = Builder.CreateFNeg(C);
3119 
3120       A = Builder.CreateExtractElement(A, (uint64_t)0);
3121       B = Builder.CreateExtractElement(B, (uint64_t)0);
3122       C = Builder.CreateExtractElement(C, (uint64_t)0);
3123 
3124       if (!isa<ConstantInt>(CI->getArgOperand(4)) ||
3125           cast<ConstantInt>(CI->getArgOperand(4))->getZExtValue() != 4) {
3126         Value *Ops[] = { A, B, C, CI->getArgOperand(4) };
3127 
3128         Intrinsic::ID IID;
3129         if (Name.back() == 'd')
3130           IID = Intrinsic::x86_avx512_vfmadd_f64;
3131         else
3132           IID = Intrinsic::x86_avx512_vfmadd_f32;
3133         Function *FMA = Intrinsic::getDeclaration(CI->getModule(), IID);
3134         Rep = Builder.CreateCall(FMA, Ops);
3135       } else {
3136         Function *FMA = Intrinsic::getDeclaration(CI->getModule(),
3137                                                   Intrinsic::fma,
3138                                                   A->getType());
3139         Rep = Builder.CreateCall(FMA, { A, B, C });
3140       }
3141 
3142       Value *PassThru = IsMaskZ ? Constant::getNullValue(Rep->getType()) :
3143                         IsMask3 ? C : A;
3144 
3145       // For Mask3 with NegAcc, we need to create a new extractelement that
3146       // avoids the negation above.
3147       if (NegAcc && IsMask3)
3148         PassThru = Builder.CreateExtractElement(CI->getArgOperand(2),
3149                                                 (uint64_t)0);
3150 
3151       Rep = EmitX86ScalarSelect(Builder, CI->getArgOperand(3),
3152                                 Rep, PassThru);
3153       Rep = Builder.CreateInsertElement(CI->getArgOperand(IsMask3 ? 2 : 0),
3154                                         Rep, (uint64_t)0);
3155     } else if (IsX86 && (Name.startswith("avx512.mask.vfmadd.p") ||
3156                          Name.startswith("avx512.mask.vfnmadd.p") ||
3157                          Name.startswith("avx512.mask.vfnmsub.p") ||
3158                          Name.startswith("avx512.mask3.vfmadd.p") ||
3159                          Name.startswith("avx512.mask3.vfmsub.p") ||
3160                          Name.startswith("avx512.mask3.vfnmsub.p") ||
3161                          Name.startswith("avx512.maskz.vfmadd.p"))) {
3162       bool IsMask3 = Name[11] == '3';
3163       bool IsMaskZ = Name[11] == 'z';
3164       // Drop the "avx512.mask." to make it easier.
3165       Name = Name.drop_front(IsMask3 || IsMaskZ ? 13 : 12);
3166       bool NegMul = Name[2] == 'n';
3167       bool NegAcc = NegMul ? Name[4] == 's' : Name[3] == 's';
3168 
3169       Value *A = CI->getArgOperand(0);
3170       Value *B = CI->getArgOperand(1);
3171       Value *C = CI->getArgOperand(2);
3172 
3173       if (NegMul && (IsMask3 || IsMaskZ))
3174         A = Builder.CreateFNeg(A);
3175       if (NegMul && !(IsMask3 || IsMaskZ))
3176         B = Builder.CreateFNeg(B);
3177       if (NegAcc)
3178         C = Builder.CreateFNeg(C);
3179 
3180       if (CI->getNumArgOperands() == 5 &&
3181           (!isa<ConstantInt>(CI->getArgOperand(4)) ||
3182            cast<ConstantInt>(CI->getArgOperand(4))->getZExtValue() != 4)) {
3183         Intrinsic::ID IID;
3184         // Check the character before ".512" in string.
3185         if (Name[Name.size()-5] == 's')
3186           IID = Intrinsic::x86_avx512_vfmadd_ps_512;
3187         else
3188           IID = Intrinsic::x86_avx512_vfmadd_pd_512;
3189 
3190         Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
3191                                  { A, B, C, CI->getArgOperand(4) });
3192       } else {
3193         Function *FMA = Intrinsic::getDeclaration(CI->getModule(),
3194                                                   Intrinsic::fma,
3195                                                   A->getType());
3196         Rep = Builder.CreateCall(FMA, { A, B, C });
3197       }
3198 
3199       Value *PassThru = IsMaskZ ? llvm::Constant::getNullValue(CI->getType()) :
3200                         IsMask3 ? CI->getArgOperand(2) :
3201                                   CI->getArgOperand(0);
3202 
3203       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
3204     } else if (IsX86 && (Name.startswith("fma.vfmaddsub.p") ||
3205                          Name.startswith("fma.vfmsubadd.p"))) {
3206       bool IsSubAdd = Name[7] == 's';
3207       int NumElts = CI->getType()->getVectorNumElements();
3208 
3209       Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3210                        CI->getArgOperand(2) };
3211 
3212       Function *FMA = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::fma,
3213                                                 Ops[0]->getType());
3214       Value *Odd = Builder.CreateCall(FMA, Ops);
3215       Ops[2] = Builder.CreateFNeg(Ops[2]);
3216       Value *Even = Builder.CreateCall(FMA, Ops);
3217 
3218       if (IsSubAdd)
3219         std::swap(Even, Odd);
3220 
3221       SmallVector<uint32_t, 32> Idxs(NumElts);
3222       for (int i = 0; i != NumElts; ++i)
3223         Idxs[i] = i + (i % 2) * NumElts;
3224 
3225       Rep = Builder.CreateShuffleVector(Even, Odd, Idxs);
3226     } else if (IsX86 && (Name.startswith("avx512.mask.vfmaddsub.p") ||
3227                          Name.startswith("avx512.mask3.vfmaddsub.p") ||
3228                          Name.startswith("avx512.maskz.vfmaddsub.p") ||
3229                          Name.startswith("avx512.mask3.vfmsubadd.p"))) {
3230       bool IsMask3 = Name[11] == '3';
3231       bool IsMaskZ = Name[11] == 'z';
3232       // Drop the "avx512.mask." to make it easier.
3233       Name = Name.drop_front(IsMask3 || IsMaskZ ? 13 : 12);
3234       bool IsSubAdd = Name[3] == 's';
3235       if (CI->getNumArgOperands() == 5 &&
3236           (!isa<ConstantInt>(CI->getArgOperand(4)) ||
3237            cast<ConstantInt>(CI->getArgOperand(4))->getZExtValue() != 4)) {
3238         Intrinsic::ID IID;
3239         // Check the character before ".512" in string.
3240         if (Name[Name.size()-5] == 's')
3241           IID = Intrinsic::x86_avx512_vfmaddsub_ps_512;
3242         else
3243           IID = Intrinsic::x86_avx512_vfmaddsub_pd_512;
3244 
3245         Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3246                          CI->getArgOperand(2), CI->getArgOperand(4) };
3247         if (IsSubAdd)
3248           Ops[2] = Builder.CreateFNeg(Ops[2]);
3249 
3250         Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
3251                                  {CI->getArgOperand(0), CI->getArgOperand(1),
3252                                   CI->getArgOperand(2), CI->getArgOperand(4)});
3253       } else {
3254         int NumElts = CI->getType()->getVectorNumElements();
3255 
3256         Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3257                          CI->getArgOperand(2) };
3258 
3259         Function *FMA = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::fma,
3260                                                   Ops[0]->getType());
3261         Value *Odd = Builder.CreateCall(FMA, Ops);
3262         Ops[2] = Builder.CreateFNeg(Ops[2]);
3263         Value *Even = Builder.CreateCall(FMA, Ops);
3264 
3265         if (IsSubAdd)
3266           std::swap(Even, Odd);
3267 
3268         SmallVector<uint32_t, 32> Idxs(NumElts);
3269         for (int i = 0; i != NumElts; ++i)
3270           Idxs[i] = i + (i % 2) * NumElts;
3271 
3272         Rep = Builder.CreateShuffleVector(Even, Odd, Idxs);
3273       }
3274 
3275       Value *PassThru = IsMaskZ ? llvm::Constant::getNullValue(CI->getType()) :
3276                         IsMask3 ? CI->getArgOperand(2) :
3277                                   CI->getArgOperand(0);
3278 
3279       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
3280     } else if (IsX86 && (Name.startswith("avx512.mask.pternlog.") ||
3281                          Name.startswith("avx512.maskz.pternlog."))) {
3282       bool ZeroMask = Name[11] == 'z';
3283       unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
3284       unsigned EltWidth = CI->getType()->getScalarSizeInBits();
3285       Intrinsic::ID IID;
3286       if (VecWidth == 128 && EltWidth == 32)
3287         IID = Intrinsic::x86_avx512_pternlog_d_128;
3288       else if (VecWidth == 256 && EltWidth == 32)
3289         IID = Intrinsic::x86_avx512_pternlog_d_256;
3290       else if (VecWidth == 512 && EltWidth == 32)
3291         IID = Intrinsic::x86_avx512_pternlog_d_512;
3292       else if (VecWidth == 128 && EltWidth == 64)
3293         IID = Intrinsic::x86_avx512_pternlog_q_128;
3294       else if (VecWidth == 256 && EltWidth == 64)
3295         IID = Intrinsic::x86_avx512_pternlog_q_256;
3296       else if (VecWidth == 512 && EltWidth == 64)
3297         IID = Intrinsic::x86_avx512_pternlog_q_512;
3298       else
3299         llvm_unreachable("Unexpected intrinsic");
3300 
3301       Value *Args[] = { CI->getArgOperand(0) , CI->getArgOperand(1),
3302                         CI->getArgOperand(2), CI->getArgOperand(3) };
3303       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
3304                                Args);
3305       Value *PassThru = ZeroMask ? ConstantAggregateZero::get(CI->getType())
3306                                  : CI->getArgOperand(0);
3307       Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep, PassThru);
3308     } else if (IsX86 && (Name.startswith("avx512.mask.vpmadd52") ||
3309                          Name.startswith("avx512.maskz.vpmadd52"))) {
3310       bool ZeroMask = Name[11] == 'z';
3311       bool High = Name[20] == 'h' || Name[21] == 'h';
3312       unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
3313       Intrinsic::ID IID;
3314       if (VecWidth == 128 && !High)
3315         IID = Intrinsic::x86_avx512_vpmadd52l_uq_128;
3316       else if (VecWidth == 256 && !High)
3317         IID = Intrinsic::x86_avx512_vpmadd52l_uq_256;
3318       else if (VecWidth == 512 && !High)
3319         IID = Intrinsic::x86_avx512_vpmadd52l_uq_512;
3320       else if (VecWidth == 128 && High)
3321         IID = Intrinsic::x86_avx512_vpmadd52h_uq_128;
3322       else if (VecWidth == 256 && High)
3323         IID = Intrinsic::x86_avx512_vpmadd52h_uq_256;
3324       else if (VecWidth == 512 && High)
3325         IID = Intrinsic::x86_avx512_vpmadd52h_uq_512;
3326       else
3327         llvm_unreachable("Unexpected intrinsic");
3328 
3329       Value *Args[] = { CI->getArgOperand(0) , CI->getArgOperand(1),
3330                         CI->getArgOperand(2) };
3331       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
3332                                Args);
3333       Value *PassThru = ZeroMask ? ConstantAggregateZero::get(CI->getType())
3334                                  : CI->getArgOperand(0);
3335       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
3336     } else if (IsX86 && (Name.startswith("avx512.mask.vpermi2var.") ||
3337                          Name.startswith("avx512.mask.vpermt2var.") ||
3338                          Name.startswith("avx512.maskz.vpermt2var."))) {
3339       bool ZeroMask = Name[11] == 'z';
3340       bool IndexForm = Name[17] == 'i';
3341       Rep = UpgradeX86VPERMT2Intrinsics(Builder, *CI, ZeroMask, IndexForm);
3342     } else if (IsX86 && (Name.startswith("avx512.mask.vpdpbusd.") ||
3343                          Name.startswith("avx512.maskz.vpdpbusd.") ||
3344                          Name.startswith("avx512.mask.vpdpbusds.") ||
3345                          Name.startswith("avx512.maskz.vpdpbusds."))) {
3346       bool ZeroMask = Name[11] == 'z';
3347       bool IsSaturating = Name[ZeroMask ? 21 : 20] == 's';
3348       unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
3349       Intrinsic::ID IID;
3350       if (VecWidth == 128 && !IsSaturating)
3351         IID = Intrinsic::x86_avx512_vpdpbusd_128;
3352       else if (VecWidth == 256 && !IsSaturating)
3353         IID = Intrinsic::x86_avx512_vpdpbusd_256;
3354       else if (VecWidth == 512 && !IsSaturating)
3355         IID = Intrinsic::x86_avx512_vpdpbusd_512;
3356       else if (VecWidth == 128 && IsSaturating)
3357         IID = Intrinsic::x86_avx512_vpdpbusds_128;
3358       else if (VecWidth == 256 && IsSaturating)
3359         IID = Intrinsic::x86_avx512_vpdpbusds_256;
3360       else if (VecWidth == 512 && IsSaturating)
3361         IID = Intrinsic::x86_avx512_vpdpbusds_512;
3362       else
3363         llvm_unreachable("Unexpected intrinsic");
3364 
3365       Value *Args[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3366                         CI->getArgOperand(2)  };
3367       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
3368                                Args);
3369       Value *PassThru = ZeroMask ? ConstantAggregateZero::get(CI->getType())
3370                                  : CI->getArgOperand(0);
3371       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
3372     } else if (IsX86 && (Name.startswith("avx512.mask.vpdpwssd.") ||
3373                          Name.startswith("avx512.maskz.vpdpwssd.") ||
3374                          Name.startswith("avx512.mask.vpdpwssds.") ||
3375                          Name.startswith("avx512.maskz.vpdpwssds."))) {
3376       bool ZeroMask = Name[11] == 'z';
3377       bool IsSaturating = Name[ZeroMask ? 21 : 20] == 's';
3378       unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
3379       Intrinsic::ID IID;
3380       if (VecWidth == 128 && !IsSaturating)
3381         IID = Intrinsic::x86_avx512_vpdpwssd_128;
3382       else if (VecWidth == 256 && !IsSaturating)
3383         IID = Intrinsic::x86_avx512_vpdpwssd_256;
3384       else if (VecWidth == 512 && !IsSaturating)
3385         IID = Intrinsic::x86_avx512_vpdpwssd_512;
3386       else if (VecWidth == 128 && IsSaturating)
3387         IID = Intrinsic::x86_avx512_vpdpwssds_128;
3388       else if (VecWidth == 256 && IsSaturating)
3389         IID = Intrinsic::x86_avx512_vpdpwssds_256;
3390       else if (VecWidth == 512 && IsSaturating)
3391         IID = Intrinsic::x86_avx512_vpdpwssds_512;
3392       else
3393         llvm_unreachable("Unexpected intrinsic");
3394 
3395       Value *Args[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3396                         CI->getArgOperand(2)  };
3397       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
3398                                Args);
3399       Value *PassThru = ZeroMask ? ConstantAggregateZero::get(CI->getType())
3400                                  : CI->getArgOperand(0);
3401       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
3402     } else if (IsX86 && (Name == "addcarryx.u32" || Name == "addcarryx.u64" ||
3403                          Name == "addcarry.u32" || Name == "addcarry.u64" ||
3404                          Name == "subborrow.u32" || Name == "subborrow.u64")) {
3405       Intrinsic::ID IID;
3406       if (Name[0] == 'a' && Name.back() == '2')
3407         IID = Intrinsic::x86_addcarry_32;
3408       else if (Name[0] == 'a' && Name.back() == '4')
3409         IID = Intrinsic::x86_addcarry_64;
3410       else if (Name[0] == 's' && Name.back() == '2')
3411         IID = Intrinsic::x86_subborrow_32;
3412       else if (Name[0] == 's' && Name.back() == '4')
3413         IID = Intrinsic::x86_subborrow_64;
3414       else
3415         llvm_unreachable("Unexpected intrinsic");
3416 
3417       // Make a call with 3 operands.
3418       Value *Args[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3419                         CI->getArgOperand(2)};
3420       Value *NewCall = Builder.CreateCall(
3421                                 Intrinsic::getDeclaration(CI->getModule(), IID),
3422                                 Args);
3423 
3424       // Extract the second result and store it.
3425       Value *Data = Builder.CreateExtractValue(NewCall, 1);
3426       // Cast the pointer to the right type.
3427       Value *Ptr = Builder.CreateBitCast(CI->getArgOperand(3),
3428                                  llvm::PointerType::getUnqual(Data->getType()));
3429       Builder.CreateAlignedStore(Data, Ptr, 1);
3430       // Replace the original call result with the first result of the new call.
3431       Value *CF = Builder.CreateExtractValue(NewCall, 0);
3432 
3433       CI->replaceAllUsesWith(CF);
3434       Rep = nullptr;
3435     } else if (IsX86 && Name.startswith("avx512.mask.") &&
3436                upgradeAVX512MaskToSelect(Name, Builder, *CI, Rep)) {
3437       // Rep will be updated by the call in the condition.
3438     } else if (IsNVVM && (Name == "abs.i" || Name == "abs.ll")) {
3439       Value *Arg = CI->getArgOperand(0);
3440       Value *Neg = Builder.CreateNeg(Arg, "neg");
3441       Value *Cmp = Builder.CreateICmpSGE(
3442           Arg, llvm::Constant::getNullValue(Arg->getType()), "abs.cond");
3443       Rep = Builder.CreateSelect(Cmp, Arg, Neg, "abs");
3444     } else if (IsNVVM && (Name.startswith("atomic.load.add.f32.p") ||
3445                           Name.startswith("atomic.load.add.f64.p"))) {
3446       Value *Ptr = CI->getArgOperand(0);
3447       Value *Val = CI->getArgOperand(1);
3448       Rep = Builder.CreateAtomicRMW(AtomicRMWInst::FAdd, Ptr, Val,
3449                                     AtomicOrdering::SequentiallyConsistent);
3450     } else if (IsNVVM && (Name == "max.i" || Name == "max.ll" ||
3451                           Name == "max.ui" || Name == "max.ull")) {
3452       Value *Arg0 = CI->getArgOperand(0);
3453       Value *Arg1 = CI->getArgOperand(1);
3454       Value *Cmp = Name.endswith(".ui") || Name.endswith(".ull")
3455                        ? Builder.CreateICmpUGE(Arg0, Arg1, "max.cond")
3456                        : Builder.CreateICmpSGE(Arg0, Arg1, "max.cond");
3457       Rep = Builder.CreateSelect(Cmp, Arg0, Arg1, "max");
3458     } else if (IsNVVM && (Name == "min.i" || Name == "min.ll" ||
3459                           Name == "min.ui" || Name == "min.ull")) {
3460       Value *Arg0 = CI->getArgOperand(0);
3461       Value *Arg1 = CI->getArgOperand(1);
3462       Value *Cmp = Name.endswith(".ui") || Name.endswith(".ull")
3463                        ? Builder.CreateICmpULE(Arg0, Arg1, "min.cond")
3464                        : Builder.CreateICmpSLE(Arg0, Arg1, "min.cond");
3465       Rep = Builder.CreateSelect(Cmp, Arg0, Arg1, "min");
3466     } else if (IsNVVM && Name == "clz.ll") {
3467       // llvm.nvvm.clz.ll returns an i32, but llvm.ctlz.i64 and returns an i64.
3468       Value *Arg = CI->getArgOperand(0);
3469       Value *Ctlz = Builder.CreateCall(
3470           Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
3471                                     {Arg->getType()}),
3472           {Arg, Builder.getFalse()}, "ctlz");
3473       Rep = Builder.CreateTrunc(Ctlz, Builder.getInt32Ty(), "ctlz.trunc");
3474     } else if (IsNVVM && Name == "popc.ll") {
3475       // llvm.nvvm.popc.ll returns an i32, but llvm.ctpop.i64 and returns an
3476       // i64.
3477       Value *Arg = CI->getArgOperand(0);
3478       Value *Popc = Builder.CreateCall(
3479           Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop,
3480                                     {Arg->getType()}),
3481           Arg, "ctpop");
3482       Rep = Builder.CreateTrunc(Popc, Builder.getInt32Ty(), "ctpop.trunc");
3483     } else if (IsNVVM && Name == "h2f") {
3484       Rep = Builder.CreateCall(Intrinsic::getDeclaration(
3485                                    F->getParent(), Intrinsic::convert_from_fp16,
3486                                    {Builder.getFloatTy()}),
3487                                CI->getArgOperand(0), "h2f");
3488     } else {
3489       llvm_unreachable("Unknown function for CallInst upgrade.");
3490     }
3491 
3492     if (Rep)
3493       CI->replaceAllUsesWith(Rep);
3494     CI->eraseFromParent();
3495     return;
3496   }
3497 
3498   const auto &DefaultCase = [&NewFn, &CI]() -> void {
3499     // Handle generic mangling change, but nothing else
3500     assert(
3501         (CI->getCalledFunction()->getName() != NewFn->getName()) &&
3502         "Unknown function for CallInst upgrade and isn't just a name change");
3503     CI->setCalledFunction(NewFn);
3504   };
3505   CallInst *NewCall = nullptr;
3506   switch (NewFn->getIntrinsicID()) {
3507   default: {
3508     DefaultCase();
3509     return;
3510   }
3511   case Intrinsic::experimental_vector_reduce_v2_fmul: {
3512     SmallVector<Value *, 2> Args;
3513     if (CI->isFast())
3514       Args.push_back(ConstantFP::get(CI->getOperand(0)->getType(), 1.0));
3515     else
3516       Args.push_back(CI->getOperand(0));
3517     Args.push_back(CI->getOperand(1));
3518     NewCall = Builder.CreateCall(NewFn, Args);
3519     cast<Instruction>(NewCall)->copyFastMathFlags(CI);
3520     break;
3521   }
3522   case Intrinsic::experimental_vector_reduce_v2_fadd: {
3523     SmallVector<Value *, 2> Args;
3524     if (CI->isFast())
3525       Args.push_back(Constant::getNullValue(CI->getOperand(0)->getType()));
3526     else
3527       Args.push_back(CI->getOperand(0));
3528     Args.push_back(CI->getOperand(1));
3529     NewCall = Builder.CreateCall(NewFn, Args);
3530     cast<Instruction>(NewCall)->copyFastMathFlags(CI);
3531     break;
3532   }
3533   case Intrinsic::arm_neon_vld1:
3534   case Intrinsic::arm_neon_vld2:
3535   case Intrinsic::arm_neon_vld3:
3536   case Intrinsic::arm_neon_vld4:
3537   case Intrinsic::arm_neon_vld2lane:
3538   case Intrinsic::arm_neon_vld3lane:
3539   case Intrinsic::arm_neon_vld4lane:
3540   case Intrinsic::arm_neon_vst1:
3541   case Intrinsic::arm_neon_vst2:
3542   case Intrinsic::arm_neon_vst3:
3543   case Intrinsic::arm_neon_vst4:
3544   case Intrinsic::arm_neon_vst2lane:
3545   case Intrinsic::arm_neon_vst3lane:
3546   case Intrinsic::arm_neon_vst4lane: {
3547     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
3548                                  CI->arg_operands().end());
3549     NewCall = Builder.CreateCall(NewFn, Args);
3550     break;
3551   }
3552 
3553   case Intrinsic::bitreverse:
3554     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
3555     break;
3556 
3557   case Intrinsic::ctlz:
3558   case Intrinsic::cttz:
3559     assert(CI->getNumArgOperands() == 1 &&
3560            "Mismatch between function args and call args");
3561     NewCall =
3562         Builder.CreateCall(NewFn, {CI->getArgOperand(0), Builder.getFalse()});
3563     break;
3564 
3565   case Intrinsic::objectsize: {
3566     Value *NullIsUnknownSize = CI->getNumArgOperands() == 2
3567                                    ? Builder.getFalse()
3568                                    : CI->getArgOperand(2);
3569     Value *Dynamic =
3570         CI->getNumArgOperands() < 4 ? Builder.getFalse() : CI->getArgOperand(3);
3571     NewCall = Builder.CreateCall(
3572         NewFn, {CI->getArgOperand(0), CI->getArgOperand(1), NullIsUnknownSize, Dynamic});
3573     break;
3574   }
3575 
3576   case Intrinsic::ctpop:
3577     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
3578     break;
3579 
3580   case Intrinsic::convert_from_fp16:
3581     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
3582     break;
3583 
3584   case Intrinsic::dbg_value:
3585     // Upgrade from the old version that had an extra offset argument.
3586     assert(CI->getNumArgOperands() == 4);
3587     // Drop nonzero offsets instead of attempting to upgrade them.
3588     if (auto *Offset = dyn_cast_or_null<Constant>(CI->getArgOperand(1)))
3589       if (Offset->isZeroValue()) {
3590         NewCall = Builder.CreateCall(
3591             NewFn,
3592             {CI->getArgOperand(0), CI->getArgOperand(2), CI->getArgOperand(3)});
3593         break;
3594       }
3595     CI->eraseFromParent();
3596     return;
3597 
3598   case Intrinsic::x86_xop_vfrcz_ss:
3599   case Intrinsic::x86_xop_vfrcz_sd:
3600     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(1)});
3601     break;
3602 
3603   case Intrinsic::x86_xop_vpermil2pd:
3604   case Intrinsic::x86_xop_vpermil2ps:
3605   case Intrinsic::x86_xop_vpermil2pd_256:
3606   case Intrinsic::x86_xop_vpermil2ps_256: {
3607     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
3608                                  CI->arg_operands().end());
3609     VectorType *FltIdxTy = cast<VectorType>(Args[2]->getType());
3610     VectorType *IntIdxTy = VectorType::getInteger(FltIdxTy);
3611     Args[2] = Builder.CreateBitCast(Args[2], IntIdxTy);
3612     NewCall = Builder.CreateCall(NewFn, Args);
3613     break;
3614   }
3615 
3616   case Intrinsic::x86_sse41_ptestc:
3617   case Intrinsic::x86_sse41_ptestz:
3618   case Intrinsic::x86_sse41_ptestnzc: {
3619     // The arguments for these intrinsics used to be v4f32, and changed
3620     // to v2i64. This is purely a nop, since those are bitwise intrinsics.
3621     // So, the only thing required is a bitcast for both arguments.
3622     // First, check the arguments have the old type.
3623     Value *Arg0 = CI->getArgOperand(0);
3624     if (Arg0->getType() != VectorType::get(Type::getFloatTy(C), 4))
3625       return;
3626 
3627     // Old intrinsic, add bitcasts
3628     Value *Arg1 = CI->getArgOperand(1);
3629 
3630     Type *NewVecTy = VectorType::get(Type::getInt64Ty(C), 2);
3631 
3632     Value *BC0 = Builder.CreateBitCast(Arg0, NewVecTy, "cast");
3633     Value *BC1 = Builder.CreateBitCast(Arg1, NewVecTy, "cast");
3634 
3635     NewCall = Builder.CreateCall(NewFn, {BC0, BC1});
3636     break;
3637   }
3638 
3639   case Intrinsic::x86_rdtscp: {
3640     // This used to take 1 arguments. If we have no arguments, it is already
3641     // upgraded.
3642     if (CI->getNumOperands() == 0)
3643       return;
3644 
3645     NewCall = Builder.CreateCall(NewFn);
3646     // Extract the second result and store it.
3647     Value *Data = Builder.CreateExtractValue(NewCall, 1);
3648     // Cast the pointer to the right type.
3649     Value *Ptr = Builder.CreateBitCast(CI->getArgOperand(0),
3650                                  llvm::PointerType::getUnqual(Data->getType()));
3651     Builder.CreateAlignedStore(Data, Ptr, 1);
3652     // Replace the original call result with the first result of the new call.
3653     Value *TSC = Builder.CreateExtractValue(NewCall, 0);
3654 
3655     std::string Name = CI->getName();
3656     if (!Name.empty()) {
3657       CI->setName(Name + ".old");
3658       NewCall->setName(Name);
3659     }
3660     CI->replaceAllUsesWith(TSC);
3661     CI->eraseFromParent();
3662     return;
3663   }
3664 
3665   case Intrinsic::x86_sse41_insertps:
3666   case Intrinsic::x86_sse41_dppd:
3667   case Intrinsic::x86_sse41_dpps:
3668   case Intrinsic::x86_sse41_mpsadbw:
3669   case Intrinsic::x86_avx_dp_ps_256:
3670   case Intrinsic::x86_avx2_mpsadbw: {
3671     // Need to truncate the last argument from i32 to i8 -- this argument models
3672     // an inherently 8-bit immediate operand to these x86 instructions.
3673     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
3674                                  CI->arg_operands().end());
3675 
3676     // Replace the last argument with a trunc.
3677     Args.back() = Builder.CreateTrunc(Args.back(), Type::getInt8Ty(C), "trunc");
3678     NewCall = Builder.CreateCall(NewFn, Args);
3679     break;
3680   }
3681 
3682   case Intrinsic::thread_pointer: {
3683     NewCall = Builder.CreateCall(NewFn, {});
3684     break;
3685   }
3686 
3687   case Intrinsic::invariant_start:
3688   case Intrinsic::invariant_end:
3689   case Intrinsic::masked_load:
3690   case Intrinsic::masked_store:
3691   case Intrinsic::masked_gather:
3692   case Intrinsic::masked_scatter: {
3693     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
3694                                  CI->arg_operands().end());
3695     NewCall = Builder.CreateCall(NewFn, Args);
3696     break;
3697   }
3698 
3699   case Intrinsic::memcpy:
3700   case Intrinsic::memmove:
3701   case Intrinsic::memset: {
3702     // We have to make sure that the call signature is what we're expecting.
3703     // We only want to change the old signatures by removing the alignment arg:
3704     //  @llvm.mem[cpy|move]...(i8*, i8*, i[32|i64], i32, i1)
3705     //    -> @llvm.mem[cpy|move]...(i8*, i8*, i[32|i64], i1)
3706     //  @llvm.memset...(i8*, i8, i[32|64], i32, i1)
3707     //    -> @llvm.memset...(i8*, i8, i[32|64], i1)
3708     // Note: i8*'s in the above can be any pointer type
3709     if (CI->getNumArgOperands() != 5) {
3710       DefaultCase();
3711       return;
3712     }
3713     // Remove alignment argument (3), and add alignment attributes to the
3714     // dest/src pointers.
3715     Value *Args[4] = {CI->getArgOperand(0), CI->getArgOperand(1),
3716                       CI->getArgOperand(2), CI->getArgOperand(4)};
3717     NewCall = Builder.CreateCall(NewFn, Args);
3718     auto *MemCI = cast<MemIntrinsic>(NewCall);
3719     // All mem intrinsics support dest alignment.
3720     const ConstantInt *Align = cast<ConstantInt>(CI->getArgOperand(3));
3721     MemCI->setDestAlignment(Align->getZExtValue());
3722     // Memcpy/Memmove also support source alignment.
3723     if (auto *MTI = dyn_cast<MemTransferInst>(MemCI))
3724       MTI->setSourceAlignment(Align->getZExtValue());
3725     break;
3726   }
3727   }
3728   assert(NewCall && "Should have either set this variable or returned through "
3729                     "the default case");
3730   std::string Name = CI->getName();
3731   if (!Name.empty()) {
3732     CI->setName(Name + ".old");
3733     NewCall->setName(Name);
3734   }
3735   CI->replaceAllUsesWith(NewCall);
3736   CI->eraseFromParent();
3737 }
3738 
3739 void llvm::UpgradeCallsToIntrinsic(Function *F) {
3740   assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");
3741 
3742   // Check if this function should be upgraded and get the replacement function
3743   // if there is one.
3744   Function *NewFn;
3745   if (UpgradeIntrinsicFunction(F, NewFn)) {
3746     // Replace all users of the old function with the new function or new
3747     // instructions. This is not a range loop because the call is deleted.
3748     for (auto UI = F->user_begin(), UE = F->user_end(); UI != UE; )
3749       if (CallInst *CI = dyn_cast<CallInst>(*UI++))
3750         UpgradeIntrinsicCall(CI, NewFn);
3751 
3752     // Remove old function, no longer used, from the module.
3753     F->eraseFromParent();
3754   }
3755 }
3756 
3757 MDNode *llvm::UpgradeTBAANode(MDNode &MD) {
3758   // Check if the tag uses struct-path aware TBAA format.
3759   if (isa<MDNode>(MD.getOperand(0)) && MD.getNumOperands() >= 3)
3760     return &MD;
3761 
3762   auto &Context = MD.getContext();
3763   if (MD.getNumOperands() == 3) {
3764     Metadata *Elts[] = {MD.getOperand(0), MD.getOperand(1)};
3765     MDNode *ScalarType = MDNode::get(Context, Elts);
3766     // Create a MDNode <ScalarType, ScalarType, offset 0, const>
3767     Metadata *Elts2[] = {ScalarType, ScalarType,
3768                          ConstantAsMetadata::get(
3769                              Constant::getNullValue(Type::getInt64Ty(Context))),
3770                          MD.getOperand(2)};
3771     return MDNode::get(Context, Elts2);
3772   }
3773   // Create a MDNode <MD, MD, offset 0>
3774   Metadata *Elts[] = {&MD, &MD, ConstantAsMetadata::get(Constant::getNullValue(
3775                                     Type::getInt64Ty(Context)))};
3776   return MDNode::get(Context, Elts);
3777 }
3778 
3779 Instruction *llvm::UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy,
3780                                       Instruction *&Temp) {
3781   if (Opc != Instruction::BitCast)
3782     return nullptr;
3783 
3784   Temp = nullptr;
3785   Type *SrcTy = V->getType();
3786   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
3787       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
3788     LLVMContext &Context = V->getContext();
3789 
3790     // We have no information about target data layout, so we assume that
3791     // the maximum pointer size is 64bit.
3792     Type *MidTy = Type::getInt64Ty(Context);
3793     Temp = CastInst::Create(Instruction::PtrToInt, V, MidTy);
3794 
3795     return CastInst::Create(Instruction::IntToPtr, Temp, DestTy);
3796   }
3797 
3798   return nullptr;
3799 }
3800 
3801 Value *llvm::UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy) {
3802   if (Opc != Instruction::BitCast)
3803     return nullptr;
3804 
3805   Type *SrcTy = C->getType();
3806   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
3807       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
3808     LLVMContext &Context = C->getContext();
3809 
3810     // We have no information about target data layout, so we assume that
3811     // the maximum pointer size is 64bit.
3812     Type *MidTy = Type::getInt64Ty(Context);
3813 
3814     return ConstantExpr::getIntToPtr(ConstantExpr::getPtrToInt(C, MidTy),
3815                                      DestTy);
3816   }
3817 
3818   return nullptr;
3819 }
3820 
3821 /// Check the debug info version number, if it is out-dated, drop the debug
3822 /// info. Return true if module is modified.
3823 bool llvm::UpgradeDebugInfo(Module &M) {
3824   unsigned Version = getDebugMetadataVersionFromModule(M);
3825   if (Version == DEBUG_METADATA_VERSION) {
3826     bool BrokenDebugInfo = false;
3827     if (verifyModule(M, &llvm::errs(), &BrokenDebugInfo))
3828       report_fatal_error("Broken module found, compilation aborted!");
3829     if (!BrokenDebugInfo)
3830       // Everything is ok.
3831       return false;
3832     else {
3833       // Diagnose malformed debug info.
3834       DiagnosticInfoIgnoringInvalidDebugMetadata Diag(M);
3835       M.getContext().diagnose(Diag);
3836     }
3837   }
3838   bool Modified = StripDebugInfo(M);
3839   if (Modified && Version != DEBUG_METADATA_VERSION) {
3840     // Diagnose a version mismatch.
3841     DiagnosticInfoDebugMetadataVersion DiagVersion(M, Version);
3842     M.getContext().diagnose(DiagVersion);
3843   }
3844   return Modified;
3845 }
3846 
3847 bool llvm::UpgradeRetainReleaseMarker(Module &M) {
3848   bool Changed = false;
3849   const char *MarkerKey = "clang.arc.retainAutoreleasedReturnValueMarker";
3850   NamedMDNode *ModRetainReleaseMarker = M.getNamedMetadata(MarkerKey);
3851   if (ModRetainReleaseMarker) {
3852     MDNode *Op = ModRetainReleaseMarker->getOperand(0);
3853     if (Op) {
3854       MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(0));
3855       if (ID) {
3856         SmallVector<StringRef, 4> ValueComp;
3857         ID->getString().split(ValueComp, "#");
3858         if (ValueComp.size() == 2) {
3859           std::string NewValue = ValueComp[0].str() + ";" + ValueComp[1].str();
3860           ID = MDString::get(M.getContext(), NewValue);
3861         }
3862         M.addModuleFlag(Module::Error, MarkerKey, ID);
3863         M.eraseNamedMetadata(ModRetainReleaseMarker);
3864         Changed = true;
3865       }
3866     }
3867   }
3868   return Changed;
3869 }
3870 
3871 bool llvm::UpgradeModuleFlags(Module &M) {
3872   NamedMDNode *ModFlags = M.getModuleFlagsMetadata();
3873   if (!ModFlags)
3874     return false;
3875 
3876   bool HasObjCFlag = false, HasClassProperties = false, Changed = false;
3877   for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
3878     MDNode *Op = ModFlags->getOperand(I);
3879     if (Op->getNumOperands() != 3)
3880       continue;
3881     MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
3882     if (!ID)
3883       continue;
3884     if (ID->getString() == "Objective-C Image Info Version")
3885       HasObjCFlag = true;
3886     if (ID->getString() == "Objective-C Class Properties")
3887       HasClassProperties = true;
3888     // Upgrade PIC/PIE Module Flags. The module flag behavior for these two
3889     // field was Error and now they are Max.
3890     if (ID->getString() == "PIC Level" || ID->getString() == "PIE Level") {
3891       if (auto *Behavior =
3892               mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0))) {
3893         if (Behavior->getLimitedValue() == Module::Error) {
3894           Type *Int32Ty = Type::getInt32Ty(M.getContext());
3895           Metadata *Ops[3] = {
3896               ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Module::Max)),
3897               MDString::get(M.getContext(), ID->getString()),
3898               Op->getOperand(2)};
3899           ModFlags->setOperand(I, MDNode::get(M.getContext(), Ops));
3900           Changed = true;
3901         }
3902       }
3903     }
3904     // Upgrade Objective-C Image Info Section. Removed the whitespce in the
3905     // section name so that llvm-lto will not complain about mismatching
3906     // module flags that is functionally the same.
3907     if (ID->getString() == "Objective-C Image Info Section") {
3908       if (auto *Value = dyn_cast_or_null<MDString>(Op->getOperand(2))) {
3909         SmallVector<StringRef, 4> ValueComp;
3910         Value->getString().split(ValueComp, " ");
3911         if (ValueComp.size() != 1) {
3912           std::string NewValue;
3913           for (auto &S : ValueComp)
3914             NewValue += S.str();
3915           Metadata *Ops[3] = {Op->getOperand(0), Op->getOperand(1),
3916                               MDString::get(M.getContext(), NewValue)};
3917           ModFlags->setOperand(I, MDNode::get(M.getContext(), Ops));
3918           Changed = true;
3919         }
3920       }
3921     }
3922   }
3923 
3924   // "Objective-C Class Properties" is recently added for Objective-C. We
3925   // upgrade ObjC bitcodes to contain a "Objective-C Class Properties" module
3926   // flag of value 0, so we can correclty downgrade this flag when trying to
3927   // link an ObjC bitcode without this module flag with an ObjC bitcode with
3928   // this module flag.
3929   if (HasObjCFlag && !HasClassProperties) {
3930     M.addModuleFlag(llvm::Module::Override, "Objective-C Class Properties",
3931                     (uint32_t)0);
3932     Changed = true;
3933   }
3934 
3935   return Changed;
3936 }
3937 
3938 void llvm::UpgradeSectionAttributes(Module &M) {
3939   auto TrimSpaces = [](StringRef Section) -> std::string {
3940     SmallVector<StringRef, 5> Components;
3941     Section.split(Components, ',');
3942 
3943     SmallString<32> Buffer;
3944     raw_svector_ostream OS(Buffer);
3945 
3946     for (auto Component : Components)
3947       OS << ',' << Component.trim();
3948 
3949     return OS.str().substr(1);
3950   };
3951 
3952   for (auto &GV : M.globals()) {
3953     if (!GV.hasSection())
3954       continue;
3955 
3956     StringRef Section = GV.getSection();
3957 
3958     if (!Section.startswith("__DATA, __objc_catlist"))
3959       continue;
3960 
3961     // __DATA, __objc_catlist, regular, no_dead_strip
3962     // __DATA,__objc_catlist,regular,no_dead_strip
3963     GV.setSection(TrimSpaces(Section));
3964   }
3965 }
3966 
3967 static bool isOldLoopArgument(Metadata *MD) {
3968   auto *T = dyn_cast_or_null<MDTuple>(MD);
3969   if (!T)
3970     return false;
3971   if (T->getNumOperands() < 1)
3972     return false;
3973   auto *S = dyn_cast_or_null<MDString>(T->getOperand(0));
3974   if (!S)
3975     return false;
3976   return S->getString().startswith("llvm.vectorizer.");
3977 }
3978 
3979 static MDString *upgradeLoopTag(LLVMContext &C, StringRef OldTag) {
3980   StringRef OldPrefix = "llvm.vectorizer.";
3981   assert(OldTag.startswith(OldPrefix) && "Expected old prefix");
3982 
3983   if (OldTag == "llvm.vectorizer.unroll")
3984     return MDString::get(C, "llvm.loop.interleave.count");
3985 
3986   return MDString::get(
3987       C, (Twine("llvm.loop.vectorize.") + OldTag.drop_front(OldPrefix.size()))
3988              .str());
3989 }
3990 
3991 static Metadata *upgradeLoopArgument(Metadata *MD) {
3992   auto *T = dyn_cast_or_null<MDTuple>(MD);
3993   if (!T)
3994     return MD;
3995   if (T->getNumOperands() < 1)
3996     return MD;
3997   auto *OldTag = dyn_cast_or_null<MDString>(T->getOperand(0));
3998   if (!OldTag)
3999     return MD;
4000   if (!OldTag->getString().startswith("llvm.vectorizer."))
4001     return MD;
4002 
4003   // This has an old tag.  Upgrade it.
4004   SmallVector<Metadata *, 8> Ops;
4005   Ops.reserve(T->getNumOperands());
4006   Ops.push_back(upgradeLoopTag(T->getContext(), OldTag->getString()));
4007   for (unsigned I = 1, E = T->getNumOperands(); I != E; ++I)
4008     Ops.push_back(T->getOperand(I));
4009 
4010   return MDTuple::get(T->getContext(), Ops);
4011 }
4012 
4013 MDNode *llvm::upgradeInstructionLoopAttachment(MDNode &N) {
4014   auto *T = dyn_cast<MDTuple>(&N);
4015   if (!T)
4016     return &N;
4017 
4018   if (none_of(T->operands(), isOldLoopArgument))
4019     return &N;
4020 
4021   SmallVector<Metadata *, 8> Ops;
4022   Ops.reserve(T->getNumOperands());
4023   for (Metadata *MD : T->operands())
4024     Ops.push_back(upgradeLoopArgument(MD));
4025 
4026   return MDTuple::get(T->getContext(), Ops);
4027 }
4028