[llvm-objcopy] [COFF] Implmement --strip-unneeded and -x/--discard-all for symbols
[llvm-complete.git] / tools / llvm-c-test / echo.cpp
blobdb926e8aceaac9c18ee6277bbc7c14a6e3cef687
1 //===-- echo.cpp - tool for testing libLLVM and llvm-c API ----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the --echo command in llvm-c-test.
12 // This command uses the C API to read a module and output an exact copy of it
13 // as output. It is used to check that the resulting module matches the input
14 // to validate that the C API can read and write modules properly.
16 //===----------------------------------------------------------------------===//
18 #include "llvm-c-test.h"
19 #include "llvm-c/DebugInfo.h"
20 #include "llvm-c/Target.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/Support/ErrorHandling.h"
24 #include <stdio.h>
25 #include <stdlib.h>
27 using namespace llvm;
29 // Provide DenseMapInfo for C API opaque types.
30 template<typename T>
31 struct CAPIDenseMap {};
33 // The default DenseMapInfo require to know about pointer alignement.
34 // Because the C API uses opaques pointer types, their alignement is unknown.
35 // As a result, we need to roll out our own implementation.
36 template<typename T>
37 struct CAPIDenseMap<T*> {
38 struct CAPIDenseMapInfo {
39 static inline T* getEmptyKey() {
40 uintptr_t Val = static_cast<uintptr_t>(-1);
41 return reinterpret_cast<T*>(Val);
43 static inline T* getTombstoneKey() {
44 uintptr_t Val = static_cast<uintptr_t>(-2);
45 return reinterpret_cast<T*>(Val);
47 static unsigned getHashValue(const T *PtrVal) {
48 return hash_value(PtrVal);
50 static bool isEqual(const T *LHS, const T *RHS) { return LHS == RHS; }
53 typedef DenseMap<T*, T*, CAPIDenseMapInfo> Map;
56 typedef CAPIDenseMap<LLVMValueRef>::Map ValueMap;
57 typedef CAPIDenseMap<LLVMBasicBlockRef>::Map BasicBlockMap;
59 struct TypeCloner {
60 LLVMModuleRef M;
61 LLVMContextRef Ctx;
63 TypeCloner(LLVMModuleRef M): M(M), Ctx(LLVMGetModuleContext(M)) {}
65 LLVMTypeRef Clone(LLVMValueRef Src) {
66 return Clone(LLVMTypeOf(Src));
69 LLVMTypeRef Clone(LLVMTypeRef Src) {
70 LLVMTypeKind Kind = LLVMGetTypeKind(Src);
71 switch (Kind) {
72 case LLVMVoidTypeKind:
73 return LLVMVoidTypeInContext(Ctx);
74 case LLVMHalfTypeKind:
75 return LLVMHalfTypeInContext(Ctx);
76 case LLVMFloatTypeKind:
77 return LLVMFloatTypeInContext(Ctx);
78 case LLVMDoubleTypeKind:
79 return LLVMDoubleTypeInContext(Ctx);
80 case LLVMX86_FP80TypeKind:
81 return LLVMX86FP80TypeInContext(Ctx);
82 case LLVMFP128TypeKind:
83 return LLVMFP128TypeInContext(Ctx);
84 case LLVMPPC_FP128TypeKind:
85 return LLVMPPCFP128TypeInContext(Ctx);
86 case LLVMLabelTypeKind:
87 return LLVMLabelTypeInContext(Ctx);
88 case LLVMIntegerTypeKind:
89 return LLVMIntTypeInContext(Ctx, LLVMGetIntTypeWidth(Src));
90 case LLVMFunctionTypeKind: {
91 unsigned ParamCount = LLVMCountParamTypes(Src);
92 LLVMTypeRef* Params = nullptr;
93 if (ParamCount > 0) {
94 Params = static_cast<LLVMTypeRef*>(
95 safe_malloc(ParamCount * sizeof(LLVMTypeRef)));
96 LLVMGetParamTypes(Src, Params);
97 for (unsigned i = 0; i < ParamCount; i++)
98 Params[i] = Clone(Params[i]);
101 LLVMTypeRef FunTy = LLVMFunctionType(Clone(LLVMGetReturnType(Src)),
102 Params, ParamCount,
103 LLVMIsFunctionVarArg(Src));
104 if (ParamCount > 0)
105 free(Params);
106 return FunTy;
108 case LLVMStructTypeKind: {
109 LLVMTypeRef S = nullptr;
110 const char *Name = LLVMGetStructName(Src);
111 if (Name) {
112 S = LLVMGetTypeByName(M, Name);
113 if (S)
114 return S;
115 S = LLVMStructCreateNamed(Ctx, Name);
116 if (LLVMIsOpaqueStruct(Src))
117 return S;
120 unsigned EltCount = LLVMCountStructElementTypes(Src);
121 SmallVector<LLVMTypeRef, 8> Elts;
122 for (unsigned i = 0; i < EltCount; i++)
123 Elts.push_back(Clone(LLVMStructGetTypeAtIndex(Src, i)));
124 if (Name)
125 LLVMStructSetBody(S, Elts.data(), EltCount, LLVMIsPackedStruct(Src));
126 else
127 S = LLVMStructTypeInContext(Ctx, Elts.data(), EltCount,
128 LLVMIsPackedStruct(Src));
129 return S;
131 case LLVMArrayTypeKind:
132 return LLVMArrayType(
133 Clone(LLVMGetElementType(Src)),
134 LLVMGetArrayLength(Src)
136 case LLVMPointerTypeKind:
137 return LLVMPointerType(
138 Clone(LLVMGetElementType(Src)),
139 LLVMGetPointerAddressSpace(Src)
141 case LLVMVectorTypeKind:
142 return LLVMVectorType(
143 Clone(LLVMGetElementType(Src)),
144 LLVMGetVectorSize(Src)
146 case LLVMMetadataTypeKind:
147 return LLVMMetadataTypeInContext(Ctx);
148 case LLVMX86_MMXTypeKind:
149 return LLVMX86MMXTypeInContext(Ctx);
150 case LLVMTokenTypeKind:
151 return LLVMTokenTypeInContext(Ctx);
154 fprintf(stderr, "%d is not a supported typekind\n", Kind);
155 exit(-1);
159 static ValueMap clone_params(LLVMValueRef Src, LLVMValueRef Dst) {
160 unsigned Count = LLVMCountParams(Src);
161 if (Count != LLVMCountParams(Dst))
162 report_fatal_error("Parameter count mismatch");
164 ValueMap VMap;
165 if (Count == 0)
166 return VMap;
168 LLVMValueRef SrcFirst = LLVMGetFirstParam(Src);
169 LLVMValueRef DstFirst = LLVMGetFirstParam(Dst);
170 LLVMValueRef SrcLast = LLVMGetLastParam(Src);
171 LLVMValueRef DstLast = LLVMGetLastParam(Dst);
173 LLVMValueRef SrcCur = SrcFirst;
174 LLVMValueRef DstCur = DstFirst;
175 LLVMValueRef SrcNext = nullptr;
176 LLVMValueRef DstNext = nullptr;
177 while (true) {
178 size_t NameLen;
179 const char *Name = LLVMGetValueName2(SrcCur, &NameLen);
180 LLVMSetValueName2(DstCur, Name, NameLen);
182 VMap[SrcCur] = DstCur;
184 Count--;
185 SrcNext = LLVMGetNextParam(SrcCur);
186 DstNext = LLVMGetNextParam(DstCur);
187 if (SrcNext == nullptr && DstNext == nullptr) {
188 if (SrcCur != SrcLast)
189 report_fatal_error("SrcLast param does not match End");
190 if (DstCur != DstLast)
191 report_fatal_error("DstLast param does not match End");
192 break;
195 if (SrcNext == nullptr)
196 report_fatal_error("SrcNext was unexpectedly null");
197 if (DstNext == nullptr)
198 report_fatal_error("DstNext was unexpectedly null");
200 LLVMValueRef SrcPrev = LLVMGetPreviousParam(SrcNext);
201 if (SrcPrev != SrcCur)
202 report_fatal_error("SrcNext.Previous param is not Current");
204 LLVMValueRef DstPrev = LLVMGetPreviousParam(DstNext);
205 if (DstPrev != DstCur)
206 report_fatal_error("DstNext.Previous param is not Current");
208 SrcCur = SrcNext;
209 DstCur = DstNext;
212 if (Count != 0)
213 report_fatal_error("Parameter count does not match iteration");
215 return VMap;
218 static void check_value_kind(LLVMValueRef V, LLVMValueKind K) {
219 if (LLVMGetValueKind(V) != K)
220 report_fatal_error("LLVMGetValueKind returned incorrect type");
223 static LLVMValueRef clone_constant_impl(LLVMValueRef Cst, LLVMModuleRef M);
225 static LLVMValueRef clone_constant(LLVMValueRef Cst, LLVMModuleRef M) {
226 LLVMValueRef Ret = clone_constant_impl(Cst, M);
227 check_value_kind(Ret, LLVMGetValueKind(Cst));
228 return Ret;
231 static LLVMValueRef clone_constant_impl(LLVMValueRef Cst, LLVMModuleRef M) {
232 if (!LLVMIsAConstant(Cst))
233 report_fatal_error("Expected a constant");
235 // Maybe it is a symbol
236 if (LLVMIsAGlobalValue(Cst)) {
237 size_t NameLen;
238 const char *Name = LLVMGetValueName2(Cst, &NameLen);
240 // Try function
241 if (LLVMIsAFunction(Cst)) {
242 check_value_kind(Cst, LLVMFunctionValueKind);
244 LLVMValueRef Dst = nullptr;
245 // Try an intrinsic
246 unsigned ID = LLVMGetIntrinsicID(Cst);
247 if (ID > 0 && !LLVMIntrinsicIsOverloaded(ID)) {
248 Dst = LLVMGetIntrinsicDeclaration(M, ID, nullptr, 0);
249 } else {
250 // Try a normal function
251 Dst = LLVMGetNamedFunction(M, Name);
254 if (Dst)
255 return Dst;
256 report_fatal_error("Could not find function");
259 // Try global variable
260 if (LLVMIsAGlobalVariable(Cst)) {
261 check_value_kind(Cst, LLVMGlobalVariableValueKind);
262 LLVMValueRef Dst = LLVMGetNamedGlobal(M, Name);
263 if (Dst)
264 return Dst;
265 report_fatal_error("Could not find variable");
268 // Try global alias
269 if (LLVMIsAGlobalAlias(Cst)) {
270 check_value_kind(Cst, LLVMGlobalAliasValueKind);
271 LLVMValueRef Dst = LLVMGetNamedGlobalAlias(M, Name, NameLen);
272 if (Dst)
273 return Dst;
274 report_fatal_error("Could not find alias");
277 fprintf(stderr, "Could not find @%s\n", Name);
278 exit(-1);
281 // Try integer literal
282 if (LLVMIsAConstantInt(Cst)) {
283 check_value_kind(Cst, LLVMConstantIntValueKind);
284 return LLVMConstInt(TypeCloner(M).Clone(Cst),
285 LLVMConstIntGetZExtValue(Cst), false);
288 // Try zeroinitializer
289 if (LLVMIsAConstantAggregateZero(Cst)) {
290 check_value_kind(Cst, LLVMConstantAggregateZeroValueKind);
291 return LLVMConstNull(TypeCloner(M).Clone(Cst));
294 // Try constant array
295 if (LLVMIsAConstantArray(Cst)) {
296 check_value_kind(Cst, LLVMConstantArrayValueKind);
297 LLVMTypeRef Ty = TypeCloner(M).Clone(Cst);
298 unsigned EltCount = LLVMGetArrayLength(Ty);
299 SmallVector<LLVMValueRef, 8> Elts;
300 for (unsigned i = 0; i < EltCount; i++)
301 Elts.push_back(clone_constant(LLVMGetOperand(Cst, i), M));
302 return LLVMConstArray(LLVMGetElementType(Ty), Elts.data(), EltCount);
305 // Try contant data array
306 if (LLVMIsAConstantDataArray(Cst)) {
307 check_value_kind(Cst, LLVMConstantDataArrayValueKind);
308 LLVMTypeRef Ty = TypeCloner(M).Clone(Cst);
309 unsigned EltCount = LLVMGetArrayLength(Ty);
310 SmallVector<LLVMValueRef, 8> Elts;
311 for (unsigned i = 0; i < EltCount; i++)
312 Elts.push_back(clone_constant(LLVMGetElementAsConstant(Cst, i), M));
313 return LLVMConstArray(LLVMGetElementType(Ty), Elts.data(), EltCount);
316 // Try constant struct
317 if (LLVMIsAConstantStruct(Cst)) {
318 check_value_kind(Cst, LLVMConstantStructValueKind);
319 LLVMTypeRef Ty = TypeCloner(M).Clone(Cst);
320 unsigned EltCount = LLVMCountStructElementTypes(Ty);
321 SmallVector<LLVMValueRef, 8> Elts;
322 for (unsigned i = 0; i < EltCount; i++)
323 Elts.push_back(clone_constant(LLVMGetOperand(Cst, i), M));
324 if (LLVMGetStructName(Ty))
325 return LLVMConstNamedStruct(Ty, Elts.data(), EltCount);
326 return LLVMConstStructInContext(LLVMGetModuleContext(M), Elts.data(),
327 EltCount, LLVMIsPackedStruct(Ty));
330 // Try undef
331 if (LLVMIsUndef(Cst)) {
332 check_value_kind(Cst, LLVMUndefValueValueKind);
333 return LLVMGetUndef(TypeCloner(M).Clone(Cst));
336 // Try null
337 if (LLVMIsNull(Cst)) {
338 check_value_kind(Cst, LLVMConstantTokenNoneValueKind);
339 LLVMTypeRef Ty = TypeCloner(M).Clone(Cst);
340 return LLVMConstNull(Ty);
343 // Try float literal
344 if (LLVMIsAConstantFP(Cst)) {
345 check_value_kind(Cst, LLVMConstantFPValueKind);
346 report_fatal_error("ConstantFP is not supported");
349 // This kind of constant is not supported
350 if (!LLVMIsAConstantExpr(Cst))
351 report_fatal_error("Expected a constant expression");
353 // At this point, it must be a constant expression
354 check_value_kind(Cst, LLVMConstantExprValueKind);
356 LLVMOpcode Op = LLVMGetConstOpcode(Cst);
357 switch(Op) {
358 case LLVMBitCast:
359 return LLVMConstBitCast(clone_constant(LLVMGetOperand(Cst, 0), M),
360 TypeCloner(M).Clone(Cst));
361 default:
362 fprintf(stderr, "%d is not a supported opcode\n", Op);
363 exit(-1);
367 struct FunCloner {
368 LLVMValueRef Fun;
369 LLVMModuleRef M;
371 ValueMap VMap;
372 BasicBlockMap BBMap;
374 FunCloner(LLVMValueRef Src, LLVMValueRef Dst): Fun(Dst),
375 M(LLVMGetGlobalParent(Fun)), VMap(clone_params(Src, Dst)) {}
377 LLVMTypeRef CloneType(LLVMTypeRef Src) {
378 return TypeCloner(M).Clone(Src);
381 LLVMTypeRef CloneType(LLVMValueRef Src) {
382 return TypeCloner(M).Clone(Src);
385 // Try to clone everything in the llvm::Value hierarchy.
386 LLVMValueRef CloneValue(LLVMValueRef Src) {
387 // First, the value may be constant.
388 if (LLVMIsAConstant(Src))
389 return clone_constant(Src, M);
391 // Function argument should always be in the map already.
392 auto i = VMap.find(Src);
393 if (i != VMap.end())
394 return i->second;
396 if (!LLVMIsAInstruction(Src))
397 report_fatal_error("Expected an instruction");
399 auto Ctx = LLVMGetModuleContext(M);
400 auto Builder = LLVMCreateBuilderInContext(Ctx);
401 auto BB = DeclareBB(LLVMGetInstructionParent(Src));
402 LLVMPositionBuilderAtEnd(Builder, BB);
403 auto Dst = CloneInstruction(Src, Builder);
404 LLVMDisposeBuilder(Builder);
405 return Dst;
408 void CloneAttrs(LLVMValueRef Src, LLVMValueRef Dst) {
409 auto Ctx = LLVMGetModuleContext(M);
410 int ArgCount = LLVMGetNumArgOperands(Src);
411 for (int i = LLVMAttributeReturnIndex; i <= ArgCount; i++) {
412 for (unsigned k = 0, e = LLVMGetLastEnumAttributeKind(); k < e; ++k) {
413 if (auto SrcA = LLVMGetCallSiteEnumAttribute(Src, i, k)) {
414 auto Val = LLVMGetEnumAttributeValue(SrcA);
415 auto A = LLVMCreateEnumAttribute(Ctx, k, Val);
416 LLVMAddCallSiteAttribute(Dst, i, A);
422 LLVMValueRef CloneInstruction(LLVMValueRef Src, LLVMBuilderRef Builder) {
423 check_value_kind(Src, LLVMInstructionValueKind);
424 if (!LLVMIsAInstruction(Src))
425 report_fatal_error("Expected an instruction");
427 size_t NameLen;
428 const char *Name = LLVMGetValueName2(Src, &NameLen);
430 // Check if this is something we already computed.
432 auto i = VMap.find(Src);
433 if (i != VMap.end()) {
434 // If we have a hit, it means we already generated the instruction
435 // as a dependancy to somethign else. We need to make sure
436 // it is ordered properly.
437 auto I = i->second;
438 LLVMInstructionRemoveFromParent(I);
439 LLVMInsertIntoBuilderWithName(Builder, I, Name);
440 return I;
444 // We tried everything, it must be an instruction
445 // that hasn't been generated already.
446 LLVMValueRef Dst = nullptr;
448 LLVMOpcode Op = LLVMGetInstructionOpcode(Src);
449 switch(Op) {
450 case LLVMRet: {
451 int OpCount = LLVMGetNumOperands(Src);
452 if (OpCount == 0)
453 Dst = LLVMBuildRetVoid(Builder);
454 else
455 Dst = LLVMBuildRet(Builder, CloneValue(LLVMGetOperand(Src, 0)));
456 break;
458 case LLVMBr: {
459 if (!LLVMIsConditional(Src)) {
460 LLVMValueRef SrcOp = LLVMGetOperand(Src, 0);
461 LLVMBasicBlockRef SrcBB = LLVMValueAsBasicBlock(SrcOp);
462 Dst = LLVMBuildBr(Builder, DeclareBB(SrcBB));
463 break;
466 LLVMValueRef Cond = LLVMGetCondition(Src);
467 LLVMValueRef Else = LLVMGetOperand(Src, 1);
468 LLVMBasicBlockRef ElseBB = DeclareBB(LLVMValueAsBasicBlock(Else));
469 LLVMValueRef Then = LLVMGetOperand(Src, 2);
470 LLVMBasicBlockRef ThenBB = DeclareBB(LLVMValueAsBasicBlock(Then));
471 Dst = LLVMBuildCondBr(Builder, CloneValue(Cond), ThenBB, ElseBB);
472 break;
474 case LLVMSwitch:
475 case LLVMIndirectBr:
476 break;
477 case LLVMInvoke: {
478 SmallVector<LLVMValueRef, 8> Args;
479 int ArgCount = LLVMGetNumArgOperands(Src);
480 for (int i = 0; i < ArgCount; i++)
481 Args.push_back(CloneValue(LLVMGetOperand(Src, i)));
482 LLVMValueRef Fn = CloneValue(LLVMGetCalledValue(Src));
483 LLVMBasicBlockRef Then = DeclareBB(LLVMGetNormalDest(Src));
484 LLVMBasicBlockRef Unwind = DeclareBB(LLVMGetUnwindDest(Src));
485 Dst = LLVMBuildInvoke(Builder, Fn, Args.data(), ArgCount,
486 Then, Unwind, Name);
487 CloneAttrs(Src, Dst);
488 break;
490 case LLVMUnreachable:
491 Dst = LLVMBuildUnreachable(Builder);
492 break;
493 case LLVMAdd: {
494 LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
495 LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
496 Dst = LLVMBuildAdd(Builder, LHS, RHS, Name);
497 break;
499 case LLVMSub: {
500 LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
501 LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
502 Dst = LLVMBuildSub(Builder, LHS, RHS, Name);
503 break;
505 case LLVMMul: {
506 LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
507 LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
508 Dst = LLVMBuildMul(Builder, LHS, RHS, Name);
509 break;
511 case LLVMUDiv: {
512 LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
513 LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
514 Dst = LLVMBuildUDiv(Builder, LHS, RHS, Name);
515 break;
517 case LLVMSDiv: {
518 LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
519 LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
520 Dst = LLVMBuildSDiv(Builder, LHS, RHS, Name);
521 break;
523 case LLVMURem: {
524 LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
525 LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
526 Dst = LLVMBuildURem(Builder, LHS, RHS, Name);
527 break;
529 case LLVMSRem: {
530 LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
531 LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
532 Dst = LLVMBuildSRem(Builder, LHS, RHS, Name);
533 break;
535 case LLVMShl: {
536 LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
537 LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
538 Dst = LLVMBuildShl(Builder, LHS, RHS, Name);
539 break;
541 case LLVMLShr: {
542 LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
543 LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
544 Dst = LLVMBuildLShr(Builder, LHS, RHS, Name);
545 break;
547 case LLVMAShr: {
548 LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
549 LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
550 Dst = LLVMBuildAShr(Builder, LHS, RHS, Name);
551 break;
553 case LLVMAnd: {
554 LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
555 LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
556 Dst = LLVMBuildAnd(Builder, LHS, RHS, Name);
557 break;
559 case LLVMOr: {
560 LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
561 LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
562 Dst = LLVMBuildOr(Builder, LHS, RHS, Name);
563 break;
565 case LLVMXor: {
566 LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
567 LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
568 Dst = LLVMBuildXor(Builder, LHS, RHS, Name);
569 break;
571 case LLVMAlloca: {
572 LLVMTypeRef Ty = CloneType(LLVMGetAllocatedType(Src));
573 Dst = LLVMBuildAlloca(Builder, Ty, Name);
574 break;
576 case LLVMLoad: {
577 LLVMValueRef Ptr = CloneValue(LLVMGetOperand(Src, 0));
578 Dst = LLVMBuildLoad(Builder, Ptr, Name);
579 LLVMSetAlignment(Dst, LLVMGetAlignment(Src));
580 break;
582 case LLVMStore: {
583 LLVMValueRef Val = CloneValue(LLVMGetOperand(Src, 0));
584 LLVMValueRef Ptr = CloneValue(LLVMGetOperand(Src, 1));
585 Dst = LLVMBuildStore(Builder, Val, Ptr);
586 LLVMSetAlignment(Dst, LLVMGetAlignment(Src));
587 break;
589 case LLVMGetElementPtr: {
590 LLVMValueRef Ptr = CloneValue(LLVMGetOperand(Src, 0));
591 SmallVector<LLVMValueRef, 8> Idx;
592 int NumIdx = LLVMGetNumIndices(Src);
593 for (int i = 1; i <= NumIdx; i++)
594 Idx.push_back(CloneValue(LLVMGetOperand(Src, i)));
595 if (LLVMIsInBounds(Src))
596 Dst = LLVMBuildInBoundsGEP(Builder, Ptr, Idx.data(), NumIdx, Name);
597 else
598 Dst = LLVMBuildGEP(Builder, Ptr, Idx.data(), NumIdx, Name);
599 break;
601 case LLVMAtomicCmpXchg: {
602 LLVMValueRef Ptr = CloneValue(LLVMGetOperand(Src, 0));
603 LLVMValueRef Cmp = CloneValue(LLVMGetOperand(Src, 1));
604 LLVMValueRef New = CloneValue(LLVMGetOperand(Src, 2));
605 LLVMAtomicOrdering Succ = LLVMGetCmpXchgSuccessOrdering(Src);
606 LLVMAtomicOrdering Fail = LLVMGetCmpXchgFailureOrdering(Src);
607 LLVMBool SingleThread = LLVMIsAtomicSingleThread(Src);
609 Dst = LLVMBuildAtomicCmpXchg(Builder, Ptr, Cmp, New, Succ, Fail,
610 SingleThread);
611 } break;
612 case LLVMBitCast: {
613 LLVMValueRef V = CloneValue(LLVMGetOperand(Src, 0));
614 Dst = LLVMBuildBitCast(Builder, V, CloneType(Src), Name);
615 break;
617 case LLVMICmp: {
618 LLVMIntPredicate Pred = LLVMGetICmpPredicate(Src);
619 LLVMValueRef LHS = CloneValue(LLVMGetOperand(Src, 0));
620 LLVMValueRef RHS = CloneValue(LLVMGetOperand(Src, 1));
621 Dst = LLVMBuildICmp(Builder, Pred, LHS, RHS, Name);
622 break;
624 case LLVMPHI: {
625 // We need to aggressively set things here because of loops.
626 VMap[Src] = Dst = LLVMBuildPhi(Builder, CloneType(Src), Name);
628 SmallVector<LLVMValueRef, 8> Values;
629 SmallVector<LLVMBasicBlockRef, 8> Blocks;
631 unsigned IncomingCount = LLVMCountIncoming(Src);
632 for (unsigned i = 0; i < IncomingCount; ++i) {
633 Blocks.push_back(DeclareBB(LLVMGetIncomingBlock(Src, i)));
634 Values.push_back(CloneValue(LLVMGetIncomingValue(Src, i)));
637 LLVMAddIncoming(Dst, Values.data(), Blocks.data(), IncomingCount);
638 return Dst;
640 case LLVMCall: {
641 SmallVector<LLVMValueRef, 8> Args;
642 int ArgCount = LLVMGetNumArgOperands(Src);
643 for (int i = 0; i < ArgCount; i++)
644 Args.push_back(CloneValue(LLVMGetOperand(Src, i)));
645 LLVMValueRef Fn = CloneValue(LLVMGetCalledValue(Src));
646 Dst = LLVMBuildCall(Builder, Fn, Args.data(), ArgCount, Name);
647 LLVMSetTailCall(Dst, LLVMIsTailCall(Src));
648 CloneAttrs(Src, Dst);
649 break;
651 case LLVMResume: {
652 Dst = LLVMBuildResume(Builder, CloneValue(LLVMGetOperand(Src, 0)));
653 break;
655 case LLVMLandingPad: {
656 // The landing pad API is a bit screwed up for historical reasons.
657 Dst = LLVMBuildLandingPad(Builder, CloneType(Src), nullptr, 0, Name);
658 unsigned NumClauses = LLVMGetNumClauses(Src);
659 for (unsigned i = 0; i < NumClauses; ++i)
660 LLVMAddClause(Dst, CloneValue(LLVMGetClause(Src, i)));
661 LLVMSetCleanup(Dst, LLVMIsCleanup(Src));
662 break;
664 case LLVMCleanupRet: {
665 LLVMValueRef CatchPad = CloneValue(LLVMGetOperand(Src, 0));
666 LLVMBasicBlockRef Unwind = nullptr;
667 if (LLVMBasicBlockRef UDest = LLVMGetUnwindDest(Src))
668 Unwind = DeclareBB(UDest);
669 Dst = LLVMBuildCleanupRet(Builder, CatchPad, Unwind);
670 break;
672 case LLVMCatchRet: {
673 LLVMValueRef CatchPad = CloneValue(LLVMGetOperand(Src, 0));
674 LLVMBasicBlockRef SuccBB = DeclareBB(LLVMGetSuccessor(Src, 0));
675 Dst = LLVMBuildCatchRet(Builder, CatchPad, SuccBB);
676 break;
678 case LLVMCatchPad: {
679 LLVMValueRef ParentPad = CloneValue(LLVMGetParentCatchSwitch(Src));
680 SmallVector<LLVMValueRef, 8> Args;
681 int ArgCount = LLVMGetNumArgOperands(Src);
682 for (int i = 0; i < ArgCount; i++)
683 Args.push_back(CloneValue(LLVMGetOperand(Src, i)));
684 Dst = LLVMBuildCatchPad(Builder, ParentPad,
685 Args.data(), ArgCount, Name);
686 break;
688 case LLVMCleanupPad: {
689 LLVMValueRef ParentPad = CloneValue(LLVMGetOperand(Src, 0));
690 SmallVector<LLVMValueRef, 8> Args;
691 int ArgCount = LLVMGetNumArgOperands(Src);
692 for (int i = 0; i < ArgCount; i++)
693 Args.push_back(CloneValue(LLVMGetArgOperand(Src, i)));
694 Dst = LLVMBuildCleanupPad(Builder, ParentPad,
695 Args.data(), ArgCount, Name);
696 break;
698 case LLVMCatchSwitch: {
699 LLVMValueRef ParentPad = CloneValue(LLVMGetOperand(Src, 0));
700 LLVMBasicBlockRef UnwindBB = nullptr;
701 if (LLVMBasicBlockRef UDest = LLVMGetUnwindDest(Src)) {
702 UnwindBB = DeclareBB(UDest);
704 unsigned NumHandlers = LLVMGetNumHandlers(Src);
705 Dst = LLVMBuildCatchSwitch(Builder, ParentPad, UnwindBB, NumHandlers, Name);
706 if (NumHandlers > 0) {
707 LLVMBasicBlockRef *Handlers = static_cast<LLVMBasicBlockRef*>(
708 safe_malloc(NumHandlers * sizeof(LLVMBasicBlockRef)));
709 LLVMGetHandlers(Src, Handlers);
710 for (unsigned i = 0; i < NumHandlers; i++)
711 LLVMAddHandler(Dst, DeclareBB(Handlers[i]));
712 free(Handlers);
714 break;
716 case LLVMExtractValue: {
717 LLVMValueRef Agg = CloneValue(LLVMGetOperand(Src, 0));
718 if (LLVMGetNumIndices(Src) != 1)
719 report_fatal_error("Expected only one indice");
720 auto I = LLVMGetIndices(Src)[0];
721 Dst = LLVMBuildExtractValue(Builder, Agg, I, Name);
722 break;
724 case LLVMInsertValue: {
725 LLVMValueRef Agg = CloneValue(LLVMGetOperand(Src, 0));
726 LLVMValueRef V = CloneValue(LLVMGetOperand(Src, 1));
727 if (LLVMGetNumIndices(Src) != 1)
728 report_fatal_error("Expected only one indice");
729 auto I = LLVMGetIndices(Src)[0];
730 Dst = LLVMBuildInsertValue(Builder, Agg, V, I, Name);
731 break;
733 default:
734 break;
737 if (Dst == nullptr) {
738 fprintf(stderr, "%d is not a supported opcode\n", Op);
739 exit(-1);
742 auto Ctx = LLVMGetModuleContext(M);
743 size_t NumMetadataEntries;
744 auto *AllMetadata =
745 LLVMInstructionGetAllMetadataOtherThanDebugLoc(Src,
746 &NumMetadataEntries);
747 for (unsigned i = 0; i < NumMetadataEntries; ++i) {
748 unsigned Kind = LLVMValueMetadataEntriesGetKind(AllMetadata, i);
749 LLVMMetadataRef MD = LLVMValueMetadataEntriesGetMetadata(AllMetadata, i);
750 LLVMSetMetadata(Dst, Kind, LLVMMetadataAsValue(Ctx, MD));
752 LLVMDisposeValueMetadataEntries(AllMetadata);
753 LLVMSetInstDebugLocation(Builder, Dst);
755 check_value_kind(Dst, LLVMInstructionValueKind);
756 return VMap[Src] = Dst;
759 LLVMBasicBlockRef DeclareBB(LLVMBasicBlockRef Src) {
760 // Check if this is something we already computed.
762 auto i = BBMap.find(Src);
763 if (i != BBMap.end()) {
764 return i->second;
768 LLVMValueRef V = LLVMBasicBlockAsValue(Src);
769 if (!LLVMValueIsBasicBlock(V) || LLVMValueAsBasicBlock(V) != Src)
770 report_fatal_error("Basic block is not a basic block");
772 const char *Name = LLVMGetBasicBlockName(Src);
773 size_t NameLen;
774 const char *VName = LLVMGetValueName2(V, &NameLen);
775 if (Name != VName)
776 report_fatal_error("Basic block name mismatch");
778 LLVMBasicBlockRef BB = LLVMAppendBasicBlock(Fun, Name);
779 return BBMap[Src] = BB;
782 LLVMBasicBlockRef CloneBB(LLVMBasicBlockRef Src) {
783 LLVMBasicBlockRef BB = DeclareBB(Src);
785 // Make sure ordering is correct.
786 LLVMBasicBlockRef Prev = LLVMGetPreviousBasicBlock(Src);
787 if (Prev)
788 LLVMMoveBasicBlockAfter(BB, DeclareBB(Prev));
790 LLVMValueRef First = LLVMGetFirstInstruction(Src);
791 LLVMValueRef Last = LLVMGetLastInstruction(Src);
793 if (First == nullptr) {
794 if (Last != nullptr)
795 report_fatal_error("Has no first instruction, but last one");
796 return BB;
799 auto Ctx = LLVMGetModuleContext(M);
800 LLVMBuilderRef Builder = LLVMCreateBuilderInContext(Ctx);
801 LLVMPositionBuilderAtEnd(Builder, BB);
803 LLVMValueRef Cur = First;
804 LLVMValueRef Next = nullptr;
805 while(true) {
806 CloneInstruction(Cur, Builder);
807 Next = LLVMGetNextInstruction(Cur);
808 if (Next == nullptr) {
809 if (Cur != Last)
810 report_fatal_error("Final instruction does not match Last");
811 break;
814 LLVMValueRef Prev = LLVMGetPreviousInstruction(Next);
815 if (Prev != Cur)
816 report_fatal_error("Next.Previous instruction is not Current");
818 Cur = Next;
821 LLVMDisposeBuilder(Builder);
822 return BB;
825 void CloneBBs(LLVMValueRef Src) {
826 unsigned Count = LLVMCountBasicBlocks(Src);
827 if (Count == 0)
828 return;
830 LLVMBasicBlockRef First = LLVMGetFirstBasicBlock(Src);
831 LLVMBasicBlockRef Last = LLVMGetLastBasicBlock(Src);
833 LLVMBasicBlockRef Cur = First;
834 LLVMBasicBlockRef Next = nullptr;
835 while(true) {
836 CloneBB(Cur);
837 Count--;
838 Next = LLVMGetNextBasicBlock(Cur);
839 if (Next == nullptr) {
840 if (Cur != Last)
841 report_fatal_error("Final basic block does not match Last");
842 break;
845 LLVMBasicBlockRef Prev = LLVMGetPreviousBasicBlock(Next);
846 if (Prev != Cur)
847 report_fatal_error("Next.Previous basic bloc is not Current");
849 Cur = Next;
852 if (Count != 0)
853 report_fatal_error("Basic block count does not match iterration");
857 static void declare_symbols(LLVMModuleRef Src, LLVMModuleRef M) {
858 auto Ctx = LLVMGetModuleContext(M);
860 LLVMValueRef Begin = LLVMGetFirstGlobal(Src);
861 LLVMValueRef End = LLVMGetLastGlobal(Src);
863 LLVMValueRef Cur = Begin;
864 LLVMValueRef Next = nullptr;
865 if (!Begin) {
866 if (End != nullptr)
867 report_fatal_error("Range has an end but no beginning");
868 goto FunDecl;
871 while (true) {
872 size_t NameLen;
873 const char *Name = LLVMGetValueName2(Cur, &NameLen);
874 if (LLVMGetNamedGlobal(M, Name))
875 report_fatal_error("GlobalVariable already cloned");
876 LLVMAddGlobal(M, LLVMGetElementType(TypeCloner(M).Clone(Cur)), Name);
878 Next = LLVMGetNextGlobal(Cur);
879 if (Next == nullptr) {
880 if (Cur != End)
881 report_fatal_error("");
882 break;
885 LLVMValueRef Prev = LLVMGetPreviousGlobal(Next);
886 if (Prev != Cur)
887 report_fatal_error("Next.Previous global is not Current");
889 Cur = Next;
892 FunDecl:
893 Begin = LLVMGetFirstFunction(Src);
894 End = LLVMGetLastFunction(Src);
895 if (!Begin) {
896 if (End != nullptr)
897 report_fatal_error("Range has an end but no beginning");
898 goto AliasDecl;
901 Cur = Begin;
902 Next = nullptr;
903 while (true) {
904 size_t NameLen;
905 const char *Name = LLVMGetValueName2(Cur, &NameLen);
906 if (LLVMGetNamedFunction(M, Name))
907 report_fatal_error("Function already cloned");
908 auto Ty = LLVMGetElementType(TypeCloner(M).Clone(Cur));
909 auto F = LLVMAddFunction(M, Name, Ty);
911 // Copy attributes
912 for (int i = LLVMAttributeFunctionIndex, c = LLVMCountParams(F);
913 i <= c; ++i) {
914 for (unsigned k = 0, e = LLVMGetLastEnumAttributeKind(); k < e; ++k) {
915 if (auto SrcA = LLVMGetEnumAttributeAtIndex(Cur, i, k)) {
916 auto Val = LLVMGetEnumAttributeValue(SrcA);
917 auto DstA = LLVMCreateEnumAttribute(Ctx, k, Val);
918 LLVMAddAttributeAtIndex(F, i, DstA);
923 Next = LLVMGetNextFunction(Cur);
924 if (Next == nullptr) {
925 if (Cur != End)
926 report_fatal_error("Last function does not match End");
927 break;
930 LLVMValueRef Prev = LLVMGetPreviousFunction(Next);
931 if (Prev != Cur)
932 report_fatal_error("Next.Previous function is not Current");
934 Cur = Next;
937 AliasDecl:
938 Begin = LLVMGetFirstGlobalAlias(Src);
939 End = LLVMGetLastGlobalAlias(Src);
940 if (!Begin) {
941 if (End != nullptr)
942 report_fatal_error("Range has an end but no beginning");
943 goto NamedMDDecl;
946 Cur = Begin;
947 Next = nullptr;
948 while (true) {
949 size_t NameLen;
950 const char *Name = LLVMGetValueName2(Cur, &NameLen);
951 if (LLVMGetNamedGlobalAlias(M, Name, NameLen))
952 report_fatal_error("Global alias already cloned");
953 LLVMTypeRef CurType = TypeCloner(M).Clone(Cur);
954 // FIXME: Allow NULL aliasee.
955 LLVMAddAlias(M, CurType, LLVMGetUndef(CurType), Name);
957 Next = LLVMGetNextGlobalAlias(Cur);
958 if (Next == nullptr) {
959 if (Cur != End)
960 report_fatal_error("");
961 break;
964 LLVMValueRef Prev = LLVMGetPreviousGlobalAlias(Next);
965 if (Prev != Cur)
966 report_fatal_error("Next.Previous global is not Current");
968 Cur = Next;
971 NamedMDDecl:
972 LLVMNamedMDNodeRef BeginMD = LLVMGetFirstNamedMetadata(Src);
973 LLVMNamedMDNodeRef EndMD = LLVMGetLastNamedMetadata(Src);
974 if (!BeginMD) {
975 if (EndMD != nullptr)
976 report_fatal_error("Range has an end but no beginning");
977 return;
980 LLVMNamedMDNodeRef CurMD = BeginMD;
981 LLVMNamedMDNodeRef NextMD = nullptr;
982 while (true) {
983 size_t NameLen;
984 const char *Name = LLVMGetNamedMetadataName(CurMD, &NameLen);
985 if (LLVMGetNamedMetadata(M, Name, NameLen))
986 report_fatal_error("Named Metadata Node already cloned");
987 LLVMGetOrInsertNamedMetadata(M, Name, NameLen);
989 NextMD = LLVMGetNextNamedMetadata(CurMD);
990 if (NextMD == nullptr) {
991 if (CurMD != EndMD)
992 report_fatal_error("");
993 break;
996 LLVMNamedMDNodeRef PrevMD = LLVMGetPreviousNamedMetadata(NextMD);
997 if (PrevMD != CurMD)
998 report_fatal_error("Next.Previous global is not Current");
1000 CurMD = NextMD;
1004 static void clone_symbols(LLVMModuleRef Src, LLVMModuleRef M) {
1005 LLVMValueRef Begin = LLVMGetFirstGlobal(Src);
1006 LLVMValueRef End = LLVMGetLastGlobal(Src);
1008 LLVMValueRef Cur = Begin;
1009 LLVMValueRef Next = nullptr;
1010 if (!Begin) {
1011 if (End != nullptr)
1012 report_fatal_error("Range has an end but no beginning");
1013 goto FunClone;
1016 while (true) {
1017 size_t NameLen;
1018 const char *Name = LLVMGetValueName2(Cur, &NameLen);
1019 LLVMValueRef G = LLVMGetNamedGlobal(M, Name);
1020 if (!G)
1021 report_fatal_error("GlobalVariable must have been declared already");
1023 if (auto I = LLVMGetInitializer(Cur))
1024 LLVMSetInitializer(G, clone_constant(I, M));
1026 size_t NumMetadataEntries;
1027 auto *AllMetadata = LLVMGlobalCopyAllMetadata(Cur, &NumMetadataEntries);
1028 for (unsigned i = 0; i < NumMetadataEntries; ++i) {
1029 unsigned Kind = LLVMValueMetadataEntriesGetKind(AllMetadata, i);
1030 LLVMMetadataRef MD = LLVMValueMetadataEntriesGetMetadata(AllMetadata, i);
1031 LLVMGlobalSetMetadata(G, Kind, MD);
1033 LLVMDisposeValueMetadataEntries(AllMetadata);
1035 LLVMSetGlobalConstant(G, LLVMIsGlobalConstant(Cur));
1036 LLVMSetThreadLocal(G, LLVMIsThreadLocal(Cur));
1037 LLVMSetExternallyInitialized(G, LLVMIsExternallyInitialized(Cur));
1038 LLVMSetLinkage(G, LLVMGetLinkage(Cur));
1039 LLVMSetSection(G, LLVMGetSection(Cur));
1040 LLVMSetVisibility(G, LLVMGetVisibility(Cur));
1041 LLVMSetUnnamedAddress(G, LLVMGetUnnamedAddress(Cur));
1042 LLVMSetAlignment(G, LLVMGetAlignment(Cur));
1044 Next = LLVMGetNextGlobal(Cur);
1045 if (Next == nullptr) {
1046 if (Cur != End)
1047 report_fatal_error("");
1048 break;
1051 LLVMValueRef Prev = LLVMGetPreviousGlobal(Next);
1052 if (Prev != Cur)
1053 report_fatal_error("Next.Previous global is not Current");
1055 Cur = Next;
1058 FunClone:
1059 Begin = LLVMGetFirstFunction(Src);
1060 End = LLVMGetLastFunction(Src);
1061 if (!Begin) {
1062 if (End != nullptr)
1063 report_fatal_error("Range has an end but no beginning");
1064 goto AliasClone;
1067 Cur = Begin;
1068 Next = nullptr;
1069 while (true) {
1070 size_t NameLen;
1071 const char *Name = LLVMGetValueName2(Cur, &NameLen);
1072 LLVMValueRef Fun = LLVMGetNamedFunction(M, Name);
1073 if (!Fun)
1074 report_fatal_error("Function must have been declared already");
1076 if (LLVMHasPersonalityFn(Cur)) {
1077 size_t FNameLen;
1078 const char *FName = LLVMGetValueName2(LLVMGetPersonalityFn(Cur),
1079 &FNameLen);
1080 LLVMValueRef P = LLVMGetNamedFunction(M, FName);
1081 if (!P)
1082 report_fatal_error("Could not find personality function");
1083 LLVMSetPersonalityFn(Fun, P);
1086 size_t NumMetadataEntries;
1087 auto *AllMetadata = LLVMGlobalCopyAllMetadata(Cur, &NumMetadataEntries);
1088 for (unsigned i = 0; i < NumMetadataEntries; ++i) {
1089 unsigned Kind = LLVMValueMetadataEntriesGetKind(AllMetadata, i);
1090 LLVMMetadataRef MD = LLVMValueMetadataEntriesGetMetadata(AllMetadata, i);
1091 LLVMGlobalSetMetadata(Fun, Kind, MD);
1093 LLVMDisposeValueMetadataEntries(AllMetadata);
1095 FunCloner FC(Cur, Fun);
1096 FC.CloneBBs(Cur);
1098 Next = LLVMGetNextFunction(Cur);
1099 if (Next == nullptr) {
1100 if (Cur != End)
1101 report_fatal_error("Last function does not match End");
1102 break;
1105 LLVMValueRef Prev = LLVMGetPreviousFunction(Next);
1106 if (Prev != Cur)
1107 report_fatal_error("Next.Previous function is not Current");
1109 Cur = Next;
1112 AliasClone:
1113 Begin = LLVMGetFirstGlobalAlias(Src);
1114 End = LLVMGetLastGlobalAlias(Src);
1115 if (!Begin) {
1116 if (End != nullptr)
1117 report_fatal_error("Range has an end but no beginning");
1118 goto NamedMDClone;
1121 Cur = Begin;
1122 Next = nullptr;
1123 while (true) {
1124 size_t NameLen;
1125 const char *Name = LLVMGetValueName2(Cur, &NameLen);
1126 LLVMValueRef Alias = LLVMGetNamedGlobalAlias(M, Name, NameLen);
1127 if (!Alias)
1128 report_fatal_error("Global alias must have been declared already");
1130 if (LLVMValueRef Aliasee = LLVMAliasGetAliasee(Cur)) {
1131 LLVMAliasSetAliasee(Alias, clone_constant(Aliasee, M));
1134 LLVMSetLinkage(Alias, LLVMGetLinkage(Cur));
1135 LLVMSetUnnamedAddress(Alias, LLVMGetUnnamedAddress(Cur));
1137 Next = LLVMGetNextGlobalAlias(Cur);
1138 if (Next == nullptr) {
1139 if (Cur != End)
1140 report_fatal_error("Last global alias does not match End");
1141 break;
1144 LLVMValueRef Prev = LLVMGetPreviousGlobalAlias(Next);
1145 if (Prev != Cur)
1146 report_fatal_error("Next.Previous global alias is not Current");
1148 Cur = Next;
1151 NamedMDClone:
1152 LLVMNamedMDNodeRef BeginMD = LLVMGetFirstNamedMetadata(Src);
1153 LLVMNamedMDNodeRef EndMD = LLVMGetLastNamedMetadata(Src);
1154 if (!BeginMD) {
1155 if (EndMD != nullptr)
1156 report_fatal_error("Range has an end but no beginning");
1157 return;
1160 LLVMNamedMDNodeRef CurMD = BeginMD;
1161 LLVMNamedMDNodeRef NextMD = nullptr;
1162 while (true) {
1163 size_t NameLen;
1164 const char *Name = LLVMGetNamedMetadataName(CurMD, &NameLen);
1165 LLVMNamedMDNodeRef NamedMD = LLVMGetNamedMetadata(M, Name, NameLen);
1166 if (!NamedMD)
1167 report_fatal_error("Named MD Node must have been declared already");
1169 unsigned OperandCount = LLVMGetNamedMetadataNumOperands(Src, Name);
1170 LLVMValueRef *OperandBuf = static_cast<LLVMValueRef *>(
1171 safe_malloc(OperandCount * sizeof(LLVMValueRef)));
1172 LLVMGetNamedMetadataOperands(Src, Name, OperandBuf);
1173 for (unsigned i = 0, e = OperandCount; i != e; ++i) {
1174 LLVMAddNamedMetadataOperand(M, Name, OperandBuf[i]);
1176 free(OperandBuf);
1178 NextMD = LLVMGetNextNamedMetadata(CurMD);
1179 if (NextMD == nullptr) {
1180 if (CurMD != EndMD)
1181 report_fatal_error("Last Named MD Node does not match End");
1182 break;
1185 LLVMNamedMDNodeRef PrevMD = LLVMGetPreviousNamedMetadata(NextMD);
1186 if (PrevMD != CurMD)
1187 report_fatal_error("Next.Previous Named MD Node is not Current");
1189 CurMD = NextMD;
1193 int llvm_echo(void) {
1194 LLVMEnablePrettyStackTrace();
1196 LLVMModuleRef Src = llvm_load_module(false, true);
1197 size_t SourceFileLen;
1198 const char *SourceFileName = LLVMGetSourceFileName(Src, &SourceFileLen);
1199 size_t ModuleIdentLen;
1200 const char *ModuleName = LLVMGetModuleIdentifier(Src, &ModuleIdentLen);
1201 LLVMContextRef Ctx = LLVMContextCreate();
1202 LLVMModuleRef M = LLVMModuleCreateWithNameInContext(ModuleName, Ctx);
1204 LLVMSetSourceFileName(M, SourceFileName, SourceFileLen);
1205 LLVMSetModuleIdentifier(M, ModuleName, ModuleIdentLen);
1207 LLVMSetTarget(M, LLVMGetTarget(Src));
1208 LLVMSetModuleDataLayout(M, LLVMGetModuleDataLayout(Src));
1209 if (strcmp(LLVMGetDataLayoutStr(M), LLVMGetDataLayoutStr(Src)))
1210 report_fatal_error("Inconsistent DataLayout string representation");
1212 size_t ModuleInlineAsmLen;
1213 const char *ModuleAsm = LLVMGetModuleInlineAsm(Src, &ModuleInlineAsmLen);
1214 LLVMSetModuleInlineAsm2(M, ModuleAsm, ModuleInlineAsmLen);
1216 declare_symbols(Src, M);
1217 clone_symbols(Src, M);
1218 char *Str = LLVMPrintModuleToString(M);
1219 fputs(Str, stdout);
1221 LLVMDisposeMessage(Str);
1222 LLVMDisposeModule(Src);
1223 LLVMDisposeModule(M);
1224 LLVMContextDispose(Ctx);
1226 return 0;