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